seq_id
string
text
string
repo_name
string
sub_path
string
file_name
string
file_ext
string
file_size_in_byte
int64
program_lang
string
lang
string
doc_type
string
stars
int64
dataset
string
pt
string
api
list
74649258984
#!/usr/bin/env python # -*- coding: UTF-8 -*- from rocketmq.client import Producer,Message from utils.my_logger import logger import time import re def push(num): tt = re.findall('^\d{13}', str(time.time()).replace('.', ''))[0] print(type(tt)) producer = Producer('PID-001') producer.set_namesrv_addr('192.168.90.131:9876') producer.start() msg = Message('linkcld_tdmp_gantry') msg.set_keys('key') msg.set_tags('bayonet') body = ("[{'enn':'河南惠济站'," \ "'gid':'G003041003005620010'," \ "'ipnc':'%s'," \ "'ln':'201'," \ "'marked':true," \ "'mid':'020000410101620060354820210315072344'," \ "'mt':3," \ "'pnc':'%s'," \ "'pt':%s," \ "'rt':1615767977000," \ "'vt':'2'}]"% (num,num,tt)) msg.set_body(body) ret = producer.send_sync(msg) print(ret.status, ret.msg_id, ret.offset) producer.shutdown() def main(): '''MQ推送预警 ''' try: push('豫A00001_1') raise except Exception: logger.exception("RocketMQ推送预警失败") raise else: logger('MQ推送成功') if __name__ == '__main__': logger.info('mqpush.py开始运行') main()
iospeng/python
pycharm_demo/pythonProject2/test_cases/mqpush.py
mqpush.py
py
1,275
python
en
code
0
github-code
36
[ { "api_name": "re.findall", "line_number": 9, "usage_type": "call" }, { "api_name": "time.time", "line_number": 9, "usage_type": "call" }, { "api_name": "rocketmq.client.Producer", "line_number": 11, "usage_type": "call" }, { "api_name": "rocketmq.client.Message",...
10830099515
import tkinter as tk import json from api import functions class window(tk.Tk): def __init__(self): super().__init__() self.geometry('767x445') self.title('Get daily news') self.funcs = functions() def main_window(self): # Creating required labels and frame title = tk.Label(self, text="Get news", font="monospace 20") frame = tk.Frame(self) # Creating required variables query = tk.StringVar() query.set('') # Creating entry boxes query_box = tk.Entry(frame, textvariable=query) # Creating label for entry box query_label = tk.Label(frame, text="Query: ") # Creating buttons submit = tk.Button(frame, text="Submit", command=lambda: (self.window_result(query.get()))) # Packing everything query_label.grid(column=1, row=1) query_box.grid(column=2, row=1) submit.grid(column=1, row=2) title.pack() frame.pack() def show_json(self, json_data: str): # Creating required frame frame = tk.Frame(self.slave_window) # Creating required variables data = json.loads(json_data) articles = data.get('articles') titles = [] selected_title = tk.StringVar() selected_title.set('Options') # Functions which will be used def find_selected_article(title: str, articles: list): for article in articles: if article.get('title') == title: return article return False def see_news(selected_article: dict): #self.slave_window.geometry('') frame.pack_forget() frame2 = tk.Frame(self.slave_window) title = tk.Label(frame2, text='Title: '+selected_article.get('title')) author = tk.Label(frame2, text='Author: '+selected_article.get('author')) source = tk.Label(frame2, text="Source: "+selected_article.get('source').get('name')) link = tk.Label(frame2, text='Link: '+selected_article.get('url')) date = tk.Label(frame2, text='Published At: '+selected_article.get('publishedAt')) content = tk.Label(frame2, text='Content: '+selected_article.get('content')) title.grid(column=1, row=1) author.grid(column=1, row=2) source.grid(column=1, row=3) link.grid(column=1, row=4) date.grid(column=1, row=5) content.grid(column=1, row=6) frame2.pack() for article in articles: titles.append(article.get('title')) # Creating label label_choose = tk.Label(frame, text="Choose News: ") # Creating option menu entry_box = tk.OptionMenu(frame, selected_title, *titles) # Creating buttons submit = tk.Button(frame, text="Submit", command=lambda: (frame.pack_forget(), see_news(find_selected_article(selected_title.get(), articles)))) # Packing Everything label_choose.grid(column=1, row=1) entry_box.grid(column=2, row=1) submit.grid(column=1, row=2) frame.pack() def window_result(self, query: str): self.slave_window = tk.Toplevel(self) self.slave_window.title(f'GET {query} NEWS') self.slave_window.geometry('700x300') json_text = self.funcs.get(query) self.show_json(json_text) if __name__=='__main__': windo = window() windo.main_window() windo.mainloop()
PingalPie/news-application
gui.py
gui.py
py
3,053
python
en
code
0
github-code
36
[ { "api_name": "tkinter.Tk", "line_number": 5, "usage_type": "attribute" }, { "api_name": "api.functions", "line_number": 10, "usage_type": "call" }, { "api_name": "tkinter.Label", "line_number": 14, "usage_type": "call" }, { "api_name": "tkinter.Frame", "line_...
4703541196
#!/usr/bin/env python3 import rospy import sounddevice as sd import numpy as np import queue import sys import sounddevice as sd from audio_universal.msg import AudioData ''' ~output_device: use `python3 -m sounddevice` to get device list, numerical device ID or case-insensitive substrings is ok. ~channels: 1 ~refresh_rate: 30 ~latency: 'high' ~blocksize: 512 ~dtype: 'float32' ~samplerate: 44100 48000 88200 96000 192000 ''' class audio_play: def __init__(self): self.initROS() self.q = queue.Queue() self.q_connects = queue.Queue() self.q_channels = queue.Queue() self.stream = sd.OutputStream(device=self.output_device, samplerate=self.samplerate, blocksize=self.blocksize, dtype=self.dtype, latency=self.latency, channels=self.channels, callback=self.audio_callback) with self.stream: rospy.spin() def initROS(self): rospy.init_node('audio_record', anonymous=True) self.output_device = rospy.get_param("~output_device", default=None) self.channels = rospy.get_param("~channels", default=1) self.refresh_rate = rospy.get_param("~refresh_rate", default=30) self.latency = rospy.get_param("~latency", default='high') self.blocksize = rospy.get_param("~blocksize", default=512) self.dtype = rospy.get_param("~dtype", default='float32') self.samplerate = rospy.get_param("~samplerate", default=48000) rospy.Subscriber('/audio_record_data', AudioData, self.AudioData_callback) def audio_callback(self, outdata, frames, time, status): if status: rospy.logwarn(status) try: data = self.q.get_nowait() connects = self.q_connects.get_nowait() in_channels = self.q_channels.get_nowait() data = data.reshape(self.blocksize, in_channels) if len(connects) / 2 != len(connects) // 2: raise Exception for idx in range(0, len(connects) // 2): if (connects[idx * 2] in range(0, self.channels)) and (connects[idx * 2 + 1] in range(0, self.channels)): outdata[:, connects[idx * 2 + 1]] = data[:, connects[idx * 2]] except queue.Empty as e: # rospy.logwarn('Buffer is empty: increase buffersize?') outdata[:] = np.zeros_like(outdata) def AudioData_callback(self, AudioData): self.q.put(np.frombuffer(AudioData.data, dtype=self.dtype)) self.q_connects.put(np.frombuffer(AudioData.connects, dtype='uint32')) self.q_channels.put(AudioData.channels) if __name__ == '__main__': audio_play()
jsbyysheng/ros_audio_universal
scripts/audio_play.py
audio_play.py
py
2,867
python
en
code
0
github-code
36
[ { "api_name": "queue.Queue", "line_number": 24, "usage_type": "call" }, { "api_name": "queue.Queue", "line_number": 25, "usage_type": "call" }, { "api_name": "queue.Queue", "line_number": 26, "usage_type": "call" }, { "api_name": "sounddevice.OutputStream", "l...
5001168268
import json import os import boto3 import logging logger = logging.getLogger() logger.setLevel(logging.INFO) dynamodb = boto3.resource("dynamodb") def lambda_handler(event, context): logger.info(f"EVENT: {event}") statistics_table_name = os.environ["STATISTICS_TABLE_NAME"] statistics_table = dynamodb.Table(statistics_table_name) try: # Get the new item from the DynamoDB event for item in event["Records"]: new_item = item["dynamodb"] if "NewImage" not in new_item.keys(): continue new_item = new_item["NewImage"] # Extract required attributes for data processing event_type = new_item.get("EventType", {}).get("S") event_details = new_item.get("EventDetails", {}).get("S") team_name = new_item.get("Team", {}).get("S") opponent_team_name = new_item.get("Opponent", {}).get("S") match_id = new_item.get("MatchID", {}).get("S") if not event_type or not team_name or not match_id or not event_details: return event_details = json.loads(event_details) # Calculate statistics based on the event_type if event_type == "goal": update_statistics(statistics_table, match_id, team_name, opponent_team_name, "total_goals_scored", 1) update_statistics(statistics_table, match_id, opponent_team_name, team_name,"total_goals_conceded", 1) elif event_type == "foul": update_statistics(statistics_table, match_id, team_name, opponent_team_name, "total_fouls", 1) update_statistics(statistics_table, match_id, opponent_team_name, team_name, "total_fouls", 0) update_match_result(statistics_table, team_name, opponent_team_name, match_id) response = statistics_table.get_item(Key={"TeamName": team_name, "MatchID": match_id}, AttributesToGet=["Date"]) if "Item" not in response or not response.get("Item", {}): date = new_item.get("Timestamp", {}).get("S") update_date(statistics_table, team_name, match_id, date) update_date(statistics_table, opponent_team_name, match_id, date) except Exception as e: print(f"Error processing data: {e}") raise e def update_statistics(statistics_table, match_id, team_name, opponent_name, statistic_type, value): # Get the existing statistics for the team from the statistics table response = statistics_table.get_item(Key={"TeamName": team_name, "MatchID": match_id}) if "Item" not in response or not response.get("Item", {}): # If the team and match are not present in the statistics table, create a new entry item = { "TeamName": team_name, "MatchID": match_id, "Opponent": opponent_name, statistic_type: str(value) } statistics_table.put_item(Item=item) else: # If the team and match are already present in the statistics table, update the existing entry existing_item = response["Item"] existing_item[statistic_type] = str(int(existing_item.get(statistic_type, "0")) + value) statistics_table.put_item(Item=existing_item) def update_match_result(statistics_table, team_name, opponent_name, match_id): response = statistics_table.get_item(Key={"TeamName": team_name, "MatchID": match_id}) response = response.get("Item", {}) goals_scored = response.get("total_goals_scored", "0") goals_conceded = response.get("total_goals_conceded", "0") # Calculate match result based on goals scored and conceded results = { 1: "win", -1: "loss", 0: "draw", } sign = lambda x: -1 if x < 0 else (1 if x > 0 else 0) result = sign(int(goals_scored) - int(goals_conceded)) # Update match result for the team response = statistics_table.update_item( Key={"TeamName": team_name, "MatchID": match_id}, UpdateExpression="SET #result = :result", ExpressionAttributeNames={"#result": "Result"}, ExpressionAttributeValues={":result": results[result]} ) # Update match result for the opponent team response = statistics_table.update_item( Key={"TeamName": opponent_name, "MatchID": match_id}, UpdateExpression="SET #result = :result", ExpressionAttributeNames={"#result": "Result"}, ExpressionAttributeValues={":result": results[-result]} ) def update_date(table, team_name, match_id, date): # Update the "Date" attribute in the StatisticsTable for the team and match_id table.update_item( Key={"TeamName": team_name, "MatchID": match_id}, UpdateExpression="SET #dateAttr = :dateValue", ExpressionAttributeNames={"#dateAttr": "Date"}, ExpressionAttributeValues={":dateValue": str(date)} )
HeNeos/SportsAnalyticsPlatform
services/dynamodb/runtime/lambda_function.py
lambda_function.py
py
4,924
python
en
code
0
github-code
36
[ { "api_name": "logging.getLogger", "line_number": 6, "usage_type": "call" }, { "api_name": "logging.INFO", "line_number": 7, "usage_type": "attribute" }, { "api_name": "boto3.resource", "line_number": 8, "usage_type": "call" }, { "api_name": "os.environ", "lin...
22398051842
import sys import cv2 import numpy as np from os import listdir PY3 = sys.version_info[0] == 3 #Define the parameters SIZE = 32 CLASS_NUMBER = 6 #Read the traffic sign dataset and store the dataset and labels into a list def load_traffic_dataset(): dataset = [] labels = [] for sign_type in range(CLASS_NUMBER): sign_list = listdir("./dataset/{}".format(sign_type)) for sign_file in sign_list: if '.png' in sign_file: path = "./dataset/{}/{}".format(sign_type,sign_file) print(path) img = cv2.imread(path,0) img = cv2.resize(img, (SIZE, SIZE)) img = np.reshape(img, [SIZE, SIZE]) dataset.append(img) labels.append(sign_type) return np.array(dataset), np.array(labels) #Deskew the images def deskew(img): m = cv2.moments(img) if abs(m['mu02']) < 1e-2: return img.copy() skew = m['mu11']/m['mu02'] M = np.float32([[1, skew, -0.5*SIZE*skew], [0, 1, 0]]) img = cv2.warpAffine(img, M, (SIZE, SIZE), flags=cv2.WARP_INVERSE_MAP | cv2.INTER_LINEAR) return img #Define a class for SVM model object class StatModel(object): def load(self, fn): self.model.load(fn) # Known bug: https://github.com/opencv/opencv/issues/4969 def save(self, fn): self.model.save(fn) class SVM(StatModel): def __init__(self, C = 12.5, gamma = 0.50625): self.model = cv2.ml.SVM_create() self.model.setGamma(gamma) self.model.setC(C) self.model.setKernel(cv2.ml.SVM_RBF) self.model.setType(cv2.ml.SVM_C_SVC) def train(self, samples, responses): self.model.train(samples, cv2.ml.ROW_SAMPLE, responses) def predict(self, samples): return self.model.predict(samples)[1].ravel() def preprocess_simple(data): return np.float32(data).reshape(-1, SIZE*SIZE) / 255.0 def get_hog() : winSize = (20,20) blockSize = (10,10) blockStride = (5,5) cellSize = (10,10) nbins = 9 deriveAperture = 1 winSigma = -1.0 histogramNormType = 0 L2HysThreshold = 0.2 gammaCorrection = 1 nlevels = 64 signedGradient = True hog = cv2.HOGDescriptor(winSize,blockSize,blockStride,cellSize,nbins,deriveAperture,winSigma,histogramNormType,L2HysThreshold,gammaCorrection,nlevels, signedGradient) return hog #Train the model def training(): print('Loading data...') data, labels = load_traffic_dataset() print(data.shape) print('Shuffling data...') rand = np.random.RandomState(10) shuffle = rand.permutation(len(data)) data, labels = data[shuffle], labels[shuffle] print('Deskewing images...') data_deskewed = list(map(deskew, data)) print('Defining HoG parameters...') hog = get_hog() print('Calculating HoG descriptor for every image...') hog_descriptors = [] for img in data_deskewed: hog_descriptors.append(hog.compute(img)) hog_descriptors = np.squeeze(hog_descriptors) print('Training SVM model...') model = SVM() model.train(hog_descriptors, labels) print('Saving SVM model...') model.save('data_svm.dat') return model #Get the label of detected traffic sign using the SVM model def getLabel(model, data): gray = cv2.cvtColor(data, cv2.COLOR_BGR2GRAY) img = [cv2.resize(gray,(SIZE,SIZE))] img_deskewed = list(map(deskew, img)) hog = get_hog() hog_descriptors = np.array([hog.compute(img_deskewed[0])]) hog_descriptors = np.reshape(hog_descriptors, [-1, hog_descriptors.shape[1]]) return int(model.predict(hog_descriptors)[0])
nabil053/Bangladeshi-Traffic-Sign-Detection-And-Recognition-System
classification.py
classification.py
py
3,647
python
en
code
0
github-code
36
[ { "api_name": "sys.version_info", "line_number": 6, "usage_type": "attribute" }, { "api_name": "os.listdir", "line_number": 17, "usage_type": "call" }, { "api_name": "cv2.imread", "line_number": 22, "usage_type": "call" }, { "api_name": "cv2.resize", "line_num...
32443531446
import imdb import json from tqdm import tqdm ia = imdb.IMDb() DATA_NEEDED = False with open("./imdb/movie_title-id.json", "r") as data: current_data = json.load(data) with open('./movie_titles_list.json', "r") as movie_list: movies = json.load(movie_list) if DATA_NEEDED: for i in tqdm(range(0, len(movies))): # searching the name name = movies[i] try: search = ia.search_movie(name) # getting the id id = search[0].movieID current_data[name]=[id] except Exception: continue for movie_name in current_data: if len(current_data[movie_name]) > 0: current_data[movie_name] = current_data[movie_name][0] with open("./imdB/movie_title-id.json", "w") as data_list: json.dump(current_data, data_list)
Shreneken/movie-data-getter
imdb/imdb_id.py
imdb_id.py
py
824
python
en
code
0
github-code
36
[ { "api_name": "imdb.IMDb", "line_number": 5, "usage_type": "call" }, { "api_name": "json.load", "line_number": 10, "usage_type": "call" }, { "api_name": "json.load", "line_number": 13, "usage_type": "call" }, { "api_name": "tqdm.tqdm", "line_number": 16, "...
41539002397
#!/usr/bin/python # Imports ### System import os import argparse ### Python import numpy as np import cv2 as cv from tqdm.auto import tqdm import matplotlib.pyplot as plt ### Pytorch import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F ### TODO: Use WandB, Pytorch Lightning & torchsummary import wandb import lightning.pytorch as pl from lightning.pytorch import LightningDataModule, LightningModule, Trainer, seed_everything from lightning.pytorch import Callback from lightning.pytorch.callbacks import DeviceStatsMonitor, TQDMProgressBar, ModelCheckpoint, EarlyStopping, LearningRateMonitor from lightning.pytorch.loggers import WandbLogger from torchsummary import summary ### Timm import timm import timm.optim ### Custom from custom_dataloader import get_dataloaders # DONE_TODO 1: Import pytorch lightning, wandb(logging), timm and use it to load a pretrained model # Done_TODO 2: Modify the model's classifier to output 3 classes instead of X (defined by the model) # Done_TODO 3: Train the model + Logging & Saving best ckpt for 10 epochs and report test accuracy def get_args(): args = argparse.ArgumentParser(description='Transfer Learning') args.add_argument('--model', '-m', type=str, default='vgg16', required=True, help='Model to use [vgg16, vgg19, resnet50, resnet101, effb4, effb5]') args.add_argument('--epochs', '-e', type=int, default=10, help='Number of epochs to train for') args.add_argument('--batch_size', type=int, default=32, help='Batch size') args.add_argument('--device', '-d', type=str, default='cuda', required=True, help='Device to use [cpu, cuda:0, cuda:1, cuda]') args.add_argument('--mode', '-md', type=str, default='train', help='Mode to run: [train, trainX, test]. train = finetune only classifier layer. trainX = finetune last few layers including the classifier. test = test the model') args.add_argument('--ckpt_path', '-cp', type=str, default="", help='Path to checkpoint to load') args.add_argument('--lr', '-lr', type=float, default=1e-3, help='Learning rate') args.add_argument('--num_workers', '-nw', type=int, default=8, help='Number of workers for dataloader') args.add_argument('--exp_name', '-en', type=str, default='generic_exp', help='Experiment name for wandb') args.add_argument('--use_cam', action='store_true', help='Use Class Activation Maps Loss') # args.print_help() return args.parse_args() def get_model(modelName): # VGG Fam if modelName == 'vgg16': model = timm.create_model('vgg16', pretrained=True) elif modelName == 'vgg19': model = timm.create_model('vgg19', pretrained=True) # Res Fam: Using catavgmax pooling to increase number of features elif modelName == 'resnet50': model = timm.create_model('resnet50', pretrained=True) elif modelName == 'resnet101': model = timm.create_model('resnet101', pretrained=True) # EfficientNet Fam: Using catavgmax pooling here as well elif modelName == 'effb4': model = timm.create_model('efficientnet_b4', pretrained=True) elif modelName == 'effb5': model = timm.create_model('efficientnet_b5', pretrained=True) return model def check_args(args): if args.model not in ['vgg16', 'vgg19', 'resnet50', 'resnet101', 'effb4', 'effb5']: raise ValueError('[!] Invalid model') if 'cuda' in args.device and not torch.cuda.is_available(): raise ValueError('[!] Cuda not available') if 'cuda:' in args.device: if int(args.device[-1]) >= torch.cuda.device_count(): raise ValueError('[!] Invalid cuda device. You have lesser cuda devices than the one you specified') class LIT_TL(pl.LightningModule): def __init__(self, model, modelName = "brrr", config: dict = None): super().__init__() self.save_hyperparameters(ignore=['model']) self.modelName = modelName self.config = config if "vgg" in modelName: self.num_filters = model.head.fc.in_features elif "eff" in modelName: self.num_filters = model.classifier.in_features else: self.num_filters = model.fc.in_features layers = list(model.children())[:-1] self.feature_extractor = nn.Sequential(*layers) num_target_classes = config['classes'] if "vgg" in modelName: # custom classifier head for vggs ;) self.classifier = nn.Sequential(*[ model.head.global_pool, model.head.drop, nn.Linear(in_features=4096, out_features=3, bias=True), model.head.flatten, ]) else: self.classifier = nn.Linear(self.num_filters, num_target_classes) self.classifier.apply(self.init_xavier) self.ce_loss = nn.CrossEntropyLoss() # TODO: Apply Class-Activation-Maps Loss and visualize it self.use_cam = config['use_cam'] if self.use_cam: self.gap_fc = nn.utils.spectral_norm(nn.Linear(self.num_filters, 1, bias=False)) self.gmp_fc = nn.utils.spectral_norm(nn.Linear(self.num_filters, 1, bias=False)) self.conv1x1 = nn.Conv2d(self.num_filters * 2, self.num_filters, kernel_size=1, stride=1, bias=True) self.conv_classifier = nn.utils.spectral_norm( nn.Conv2d(self.num_filters, 1, kernel_size=4, stride=1, padding=0, bias=False)) self.cam_loss = nn.CrossEntropyLoss() def init_xavier(self, m): if type(m) == nn.Linear: torch.nn.init.xavier_uniform_(m.weight) m.bias.data.fill_(0.01) def calculate_accuracy(self, yhat, y): return 100. * torch.sum(yhat == y) / len(y) def forward(self, x): self.feature_extractor.eval() with torch.no_grad(): rep = self.feature_extractor(x) if self.use_cam: gap = torch.nn.functional.adaptive_avg_pool2d(rep, 1) gap_logit = self.gap_fc(gap.view(rep.shape[0], -1)) gap_weight = list(self.gap_fc.parameters())[0] gap = rep * gap_weight.unsqueeze(2).unsqueeze(3) gmp = torch.nn.functional.adaptive_max_pool2d(rep, 1) gmp_logit = self.gmp_fc(gmp.view(rep.shape[0], -1)) gmp_weight = list(self.gmp_fc.parameters())[0] gmp = rep * gmp_weight.unsqueeze(2).unsqueeze(3) c_logit = torch.cat([gap_logit, gmp_logit], 1) rep = torch.cat([gap, gmp], 1) rep = self.leaky_relu(self.conv1x1(rep)) heatmap = torch.sum(rep, dim=1, keepdim=True) rep = self.pad(rep) out = self.conv_classifier(rep) return out, c_logit, heatmap else: if not "vgg" in self.modelName: rep = rep.flatten(1) out = self.classifier(rep) return out def configure_optimizers(self): opt = timm.optim.AdamW((param for param in self.classifier.parameters() if param.requires_grad), lr=self.config['lr'], weight_decay=self.config['decay']) scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(opt, T_0=self.config['T_0'], eta_min=self.config['eta_min']) return [opt], [scheduler] def training_step(self, batch, batch_idx): img = batch['image'].to(self.device) # mask = batch['mask'] # Not Needed in classification setting y = batch['class_label'].to(self.device) if self.use_cam: y_hat, logits, heatmap = self.forward(img) if 1 + batch_idx % 100 == 0: plt.savefig(f"{self.config['model']}_{batch_idx}.png", heatmap.squeeze(0).cpu().numpy()) cam_loss = self.cam_loss(logits, y) loss = self.ce_loss(y_hat, y) + cam_loss else: y_hat = self.forward(img) loss = self.ce_loss(y_hat, y) preds = torch.argmax(y_hat, dim=1) # print(f"y: {y}, y_hat: {y_hat}") # DONE_TODO: Log train metrics here train_step_acc = self.calculate_accuracy(preds, y) # DONE_TODO: Calculate train accuracy here self.log("train_acc", train_step_acc, on_step=True, on_epoch=True, prog_bar=True, logger=True) return loss def validation_step(self, batch, batch_idx): img = batch['image'].to(self.device) # mask = batch['mask'] # Not Needed in classification setting y = batch['class_label'].to(self.device) # print(f"{i+1} | {img.shape} | {y}") y_hat = self.forward(img) preds = torch.argmax(y_hat, dim=1) test_acc = self.calculate_accuracy(preds, y) self.log("test_acc", test_acc, on_step=True, on_epoch=True, prog_bar=True, logger=True) # DONE_TODO: Add images to the logger for one batch if (batch_idx + 1) % 10 == 0: id2cat = {'0': 'authentic', '1': 'copy-moved', '2': 'spliced'} caption_strs = [] for i in range(len(img)): correct = "Misclassified" if preds[i] != y[i] else "Correct" caption_strs.append(f"Pred: {id2cat[str(preds[i].item())]}, Label: {id2cat[str(y[i].item())]} | {correct}") self.logger.log_image( key=f"Validation Batch: {batch_idx + 1}", images=[img[i] for i in range(len(img))], caption=caption_strs, ) def test_step(self, batch, batch_idx): # NOTE: Same as validation loop minus the image logging # No image logging so that export can be done easily img = batch['image'].to(self.device) # mask = batch['mask'] # Not Needed in classification setting y = batch['class_label'].to(self.device) # print(f"{i+1} | {img.shape} | {y}") y_hat = self.forward(img) preds = torch.argmax(y_hat, dim=1) test_acc = self.calculate_accuracy(preds, y) self.log("test_acc", test_acc, on_step=True, on_epoch=True, prog_bar=True, logger=True) def get_config(args): config = { 'seed': 42, 'model': args.model, 'mode': args.mode, 'lr': args.lr, 'batch_size': args.batch_size, 'epochs': args.epochs, 'device': args.device, 'num_workers': args.num_workers, 'T_0': 50, 'eta_min': 6e-4, 'classes': 3, 'decay': 1e-3, 'exp_name': args.exp_name, 'use_cam': args.use_cam } return config if __name__ == '__main__': args = get_args() # print("Total devices:", torch.cuda.device_count()) check_args(args) # will also set args.device properly config = get_config(args) seed_everything(42) if torch.cuda.is_available(): device_name = torch.cuda.get_device_name(args.device) else: device_name = 'cpu' print("--------------------------------------------\nSelected device:", device_name,"\n--------------------------------------------") print(f"[+] Model Selected: {config['model']}") model = get_model(config['model']) lit_model = LIT_TL(model, config['model'], config) train_dataloader, test_dataloader = get_dataloaders(batch_size=config['batch_size'], num_workers=config['num_workers']) # Callbacks checkpoint_callback = ModelCheckpoint(monitor="test_acc", mode="max", save_top_k=1, dirpath="checkpoints/", filename=f"{config['model']}" + "_{test_acc:.3f}") lr_monitor = LearningRateMonitor(logging_interval='step', log_momentum=True) # early_stop_callback = EarlyStopping(monitor="loss", patience=99) wandb.login() if config['exp_name'] == 'generic_exp': fnam = f"{config['model']}_GE" else: fnam = config['exp_name'] wandb_logger = WandbLogger(project='forgery_detection', name=f"TL_{fnam}", config=config, job_type='finetuning', log_model="all") # call trainer trainer = Trainer(fast_dev_run=False, inference_mode=False, # to enable grad enabling during inference max_epochs=config['epochs'], accelerator="gpu" if "cuda" in config['device'] else "cpu", devices=[int(config['device'].split(":")[-1])], # GPU ID that you selected precision="16", # automatic mixed precision training deterministic=True, enable_checkpointing=True, callbacks=[checkpoint_callback, lr_monitor], gradient_clip_val=None, log_every_n_steps=50, logger=wandb_logger, # The absolute best: wandb <3 enable_progress_bar=True) # fit model if config['mode'] == 'train' or config['mode'] == 'trainX': # TODO: Implement trainX mode trainer.fit(lit_model, train_dataloader, test_dataloader) else: # DONE_TODO: Load last checkpoint and test if not os.exists(args.ckpt_path): args.ckpt_path = checkpoint_callback.best_model_path lit_model = LIT_TL.load_from_checkpoint(args.ckpt_path) lit_model.freeze() trainer.test(lit_model, test_dataloader) wandb.finish()
Aryan-Garg/Image-Forgery-Detection
transfer_learning.py
transfer_learning.py
py
13,826
python
en
code
0
github-code
36
[ { "api_name": "argparse.ArgumentParser", "line_number": 42, "usage_type": "call" }, { "api_name": "timm.create_model", "line_number": 60, "usage_type": "call" }, { "api_name": "timm.create_model", "line_number": 62, "usage_type": "call" }, { "api_name": "timm.crea...
26094620258
import google import firebase_admin from firebase_admin import credentials from firebase_admin import firestore import base64 keyPath = '../firestoreKEY.json' def initializeDb(path): cred = credentials.Certificate(path) firebase_admin.initialize_app(cred) db = firestore.client() return db def stringToImage(string, imagePath): fh = open(imagePath, "wb") fh.write(string.decode('base64')) fh.close() def getFieldFromDB(database, collectionName, docName, fieldName): dbRef = database.collection(collectionName).document(docName) try: doc = dbRef.get() str = doc.to_dict()[fieldName] except google.cloud.exception.NotFound: str = 'NO SUCH DOCUMENT' return str def getDocsFromCol(database, collectionName): return database.collection(collectionName).get() def main(): database = initializeDb(keyPath) # str = getFieldFromDB(database, u'photos', u'04, 03:59AM on December 15, 2018', u'im') strIngs = getDocsFromCol(database, u'photos') for ims in strIngs: docInfo = ims.to_dict() stringToImage(docInfo[u'im'], "images/" + ims.id + ".jpg") if __name__ == '__main__': main()
16francej/firestoredemo
RecieveImage.py
RecieveImage.py
py
1,190
python
en
code
0
github-code
36
[ { "api_name": "firebase_admin.credentials.Certificate", "line_number": 11, "usage_type": "call" }, { "api_name": "firebase_admin.credentials", "line_number": 11, "usage_type": "name" }, { "api_name": "firebase_admin.initialize_app", "line_number": 12, "usage_type": "call"...
8373131694
import jwt JWT_SECRET = "this_is_just_for_testing" def create_jwt(payload): token = jwt.encode( payload, JWT_SECRET, algorithm="HS256" ) return token def validate_jwt(token): try: payload = jwt.decode(token, JWT_SECRET, "HS256") except: raise return payload
walterbrunetti/playground
auth/core/jwt_utils.py
jwt_utils.py
py
338
python
en
code
0
github-code
36
[ { "api_name": "jwt.encode", "line_number": 11, "usage_type": "call" }, { "api_name": "jwt.decode", "line_number": 21, "usage_type": "call" } ]
27029634669
import copy import logging import os.path as osp import numpy as np import torch from fvcore.common.file_io import PathManager from PIL import Image from pycocotools import mask as maskUtils from detectron2.data import detection_utils as utils from detectron2.data import transforms as T from detectron2.data.dataset_mapper import DatasetMapper from detectron2.data.detection_utils import SizeMismatchError from detectron2.structures import BoxMode from .augmentation import RandomCropWithInstance from .detection_utils import (annotations_to_instances, build_augmentation, transform_instance_annotations) """ This file contains the default mapping that's applied to "dataset dicts". """ __all__ = ["DatasetMapperWithBasis"] logger = logging.getLogger(__name__) def segmToRLE(segm, img_size): h, w = img_size if type(segm) == list: # polygon -- a single object might consist of multiple parts # we merge all parts into one mask rle code rles = maskUtils.frPyObjects(segm, h, w) rle = maskUtils.merge(rles) elif type(segm["counts"]) == list: # uncompressed RLE rle = maskUtils.frPyObjects(segm, h, w) else: # rle rle = segm return rle def segmToMask(segm, img_size): rle = segmToRLE(segm, img_size) m = maskUtils.decode(rle) return m def filter_empty_instances(instances): """ Filter out empty instances in an `Instances` object. Args: instances (Instances): by_box (bool): whether to filter out instances with empty boxes by_mask (bool): whether to filter out instances with empty masks box_threshold (float): minimum width and height to be considered non-empty return_mask (bool): whether to return boolean mask of filtered instances Returns: Instances: the filtered instances. tensor[bool], optional: boolean mask of filtered instances """ pass r = [] r.append(instances.gt_boxes.nonempty()) if not r: return instances m = r[0] for x in r[1:]: m = m & x return instances[m] class DatasetMapperWithBasis(DatasetMapper): """ This caller enables the default Detectron2 mapper to read an additional basis semantic label """ def __init__(self, cfg, is_train=True): super().__init__(cfg, is_train) # Rebuild augmentations logger.info( "Rebuilding the augmentations. The previous augmentations will be overridden." ) self.augmentation = build_augmentation(cfg, is_train) if cfg.INPUT.CROP.ENABLED and is_train and cfg.MODEL.TRANSFORMER.BOUNDARY_HEAD: self.augmentation.insert( 0, RandomCropWithInstance( cfg.INPUT.CROP.TYPE, cfg.INPUT.CROP.SIZE, cfg.INPUT.CROP.CROP_INSTANCE, ), ) logging.getLogger(__name__).info( "Cropping used in training: " + str(self.augmentation[0]) ) if cfg.INPUT.ROTATE and is_train: if cfg.MODEL.TRANSFORMER.BOUNDARY_HEAD: self.augmentation.insert(0, T.RandomRotation(angle=[-45, 45])) else: self.augmentation.insert(0, T.RandomRotation(angle=[-90, 90])) def __call__(self, dataset_dict): """ Args: dataset_dict (dict): Metadata of one image, in Detectron2 Dataset format. Returns: dict: a format that builtin models in detectron2 accept """ dataset_dict = copy.deepcopy(dataset_dict) # it will be modified by code below # USER: Write your own image loading if it's not from a file try: image = utils.read_image( dataset_dict["file_name"], format=self.image_format ) except Exception as e: print(dataset_dict["file_name"]) print(e) raise e try: utils.check_image_size(dataset_dict, image) except SizeMismatchError as e: expected_wh = (dataset_dict["width"], dataset_dict["height"]) image_wh = (image.shape[1], image.shape[0]) if (image_wh[1], image_wh[0]) == expected_wh: print("transposing image {}".format(dataset_dict["file_name"])) image = image.transpose(1, 0, 2) else: raise e ###################################################################### boxes = np.asarray( [ BoxMode.convert( instance["bbox"], instance["bbox_mode"], BoxMode.XYXY_ABS ) for instance in dataset_dict["annotations"] ] ) ###################################################################### # aug_input = T.StandardAugInput(image) aug_input = T.StandardAugInput(image, boxes=boxes) transforms = aug_input.apply_augmentations(self.augmentation) image = aug_input.image image_shape = image.shape[:2] # h, w # Pytorch's dataloader is efficient on torch.Tensor due to shared-memory, # but not efficient on large generic data structures due to the use of pickle & mp.Queue. # Therefore it's important to use torch.Tensor. dataset_dict["image"] = torch.as_tensor( np.ascontiguousarray(image.transpose(2, 0, 1)) ) if not self.is_train: dataset_dict.pop("annotations", None) dataset_dict.pop("sem_seg_file_name", None) dataset_dict.pop("pano_seg_file_name", None) return dataset_dict if "annotations" in dataset_dict: # USER: Modify this if you want to keep them for some reason. for anno in dataset_dict["annotations"]: if not self.use_instance_mask: anno.pop("segmentation", None) if not self.use_keypoint: anno.pop("keypoints", None) # USER: Implement additional transformations if you have other types of data annos = [ transform_instance_annotations( obj, transforms, image_shape, keypoint_hflip_indices=self.keypoint_hflip_indices, ) for obj in dataset_dict.pop("annotations") if obj.get("iscrowd", 0) == 0 ] instances = annotations_to_instances( annos, image_shape, mask_format=self.instance_mask_format ) # dataset_dict["instances"] = instances dataset_dict["instances"] = utils.filter_empty_instances(instances) return dataset_dict
ViTAE-Transformer/DeepSolo
adet/data/dataset_mapper.py
dataset_mapper.py
py
6,846
python
en
code
177
github-code
36
[ { "api_name": "logging.getLogger", "line_number": 27, "usage_type": "call" }, { "api_name": "pycocotools.mask.frPyObjects", "line_number": 35, "usage_type": "call" }, { "api_name": "pycocotools.mask", "line_number": 35, "usage_type": "name" }, { "api_name": "pycoc...
37989827251
""" Steps to run: python insured_info_scraper.py <account number> Eg: python insured_info_scraper.py 20011 Program written in Python 3 Program Output: 1 file: Insured_Info_<account_num>.json - json file that contains the insured info details Program Description: Progam first fetches the ASP login page paramters - __VIEWSTATE, __VIEWSTATEGENERATOR, etc and then inputs these paramters and the login credentials to login Then the program stores cookie info and uses it along with the new page parameters to access the quotes page. The code then access the account details page by sending the account number (retrieved as a command line argument) along with other parameter to get the account details. The insured information is then scraped and stored into a dictionary var which is written into a json file """ import sys import requests from bs4 import BeautifulSoup import json # Main Function def main(): # Variable to store the json putput insured_information = {} # Getting the account number from the command line account_num = str(sys.argv[1]) print("Account number entered:") print(account_num) # Login credentials credentials = dict() credentials['username'] = 'samplecsrtest' credentials['password'] = 'Ik vaari aa---123' print("Getting login session parameters to login") # Home page URL home_page_url = 'https://secure.financepro.net/financepro/default.aspx?company=deltafinance' # Storing the session info session = requests.Session() response = session.get(home_page_url) # Parsing the response using Beautiful Soup soup = BeautifulSoup(response.content, 'html.parser') # Storing 3 ASP web-page specific form parameters to use to login viewstate = soup.select('input[name=__VIEWSTATE]')[0]['value'] viewstate_generator = soup.select('input[name=__VIEWSTATEGENERATOR]')[0]['value'] event_validation = soup.select('input[name=__EVENTVALIDATION]')[0]['value'] login_form_parameters = dict() login_form_parameters['__VIEWSTATE'] = viewstate login_form_parameters['__VIEWSTATEGENERATOR'] = viewstate_generator login_form_parameters['__EVENTVALIDATION'] = event_validation login_form_parameters['tblForm$txtUserName'] = credentials['username'] login_form_parameters['tblForm$txtPassword'] = credentials['password'] login_form_parameters['tblForm$btnLogin'] = 'Log In' login_form_parameters['tblForm$txtCompanyCode'] = 'deltafinance' # Storing the cookies post login response = session.post(home_page_url, login_form_parameters) cookies = session.cookies.get_dict() # Logging in response = requests.post(home_page_url, login_form_parameters) print("Logged in") print("Accessing the accounts page session paramaters to navigate to accounts page") accounts_url = 'https://secure.financepro.net/financepro/account/account.aspx' # Sending the same session cookies response = session.get(accounts_url, cookies=cookies) soup = BeautifulSoup(response.content, 'html.parser') # Getting the ASP accounts web page session paramters viewstate = soup.select('input[name=__VIEWSTATE]')[0]['value'] viewstate_generator = soup.select('input[name=__VIEWSTATEGENERATOR]')[0]['value'] event_validation = soup.select('input[name=__EVENTVALIDATION]')[0]['value'] print("Parameters retrieved") # Storing paramters to get account details page account_info_params = dict() account_info_params['__VIEWSTATE'] = viewstate account_info_params['__VIEWSTATEGENERATOR'] = viewstate_generator account_info_params['__EVENTVALIDATION'] = event_validation account_info_params['fndAccountSearch$hdnName'] = 'hvalue' # Account number sent as input here account_info_params['fndAccountSearch$txtAccountNumber'] = account_num account_info_params['fndAccountSearch$txtAccountStatus'] = '0' account_info_params['fndAccountSearch$txtCompanyCheckType'] = 'paid' account_info_params['fndAccountSearch$btnFind'] = 'Find Account' # POST request to get account and insured details print("\nAccessing Account Details Page") response = requests.post(accounts_url, account_info_params, cookies=cookies) soup = BeautifulSoup(response.content, 'html.parser') # All insured information is stored in span tags insured_name = soup.find("span", {"id": "lblInsuredName"}).text print("\nInsured Details are:\n") print("Insured name:") print(insured_name) insured_information['Name'] = insured_name insured_address = soup.find("span", {"id": "lblInsuredAddress"}) # Converting the <br> tag into a new line char and then splitting the # address into its components insured_address = str(insured_address).replace("<br/>", "\n") insured_address = insured_address.replace('<span id="lblInsuredAddress">', '') insured_address = insured_address.replace('</span>', '') address_dict = dict() insured_address = insured_address.split("\n") address_dict['Line 1'] = insured_address[0] line2 = insured_address[1].split(" ") address_dict['City'] = line2[0][:-1] address_dict['State'] = line2[1] address_dict['Zip Code'] = line2[2] print("Insured address:") print("Address Line 1:") print(address_dict['Line 1']) print("City:") print(address_dict['City']) print("State:") print(address_dict['State']) print("Zip Code:") print(address_dict['Zip Code']) insured_information['Address'] = address_dict insured_telephone = soup.find("span", {"id": "lblInsuredPhone"}).text print("Insured telephone:") print(insured_telephone) insured_information['Telephone'] = insured_telephone # Writing the insured information into a json file file_name = 'Insured_Info_' + account_num + '.json' with open(file_name, 'w') as f: json.dump(insured_information, f) print("\nOutput File Created:") print(file_name) print("\nLogging off") # Log off page called with cookie info log_off_url = 'https://secure.financepro.net/financepro/logoff.aspx' response = requests.get(log_off_url, cookies=cookies) final_url = 'https://www.deltafinanceoftexas.com/' response = requests.get(final_url) # Entry point of code if __name__ == "__main__": main()
tebbythomas/Freelance_Projects
Web_Data_Extraction_Projects/J10_Finance_Pro_Insured_Info_Scraper/Insured_Info/insured_info_scraper.py
insured_info_scraper.py
py
6,297
python
en
code
1
github-code
36
[ { "api_name": "sys.argv", "line_number": 37, "usage_type": "attribute" }, { "api_name": "requests.Session", "line_number": 48, "usage_type": "call" }, { "api_name": "bs4.BeautifulSoup", "line_number": 51, "usage_type": "call" }, { "api_name": "requests.post", ...
6432536009
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import apps.users.models class Migration(migrations.Migration): dependencies = [ ('users', '0005_auto_20180802_1614'), ] operations = [ migrations.AlterModelManagers( name='user', managers=[ ('objects', apps.users.models.MyUserManager()), ], ), ]
eashme/Django-backend
Hello_Server/apps/users/migrations/0006_auto_20180802_1723.py
0006_auto_20180802_1723.py
py
449
python
en
code
1
github-code
36
[ { "api_name": "django.db.migrations.Migration", "line_number": 8, "usage_type": "attribute" }, { "api_name": "django.db.migrations", "line_number": 8, "usage_type": "name" }, { "api_name": "django.db.migrations.AlterModelManagers", "line_number": 15, "usage_type": "call" ...
70489042024
from unittest.mock import MagicMock from uuid import uuid4 import pytest from pytest import raises from pydantic import ValidationError from api.exceptions import InvalidParameterError from api.schemas.output import ( ConsultaProcessoOutput, ExtractDataOutput, ExtractDataSecondInstanceOutput, StatusSolicitacaoOutput ) def test_valida_numero_solicitacao_valid(): """Testa se a validação do UUID é bem-sucedida com um UUID válido.""" valid_uuid = str(uuid4()) ConsultaProcessoOutput(numero_solicitacao=valid_uuid) @pytest.mark.parametrize("invalid_uuid", ["invalid_uuid_string"]) def test_valida_numero_solicitacao_invalid(invalid_uuid): """Testa se a validação do UUID falha com uma string inválida.""" with MagicMock(side_effect=InvalidParameterError("Mocked error")): with raises(InvalidParameterError): ConsultaProcessoOutput(numero_solicitacao=invalid_uuid) def test_valid_extract_data(): """Testa se o modelo é válido com dados corretos.""" valid_data = { 'classe': 'Penal', 'area': 'Criminal', 'assunto': 'Roubo', 'data_distribuicao': 'Sorteio', 'juiz': 'Dr. João Silva', 'valor_acao': '5000,00', 'partes_processo': [], 'lista_movimentacoes': [] } ExtractDataOutput(**valid_data) def test_valid_output(): """Testa um output válido para ExtractDataSecondInstanceOutput.""" valid_data = { "classe": "Recurso Penal", "area": "Criminal", "assunto": "Furto", "partes_processo": [], "lista_movimentacoes": [] } output = ExtractDataSecondInstanceOutput(**valid_data) assert output.classe == "Recurso Penal" assert output.area == "Criminal" def test_missing_required_field(): """Testa a ausência de campos obrigatórios para ExtractDataSecondInstanceOutput.""" invalid_data = { "classe": "Recurso Penal", "assunto": "Furto", "partes_processo": [], "lista_movimentacoes": [] } with raises(ValidationError): ExtractDataSecondInstanceOutput(**invalid_data) def test_valid_output_first_instance_only(): """Testa um output válido para StatusSolicitacaoOutput com apenas dados da primeira instância.""" valid_data = { "numero_processo": "0113546-72.2018.8.02.0001", "sigla_tribunal": "TJAL", "status": "Na Fila", "first_instance": { "classe": "Penal", "area": "Criminal", "assunto": "Roubo", "data_distribuicao": "Sorteio", "juiz": "Dr. João Silva", "partes_processo": [], "lista_movimentacoes": [] } } output = StatusSolicitacaoOutput(**valid_data) assert output.numero_processo == "0113546-72.2018.8.02.0001" assert output.first_instance.classe == "Penal" def test_valid_output_both_instances(): """Testa um output válido para StatusSolicitacaoOutput com dados de ambas as instâncias.""" valid_data = { "numero_processo": "0113546-72.2018.8.02.0001", "sigla_tribunal": "TJAL", "status": "Na Fila", "first_instance": ExtractDataOutput( classe="Penal", area="Criminal", assunto="Roubo", data_distribuicao="Sorteio", juiz="Dr. João Silva", valor_acao="5000,00", partes_processo=[], lista_movimentacoes=[] ), "second_instance": ExtractDataSecondInstanceOutput( classe="Recurso Penal", area="Criminal", assunto="Furto", valor_acao="2500,55", partes_processo=[], lista_movimentacoes=[] ) } output = StatusSolicitacaoOutput(**valid_data) assert output.numero_processo == "0113546-72.2018.8.02.0001" assert output.sigla_tribunal == "TJAL" assert output.status == "Na Fila" assert isinstance(output.first_instance, ExtractDataOutput) assert isinstance(output.second_instance, ExtractDataSecondInstanceOutput) def test_invalid_output(): """Testa um output inválido para StatusSolicitacaoOutput.""" invalid_data = { "numero_processo": 123456 # Um número em vez de uma string } with raises(ValidationError): StatusSolicitacaoOutput(**invalid_data)
BrunoPisaneschi/JusBrasil
tests/unit/api/schemas/test_output.py
test_output.py
py
4,369
python
pt
code
0
github-code
36
[ { "api_name": "uuid.uuid4", "line_number": 20, "usage_type": "call" }, { "api_name": "api.schemas.output.ConsultaProcessoOutput", "line_number": 21, "usage_type": "call" }, { "api_name": "unittest.mock.MagicMock", "line_number": 27, "usage_type": "call" }, { "api_...
9148386910
#coding=utf-8 """ 这是一个关于QQ模拟(QListView的使用)的例子--模型定义! 文章链接:http://www.xdbcb8.com/archives/701.html """ import random import Random_Name from PyQt5.QtCore import QAbstractListModel, Qt, QModelIndex, QVariant, QSize from PyQt5.QtGui import QIcon, QFont class ListModel(QAbstractListModel): ''' 自定义模型 ''' def __init__(self): ''' 一些初始设置 ''' super().__init__() self.ListItemData = [] # 存储每个QQ用户的列表 self.Data_init() def data(self, index, role): ''' 子类化QAbstractListModel必须要实现的函数,主要作用就是返回index所引用项目的给定role下存储的数据。 ''' if index.isValid() or (0 <= index.row() < len(self.ListItemData)): if role == Qt.DisplayRole: return QVariant(self.ListItemData[index.row()]['name']) # 文本形式呈现数据 elif role == Qt.DecorationRole: return QVariant(QIcon(self.ListItemData[index.row()]['iconPath'])) # 以图标形式呈现装饰数据 elif role == Qt.SizeHintRole: return QVariant(QSize(70, 80)) # 视图项目大小 elif role == Qt.TextAlignmentRole: return QVariant(int(Qt.AlignHCenter|Qt.AlignVCenter)) # 文本对齐方式 elif role == Qt.FontRole: font = QFont() font.setPixelSize(20) return QVariant(font) # 字体设置 return QVariant() # 非上述情况,返回为空,记住这里是QVariant() def rowCount(self, parent = QModelIndex()): ''' 返回行数,在这里就是数据列表的大小。 ''' return len(self.ListItemData) def Data_init(self): ''' 数据初始化 ''' randomnum = random.sample(range(26), 10) # 从0-25个数字中随机的抽取10个不重复的数字组成一个列表 for i in randomnum: randname = Random_Name.getname() ItemData = {'name':'', 'iconPath':''} ItemData['name'] = randname ItemData['iconPath'] = "./res/"+ str(i) + ".jpg" # 遍历这个列表randomnum,其中联系人的姓名我是随机生成的,随机的生成图标的路径;把姓名和图标路径添加到字典当中。 self.ListItemData.append(ItemData) # append到数据列表里面。 def addItem(self, itemData): ''' 新增的操作实现 ''' if itemData: self.beginInsertRows(QModelIndex(), len(self.ListItemData), len(self.ListItemData) + 1) self.ListItemData.append(itemData) self.endInsertRows() # 结束行插入操作 def deleteItem(self, index): ''' 指定索引的数据从数据列表中删除 ''' del self.ListItemData[index] def getItem(self, index): ''' 获得相应的项目数据 ''' if index > -1 and index < len(self.ListItemData): return self.ListItemData[index]
redmorningcn/PyQT5Example
PyQt5All/PyQt535、36、37/ListModel.py
ListModel.py
py
3,281
python
zh
code
1
github-code
36
[ { "api_name": "PyQt5.QtCore.QAbstractListModel", "line_number": 13, "usage_type": "name" }, { "api_name": "PyQt5.QtCore.Qt.DisplayRole", "line_number": 32, "usage_type": "attribute" }, { "api_name": "PyQt5.QtCore.Qt", "line_number": 32, "usage_type": "name" }, { "...
17929378111
#!/usr/bin/python3 import multiprocessing import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button, RadioButtons import math import time def points(): import sys for line in open("input.txt"): line = line.replace("position=", "").replace("velocity=", "").replace(' ', '').replace('<', '').strip() a = line.split('>') yield [tuple([int(y) for y in x.split(',')]) for x in a[0:2]] def produce_state(PP, PV, T): ret = [] for p in zip(PP, PV): v = p[1] p = p[0] ret.append([p[0] + v[0] * T, p[1] + v[1] * T]) return ret def render(PP, T): plt.scatter([p[0] for p in PP], [p[1] for p in PP]) plt.show(block=True) def BB(PP): sx = 0 sy = 0 ex = 0 ey = 0 for p in PP: if p[0] < sx: sx = p[0] if p[0] > ex: ex = p[0] if p[1] < sy: sy = p[1] if p[1] > ey: ey = p[1] return sx, sy, ex, ey P = [point for point in points()] # calc BB PP = [point[0] for point in P] PV = [point[1] for point in P] T = 0 Emin = 0 Tmin = -1 step = 1 def update(T): S = produce_state(PP, PV, T) sx, sy, ex, ey = BB(S) #render(S, T) return (math.sqrt((sx - ex) ** 2 + (sy - ey) ** 2)) fuck = 256000 scale = 100 start = int(10518.9 * scale) end = int((1 + 10519) * scale) #for T in range(start, end, 1): for i in range(1): T = 10519 #T = T / scale S = produce_state(PP, PV, T) sx, sy, ex, ey = BB(S) cunt = (math.sqrt((sx - ex) ** 2 + (sy - ey) ** 2)) print(T) #if fuck< cunt: # print(T) # render(S, T) # break render(S, T) fuck = cunt
Easimer/advent-of-code-2018
day10/day10.py
day10.py
py
1,643
python
en
code
0
github-code
36
[ { "api_name": "matplotlib.pyplot.scatter", "line_number": 26, "usage_type": "call" }, { "api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name" }, { "api_name": "matplotlib.pyplot.show", "line_number": 27, "usage_type": "call" }, { "api_name": "ma...
25759790506
import os from datetime import datetime dir = os.path.dirname(os.getcwd()+'/users/') print(dir) try: os.stat(dir) except: os.mkdir(dir) print('make directory') all_users = {} for f in os.listdir(os.getcwd()): if f.endswith(".csv"): split = str(f).split('_') code = split[1] print('[{}] Processing {} - {}'.format(datetime.now(), code, f)) users = {} with open(f, 'r', encoding='utf8') as fr: for line in fr: split = line.split(',') if len(split) < 2: continue try: uid = int(split[1]) except: continue # This file users f_uid = users.get(uid) if f_uid is None: users[uid] = 1 else: users[uid] = f_uid + 1 # All users f_all = all_users .get(uid) if f_all is None: all_users[uid] = 1 else: all_users[uid] = f_all + 1 with open(dir + '/' + str(code) + '.csv', 'w') as fw: for uid, f_uid in users.items(): fw.write('{},{}\n'.format(uid,f_uid)) users.clear() print('[{}] Processing all files'.format(datetime.now())) with open(dir + '/#ALL.csv', 'w') as fw_all: for uid, f_all in all_users.items(): fw_all.write('{},{}\n'.format(uid,f_all)) print('[{}] Program finished'.format(datetime.now()))
gunarto90/twitter-stream
iterate user id.py
iterate user id.py
py
1,564
python
en
code
1
github-code
36
[ { "api_name": "os.path.dirname", "line_number": 4, "usage_type": "call" }, { "api_name": "os.path", "line_number": 4, "usage_type": "attribute" }, { "api_name": "os.getcwd", "line_number": 4, "usage_type": "call" }, { "api_name": "os.stat", "line_number": 7, ...
18924218055
from selenium import webdriver from selenium.webdriver.common.by import By import time class SwitchToWindow(): def test(self): baseUrl = "https://letskodeit.teachable.com/pages/practice" driver = webdriver.Firefox() driver.maximize_window() driver.get(baseUrl) # Find parent handle -> Main Window parentHandle = driver.current_window_handle print("Parent Handle: " + parentHandle) # Find open window button and click it driver.find_element(By.ID, "openwindow").click() time.sleep(2) # Find all handles, there should two handles after clicking open window button handles = driver.window_handles # Switch to window and search course for handle in handles: print("Handle: " + handle) ff = SwitchToWindow() ff.test()
PacktPublishing/-Selenium-WebDriver-With-Python-3.x---Novice-To-Ninja-v-
CODES/S23 - Selenium WebDriver -_ Switch Window And IFrames/1_switch-to-window.py
1_switch-to-window.py
py
847
python
en
code
11
github-code
36
[ { "api_name": "selenium.webdriver.Firefox", "line_number": 9, "usage_type": "call" }, { "api_name": "selenium.webdriver", "line_number": 9, "usage_type": "name" }, { "api_name": "selenium.webdriver.common.by.By.ID", "line_number": 18, "usage_type": "attribute" }, { ...
28492416311
from django.shortcuts import render, HttpResponse from django.conf import settings from rest_framework.decorators import api_view from rest_framework.response import Response import random from .models import Planet from .serializers import PlanetSerializer from api.serializers import GenericSerializer from api.views import BaseRandomView, BaseIdView from api.utils import validate_request, set_options_response MODEL = Planet @api_view(['GET', 'OPTIONS']) def index(request): if request.method == 'OPTIONS': return set_options_response() result = validate_request(request) if 'error' in result: return Response({"error": result['error']}, status=result['status'], headers=settings.CORS_HEADERS) name = request.GET.get('name', None) affiliation = request.GET.get('affiliation', None) region = request.GET.get('region', None) page = request.GET.get('page', 0) planets_set = Planet.objects.all().order_by('id') if name: planets_set = planets_set.filter(name__icontains=name) if affiliation: planets_set = planets_set.filter(info__affiliation__icontains=affiliation) if region: planets_set = planets_set.filter(info__region__icontains=region) if page: try: page = int(page) except: page = 1; start = settings.RESOURCE_LIMIT*(page-1) end = settings.RESOURCE_LIMIT*(page-1)+settings.RESOURCE_LIMIT planets_set = planets_set[start:end] else: planets_set = planets_set[0:settings.RESOURCE_LIMIT] serializer = PlanetSerializer(planets_set, many=True) # If nothing matches queries if not serializer.data: return Response({"error": settings.MSG_404}, status=404, headers=settings.CORS_HEADERS) return Response(serializer.data, headers=settings.CORS_HEADERS) class RandomPlanetView(BaseRandomView): model = MODEL class PlanetIdView(BaseIdView): model = MODEL
yitchee/The-Clone-Wars-API
api/planets/views.py
views.py
py
1,971
python
en
code
0
github-code
36
[ { "api_name": "models.Planet", "line_number": 17, "usage_type": "name" }, { "api_name": "api.utils.set_options_response", "line_number": 23, "usage_type": "call" }, { "api_name": "api.utils.validate_request", "line_number": 25, "usage_type": "call" }, { "api_name"...
10495517316
from django.test import TestCase, RequestFactory from djlotrek.request_utils import get_host_url class RequestUtilsTestCase(TestCase): def test_get_host_url(self): """ get_host_url function retrieve request object and return host url when request object is not None """ request_factory = RequestFactory() request = request_factory.get("/path") request.META["HTTP_HOST"] = "localhost" host_url = get_host_url(request) self.assertEqual(host_url, "http://localhost") def test_get_host_url_no_request(self): """ get_host_url function retrieve request object and return None when request object is None """ host_url = get_host_url(None) self.assertEqual(host_url, None)
lotrekagency/djlotrek
tests/test_request_utils.py
test_request_utils.py
py
797
python
en
code
7
github-code
36
[ { "api_name": "django.test.TestCase", "line_number": 6, "usage_type": "name" }, { "api_name": "django.test.RequestFactory", "line_number": 12, "usage_type": "call" }, { "api_name": "djlotrek.request_utils.get_host_url", "line_number": 15, "usage_type": "call" }, { ...
2434152222
from funcs import * import numpy as np import matplotlib.pyplot as plt counter = lambda List, isPositive: sum(List) if isPositive else N - sum(List) # Выборка N = 1000 # Class 0 mu_0 = 190 sigma_0 = 10 basketballers = np.random.normal(mu_0, sigma_0, N) # Class 1 mu_1 = 173 sigma_1 = 12 footballers = np.random.normal(mu_1, sigma_1, N) # Порог бинарного классификатора limit = 250 tpr_list, fpr_list, alpha_list, one_minus_beta, accuracy_list = [], [], [], [], [] TruePositive, FalsePositive, FalseNegative, TrueNegative = [], [], [], [] for lim in range(limit): classified_basketballers = Classification(basketballers, lim) classified_footballers = Classification(footballers, lim) TruePositive.append(counter(classified_footballers, True)) TrueNegative.append(counter(classified_basketballers, False)) FalsePositive.append(counter(classified_basketballers, True)) FalseNegative.append(counter(classified_footballers, False)) if TruePositive[lim] != 0 and (FalsePositive[lim] + TrueNegative[lim]) != 0: accuracy = Accuracy(TruePositive[lim], TrueNegative[lim], FalsePositive[lim], FalseNegative[lim]) accuracy_list.append(accuracy) alpha = ALPHA(FalsePositive[lim], TrueNegative[lim]) alpha_list.append(alpha) beta = BETA(FalseNegative[lim], TruePositive[lim]) one_minus_beta.append(1 - beta) precision = Precision(TruePositive[lim], FalsePositive[lim]) recall = Recall(TruePositive[lim], FalseNegative[lim]) f1 = F1(precision, recall) tpr_list.append(TPR(TruePositive[lim], FalseNegative[lim])) fpr_list.append(FPR(FalsePositive[lim], TrueNegative[lim])) else: accuracy_list.append(0) # Площадь под под построенной кривой (AUC) print(f"AUC: {S(fpr_list, tpr_list)}") # Максимальный Accuracy index = accuracy_list.index(max(accuracy_list)) print(f"Порог при максимальном значении Accuracy: {index}") TP_max = TruePositive[index] FP_max = FalsePositive[index] FN_max = FalseNegative[index] TN_max = TrueNegative[index] accuracy = Accuracy(TP_max, TN_max, FP_max, FN_max) print(f"Accuracy = {accuracy}") precision = Precision(TP_max, FP_max) print(f"Precision = {precision}") recall = Recall(TP_max, FN_max) print(f"Recall = {recall}") f1 = F1(precision, recall) print(f"F1-score = {f1}") alpha = ALPHA(FP_max, TN_max) print(f"Alpha = {alpha}") beta = BETA(FN_max, TP_max) print(f"Beta = {beta}") # График ROC кривой fig = plt.figure() plt.plot(alpha_list, one_minus_beta) plt.show()
shulayonok/ML4
main.py
main.py
py
2,654
python
en
code
0
github-code
36
[ { "api_name": "numpy.random.normal", "line_number": 13, "usage_type": "call" }, { "api_name": "numpy.random", "line_number": 13, "usage_type": "attribute" }, { "api_name": "numpy.random.normal", "line_number": 18, "usage_type": "call" }, { "api_name": "numpy.rando...
29858390178
import time import pickle from pathlib import Path from os.path import splitext import json from tensorflow.keras.wrappers.scikit_learn import KerasClassifier # ASReview dependencies from asreview.review import ReviewSimulate, ReviewOracle, MinimalReview from asreview.utils import text_to_features from asreview.types import is_pickle from asreview.config import AVAILABLE_CLI_MODI, AVAILABLE_REVIEW_CLASSES,\ DEFAULT_MODEL, DEFAULT_QUERY_STRATEGY, DEFAULT_BALANCE_STRATEGY,\ DEFAULT_N_INSTANCES, DEFAULT_N_PRIOR_INCLUDED, DEFAULT_N_PRIOR_EXCLUDED,\ DEMO_DATASETS, KERAS_MODELS from asreview.models.embedding import download_embedding, EMBEDDING_EN from asreview.models.embedding import load_embedding, sample_embedding from asreview.utils import get_data_home from asreview.query_strategies import get_query_strategy from asreview.balance_strategies import get_balance_strategy from asreview.logging import Logger from asreview.settings import ASReviewSettings from asreview.models import create_lstm_base_model, lstm_base_model_defaults from asreview.models import create_lstm_pool_model, lstm_pool_model_defaults from asreview.models import lstm_fit_defaults from asreview.readers import ASReviewData def get_reviewer(dataset, mode='oracle', model=DEFAULT_MODEL, query_strategy=DEFAULT_QUERY_STRATEGY, balance_strategy=DEFAULT_BALANCE_STRATEGY, n_instances=DEFAULT_N_INSTANCES, n_queries=1, embedding_fp=None, verbose=1, prior_included=None, prior_excluded=None, n_prior_included=DEFAULT_N_PRIOR_INCLUDED, n_prior_excluded=DEFAULT_N_PRIOR_EXCLUDED, config_file=None, src_log_fp=None, **kwargs ): # Find the URL of the datasets if the dataset is an example dataset. if dataset in DEMO_DATASETS.keys(): dataset = DEMO_DATASETS[dataset] if src_log_fp is not None: logger = Logger(log_fp=src_log_fp) settings = logger.settings else: logger = None settings = ASReviewSettings(model=model, n_instances=n_instances, n_queries=n_queries, n_prior_included=n_prior_included, n_prior_excluded=n_prior_excluded, query_strategy=query_strategy, balance_strategy=balance_strategy, mode=mode, data_fp=dataset ) settings.from_file(config_file) model = settings.model if model in ["lstm_base", "lstm_pool"]: base_model = "RNN" else: base_model = "other" # Check if mode is valid if mode in AVAILABLE_REVIEW_CLASSES: if verbose: print(f"Start review in '{mode}' mode.") else: raise ValueError(f"Unknown mode '{mode}'.") print(f"Model: '{model}'") # if the provided file is a pickle file if is_pickle(dataset): with open(dataset, 'rb') as f: data_obj = pickle.load(f) if isinstance(data_obj, tuple) and len(data_obj) == 3: X, y, embedding_matrix = data_obj elif isinstance(data_obj, tuple) and len(data_obj) == 4: X, y, embedding_matrix, _ = data_obj else: raise ValueError("Incorrect pickle object.") else: as_data = ASReviewData.from_file(dataset) _, texts, labels = as_data.get_data() # get the model if base_model == "RNN": if embedding_fp is None: embedding_fp = Path( get_data_home(), EMBEDDING_EN["name"] ).expanduser() if not embedding_fp.exists(): print("Warning: will start to download large " "embedding file in 10 seconds.") time.sleep(10) download_embedding(verbose=verbose) # create features and labels X, word_index = text_to_features(texts) y = labels embedding = load_embedding(embedding_fp, word_index=word_index) embedding_matrix = sample_embedding(embedding, word_index) elif model.lower() in ['nb', 'svc', 'svm']: from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import CountVectorizer text_clf = Pipeline([('vect', CountVectorizer()), ('tfidf', TfidfTransformer())]) X = text_clf.fit_transform(texts) y = labels settings.fit_kwargs = {} settings.query_kwargs = {} if base_model == 'RNN': if model == "lstm_base": model_kwargs = lstm_base_model_defaults(settings, verbose) create_lstm_model = create_lstm_base_model elif model == "lstm_pool": model_kwargs = lstm_pool_model_defaults(settings, verbose) create_lstm_model = create_lstm_pool_model else: raise ValueError(f"Unknown model {model}") settings.fit_kwargs = lstm_fit_defaults(settings, verbose) settings.query_kwargs['verbose'] = verbose # create the model model = KerasClassifier( create_lstm_model(embedding_matrix=embedding_matrix, **model_kwargs), verbose=verbose ) elif model.lower() in ['nb']: from asreview.models import create_nb_model model = create_nb_model() elif model.lower() in ['svm', 'svc']: from asreview.models import create_svc_model model = create_svc_model() else: raise ValueError('Model not found.') # Pick query strategy query_fn, query_str = get_query_strategy(settings) if verbose: print(f"Query strategy: {query_str}") train_data_fn, train_method = get_balance_strategy(settings) if verbose: print(f"Using {train_method} method to obtain training data.") # Initialize the review class. if mode == "simulate": reviewer = ReviewSimulate( X, y, model=model, query_strategy=query_fn, train_data_fn=train_data_fn, n_instances=settings.n_instances, n_queries=settings.n_queries, verbose=verbose, prior_included=prior_included, prior_excluded=prior_excluded, n_prior_included=settings.n_prior_included, n_prior_excluded=settings.n_prior_excluded, fit_kwargs=settings.fit_kwargs, balance_kwargs=settings.balance_kwargs, query_kwargs=settings.query_kwargs, logger=logger, **kwargs) elif mode == "oracle": reviewer = ReviewOracle( X, model=model, query_strategy=query_fn, as_data=as_data, train_data_fn=train_data_fn, n_instances=settings.n_instances, n_queries=settings.n_queries, verbose=verbose, prior_included=prior_included, prior_excluded=prior_excluded, fit_kwargs=settings.fit_kwargs, balance_kwargs=settings.balance_kwargs, query_kwargs=settings.query_kwargs, logger=logger, **kwargs) elif mode == "minimal": reviewer = MinimalReview( X, model=model, query_strategy=query_fn, train_data_fn=train_data_fn, n_instances=settings.n_instances, n_queries=settings.n_queries, verbose=verbose, prior_included=prior_included, prior_excluded=prior_excluded, fit_kwargs=settings.fit_kwargs, balance_kwargs=settings.balance_kwargs, query_kwargs=settings.query_kwargs, logger=logger, **kwargs) else: raise ValueError("Error finding mode, should never come here...") reviewer._logger.add_settings(settings) return reviewer def review(*args, mode="simulate", model=DEFAULT_MODEL, save_model_fp=None, **kwargs): if mode not in AVAILABLE_CLI_MODI: raise ValueError(f"Unknown mode '{mode}'.") reviewer = get_reviewer(*args, model=model, **kwargs) # Wrap in try expect to capture keyboard interrupt try: # Start the review process. reviewer.review() except KeyboardInterrupt: print('\nClosing down the automated systematic review.') # If we're dealing with a keras model, we can save the last model weights. if save_model_fp is not None and model in KERAS_MODELS: save_model_h5_fp = splitext(save_model_fp)[0]+".h5" json_model = model.model.to_json() with open(save_model_fp, "w") as f: json.dump(json_model, f, indent=2) model.model.save_weights(save_model_h5_fp, overwrite=True) if not reviewer.log_file: print(reviewer._logger._print_logs()) def review_oracle(dataset, **kwargs): """CLI to the interactive mode.""" review(dataset, mode='oracle', **kwargs) def review_simulate(dataset, **kwargs): """CLI to the oracle mode.""" review(dataset, mode='simulate', **kwargs)
syuanuvt/automated-systematic-review
asreview/review/factory.py
factory.py
py
9,549
python
en
code
null
github-code
36
[ { "api_name": "asreview.config.DEFAULT_MODEL", "line_number": 34, "usage_type": "name" }, { "api_name": "asreview.config.DEFAULT_QUERY_STRATEGY", "line_number": 35, "usage_type": "name" }, { "api_name": "asreview.config.DEFAULT_BALANCE_STRATEGY", "line_number": 36, "usage...
8729618404
#This script will format all images in a given directory to the same size and to gray scale using OpenCV from scipy import ndimage, misc import numpy as np import cv2 as cv from os import listdir #Iterate throuh the training image directory and sub folders img_directory= "/home/paok/Documents/FaceRecognition/trainImages" #create a list with file names in image directory #Iterate through folder in img_directory subjects= listdir(img_directory) #Iterate through file name list and add to csv file for i in range(len(subjects)): pictures = listdir("/home/paok/Documents/FaceRecognition/trainImages/"+subjects[i]) for pic in pictures: filtered = np.zeros((256, 256, 1), dtype = "uint8") path = "/home/paok/Documents/FaceRecognition/trainImages/"+subjects[i]+"/"+pic #print(path) #Open image in direcotry image = cv.imread(path) #Convert it to gray scale image = cv.cvtColor(image, cv.COLOR_BGR2GRAY) #Saturate image image = 1.2*image #Format as float32 img = np.array(image, dtype=np.float32) #Filter filtered = cv.bilateralFilter(img,2,15,15) #Resize to 200x200 pixels filtered = cv.resize(filtered,(200,200)) wrt = np.array(filtered, dtype="uint8") write = cv.equalizeHist(wrt) cv.imwrite(path, write)
PAOK-2001/FaceRecognition
Trainer_auxfiles/imageFormater.py
imageFormater.py
py
1,359
python
en
code
0
github-code
36
[ { "api_name": "os.listdir", "line_number": 10, "usage_type": "call" }, { "api_name": "os.listdir", "line_number": 13, "usage_type": "call" }, { "api_name": "numpy.zeros", "line_number": 15, "usage_type": "call" }, { "api_name": "cv2.imread", "line_number": 19,...
70190123945
from tech_news.database import search_news from datetime import datetime # Requisito 6 def search_by_title(title): find = search_news( {"title": {"$regex": f"{title}", "$options": "i"}} ) return [(item["title"], item["url"]) for item in find] # Requisito 7 def search_by_date(date): try: find_by_date = list() date = datetime.strptime(date, '%Y-%m-%d') default_date = datetime.strftime(date, '%d/%m/%Y') new_date = search_news({ 'timestamp': default_date }) for date in new_date: find_by_date.append((date['title'], date['url'])) except ValueError: raise ValueError('Data inválida') return find_by_date # Requisito 8 def search_by_tag(tag): find = search_news( {"tags": {"$regex": tag, "$options": "i"}} ) return [(item["title"], item["url"]) for item in find] # Requisito 9 def search_by_category(category): find = search_news( {"category": {"$regex": category, "$options": "i"}} ) return [(item["title"], item["url"]) for item in find]
mabiiak/tech-news
tech_news/analyzer/search_engine.py
search_engine.py
py
1,103
python
en
code
0
github-code
36
[ { "api_name": "tech_news.database.search_news", "line_number": 7, "usage_type": "call" }, { "api_name": "datetime.datetime.strptime", "line_number": 18, "usage_type": "call" }, { "api_name": "datetime.datetime", "line_number": 18, "usage_type": "name" }, { "api_na...
7749021941
import sys import os from Bio.Blast import NCBIWWW from Bio.Blast.Applications import NcbiblastxCommandline from Bio.Blast import NCBIXML from Bio import SeqIO E_VALUE_THRESH = 10 RESULTS_XML = "results.xml" PROT_DB = "swissprot" NUC_DB = "nt" if len (sys.argv) != 5: print("Invalid params: 1) In file path - 2) Out file path 3) Type ( --prot or --nuc ) 4) Mode ( --online --local)") sys.exit(1) fasta_string = open(sys.argv[1]).read() if sys.argv[3] == "--prot": if sys.argv[4] == '--online': result_handle = NCBIWWW.qblast("blastp", PROT_DB, fasta_string, expect=E_VALUE_THRESH) with open(RESULTS_XML, "w") as out_handle: out_handle.write(result_handle.read()) result_handle = open(RESULTS_XML) elif sys.argv[4] == '--local': blastx_cline = NcbiblastxCommandline(cmd='blastp', query=sys.argv[1], db=PROT_DB, evalue=E_VALUE_THRESH, out=RESULTS_XML, outfmt=5) stdout, stderr = blastx_cline() result_handle = open(RESULTS_XML) else: print("Invalid Mode for blast") sys.exit(1) elif sys.argv[3] == "--nuc": result_handle = NCBIWWW.qblast("blastn", NUC_DB, fasta_string) else: print("Invalid type for blast") sys.exit(1) blast_records = NCBIXML.parse(result_handle) if os.path.exists(sys.argv[2]): os.remove(sys.argv[2]) for blast_record in blast_records: for alignment in blast_record.alignments: for hsp in alignment.hsps: with open(sys.argv[2], "a") as f: print("****Blast Result****", file=f) print("sequence:", alignment.title, file = f) print("length:", alignment.length, file = f) print("e value:", hsp.expect, file = f) print("gaps:", hsp.gaps, file = f) print("identities:", hsp.identities, file = f) print("positives:", hsp.positives, file = f) print("score:", hsp.score, file = f) print(hsp.query[0:75] + "...", file = f) print(hsp.match[0:75] + "...", file = f) print(hsp.sbjct[0:75] + "...", file = f) if os.path.exists("results.xml"): os.remove("results.xml")
jpalacci/bio
src/ex2.py
ex2.py
py
1,987
python
en
code
0
github-code
36
[ { "api_name": "sys.argv", "line_number": 14, "usage_type": "attribute" }, { "api_name": "sys.exit", "line_number": 16, "usage_type": "call" }, { "api_name": "sys.argv", "line_number": 18, "usage_type": "attribute" }, { "api_name": "sys.argv", "line_number": 20...
3300025718
from exif_service import ExifService from ai_service import AiService import base64 import os class ImageService: def __init__(self, app, initial_path, ai_enabled=True): self.directory = initial_path self.app = app self.ai_enabled = ai_enabled self.exif_service = ExifService() if self.ai_enabled: self.ai_service = AiService() def get_current_directory(self): return self.directory def get_images(self): return self.__get_images(self.directory, 10) def __get_images(self, directory, remaining_depth=0): images = [] for file in os.listdir(directory): if os.path.isfile(os.path.join(directory, file)): try: Image.open(os.path.join(directory, file)) except IOError: self.app.logger.warning("File %s is not an image", file) continue try: images.append(self.exif_service.get_metadata(directory, file)) except LookupError: continue if self.ai_enabled: images[-1]["motif"] = self.ai_service.get_image_motif(directory, file) elif remaining_depth > 0: images.extend(self.__get_images(os.path.join(directory, file), remaining_depth - 1)) return images def change_directory(self, directory): if len(directory.split(os.path.sep)) > 1: self.directory = directory elif directory == "..": self.directory = os.path.dirname(self.directory) else: self.directory = os.path.join(self.directory, directory) def get_image(self, file): with open(os.path.join(self.directory, file), "rb") as image_file: return base64.b64encode(image_file.read()).decode("utf-8") def get_files_and_directories(self): files = [{"name": "..", "isFile": False}] files.extend([{"name": f, "isFile": os.path.isfile(os.path.join(self.directory, f))} for f in os.listdir(self.directory)]) return files
tim0-12432/photo-analyzer
backend/image_service.py
image_service.py
py
2,127
python
en
code
0
github-code
36
[ { "api_name": "exif_service.ExifService", "line_number": 13, "usage_type": "call" }, { "api_name": "ai_service.AiService", "line_number": 15, "usage_type": "call" }, { "api_name": "os.listdir", "line_number": 25, "usage_type": "call" }, { "api_name": "os.path.isfi...
30540305178
#!/usr/bin/env python3 import requests import pandas as pd import json import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) # Our endpoint URL endpoint = "http://universities.hipolabs.com/search?country=Canada" def report_to_csv(api_url): # Making a GET request to the endpoint response = requests.get(api_url) # Serialize the response as JSON json_response = json.dumps(response.json()) logging.info(" Data buffered successfully") # Use the pandas library to buffer the serialized response df = pd.read_json(json_response) logging.info(" %d records retrieved", (len(df)-1)) logging.info(" Data converted to type JSON") # Sort the data frame by the 'name' column, ascending sorted_df = df.sort_values(by=["name"]) logging.info(" Data Frame is now sorted alphabetically") # Create the universities.csv file and again use the pandas linrary to export the # JSON data frame to CSV format and write it to the file. # We're also changing the order of the columns in the CSV file so that it makes more sense. with open("universities.csv", 'w') as uni_csv: sorted_df.to_csv(uni_csv, index=False, columns=['name', 'domains', 'web_pages', 'state-province', 'alpha_two_code', 'country']) logging.info(" Data is now written to file universities.csv") if __name__ == "__main__": report_to_csv(endpoint) logging.info(" Task finished with no error")
samsheriff/seccomp-proj-api
main.py
main.py
py
1,463
python
en
code
0
github-code
36
[ { "api_name": "logging.basicConfig", "line_number": 9, "usage_type": "call" }, { "api_name": "sys.stdout", "line_number": 9, "usage_type": "attribute" }, { "api_name": "logging.DEBUG", "line_number": 9, "usage_type": "attribute" }, { "api_name": "requests.get", ...
71239927463
''' Author - Imanpal Singh <imanpalsingh@gmail.com> GUI application for twitter sentiment analysis Date created : - 02-07-2019 Date modified : - 03-07-2019 ''' #importing requierd libraries import numpy as np import pandas as pd from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer ps = PorterStemmer() from sklearn.naive_bayes import GaussianNB nb = GaussianNB() from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(max_features = 8000) import re import tkinter as tk from tkinter import Text import pyperclip #Global variable to hold score score=0 #Machine Learning part def Algorithm(file): global score #Loading the dataset dataset = pd.read_csv(file) #Cleaning tweets clean_tweets = [] for i in range(len(dataset)): tw = re.sub('[^a-zA-Z]', ' ', dataset['tweet'][i]) tw = re.sub('@[\w]*',' ',tw) tw = tw.lower() tw = tw.split() tw = [ps.stem(token) for token in tw if not token in set(stopwords.words('english'))] tw = ' '.join(tw) clean_tweets.append(tw) #textual encoding X = cv.fit_transform(clean_tweets) X = X.toarray() y = dataset.iloc[:, 1].values #splitting the data from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test = train_test_split(X,y) #training the data nb.fit(X_train,y_train) score = nb.score(X_test,y_test) print("Score is : - ",score) #Function to handle Go button event def forward(): #Getting the tweet tw = tweet.get("1.0","end") #Cleaning the tweet tw = re.sub('[^a-zA-Z]', ' ', tw) tw = re.sub('@[\w]*',' ',tw) tw = tw.lower() tw = tw.split("\n") tw = [ps.stem(token) for token in tw if not token in set(stopwords.words('english'))] tw = cv.transform(tw) tw = tw.toarray() #Predicting the class y_pred = nb.predict(tw) #Clearning the Entry tweet.delete("1.0","end") #Displaying the class if y_pred[0] == 0: tweet.insert("1.0","The tweet entered is normal ( model's accuracy : {}% )".format(score*100)) else : tweet.insert("1.0","The tweet entered is negative ( model's accuracy : {}% )".format(score*100)) #Function to handle Paste from clipboard button event def clippaste(): tweet.insert("1.0",pyperclip.paste()) #Initialising algorithm Algorithm('train.csv') #GUI part #Creating a window Main = tk.Tk() Main.configure(background='white') Main.title("Twitter Sentiment analysis") Main.geometry("1000x400+400+300") #Adding the heading one = tk.Label(Main,text="Twitter Sentiment analysis",fg="white",width="100",height="2") one.configure(background="#6E97ED",font=(20)) #Adding the textbox tweet = tk.Text(Main,height="10",width="60") tweet.insert("1.0","Paste tweet here..") tweet.configure(bd=0,fg="#6E97ED") #Adding buttons button_frame = tk.Frame(Main) button_frame.configure(background="white") go= tk.Button(button_frame,text="GO !",width="10",height="5",command=forward) go.configure(background="#6E97ED",fg="white",bd=0) paste = tk.Button(button_frame,text="Paste from clipboard",width="20",height="5",command=clippaste) paste.configure(background="#6E97ED",fg="white",bd=0) #Finishing up one.pack(pady=30) tweet.pack(side="top",padx=10,pady=20) go.pack(side="left") paste.pack(side="left",padx="30") button_frame.pack(side="bottom") #Removing resizeable feature Main.resizable(0,0) tk.mainloop()
imanpalsingh/twitter-sentiment-analysis
GUI.py
GUI.py
py
3,692
python
en
code
1
github-code
36
[ { "api_name": "nltk.stem.porter.PorterStemmer", "line_number": 14, "usage_type": "call" }, { "api_name": "sklearn.naive_bayes.GaussianNB", "line_number": 17, "usage_type": "call" }, { "api_name": "sklearn.feature_extraction.text.CountVectorizer", "line_number": 20, "usage...
24304392906
import numpy import matplotlib import matplotlib.pyplot as plt from scipy.spatial import distance from copy import deepcopy filename1 = 'normal.txt' filename2 = 'unbalanced.txt' def readData(filename): xc = [] yc = [] coords = [xc, yc] with open(filename,'r') as f: for line in f: x, y = line.split() xc.append(float(x)) yc.append(float(y)) return coords def chooseCentroids(k): centroidX = [] centroidY = [] index = numpy.random.randint(0, len(data[0]), size = k) centroids = [centroidX, centroidY] for i in range(0, k): centroidX.append(data[0][index[i]]) centroidY.append(data[1][index[i]]) return centroids def computeError(current, previous): errorSum = 0 for i in range(len(current)): point0 = [current[0][i], current[1][i]] point1 = [previous[0][i], previous[1][i]] error = distance.euclidean(point0, point1) errorSum = errorSum + error return errorSum def kMeans(data, k): #Step 1 - Picking K random points as cluster centers,i.e centroids. #centroids = [[x1,..,xk], [y1,..yk]], xi,yi - centroids coordinates centroids = [map(float, coord) for coord in chooseCentroids(k)] #plt.scatter(data[0], data[1]) #plt.scatter(centroids[0], centroids[1] , c='r') #plt.show() #prevCentroids will be used for saving centroids coordinates before #choosing another ones x = [0] y = [0] for i in range(len(centroids[0]) - 1): x.append(0) y.append(0) prevCentroids = [x, y] centroidNumbers = [] error = computeError(centroids, prevCentroids) while error != 0: #Step 2 - Assigning each point to nearest cluster by calculating its distance to #each centroid. centrN = 0 #data[0] = [x1,...,xn] #data[1] = [y1,...,yn] #for each point [x, y] in data - compute Euclidean distance between #the point and each of centroid points. Then for each point find #to which centroid the distance is minimal. #In centroidNumbers each element represents the number of the centroid #to which corresponding point is closest, i.e: #centroidNumbers[c0=1, c1=0,..., cn=2] means that first point in data #is closest to centroid number 1, second point in data is closest to # centroid number 0 and so on. for pointN in range(len(data[0])): point = [data[0][pointN], data[1][pointN]] centroid = [centroids[0][0], centroids[1][0]] minDist = distance.euclidean(point, centroid) for i in range(1, k): centroid = [centroids[0][i], centroids[1][i]] currDist = distance.euclidean(point, centroid) if minDist > currDist: minDist = currDist centrN = i centroidNumbers.append(centrN) centrN = 0 #copying old centroid coordinates in prevCentroids prevCentroids = deepcopy(centroids) #Step 3 - Finding new centroids by taking the average of the assigned points. x = [] y = [] #cluster = [[x1,...,xn], [y1,...,yn]] cluster = [x, y] #points in cluster0 #points in cluster1 #clusters = [[[xk0,..], [yk0,...]], [[xk1,...], [yk1,...]],...] clusters = [] for clustN in range(0, k): for pointN in range(len(data[0])): if clustN == centroidNumbers[pointN]: x.append(data[0][pointN]) y.append(data[1][pointN]) centroids[0][clustN] = numpy.mean(x) centroids[1][clustN] = numpy.mean(y) clusters.append(cluster) x = [] y = [] error = computeError(centroids, prevCentroids) #Step 4 - Repeat Step 2 and 3. return centroids, clusters colors = ['r', 'g', 'r'] #data = 2-dimensional array coords=[[x1,...,xn], [y1,...,yn]] data = [map(float, coord) for coord in readData(filename1)] #data = [map(float, coord) for coord in readData(filename2)] cluster_centers, ac = kMeans(data, 3) fig, ax = plt.subplots() for i in range(3): ax.scatter(ac[i][0], ac[i][1], c=colors[i]) ax.scatter(cluster_centers[0],cluster_centers[1], s=100, c='black') plt.plot(ax)
nyuseinova/K-Means-Clustering
kMeans.py
kMeans.py
py
3,806
python
en
code
0
github-code
36
[ { "api_name": "numpy.random.randint", "line_number": 24, "usage_type": "call" }, { "api_name": "numpy.random", "line_number": 24, "usage_type": "attribute" }, { "api_name": "scipy.spatial.distance.euclidean", "line_number": 36, "usage_type": "call" }, { "api_name"...
41610031938
import json with open("players.json", 'r') as file: data=json.load(file) p1=data['player'] d={} for wkr in p1: for k,v in wkr.items(): if k=="role" and v=="Wicket-keeper": print("There is one wicket-keeper in a BTeam:", k,v)
tangellamudimanisha/BTeam
wicket-keeper.py
wicket-keeper.py
py
270
python
en
code
0
github-code
36
[ { "api_name": "json.load", "line_number": 3, "usage_type": "call" } ]
25951213667
import streamlit as st import pickle import numpy as np import pandas as pd movies_data = pickle.load(open('./books/movies.pkl','rb')) similarities = pickle.load(open('./books/movie_similarities.pkl','rb')) movies_df = pd.DataFrame(movies_data) movies_title = movies_df['title'].values def recommend(movie): movie = movie.lower() movie_id = movies_df[movies_df['lower_title'] == movie].index best5 = np.argsort(similarities[movie_id])[0,-6:-1] return movies_df['title'].values[best5] # print(recommend('Avatar')) st.title('Movie Recommender System') selected_movie_name = st.selectbox( 'Choose a movie', movies_title ) if st.button('Recommend'): recommendations = recommend(selected_movie_name) for m in recommendations: # type: ignore st.write(m)
bheemisme/movie-recommendar-system
app.py
app.py
py
797
python
en
code
0
github-code
36
[ { "api_name": "pickle.load", "line_number": 7, "usage_type": "call" }, { "api_name": "pickle.load", "line_number": 8, "usage_type": "call" }, { "api_name": "pandas.DataFrame", "line_number": 9, "usage_type": "call" }, { "api_name": "numpy.argsort", "line_numbe...
8827399963
from __future__ import absolute_import, division, print_function from collections import OrderedDict import flask from flask import current_app, request class APIEndpoint(object): MIN_API_VERSION = 3 LATEST_API_VERSION = 3 HEADER_PREFIX = "application/vnd.marv.v" def __init__(self, name, func, url_rule, defaults=None, methods=None, version=None, acl=None): self.name = name version = self.MIN_API_VERSION if version is None else version self.funcs = [(version, func)] self.url_rules = [(url_rule, {'defaults': defaults, 'methods': methods})] self.acl = set(acl) if acl else set() def __call__(self, *args, **kw): authorization = request.headers.get('Authorization') # TODO: can authorization be '' or is None test? if not authorization: authorization = request.args.get('access_token') groups = current_app.um.check_authorization(self.acl, authorization) try: accepted = (x[0] for x in flask.request.accept_mimetypes if x[0].startswith(self.HEADER_PREFIX)).next() accepted_version = int(accepted[len(self.HEADER_PREFIX):]) except (StopIteration, ValueError): accepted_version = self.MIN_API_VERSION try: func = (func for version, func in self.funcs if version <= accepted_version).next() except StopIteration: flask.abort(406) return func(*args, **kw) def init_app(self, app, url_prefix=None, name_prefix=None): name = '.'.join(filter(None, [name_prefix, self.name])) for url_rule, options in self.url_rules: url_rule = ''.join(filter(None, [url_prefix, url_rule])) app.add_url_rule(url_rule, name, self, **options) class APIGroup(object): def __init__(self, name, func, url_prefix=None): self.name = name self.func = func self.url_prefix = url_prefix self.endpoints = OrderedDict() def add_endpoint(self, ep): """endpoints and groups are all the same (for now)""" assert ep.name not in self.endpoints, ep self.endpoints[ep.name] = ep def endpoint(self, *args, **kw): return api_endpoint(*args, registry=self.endpoints, **kw) def init_app(self, app, url_prefix=None, name_prefix=None): self.func(app) name_prefix = '.'.join(filter(None, [name_prefix, self.name])) url_prefix = '/'.join(filter(None, [url_prefix, self.url_prefix])) or None for ep in self.endpoints.values(): ep.init_app(app, url_prefix=url_prefix, name_prefix=name_prefix) def __repr__(self): return '<APIGroup {} url_prefix={}>'.format(self.name, self.url_prefix) def api_endpoint(url_rule, defaults=None, methods=None, version=None, cls=APIEndpoint, registry=None, acl=None): def decorator(func): if isinstance(func, cls): func.url_rules.append((url_rule, {'defaults': defaults, 'methods': methods})) return func name = func.func_name rv = cls(name, func, url_rule=url_rule, defaults=defaults, methods=methods, version=version, acl=acl) rv.__doc__ = func.__doc__ if registry is not None: assert name not in registry, name registry[name] = rv return rv return decorator def api_group(url_prefix=None, cls=APIGroup): def decorator(func): if isinstance(func, cls): raise TypeError('Attempted to convert function into api group twice.') name = func.func_name rv = cls(name, func, url_prefix) rv.__doc__ = func.__doc__ return rv return decorator
ternaris/marv
marv_webapi/tooling.py
tooling.py
py
3,760
python
en
code
3
github-code
36
[ { "api_name": "flask.request.headers.get", "line_number": 22, "usage_type": "call" }, { "api_name": "flask.request.headers", "line_number": 22, "usage_type": "attribute" }, { "api_name": "flask.request", "line_number": 22, "usage_type": "name" }, { "api_name": "fl...
9645302628
''' Find sum of all primes below N. ''' from datetime import datetime import math import itertools def summationOfPrimes(N): sum = 0 #initialize prime number array, number corresponding to index is a prime if value is True (except first 2) primeArray = [True for i in range(N+1)] number = 2 while True: #If current number of prime, mark its multiples out of the primeArray if primeArray[number]: sum += number #print(sum) if number * 2 > N: number += 1 continue for counter in range(number * 2, N+1, number): #Number corresponding to this index is not prime if primeArray[counter]: primeArray[counter] = False number += 1 if number > N: break return sum if __name__ == '__main__': N = int (input('Input upper bound number to find sum of all primes (E.g. 2000000): ') ) start = datetime.now().strftime("%H:%M:%S") print('Answer: ', str(summationOfPrimes( N) ) ) end = datetime.now().strftime("%H:%M:%S") print( 'Start and end time: ', start, ' ', end )
bikram-gill/code
solutions/projectEuler/python/P0010-SummationOfPrimes.py
P0010-SummationOfPrimes.py
py
1,217
python
en
code
1
github-code
36
[ { "api_name": "datetime.datetime.now", "line_number": 40, "usage_type": "call" }, { "api_name": "datetime.datetime", "line_number": 40, "usage_type": "name" }, { "api_name": "datetime.datetime.now", "line_number": 44, "usage_type": "call" }, { "api_name": "datetim...
27095189897
from django.urls import path from .views import register, login,home, task_edit,task_delete, filter_period_view,logout urlpatterns =[ path("register/", register, name='register'), path('', login, name='login'), path('logout/', logout, name='logout' ), path('home/', home, name='home'), path('task/edit/<int:id>', task_edit, name='task_edit' ), path('task/delete/<int:id>', task_delete, name='task_delete'), path('task/<str:slug>', filter_period_view, name='filter-period'), ]
cavidanhasanli/Planner_project
planner_app/urls.py
urls.py
py
507
python
en
code
1
github-code
36
[ { "api_name": "django.urls.path", "line_number": 5, "usage_type": "call" }, { "api_name": "views.register", "line_number": 5, "usage_type": "argument" }, { "api_name": "django.urls.path", "line_number": 6, "usage_type": "call" }, { "api_name": "views.login", "...
43380221313
import openai def interact_with_chatgpt_prova(user, system, API_KEY, maxContent, creativita): openai.api_key = API_KEY response = openai.ChatCompletion.create( model="gpt-3.5-turbo-16k", messages=[ {"role": "system", "content": system}, {"role": "user", "content": user} ], max_tokens=maxContent, # Puoi regolare questo valore per ottenere risposte più lunghe o più corte (N token) temperature=creativita, # Puoi regolare questo valore per controllare la "creatività" delle risposte ) return [response['choices'][0]['message']['content'], response['usage']['total_tokens']]
Rfusar/dashboard
dashboard/interazioneGPT/connGPT.py
connGPT.py
py
678
python
it
code
0
github-code
36
[ { "api_name": "openai.api_key", "line_number": 5, "usage_type": "attribute" }, { "api_name": "openai.ChatCompletion.create", "line_number": 7, "usage_type": "call" }, { "api_name": "openai.ChatCompletion", "line_number": 7, "usage_type": "attribute" } ]
74478447143
import random import pygame from pygame.locals import QUIT from pelota import* from Raqueta import* pygame.mixer.init() VENTANA_HORI = 1200 VENTANA_VERT = 600 FPS = 160 BLANCO = (255, 255, 255) NEGRO = (0, 0, 0) fondo= pygame.image.load("fondo.png") pantalla = pygame.display.set_mode((VENTANA_HORI,VENTANA_VERT)) def main(): pygame.init() pantalla.blit(fondo,(0,0)) sonido_fondo = pygame.mixer.Sound("theme.mp3") pygame.mixer.Sound.play(sonido_fondo, -1) ventana = pygame.display.set_mode((VENTANA_HORI, VENTANA_VERT)) pygame.display.set_caption("Pong ") fuente = pygame.font.Font(None, 60) pelota = PelotaPong("ball.png") raqueta_1 = RaquetaPong() raqueta_1.x = 60 raqueta_2 = RaquetaPong() raqueta_2.x = VENTANA_HORI - 60 - raqueta_2.ancho jugando = True while jugando: pelota.mover() pelota.rebotar() raqueta_1.mover() raqueta_2.mover_ia(pelota) raqueta_1.golpear(pelota) raqueta_2.golpear_ia(pelota) ventana.blit(pygame.image.load("fondo.png"),(0,0)) ventana.blit(pelota.imagen, (pelota.x, pelota.y)) ventana.blit(raqueta_1.imagen, (raqueta_1.x, raqueta_1.y)) ventana.blit(raqueta_2.imagen, (raqueta_2.x, raqueta_2.y)) texto = f"{pelota.puntuacion} : {pelota.puntuacion_ia}" if(pelota.puntuacion>=10): ventana.blit(pygame.image.load("win.png"),(300,100)) if(pelota.puntuacion_ia>=10): ventana.blit(pygame.image.load("lose.png"),(300,100)) letrero = fuente.render(texto, False, BLANCO) ventana.blit(letrero, (VENTANA_HORI / 2 - fuente.size(texto)[0] / 2, 50)) for event in pygame.event.get(): if event.type == QUIT: jugando = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_w: raqueta_1.dir_y = -5 if event.key == pygame.K_s: raqueta_1.dir_y = 5 if event.type == pygame.KEYUP: if event.key == pygame.K_w: raqueta_1.dir_y = 0 if event.key == pygame.K_s: raqueta_1.dir_y = 0 pygame.display.flip() pygame.time.Clock().tick(FPS) pygame.quit() if __name__ == "__main__": main()
luis10dsn/Pong
Pong/main.py
main.py
py
2,513
python
es
code
0
github-code
36
[ { "api_name": "pygame.mixer.init", "line_number": 6, "usage_type": "call" }, { "api_name": "pygame.mixer", "line_number": 6, "usage_type": "attribute" }, { "api_name": "pygame.image.load", "line_number": 17, "usage_type": "call" }, { "api_name": "pygame.image", ...
19643341301
#! /usr/bin/env python # -*- coding: utf-8 -*- # PyArtForms - Python generative art forms paint algorithms (artificial artist) # experimental 'smears' paint algorithms, v1.0 - core algorithm definitions # (c)2017-2021 MoNsTeR/GDC, Noniewicz.com, Noniewicz.art.pl, Jakub Noniewicz # #01 [...] 'cruel red smears', not only red # #02 [tested, ok] circle worms # #03 [tested, ok] crazy trangles --- finish: more par, opt less random? # #04 [tested, ok] self-crossed filled polygons # #05 [...] star flowers --- finish: a lot here # #06 [...] circle ripples - co-centered circle groups --- finish: par + misc # #07 [tested, ok] random rectangles - grayish and colorish rects mess --- finish: new colorer proper # #08 [tested, ok] just rectangles, may flux --- finish: new params, more variants in defs # #09 [tested, ok] 'Warp' effect - triangle rays from center, opt center point shifted rnd # #10 [...] long beziers # #11 [tested, ok] horizontal gradients with suprizes # #12 [tested, ok/so-so] opart-like boxes/circles/triangles # #13 [tested, ok] opart-like single big poly (like #04?) # #14 [tested, ok/so-so] opart-like cicrles xor-cut by triangles # #15 [tested, ok, predictable] opart-like or color circle-interference patterns # #16 [tested, ok, predictable] opart-like circles # #17 [tested, ok] scottish-like grid --- finish: postproc satur 75 up + light 10 up? | 0,0 missing in rnd issue # #18 [tested, ok] slim colorful circles --- finish: more par or var th*, more with self-call # #19 [tested, ok, predictable] opart-like grid # #20 [tested, ok, predictable] opart-like / papercut-like / video feedback-like 'dragon' effect # #21 [tested, ok, predictable] opart-like scaled and pasted frames # #22 [...] pie slice effects --- finish: reduce total count, mimosrod opt? # #23 [tested, ok, predictable] Sierpinski's triangle fractal # #24 [tested, ok, predictable] rotated traingles --- finish: reduce total count, more par ver, mimosrod opt, a scale par # #25 [tested, ok] waves#1 --- finish: more par # #26 [tested, ok] waves#2 --- finish: more par, simplify code # #27 [tested, ok] multishaped polygon mess --- finish: more par # future fun: # #28 [...] # #29 [...] # #30 [...] # #31 # #32 # cre: 20180430 # upd: 20180501, 02, 03 # cre: 20180805, 07, 08 # upd: 20180928, 29 # upd: 20181019, 20 # upd: 20190105, 06, 12, 13, 18, 19, 21, 22 # upd: 20190306, 11, 29, 30 # upd: 20190414, 15, 17, 18, 22, 24, 26, 27 # upd: 20200507, 10 # upd: 20210106, 15, 16, 19, 20, 21, 22 # upd: 20210515, 16, 22, 23, 24, 25, 26, 27 # upd: 20210606, 07, 10, 11, 12, 13, 14, 17, 18, 19, 20 # see: # https://pillow.readthedocs.io/en/stable/ # note: now required at least pillow version 5.3.0, tested on 7.2.0, my prev was 5.0.0 # TODO: # - ? from PIL import Image, ImageDraw, ImageChops, ImageOps #, ImageMorph, ImageMath # test import random, math, string, os, sys, copy from bezier import make_bezier from drawtools import * from color_defs import * """ import PIL print('PIL',PIL.__version__) """ # --- def mazy1(draw, params): """ ? """ w, h, cnt = init_common(params) mar = 0 if 'mar' in params: mar = params['mar'] v = 0 if 'v' in params: v = params['v'] ts = [t/100.0 for t in range(101)] # par? sc = float(h) / 3507 # lame par! wx = int(float(params['penw']) * sc) if wx <= 0: wx = 1 for n in range(cnt): po = [(random.randint(0+mar, w-mar), random.randint(0+mar, h-mar)), (random.randint(0+mar, w-mar), random.randint(0+mar, h-mar)), (random.randint(0+mar, w-mar), random.randint(0+mar, h-mar)), (random.randint(0+mar, w-mar), random.randint(0+mar, h-mar))] if 'color' in params: if params['color'] == 'rg': color = gradient2((255,255,0), (255,0,0), random.randint(0, 255), 255) else: color = new_colorer(params['color'], n, cnt) else: color = (0,0,0) if 'addalpha' in params: color = add_alpha(color, params['addalpha']) r = color[0] g = color[1] b = color[2] if params['prefill'] == True: bezier = make_bezier(po) points = bezier(ts) draw.polygon(points, fill=color, outline=None) for m in range(params['m']): if params['keep'] == True: po0 = po[0] po3 = po[3] vsc = int(v*sc) po[:] = [(xy[0]+random.randint(0, vsc)-random.randint(0, vsc), xy[1]+random.randint(0, vsc)-random.randint(0, vsc)) for xy in po] if params['keep'] == True: po[0] = po0 po[3] = po3 old = False if params['mode'] == 'red': color = (r ^ random.randint(0, 48), 0, 0) old = True if params['mode'] == 'black': rr = random.randint(0, 48) color = (rr, rr, rr) old = True if old == False: color = new_colorer(params['mode'], n, cnt) if 'addblack' in params: # todo: (re)use if params['addblack'] == True and random.randint(0, 100) > 80: color = (0,0,0) if 'addalpha' in params: color = add_alpha(color, params['addalpha']) bezier = make_bezier(po) points = bezier(ts) draw.line(points, fill=color, width=wx) def mazy2(draw, params): """ circle worms """ w, h, cnt = init_common(params) cntm = params['m'] if cntm <= 0: cntm = 1 sc = 50 # dflt if 'sc' in params: sc = params['sc'] if sc > 0: v = int(h/sc) else: v = 0 for n in range(cnt): r1 = random.randint(int(h*0.15), int(h*0.45)) po = [(random.randint(-r1, w+r1), random.randint(-r1, h+r1)), (random.randint(-r1, w+r1), random.randint(-r1, h+r1))] r0 = random.randint(int(r1*0.7), int(r1*0.99)) if r0 < cntm: r0 = cntm de = 1/cntm for m in range(cntm): #v = int((cntm-m)/cntm * h/20) # test4 po[:] = [(xy[0]+random.randint(0, v)-random.randint(0, v), xy[1]+random.randint(0, v)-random.randint(0, v)) for xy in po] color = new_colorer(params['color'], m, cntm) if 'addalpha' in params: if params['addalpha'] > 0: color = add_alpha(color, params['addalpha']) circle(draw, po[0][0], po[0][1], int(r0*(1-m*de)), fill=color, outline=None) def mazy3(draw, params): """ crazy trangles """ w, h, cnt = init_common(params) def r(p, d): return int(p/2+random.randint(int(-p/d), int(p/d))) d = 0.5 # par, 1.3, 2.2 ? # todo: ext par da = 0.06 # dflt, how quickly they get smaller in center mode, 0.5 ok too if 'da' in params: da = params['da'] for n in range(cnt): if params['mode'] == 'center': po = [(r(w, d), r(h, d)), (r(w, d), r(h, d)), (r(w, d), r(h, d))] d = d + da if params['mode'] == 'xcenter': d = 2.2 # par po = [(int(w/2), int(h/2)), (r(w, d), r(h, d)), (r(w, d), r(h, d))] if params['mode'] == 'rnd': d = 2.2 # par po = [(r(w, d), r(h, d)), (r(w, d), r(h, d)), (r(w, d), r(h, d))] color = new_colorer(params['color'], n, cnt) if 'addalpha' in params: if params['addalpha'] > 0: color = add_alpha(color, params['addalpha']) triangle(draw, po, fill=color, outline=None) def mazy4(draw, params): """ self-crossed filled polygons """ w, h, cnt = init_common(params) sc = 2.1 # dflt if 'sc' in params: sc = params['sc'] if sc <= 0: sc = 1 sx = int(w/sc) sy = int(h/sc) p_cnt = 20 # dflt if 'pc' in params: p_cnt = params['pc'] mode = 'center' if 'mode' in params: mode = params['mode'] for n in range(cnt): if mode == 'center': w0 = w/2 h0 = h/2 else: w0 = random.randint(0, w) h0 = random.randint(0, h) po = [] for p in range(p_cnt): po.extend((w0+random.randint(-sx, sx), h0+random.randint(-sy, sy))) color = new_colorer(params['color'], n, cnt) if 'addalpha' in params: color = add_alpha(color, params['addalpha']) draw.polygon(po, fill=color, outline=None) def mazy5(draw, params): """ star flowers """ w, h, cnt = init_common(params) # cnt unused colors = params['colors'] c = math.pi/180 dg = h*0.037 # thickness, par #dg = h*0.01 # TEST interesting... r0 = h/2*0.93 # base radius, par #r0 = h/2*1.5 # TEST rOut = float(h)*0.77 # outer circle radius, par #rOut = float(h)*0.3 # TEST sc = float(h)/2480 # par step = 10 # par (?) n = 10 # count of all 'stars', const, par for i in range(n): a = random.randint(4, 28) # number of 'spikes', par rv = random.randint(20, int(300/a*2)) # 'spike' amplitude, [todo: correlate with a - less if a big] par if i == 0: x0 = w/2 y0 = h/2 else: axy = c*(i-1)*360/8 # par x0 = w/2 + rOut * math.cos(axy) y0 = h/2 + rOut * math.sin(axy) bands = 16 # par r decrease steps, also related to num colors #bands = len(colors)*3 # test for m in range(bands): points = [] for n in range(int(360*step)): angle = c*float(n)/float(step) r = r0 + sc * (rv * math.sin(angle*a)) - m*dg x = x0 + r * math.cos(angle) y = y0 + r * math.sin(angle) points.extend((x, y)) color = colors[m%len(colors)] # TODO: fix: not new not old if 'addalpha' in params: color = add_alpha(color, params['addalpha']) draw.polygon(points, fill=color, outline=params['outline']) def mazy6(draw, params): """ circle ripples - co-centered circle groups """ w, h, cnt = init_common(params) useblack = False if 'useblack' in params: useblack = params['useblack'] n_r_max = 16 # par r_min = int(h/25) # par r_max = int(h/7) # par #r_max = int(h/3) # par #r_max = int(h/15) # par # todo: start w big r_mx then go to lower? == start with big 1st # todo: mix color modes maybe? for m in range(cnt): x = random.randint(int(w/2-w/3), int(w/2+w/3)) y = random.randint(int(h/2-h/3), int(h/2+h/3)) r = random.randint(r_min, r_max) n_r = random.randint(3, n_r_max) for n in range(n_r): nn = n_r - n ro = int(r*(1+nn*nn*0.015)) # par if n & 1 and useblack == True: color = (0, 0, 0) else: color = new_colorer(params['mode'], n, n_r) try: color except NameError: print('ERROR: undefined color mode, using black', params['mode']) color = (0,0,0) #color = add_alpha(color, 100) # todo circle(draw, x, y, ro, fill=color, outline=None) def mazy7(draw, params): """ random rectangles - grayish and colorish rects mess """ w, h, cnt = init_common(params) hdiv = int(h/30) # dflt if 'div' in params: d = int(params['div']) if d <= 0: d = 1 hdiv = int(h/d) for m in range(cnt): x1 = random.randint(int(w/2-w/3), int(w/2+w/3)) y1 = random.randint(int(h/2-h/3), int(h/2+h/3)) w1 = 0 h1 = 0 if params['mode'] == 'dec': # big2small any sc = (m+1)/cnt if sc == 0: sc = 1 wm = int(w/8 * 1/sc) hm = int(w/8 * 1/sc) w1 = random.randint(int(w/35), wm) h1 = random.randint(int(w/35), hm) if params['mode'] == 'decp': # big2small rect prop sc = (m+1)/cnt if sc == 0: sc = 1 wm = int(w/7 * 1/sc) hm = int(h/7 * 1/sc) w1 = random.randint(int(w/35), wm) h1 = random.randint(int(h/35), hm) if params['mode'] == 'const': # const small sqare w1 = hdiv h1 = hdiv color = (0,0,0) # todo: new colorer proper if params['cmode'] == 'std': color = gradient2((255,255,255), (0,0,0), m, cnt) if params['cmode'] == 'inv': # or inverse color = gradient2((0,0,0), (255,255,255), m, cnt) if params['cmode'] == 'rnd': # or rnd ci = random.randint(0, 255) color = (ci,ci,ci) if params['cmode'] == 'color': # color color = colors_happy[random.randint(0, len(colors_happy)-1)] if params['cmode'] == 'wryb': color = colors_fwd[random.randint(0, len(colors_fwd)-1)] if params['cmode'] == 'BeachTowels': color = colors_BeachTowels[random.randint(0, len(colors_BeachTowels)-1)] if params['cmode'] == 'MoonlightBytes6': color = colors_MoonlightBytes6[random.randint(0, len(colors_MoonlightBytes6)-1)] if params['cmode'] == 'RainbowDash': color = colors_RainbowDash[random.randint(0, len(colors_RainbowDash)-1)] if 'addalpha' in params: color = add_alpha(color, params['addalpha']) rect(draw, x1, y1, w1, h1, fill=color, outline=None) def mazy8(draw, params): """ Block grid with random colors """ w, h, cnt = init_common(params) # cnt unused xcnt = params['xcnt'] ycnt = params['ycnt'] # todo: new par use ext alpha_flux_p = 50 alpha_flux_p = None alpha_flux_vmin = 20 alpha_flux_vmax = 90-40 # todo: opt dodatkowe 'cienkie' flux_p = None v = 0 if 'flux_p' in params: flux_p = params['flux_p'] if 'v' in params: v = params['v'] border = 0 if 'border' in params: border = params['border'] ou = None if 'ou' in params: ou = params['ou'] w1 = int(w/xcnt) h1 = int(h/ycnt) max_c = len(get_colors(params['color'])) for y in range(ycnt-border*2): for x in range(xcnt-border*2): x1 = x*w1 + int(w1/2) + border*w1 y1 = y*h1 + int(h1/2) + border*h1 ci = random.randint(0, max_c-1) color = new_colorer(params['color'], ci, -1) if alpha_flux_p != None and alpha_flux_p > 0: # rnd flux if random.randint(0, 100) > alpha_flux_p: ar = random.randint(alpha_flux_vmin, alpha_flux_vmax) color = add_alpha(color, ar) vx = vy = vw = vh = 0 if flux_p != None and flux_p > 0: # rnd flux if random.randint(0, 100) > flux_p: vx = float(w1)*(random.randint(0, v)-random.randint(0, v))/100.0 vy = float(h1)*(random.randint(0, v)-random.randint(0, v))/100.0 vw = float(w1)*(random.randint(0, v)-random.randint(0, v))/100.0 vh = float(h1)*(random.randint(0, v)-random.randint(0, v))/100.0 rect(draw, x1+vx, y1+vy, w1+vw, h1+vh, fill=color, outline=ou) def mazy9(draw, params): """ 'Warp' effect - triangle rays from center, opt center point shifted rnd """ w, h, cnt = init_common(params) w2 = int(w/2) h2 = int(h/2) c = math.pi/180 v = 0 if 'v' in params: v = params['v'] rndc = False if 'rndc' in params: rndc = params['rndc'] po = [(w2, h2), (0, 0), (0, 0)] da = c * float(360)/cnt r = w for n in range(cnt): if v > 0: po[0] = (w2+random.randint(int(-v), int(v)), h2+random.randint(int(-v), int(v))) x = w2 + r * math.cos(da*n) y = h2 + r * math.sin(da*n) po[1] = (x, y) x = w2 + r * math.cos(da*(n+1)) y = h2 + r * math.sin(da*(n+1)) po[2] = (x, y) if params['color'] == 'red' or params['color'] == 'bw': # todo: more? + both modes as one? ci = random.randint(0, 255) color = new_colorer(params['color'], ci, 255) else: cx = get_colors(params['color']) if cx == None: raise Exception('Undefined color: '+params['color']) # todo: err only, no raise/crash cx_len = len(cx) if rndc == True: color = cx[random.randint(0, cx_len-1)] else: color = cx[n%cx_len] triangle(draw, po, fill=color, outline=None) def mazy10(draw, params): """ Random bezier threads or aeas """ w, h, cnt = init_common(params) mode = params['mode'] # todo: fix make threads no-lame # todo: for closed make internal pts bigger while 1st+last with margin? # todo: 1-2 bezier stripes then rnd mutate? #np = 1800 #par np = 5000 #par ts = [t/float(np) for t in range(np+1)] sc = float(h) / 3507 # todo: not like that? wx = int(float(params['penw']) * sc) if wx <= 0: wx = 1 def rwh(): ex = 1 if params['open'] == True: return (random.randint(-w*ex, w*(ex+1)), random.randint(-h*ex, h*(ex+1))) else: return (random.randint(0, w), random.randint(0, h)) for n in range(cnt): po = [rwh()] for x in range(params['complexity']): po.extend([rwh()]) if params['color'] == 'blue_const': color = (16,48,255) if params['color'] == 'happy': color = colors_happy[n%len(colors_happy)] if params['color'] == 'rg': color = gradient2((255,255,0), (255,0,0), random.randint(0, 255), 255) if params['color'] == 'red': color = gradient2((0,0,0), (255,0,0), random.randint(0, 255), 255) if params['color'] == 'wryb': color = colors_fwd[n%len(colors_fwd)] # todo: new colorer proper if 'addalpha' in params: color = add_alpha(color, params['addalpha']) bezier = make_bezier(po) points = bezier(ts) if params['mode'] == 'line': draw.line(points, fill=color, width=wx) if params['mode'] == 'fill': draw.polygon(points, fill=color, outline=None) def mazy11(draw, params): """ Horizontal gradients with suprizes """ w, h, cnt = init_common(params) cx = get_colors(params['color']) csize = len(cx) dy = float(h)/cnt if dy*cnt < h: # lame fix for small images cnt += 3 steps = 256 # const, max rational limit for RGB24 gradient if steps > w: steps = w dx = float(w)/steps for n in range(cnt): n1 = random.randint(0, csize-1) n2 = n%csize n3 = random.randint(0, csize-1) color1 = cx[n1] color2 = cx[n2] color3 = cx[n3] for step in range(steps): color = gradient(color1, color2, color3, step, steps) x = step*dx y = n*dy xy = [(x, y), (x+dx, y+dy)] draw.rectangle(xy, fill=color, outline=None) def mazy12(draw, params): """ Opart-like boxes/circles/triangles """ w, h, cnt = init_common(params) c = math.pi/180 o = params['o'] v = False if 'v' in params: v = params['v'] rc = 1.0 if 'rc' in params: rc = params['rc'] w0 = w/2 h0 = h/2 r = int(h/2/2 * rc) for i in range(cnt): a = c*i/cnt*360 x = int(w0+r*math.cos(a)) y = int(h0+r*math.sin(a)) if v: va = random.randint(int(-h0/8), int(h0/8)) # par vx = random.randint(int(-w0/8), int(w0/8)) # par vy = random.randint(int(-h0/8), int(h0/8)) # par else: va = 0 vx = 0 vy = 0 if i&1 == 0: co = (0,0,0) ou = (255,255,255) else: co = (255,255,255) ou = (0,0,0) if o == 'box': rect(draw, x+vx, y+vy, r+va, r+va, fill=co, outline=ou) if o == 'cir': circle(draw, x+vx, y+vy, r+va, fill=co, outline=ou) if o == 'tri': vx1 = random.randint(int(-w0/2), int(w0/2)) # par vx2 = random.randint(int(-w0/2), int(w0/2)) # par vx3 = random.randint(int(-w0/2), int(w0/2)) # par vy1 = random.randint(int(-h0/2), int(h0/2)) # par vy2 = random.randint(int(-h0/2), int(h0/2)) # par vy3 = random.randint(int(-h0/2), int(h0/2)) # par points = [(x+vx1, y+vy1), (x+vx2, y+vy2), (x+vx3, y+vy3)] triangle(draw, points, fill=co, outline=ou) def mazy13(draw, params): """ Opart-like single big poly """ w, h, cnt = init_common(params) w0 = w/2 h0 = h/2 sc = 1.0 sx = int(w/sc) sy = int(h/sc) po = [] for n in range(cnt): newp = (w0+random.randint(-sx, sx), h0+random.randint(-sy, sy)) po.append(newp) color = params['color'] draw.polygon(po, fill=color, outline=None) def mazy14(draw, params): """ Opart-like cicrles xor-cut by triangles """ w, h, cnt = init_common(params) c = math.pi/180 if w > h: sc = w/2*1.5/cnt else: sc = h/2*1.5/cnt if 'm' in params: cnt2 = params['m'] if cnt2 < 4: cnt2 = 4 else: cnt2 = 4 # some min v = 0 if 'div' in params: v = params['div'] if v > 0: v = w/v im1 = Image.new('RGB', (params['w'], params['h']), params['Background']) im2 = Image.new('RGB', (params['w'], params['h']), params['color']) # note: 2nd image is reversed draw1 = ImageDraw.Draw(im1) draw2 = ImageDraw.Draw(im2) for n in range(cnt): # centered circles 1st r = int(sc*(cnt-n)) if n&1 == 0: co = params['Background'] else: co = params['color'] circle(draw1, int(w/2), int(h/2), r, fill=co, outline=None) po = [(int(w/2), int(h/2)), (0, 0), (0, 0)] da = float(360)/cnt2 r = w for n in range(cnt2): if v > 0: v1 = random.randint(int(-v), int(v)) v2 = random.randint(int(-v), int(v)) po[0] = (int(w/2)+v1, int(h/2)+v2) x = w/2 + r * math.cos(c*da*n) y = h/2 + r * math.sin(c*da*n) po[1] = (x, y) x = w/2 + r * math.cos(c*da*(n+1)) y = h/2 + r * math.sin(c*da*(n+1)) po[2] = (x, y) if n&1 == 0: color = params['Background'] else: color = params['color'] triangle(draw2, po, fill=color, outline=None) imout = ImageChops.difference(im1, im2) params['im'].paste(imout, (0, 0)) draw1 = None draw2 = None im1 = None im2 = None imout = None def mazy15(draw, params): """ opart-like or color circle-interference patterns, predictable (no rnd parts) """ w, h, cnt = init_common(params) c = math.pi/180 scc = 1.5 # par if w > h: sc = w/2*scc/cnt # note: off-screen to fill all else: sc = h/2*scc/cnt ys1 = 0 xs1 = 0 if 'xs1' in params: xs1 = params['xs1'] if 'ys1' in params: ys1 = params['ys1'] ys2 = 0 xs2 = 0 if 'xs2' in params: xs2 = params['xs2'] if 'ys2' in params: ys2 = params['ys2'] colorer = None if 'colorer' in params: colorer = params['colorer'] def draw_it(draw, xs, ys, r): if n&1 == 0: if colorer == None: co = params['Background'] else: co = new_colorer(colorer, n, cnt) else: if colorer == None: co = params['color'] else: co = new_colorer(colorer, n, cnt) circle(draw, int(w/2+xs), int(h/2+ys), r, fill=co, outline=None) im1 = Image.new('RGB', (params['w'], params['h']), params['Background']) im2 = Image.new('RGB', (params['w'], params['h']), params['color']) # note: 2nd image is reversed in 'polarity' for better difference effect draw1 = ImageDraw.Draw(im1) draw2 = ImageDraw.Draw(im2) for n in range(cnt): # circles #1 r = int(sc*(cnt-n)) if 'mode' in params: if params['mode'] == 'linear': if 'xs1v' in params: xs1 = xs1 + params['xs1v'] if 'ys1v' in params: ys1 = ys1 + params['ys1v'] if params['mode'] == 'circle': a0 = c*n/cnt*360 if 'xs1v' in params: xs1 = params['xs1v']*math.cos(a0) if 'ys1v' in params: ys1 = params['ys1v']*math.sin(a0) draw_it(draw1, xs1, ys1, r) for n in range(cnt): # circles #2 r = int(sc*(cnt-n)) if 'mode' in params: if params['mode'] == 'linear': if 'xs2v' in params: xs2 = xs2 + params['xs2v'] if 'ys2v' in params: ys2 = ys2 + params['ys2v'] if params['mode'] == 'circle': a0 = c*n/cnt*360 if 'xs2v' in params: xs2 = params['xs2v']*math.cos(a0) if 'ys2v' in params: ys2 = params['ys2v']*math.sin(a0) draw_it(draw2, xs2, ys2, r) if colorer == None: imout = ImageChops.difference(im1, im2) # only difference is cool for bw else: imout = ImageChops.blend(im1, im2, 0.5) # only blend for color now params['im'].paste(imout, (0, 0)) im1 = None im2 = None imout = None def mazy16(draw, params): """ Opart-like circles, predictable (no rnd parts) """ w, h, cnt = init_common(params) c = math.pi/180 if w > h: sc = w/2 else: sc = h/2 rcoef = params['rcoef'] acoef = params['acoef'] rscale = params['rscale'] for n in range(cnt): r = int(sc * (cnt-n)/cnt*rcoef) if n&1 == 0: co = params['Background'] ou = params['color'] else: co = params['color'] ou = params['Background'] #ou = None a0 = c*n/cnt*360 * acoef xs2 = rscale*sc/2*math.cos(a0) ys2 = rscale*sc/2*math.sin(a0) circle(draw, int(w/2+xs2), int(h/2+ys2), r, fill=co, outline=ou) def mazy17(draw, params): """ Scottish-like grid """ w, h, cnt = init_common(params) vv = params['v'] v = int(w*vv) for z in range(cnt): ndx = random.randint(0, cnt) color = new_colorer(params['color'], ndx, cnt) if 'addalpha' in params: if params['addalpha'] > 0: color = add_alpha(color, params['addalpha']) x = random.randint(0, w) y = random.randint(0, h) lw = random.randint(1, v) xy = [(0, y), (w, y+lw)] draw.rectangle(xy, fill=color, outline=None) xy = [(x, 0), (x+lw, h)] draw.rectangle(xy, fill=color, outline=None) def mazy18(draw, params): """ Random circle bundles """ w, h, cnt = init_common(params) if 'multi' in params: multi = params['multi'] for p in multi: p['w'] = params['w'] p['h'] = params['h'] p['call'] = params['call'] p['color'] = params['color'] p['name'] = params['name'] mazy18(draw, p) return v = params['v'] r0v = w if 'r0v' in params: r0v = params['r0v'] for n in range(cnt): x = random.randint(0, w) y = random.randint(0, h) r0 = random.randint(0, r0v) for m in range(params['m']): r = r0 + random.randint(-v, v) color = new_colorer(params['color'], n, cnt) # note: alpha for outline does not seem to work thn = 3 # par thd = 0.2 # par thw = 2 # par for th in range(thn): circle_w(draw, x, y, r+th*thd, fill=None, outline=color, width=thw) # note width, v 5.3.0+ # was # for th in range(5): # circle(draw, x, y, r+th*0.15, fill=None, outline=color) def mazy19(draw, params): """ Chequered opart grids with x variations, predictable (no rnd parts) """ w, h, cnt = init_common(params) c = math.pi/180 nx = cnt ny = params['m'] dx = int(2*w/nx) dy = int(2*h/ny) c_white = (255,255,255) c_black = (0,0,0) if 'c_white' in params: c_white = params['c_white'] if 'c_black' in params: c_black = params['c_black'] if params['mode'] == 'exp': fncx = [] coef = 17 # par / const 17 good for 40 for x in range(coef): # precalc fx = 2.0*math.exp(-x/4) fncx.append(fx) if params['mode'] == 'sin': fncx2 = [] coef2 = nx # ? for x in range(coef2): # precalc fx = abs(1.1*math.sin(x/coef2*360*2*c)) #par x2 fncx2.append(fx) dxmap = [] f = 0 x = 0 while f < w+dx: # fill whole width fx = 0 if x > 0: if params['mode'] == 'grid': fx = dx if params['mode'] == 'lin': fx = dx*f/(w+dx)*1.01 if params['mode'] == 'exp': if x < coef: fx = dx * fncx[x] else: if x < 2*coef: ndx = coef-(x-coef)-1 fx = dx * fncx[ndx] else: fx = dx if params['mode'] == 'sin': if x < coef2: fx = dx * fncx2[x] else: fx = dx if fx < 1: fx = 1 f = f + fx dxmap.append(f) x += 1 for y in range(ny): for x in range(len(dxmap)-1): b = ((x&1) == 1 and (y&1) == 1) or ((x&1) == 0 and (y&1) == 0) if b == True: cx = c_white else: cx = c_black xp = dxmap[x] xy = [(xp, y*dy), (xp+(dxmap[x+1]-dxmap[x]), y*dy+dy)] draw.rectangle(xy, fill=cx, outline=None) def mazy20(draw, params): """ opart-like / papercut-like / video feedback-like 'dragon' effect, predictable (no rnd parts) """ w, h, cnt = init_common(params) da = params['da'] dd = 10 # dflt if 'dd' in params: dd = params['dd'] if dd < 1: dd = 1 dx = int(w/dd) dy = int(h/dd) sc = 0.75 # dflt if 'sc' in params: sc = params['sc'] nw = int(sc*w) nh = int(sc*h) xy = [(dx, dy), (w-dx, h-dy)] draw.rectangle(xy, fill=params['Foreground'], outline=None) xy = [(dx*2, dy*2), (w-dx*2, h-dy*2)] draw.rectangle(xy, fill=params['Background'], outline=None) for n in range(cnt): im1 = params['im'] im1 = im1.resize((nw, nh), Image.BICUBIC) im1 = im1.rotate(da, Image.BICUBIC) params['im'].paste(im1, (int((w-nw)/2), int((h-nh)/2))) im1 = None if 'invert' in params: if params['invert'] == True: params['im'] = invert_image(params['im']) def mazy21(draw, params): """ opart-like scaled and pasted frames, predictable (no rnd parts) """ w, h, cnt = init_common(params) dx = int(w/10) dy = int(h/10) sc = 0.666 nw = int(sc*w) nh = int(sc*h) mode = 0 if 'mode' in params: mode = params['mode'] xy = [(dx, dy), (w-dx, h-dy)] draw.rectangle(xy, fill=params['Foreground'], outline=None) xy = [(dx*2, dy*2), (w-dx*2, h-dy*2)] draw.rectangle(xy, fill=params['Background'], outline=None) for n in range(cnt): im1 = params['im'].resize((nw, nh), Image.BICUBIC) xx = int(nw/2) yy = int(nh/2) if mode == 0: params['im'].paste(im1, (0+int(nw/2/2), 0+int(nh/2/2))) #center if mode == 1: params['im'].paste(im1, (0, 0)) #l/u if mode == 2: params['im'].paste(im1, (xx, yy)) #r/d if mode == 3 or mode == 4: # l/u + r/d - extravagant if n&1 == 0: params['im'].paste(im1, (0, 0)) #l/u else: params['im'].paste(im1, (xx, yy)) #r/d if mode == 4 or mode == 5: params['im'].paste(im1, (0+int(nw/3), 0+int(nh/3))) # lame if mode == 6: # maxxx fract like nn = n&3 if nn == 0: params['im'].paste(im1, (0, 0)) if nn == 1: params['im'].paste(im1, (xx, 0)) if nn == 2: params['im'].paste(im1, (0, yy)) if nn == 3: params['im'].paste(im1, (xx, yy)) im1 = None if 'invert' in params: if params['invert'] == True: params['im'] = invert_image(params['im']) def mazy22(draw, params): """ pie slice effects """ w, h, cnt = init_common(params) colorer = params['color'] do_rnd = False if 'rnd' in params: do_rnd = params['rnd'] drc = 0.97 if 'drc' in params: drc = params['drc'] a_s = 0 a_e = 35 if 'a_e' in params: a_e = params['a_e'] da = 12 if 'da' in params: da = params['da'] #note: some nice: drc a_e da #0.97, 90, 12 #0.97, 35, 12 #0.97, 10, 12 #0.97, 90, 45 # good for colorsets #0.97, 90 90 # special #0.97, 90 89 # special + good for colorsets #0.97, 90 85 # special + good for colorsets #0.97, 90 80 # special + good for colorsets #0.9, 90, 45 radius = h/2 * 1.0 # par for i in range(cnt): if do_rnd: a_s = random.randint(0, 360) # par x2 a_e = random.randint(0, 360) # par x2 drc = random.randint(92, 98)/100 # par x2 if i == cnt-1: a_s = 0 a_e = 360 if params['Background'] == (255,255,255) and do_rnd and params['color'] == 'bw': # rev bw color in this special case color = new_colorer(colorer, cnt-1-i, cnt) else: color = new_colorer(colorer, i, cnt) draw.pieslice((w/2-radius, h/2-radius, w/2+radius, h/2+radius), a_s, a_e, fill=color) radius = radius * drc if not do_rnd: a_s = a_s + da a_e = a_e + da def mazy23(draw, params): """ Sierpinski's triangle fractal, predictable (no rnd parts) """ # https://en.wikipedia.org/wiki/Sierpi%C5%84ski_triangle w, h, cnt = init_common(params) limit0 = cnt margin = 5/100 if 'margin' in params: margin = params['margin'] dd = h*margin color = (255, 255, 255) if 'color1' in params: color = params['color1'] color2 = (0, 0, 0) if 'color2' in params: color2 = params['color2'] colorer = None if 'colorer' in params: colorer = params['colorer'] colorer_mode = None if 'colorer_mode' in params: colorer_mode = params['colorer_mode'] def m23(draw, limit, a, htr, ofsx, ofsy): if limit <= 0: return a /= 2 htr = 0.5 * math.sqrt(3) * a c2 = color2 if colorer != None and colorer_mode == 0: c2 = new_colorer(colorer, limit, limit0) # mode=0 xx1 = wo+a/4 +(0.5) # note: 0.5 'visual' fix xx2 = wo+a/2 xx3 = wo+a-a/4 -(0.5) yy1 = h-dd-htr/2 +(0.5) yy2 = h-dd -(0.5) fix_x = ofsx fix_y = ofsy po = [(int(xx1+fix_x), int(yy1+fix_y)), (int(xx2+fix_x), int(yy2+fix_y)), (int(xx3+fix_x), int(yy1+fix_y))] if colorer != None and colorer_mode == 1: c2 = new_colorer(colorer, limit+0, limit0) # mode=1 triangle(draw, po, fill=c2, outline=None) m23(draw, limit-1, a, htr, fix_x, fix_y) fix_x = a + ofsx fix_y = ofsy po = [(int(xx1+fix_x), int(yy1+fix_y)), (int(xx2+fix_x), int(yy2+fix_y)), (int(xx3+fix_x), int(yy1+fix_y))] if colorer != None and colorer_mode == 1: c2 = new_colorer(colorer, limit+1, limit0) # mode=1 triangle(draw, po, fill=c2, outline=None) m23(draw, limit-1, a, htr, fix_x, fix_y) fix_x = a/2 + ofsx fix_y = -htr + ofsy po = [(int(xx1+fix_x), int(yy1+fix_y)), (int(xx2+fix_x), int(yy2+fix_y)), (int(xx3+fix_x), int(yy1+fix_y))] if colorer != None and colorer_mode == 1: c2 = new_colorer(colorer, limit+2, limit0) # mode=1 triangle(draw, po, fill=c2, outline=None) m23(draw, limit-1, a, htr, fix_x, fix_y) a = h-dd-dd # start side len, todo: try par >> w? wo = (w-a)/2 htr = 0.5 * math.sqrt(3) * a # start triangle h po = [(wo, h-dd), (wo+a/2, h-dd-htr), (wo+a, h-dd)] triangle(draw, po, fill=color, outline=None) # main po = [(wo+a/4, h-dd-htr/2), (wo+a/2, h-dd), (wo+a-a/4, h-dd-htr/2)] triangle(draw, po, fill=color2, outline=None) # 1st cut m23(draw, limit0-1, a, htr, 0, 0) # recurent inside def mazy24(draw, params): """ rotated traingles, predictable (no rnd parts) """ w, h, cnt = init_common(params) cx = w/2 cy = h/2 + h/12 # 'y center' slightly moved down, nicer this way c = math.pi/180 colorer = params['colorer'] ou = None if 'ou' in params: ou = params['ou'] a_sc = 0.93 # par a_base = 1.0 if 'a_base' in params: a_base = params['a_base'] an_sc = 1.0 if 'an_sc' in params: an_sc = params['an_sc'] a = h*a_base for i in range(cnt): htr = 0.5 * math.sqrt(3) * a po = [(cx-a/2, cy-htr/2), (cx, cy+htr/2), (cx+a/2, cy-htr/2)] ce = (1/3*(po[0][0]+po[1][0]+po[2][0]), 1/3*(po[0][1]+po[1][1]+po[2][1])) # actual triangle center is here (triangle centroid) an = i/cnt * 360 * c * an_sc po_ = [rotate_point(po[0], ce[0], ce[1], an), rotate_point(po[1], ce[0], ce[1], an), rotate_point(po[2], ce[0], ce[1], an)] color = new_colorer(colorer, i, cnt) if 'addalpha' in params: color = add_alpha(color, params['addalpha']) triangle(draw, po_, fill=color, outline=ou) a = a * a_sc def mazy25(draw, params): """ waves#1 """ # todo: par + more like it? w, h, cnt = init_common(params) c = math.pi/180 fd = 100.0*params['f0'] div = float(cnt*2+4+(-4)) # par if div == 0: div = 1 if params['horizontal'] == True: rn = w dx = h/div else: rn = h dx = w/div mofs0 = 0 # par, was 2 rnd_color = True # par rnd_color = False for z in range(cnt): if rnd_color: ndx = random.randint(0, cnt) else: ndx = z color = new_colorer(params['color'], ndx, cnt) if 'addalpha' in params: color = add_alpha(color, params['addalpha']) aofs1 = random.randint(0, 360) aofs2 = random.randint(0, 360) aofs3 = random.randint(0, 360) aofs4 = random.randint(0, 360) fofs1 = random.randint(0, 100)/fd*1 fofs2 = random.randint(0, 100)/fd*1 fofs3 = random.randint(0, 100)/fd*2 fofs4 = random.randint(0, 100)/fd*2 mofs1 = (z+mofs0)*dx y = 0 for n in range(rn): nsc = float(n)/float(rn)*360*10 # par 10 x_in = mofs1 + dx * (1 + (math.sin(c*(nsc*fofs1+aofs1))+2*math.sin(c*(nsc*fofs3+aofs3)))/3) x_out = mofs1 + dx * (1 + (math.sin(c*(nsc*fofs2+aofs2))+2*math.sin(c*(nsc*fofs4+aofs4)))/3) if params['horizontal'] == True: xy = [(y, x_in), (y, h - x_out)] else: xy = [(x_in, y), (w - x_out, y)] draw.rectangle(xy, fill=color, outline=None) # 1px rects? y += 1 def mazy26(draw, params): """ waves#2 """ if 'par1' in params and 'par2' in params: mazy26(draw, params['par1']) mazy26(draw, params['par2']) return w, h, cnt = init_common(params) # todo: uproscic kod (czemu 2x?) | exp par w = params['w'] h = params['h'] cnt = params['n'] random.seed() c = math.pi/180 sc = 3.0 #par was 4 if params['horizontal'] == True: rn = w dx = h/float(cnt)*sc else: rn = h dx = w/float(cnt)*sc for z in range(cnt): ndx = random.randint(0, cnt) color = new_colorer(params['color'], ndx, cnt) if 'addalpha' in params: color = add_alpha(color, params['addalpha']) aofs1 = random.randint(0, 360) aofs2 = random.randint(0, 360) aofs3 = random.randint(0, 360) aofs4 = random.randint(0, 360) fofs1 = random.randint(0, 100)/100.0*1 # par fofs2 = random.randint(0, 100)/100.0*1 # par fofs3 = random.randint(0, 100)/100.0*2 # par fofs4 = random.randint(0, 100)/100.0*2 # par mofs1 = float(z*dx) am1 = 1.0 # par am2 = 1.0 # par am3 = 3.0 # par was 2 am4 = 3.0 # par was 2 y = 0 points1 = [] points2 = [] points1a = [] points2a = [] for n in range(rn): nsc = float(n)/float(rn)*360*10 # par 10 x_in = int(mofs1 + dx * (1 + (am1*math.sin(c*(nsc*fofs1+aofs1))+am3*math.sin(c*(nsc*fofs3+aofs3))))) x_out = int(mofs1 + dx * (1 + (am2*math.sin(c*(nsc*fofs2+aofs2))+am4*math.sin(c*(nsc*fofs4+aofs4))))) if params['horizontal'] == True: points1.extend((y, x_in)) points2.extend((y, x_out)) else: points1.extend((x_in, y)) points2.extend((x_out, y)) y += 1 lw = random.randint(1, int(w/30)) #par, opt big->small? points1a[:] = [xy for xy in points1] points2a[:] = [xy for xy in points2] for a in range(int(len(points1a)/2)): ndx = int(len(points1a)/2)-1-a if params['horizontal'] == True: points1.extend((points1a[ndx*2], lw+points1a[ndx*2+1])) else: points1.extend((lw+points1a[ndx*2], points1a[ndx*2+1])) for a in range(int(len(points2a)/2)): ndx = int(len(points2a)/2)-1-a if params['horizontal'] == True: points2.extend((points2a[ndx*2], lw+points2a[ndx*2+1])) else: points2.extend((lw+points2a[ndx*2], points2a[ndx*2+1])) draw.polygon(points1, fill=color, outline=color) draw.polygon(points2, fill=color, outline=color) def mazy27(draw, params): """ multishaped polygon mess """ w, h, cnt = init_common(params) colorer = params['colorer'] addalpha = 0 if 'addalpha' in params: addalpha = params['addalpha'] saturation_factor = 1.5 # dflt if 'saturation' in params: saturation_factor = params['saturation'] minsides = 3 maxsides = 8 if 'minsides' in params: minsides = params['minsides'] if 'maxsides' in params: maxsides = params['maxsides'] if minsides < 3: minsides = 3 if maxsides < 3: maxsides = 3 maxangle = 90 if 'maxangle' in params: maxangle = params['maxangle'] rmin = int(h/30) if 'rmin' in params: rmin = params['rmin'] rmax = h/4 # h h/2 # h/4 if 'rmax' in params: rmax = params['rmax'] rsc = 0.997 # 0 if 'rsc' in params: rsc = params['rsc'] ofs = int(h/4) # centers this much off-screen for n in range(cnt): color = new_colorer(colorer, n, cnt) if addalpha > 0: color = add_alpha(color, addalpha) r = random.randint(rmin, int(rmax)) cx = random.randint(-ofs, w+ofs) cy = random.randint(-ofs, h+ofs) if maxangle > 0: a = random.randint(0, maxangle) else: a = 0 sides = random.randint(minsides, maxsides) nsided(draw, sides, cx, cy, r, a, color, None) if rsc > 0: rmax = rmax * rsc if rmax < rmin: rmax = rmin if addalpha > 0 and saturation_factor > 0: params['im'] = enhace(params['im'], saturation_factor) # future fun def mazy28(draw, params): """ ? """ # fin or remove w, h, cnt = init_common(params) c = math.pi/180 cnt = 400 sx = int(w/cnt) color = (0xd4,0x8a,0x3e) aofs1 = 0 fofs1 = 3 fofs3 = 1 am1 = 3 am3 = 1 dx = sx/3 po = [(w,0), (0, 0)] x = 0 y = h for n in range(cnt): aofs2 = random.randint(0, 90) aofs3 = random.randint(0, 180) fofs2 = random.randint(1, 5) am2 = random.randint(1, 15) nsc = float(n)/float(cnt)*360*3 # par f = int(dx * (2 + (am1*math.sin(c*(nsc*fofs1+aofs1))+am2*math.sin(c*(nsc*fofs2+aofs2))+am3*math.sin(c*(nsc*fofs3+aofs3))))) po.extend((x, y)) y -= f x += sx draw.polygon(po, fill=color, outline=None) def mazy29(draw, params): """ ? """ # note: hard one, probably will fail w, h, cnt = init_common(params) c = math.pi/180 color = (255,255,255) hb = int(h/10) y0 = (hb/2) cnt = 300 dx = int(w/cnt) bcnt = 5 def f1(p): x = p[0] y = p[1] + hb*2 return (x, y) po = [] # build one model block po.append((0,y0)) for n in range(cnt): pn = (dx*n, y0) po.append(pn) po.append((w, y0)) po.append((w, y0+hb)) for n in range(cnt): po.append((w-dx*n, y0+hb)) po.append((0, y0+hb)) poall = [None] * bcnt # copy block bcnt times for n in range(bcnt): if n == 0: poall[n] = copy.deepcopy(po) else: po[:] = (f1(p) for p in po) poall[n] = copy.deepcopy(po) s1 = 1 s2 = 1 + cnt + 2 # test sin wave - remove later? for n in range(bcnt): for x in range(cnt): #fn = 30*math.sin(c*x/cnt*360*4 fn = 0 for f in range(10): fn += (20+f*2)*math.sin(c*x/cnt*360*(1+f*2)) tup = poall[n][s1+x] tup = (tup[0], tup[1]+fn) # change y-s poall[n][s1+x] = tup tup = poall[n][s2+cnt-x] tup = (tup[0], tup[1]+fn) # change y-s poall[n][s2+cnt-x] = tup """ def dist(p, sm): start = sm['start'] ds = math.sqrt((start[0]-p[0])*(start[0]-p[0])+(start[1]-p[1])*(start[1]-p[1])) is_affecting = ds < sm['radius'] inte = sm['intensity']*math.exp(-ds*0.05)*1000 intex = inte*math.cos(c*sm['angle']) intey = inte*math.sin(c*sm['angle']) return ds, inte, intex, intey, is_affecting def apply_smear(sm): for m in range(cnt): for n in range(bcnt): tup = poall[n][s1+m] ds, inte, intex, intey, is_affecting = dist(tup, sm) if is_affecting: tup = (tup[0]+intex, tup[1]+intey) # change poall[n][s1+m] = tup tup = poall[n][s2+cnt-m] ds, inte, intex, intey, is_affecting = dist(tup, sm) if is_affecting: tup = (tup[0]+intex, tup[1]+intey) # change poall[n][s2+cnt-m] = tup # todo: smear with intensity ~ 1/range and params: angle + radius + strength + len sme1 = {'start': (w/2, h/2), 'angle': 45, 'radius': 400, 'intensity': 100, 'length': 300} apply_smear(sme1) sme2 = {'start': (w/4, h/4), 'angle': 15, 'radius': 400, 'intensity': 100, 'length': 300} apply_smear(sme2) """ for n in range(bcnt): #po = poall[n] po = poall[bcnt-1-n] # rev order for test color = (255,255, int(255*n/bcnt)) draw.polygon(po, fill=color, outline=None) #circle(draw, sme1['start'][0], sme1['start'][1], sme1['radius'], fill=None, outline=(0,0,255)) #circle(draw, sme2['start'][0], sme2['start'][1], sme2['radius'], fill=None, outline=(0,0,255)) def mazy30(draw, params): """ ? """ w, h, cnt = init_common(params) w2 = int(w/2) h2 = int(h/2) cnt = 100*2 # par r0 = h*0.3 # par v = 200+100 # par sc = 1.0 # par rv = 200 # par asc = 10 # par 6 50 po = [] for n in range(cnt): a = math.pi/180 * 360 * float(n/cnt) # par rv = random.randint(100,500) # test r = r0 + sc * (rv * math.sin(asc*a)) #r = r0 po.append((int(w2+r*math.cos(a)), int(h2+r*math.sin(a)))) def fr0(p): # par x2 if random.randint(0, 100) > 80: return (p[0]+random.randint(-v,v), p[1]+random.randint(-v,v)) #return (p[0]+random.randint(-v,v), p[1]) else: return p def fr(p): return p #return (p[0]+random.randint(-v,v), p[1]+random.randint(-v,v)) po[:] = (fr(xy) for xy in po) draw.polygon(po, fill=(255, 255, 0), outline=None) # par po.append((po[0][0], po[0][1])) draw.line(po, fill=(255,0,0), width=3) # par # opt if False: ts = [t/2000.0 for t in range(2001)] #ts = [t/20.0 for t in range(21)] bezier = make_bezier(po) points = bezier(ts) draw.polygon(points, fill=(255, 0, 0), outline=(255,255,255)) def mazy31(draw, params): """ ? """ w, h, cnt = init_common(params) # ... return 0 def mazy32(draw, params): """ ? """ w, h, cnt = init_common(params) # ... return 0
monstergdc/pyartforms
playgroud/smears.py
smears.py
py
49,566
python
en
code
4
github-code
36
[ { "api_name": "random.randint", "line_number": 94, "usage_type": "call" }, { "api_name": "random.randint", "line_number": 95, "usage_type": "call" }, { "api_name": "random.randint", "line_number": 96, "usage_type": "call" }, { "api_name": "random.randint", "li...
74713864745
from UM.Application import Application from UM.Logger import Logger from cura.CuraApplication import CuraApplication from cura.PrinterOutputDevice import PrinterOutputDevice, ConnectionState from PyQt5.QtNetwork import QHttpMultiPart, QHttpPart, QNetworkRequest, QNetworkAccessManager, QNetworkReply from PyQt5.QtCore import pyqtProperty, pyqtSignal, pyqtSlot, pyqtSignal, QUrl, QCoreApplication from time import time from typing import Callable, Any, Optional, Dict, Tuple from enum import IntEnum from typing import List import os # To get the username import gzip class AuthState(IntEnum): NotAuthenticated = 1 AuthenticationRequested = 2 Authenticated = 3 AuthenticationDenied = 4 AuthenticationReceived = 5 class NetworkedPrinterOutputDevice(PrinterOutputDevice): authenticationStateChanged = pyqtSignal() def __init__(self, device_id, address: str, properties, parent = None) -> None: super().__init__(device_id = device_id, parent = parent) self._manager = None # type: QNetworkAccessManager self._last_manager_create_time = None # type: float self._recreate_network_manager_time = 30 self._timeout_time = 10 # After how many seconds of no response should a timeout occur? self._last_response_time = None # type: float self._last_request_time = None # type: float self._api_prefix = "" self._address = address self._properties = properties self._user_agent = "%s/%s " % (Application.getInstance().getApplicationName(), Application.getInstance().getVersion()) self._onFinishedCallbacks = {} # type: Dict[str, Callable[[QNetworkReply], None]] self._authentication_state = AuthState.NotAuthenticated # QHttpMultiPart objects need to be kept alive and not garbage collected during the # HTTP which uses them. We hold references to these QHttpMultiPart objects here. self._kept_alive_multiparts = {} # type: Dict[QNetworkReply, QHttpMultiPart] self._sending_gcode = False self._compressing_gcode = False self._gcode = [] # type: List[str] self._connection_state_before_timeout = None # type: Optional[ConnectionState] printer_type = self._properties.get(b"machine", b"").decode("utf-8") printer_type_identifiers = { "9066": "ultimaker3", "9511": "ultimaker3_extended" } self._printer_type = "Unknown" for key, value in printer_type_identifiers.items(): if printer_type.startswith(key): self._printer_type = value break def requestWrite(self, nodes, file_name=None, filter_by_machine=False, file_handler=None, **kwargs) -> None: raise NotImplementedError("requestWrite needs to be implemented") def setAuthenticationState(self, authentication_state) -> None: if self._authentication_state != authentication_state: self._authentication_state = authentication_state self.authenticationStateChanged.emit() @pyqtProperty(int, notify=authenticationStateChanged) def authenticationState(self) -> int: return self._authentication_state def _compressDataAndNotifyQt(self, data_to_append: str) -> bytes: compressed_data = gzip.compress(data_to_append.encode("utf-8")) self._progress_message.setProgress(-1) # Tickle the message so that it's clear that it's still being used. QCoreApplication.processEvents() # Ensure that the GUI does not freeze. # Pretend that this is a response, as zipping might take a bit of time. # If we don't do this, the device might trigger a timeout. self._last_response_time = time() return compressed_data def _compressGCode(self) -> Optional[bytes]: self._compressing_gcode = True ## Mash the data into single string max_chars_per_line = int(1024 * 1024 / 4) # 1/4 MB per line. file_data_bytes_list = [] batched_lines = [] batched_lines_count = 0 for line in self._gcode: if not self._compressing_gcode: self._progress_message.hide() # Stop trying to zip / send as abort was called. return None # if the gcode was read from a gcode file, self._gcode will be a list of all lines in that file. # Compressing line by line in this case is extremely slow, so we need to batch them. batched_lines.append(line) batched_lines_count += len(line) if batched_lines_count >= max_chars_per_line: file_data_bytes_list.append(self._compressDataAndNotifyQt("".join(batched_lines))) batched_lines = [] batched_lines_count = 0 # Don't miss the last batch (If any) if len(batched_lines) != 0: file_data_bytes_list.append(self._compressDataAndNotifyQt("".join(batched_lines))) self._compressing_gcode = False return b"".join(file_data_bytes_list) def _update(self) -> bool: if self._last_response_time: time_since_last_response = time() - self._last_response_time else: time_since_last_response = 0 if self._last_request_time: time_since_last_request = time() - self._last_request_time else: time_since_last_request = float("inf") # An irrelevantly large number of seconds if time_since_last_response > self._timeout_time >= time_since_last_request: # Go (or stay) into timeout. if self._connection_state_before_timeout is None: self._connection_state_before_timeout = self._connection_state self.setConnectionState(ConnectionState.closed) # We need to check if the manager needs to be re-created. If we don't, we get some issues when OSX goes to # sleep. if time_since_last_response > self._recreate_network_manager_time: if self._last_manager_create_time is None: self._createNetworkManager() if time() - self._last_manager_create_time > self._recreate_network_manager_time: self._createNetworkManager() elif self._connection_state == ConnectionState.closed: # Go out of timeout. self.setConnectionState(self._connection_state_before_timeout) self._connection_state_before_timeout = None return True def _createEmptyRequest(self, target, content_type: Optional[str] = "application/json") -> QNetworkRequest: url = QUrl("http://" + self._address + self._api_prefix + target) request = QNetworkRequest(url) if content_type is not None: request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json") request.setHeader(QNetworkRequest.UserAgentHeader, self._user_agent) return request def _createFormPart(self, content_header, data, content_type = None) -> QHttpPart: part = QHttpPart() if not content_header.startswith("form-data;"): content_header = "form_data; " + content_header part.setHeader(QNetworkRequest.ContentDispositionHeader, content_header) if content_type is not None: part.setHeader(QNetworkRequest.ContentTypeHeader, content_type) part.setBody(data) return part ## Convenience function to get the username from the OS. # The code was copied from the getpass module, as we try to use as little dependencies as possible. def _getUserName(self) -> str: for name in ("LOGNAME", "USER", "LNAME", "USERNAME"): user = os.environ.get(name) if user: return user return "Unknown User" # Couldn't find out username. def _clearCachedMultiPart(self, reply: QNetworkReply) -> None: if reply in self._kept_alive_multiparts: del self._kept_alive_multiparts[reply] def put(self, target: str, data: str, onFinished: Optional[Callable[[Any, QNetworkReply], None]]) -> None: if self._manager is None: self._createNetworkManager() request = self._createEmptyRequest(target) self._last_request_time = time() reply = self._manager.put(request, data.encode()) self._registerOnFinishedCallback(reply, onFinished) def get(self, target: str, onFinished: Optional[Callable[[Any, QNetworkReply], None]]) -> None: if self._manager is None: self._createNetworkManager() request = self._createEmptyRequest(target) self._last_request_time = time() reply = self._manager.get(request) self._registerOnFinishedCallback(reply, onFinished) def post(self, target: str, data: str, onFinished: Optional[Callable[[Any, QNetworkReply], None]], onProgress: Callable = None) -> None: if self._manager is None: self._createNetworkManager() request = self._createEmptyRequest(target) self._last_request_time = time() reply = self._manager.post(request, data) if onProgress is not None: reply.uploadProgress.connect(onProgress) self._registerOnFinishedCallback(reply, onFinished) def postFormWithParts(self, target:str, parts: List[QHttpPart], onFinished: Optional[Callable[[Any, QNetworkReply], None]], onProgress: Callable = None) -> None: if self._manager is None: self._createNetworkManager() request = self._createEmptyRequest(target, content_type=None) multi_post_part = QHttpMultiPart(QHttpMultiPart.FormDataType) for part in parts: multi_post_part.append(part) self._last_request_time = time() reply = self._manager.post(request, multi_post_part) self._kept_alive_multiparts[reply] = multi_post_part if onProgress is not None: reply.uploadProgress.connect(onProgress) self._registerOnFinishedCallback(reply, onFinished) return reply def postForm(self, target: str, header_data: str, body_data: bytes, onFinished: Optional[Callable[[Any, QNetworkReply], None]], onProgress: Callable = None) -> None: post_part = QHttpPart() post_part.setHeader(QNetworkRequest.ContentDispositionHeader, header_data) post_part.setBody(body_data) self.postFormWithParts(target, [post_part], onFinished, onProgress) def _onAuthenticationRequired(self, reply, authenticator) -> None: Logger.log("w", "Request to {url} required authentication, which was not implemented".format(url = reply.url().toString())) def _createNetworkManager(self) -> None: Logger.log("d", "Creating network manager") if self._manager: self._manager.finished.disconnect(self.__handleOnFinished) self._manager.authenticationRequired.disconnect(self._onAuthenticationRequired) self._manager = QNetworkAccessManager() self._manager.finished.connect(self.__handleOnFinished) self._last_manager_create_time = time() self._manager.authenticationRequired.connect(self._onAuthenticationRequired) machine_manager = CuraApplication.getInstance().getMachineManager() machine_manager.checkCorrectGroupName(self.getId(), self.name) def _registerOnFinishedCallback(self, reply: QNetworkReply, onFinished: Optional[Callable[[Any, QNetworkReply], None]]) -> None: if onFinished is not None: self._onFinishedCallbacks[reply.url().toString() + str(reply.operation())] = onFinished def __handleOnFinished(self, reply: QNetworkReply) -> None: # Due to garbage collection, we need to cache certain bits of post operations. # As we don't want to keep them around forever, delete them if we get a reply. if reply.operation() == QNetworkAccessManager.PostOperation: self._clearCachedMultiPart(reply) if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) is None: # No status code means it never even reached remote. return self._last_response_time = time() if self._connection_state == ConnectionState.connecting: self.setConnectionState(ConnectionState.connected) callback_key = reply.url().toString() + str(reply.operation()) try: if callback_key in self._onFinishedCallbacks: self._onFinishedCallbacks[callback_key](reply) except Exception: Logger.logException("w", "something went wrong with callback") @pyqtSlot(str, result=str) def getProperty(self, key: str) -> str: bytes_key = key.encode("utf-8") if bytes_key in self._properties: return self._properties.get(bytes_key, b"").decode("utf-8") else: return "" def getProperties(self): return self._properties ## Get the unique key of this machine # \return key String containing the key of the machine. @pyqtProperty(str, constant=True) def key(self) -> str: return self._id ## The IP address of the printer. @pyqtProperty(str, constant=True) def address(self) -> str: return self._properties.get(b"address", b"").decode("utf-8") ## Name of the printer (as returned from the ZeroConf properties) @pyqtProperty(str, constant=True) def name(self) -> str: return self._properties.get(b"name", b"").decode("utf-8") ## Firmware version (as returned from the ZeroConf properties) @pyqtProperty(str, constant=True) def firmwareVersion(self) -> str: return self._properties.get(b"firmware_version", b"").decode("utf-8") @pyqtProperty(str, constant=True) def printerType(self) -> str: return self._printer_type ## IPadress of this printer @pyqtProperty(str, constant=True) def ipAddress(self) -> str: return self._address
criscola/G-Gen
misc/zip/Cura-master/cura/PrinterOutput/NetworkedPrinterOutputDevice.py
NetworkedPrinterOutputDevice.py
py
14,072
python
en
code
1
github-code
36
[ { "api_name": "enum.IntEnum", "line_number": 17, "usage_type": "name" }, { "api_name": "cura.PrinterOutputDevice.PrinterOutputDevice", "line_number": 25, "usage_type": "name" }, { "api_name": "PyQt5.QtCore.pyqtSignal", "line_number": 26, "usage_type": "call" }, { ...
30129375464
import cv2 face_cascade=cv2.CascadeClassifier(r"C:\Users\KIIT\AppData\Roaming\Python\Python310\site-packages\cv2\data\haarcascade_frontalface_default.xml") cap=cv2.VideoCapture(0) while 1: ret,img=cap.read() color=cv2.cvtColor(img,cv2.COLOR_BGR2RGBA) faces=face_cascade.detectMultiScale(color,1.3,5) for (x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,255),2) cv2.imshow('img',img) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
rimo10/object-detection
face.py
face.py
py
520
python
en
code
0
github-code
36
[ { "api_name": "cv2.CascadeClassifier", "line_number": 3, "usage_type": "call" }, { "api_name": "cv2.VideoCapture", "line_number": 4, "usage_type": "call" }, { "api_name": "cv2.cvtColor", "line_number": 8, "usage_type": "call" }, { "api_name": "cv2.COLOR_BGR2RGBA",...
29567698176
import requests KIND_SELL = "f3b277728b3fee749481eb3e0b3b48980dbbab78658fc419025cb16eee346775" BALANCE_ERC20 = "5a28e9363bb942b639270062aa6bb295f434bcdfc42c97267bf003f272060dc9" def api_get_sell_fee(sell_token, buy_token, sell_amount, network="mainnet"): fee_url = f"https://api.cow.fi/{network}/api/v1/feeAndQuote/sell" get_params = {"sellToken": sell_token, "buyToken": buy_token, "sellAmountBeforeFee": sell_amount} r = requests.get(fee_url, params=get_params) assert r.ok and r.status_code == 200 fee_amount = int(r.json()["fee"]["amount"]) buy_amount_after_fee = int(r.json()["buyAmountAfterFee"]) assert fee_amount > 0 assert buy_amount_after_fee > 0 return (fee_amount, buy_amount_after_fee) def api_get_quote(sell_token, buy_token, sell_amount, valid_to, sender, partiallyFillable=False, network="mainnet"): quote_url = f"https://api.cow.fi/{network}/api/v1/quote" order_payload = { "sellToken": sell_token, "buyToken": buy_token, "sellAmountBeforeFee": int(sell_amount), "validTo": valid_to, "partiallyFillable": partiallyFillable, "from": sender, "receiver": "0x0000000000000000000000000000000000000000", "appData": "0x0000000000000000000000000000000000000000000000000000000000000000", "kind": "sell", "sellTokenBalance": "erc20", "buyTokenBalance": "erc20", "signingScheme": "presign", # Very important. this tells the api you are going to sign on chain } r = requests.post(quote_url, json=order_payload) assert r.ok and r.status_code == 200 fee_amount = int(r.json()["fee"]["amount"]) buy_amount_after_fee = int(r.json()["buyAmountAfterFee"]) assert fee_amount > 0 assert buy_amount_after_fee > 0 return (fee_amount, buy_amount_after_fee) def api_get_order_status(orderUid, network="mainnet"): order_url = f"https://api.cow.fi/{network}/api/v1/orders/{orderUid}" r = requests.get(order_url) assert r.ok and r.status_code == 200 status = r.json()["status"] return status def api_create_order( sell_token, buy_token, sell_amount, buy_amount, fee_amount, valid_to, sender, receiver, partiallyFillable=False, app_data="0x0000000000000000000000000000000000000000000000000000000000000000", network="mainnet", ): order_url = f"https://api.cow.fi/{network}/api/v1/orders" partiallyFillable = False order_payload = { "sellToken": sell_token, "buyToken": buy_token, "sellAmount": str(sell_amount), # sell amount before fee "buyAmount": str(buy_amount), # buy amount after fee "validTo": valid_to, "appData": app_data, "feeAmount": str(fee_amount), "kind": "sell", "partiallyFillable": partiallyFillable, "receiver": receiver, "signature": "0x", "from": sender, "sellTokenBalance": "erc20", "buyTokenBalance": "erc20", "signingScheme": "presign", # Very important. this tells the api you are going to sign on chain } r = requests.post(order_url, json=order_payload) assert r.ok and r.status_code == 201 order_uid = r.json() return order_uid
lidofinance/lido-otc-seller
utils/cow.py
cow.py
py
3,245
python
en
code
1
github-code
36
[ { "api_name": "requests.get", "line_number": 10, "usage_type": "call" }, { "api_name": "requests.post", "line_number": 36, "usage_type": "call" }, { "api_name": "requests.get", "line_number": 47, "usage_type": "call" }, { "api_name": "requests.post", "line_num...
36395547481
from selenium import webdriver from selenium.webdriver.common.keys import Keys from datetime import datetime import time class InstagramBot: def __init__(self, username, password): self.username = username self.password = password self.bot = webdriver.Firefox() self.cont = 0 self.stopCont = 10 self.numeroSeguidores = '0' self.codigoLocal = '' def login(self): bot = self.bot bot.get('https://www.instagram.com/accounts/login/?source=auth_switcher') time.sleep(3) email = bot.find_element_by_name('username') password = bot.find_element_by_name('password') email.clear() password.clear() email.send_keys(self.username) password.send_keys(self.password) password.send_keys(Keys.RETURN) time.sleep(3) def encontrarFotos(self, tag): bot = self.bot time.sleep(2) for i in range(1,3): bot.execute_script('window.scrollTo(0,document.body.scrollHeight)') time.sleep(2) foto = bot.find_elements_by_tag_name('a') links = [elem.get_attribute('href') for elem in foto] for i in range(13,30): bot.get(links[i]) try: time.sleep(2) if ed.verificarLike() == False: bot.find_element_by_class_name('fr66n').click() #curtir time.sleep(2) if tag == seguirTag: ed.verificarSeguindo() time.sleep(2) except Exception as ex: time.sleep(6) def seguirSeguidores(self): bot = self.bot bot.get('https://www.instagram.com/'+self.username) time.sleep(2) elemento = bot.find_elements_by_tag_name('a') links = [elem.get_attribute('href') for elem in elemento] for i in range(len(links)): if links[i]=='https://www.instagram.com/'+ self.username +'/followers/': elemento[i].click() break time.sleep(4) bot2 = self.bot seguidores = bot2.find_elements_by_class_name('wo9IH') listaSeguidores = [seguidores.find_element_by_class_name('uu6c_') for seguidores in seguidores] listaBotaoSeguir = [listaSeguidores.find_element_by_class_name('Pkbci') for listaSeguidores in listaSeguidores] for listaBotaoSeguir in listaBotaoSeguir: if listaBotaoSeguir.find_element_by_tag_name('button').text == 'Seguir': listaBotaoSeguir.find_element_by_tag_name('button').click() time.sleep(1) def calcularSeguidores(self): bot = self.bot numeroSeguidores = bot.find_element_by_xpath('//*[@id="react-root"]/section/main/div/header/section/ul/li[2]/a/span').text if self.numeroSeguidores != numeroSeguidores: self.numeroSeguidores = numeroSeguidores print('--------------------------\nNúmero atual de seguidores: '+numeroSeguidores) def seguirIdeal(self): bot = self.bot bot.get('https://www.instagram.com/lpeventos08') time.sleep(2) elemento = bot.find_elements_by_tag_name('a') links = [elem.get_attribute('href') for elem in elemento] for i in range(len(links)): if links[i]=='https://www.instagram.com/lpeventos08/following/': elemento[i].click() def verificarLike(self): bot = self.bot botao = bot.find_element_by_class_name('fr66n') botao2 = botao.find_element_by_tag_name('button') botaoFinal = botao2.find_element_by_tag_name('span') if botaoFinal.get_attribute('class') == 'glyphsSpriteHeart__filled__24__red_5 u-__7': return True return False def buscarTag(self, tag): bot = self.bot bot.get('https://www.instagram.com/'+self.username) time.sleep(2) ed.calcularSeguidores() bot.get('https://www.instagram.com/explore/tags/'+tag) time.sleep(2) ed.encontrarFotos(tag) def verificarSeguindo(self): bot = self.bot if ed.cont<10: ed.cont = ed.cont+1 bot.find_element_by_xpath('//*[@id="react-root"]/section/main/div/div/article/header/div[2]/div[1]/div[2]/button').click() else: ed.zerarCont() def zerarCont(self): self.stopCont = self.stopCont - 1 if self.stopCont == 0: self.cont = 0 self.stopCont = 10 def getCodigoCidade(self, cidade): codigoCidades = ['213106903','405027146','248738611','112047398814697','213665608','221337983','8226756'] return codigoCidades[cidade] def verificaCidade(self, tag): cidades = ['curitiba', 'riodejaneiro', 'parana', 'saopaulo','londrina','assis', 'maringa'] for i in range(len(cidades)): if tag == cidades[i]: self.codigoLocal = ed.getCodigoCidade(i) return True return False def buscarLocalizacao(self, tag): bot = self.bot bot.get('https://www.instagram.com/'+self.username) time.sleep(2) ed.calcularSeguidores() bot.get('https://www.instagram.com/explore/locations/'+self.codigoLocal) time.sleep(2) ed.encontrarFotos(tag) usuario = '' senha = '' print('Usuário:') #usuario = input(usuario) print('Senha:') #senha = input(senha) tags = [] tag = '' print('PARA INICIAR A APLICAÇÃO DIGITE: start') while True: print('Insira uma tag:') tag = '' tag = input(tag) if tag == 'start': break tags.append(tag) seguirTag = 'nao seguir' ed = InstagramBot(usuario,senha) ed.login() time.sleep(2) while True: i=0 for i in range(len(tags)): try: if ed.verificaCidade(tags[i]): ed.buscarLocalizacao(tags[i]) else: ed.buscarTag(tags[i]) except Exception as ex: ed.bot.get('https://www.instagram.com/'+usuario)
matheusleps/InstaBot
instabot.py
instabot.py
py
6,262
python
pt
code
0
github-code
36
[ { "api_name": "selenium.webdriver.Firefox", "line_number": 10, "usage_type": "call" }, { "api_name": "selenium.webdriver", "line_number": 10, "usage_type": "name" }, { "api_name": "time.sleep", "line_number": 19, "usage_type": "call" }, { "api_name": "selenium.web...
18801922589
from flask import request, json, Response, Blueprint, g, jsonify, make_response from ..models.UserModel import UserModel, UserSchema from ..shared.Authentication import Auth from marshmallow import ValidationError user_api = Blueprint('users', __name__) user_schema = UserSchema() @user_api.after_request # blueprint can also be app~~ def after_request(response): header = response.headers header['Access-Control-Allow-Origin'] = '*' header['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS, PUT, PATCH, DELETE' header['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, x-auth' return response @user_api.route('/', methods=['POST']) def create(): """ Create User Function """ req_data = request.get_json() try: data = user_schema.load(req_data) except ValidationError as error: return custom_response(error.messages, 400) # check if user already exist in the db user_in_db = UserModel.get_user_by_email(data.get('email')) if user_in_db: message = {'error': 'User already exist, please supply another email address'} return custom_response(message, 400) user = UserModel(data) user.save() ser_data = user_schema.dump(user) token = Auth.generate_token(ser_data.get('id')) return custom_response({'jwt_token': token}, 201) # @user_api.route('/', methods=['GET']) # @Auth.auth_required # def get_all(): # users = UserModel.get_all_users() # ser_users = user_schema.dump(users, many=True) # return custom_response(ser_users, 200) @user_api.route('/login', methods=['POST']) def login(): req_data = request.get_json() try: data = user_schema.load(req_data, partial=True) except ValidationError as error: return custom_response(error.messages, 400) if not data.get('email') or not data.get('password'): return custom_response({'error': 'you need email and password to sign in'}, 400) user = UserModel.get_user_by_email(data.get('email')) if not user: return custom_response({'error': 'invalid credentials'}, 400) if not user.check_hash(data.get('password')): return custom_response({'error': 'invalid credentials'}, 400) ser_data = user_schema.dump(user) token = Auth.generate_token(ser_data.get('id')) return custom_response({'jwt_token': token}, 200) # @user_api.route('/<int:user_id>', methods=['GET']) # @Auth.auth_required # def get_a_user(user_id): # """ # Get a single user # """ # user = UserModel.get_one_user(user_id) # if not user: # return custom_response({'error': 'user not found'}, 404) # ser_user = user_schema.dump(user) # return custom_response(ser_user, 200) @user_api.route('/me', methods=['PUT']) @Auth.auth_required def update(): """ Update me """ req_data = request.get_json() try: data = user_schema.load(req_data, partial=True) except ValidationError as error: return custom_response(error.messages, 400) user = UserModel.get_one_user(g.user.get('id')) user.update(data) ser_user = user_schema.dump(user) return custom_response(ser_user, 200) @user_api.route('/me', methods=['GET']) @Auth.auth_required def get_me(): """ Get me """ user = UserModel.get_one_user(g.user.get('id')) ser_user = user_schema.dump(user) return custom_response(ser_user, 200) def custom_response(res, status_code): """ Custom Response Function """ resp = Response( mimetype="application/json", response=json.dumps(res), status=status_code ) resp.headers['Access-Control-Allow-Origin'] = '*' resp.headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS' resp.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization' return resp
AnthonyClausing/movie-night-api
src/views/UserView.py
UserView.py
py
3,721
python
en
code
0
github-code
36
[ { "api_name": "flask.Blueprint", "line_number": 6, "usage_type": "call" }, { "api_name": "models.UserModel.UserSchema", "line_number": 7, "usage_type": "call" }, { "api_name": "flask.request.get_json", "line_number": 23, "usage_type": "call" }, { "api_name": "flas...
12366385422
#!/usr/bin/env ccp4-python """ Created on 2 Feb 2015 @author: jmht """ import logging import os import shutil import sys import uuid from ample.util import ample_util, mtz_util try: from mrbump.parsers import parse_shelxe except ImportError: mrbumpd = os.path.join(os.environ['CCP4'], "share", "mrbump", "include", "parsers") sys.path.insert(0, mrbumpd) import parse_shelxe logger = logging.getLogger(__name__) class MRinfo(object): """An object to analyse Molecular Replacement solutions Attributes ---------- work_dir : str Path to the working directory shelxe_exe : str Path to the SHELXE executable stem : str The name for all the SHELXE files originShift : list The origin shift of the MR pdb to native as a list of three floats MPE : float The Mean Phase Error of the MR pdb to the native pdb wMPE : float The weighted Mean Phase Error of the MR pdb to the native pdb """ def __init__(self, shelxe_exe, native_pdb, native_mtz, work_dir=None): """Intialise from native pdb and mtz so that analyse only requires a MR pdb Parameters ---------- shelxe_exe : str Path to the SHELXE executable native_pdb : str Path to the native PDB file native_mtz : str Path to the native MTZ file """ self.work_dir = work_dir or os.getcwd() self.shelxe_exe = shelxe_exe self.stem = 'shelxe-input-{}'.format(str(uuid.uuid1())) self.MPE = None self.wMPE = None self.originShift = None self.mk_native_files(native_pdb, native_mtz) return def mk_native_files(self, native_pdb, native_mtz): """Create the files required by SHELXE from the native structure Parameters ---------- native_pdb : str Path to the native PDB file native_mtz : str Path to the native MTZ file """ mtz_util.to_hkl(native_mtz, hkl_file=os.path.join(self.work_dir, self.stem + ".hkl")) shutil.copyfile(native_pdb, os.path.join(self.work_dir, self.stem + ".ent")) def analyse(self, mr_pdb, cleanup=True): """Use SHELXE to analyse an MR pdb file to determine the origin shift and phase error This function sets the ``MPE``, ``wMPE`` and ``originShift`` attributes. Parameters ---------- mr_pdb : str Path to the Molecular Replacement PDB file """ os.chdir(self.work_dir) input_pdb = self.stem + ".pda" shutil.copyfile(mr_pdb, os.path.join(self.work_dir, input_pdb)) cmd = [self.shelxe_exe, input_pdb, '-a0', '-q', '-s0.5', '-o', '-n', '-t0', '-m0', '-x'] logfile = os.path.abspath('shelxe_{}.log'.format(str(uuid.uuid1()))) ret = ample_util.run_command(cmd=cmd, logfile=logfile, directory=None, dolog=False, stdin=None) if ret != 0: raise RuntimeError("Error running shelxe - see log: {0}".format(logfile)) sp = parse_shelxe.ShelxeLogParser(logfile) # Only added in later version of MRBUMP shelxe parser if hasattr(sp, 'MPE'): self.MPE = sp.MPE self.wMPE = sp.wMPE if isinstance(sp.originShift, list): self.originShift = [o * -1 for o in sp.originShift] if cleanup: for ext in ['.hkl', '.ent', '.pda', '.pdo', '.phs', '.lst', '_trace.ps']: try: os.unlink(self.stem + ext) except: pass os.unlink(logfile) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='Determine origin using SHELXE', prefix_chars="-") parser.add_argument('--native_mtz', help='Native MTZ', required=True) parser.add_argument('--native_pdb', help='Native PDB', required=True) parser.add_argument('--mr_pdb', help='Molecular Replacement MTZ', required=True) parser.add_argument('--executable', help="Path to SHELXE executable") args = parser.parse_args() logging.basicConfig(level=logging.INFO) executable = None if args.executable: executable = args.executable else: executable = os.path.join(os.environ['CCP4'], "bin", "shelxe" + ample_util.EXE_EXT) # Get full paths to all files native_mtz = os.path.abspath(args.native_mtz) if not os.path.isfile(native_mtz): raise RuntimeError("Cannot find input file: {0}".format(native_mtz)) native_pdb = os.path.abspath(args.native_pdb) if not os.path.isfile(native_pdb): raise RuntimeError("Cannot find input file: {0}".format(native_pdb)) mr_pdb = os.path.abspath(args.mr_pdb) if not os.path.isfile(mr_pdb): raise RuntimeError("Cannot find input file: {0}".format(mr_pdb)) mrinfo = MRinfo(executable, native_pdb, native_mtz) mrinfo.analyse(mr_pdb) os.unlink('shelxe-input.hkl') os.unlink('shelxe-input.ent') logger.info("Origin shift is: {0}".format(mrinfo.originShift)) logger.info("Phase error is MPE: {0} | wMPE: {1}".format(mrinfo.originShift, mrinfo.MPE, mrinfo.wMPE))
rigdenlab/ample
ample/util/shelxe.py
shelxe.py
py
5,172
python
en
code
6
github-code
36
[ { "api_name": "os.path.join", "line_number": 19, "usage_type": "call" }, { "api_name": "os.path", "line_number": 19, "usage_type": "attribute" }, { "api_name": "os.environ", "line_number": 19, "usage_type": "attribute" }, { "api_name": "sys.path.insert", "line...
70617927783
# Speech Brain Viewer app # to accompany Hamilton, Oganian, Hall, and Chang, Cell 2021 # https://doi.org/10.1016/j.cell.2021.07.019 # # Viewer created by Liberty Hamilton, 2021 # Email liberty.hamilton@austin.utexas.edu with questions # import scipy.io import numpy as np import dash import dash_core_components as dcc import dash_html_components as html import dash_daq as daq from dash.dependencies import Input, Output, State, ClientsideFunction import plotly.express as px import pandas as pd from plotly.subplots import make_subplots import plotly.graph_objs as go import time import os from flask_caching import Cache from dash.exceptions import PreventUpdate external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] suppress_callback_exceptions=True app = dash.Dash(__name__, external_stylesheets=external_stylesheets) app.title='Speech Brain Viewer' server = app.server cache = Cache(app.server, config={ 'CACHE_TYPE': 'redis', 'CACHE_REDIS_URL': os.environ.get('REDIS_URL', '') }) timeout = 300 styles = { 'pre': { 'border': 'thin lightgrey solid', 'overflowX': 'scroll' } } full_strf = scipy.io.loadmat('full_strf.mat')['strf'] spect_strf = scipy.io.loadmat('spect_strf.mat')['strf'] onset_strf = scipy.io.loadmat('onset_strf.mat')['strf'] peakrate_strf = scipy.io.loadmat('peakrate_strf.mat')['peakrate_strf'] phnfeat_strf = scipy.io.loadmat('phnfeat_strf.mat')['strf'] rel_strf = scipy.io.loadmat('rel_strf.mat')['strf'] elecs = scipy.io.loadmat('elecmatrix.mat')['elecmatrix'] vcorrs1 = scipy.io.loadmat('vcorrs.mat')['vcorrs'] vcorrs = scipy.io.loadmat('uvar.mat')['uvar'] vcorrs = np.hstack((vcorrs, vcorrs1)) trivert = scipy.io.loadmat('lh_pial_trivert.mat') v = trivert['vert'] t = trivert['tri'] temporal_trivert = scipy.io.loadmat('cvs_avg_inMNI152_lh_temporal_pial.mat') tv = temporal_trivert['vert'] tt = temporal_trivert['tri'] curv = scipy.io.loadmat('cvs_curv.mat')['curv'] anatomy = scipy.io.loadmat('elecmatrix.mat')['anatomy'] anum = np.array([a[0]-1 for a in anatomy]) elecs[anum>=5,0] = elecs[anum>=5,0]-1 anames = scipy.io.loadmat('elecmatrix.mat')['new7AreaNames'] anames2 = [a[0] for a in anames[0]] anat_labels = [anames2[a[0]-1] for a in anatomy] clr = scipy.io.loadmat('elecmatrix.mat')['area7Cols'] clrs = [clr[a[0]-1,:].tolist() for a in anatomy] # We have a small number in the right hem that were projected to the medial wall, lets remove rm_elecs = np.intersect1d(np.where(elecs[:,1]<-20)[0], np.where(elecs[:,2]<-20)[0]) elec_no = np.arange(elecs.shape[0]) elecs_mask = np.ones((elecs.shape[0],), dtype=bool) elecs_mask[rm_elecs] = False elec_no = elec_no[elecs_mask] elecs = elecs[elecs_mask,:] vcorrs = vcorrs[elecs_mask,:] full_strf = full_strf[elecs_mask,:,:] onset_strf = onset_strf[elecs_mask,:,:] spect_strf = spect_strf[elecs_mask,:,:] peakrate_strf = peakrate_strf[elecs_mask,:] phnfeat_strf = phnfeat_strf[elecs_mask,:,:] rel_strf = rel_strf[elecs_mask,:,:] anum = anum[elecs_mask] anat_labels = [anat_labels[a] for a in elec_no] clrs = [clrs[a] for a in elec_no] #stim_effects = pd.read_excel(io='/Users/jsh3653/Dropbox/Heschls_STRFs/data/stim/HG_stim_summary.xlsx', # sheet_name='unique_for_manuscript') stim_effects = pd.read_excel(io='stim_results.xlsx', sheet_name='Sheet1') stim_df = pd.DataFrame( data={'elec_number': np.arange(len(stim_effects)), 'x': stim_effects['x'], 'y': stim_effects['y'], 'z': stim_effects['z'], 'anatomy': stim_effects['anatomy'], 'effect': stim_effects['effect'], 'passive_effect': stim_effects['passive_effect'], 'repetition_effect': stim_effects['repetition_effect']}, ) def create_figure(dropdownData='RF', elec_marker='vcorrs', show_rest_of_brain=True, corr_type=20): ''' Create the brain figure and modify the electrode colors based on dropdown menus. The frontal lobe will be shown or not depending on the value of the show_rest_of_brain switch. ''' if dropdownData=='RF': chosen_elecs = np.arange(elecs.shape[0]) df = pd.DataFrame( data={'elec_number': chosen_elecs, 'x': elecs[chosen_elecs,0], 'y': elecs[chosen_elecs,1], 'z': elecs[chosen_elecs,2], 'anatomy': [anat_labels[a] for a in chosen_elecs], 'anatomy_num': [anum[a] for a in chosen_elecs], 'vcorrs': vcorrs[chosen_elecs,corr_type]}, ) else: df = stim_df if elec_marker == 'anatomy_num': marker = dict(color=clrs, size=6) elif elec_marker == 'vcorrs': marker = dict(color=df['vcorrs'], colorscale='RdBu_r', cmin=-df['vcorrs'].max(), cmax=df['vcorrs'].max(), size=6, colorbar=dict(title='Corr.', thickness=20)) elif elec_marker == 'stim_eff': marker = dict(color=df['effect'], colorscale='RdBu_r', cmin=1, cmax=3, size=6, colorbar=dict(title='Effect', thickness=20)) fig = go.Figure( data = [go.Mesh3d( x=tv[:, 0], y=tv[:, 1], z=tv[:, 2], i=tt[:, 0], j=tt[:, 1], k=tt[:, 2], colorbar=None, showscale=False, color='rgb(200,200,200)', name='temporal lobe', opacity=0.6, lighting=dict(ambient=0.9, diffuse=0.9), intensity=curv, colorscale=[[0, 'white'], [0.5, 'gray'], [1, 'black']] ), ]) if show_rest_of_brain: fig.add_trace( go.Mesh3d( x=v[:, 0], y=v[:, 1], z=v[:, 2], i=t[:, 0], j=t[:, 1], k=t[:, 2], colorbar=None, showscale=False, color='rgb(200,200,200)', name='brain', text=None, opacity=0.2, lighting=dict(ambient=0.9, diffuse=0.9), intensity=curv, colorscale=[[0, 'white'], [0.5, 'gray'], [1, 'black']] ) ) fig.add_trace( go.Scatter3d( x=df['x'], y=df['y'], z=df['z'], ids=df['elec_number'], mode='markers', name='electrode', text=df['anatomy'], marker=marker, ), ) camera = dict( up=dict(x=0, y=0, z=1), center=dict(x=0, y=0, z=0), eye=dict(x=-1.25, y=0.1, z=0.13), ) fig.update_layout(clickmode='event+select', scene=dict( xaxis=dict(showticklabels=False, showgrid=False, title='L-R'), yaxis=dict(showticklabels=False, showgrid=False, title='A-P'), zaxis=dict(showticklabels=False, showgrid=False, title='D-V'), ), scene_camera=camera, height=int(500), ) fig.update_scenes(xaxis_showbackground=False, yaxis_showbackground=False, zaxis_showbackground=False, xaxis_showaxeslabels=False, yaxis_showaxeslabels=False, zaxis_showaxeslabels=False,) return fig def create_rf(elec_num=310, corr_type=12): ''' This creates the receptive field heat map plot for the model of interest (based on `corr_type` number). For reference, those corr numbers are: Unique Onset: 0 Unique Peak rate: 1 Unique Features: 2 Unique Abs Pitch: 3 Unique Rel Pitch: 4 Full phonological+pitch: 12, Spectrogram: 20 ''' if elec_num is None: elec_num = 310 title = 'Please select an electrode...' strf = np.zeros((spect_strf.shape[1], spect_strf.shape[2])) yticks = [] yticklabels = [] ticksize = 12 ylabel = '' autorange = True else: if (corr_type == 20) or (corr_type == 12): title = 'Electrode %d, r=%2.2f'%(elec_num, vcorrs[elec_num,corr_type]) else: title = 'Electrode %d, unique r^2=%2.2f'%(elec_num, vcorrs[elec_num,corr_type]) if corr_type == 20: strf = np.fliplr(spect_strf[elec_num,:,:]) yticks = [11, 43, 79] yticklabels = [0.5, 2, 8] ticksize = 12 ylabel = 'Frequency (kHz)' autorange = True elif corr_type == 0: # onset strf = np.fliplr(onset_strf[elec_num,:,:]) ticksize = 12 yticks = [strf.min(), 0, strf.max()] ylabel = 'Onset weight (A.U.)' yticklabels = [np.round(strf.min()*100)/100., 0, np.round(strf.max()*100)/100.] autorange = True elif corr_type == 1: # peakrate strf = peakrate_strf[elec_num,:][::-1] ticksize = 12 yticks = [strf.min(), 0, strf.max()] ylabel = 'Peak rate weight (A.U.)' yticklabels = [np.round(strf.min()*100)/100., 0, np.round(strf.max()*100)/100.] autorange = True elif corr_type == 2: strf = np.fliplr(phnfeat_strf[elec_num,:,:]) yticks = np.arange(phnfeat_strf.shape[1]) yticklabels = ['sonorant','obstruent','voiced', 'nasal','syllabic','fricative','plosive', 'back','low','front','high','labial', 'coronal','dorsal'] ticksize = 6 ylabel = '' autorange = 'reversed' elif corr_type == 3: # abs pitch strf = np.fliplr(full_strf[elec_num,15:25,:]) #yticks = [0,1,15,25,35] #yticklabels = ['on','ph','ab','rl','dr'] yticks = [0,9] yticklabels = [90, 250] ticksize = 12 ylabel = 'Abs. Pitch (Hz)' autorange = True elif corr_type == 4: strf = np.fliplr(rel_strf[elec_num,:,:]) yticks = [0, 4.5, 9, 10, 14.5, 19]#np.arange(rel_strf.shape[1]) yticklabels = [-1.9, 0, 1.9, -0.4, 0, 0.3] ticksize = 12 ylabel = 'Rel. Pitch + ∆Rel. Pitch' autorange = True else: strf = np.fliplr(full_strf[elec_num,:,:]) reorder = [0,strf.shape[0]-1]+list(np.arange(1,full_strf.shape[1]-1)) print(strf.shape) print(reorder) strf = strf[reorder,:] #yticks = [0,1,15,25,35] #yticklabels = ['on','ph','ab','rl','dr'] yticks = np.arange(full_strf.shape[1]) yticklabels = ['onset','peakRate','sonorant','obstruent','voiced', 'nasal','syllabic','fricative','plosive', 'back','low','front','high','labial', 'coronal','dorsal','abs. pitch','','','', '','','','','','','rel. pitch','','','', '','','','','','','∆rel. pitch','','','', '','','','','',''] ticksize = 6 ylabel = '' autorange = 'reversed' smax = np.abs(strf.max()) if smax==0: smax = 1 if corr_type == 0: smax = 0.1 if corr_type > 1: fig = go.Figure(data = [ go.Heatmap( x=np.linspace(-0.6,0,60), z=strf, zmin=-smax, zmax=smax, colorscale='RdBu_r', colorbar=dict(title='Beta<br>weight<br>(A.U.)', tickvals=[-smax,0,smax], ticktext=['-max','0','max']), ) ] ) else: fig = go.Figure(data = [ go.Scatter( x=np.linspace(-0.6,0,60), y=strf.ravel(), mode='lines', ) ] ) if corr_type != 20: if corr_type == 12: fig.add_hline(y=0.5, line_width=1, line_color='black', line_dash='dash') fig.add_hline(y=1.5, line_width=1, line_color='black', line_dash='dash') fig.add_hline(y=15.5, line_width=1, line_color='black', line_dash='dash') fig.add_hline(y=25.5, line_width=1, line_color='black', line_dash='dash') fig.add_hline(y=35.5, line_width=1, line_color='black', line_dash='dash') if corr_type == 4: fig.add_hline(y=9.5, line_width=1, line_color='black', line_dash='dash') else: fig.add_hline(y=11, line_width=1, line_color='black', line_dash='dash') fig.add_hline(y=43, line_width=1, line_color='black', line_dash='dash') fig.add_hline(y=79, line_width=1, line_color='black', line_dash='dash') fig.update_layout( title={'text': title, 'x': 0.5, 'xanchor': 'center', 'yanchor': 'top'}, xaxis={'title': 'Time (s)'}, yaxis={'title': ylabel, 'tickmode': 'array', 'tickvals': yticks, 'ticktext': yticklabels, 'showgrid': False, 'autorange': autorange, 'tickfont_size': ticksize, 'automargin': False, } ) return fig fig = create_figure() rf_fig = create_rf() #fig = px.scatter(df, x="x", y="y", color="fruit", custom_data=["customdata"]) #fig.update_traces(selector=dict(name='electrode'), marker=dict(color='mediumblue', size=20), row=1, col=1) rf_markdown = dcc.Markdown(''' Click on an electrode on the brain to see its corresponding receptive field or stimulation result on the right. **Brain Controls:** * Zoom in and out of the brain by scrolling * Rotate the brain by clicking and dragging Note that the nonlinear warping of electrodes sometimes means the electrodes will seem farther forward or back than expected. The anatomical name that shows on hover is taken from the original (native space) brain data. Electrodes have been projected to the nearest surface vertex for ease of clicking. For the most accurate visualization, please see [our paper](https://doi.org/10.1016/j.cell.2021.07.019). Brain viewer created by Liberty Hamilton 2021 using [Dash and Plotly for python](https://dash.plotly.com/). Contact liberty.hamilton@austin.utexas.edu with any questions. ''') # This creates the initial app in its first instantiation. This will be # modified by user behaviors (clicking, changing menu items, etc.) app.layout = html.Div([ html.Div([ dcc.Markdown(''' ### Parallel and distributed speech encoding across human auditory cortex ### *Citation*: [Hamilton, Oganian, Hall, and Chang. _Cell_ 2021](https://doi.org/10.1016/j.cell.2021.07.019) This is an interactive tool to accompany our paper showing receptive fields across multiple sub-fields of auditory cortex. Select from the Dropdown menu below to explore receptive field findings and stimulation findings. Works best on desktop computers, tablet/mobile does not include all features. [Video Tutorial.](https://www.youtube.com/watch?v=Q0zulm4ciRI&ab_channel=LibertyHamilton) '''), ]), html.Div([ html.Div([ daq.BooleanSwitch( id='show-brain', on=True, label="Whole brain", labelPosition="top", ), ], className='three columns', style={'background-color': 'lightgrey', 'padding': '10px', 'float': 'left'}), html.Div([ html.Label('Color electrodes by:'), dcc.RadioItems( id='radio-color', options=[ {'label': 'Anatomy', 'value': 'anatomy_num'}, {'label': 'Correlation', 'value': 'vcorrs'}, ], value='vcorrs' )], className='three columns', style={'background-color': 'lightgrey', 'padding': '10px'}, id='color-electrodes-div'), html.Div([ html.Label('Correlation type:'), dcc.Dropdown( id='corr-type-dropdown', options=[ {'label': 'Spectrogram', 'value': '20'}, {'label': 'Full phonological+pitch', 'value': '12'}, {'label': 'Unique Onset', 'value': '0'}, {'label': 'Unique Peak rate', 'value': '1'}, {'label': 'Unique Features', 'value': '2'}, {'label': 'Unique Absolute Pitch', 'value': '3'}, {'label': 'Unique Relative Pitch', 'value': '4'}, ], # options=[ # {'label': 'Onset', 'value': '0'}, # {'label': 'Full', 'value': '6'}, # {'label': 'Relative pitch', 'value': '12'}, # {'label': 'Spectrogram', 'value': '14'}, # ], value='20' )], className='three columns', id='corr-type-div', style={'background-color': 'lightgrey', 'padding': '10px', 'display': 'inline-block'}), html.Div([ html.Label('Choose results to explore:'), dcc.Dropdown( id='rf-stim-dropdown', options=[ {'label': 'Receptive Fields', 'value': 'RF'}, {'label': 'Stimulation', 'value': 'ST'}, ], value='RF' )], className='three columns', style={'background-color': 'lightgrey', 'padding': '10px', 'display': 'inline-block', 'float': 'right'}), ], style={'background-color': 'lightgrey', 'display': 'inline-block', 'width': '100%'} ), html.Div([ dcc.Loading( dcc.Graph( id='brain-fig', figure=fig, ), type='circle', ), ], style={'width': '70%', 'display': 'inline-block', 'height': '70%'}), html.Div([ html.Div([ dcc.Graph( id='rf', figure=rf_fig, ), ], id="rf_div", style={'width': '100%', 'display': 'inline-block', 'vertical-align': 'top'}, ), html.Div([ html.H4('Stimulation effects'), html.P('Click on an electrode to see effects of stimulation on passive \ listening and on speech perception. We recommend you turn off\ the "whole brain" switch at the top left to show the temporal lobe only.'), html.P('Effect types: ', style={'font-weight': 'bold'}), html.P('1 (blue): sound hallucination + no problems perceiving speech', style={'background-color': '#0c2350', 'padding': '10px', 'color': '#ffffff'}), html.P('2 (white): no sound hallucination + problems perceiving speech', style={'background-color': '#f1f2f2', 'padding': '10px', 'color': '#000000'}), html.P('3 (red): Complex response', style={'background-color': '#73001c', 'padding': '10px', 'color': '#ffffff'}), html.H5('', id='stim_desc'), html.H5('', id='repet_effect') ], id="stim_div", style={'width': '100%', 'display': 'none', 'vertical-align': 'middle'}, ) ], id="rf_or_stim_div", style={'width': '30%', 'display': 'inline-block', 'vertical-align': 'top'}), html.Div([ rf_markdown, ], style={'background-color': 'lightgrey', 'padding': '10px'}), ], style={'max-width': '1200px'}, ) # This callback will create the receptive field figure # based on the correlation type you choose and what you # have clicked on the brain figure @app.callback( [Output('rf', 'figure'), Output('stim_desc', 'children'), Output('repet_effect', 'children'), Output('corr-type-div', 'style'), Output('color-electrodes-div', 'style')], [Input('brain-fig', 'clickData'), Input('corr-type-dropdown', 'value'), Input('rf-stim-dropdown', 'value')]) def update_rf(clickData, corr_val, rf_value): ctx = dash.callback_context prop_id = ctx.triggered[0]['prop_id'].split('.')[0] try: elec_num = clickData['points'][0]['id'] except: elec_num = None if rf_value == 'RF': rf_updated = create_rf(elec_num=elec_num, corr_type=int(corr_val)) stim_updated = '' rep_updated = '' corr_div_style={'background-color': 'lightgrey', 'padding': '10px', 'display': 'inline-block'} color_elec_style={'background-color': 'lightgrey', 'padding': '10px', 'display': 'inline-block'} else: corr_div_style={'background-color': 'lightgrey', 'padding': '10px', 'display': 'none'} color_elec_style={'background-color': 'lightgrey', 'padding': '10px', 'display': 'none'} if (prop_id == 'rf-stim-dropdown') or (prop_id=='corr-type-dropdown'): elec_num = 0 rf_updated = create_rf(elec_num=elec_num, corr_type=int(corr_val)) stim_updated = '' rep_updated = '' else: passive_description = stim_df['passive_effect'][elec_num] repet_description = stim_df['repetition_effect'][elec_num] rf_updated = create_rf(elec_num=elec_num, corr_type=int(corr_val)) stim_updated = 'Passive: ' + passive_description rep_updated = 'Repetition: ' + repet_description return rf_updated, stim_updated, rep_updated, corr_div_style, color_elec_style # This callback will change the brain figure to show # either receptive field data or stimulation data # based on the dropdown values. It will also change # the correlation type that is shown if in "RF" mode @app.callback( [Output('brain-fig', 'figure'), Output('show-brain', 'label'), Output('rf_div', 'style'), Output('stim_div', 'style'),], [Input('rf-stim-dropdown', 'value'), Input('radio-color', 'value'), Input('show-brain', 'on'), Input('corr-type-dropdown', 'value')]) # @cache.memoize(timeout=timeout) # in seconds, cache the data def display_click_data(rf_value, radio_value, brain_value, corr_val): ctx = dash.callback_context prop_id = ctx.triggered[0]['prop_id'].split('.')[0] value = ctx.triggered[0]['value'] if rf_value == 'ST': # Override elec_marker type el_marker = 'stim_eff' stim_style = {'width': '100%', 'display': 'inline-block', 'vertical-align': 'middle'} rf_style = {'width': '100%', 'display': 'none', 'vertical-align': 'top'} else: el_marker = radio_value stim_style = {'width': '100%', 'display': 'none', 'vertical-align': 'middle'} rf_style = {'width': '100%', 'display': 'inline-block', 'vertical-align': 'top'} fig = create_figure(dropdownData=rf_value, elec_marker=el_marker, show_rest_of_brain=brain_value, corr_type=int(corr_val)) if brain_value: show_brain = "Whole brain" else: show_brain = "Temporal lobe only" # if rf_value=='RF': # rf_stim_update = dcc.Loading(dcc.Graph(id='rf', figure=rf_fig)) # else: # rf_stim_update = ... #markdown for stim return fig, show_brain, rf_style, stim_style if __name__ == '__main__': #app.run_server(processes=6) app.run_server(debug=True, host='127.0.0.1')
libertyh/SpeechCortex
app.py
app.py
py
24,899
python
en
code
2
github-code
36
[ { "api_name": "dash.Dash", "line_number": 29, "usage_type": "call" }, { "api_name": "flask_caching.Cache", "line_number": 32, "usage_type": "call" }, { "api_name": "os.environ.get", "line_number": 34, "usage_type": "call" }, { "api_name": "os.environ", "line_n...
33109766349
import ctypes import re import os import sys from codegen import clear def extract(): extracts = 0 clear() ctypes.windll.kernel32.SetConsoleTitleW("Loveless.codes | Google Mini Extractor") if not os.path.exists("extracting.txt"): open("extracting.txt", mode='x').close() input('Please paste all your codes as such "link" in extracting.txt\r\n') clear() sys.exit(0) with open("extracting.txt", "r") as extract: for link in extract: b = re.search('.*promoCode=(.*?)$',link) extracted = b.group(1) print(extracted) with open("codes.txt", "a") as saveCode: saveCode.write(extracted + "\n") extracts += 1 ctypes.windll.kernel32.SetConsoleTitleW("Finished! | Extracted: [" + str(extracts) + "]") print("\nExtracted: " + str(extracts) + "\r") print("Done \o/\r") input("Do you want to restart?\r\n")
pepsi/LovelessGen
modules/extractor.py
extractor.py
py
975
python
en
code
0
github-code
36
[ { "api_name": "codegen.clear", "line_number": 8, "usage_type": "call" }, { "api_name": "ctypes.windll.kernel32.SetConsoleTitleW", "line_number": 9, "usage_type": "call" }, { "api_name": "ctypes.windll", "line_number": 9, "usage_type": "attribute" }, { "api_name": ...
25371860228
from plugins.search_engine_scraping_plugin import SearchEngineScrapingPlugin import requests import re from bs4 import BeautifulSoup class DuckDuckGoPlugin(SearchEngineScrapingPlugin): """ This plugin implements a screen scraping for Duck Duck Go search engine""" _url = None def get_results(self, query): """ Gets the first page result from DuckDuckGo search :param query: query for search :type query: string :return: results :rtype: list of dictionaries """ if type(query) is not str: raise TypeError(f"Parameter 'query' is of type {type(query)}. Must be of type string.") query = re.sub(' +', '+', query) self._url = 'https://duckduckgo.com/html/?q={}'.format(query) return self._do_scraping() def do_scraping(self): page = requests.get(self._url) if page.status_code == 200: soup = BeautifulSoup(page.content, 'html.parser') div_results = soup.select('div .result') results = [] for div_result in div_results: div_result.find('div.no-results') result = {} result['title'] = div_result.select('h2.result__title a')[0].text if result['title'] == 'No results.': break result['snippet'] = div_result.select('a.result__snippet')[0].text result['url'] = div_result.find('a', class_='result__snippet').get('href') results.append(result) return results else: raise RuntimeError(f"Error for {query}: {page.status_code}")
willsimoes/projeto-final
plugins/duck_duck_go_plugin.py
duck_duck_go_plugin.py
py
1,675
python
en
code
0
github-code
36
[ { "api_name": "plugins.search_engine_scraping_plugin.SearchEngineScrapingPlugin", "line_number": 7, "usage_type": "name" }, { "api_name": "re.sub", "line_number": 24, "usage_type": "call" }, { "api_name": "requests.get", "line_number": 30, "usage_type": "call" }, { ...
27520193757
from nltk.util import ngrams import nltk f1=open('wsw.txt', 'r') f2=open('posonly.txt', 'w') f3=open('negonly.txt', 'w') for line in f1: if line.split(None, 1)[0] == '+': s=line.split(' ',1)[1] f2.write(s) f1.close() f1=open('wsw.txt', 'r') for line in f1: if line.split(None, 1)[0] == '-': s=line.split(' ',1)[1] f3.write(s) f2.close() f3.close() f2=open('posonly.txt', 'r') f3=open('negonly.txt', 'r') f4=open('posonly1.txt', 'w') f5=open('negonly1.txt', 'w') bgs=[] for line in f2: sentence = line n = 2 bigrams = ngrams(sentence.split(), n) bgs.extend(bigrams) fdist=nltk.FreqDist(bgs) for i,j in fdist.items(): if j>=2: f4.write(i[0]) f4.write(" ") f4.write(i[1]) f4.write(" ") f4.write(str(j)) f4.write("\n") bgs=[] for line in f3: sentence = line n = 2 bigrams = ngrams(sentence.split(), n) bgs.extend(bigrams) fdist=nltk.FreqDist(bgs) for i,j in fdist.items(): if j>=2: f5.write(i[0]) f5.write(" ") f5.write(i[1]) f5.write(" ") f5.write(str(j)) f5.write("\n")
koder951/NLP_Project
6/bigram.py
bigram.py
py
1,026
python
en
code
0
github-code
36
[ { "api_name": "nltk.util.ngrams", "line_number": 37, "usage_type": "call" }, { "api_name": "nltk.FreqDist", "line_number": 39, "usage_type": "call" }, { "api_name": "nltk.util.ngrams", "line_number": 54, "usage_type": "call" }, { "api_name": "nltk.FreqDist", "...
70954832424
#!/usr/bin/env python # -*- coding: utf-8 -*- """Contains an interpreter class that takes raw grayscale data from the picarx grayscale module and maps it to a direction value between -1 and 1. The direction value is determined with a psuedo PD controller.""" import picarx_improved import logging import time import numpy as np import logging logging.basicConfig(format="%(asctime)s:%(message)s", level=logging.INFO, datefmt="%H:%M:%S") logging.getLogger().setLevel(logging.DEBUG) class Interpreter(object): """Class for interpreting the grayscale sensor data into a discrete position. Higher sensor numbers are lighter, lower numbers are darker.""" def __init__(self, proportional_gain=50,derivative_gain=5, line_polarity='darker'): polarity_map = {'darker':1,'lighter':-1} self.line_polarity = polarity_map[line_polarity] if line_polarity == 'darker': self.mostly_under_func = np.argmin else: self.mostly_under_func = np.argmax self.p_gain = proportional_gain / 5000 self.d_gain = derivative_gain / 500 self.running_data = [ [], [], [] ] self.running_aves = [0,0,0] self.deriv_vals = [0,0,0] self.prop_vals = [0,0,0] self.moving_ave_num = 2 self.buffer_full = False self.line_centered = True def reset(self): self.running_data = [ [], [], [] ] self.running_aves = [0,0,0] self.deriv_vals = [0,0,0] self.buffer_full = False def get_direction(self, sensor_data): """Psuedo PD controller to turn sensor data into a direction value between -1 and 1, which is returned.""" mostly_under = self.mostly_under_func(self.running_aves) # The sensor index the target is mostly under. self.line_centered = True if mostly_under == 1 else False if self.buffer_full: # A buffer us used to fill up queues of data to get more reliable readings. for sensor_i in range(len(sensor_data)): self.running_data[sensor_i].append(sensor_data[sensor_i]) del self.running_data[sensor_i][0] ave = np.average(self.running_data[sensor_i]) """The derivative portion of the controller gives values to steer the car in response to the change of the values. There are two relevant scenarios: (1) The target is mostly under an outside sensor, and that sensor is seeing values that are changing away from the target (lighter/darker), and the center sensor is also not changing in the right way. In this case, if the outside sensor is turning less like the target it is about the lose the line (not moving more centered over the line.) Need to steer strongly back towards the outside sensor with the target under it. (which is the opposite response given from case 2.) (2) Else. In all other cases if the outside sensor is becoming less like the target sensor, it is already changing in the right direction. Don't need to turn into the center even more. """ change = ave - self.running_aves[sensor_i] self.deriv_vals[sensor_i] = change * self.d_gain * self.line_polarity *-1 self.running_aves[sensor_i] = ave # negative deriv_vals are changing to be more like the target. The /4 value is a hand picked threshold. if not self.line_centered and self.deriv_vals[mostly_under] > 0 and self.deriv_vals[1] > -self.deriv_vals[mostly_under]/4: # Case 1. The car is about to lose the line, which requires the opposite response. self.deriv_vals.reverse() # Give the opposite response. """The derivative portion of the controller is calculated at this point. Ex. [20,3,-6]. Alone this would result in a steering direction value towards the first sensor (20) and away from the third sensor (-6).""" else: # Buffer isn't full yet. Fill it. buffer_size = self._add_to_buffer(sensor_data) if buffer_size == self.moving_ave_num: self.buffer_full = True direction = 0 return direction # Return a neutral position until buffer fills. # Start calculating the proportional values by multiplying the sensor readings by the polarity and p gain. self.prop_vals = [x*self.line_polarity*self.p_gain for x in self.running_aves] # adjust down so the lowest value is zero. This makes the proportional value robust to different lighting conditions. self.prop_vals = self.prop_vals - np.min(self.prop_vals) self.prop_vals = np.flip(self.prop_vals) # Flip, because that is the way it works out... # Add the proportional and derivative terms to get a reference direction. raw_direction = np.add(self.prop_vals,self.deriv_vals) return self._transform_direction(raw_direction) def _transform_direction(self,direction): """Transform the PD controller reference direction (3 number list) to a single number between -1 and 1.""" direction[0] = direction[0] * -1 direction[1] = 0 direction[2] = direction[2] * 1 direction = np.sum(direction) * self.line_polarity if direction < -1: direction = -1 if direction > 1: direction = 1 return direction def _add_to_buffer(self, sensor_data): for i in range(len(sensor_data)): self.running_data[i].append(sensor_data[i]) ave = np.average(self.running_data[i]) change = ave - self.running_aves[i] self.deriv_vals[i] = change self.running_aves[i] = ave buffer_size = len(self.running_data[0]) return buffer_size def test(): data = [[191, 223, 210],[181, 230, 214],[185, 224, 207],[184, 225, 211],[187, 224, 211],[186, 233, 205], [181, 232, 206],[190, 226, 210],[187, 226, 211],[182, 229, 213],[184, 229, 211],[185, 231, 210], [190, 227, 207],[187, 230, 210],[185, 227, 210]] interpreter = Interpreter() for i in range(len(data)): print(interpreter.get_direction(data[i])) def main(): logging.getLogger().setLevel(logging.INFO) test() if __name__ == '__main__': main()
EverardoG/RobotSystems
lib/line_following_interpreter.py
line_following_interpreter.py
py
6,327
python
en
code
0
github-code
36
[ { "api_name": "logging.basicConfig", "line_number": 12, "usage_type": "call" }, { "api_name": "logging.INFO", "line_number": 12, "usage_type": "attribute" }, { "api_name": "logging.getLogger", "line_number": 13, "usage_type": "call" }, { "api_name": "logging.DEBUG...
7755827639
import asyncio import io import logging from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union from urllib.parse import urlsplit import aiohttp import mercantile from funclib.models import RenderOptions from funclib.raster import ( Bbox, ExportFormats, GDALRaster, PILRaster, Raster, RasterExtent, ) from funclib.settings import BaseExporterSettings from mercantile import Tile from PIL import Image from pccommon.backoff import BackoffStrategy, with_backoff_async logger = logging.getLogger(__name__) T = TypeVar("T", bound=Raster) U = TypeVar("U", bound="TileSet") class TilerError(Exception): def __init__(self, msg: str, resp: aiohttp.ClientResponse): super().__init__(msg) self.resp = resp @dataclass class TileSetDimensions: tile_cols: int tile_rows: int total_cols: int total_rows: int tile_size: int def get_tileset_dimensions(tiles: List[Tile], tile_size: int) -> TileSetDimensions: tile_cols = len(set([tile.x for tile in tiles])) tile_rows = int(len(tiles) / tile_cols) return TileSetDimensions( tile_cols=tile_cols, tile_rows=tile_rows, total_cols=tile_cols * tile_size, total_rows=tile_rows * tile_size, tile_size=tile_size, ) class TileSet(ABC, Generic[T]): def __init__( self, tile_url: str, render_options: RenderOptions, max_concurrency: int = 10, tile_size: int = 512, ) -> None: self.tile_url = tile_url self.render_options = render_options self.tile_size = tile_size self._async_limit = asyncio.Semaphore(max_concurrency) def get_tile_url(self, z: int, x: int, y: int) -> str: url = ( self.tile_url.replace("{x}", str(x)) .replace("{y}", str(y)) .replace("{z}", str(z)) ) url += f"?{self.render_options.encoded_query_string}" return url @abstractmethod async def get_mosaic(self, tiles: List[Tile]) -> T: ... @staticmethod def get_covering_tiles( bbox: Bbox, target_cols: int, target_rows: int, tile_size: int = 512, min_zoom: Optional[int] = None, ) -> List[Tile]: """Gets tiles covering the given geometry at a zoom level that can produce a target_cols x target_rows image.""" if min_zoom: candidate_zoom = min_zoom else: candidate_zoom = 3 while True: sw_tile = mercantile.tile(bbox.xmin, bbox.ymin, candidate_zoom) ne_tile = mercantile.tile(bbox.xmax, bbox.ymax, candidate_zoom) x_diff = ne_tile.x - sw_tile.x y_diff = sw_tile.y - ne_tile.y width = (x_diff - 1) * tile_size height = (y_diff - 1) * tile_size if width < target_cols or height < target_rows: candidate_zoom += 1 else: break return [ tile for tile in mercantile.tiles( bbox.xmin, bbox.ymin, bbox.xmax, bbox.ymax, candidate_zoom ) ] @classmethod async def create( cls: Type[U], cql: Dict[str, Any], render_options: RenderOptions, settings: BaseExporterSettings, data_api_url_override: Optional[str] = None, ) -> U: register_url = settings.get_register_url(data_api_url_override) async with aiohttp.ClientSession() as session: # Register the search and get the tilejson_url back resp = await session.post(register_url, json=cql) mosaic_info = await resp.json() tilejson_href = [ link["href"] for link in mosaic_info["links"] if link["rel"] == "tilejson" ][0] tile_url = f"{tilejson_href}?{render_options.encoded_query_string}" # Get the full tile path template resp = await session.get(tile_url) tilejson = await resp.json() tile_url = tilejson["tiles"][0] scheme, netloc, path, _, _ = urlsplit(tile_url) tile_url = f"{scheme}://{netloc}{path}".replace("@1x", "@2x") return cls(tile_url, render_options) class GDALTileSet(TileSet[GDALRaster]): async def get_mosaic(self, tiles: List[Tile]) -> GDALRaster: raise NotImplementedError() class PILTileSet(TileSet[PILRaster]): async def _get_tile(self, url: str) -> io.BytesIO: async def _f() -> io.BytesIO: async with aiohttp.ClientSession() as session: async with self._async_limit: async with session.get(url) as resp: if resp.status == 200: return io.BytesIO(await resp.read()) else: raise TilerError( f"Error downloading tile: {url}", resp=resp ) try: return await with_backoff_async( _f, is_throttle=lambda e: isinstance(e, TilerError), strategy=BackoffStrategy(waits=[0.2, 0.5, 0.75, 1, 2]), ) except Exception: logger.warning(f"Tile request failed with backoff: {url}") img_bytes = Image.new("RGB", (self.tile_size, self.tile_size), "gray") empty = io.BytesIO() img_bytes.save(empty, format="png") return empty async def get_mosaic(self, tiles: List[Tile]) -> PILRaster: tasks: List[asyncio.Future[io.BytesIO]] = [] for tile in tiles: url = self.get_tile_url(tile.z, tile.x, tile.y) print(f"Downloading {url}") tasks.append(asyncio.ensure_future(self._get_tile(url))) tile_images: List[io.BytesIO] = list(await asyncio.gather(*tasks)) tileset_dimensions = get_tileset_dimensions(tiles, self.tile_size) mosaic = Image.new( "RGBA", (tileset_dimensions.total_cols, tileset_dimensions.total_rows) ) x = 0 y = 0 for i, img in enumerate(tile_images): tile = Image.open(img) mosaic.paste(tile, (x * self.tile_size, y * self.tile_size)) # Increment the row/col position for subsequent tiles if (i + 1) % tileset_dimensions.tile_rows == 0: y = 0 x += 1 else: y += 1 raster_extent = RasterExtent( bbox=Bbox.from_tiles(tiles), cols=tileset_dimensions.total_cols, rows=tileset_dimensions.total_rows, ) return PILRaster(raster_extent, mosaic) async def get_tile_set( cql: Dict[str, Any], render_options: RenderOptions, settings: BaseExporterSettings, format: ExportFormats = ExportFormats.PNG, data_api_url_override: Optional[str] = None, ) -> Union[PILTileSet, GDALTileSet]: """Gets a tile set for the given CQL query and render options.""" # Get the TileSet if format == ExportFormats.PNG: return await PILTileSet.create( cql, render_options, settings, data_api_url_override ) else: return await GDALTileSet.create( cql, render_options, settings, data_api_url_override )
microsoft/planetary-computer-apis
pcfuncs/funclib/tiles.py
tiles.py
py
7,469
python
en
code
88
github-code
36
[ { "api_name": "logging.getLogger", "line_number": 26, "usage_type": "call" }, { "api_name": "typing.TypeVar", "line_number": 28, "usage_type": "call" }, { "api_name": "funclib.raster.Raster", "line_number": 28, "usage_type": "name" }, { "api_name": "typing.TypeVar...
27941619917
import gc import itertools import multiprocessing as mp from math import ceil import numpy as np import pandas as pd from scipy.sparse import csr_matrix from scipy.sparse import issparse from SEMITONES._utils import _chunk_indices from SEMITONES._utils import _linreg_get_beta from SEMITONES._utils import _permute from SEMITONES._utils import _std_sparse from SEMITONES.support_funcs import pairwise_similarities gc.enable() def _enrichment_scoring(X, S, scale_exp, i, n_chunks=None): """Perform the actual enrichment scoring""" n_chunks = 100 if n_chunks is None else n_chunks if len(S.shape) == 2: params = {} for c in range(S.shape[1]): if issparse(X): pars = [] for chunk in _chunk_indices(X, n_chunks, axis=1): pars.extend(np.apply_along_axis(_linreg_get_beta, 0, X[:, chunk].A, S[:, c], scale_exp)) params[c] = pars else: params[c] = np.apply_along_axis(_linreg_get_beta, 0, X, S[:, c], scale_exp) else: if issparse(X): params = [] for chunk in _chunk_indices(X, n_chunks, axis=1): params.extend(np.apply_along_axis(_linreg_get_beta, 0, X[:, chunk].A, S, scale_exp)) else: params = np.apply_along_axis(_linreg_get_beta, 0, X, S, scale_exp) return i, params def calculate_escores(X, query, metric=None, S=None, scale_exp=None, optim_over=None, ncpu=None, n_chunks=None, make_copy=None): """Calculate the enrichment scores for all features with respect to the reference cells in the query. Parameters ---------- X: matrix-like object (n_samples, n_features) An array where the rows are samples (i.e. cells) and the columns are features (i.e. genes). Accepts pandas dataframes, numpy arrays, and scipy compressed sparse row matrix. query: list-like object An iterable which contains the names or indices of the cells with respect to which enrichment scoring should be performed. If providing a pandas dataframe, these should be strings. If providing a numpy array or sparse matrix, these should be indices (int). If providing a matrix S that contains a different metric to rank cells by and X is a dataframe, the strings may be identifiers of the columns in S, even if these do not correspond to any cell (i.e. sample) in X. metric: str, optional If S is None, this metric will be used to calculate the similarity to the reference cell for each cell. Available metrics are those in sklearn.metrics.pairwise_distances and sklearn.metrics.pairwise.pairwise_kernels modules. S: numpy array (n_samples, n_features), optional A similarity matrix where each column represents the similarity to the reference cell for each cell in X. The columns should be ordered as the cells in the query. scale_exp: boolean Whether to scale the expression vector before performing enrichment scores. ncpu: int Number of CPUs the use when using parallel processing. Defaults to 1. optim_over: "cols" or "rows" Choose “cols” if enrichment scores will be computed for many features and “rows” if there are many reference cells in the query. Paralellization over “rows” is only beneficial if enough memory is available. n_chunks: int The number of chunks to divide the feature matrix into when processing a scipy CSR matrix. If memory is limited, choosing a higher number of chunks might be beneficial. Defaults to n_features * 0.01 rounded up to the first integer. Returns ------- A pandas dataframe of enrichment scores of size (n_features, n_reference_cells).""" # set the default parameters metric = "cosine" if metric is None else metric scale_exp = True if scale_exp is None else scale_exp if optim_over is None: if X.shape[1] > len(query): optim_over = "cols" else: optim_over = "rows" if n_chunks is None: n_chunks = ceil(X.shape[1] * 0.01) if n_chunks is None else n_chunks ncpu = 1 if ncpu is None else ncpu make_copy = True if make_copy is None else make_copy if make_copy is True: X = X.copy() if isinstance(X, pd.DataFrame): cells, genes = X.index, X.columns if all(i in cells for i in query): query = [X.index.get_loc(i) for i in query] X = X.values if S is None: print("Calculating pairwise similarities") S = pairwise_similarities(X, query, metric) else: S = S if ncpu > 1: print("Start enrichment scoring using {0} CPUs".format(ncpu)) print("Creating process pool") with mp.Pool(processes=ncpu) as pool: if optim_over == "cols": i_chunks = _chunk_indices(X, n=ncpu, axis=1) mpres = [pool.apply_async(_enrichment_scoring, args=(X[:, i], S, scale_exp, i, n_chunks)) for i in i_chunks] else: i_chunks = _chunk_indices(S, n=ncpu, axis=1) mpres = [pool.apply_async(_enrichment_scoring, args=(X, S[:, i], scale_exp, i, n_chunks)) for i in i_chunks] print("Run enrichment scoring") mpres = [r.get() for r in mpres] pool.close() pool.join() print("Enrichment scoring complete") else: print("Start enrichment scoring") i_chunks = _chunk_indices(X, n=2, axis=1) mpres = [_enrichment_scoring(X[:, i], S, scale_exp, i, n_chunks) for i in i_chunks] print("Enrichment scoring complete") if "cells" in locals(): rows = [list(mpres[i][0]) for i in range(len(mpres))] rows = [genes[i] for i in itertools.chain.from_iterable(rows)] if all(cells[item] in cells for item in query): cols = [cells[i] for i in query] else: cols = query else: rows = [list(mpres[i][0]) for i in range(len(mpres))] rows = list(itertools.chain.from_iterable(rows)) cols = query scores = [pd.DataFrame(mpres[i][1]) for i in range(len(mpres))] if (optim_over == "rows") and (ncpu > 1): scores = pd.concat(scores, axis=1) if "genes" in locals(): scores.index, scores.columns = genes, cols else: scores.columns = cols else: scores = pd.concat(scores, axis=0) scores.index, scores.columns = rows, cols return scores def permute(X, n=None, axis=None, seed=None): """Permute a dataframe n times. Parameters ---------- X: a matrix-like object A matrix-like object where rows are samples (i.e. cells) and columns are features (i.e. genes). Accepts pandas dataframes, numpy arrays, and scipy compressed sparse row matrices. n: int The number of times to permute the dataframe seed: int The seed to pass to numpy.random for reproducibility axis: 0 or 1 Whether to permute the rows or columns of the dataframe. 0 corresponds to permuting the expression vectors of a feature matrix of shape (n_samples, n_features). Returns: an n-times permuted matrix of shape X.""" n = 100 if n is None else n seed = 42 if seed is None else seed axis = 0 if axis is None else axis return _permute(X, n=n, axis=axis, seed=seed) def sig_interval(pscores, n_sds, query=None): """Returns a dictionary {query cell: (lower, upper} of enrichment score significance cut-off below (lower) and above (upper) which the scores are significant at a certain standard deviation (n_sds) away from the mean of the permutation enrichment scores. Parameters ---------- pscores: pandas dataframe A pandas dataframe of enrichment scores obtained from permuted expression vectors (e.g. from permute(X)). through the permute() function. n_sds: int The number of standard deviations away from the mean of the pscores at which to declare significance. Defaults to 5. query: list-like A list of reference cells corresponding to the columns in the pscores dataframe. Returns ------- A dictionary of the shape {cell: (lower, upper)} """ n_sds = 5 if n_sds is None else n_sds if issparse(pscores): if query is None: print("Outputting cut-offs in order. Please provide a" + " query in order if you want to use labels as keys.") if pscores.getformat() not in ["csr", "csc"]: pscores = pscores.to_csr() mu = np.array(pscores.mean(axis=0)) std = _std_sparse(pscores, axis=0, ddof=1) else: mu, std = np.mean(pscores, axis=0), np.std(pscores, axis=0, ddof=1) if not issparse(pscores): query = pscores.columns else: query = list(range(pscores.shape[1])) return dict(zip(query, zip(mu - std * n_sds, mu + std * n_sds))) def _min_set(X, sets, i=None): """Return the min value of each set as expression value""" if issparse(X): return i, csr_matrix([np.amin(X[:, s].A, 1) for s in sets]).T else: return i, csr_matrix([np.amin(X[:, s], 1) for s in sets]).T def _max_set(X, sets, i=None): """Return the max value of each set as expression value""" if issparse(X): return i, csr_matrix([np.amax(X[:, s].A, 1) for s in sets]).T else: return i, csr_matrix([np.amax(X[:, s], 1) for s in sets]).T def _median_set(X, sets, i=None): """Return the median value of each set as expression value""" if issparse(X): return i, csr_matrix([np.median(X[:, s].A, 1) for s in sets]).T else: return i, csr_matrix([np.median(X[:, s], 1) for s in sets]).T def _interaction_set(X, sets, i=None): """Return the expression product of each set as expression value""" if issparse(X): return i, csr_matrix([np.prod(X[:, s].A, 1) for s in sets]).T else: return i, csr_matrix([np.prod(X[:, s], 1) for s in sets]).T def _binary_set(X, sets, i=None): if issparse(X): gse = csr_matrix([np.sum(X[:, s].A, 1) for s in sets]).T else: gse = csr_matrix([np.sum(X[:, s], 1) for s in sets]).T gse[gse > 1] = 1 return i, gse def feature_set_values(X, sets, combtype): """Combines feature values for all elements in a set. Parameters ---------- X: matrix-like A matrix-like object where rows are samples (i.e. cells) and columns are features (i.e. genes). Accepts numpy arrays, pandas dataframes and scipy compressed sparse row matrices. sets: iterable of tuples An iterable of tuples (i, …, n) where i is the column index of feature 1 and n is the column index of feature n. combtype: str - “min”: set the feature set value to be the element-wise minimum of the feature vectors. - “max”: set the feature set value to be the element-wise maximum of the feature vectors. - “median”: set the feature value to be the element-wise median of the feature vectors. - “interaction”: set the feature value to be the element-wise product of the feature vectors. - “binary”: set the feature value to 1 if at least one of the features is present and 0 if none are present. Returns ------- A matrix-like object (n_samples, sets) of feature vectors (columns) for each set in sets.""" if isinstance(X, pd.DataFrame): X = X.values if (issparse(X)) and (X.getformat() not in ["csr", "csc"]): X = X.tocsr() print("Constructing expression set") if combtype == "min": return _min_set(X, sets)[1] elif combtype == "max": return _max_set(X, sets)[1] elif combtype == "median": return _median_set(X, sets)[1] elif combtype == "interaction": return _interaction_set(X, sets)[1] elif combtype == "binary": return _binary_set(X, sets)[1] def pvals_per_cell(escores, pscores, mt_cor=None, alpha=None, ret=None): """Computes the p-value with respect to a permutation null for each gene in each reference cell. ----- escores: matrix-like A np.array or pd.DataFrame that contains the enrichment scores for each gene (row) in each reference cell (column) pscores: matrix-like A np.array or pd.DataFrame that contains the enrichment scores for each permutated gene (row) in each reference cell (column). mt_cor: str The method by which to perform multiple testing correction. alpha: float Family-wise error rate. ret: str Whether to return p-values ("p"), corrected p-values ("q"), or both ("pq"). Defaults to corrected p-values ("q"). ----- Returns: a pd.DataFrame of p-values, corrected p-values, or both. """ from scipy.stats import norm from statsmodels.sandbox.stats.multicomp import multipletests mt_cor = "bonferroni" if mt_cor is None else mt_cor alpha = .05 if alpha is None else alpha ret = "q" if ret is None else ret if isinstance(escores, pd.DataFrame): genes, cells, escores = escores.index, escores.columns, escores.values mu, sigma = np.mean(pscores, axis=0), np.std(pscores, axis=0, ddof=1) pvals = 2 * (1 - norm.cdf(abs(escores), loc=mu, scale=sigma)) if (ret == "q") or (ret == "pq"): pvals_cor = [] for i in range(pvals.shape[1]): pvals_cor.append(multipletests(pvals[:, i], alpha=alpha, method=mt_cor)[1]) # make corrected p-value dataframe if "cells" in locals(): pvals_cor = pd.DataFrame(pvals_cor, columns=genes, index=cells).T else: pvals_cor = pd.DataFrame(pvals_cor).T if (ret == "pq") or (ret == "p"): if "cells" in locals(): pvals = pd.DataFrame(pvals, index=genes, columns=cells) else: pvals = pd.DataFrame(pvals) # return the appropiate dataframe if ret == "q": return pvals_cor elif ret == "pq": return pvals, pvals_cor else: return pvals def pvals_per_gene(escores, pscores, mt_cor="bonferroni", alpha=0.05): """Computes a p-value per gene. ----- escores: matrix-like A np.array or pd.DataFrame that contains the enrichment scores for each gene (row) in each reference cell (column) pscores: matrix-like A np.array or pd.DataFrame that contains the enrichment scores for each permutated gene (row) in each reference cell (column). mt_cor: str The method by which to perform multiple testing correction. alpha: float Family-wise error rate. ret: str Whether to return p-values ("p"), corrected p-values ("q"), or both ("pq"). Defaults to corrected p-values ("q"). ----- Returns: a pd.DataFrame of p-values, corrected p-values, or both. """ from scipy.stats import ks_2samp from statsmodels.stats.multitest import multipletests mt_cor = "bonferroni" if mt_cor is None else mt_cor alpha = .05 if alpha is None else alpha if isinstance(escores, pd.DataFrame): egenes, ecells, escores = escores.index, escores.columns, escores.values if isinstance(pscores, pd.DataFrame): pgenes, pcells, pscores = pscores.index, pscores.columns, pscores.values n = escores.shape[0] ks = [ks_2samp(escores[i, :], pscores[i, :]) for i in range(n)] ks = pd.DataFrame(data=[(d, k) for d, k in ks], columns=["d", "p"]) if "egenes" in locals(): ks.index = egenes r, q, s, b = multipletests(ks.loc[:, "p"], alpha, method=mt_cor) ks["q"] = q return ks
ohlerlab/SEMITONES
src/SEMITONES/enrichment_scoring.py
enrichment_scoring.py
py
16,684
python
en
code
8
github-code
36
[ { "api_name": "gc.enable", "line_number": 17, "usage_type": "call" }, { "api_name": "scipy.sparse.issparse", "line_number": 27, "usage_type": "call" }, { "api_name": "SEMITONES._utils._chunk_indices", "line_number": 29, "usage_type": "call" }, { "api_name": "numpy...
27888263770
from django.db import models from django.core.exceptions import ValidationError def validate_thumbnail_size(field_file_obj): file_size = field_file_obj.file.size kilobyte_limit = 256 if file_size >= kilobyte_limit * 1024: raise ValidationError(f"This image is {file_size / 1024}kb. Please make sure it is less than 256kb.") class CreationModificationDateBase(models.Model): """ Abstract base class with a creation and modification date and time """ created = models.DateTimeField( "Creation Date and Time", auto_now_add=True, ) modified = models.DateTimeField( "Modification Date and Time", auto_now=True, ) class Meta: abstract = True
theorangeyakco/sarpanch
content/utils.py
utils.py
py
700
python
en
code
2
github-code
36
[ { "api_name": "django.core.exceptions.ValidationError", "line_number": 10, "usage_type": "call" }, { "api_name": "django.db.models.Model", "line_number": 13, "usage_type": "attribute" }, { "api_name": "django.db.models", "line_number": 13, "usage_type": "name" }, { ...
13097952438
# !/usr/bin/env python # -*- coding: utf-8 -*- """ @author: lishuang @description: 绘制 sigmoid 函数 """ import numpy as np import matplotlib.pyplot as plt def sigmoid(x): """ sigmoid 函数 :param x: :return: """ y = 1 / (1 + np.exp(-x)) return y def derivative_sigmoid(x): """ sigmoid 函数的导数 :param x: :return: """ y = sigmoid(x) dy = y * (1 - y) return dy def plot_sigmoid(is_derivative): # 设置参数 x(起点,终点,间距) x = np.arange(-8, 8, 0.2) if is_derivative: y = derivative_sigmoid(x) else: y = sigmoid(x) plt.plot(x, y) plt.show() if __name__ == '__main__': plot_sigmoid(False)
TatenLee/machine-learning
bi/core/l7/activation_function/sigmoid.py
sigmoid.py
py
733
python
en
code
1
github-code
36
[ { "api_name": "numpy.exp", "line_number": 20, "usage_type": "call" }, { "api_name": "numpy.arange", "line_number": 38, "usage_type": "call" }, { "api_name": "matplotlib.pyplot.plot", "line_number": 44, "usage_type": "call" }, { "api_name": "matplotlib.pyplot", ...
22753766688
"""Deep_acsauto package definition""" from setuptools import setup, find_packages from __init__ import __version__ # Read long description from file with open("README.md", "r") as fh: LONG_DESCRIPTION = fh.read() setup( name="DeepACSA", version=__version__, description=( "Anatomical cross-sectional area evalutaion in Ultrasound images." ), long_description=LONG_DESCRIPTION, long_description_content_type="text/markdown", url="https://github.com/PaulRitsche/ACSAuto_DeepLearning", author="Paul Ritsche", author_email="paul.ritsche@unibas.ch", maintainers=["Paul Ritsche", "Philipp Wirth", "Neil Cronin"], maintainers_email=["paul.ritsche@unibas.ch", "philipp.m.wirth@gmail.com", "neil.cronin@jyu.fi"], classifiers=[ "Environment :: Console", "Intended Audience :: Science/Research", "License :: ", "Natural Language :: English", "Programming Language :: Python :: 3.8", "Topic :: Scientific/Engineering :: Physiology", "Topic :: Utilities", ], entry_points={ 'console_scripts': [ 'deep_acsa = deep_acsa_gui:main', ], }, keywords=[ 'ultrasound', 'physiology', 'deep learning', 'muscle', ], project_urls={ "Github": "https://github.com/PaulRitsche/DeepACSA.git", }, packages=find_packages(), include_package_data=True, setup_requires=[ "setuptools_git == 1.2", ], )
maxull/Sharples-Lab
DeepACSA/DeepACSA-main/setup.py
setup.py
py
1,552
python
en
code
2
github-code
36
[ { "api_name": "setuptools.setup", "line_number": 11, "usage_type": "call" }, { "api_name": "__init__.__version__", "line_number": 13, "usage_type": "name" }, { "api_name": "setuptools.find_packages", "line_number": 49, "usage_type": "call" } ]
30292556243
from mesa import Agent from src.agents import Environment, Food from src.utils import calculate_distance, get_item, random_move FORAGING = 'PROCURANDO' HOMING = 'VOLTANDO' class ForagingAnt(Agent): def __init__(self, current_id, model, pos, color): super().__init__(current_id, model) self.state = FORAGING self.home = pos self.pos = pos self.age = self.model.ant_max_age + self.random.randrange(75, 200) self.color = color self.with_food = False self.go_home = self.random.randrange(100, 200) def step(self): if self.age <= 0: food = Food( self.model.next_id(), self.model, self.pos, self.model.food_group ) self.model.register(food) self.model.kill_agents.append(self) return food = get_item(self, Food) # Procurando comida if self.state == FORAGING: # Não encontrou comida if not food: self.go_home -= 1 # Se o mãximo de exploração foi atingido, volta pra casa if self.go_home <= 0: self.home_move() self.state = HOMING # Randomiza e calcula a chance de seguir pelo feromônio elif self.random.random() > self.model.random_change_to_move: self.food_move() # Se não, movimento aleatório else: random_move(self) # Achou comida, volta pra casa com ela else: food.eat() self.age *= (1 + (self.model.ant_age_gain / 100)) e = get_item(self, Environment) e.food_smell = 0 self.with_food = True self.state = HOMING # Voltando para casa elif self.state == HOMING: # Enquanto não estiver em casa if self.pos != self.home: e = get_item(self, Environment) # Se estiver carregando comida, deposita feromônio if self.with_food: e.deposit_pheromone() self.home_move() # Se não, tiver comida e achar um caminho ou comida, faz o movimento de comida elif food or e.pheromone > 0 or e.food_smell: self.state = FORAGING self.food_move() # Se não, só volta pra casa else: self.home_move() # Estando em casa, volta a procurar comida else: self.go_home = self.random.randrange(100, 200) self.with_food = False self.state = FORAGING self.age -= 1 # Procura caminhos para voltar pra casa, para não ser ideal usa # o segundo melhor caminho encontrado. Se o melhor caminho for # a sua casa, usa ele def home_move(self): possible_home = [ (calculate_distance(agent.pos, self.home), agent.pos) for agent in self.model.grid.get_neighbors(self.pos, True) if type(agent) is Environment ] possible_home.sort(key=(lambda i: i[0])) if possible_home[0][1] == self.home: self.model.grid.move_agent(self, possible_home[0][1]) else: self.model.grid.move_agent(self, possible_home[1][1]) # Procura feromônios def food_move(self): food_smells = [] food_points = [] possible_food = [] neighbors = self.model.grid.get_neighbors(self.pos, True) for agent in neighbors: # Salva se o vizinho for um ponto de comida if type(agent) is Food: food_points.append(agent.pos) else: # Se não, só salva se tiver feromônio if type(agent) is Environment and agent.pheromone > 0: possible_food.append((agent.pheromone, agent.pos)) # Se não, só salva se tiver cheiro de comida if type(agent) is Environment and agent.food_smell > 0: food_smells.append((agent.food_smell, agent.pos)) # Se tiver encontrado comida, randomiza e usa um desses pontos if food_points: self.model.grid.move_agent(self, food_points[0]) # Se não tiver encontrado nem comida, nem feromônio e nem cheiro movimenta aleatoriamente elif not possible_food and not food_smells: random_move(self) # Se tiver encontrado cheiro de comida, segue pelo cheiro elif not possible_food: food_smells = max( food_smells, key=(lambda i: i[0]) ) self.model.grid.move_agent(self, food_smells[1]) # Se não, usa o caminho com a menor quantidade de feromônio e que # se encontra mais distante de casa. else: possible_food = min( possible_food, key=(lambda i: i[0] - (10 * calculate_distance(i[1], self.home))) ) if possible_food[0] > self.model.min_pheromone_needed: self.model.grid.move_agent(self, possible_food[1]) else: random_move(self)
UnBParadigmas2022-1/2022.1_G3_SMA_Formigueiro
src/agents/foragingAgent.py
foragingAgent.py
py
5,369
python
pt
code
6
github-code
36
[ { "api_name": "mesa.Agent", "line_number": 11, "usage_type": "name" }, { "api_name": "src.agents.Food", "line_number": 25, "usage_type": "call" }, { "api_name": "src.utils.get_item", "line_number": 34, "usage_type": "call" }, { "api_name": "src.agents.Food", "...
70010914665
import urllib.request import ssl import json ssl._create_default_https_context = ssl._create_unverified_context def search(keyword): client_id = "BoqP7ttLY0wDhxvLzawS" client_secret = "ztLCPvpLyO" encText = urllib.parse.quote(keyword) url = "https://openapi.naver.com/v1/search/blog?query=" + encText request = urllib.request.Request(url) request.add_header("X-Naver-Client-Id", client_id) request.add_header("X-Naver-Client-Secret", client_secret) response = urllib.request.urlopen(request) rescode = response.getcode() if (rescode == 200): response_body = response.read() result = response_body.decode('utf-8') result = json.loads(result) return result['items'] else: print("Error Code:" + rescode) return None result = search("라디오 스타") print(result)
Kyeongrok/python_yla
com/week7/am/naver_openapi8.py
naver_openapi8.py
py
862
python
en
code
1
github-code
36
[ { "api_name": "ssl._create_default_https_context", "line_number": 5, "usage_type": "attribute" }, { "api_name": "ssl._create_unverified_context", "line_number": 5, "usage_type": "attribute" }, { "api_name": "urllib.request.parse.quote", "line_number": 12, "usage_type": "c...
72514606824
import logging import os import sys import tempfile import warnings from contextlib import contextmanager from collections import defaultdict from datetime import datetime, timedelta, timezone from itertools import chain from subprocess import CalledProcessError from urllib.parse import urljoin, urlsplit, urlunsplit import requests from yaml import load log = logging.getLogger('keystone_light') log.addHandler(logging.NullHandler()) # ====================================================================== # OpenStack Keystone # ---------------------------------------------------------------------- # cloud = Cloud(CloudsYamlConfig('cloudX')) # or: # cloud = Cloud(DirectConfig('https://domain:user:pass@...')) # ====================================================================== class PermissionDenied(Exception): def __init__(self, method, url, status_code, response): self.args = (method, url, status_code, response) class ObjectNotFound(Exception): pass class MultipleObjectsFound(Exception): pass def the_one_entry(list_, type_, params): if not list_: raise ObjectNotFound( 'lookup of {} with params {} yielded nothing'.format( type_, params)) if len(list_) > 1: raise MultipleObjectsFound( 'lookup of {} with params {} yielded multiple results: {}'.format( type_, params, list_)) return list_[0] class CloudsYamlConfig: """ Reads ~/.config/openstack/clouds.yaml and selects one Example file contents:: clouds: # v-- this would be the selected os_cloud='my-cloud-admin' my-cloud-admin: auth: auth_url: https://KEYSTONE/ system_scope: all user_domain_name: DOMAIN username: USERNAME password: PASSWORD identity_api_version: 3 region_name: NL1 """ def __init__(self, os_cloud): with open(os.path.expanduser('~/.config/openstack/clouds.yaml')) as fp: clouds_yaml = load(fp.read()) self.user_info = clouds_yaml['clouds'][os_cloud] assert self.user_info['identity_api_version'] == 3, self.user_info def get_auth_url(self): return self.user_info['auth']['auth_url'] def as_user_password(self): auth = self.user_info['auth'] password = { 'user': { 'name': auth['username'], 'domain': { 'name': auth['user_domain_name'], }, 'password': auth['password'], }, } return password def __str__(self): return str(self.user_info) class CloudConfig(CloudsYamlConfig): """ Old name for CloudsYamlConfig """ def __init__(self, *args, **kwargs): warnings.warn( 'CloudConfig is deprecated, please use CloudsYamlConfig', DeprecationWarning, stacklevel=2) super().__init__(*args, **kwargs) class DirectConfig: """ Direct config, by passing https://<DOMAIN>:<USER>:<PASS>@KEYSTONE """ def __init__(self, auth_url): parts = urlsplit(auth_url) self._auth_url = urlunsplit(( parts.scheme, ('{}:{}'.format(parts.hostname, parts.port) if parts.port else parts.hostname), parts.path, parts.query, parts.fragment)) domain, password = parts.username, parts.password assert ':' not in domain, domain assert ':' in password, 'expected <domain>:<user>:<pass>' self._user_domain_name = domain self._username, self._password = password.split(':', 1) def get_auth_url(self): return self._auth_url def as_user_password(self): password = {'user': { 'name': self._username, 'domain': {'name': self._user_domain_name}, 'password': self._password, }} return password class CloudToken: def __init__(self, unscoped_token=None, cloud_config=None, scope=None): self.unscoped_token = unscoped_token self.cloud_config = cloud_config self.scope = scope self.base_url = None self.data = None self.expires_at = None self.token = None self.renew() def renew(self): if self.unscoped_token: assert not self.cloud_config base_url = self.unscoped_token.base_url post_data = { 'auth': { 'identity': { 'methods': ['token'], 'token': { 'id': str(self.unscoped_token), }, }, }, } elif self.cloud_config: assert not self.unscoped_token base_url = self.cloud_config.get_auth_url() post_data = { 'auth': { 'identity': { 'methods': ['password'], 'password': self.cloud_config.as_user_password(), }, }, } else: raise TypeError('expect unscoped_token OR cloud_config') if self.scope: post_data['auth']['scope'] = self.scope # Optional "?nocatalog", but then we won't get the catalog, # which we need for project endpoints. url = urljoin(base_url, '/v3/auth/tokens') headers = {} if self.unscoped_token: headers['X-Auth-Token'] = str(self.unscoped_token) out = requests.post(url, json=post_data, headers=headers) if out.status_code == 401: raise PermissionDenied('POST', url, out.status_code, out.text) try: assert out.status_code == 201 out_token = out.headers['X-Subject-Token'] out_data = out.json() except (AssertionError, KeyError): # FIXME: auth leak to logging in case of errors. log.debug(out) log.debug(out.headers) log.debug(out.content) raise self.base_url = base_url self.data = out_data.pop('token') expires_at = self.data.get('expires_at') if expires_at is not None: if expires_at.endswith('Z'): expires_at = expires_at[:-1] + '+00:00' expires_at = datetime.fromisoformat(expires_at) self.expires_at = expires_at assert not out_data, out_data self.token = out_token def will_expire_within(self, **kwargs): if self.expires_at is not None: utcnow = datetime.now(timezone.utc) if utcnow + timedelta(**kwargs) > self.expires_at: return True return False def __str__(self): if self.will_expire_within(minutes=2): log.debug('token will expire at %s, force renew', self.expires_at) self.renew() return self.token class Cloud: def __init__(self, cloud_config): self.base_url = cloud_config.get_auth_url() self.cloud_config = cloud_config self._unscoped_token = None self._system_token = None self._domain_tokens = {} self._project_tokens = {} self._endpoints = {} self._domains = {} def get_roles(self): if not hasattr(self, '_get_roles'): system_token = self.get_system_token() url = urljoin(self.base_url, '/v3/roles') out = requests.get( url=url, headers={'X-Auth-Token': str(system_token)}) self._get_roles = [ Role.from_keystone(i, cloud=self) for i in out.json()['roles']] return self._get_roles def get_role(self, name=None): roles = self.get_roles() if name is not None: roles = [i for i in roles if i.name == name] return the_one_entry(roles, 'role', dict(name=name)) def get_domains(self): """ Get domains from SYSTEM scope """ if not hasattr(self, '_get_domains'): system_token = self.get_system_token() url = urljoin(self.base_url, '/v3/domains') out = requests.get( url=url, headers={'X-Auth-Token': str(system_token)}) for data in out.json()['domains']: if data['id'] not in self._domains: self._domains[data['id']] = Domain.from_keystone( data, cloud=self) self._get_domains = self._domains.values() return self._get_domains def get_domain(self, name=None, domain_id=None): """ Get domains by name or id """ # If we have it in cache, return immediately, or create one if # we have all the values. if domain_id in self._domains: return self._domains[domain_id] if name and domain_id: ret = Domain(name=name, id=domain_id, enabled=True) ret.cloud = self self._domains[domain_id] = ret return ret # Otherwise, fetch the SYSTEM domains and filter by args. domains = self.get_domains() if name is not None: domains = [i for i in domains if i.name == name] if domain_id is not None: domains = [i for i in domains if i.id == domain_id] return the_one_entry( domains, 'domain', dict(name=name, domain_id=domain_id)) def get_groups(self, domain_id=None): if not hasattr(self, '_get_groups'): system_token = self.get_system_token() url = urljoin(self.base_url, '/v3/groups') out = requests.get( url=url, headers={'X-Auth-Token': str(system_token)}) groups = [ Group.from_keystone(i, cloud=self) for i in out.json()['groups']] groups_by_domain = defaultdict(list) for group in groups: groups_by_domain[group.domain_id].append(group) self._get_groups = groups_by_domain if domain_id: return self._get_groups[domain_id] return list(chain(*self._get_groups.values())) def get_group(self, name=None, domain_id=None): groups = self.get_groups() if name is not None: groups = [i for i in groups if i.name == name] if domain_id is not None: groups = [i for i in groups if i.domain_id == domain_id] return the_one_entry( groups, 'group', dict(name=name, domain_id=domain_id)) def get_projects(self, domain_id=None): """ Get projects from SYSTEM scope """ if not hasattr(self, '_get_projects'): system_token = self.get_system_token() url = urljoin(self.base_url, '/v3/projects') out = requests.get( url=url, headers={'X-Auth-Token': str(system_token)}) projects = [ Project.from_keystone(i, cloud=self) for i in out.json()['projects']] projects_by_domain = defaultdict(list) for project in projects: projects_by_domain[project.domain_id].append(project) self._get_projects = projects_by_domain if domain_id: return self._get_projects[domain_id] return list(chain(*self._get_projects.values())) def get_current_project(self): """ Get CURRENT project that belongs to this user """ if not hasattr(self, '_get_current_project'): # We expect this in the unscoped_token.data: # "project": { # "name": "x", "domain": {"name": "x", "id": "abc123"}, # "id": "abc123"} data = self.get_unscoped_token().data keystone_dict = { 'id': data['project']['id'], 'name': data['project']['name'], 'enabled': True, 'is_domain': data['is_domain'], # not on project...? 'domain_id': data['project']['domain']['id'], } self.get_domain( # the get_domain() creates on in cache name=data['project']['domain']['name'], domain_id=data['project']['domain']['id']) project = Project.from_keystone(keystone_dict, cloud=self) self._get_current_project = project return self._get_current_project def get_unscoped_token(self): if not self._unscoped_token: self._unscoped_token = CloudToken(cloud_config=self.cloud_config) return self._unscoped_token def get_system_token(self): if not self._system_token: system_scope = {'system': {'all': True}} unscoped_token = self.get_unscoped_token() self._system_token = CloudToken( unscoped_token=unscoped_token, scope=system_scope) for catalog_row in self._system_token.data.get('catalog', []): type_, name = catalog_row['type'], catalog_row['name'] self.update_endpoints( (type_, name, 'system', 'all'), catalog_row['endpoints']) return self._system_token def get_domain_token(self, domain_id): if domain_id not in self._domain_tokens: domain_scope = {'domain': {'id': domain_id}} unscoped_token = self.get_unscoped_token() domain_token = CloudToken( unscoped_token=unscoped_token, scope=domain_scope) for catalog_row in domain_token.data.get('catalog', []): type_, name = catalog_row['type'], catalog_row['name'] self.update_endpoints( (type_, name, 'domain', domain_id), catalog_row['endpoints']) self._domain_tokens[domain_id] = domain_token return self._domain_tokens[domain_id] def get_project_token(self, project_id): if project_id not in self._project_tokens: project_scope = {'project': {'id': project_id}} unscoped_token = self.get_unscoped_token() project_token = CloudToken( unscoped_token=unscoped_token, scope=project_scope) for catalog_row in project_token.data.get('catalog', []): type_, name = catalog_row['type'], catalog_row['name'] self.update_endpoints( (type_, name, 'project', project_id), catalog_row['endpoints']) self._project_tokens[project_id] = project_token return self._project_tokens[project_id] def update_endpoints(self, key, endpoints): # endpoints = [{"id": "c3f2..", "interface": "public", # "region_id": "NL1", "url": "https://KEYSTONE/v3/", "region": "NL1"}] assert key not in self._endpoints, (key, self._endpoints) # print('<endpoints>', key, endpoints) self._endpoints[key] = endpoints class Role: @classmethod def from_keystone(cls, data, cloud): # data = {"id": "7931..", "name": "admin", # "domain_id": None, "description": None, "options": {}, # "links": {"self": "http://KEYSTONE/v3/roles/7931.."}} ret = cls( name=data['name'], id=data['id'], domain_id=data['domain_id']) ret.cloud = cloud return ret def __init__(self, name, id, domain_id): self.name = name self.id = id self.domain_id = domain_id def __repr__(self): return '<Role({})>'.format(self.name) class Domain: @classmethod def from_keystone(cls, data, cloud): # data = {"id": "b49d...", "name": "DOMAIN", "description": "", # "enabled": True, "tags": [], "options": {}, # "links": {"self": "http://KEYSTONE/v3/domains/b49d..."}} ret = cls(name=data['name'], id=data['id'], enabled=data['enabled']) ret.cloud = cloud return ret def __init__(self, name, id, enabled): self.name = name self.id = id self.enabled = enabled def get_admin_group(self): """ WARNING: This is a configuration choice. We choose to have an admin group named DOMAIN-admins. This group should exist. """ groups = [ i for i in self.get_groups() if i.name == '{}-admins'.format(self.name)] if len(groups) != 1: raise ValueError( 'expected a single {o.name}-admins group ' 'in domain {o.name} [domain_id={o.id}]'.format(o=self)) return groups[0] def get_groups(self): return self.cloud.get_groups(domain_id=self.id) def get_projects(self): return self.cloud.get_projects(domain_id=self.id) def __repr__(self): return '<Domain({})>'.format(self.name) class Group: @classmethod def from_keystone(cls, data, cloud): # data = {"id": "19d9..", "name": "admins", "domain_id": "default", # "description": "", # "links": {"self": "http://KEYSTONE/v3/groups/19d9..."}} ret = cls( name=data['name'], id=data['id'], domain_id=data['domain_id']) ret.cloud = cloud return ret def __init__(self, name, id, domain_id): self.name = name self.id = id self.domain_id = domain_id def __repr__(self): return '<Group({})>'.format(self.name) class Project: @classmethod def from_keystone(cls, data, cloud): # data = {"id": "d304..", "name": "admin", "domain_id": "default", # "description": "Bootstrap..", "enabled": true, # "parent_id": "default", "is_domain": false, "tags": [], # "options": {}, # "links": {"self": "http://KEYSTONE/v3/projects/d304.."}} ret = cls( name=data['name'], id=data['id'], enabled=data['enabled'], domain_id=data['domain_id']) ret.cloud = cloud return ret def __init__(self, name, id, enabled, domain_id): self.name = name self.id = id self.enabled = enabled self.domain_id = domain_id def __repr__(self): return '<Project({})>'.format(self.name) def get_fullname(self): return '{}:{}'.format(self.get_domain().name, self.name) def get_domain(self): return self.cloud.get_domain(domain_id=self.domain_id) def get_swift(self): key = ('object-store', 'swift', 'project', self.id) # Getting the project token ensures we get the endpoint in the # endpoints dict. project_token = self.cloud.get_project_token(self.id) del project_token endpoints = self.cloud._endpoints[key] # FIXME: encapsulation! endpoints = [i for i in endpoints if i['interface'] == 'public'] endpoint = the_one_entry(endpoints, 'endpoints', dict()) return Swift.from_keystone( endpoint, project_id=self.id, cloud=self.cloud) # ====================================================================== # OpenStack Swift # ---------------------------------------------------------------------- # swift = cloud.get....project().get_swift() # ====================================================================== class SwiftFileExistsError(FileExistsError): def __init__(self, filename, strerror): EEXIST = 17 super().__init__(EEXIST, filename) self._strerror = strerror def __str__(self): return self._strerror class SwiftFileNotFoundError(FileNotFoundError): def __init__(self, filename, strerror): ENOENT = 2 super().__init__(ENOENT, filename) self._strerror = strerror def __str__(self): return self._strerror class Swift: @classmethod def from_keystone(cls, data, project_id, cloud): # data = {"id": "8888..", "interface": "admin", # "url": "https://SWIFT/v1", "region": "NL1"} ret = cls(id=data['id'], url=data['url'], region=data['region']) ret.project_id = project_id ret.cloud = cloud return ret def __init__(self, id, url, region): self.id = id self.url = url self.region = region def _mkurl(self, *args): if args: return '{}/{}'.format(self.url, '/'.join(args)) return self.url def _mkhdrs(self, json=False): project_token = self.cloud.get_project_token(self.project_id) headers = {'X-Auth-Token': str(project_token)} if json: # text/plain, application/json, application/xml, text/xml headers['Accept'] = 'application/json' return headers def get_stat(self): url, hdrs = self._mkurl(), self._mkhdrs() out = requests.head(url, headers=hdrs) if out.status_code == 403: # "We" need to give ourselves permission, if possible. raise PermissionDenied('HEAD', url, out.status_code, out.text) return out.headers def get_containers(self): url, hdrs = self._mkurl(), self._mkhdrs(json=True) out = requests.get(url, headers=hdrs) if out.status_code != 200: raise PermissionDenied('GET', url, out.status_code, out.text) # headers = { # "Server": "nginx/x.x (Ubuntu)", # "Date": "Sat, 16 May 2020 14:57:27 GMT", # "Content-Type": "application/json; charset=utf-8", # "Content-Length": "2", # "X-Account-Container-Count": "0", # "X-Account-Object-Count": "0", # "X-Account-Bytes-Used": "0", # "X-Timestamp": "1589641047.63424", # "X-Put-Timestamp": "1589641047.63424", # "X-Trans-Id": "tx97..", # "X-Openstack-Request-Id": "tx97.."} # out.json() = { # {"name": "logbunny-test", "count": 0, "bytes": 0, # "last_modified": "2020-05-16T15:02:03.684680"} return [SwiftContainer.from_list(i, swift=self) for i in out.json()] def get_container(self, name): ret = SwiftContainer(name=name) ret.swift = self return ret class SwiftContainer: @classmethod def from_list(cls, data, swift): # data = {"name": "logbunny-test", "count": 0, "bytes": 0, # "last_modified": "2020-05-16T15:02:03.684680"} ret = cls(name=data['name']) ret.swift = swift return ret def __init__(self, name): self.name = name def _mkurl(self, *args): return self.swift._mkurl(self.name, *args) def ensure_exists(self): """ Make sure the container exists by creating it if it doesn't. Keep in mind that it will be created with "default" properties/metadata. """ url, hdrs = self._mkurl(), self.swift._mkhdrs() out = requests.head(url, headers=hdrs) # 200 = OK, 204 = OK (but has no content) # 201 = created, 202 accepted (will be creating shortly) if out.status_code in (200, 204): pass elif out.status_code == 404: out = requests.put(url, headers=hdrs) assert out.status_code in (201, 202), (url, out.status_code) out = requests.head(url, headers=hdrs) assert out.status_code in (200, 204), (url, out.status_code) else: assert False, (url, out.status_code) def list(self): """ List all files in the container; returns a list of dicts NOTE: This interface will change in the future, as we'll want filtering capabilities. Example return value: [ {"bytes": 432, "content_type": "application/octet-stream", "hash": "<md5-hash>", "last_modified": "2020-05-16T15:58:02.489890", "name": "README.rst"}, ... ] """ url, hdrs = self._mkurl(), self.swift._mkhdrs(json=True) out = requests.get(url, headers=hdrs) if out.status_code != 200: raise PermissionDenied('GET', url, out.status_code, out.text) # headers = { # "Server": "nginx/x.x (Ubuntu)", # "Date": "Sat, 16 May 2020 15:20:45 GMT", # "Content-Type": "application/json; charset=utf-8", # "Content-Length": "2", # "X-Container-Object-Count": "0", # "X-Container-Bytes-Used": "0", # "X-Timestamp": "1589641323.69412", # "Last-Modified": "Sat, 16 May 2020 15:02:04 GMT", # "Accept-Ranges": "bytes", # "X-Storage-Policy": "policy0", # "X-Trans-Id": "txe3a...", # "X-Openstack-Request-Id": "txe3a..."} # out.json() = [ # {"bytes": 432, "hash": "5a..", # "name": "README.rst", "content_type": "application/octet-stream", # "last_modified": "2020-05-16T15:58:02.489890"}] return out.json() def delete(self, name): """ DELETE (remove) remote Swift file """ url, hdrs = self._mkurl(name), self.swift._mkhdrs() out = requests.delete(url, headers=hdrs) if out.status_code == 404: raise SwiftFileNotFoundError( filename=name, strerror='DELETE {} {}'.format(url, out.status_code)) if out.status_code != 204: raise PermissionDenied('DELETE', url, out.status_code, out.text) assert out.content == b'', out.content def get(self, name): """ GET (read) remote Swift file, returns a requests.Response object Example usage: with container.get(filename) as response, \ open(local_filename, 'wb') as fp: for chunk in response.iter_content(chunk_size=8192): fp.write(chunk) See: https://requests.readthedocs.io/en/master/api/#requests.Response """ url, hdrs = self._mkurl(name), self.swift._mkhdrs() out = requests.get(url, headers=hdrs) if out.status_code == 404: raise SwiftFileNotFoundError( filename=name, strerror='GET {} {}'.format(url, out.status_code)) if out.status_code != 200: raise PermissionDenied('GET', url, out.status_code, out.text) return out def head(self, name): """ HEAD (read) remote Swift file metadata, returns a requests.Response object """ url, hdrs = self._mkurl(name), self.swift._mkhdrs() out = requests.head(url, headers=hdrs) if out.status_code == 404: raise SwiftFileNotFoundError( filename=name, strerror='GET {} {}'.format(url, out.status_code)) if out.status_code != 200: raise PermissionDenied('GET', url, out.status_code, out.text) assert out.content == b'', out.content return out def put(self, name, fp, content_type='application/octet-stream', check_exists_before=True, check_exists_after=True): """ PUT (write) remote Swift file BEWARE: if you're uploading from a file of unknown size (a pipe/stream), you may want to wrap the fp in a ChunkIteratorIOBaseWrapper: instead of iterating over lines, it will iterate over chunks of data. NOTE: Right now, we do a: - HEAD check before PUT (to ensure we do not overwrite), and a - HEAD check after PUT (to ensure the file was written). This may prove to be more overhead than we want, so this might change in the future. You can disable this by setting the `check_exists_*` arguments to False. """ url, hdrs = self._mkurl(name), self.swift._mkhdrs() hdrs['Content-Type'] = content_type if check_exists_before: out = requests.head(url, headers=hdrs) if out.status_code != 404: raise SwiftFileExistsError( filename=name, strerror='HEAD before PUT {} {}'.format( url, out.status_code)) assert out.content == b'', out.content out = requests.put(url, headers=hdrs, data=fp) if out.status_code != 201: raise PermissionDenied('PUT', url, out.status_code, out.text) assert out.content == b'', out.content if check_exists_after: out = requests.head(url, headers=hdrs) if out.status_code != 200: raise SwiftFileNotFoundError( filename=name, strerror='HEAD after PUT {} {}'.format( url, out.status_code)) assert out.content == b'', out.content # ====================================================================== # Request helpers # ====================================================================== class ChunkIteratorIOBaseWrapper: """ Wrapper around python file objects with a chunked iterator Regular file objects (IOBase) have a readline() iterator. This wrapper changes the iterator to provide appropriately sized chunks instead. When an input file size is not known beforehand (for streamed IO), the requests http library will iterate over the input file. This wrapper makes it a lot more efficient. Usage: infp = sys.stdin.buffer # let input be a pipe, instead of a file # Slow: as infp is iterated over using readlines() requests.put('https://path/to/somewhere', data=infp) # Fast: as we get decent sized chunks requests.put('https://path/to/somewhere', data=( ChunkIteratorIOBaseWrapper(infp)) See also: wsgiref.util.FileWrapper -- but that one does not forward calls to like fileno() and seek(). """ BUFSIZ = 256 * 1024 def __init__(self, fp): self.__fp = fp def __iter__(self): # TODO: check for closed file? return self def __next__(self): buf = self.__fp.read(self.BUFSIZ) if buf == b'': raise StopIteration() return buf def __getattr__(self, attr): "Get property/method from self.__fp instead" return getattr(self.__fp, attr) class FuncOpen: """ Popen "compatible" subprocess handler to be used in Popen-chains Because reading a HTTP stream takes userland code (we cannot simply read() from the socket), we spawn a subprocess to read and write to an anonymous pipe. (*) The other end of the pipe can then be read() as usual. Usage: def data_get_func(dstfp): "Closure, to call container.get(name) and write to dstfp" with container.get(name) as response: for chunk in response.iter_content(chunk_size=8192): if chunk: dstfp.write(chunk) # Example that loads data from a Swift container and feeds it to # md5sum directly: with FuncOpen(data_get_func) as pipe1, ( subprocess.Popen( ["md5sum"], stdin=pipe1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)) as pipe2: md5out, err = pipe2.communicate() assert pipe2.wait() == 0 and err == b'' void, err = pipe1.communicate() assert pipe1.wait() == 0 and void == b'' and err == b'', ( pipe1.returncode, void, err) print(md5out) # b'<md5-hash> -<LF>' (*) Why? For chunked transfer, the data is intermixed with chunk headers. For gzipped data, the data also needs decompression. """ def __init__(self, function, stdout=None): if stdout is None: # Our pipe, our responsibility to clean up the fd. c2pread, c2pwrite = os.pipe() else: # Someone elses responsibility. c2pread, c2pwrite = None, stdout.fileno() errread, errwrite = os.pipe() pid = os.fork() if not pid: # This is the child handled_fds = (None, c2pread, c2pwrite) os.close(errread) if c2pread is not None: os.close(c2pread) if sys.stdin and sys.stdin.fileno() not in handled_fds: sys.stdin.close() if sys.stdout and sys.stdout.fileno() not in handled_fds: sys.stdout.close() if sys.stderr.fileno() is not None: os.dup2(errwrite, sys.stderr.fileno()) try: # Function is called first after the fork(), so we need # not worry about anyone setting CLOEXEC on its newly # created FDs. with os.fdopen(c2pwrite, 'wb') as dstfp: function(dstfp) finally: try: os.close(errwrite) except Exception: pass os._exit(0) self.pid = pid self.returncode = None self._using_pipe = (c2pread is not None) if self._using_pipe: os.close(c2pwrite) self.stdout = os.fdopen(c2pread, 'rb') os.close(errwrite) self._stderr = errread def communicate(self): # Behave as much as regular Popen as possible. Note that we # don't cope with large amounts of stderr while stdout is still # (supposed) to be flowing. out = b'' with os.fdopen(self._stderr, 'rb') as fp: err = fp.read() self._stderr = None self.wait() return out, err def wait(self): if self.returncode is None: pid, returncode = os.waitpid(self.pid, 0) self.returncode = returncode if self._stderr is not None: os.close(self._stderr) self._stderr = None return self.returncode def __enter__(self): return self def __exit__(self, type, value, traceback): if self._using_pipe: self.stdout.close() self.wait() class FuncPipe(FuncOpen): """ FuncOpen as a Pipe where we assert that there was no failure """ def communicate(self): out, err = super().communicate() assert out in (b'', None), out if self.returncode != 0: log.debug('(stderr) %s', err.decode('ascii', 'replace')) raise CalledProcessError( cmd='{} (FuncPipe child)'.format(sys.argv[0]), output=err, returncode=self.returncode) return (None, err) class SwiftContainerGetPipe(FuncPipe): """ Get data from a container in a subprocess: self.stdout iterates the data Usage: with SwiftContainerGetPipe(container, remote_name) as pipe1, ( subprocess.Popen( ["md5sum"], stdin=pipe1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)) as pipe2: md5out, err = pipe2.communicate() pipe1.communicate() print(md5out) # b'<md5-hash> -<LF>' """ def __init__(self, container, filename, stdout=None): # Call generator enter manually and immediately: any 403/404 # will get picked up now. self._response = response = container.get(filename).__enter__() # The container data fetch gets to be done in the subprocess. def getter(dstfp): for chunk in response.iter_content(chunk_size=8192): # In the wild, we have seen one case where an apparently empty # write propagated to a process causing the read to be cut # short, aborting the reader. Still not entirely sure what # happened, because we haven't been able to reproduce. But the # addition of this if-condition fixed the problem in both # occurrences: don't write empty data. It may cause someone to # think there is nothing left. if chunk: dstfp.write(chunk) super().__init__(function=getter, stdout=stdout) def __exit__(self, type, value, traceback): self._response.__exit__(type, value, traceback) super().__exit__(type, value, traceback) @contextmanager def TemporaryUntilClosedFile(filename, mode='wb'): """ NamedTemporaryFile replacement that renames if there is no exception If there is an exception inside the context handler, the temporary file is deleted. If there is _no_ exception, the temporary file is renamed to the target filename. Usage: with TemporaryUntilClosedFile(local_name) as outfp, \\ SwiftContainerGetPipe( container, remote_name, outfp) as source: source.communicate() """ # Use dir=directory-of-the-file, so we won't have issues with # cross-filesystem-moves. ret = tempfile.NamedTemporaryFile( mode=mode, dir=os.path.dirname(filename), delete=False) try: yield ret except Exception: os.unlink(ret.name) raise else: os.rename(ret.name, filename)
ossobv/keystone-light
keystone_light/__init__.py
__init__.py
py
37,297
python
en
code
0
github-code
36
[ { "api_name": "logging.getLogger", "line_number": 17, "usage_type": "call" }, { "api_name": "logging.NullHandler", "line_number": 18, "usage_type": "call" }, { "api_name": "os.path.expanduser", "line_number": 72, "usage_type": "call" }, { "api_name": "os.path", ...
23563599190
# -*- coding: utf-8 -*- """ Created on Tue Jun 20 07:39:26 2017 @author: mnshr """ from statsmodels.stats.outliers_influence import variance_inflation_factor """ VIF = 1 (Not correlated) 1 < VIF < 5 (Moderately correlated) VIF > 5 to 10 (Highly correlated) VIF is one way to understand whether any two independent variable are highly correlated. In that case both the variable explain same variance in the model. So it is generally good to drop any one of them. Feature selection vs Multicollinearity Checks Vs Mean Centering (Standardization) Answer by Robert Kubrick in the following link give some interesting information on the front https://stats.stackexchange.com/questions/25611/how-to-deal-with-multicollinearity-when-performing-variable-selection VIF calculations are straightforward - the higher the value, the higher the collinearity. """ def calculate_vif_(X): variables = list(X.columns) vif = {variable:variance_inflation_factor(exog=X.values, exog_idx=ix) for ix,variable in enumerate(list(X.columns))} return vif from scipy.stats import kendalltau #https://www.kaggle.com/ffisegydd/sklearn-multicollinearity-class/comments/notebook from statsmodels.stats.outliers_influence import variance_inflation_factor class ReduceVIF(BaseEstimator, TransformerMixin): def __init__(self, thresh=5.0, impute=True, impute_strategy='median'): # From looking at documentation, values between 5 and 10 are "okay". # Above 10 is too high and so should be removed. self.thresh = thresh # The statsmodel function will fail with NaN values, as such we have to impute them. # By default we impute using the median value. # This imputation could be taken out and added as part of an sklearn Pipeline. if impute: self.imputer = Imputer(strategy=impute_strategy) def fit(self, X, y=None): print('ReduceVIF fit') if hasattr(self, 'imputer'): self.imputer.fit(X) return self def transform(self, X, y=None): print('ReduceVIF transform') columns = X.columns.tolist() if hasattr(self, 'imputer'): X = pd.DataFrame(self.imputer.transform(X), columns=columns) return ReduceVIF.calculate_vif(X, self.thresh) @staticmethod def calculate_vif(X, thresh=5.0): # Taken from https://stats.stackexchange.com/a/253620/53565 and modified dropped=True while dropped: variables = X.columns dropped = False vif = [variance_inflation_factor(X[variables].values, X.columns.get_loc(var)) for var in X.columns] max_vif = max(vif) if max_vif > thresh: maxloc = vif.index(max_vif) print(f'Dropping {X.columns[maxloc]} with vif={max_vif}') X = X.drop([X.columns.tolist()[maxloc]], axis=1) dropped=True return X
mnshr/kgl
stats.py
stats.py
py
2,925
python
en
code
0
github-code
36
[ { "api_name": "statsmodels.stats.outliers_influence.variance_inflation_factor", "line_number": 26, "usage_type": "call" }, { "api_name": "statsmodels.stats.outliers_influence.variance_inflation_factor", "line_number": 67, "usage_type": "call" } ]
42544034746
#!/usr/bin/env python3 import argparse import csv import os import pickle import shutil import time from concurrent import futures import grpc from pysrbup.backup_system_pb2 import (Block, DeleteBackupResponse, GetBackupResponse, GetBlocksResponse, GetMissingCodesResponse, ListBackupsResponse, PushBlocksResponse, Row, UpdateDictResponse, UploadBackupResponse) from pysrbup.backup_system_pb2_grpc import add_BackupServicer_to_server class BackupServicer(): def __init__(self, backups_dir, dictionary_file): self.backups_dir = backups_dir self.meta_file = os.path.join(self.backups_dir, 'meta.csv') self.dictionary_file = dictionary_file with open(dictionary_file, 'rb') as f: self.dictionary = pickle.load(f) def UploadBackup(self, request, context): # pylint: disable=invalid-name,unused-argument curr_backup_dir = os.path.join(self.backups_dir, request.id) os.mkdir(curr_backup_dir) backup_file = os.path.join(curr_backup_dir, 'data.bin') with open(backup_file, 'wb') as f: f.write(request.data) with open(self.meta_file, 'a') as f: writer = csv.writer(f) writer.writerow([request.id, time.asctime(time.gmtime())]) return UploadBackupResponse() def GetMissingCodes(self, request, context): # pylint: disable=invalid-name,unused-argument missing_codes = [] for code in request.codes: if code not in self.dictionary: missing_codes.append(code) else: self.dictionary[code][1] += 1 return GetMissingCodesResponse(codes=missing_codes) def PushBlocks(self, request, context): # pylint: disable=invalid-name,unused-argument for block in request.blocks: self.dictionary[block.code] = [block.data, 1] with open(self.dictionary_file, 'wb') as f: pickle.dump(self.dictionary, f) return PushBlocksResponse() def GetBackup(self, request, context): # pylint: disable=invalid-name,unused-argument if not request.id in os.listdir(self.backups_dir): return GetBackupResponse() file_to_restore = os.path.join(self.backups_dir, request.id, 'data.bin') with open(file_to_restore, 'rb') as f: data = f.read() return GetBackupResponse(data=data) # pylint: disable=invalid-name,unused-argument def GetBlocks(self, request, context): blocks = [] for code in request.codes: block = Block(code=code, data=self.dictionary[code][0]) blocks.append(block) return GetBlocksResponse(blocks=blocks) def DeleteBackup(self, request, context): # pylint: disable=invalid-name,unused-argument if request.id not in os.listdir(self.backups_dir): return GetBackupResponse() backup_dir_to_delete = os.path.join(self.backups_dir, request.id) backup_file = os.path.join(backup_dir_to_delete, 'data.bin') with open(backup_file, 'rb') as f: data = f.read() with open(self.meta_file, 'r') as infile: rows = [] for row in csv.reader(infile): if row and row[0] != request.id: rows.append(row) with open(self.meta_file, 'w') as outfile: writer = csv.writer(outfile) for row in rows: writer.writerow(row) shutil.rmtree(backup_dir_to_delete) return DeleteBackupResponse(data=data) def UpdateDict(self, request, context): # pylint: disable=invalid-name,unused-argument for code in request.codes: if self.dictionary[code][1] == 1: del self.dictionary[code] else: self.dictionary[code][1] -= 1 with open(self.dictionary_file, 'wb') as d: pickle.dump(self.dictionary, d) return UpdateDictResponse() def ListBackups(self, request, context): # pylint: disable=invalid-name,unused-argument with open(self.meta_file, 'r') as mf: rows = [] count = 0 for row in csv.reader(mf): if row and count > 0: rows.append(Row(col=row)) count += 1 return ListBackupsResponse(rows=rows) def create_args_parser(): parser = argparse.ArgumentParser() parser.add_argument('--server-address', default='localhost:50000') parser.add_argument('--num-threads', default=3) parser.add_argument('backups_dir') return parser def create_dictionary(root_path): dictionary_file = os.path.join(root_path, 'dictionary') with open(dictionary_file, 'wb') as f: pickle.dump({}, f) return dictionary_file def create_meta_file(root_path): meta_file = os.path.join(root_path, 'meta.csv') with open(meta_file, 'a') as f: writer = csv.writer(f) writer.writerow(['id', 'creation_time']) def main(): args = create_args_parser().parse_args() if 'dictionary' not in os.listdir(args.backups_dir): dictionary_file = create_dictionary(args.backups_dir) else: dictionary_file = os.path.join(args.backups_dir, 'dictionary') if 'meta.csv' not in os.listdir(args.backups_dir): create_meta_file(args.backups_dir) server = grpc.server( futures.ThreadPoolExecutor(max_workers=args.num_threads)) add_BackupServicer_to_server( BackupServicer(args.backups_dir, dictionary_file), server) server.add_insecure_port(args.server_address) server.start() server.wait_for_termination() if __name__ == '__main__': main()
dorchul/pysrbup
pysrbup/server.py
server.py
py
5,900
python
en
code
0
github-code
36
[ { "api_name": "os.path.join", "line_number": 25, "usage_type": "call" }, { "api_name": "os.path", "line_number": 25, "usage_type": "attribute" }, { "api_name": "pickle.load", "line_number": 28, "usage_type": "call" }, { "api_name": "os.path.join", "line_number...
22517487941
from datetime import timedelta from django.utils import timezone from django.contrib.auth.models import User import pytest from typing import List from .. import models EVENT_NAME = "football with friends" MAX_PART = 20 IS_PRIVATE = False DATETIME = timezone.now() + timedelta(days=2) POLL_END_TIME = timezone.now() POLL_MAX_SUGGESTIONS = 3 @pytest.fixture def category1(): category = models.Category(name="test1") category.save() return category @pytest.fixture def location1(): location = models.Location( name="test1", city="test1", street="test1", street_number=1, indoor=False, description="test1" ) location.save() return location @pytest.fixture def category_location1(category1, location1): cat_loc = models.CategoryLocation(category=category1, location=location1) cat_loc.save() return cat_loc @pytest.fixture def user1(): user = User.objects.create_user(username='test', password='test', email='myemail@example.com') profile = models.Profile( user=user, date_of_birth=timezone.now(), phone_number="test", image='default.jpg' ) profile.save() return profile @pytest.fixture def user2(): user = User.objects.create_user(username='test1', password='test1', email='myemail1@example.com') profile = models.Profile( user=user, date_of_birth=timezone.now(), phone_number="test1", image='default.jpg' ) profile.save() return profile @pytest.fixture def poll1(): poll = models.Poll(max_suggestions=POLL_MAX_SUGGESTIONS, end_time=POLL_END_TIME) poll.save() return poll @pytest.fixture def event1(category_location1, poll1): new_event = models.Event( category=category_location1.category, location=category_location1.location, poll=poll1, name=EVENT_NAME, max_participants=MAX_PART, start_time=DATETIME, end_time=DATETIME + timedelta(hours=3), is_private=IS_PRIVATE, ) new_event.save() return new_event @pytest.fixture def validate_event1(category_location1, user1): event_id = models.Event.manager.create_event( category_id=category_location1.category.id, location_id=category_location1.location.id, name=EVENT_NAME, max_participants=MAX_PART, start_time=DATETIME, end_time=DATETIME + timedelta(hours=3), is_private=IS_PRIVATE, poll_end_time=POLL_END_TIME, poll_suggestions=POLL_MAX_SUGGESTIONS, user_id=user1.id, ) event = models.Event.manager.get(id=event_id) return event @pytest.fixture(scope="session") def categories1(django_db_blocker) -> List[models.Category]: with django_db_blocker.unblock(): query_set = models.Category.objects.all() query_set = list(query_set)[:5] return query_set @pytest.fixture(scope="session") def locations1(django_db_blocker) -> List[models.Location]: with django_db_blocker.unblock(): names = ['Sportech', 'Sami offer stadium', 'Terner stadium', 'Tedi Stadium', 'Bluemfield Stadium'] cities = ['Tel Aviv', 'Haifa', 'Beer Sheva', 'Jerusalem', 'Yaffo'] locations_lst = [] for location_name, city in zip(names, cities): new_location = models.Location( name=location_name, city=city, street='test', street_number=1, indoor=False, description='test' ) new_location.save() locations_lst.append(new_location) return locations_lst @pytest.fixture(scope="session") def categories_locations1(django_db_blocker, categories1, locations1) -> List[models.CategoryLocation]: with django_db_blocker.unblock(): categories_locations = [] for category in categories1: for location in locations1: cat_loc = models.CategoryLocation(category=category, location=location) cat_loc.save() categories_locations.append(cat_loc) return categories_locations @pytest.fixture(scope="session") def users1(django_db_blocker) -> List[models.Profile]: with django_db_blocker.unblock(): users = [] for i in range(25): user = User.objects.create_user(username=f'user{i}', password=f'password{i}', email=f'user{i}@example.com') profile = models.Profile( user=user, date_of_birth=timezone.now(), phone_number=f"user{i}", image='default.jpg' ) profile.save() users.append(profile) return users @pytest.fixture(scope="session") def time_samples(django_db_blocker): with django_db_blocker.unblock(): current_time = timezone.now() lst = [ current_time + timedelta(days=1), current_time + timedelta(days=3), current_time + timedelta(weeks=1), current_time + timedelta(days=3, weeks=1), current_time + timedelta(weeks=3), ] return lst @pytest.fixture(scope="session") def event_data_set(django_db_blocker, categories_locations1, users1, time_samples): with django_db_blocker.unblock(): for index, user in enumerate(users1): cat_loc = categories_locations1.pop() start_time = time_samples[index % len(time_samples)] end_time = start_time + timedelta(hours=3) poll_end_time = start_time + timedelta(days=-1) models.Event.manager.create_event( category_id=cat_loc.category.id, location_id=cat_loc.location.id, max_participants=2 * index + 2, name=f'test event {index}', start_time=start_time, end_time=end_time, is_private=index > 15, poll_end_time=poll_end_time, poll_suggestions=3, user_id=user.id, ) @pytest.fixture def base_url(db, user1): return f'/{user1.id}/event/' @pytest.fixture def create_url(base_url): return base_url + 'create/' @pytest.fixture def first_event_info_url(base_url): event = models.Event.manager.first() return f'{base_url}info/?id={event.id}' @pytest.fixture def create_event_form_data1(category_location1): return { 'name': EVENT_NAME, 'category': category_location1.category.id, 'location': category_location1.location.id, 'max_participants': MAX_PART, 'start_time': DATETIME + timedelta(days=2), 'end_time': DATETIME + timedelta(days=2, hours=3), 'poll_end_time': DATETIME + timedelta(days=1), 'poll_max_suggestions': POLL_MAX_SUGGESTIONS, 'is_private': IS_PRIVATE, }
redhat-beyond/FitMeet
event/tests/conftest.py
conftest.py
py
6,663
python
en
code
0
github-code
36
[ { "api_name": "django.utils.timezone.now", "line_number": 12, "usage_type": "call" }, { "api_name": "django.utils.timezone", "line_number": 12, "usage_type": "name" }, { "api_name": "datetime.timedelta", "line_number": 12, "usage_type": "call" }, { "api_name": "dj...
2496560289
#!/usr/bin/env python """ photomongo - read and process all tweets possible Usage: photomongo [options] CONFIGFILE Options: -h --help Show this screen. --pickle-to=<picklefile> file to save tweets. --pickle-from=<picklefile> file to read tweets. --max=<number> maximum number to process, primarily for debug --since=<days> maximum number of days to get in the past --progress-bar display the progress bar """ import sys import logging logging.basicConfig( format = '%(asctime)s %(levelname)s %(module)s [%(funcName)s] %(message)s', datefmt='%Y-%m-%d,%H:%M:%S', level=logging.DEBUG, handlers = [logging.FileHandler('photomongo.log')] ) log = logging.getLogger(__name__) import os from docopt import docopt import configparser import json import searcher from twitter import Twitter from gmail import Gmail import progress_bar # to save/reload tweets use pickle import pickle # control logging level of modules logging.getLogger("requests").setLevel(logging.WARNING) logging.getLogger("urllib3").setLevel(logging.WARNING) logging.getLogger("PIL").setLevel(logging.WARNING) logging.getLogger("oauthlib").setLevel(logging.WARNING) logging.getLogger("tweepy").setLevel(logging.WARNING) logging.getLogger("requests_oauthlib").setLevel(logging.WARNING) logging.getLogger("googleapiclient").setLevel(logging.WARNING) if __name__=='__main__': args = docopt(__doc__) try: pickleFromFile = args['--pickle-from'] except KeyError: pickleFromFile = None try: pickleToFile = args['--pickle-to'] except KeyError: pickleToFile = None try: maxCount = int(args['--max']) except ( KeyError, TypeError ): maxCount = None try: sinceDays = int(args['--since']) except ( KeyError, TypeError): sinceDays = None try: showProgressBar = args['--progress-bar'] except KeyError: showProgressBar = False log.debug('pickleToFile = ' + str(pickleToFile)) log.debug('pickleFromFile = ' + str(pickleFromFile)) # get the configuration file conf_file = args['CONFIGFILE'] # read the config file and determine what to do config = configparser.ConfigParser() config.read(conf_file) # check if gmail is configured # if the gmail section is not present in the config file, then a Null # Gmail handler will be created that does nothing. try: gmailconf = config['gmail'] except KeyError: # gmail not configured log.info('gmail not configured, emails will not be sent') gmailconf = None try: gm = Gmail(gmailconf) log.info('gmail configured') except: # gmail configuration error log.error('gmail configuration error') raise # require a 'search' section in the config file know what to search fo try: searchconf = config['search'] except KeyError: log.exception('Search configuration parameters not configured') raise # check if configured to write out save file try: results_save_file = searchconf['save results file'] log.info('Will save search results to: ' + results_save_file) except KeyError: results_save_file = None log.info('No configured file for search results') # require a twitter configuration unless reading from an external file if pickleFromFile: # read tweets from pickle file instead of from twitter api with open(pickleFromFile,'rb') as f: alltweets = pickle.load(f) else: # read the tweets from twitter api directly try: twitconfig = config['twitter'] except KeyError: log.exception('Twitter not configured') raise twit = Twitter(twitconfig) # get all the tweets # alltweets will be a dict of lists # each dict key is a followed twitter stream alltweets = twit.getAllTweets(sinceDays = sinceDays) #alltweets = twit.getAllTweets() # save the tweets if needed if pickleToFile: # write the tweets to a picklefile with open(pickleToFile,'wb') as f: pickle.dump(alltweets,f) # set up to search the tweets tweetsearcher = searcher.TweetSearcher(searchconf) # search all the tweets # https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python flatten = lambda l: [item for sublist in l for item in sublist] # convert all tweets to a list if needed try: # assume a dictionary alltweets = flatten( alltweets.values() ) except AttributeError: # assume it's a list pass if not maxCount: # if maxCount not set, use all tweets at max totlen = len(alltweets) elif len(alltweets) < maxCount: # if fewer tweets found than max count, use that number totlen = len(alltweets) else: # otherwise, process maxcCount at most totlen = maxCount searchresults = [] if alltweets: for i,tweet in enumerate( alltweets ): # this searches on tweet at a time searchresults.extend( tweetsearcher.searchTweet(tweet) ) # count in progress_bar is i+1 because we start at zero and # this should not be zero-based counter if showProgressBar: progress_bar.print_progress(i+1,totlen) if i == totlen: break # send email if search results come back if searchresults: # format message to send msg = '' for sr in searchresults: url = 'https://twitter.com/' +\ sr.reference.user.screen_name +\ '/status/' +\ sr.reference.id_str msg += url + ' at ' + str(sr.match_loc) + '\n\n' log.info(msg) gm.create_and_send_message('photomongo results to review',\ msg) else: msg = 'Photomongo found no results in ' + str(totlen) + ' tweets.' log.info(msg) gm.create_and_send_message('photomongo no results',\ msg)
anielsen001/photomongo
photomongo.py
photomongo.py
py
6,387
python
en
code
1
github-code
36
[ { "api_name": "logging.basicConfig", "line_number": 20, "usage_type": "call" }, { "api_name": "logging.DEBUG", "line_number": 23, "usage_type": "attribute" }, { "api_name": "logging.FileHandler", "line_number": 24, "usage_type": "call" }, { "api_name": "logging.ge...
25285589404
''' Find out the relationship between Liquor Sales and Vehicle Accidents ''' import sys import math import uuid from schema import liquor_schema from matplotlib import pyplot as plt import pandas as pd from pyspark.sql import SparkSession, types from pyspark.sql import functions as F assert sys.version_info >= (3, 5) # make sure we have Python 3.5+ cluster_seeds = ['199.60.17.32', '199.60.17.65'] spark = SparkSession.builder.appName('liquor vehicle').config('spark.cassandra.connection.host', ','.join(cluster_seeds)).getOrCreate() spark.sparkContext.setLogLevel('WARN') sc = spark.sparkContext assert spark.version >= '2.4' # make sure we have Spark 2.4+ def main(liquor_sales_inputs, vehicle_accidents_inputs): # process vehicle accidents dataset va_df = spark.read.csv(vehicle_accidents_inputs, header=True) va_df = va_df.select(F.to_date(F.split(va_df['Crash Date & Time'], ' ')[0], "MM/dd/yyyy").alias('Date'),\ 'County', 'City', 'Drug/Alcohol Related') va_df = va_df.withColumn('Year', F.year(va_df['Date'])) va_df = va_df.withColumn('Month', F.month(va_df['Date'])) va_df = va_df.where("Year <= 2018 and Year >= 2013") va_df = va_df.where(va_df['Drug/Alcohol Related'].like('%Alcohol%')) va_df = va_df.groupBy(['Year', 'Month']).agg(F.count("*").alias('total_number_of_accidents')) # process liquor sales dataset liquor_df = spark.read.csv(liquor_sales_inputs, schema=liquor_schema) liquor_df = liquor_df.select(F.to_date(liquor_df['Date'], 'MM/dd/yyyy').alias('Date'), 'Category', 'Bottles Sold') liquor_df = liquor_df.withColumn('Year', F.year(liquor_df['Date'])) liquor_df = liquor_df.withColumn('Month', F.month(liquor_df['Date'])) liquor_df = liquor_df.where("Year <= 2018 and Year >= 2013") liquor_df = liquor_df.groupBy(['Year', "Month"]).sum('Bottles Sold') # join two datasets liquor_vehicle_df = liquor_df.join(va_df, ['Year', 'Month']) liquor_vehicle_df = liquor_vehicle_df.withColumn('id', F.lit(str(uuid.uuid1()))) liquor_vehicle_df = liquor_vehicle_df.withColumnRenamed('Year', 'year').withColumnRenamed('Month', 'month')\ .withColumnRenamed('sum(Bottles Sold)', 'bottles_sold') liquor_vehicle_df = liquor_vehicle_df.orderBy(['year', 'month'], ascending=True) liquor_vehicle_df.show() # liquor_vehicle_df.write.format("org.apache.spark.sql.cassandra") \ # .options(table="liquor_accidents", keyspace="qya23").mode('append').save() # calculate correlation coefficient six_values = liquor_vehicle_df.select(F.lit(1).alias('sum'), liquor_vehicle_df['bottles_sold'].alias('x'), liquor_vehicle_df['total_number_of_accidents'].alias('y'), \ (liquor_vehicle_df['bottles_sold']**2).alias('x^2'), (liquor_vehicle_df['total_number_of_accidents']**2).alias('y^2'), \ (liquor_vehicle_df['bottles_sold'] * liquor_vehicle_df['total_number_of_accidents']).alias('x*y')) six_sums = six_values.select(F.sum('sum'), F.sum('x'), F.sum('y'), F.sum('x^2'), F.sum('y^2'), F.sum('x*y')) params = six_sums.collect()[0] r = (params['sum(sum)'] * params['sum(x*y)'] - params['sum(x)'] * params['sum(y)']) / ((math.sqrt(params['sum(sum)'] * params['sum(x^2)'] - params['sum(x)']**2)) * (math.sqrt(params['sum(sum)'] * params['sum(y^2)'] - params['sum(y)']**2))) print('r^2 = {0:.6f}'.format(r**2)) if __name__ == '__main__': liquor_sales_inputs = sys.argv[1] vehicle_accidents_inputs = sys.argv[2] main(liquor_sales_inputs, vehicle_accidents_inputs)
libou/Liquor-Sale-Analysis
liquor_vehicle.py
liquor_vehicle.py
py
3,441
python
en
code
0
github-code
36
[ { "api_name": "sys.version_info", "line_number": 14, "usage_type": "attribute" }, { "api_name": "pyspark.sql.SparkSession.builder.appName", "line_number": 18, "usage_type": "call" }, { "api_name": "pyspark.sql.SparkSession.builder", "line_number": 18, "usage_type": "attri...
15576814335
from collections import deque T = int(input()) for _ in range(T): N, M = map(int, input().split()) queue = deque(map(int, input().split())) queue = deque([(i, idx) for idx, i in enumerate(queue)]) count = 0 while True: if queue[0][0] == max(queue, key=lambda x: x[0])[0]: count += 1 if queue[0][1] == M: print(count) break else: queue.popleft() else: queue.append(queue.popleft())
HelloWook/AlgorithmStudy
백준/Silver/1966. 프린터 큐/프린터 큐.py
프린터 큐.py
py
532
python
en
code
0
github-code
36
[ { "api_name": "collections.deque", "line_number": 6, "usage_type": "call" }, { "api_name": "collections.deque", "line_number": 7, "usage_type": "call" } ]
2022880805
import logging as log import math import torch import torch.nn as nn from pytorch_lightning.core.lightning import LightningModule import nltocode.decoder as custom_decoder import nltocode.encoder as custom_encoder class Transformer(LightningModule): def __init__(self, d_model, nhead, num_encoder_layers, num_decoder_layers, dim_feedforward, dropout, multihead_attention_dropout, normalize_before, activation, learning_rate, batch_size, num_dataloader_workers, train_valid_data_path, train_split, val_split, vocabsrc_size, vocabtgt_size, vocab_pad_id, max_src_sentence_length, max_tgt_sentence_length, max_path_depth, path_multiple=0, tgt_pos_enc_type=None, label_smoothing=None, logits_forbidden_token_modifier=None, logits_forbidden_token_modifier_schedule=None, logits_forbidden_token_op='sum', logits_forbidden_token_modifier_learning_rate=None, enable_copy=True, copy_att_layer=-1, withcharemb=False, vocabchar_size=None, max_charseq_len=None, # Test-only parameters test_data_path=None, grammar_graph_file=None, target_language='python', num_beams=None, disable_decoder_constraint_mask=False, max_beam_length=None, max_num_predicted_results=None, beam_search_mode=None, keep_invalid_beamsearch_results=False, target_output_file=None, is_test_only_run=False ): super().__init__() self.d_model = d_model self.nhead = nhead self.num_encoder_layers = num_encoder_layers self.num_decoder_layers = num_decoder_layers self.dim_feedforward = dim_feedforward self.dropout = dropout self.multihead_attention_dropout = multihead_attention_dropout self.normalize_before = normalize_before self.activation = activation self.learning_rate = learning_rate self.label_smoothing = label_smoothing self.batch_size = batch_size self.withcharemb = withcharemb self.num_dataloader_workers = num_dataloader_workers self.vocabsrc_size = vocabsrc_size self.vocabtgt_size = vocabtgt_size self.vocabchar_size = vocabchar_size self.max_charseq_len = max_charseq_len self.tgt_pos_enc_type = tgt_pos_enc_type self.max_path_depth = max_path_depth self.path_multiple = path_multiple self.enable_copy = enable_copy self.encoder_src = nn.Embedding(self.vocabsrc_size, self.d_model) self.encoder_tgt = nn.Embedding(self.vocabtgt_size, self.d_model) if self.withcharemb: self.encoder_char = nn.Embedding(self.vocabchar_size, self.d_model) self.linear_char = nn.Linear(self.d_model * self.max_charseq_len, self.d_model) self.norm_char = nn.LayerNorm(self.d_model) self.dropout_reg_src = nn.Dropout(p=self.dropout) self.dropout_reg_tgt = nn.Dropout(p=self.dropout) decoder_layer = custom_decoder.TransformerDecoderLayer(d_model=self.d_model, nhead=self.nhead, dim_feedforward=self.dim_feedforward, dropout=self.dropout, multihead_attention_dropout=self.multihead_attention_dropout, normalize_before=self.normalize_before) self.decoder = custom_decoder.TransformerDecoder(decoder_layer, num_layers=self.num_decoder_layers, att_layer=copy_att_layer, norm=nn.LayerNorm(self.d_model)) encoder_layer = custom_encoder.TransformerEncoderLayer(d_model=self.d_model, nhead=self.nhead, dim_feedforward=self.dim_feedforward, dropout=self.dropout, activation=self.activation, withcharemb=self.withcharemb) encoder_norm = nn.LayerNorm(self.d_model) self.encoder = custom_encoder.TransformerEncoder(encoder_layer, self.num_encoder_layers, encoder_norm) self.lin_vocab = nn.Linear(self.d_model, vocabtgt_size) if self.enable_copy: self.p_gen = nn.Sequential(nn.Linear(self.d_model * 3, 1), nn.Sigmoid()) def forward(self, src, char, tgt, edge_path_seqs, logits_token_mask=None): try: mask = torch.triu(torch.ones(len(tgt), len(tgt)), 1) mask = mask.type_as(tgt).type(torch.float) tgt_mask = mask.masked_fill(mask == 1, float('-inf')) src_pad_mask = (src == 0).transpose(0, 1) tgt_pad_mask = (tgt == 0).transpose(0, 1) src_embeddings = self.encoder_src(src) tgt_embeddings = self.encoder_tgt(tgt) src_embeddings_with_pos = self.pos_encode_seq(src_embeddings, self.d_model) tgt_embeddings_with_pos = self.pos_encode(tgt_embeddings, self.tgt_pos_enc_type, edge_path_seqs) src_embeddings_with_pos = self.dropout_reg_src(src_embeddings_with_pos) tgt_embeddings_with_pos = self.dropout_reg_tgt(tgt_embeddings_with_pos) if self.withcharemb: char_embeddings = self.encoder_char(char) char_embeddings = char_embeddings.view(-1, char.size(1), self.d_model * self.max_charseq_len) char_embeddings = self.linear_char(char_embeddings) char_embeddings = self.norm_char(char_embeddings) else: char_embeddings = None enc_hs = self.encoder(src_embeddings_with_pos, char_embeddings, mask=None, src_key_padding_mask=src_pad_mask) dec_hs, attention = self.decoder(tgt_embeddings_with_pos, enc_hs, tgt_mask=tgt_mask, memory_mask=None, tgt_key_padding_mask=tgt_pad_mask, memory_key_padding_mask=None) logits = self.lin_vocab(dec_hs) if self.enable_copy: return self.apply_copy(attention, dec_hs, enc_hs, logits, src, tgt_embeddings_with_pos) else: return torch.log_softmax(logits, dim=-1) except: log.error("ERROR SRC/TGT SHAPE: %s / %s", src.shape, tgt.shape) raise def apply_copy(self, attention, dec_hs, enc_hs, logits, src, tgt_embeddings_with_pos): p_vocab = logits.softmax(dim=-1) hidden_states = enc_hs.transpose(0, 1) context_vectors = torch.matmul(attention, hidden_states).transpose(0, 1) total_states = torch.cat((context_vectors, dec_hs, tgt_embeddings_with_pos), dim=-1) p_gen = self.p_gen(total_states) p_copy = 1 - p_gen src_t = src.transpose(0, 1) one_hot = torch.zeros(src_t.size(0), src_t.size(1), self.vocabsrc_size, device=src_t.device) one_hot = one_hot.scatter_(dim=-1, index=src_t.unsqueeze(-1), value=1) p_copy_src_vocab = torch.matmul(attention, one_hot) input_vocab = torch.arange(self.vocabtgt_size - self.vocabsrc_size, self.vocabtgt_size, device=src_t.device) src_to_tgt_conversion_matrix = torch.zeros(self.vocabsrc_size, self.vocabtgt_size, device=src_t.device) src_to_tgt_conversion_matrix_scatter = src_to_tgt_conversion_matrix.scatter_(dim=-1, index=input_vocab.unsqueeze( -1), value=1) p_copy_tgt_vocab = torch.matmul(p_copy_src_vocab, src_to_tgt_conversion_matrix_scatter).transpose(0, 1) p = torch.add(p_vocab * p_gen, p_copy_tgt_vocab * p_copy) log_probs = torch.log(p) return log_probs def pos_encode(self, embeddings, pos_enc_type, edge_path_seqs): if pos_enc_type == 'tree': return self.pos_encode_tree(embeddings, edge_path_seqs, self.d_model) elif pos_enc_type == 'seq': return self.pos_encode_seq(embeddings, self.d_model) elif pos_enc_type is None: raise ValueError("Positional encoding type not specified") else: raise ValueError('Unknown positional encoding type %s' % pos_enc_type) def pos_encode_seq(self, embeddings, dmodel): length = embeddings.size(0) pos_encoder = torch.zeros(length, dmodel).type_as(embeddings) pos = torch.arange(0, length, dtype=torch.float).type_as(embeddings).unsqueeze(1) div_term = torch.exp(torch.arange(0, dmodel, 2).type_as(embeddings) * (-math.log(10000.0) / dmodel)) phase = pos * div_term pos_encoder[:, 0::2] = torch.sin(phase) pos_encoder[:, 1::2] = torch.cos(phase) pos_encoder = pos_encoder.unsqueeze(0).transpose(0, 1) embeddings_with_pos = embeddings + pos_encoder return embeddings_with_pos def pos_encode_tree(self, embeddings, edge_path_seqs, dmodel): max_sentence_length = embeddings.size(0) batch_size = embeddings.size(1) max_depth = edge_path_seqs.size(2) d_pos = dmodel // max_depth pos = edge_path_seqs.unsqueeze(-1) freq_index = torch.arange(0, d_pos, 2, device=embeddings.device, dtype=torch.float) frequency = torch.exp(freq_index * (-math.log(10000.0) / d_pos)) phase = pos * frequency phase = phase.view(max_sentence_length, batch_size, max_depth * d_pos // 2) padding = (phase == 0) pos_encoder = torch.zeros(max_sentence_length, batch_size, max_depth * d_pos, device=embeddings.device) pos_encoder[:, :, 0::2] = torch.sin(phase) pos_encoder[:, :, 1::2] = torch.cos(phase) padding_replacement = 0.0 pos_encoder[:, :, 0::2].masked_fill_(padding, padding_replacement) pos_encoder[:, :, 1::2].masked_fill_(padding, padding_replacement) embeddings_with_pos = embeddings + pos_encoder return embeddings_with_pos
SmartDataAnalytics/codeCAI
nl2codemodel/src/nltocode/transformerinf.py
transformerinf.py
py
11,778
python
en
code
4
github-code
36
[ { "api_name": "pytorch_lightning.core.lightning.LightningModule", "line_number": 12, "usage_type": "name" }, { "api_name": "torch.nn.Embedding", "line_number": 92, "usage_type": "call" }, { "api_name": "torch.nn", "line_number": 92, "usage_type": "name" }, { "api_...
14644417459
from fastapi import FastAPI, Response from starlette.middleware.cors import CORSMiddleware from routes import jobs from logger.log_info import logger app = FastAPI() @app.middleware('http') async def log_request(request, call_next): logger.info(f'{request.method} {request.url}') response = await call_next(request) logger.info(f'Status code: {response.status_code}') body = b"" async for chunk in response.body_iterator: body += chunk return Response( content=body, status_code=response.status_code, headers=dict(response.headers), media_type=response.media_type ) # app.add_middleware( # CORSMiddleware, # allow_origins=["*"], # allow_credentials=True, # allow_methods=["*"], # allow_headers=["*"], # ) app.include_router(jobs.router)
Baktybek0312/Log_BloG
main.py
main.py
py
831
python
en
code
0
github-code
36
[ { "api_name": "fastapi.FastAPI", "line_number": 7, "usage_type": "call" }, { "api_name": "logger.log_info.logger.info", "line_number": 12, "usage_type": "call" }, { "api_name": "logger.log_info.logger", "line_number": 12, "usage_type": "name" }, { "api_name": "log...
1938568135
import os import glob import pathlib from io import StringIO from typing import List, Dict, Optional from dataclasses import dataclass import kclvm.compiler.parser.parser as parser import kclvm.compiler.vfs as vfs import kclvm.compiler.extension.plugin.plugin_model as plugin import kclvm.compiler.extension.builtin.builtin as builtin import kclvm.kcl.ast.ast as ast import kclvm.kcl.info as kcl_info import kclvm.tools.printer.printer as printer @dataclass class Config: name_len: int = 30 type_len: int = 30 default_len: int = 30 final_len: int = 10 optional_len: int = 10 def get_import_module( module: ast.Module, result: Dict[str, ast.Module] = None ) -> Optional[Dict[str, ast.Module]]: """Get all import module in a module.""" if not module: return None assert isinstance(module, ast.Module) if not result: result = {} import_file_list = [] import_stmt_list = module.GetImportList() work_dir = os.path.dirname(module.filename) root: str = vfs.GetPkgRoot(work_dir) if not root: root = work_dir for stmt in import_stmt_list or []: if ( stmt.path.startswith(plugin.PLUGIN_MODULE_NAME) or stmt.name in builtin.STANDARD_SYSTEM_MODULES ): continue # import_path to abs_path fix_path = vfs.FixImportPath(root, module.filename, stmt.path).replace( ".", os.sep ) abs_path = os.path.join(root, fix_path) # Get all .k file if path is a folder if os.path.isdir(abs_path): file_glob = os.path.join(abs_path, "**", kcl_info.KCL_FILE_PATTERN) import_file_list += glob.glob(file_glob, recursive=True) else: abs_path += kcl_info.KCL_FILE_SUFFIX import_file_list.append(abs_path) for file in import_file_list: # Skip `_*.k` and `*_test.k` kcl files if os.path.basename(file).startswith("_"): continue if file.endswith("_test.k"): continue if file not in result: import_module = parser.ParseFile(file) result[file] = import_module if import_module.GetImportList(): get_import_module(import_module, result) return result def get_import_schema( module: ast.Module, ) -> Optional[Dict[ast.Module, List[ast.SchemaStmt]]]: """Get all import schema in a module.""" if not module: return None assert isinstance(module, ast.Module) import_module_list = get_import_module(module).values() import_schema_map = {m: m.GetSchemaList() for m in import_module_list} return import_schema_map class FullSchema(ast.SchemaStmt): """ Schema with base schema's attr. todo: mixin attr """ def __init__(self, schema: ast.SchemaStmt, module: ast.Module) -> None: super().__init__(schema.line, schema.column) self.self_schema = schema self.parent_attr: Dict[str, List[ast.SchemaAttr]] = get_parent_attr_map( schema, module, {} ) def __str__(self): s = self.self_schema.name + ", attr:[" for name in self.self_schema.GetAttrNameList(): s += f"{name}, " s = s[:-2] + "]," for p in self.parent_attr: s += f" parent:{p}, attr:[" for attr in self.parent_attr[p]: s += f"{attr.name}, " s = s[:-2] + "]," return s def get_parent_attr_map( ori_schema: ast.SchemaStmt, module: ast.Module, result: Dict[str, List[ast.SchemaAttr]] = None, ) -> Optional[Dict[str, List[ast.SchemaAttr]]]: if not ori_schema or not module: return None assert isinstance(ori_schema, ast.SchemaStmt) assert isinstance(module, ast.Module) if not result: result = {} if not ori_schema.parent_name: return result else: # Current module and schema. full_schema_map: Dict[ast.Module, List[ast.SchemaStmt]] = { module: module.GetSchemaList() } # Import module and schemas. full_schema_map.update(get_import_schema(module)) # key : module , value: List[ast.SchemaStmt] for key, value in full_schema_map.items(): for schema in value: if schema.name == ori_schema.parent_name.get_name(): result[schema.name] = schema.GetAttrList() if schema.parent_name: get_parent_attr_map(schema, key, result) break else: continue break return result def get_full_schema_list(module: ast.Module) -> List[FullSchema]: """Get all FullSchema in a module""" schema_list = module.GetSchemaList() full_schema_list = [FullSchema(schema, module) for schema in schema_list] return full_schema_list class ListAttributePrinter: def __init__(self, file: str = None, config: Config = Config()) -> None: self.file = file self.name_len = config.name_len self.type_len = config.type_len self.default_len = config.default_len self.final_len = config.final_len self.optional_len = config.optional_len self.module = None self.schema_list = None self.import_schema_list = None self.full_schema_list = None def build_full_schema_list(self): self.module = parser.ParseFile(self.file) self.schema_list = self.module.GetSchemaList() self.import_schema_list = get_import_schema(self.module) self.full_schema_list = get_full_schema_list(self.module) def print(self): self.build_full_schema_list() if self.module: self.print_schema_list() self.print_schema_structures() def print_schema_list(self): print("------------ schema list ------------") file_path = self.module.filename file_name = pathlib.Path(file_path).name print("Here are schemas defined in {}:".format(file_name)) for schema in self.schema_list: print("- " + schema.name) print("Here are schemas imported to {}:".format(file_name)) for key, value in self.import_schema_list.items(): import_file_path = key.filename import_file_name = pathlib.Path(import_file_path).name if len(value) > 0: print("imported from {}".format(import_file_name)) for schema in value: print("- " + schema.name) def print_schema_structures(self): print("------------ schema structures ------------") for full_schema in self.full_schema_list: print("schema {}:".format(full_schema.self_schema.name)) self.print_header() for attr in full_schema.self_schema.GetAttrList(): self.print_schema_attr(attr) for key, value in full_schema.parent_attr.items(): print("attrs inherited from {}".format(key)) for attr in value: self.print_schema_attr(attr) print() def _print_schema_attr(self, attr: ast.SchemaAttr, default: str): print( "{:<{}}{:<{}}{:<{}}{:<{}}{:<{}}".format( # name attr.name if len(attr.name) <= self.name_len else attr.name[: self.name_len - 3] + "...", self.name_len, # type attr.type_str if len(attr.type_str) <= self.type_len else attr.type_str[: self.type_len - 3] + "...", self.type_len, # default default, self.default_len, "", self.final_len, # is_optional "" if attr.is_optional else "Required", self.optional_len, ) ) def print_schema_attr(self, attr: ast.SchemaAttr): if not attr: return assert isinstance(attr, ast.SchemaAttr) if attr.value and isinstance(attr.value, ast.SchemaExpr): """ Because ast node SchemaExpr is too long to print, when the default value of attr.value is a SchemaExpr,just print schema name,e.g.: schema Name: firstName : str lastName : str schema Person: name: Name = Name { firstName = "hello" lastName = "world" } ------------------------------------- schema Person: name type default ... name Name -> Name{...} """ default = ( attr.type_str if len(attr.type_str) <= (self.default_len - 5) else attr.type_str[: self.default_len - 5] ) + "{...}" self._print_schema_attr(attr, default) return with StringIO() as expr: printer.PrintAST(attr.value, expr) default_str = expr.getvalue() if len(default_str) > self.default_len or ("\n" in default_str): default_str = "..." self._print_schema_attr(attr, default_str) def print_header(self): print( "{:<{}}{:<{}}{:<{}}{:<{}}{:<{}}".format( # name "name", self.name_len, # type "type", self.type_len, # default "default", self.default_len, # is_final "is_final", self.final_len, # is_optional "is_optional", self.optional_len, ) )
kcl-lang/kcl-py
kclvm/tools/list_attribute/utils.py
utils.py
py
9,943
python
en
code
8
github-code
36
[ { "api_name": "dataclasses.dataclass", "line_number": 17, "usage_type": "name" }, { "api_name": "kclvm.kcl.ast.ast.Module", "line_number": 27, "usage_type": "attribute" }, { "api_name": "kclvm.kcl.ast.ast", "line_number": 27, "usage_type": "name" }, { "api_name": ...
3585569128
import pandas as pd import numpy as np import matplotlib.pyplot as plt master_list = list() with open("../Data_sets/corpus_2_unigram_sorted.txt") as fileobj: for line in fileobj: if line == "" or line == " " or line == "\n": continue l = line.strip(' ') l = l.strip('\n') line_split = l.split(' ') master_list.append((line_split[0],int(line_split[1]))) index = list() freq = list() for i in range(10000,11000): freq.append(master_list[i][1]) index.append(i) df = pd.DataFrame({'10000-11000': freq}, index=index) lines = df.plot.line() lines.set_title('Corpus 2 Zipfs Law') lines.set_xlabel('Rank') lines.set_ylabel('Frequency') plt.show()
tarun0409/nlp-assignment-3-4
zipfs.py
zipfs.py
py
705
python
en
code
0
github-code
36
[ { "api_name": "pandas.DataFrame", "line_number": 21, "usage_type": "call" }, { "api_name": "matplotlib.pyplot.show", "line_number": 26, "usage_type": "call" }, { "api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name" } ]
71050589225
import streamlit as st from langchain.llms import OpenAI from langchain.prompts import PromptTemplate st.title("💬 Prompt Critic") openai_api_key = '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' def prompt_critic(prompts): # Instantiate LLM model llm = OpenAI(model_name="gpt-4", openai_api_key=openai_api_key) # Prompt template = "As an expert prompt enigneer, critique this '{prompts}'. Provide feedback and areas of improvement. At the end, please improve it" prompt = PromptTemplate(input_variables=["prompts"], template=template) prompt_query = prompt.format(prompts=prompts) # Run LLM model response = llm(prompt_query) # Print results return st.info(response) with st.form("myform"): topic_text = st.text_input("Enter prompt:", "") submitted = st.form_submit_button("Submit") if not openai_api_key: st.info("Please add your OpenAI API key to continue.") elif submitted: prompt_critic(topic_text)
shihwesley/CMPE297
Prompt Engineering assignment/pages/1_Prompt Critic.py
1_Prompt Critic.py
py
990
python
en
code
0
github-code
36
[ { "api_name": "streamlit.title", "line_number": 5, "usage_type": "call" }, { "api_name": "langchain.llms.OpenAI", "line_number": 12, "usage_type": "call" }, { "api_name": "langchain.prompts.PromptTemplate", "line_number": 15, "usage_type": "call" }, { "api_name": ...
25376871762
from sklearn.model_selection import cross_val_score from sklearn.model_selection import cross_val_predict from sklearn.metrics import classification_report import numpy as np def get_cv_metrics(text_clf, train_data, train_class, k_split): accuracy_scores = cross_val_score(text_clf, # steps to convert raw messages into models train_data, # training data train_class, # training labels cv=k_split, # split data randomly into 10 parts: 9 for training, 1 for scoring scoring='accuracy', # which scoring metric? n_jobs=-1, # -1 = use all cores = faster ) cv_predicted = cross_val_predict(text_clf, train_data, train_class, cv=k_split) return np.mean(accuracy_scores), classification_report(train_class, cv_predicted)
abelsaug/EmpathyPrediction
CV_metrics.py
CV_metrics.py
py
1,078
python
en
code
0
github-code
36
[ { "api_name": "sklearn.model_selection.cross_val_score", "line_number": 7, "usage_type": "call" }, { "api_name": "sklearn.model_selection.cross_val_predict", "line_number": 14, "usage_type": "call" }, { "api_name": "numpy.mean", "line_number": 19, "usage_type": "call" }...
16127616120
import os import json from keras.models import load_model import pandas as pd import pickle import numpy as np import shutil from keras.preprocessing import image from tqdm.notebook import tqdm from PIL import ImageFile BASE_MODEL_PATH = os.path.join(os.getcwd(),"model") PICKLE_DIR = os.path.join(os.getcwd(),"pickle_files") JSON_DIR = os.path.join(os.getcwd(),"json_files") if not os.path.exists(JSON_DIR): os.makedirs(JSON_DIR) BEST_MODEL = os.path.join(BASE_MODEL_PATH,"self_trained","distracted-23-1.00.hdf5") model = load_model(BEST_MODEL) with open(os.path.join(PICKLE_DIR,"labels_list.pkl"),"rb") as handle: labels_id = pickle.load(handle) def path_to_tensor(img_path): # loads RGB image as PIL.Image.Image type img = image.load_img(img_path, target_size=(128, 128)) # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3) x = image.img_to_array(img) # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor return np.expand_dims(x, axis=0) def paths_to_tensor(img_paths): list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)] return np.vstack(list_of_tensors) ImageFile.LOAD_TRUNCATED_IMAGES = True # test_tensors = paths_to_tensor(data_test.iloc[:,0]).astype('float32')/255 - 0.5 # image_tensor = paths_to_tensor(image_path).astype('float32')/255 - 0.5 def predict_result(image_tensor): ypred_test = model.predict(image_tensor,verbose=1) ypred_class = np.argmax(ypred_test,axis=1) print(ypred_class) id_labels = dict() for class_name,idx in labels_id.items(): id_labels[idx] = class_name ypred_class = int(ypred_class) print(id_labels[ypred_class]) #to create a human readable and understandable class_name class_name = dict() class_name["c0"] = "SAFE_DRIVING" class_name["c1"] = "TEXTING_RIGHT" class_name["c2"] = "TALKING_PHONE_RIGHT" class_name["c3"] = "TEXTING_LEFT" class_name["c4"] = "TALKING_PHONE_LEFT" class_name["c5"] = "OPERATING_RADIO" class_name["c6"] = "DRINKING" class_name["c7"] = "REACHING_BEHIND" class_name["c8"] = "HAIR_AND_MAKEUP" class_name["c9"] = "TALKING_TO_PASSENGER" with open(os.path.join(JSON_DIR,'class_name_map.json'),'w') as secret_input: json.dump(class_name,secret_input,indent=4,sort_keys=True) with open(os.path.join(JSON_DIR,'class_name_map.json')) as secret_input: info = json.load(secret_input) label = info[id_labels[ypred_class]] print(label) return label
Abhinav1004/Distracted-Driver-Detection
demo_on_video/driver_prediction.py
driver_prediction.py
py
2,607
python
en
code
37
github-code
36
[ { "api_name": "os.path.join", "line_number": 13, "usage_type": "call" }, { "api_name": "os.path", "line_number": 13, "usage_type": "attribute" }, { "api_name": "os.getcwd", "line_number": 13, "usage_type": "call" }, { "api_name": "os.path.join", "line_number":...
26910125965
#!/usr/bin/python3 import sys import re import string import xml.etree.ElementTree as ET import getopt import math import codecs import time import png # global variables inputFile = "" outputFile = "" parseAll = True timeFrom = "" timeTo = "" objectNames = "" eventTypes = "" actionNames = "" objectClasses = "" pathSubstr = "" textSubstr = "" timeFromMs = 0 timeToMs = 0 tree = 0 root = 0 windowWidth = 0; windowHeight = 0; clickCnt = 0 dblClickCnt = 0 leftDblClickCnt = 0 rightDblClickCnt = 0 middleDblClickCnt = 0 leftClickCnt = 0 rightClickCnt = 0 middleClickCnt = 0 dragLength = 0 leftDragLength = 0 rightDragLength = 0 middleDragLength = 0 mat = 0 # Print help def help(): print("\nlogProcessing.py -i <inputFilePath/inputFileName.xml> [-o <outputFilePath/outputFileName.xml>] [-f <hh:mm:ss>] [-t <hh:mm:ss>] [-e <event1,event2,...>] [-a <action1,action2,...>] [-n <object1,object2,...>]\n\n\ -i Full path to input xml file.\n\ -o Full path to output xml file, that will be created.\n\ -f Beginning of the restrictive time interval.\n\ -t End of the restrictive time interval.\n\ -e Names of events, which should be processed, separated by ','. If not set, all events will be processed.\n\ Possible values: mouseevent, wheelevent, keyboardevent, specialevent, customevent\n\ -a Actions, which should be processed, separated by ','. Works only for mouseevent and wheelevent. If not set, all actions will be processed.\n\ Possible values: (click, doubleclick, drag, menuclick) - for mouseevent; (rollup, rolldown) - for wheelevent \n\ -n Names of the objects, which should be processed, separated by ','.\n\ -c Names of object classes, which should be processed, separated by ','.\n\ -p String, which will be searched in object path.\n\ -s String, which will be searched in object text.\n\ ") # Process console parametrs def processParameters(argv): global inputFile global outputFile global parseAll global timeFrom global timeTo global timeFromMs global timeToMs global objectNames global eventTypes global actionNames global objectClasses global pathSubstr global textSubstr try: opts, args = getopt.getopt(argv,"hi:o:f:t:e:a:n:c:p:s:",["ifile=","ofile=","from=","to=","events=","actions=","objects=","classes=","path=","text="]) except getopt.GetoptError: help() sys.exit(2) for opt, arg in opts: if opt == '-h': help() sys.exit() elif opt in ("-i", "--ifile"): inputFile = arg elif opt in ("-o", "--ofile"): outputFile = arg elif opt in ("-f", "--from"): timeFrom = arg elif opt in ("-t", "--to"): timeTo = arg elif opt in ("-e", "--events"): eventTypes = arg elif opt in ("-a", "--actions"): actionNames = arg elif opt in ("-n", "--objects"): objectNames = arg elif opt in ("-c", "--classes"): objectClasses = arg elif opt in ("-p", "--path"): pathSubstr = arg elif opt in ("-s", "--text"): textSubstr = arg # some non-optional arguments missing if (inputFile == ""): help() sys.exit(2) if (outputFile == ""): outputFile = "out.xml" # process given time interval (convert times to miliseconds) if ((timeFrom != "") | (timeTo != "")): parseAll = False if (timeFrom != ""): timeFrom += ":000" if (timeTo != ""): timeTo += ":000" # Parse one event (xml element) def parseEvent(event): global objectNames global eventTypes global actionNames global tree global root global clickCnt global leftClickCnt global rightClickCnt global middleClickCnt global dblClickCnt global leftDblClickCnt global rightDblClickCnt global middleDblClickCnt global dragLength global leftDragLength global rightDragLength global middleDragLength global objectClasses global windowWidth global windowHeight global mat global pathSubstr global textSubstr # remove event with wrong type if ((eventTypes != "") & (eventTypes.find(event.get("type")) == -1)): root.remove(event) return # remove event with wrong action if ((actionNames != "") & ((event.get("type") == "mouseevent") | (event.get("type") == "wheelevent"))): try: actionNames.split(",").index(event.find("action").text) except ValueError: root.remove(event) return # remove event with wrong objectClass if (objectClasses != ""): if (event.find("objectClass").text == None): root.remove(event) return if (objectClasses.find(event.find("objectClass").text) == -1): root.remove(event) return # remove event with wrong objectName if (objectNames != ""): if (event.find("objectName").text == None): root.remove(event) return if (objectNames.find(event.find("objectName").text) == -1): root.remove(event) return # remove event with wrong objectPath if (pathSubstr != ""): if (event.find("objectPath").text == None): root.remove(event) return if ((event.find("objectPath").text).find(pathSubstr) == -1): root.remove(event) return # remove event with wrong objectText if (textSubstr != ""): if (event.find("objectText").text == None): root.remove(event) return if ((event.find("objectText").text).find(textSubstr) == -1): root.remove(event) return # count mouse clicks, double click and drag length if (event.get("type") == "mouseevent"): if (event.find("action").text == "click"): clickCnt += 1 x, y = event.find("position").text.split(":") mat[int(y)][int(x)*2] += 1; if (event.find("mouseButton").text == "left"): leftClickCnt += 1 elif (event.find("mouseButton").text == "right"): rightClickCnt += 1 elif (event.find("mouseButton").text == "middle"): middleClickCnt += 1 elif (event.find("action").text == "doubleclick"): dblClickCnt += 1 x, y = event.find("position").text.split(":") mat[int(y)][int(x)*2] += 1; if (event.find("mouseButton").text == "left"): leftDblClickCnt += 1 elif (event.find("mouseButton").text == "right"): rightDblClickCnt += 1 elif (event.find("mouseButton").text == "middle"): middleDblClickCnt += 1 elif (event.find("action").text == "drag"): startX, startY = event.find("startPosition").text.split(":") endX, endY = event.find("endPosition").text.split(":") distance = math.sqrt(math.pow((int(endX) - int(startX)), 2) + math.pow((int(endY) - int(startY)), 2)) dragLength += distance if (event.find("mouseButton").text == "left"): leftDragLength += distance elif (event.find("mouseButton").text == "right"): rightDragLength += distance elif (event.find("mouseButton").text == "middle"): middleDragLength += distance # Load input xml file and parse it def parseFile(): global inputFile global outputFile global parseAll global timeFrom global timeTo global timeFromMS global timeToMs global tree global root global windowWidth global windowHeight global mat inFile = codecs.open(inputFile, mode='r') # parse file tree = ET.parse(inFile) # get root element root = tree.getroot() # get window size width, height = root.get("windowSize").split(":") windowWidth = int(width) windowHeight = int(height) # create matrix which is 2*wider than window (alpha channel) mat = [[0 for x in range(windowWidth*2)] for y in range(windowHeight)] # find all events events = root.findall("event") # get start and end time start = (timeFrom if (timeFrom != "") else events[0].find("time").text) end = (timeTo if (timeTo != "") else events[len(events)-1].find("time").text) # convert it to miliseconds hFrom, mFrom, sFrom, msFrom = start.split(":") timeFromMs = int(hFrom) * 3600000 + int(mFrom) * 60000 + int(sFrom) * 1000 + int(msFrom) hTo, mTo, sTo, msTo = end.split(":") timeToMs = int(hTo) * 3600000 + int(mTo) * 60000 + int(sTo) * 1000 + int(msTo) # count duration and convert it to readeable string durationMs = timeToMs - timeFromMs duration = str(int(durationMs/3600000)) if ((durationMs/3600000) > 9) else ("0" + str(int(durationMs/3600000))) durationMs -= int(durationMs/3600000) * 3600000 duration += str(":" + str(int(durationMs/60000))) if ((durationMs/60000) > 9) else (":0" + str(int(durationMs/60000))) durationMs -= int(durationMs/60000) * 60000 duration += str(":" + str(int(durationMs/1000))) if ((durationMs/1000) > 9) else (":0" + str(int(durationMs/1000))) durationMs -= int(durationMs/1000) * 1000 duration += str(":" + str(durationMs)) # print all arguments - it is here, because i need to get start and end time from file (if it is not set) print("\nParameters:") print(" Input file: " + inputFile) print(" Output file: " + outputFile) print(" Start time: " + start) print(" End time: " + end) print(" Duration: " + str(duration)) print(" Event types: " + eventTypes) print(" Action names: " + actionNames) print(" Object names: " + objectNames) print(" Object classes: " + objectClasses) print(" Text substring: " + textSubstr) print(" Path substring: " + pathSubstr) print("\n") # go thru all events for event in events: # no time interval given, process all events if (parseAll): parseEvent(event) else: # get event time and convert it to miliseconds h, m, s, ms = event[0].text.split(":") time = int(h) * 3600000 + int(m) * 60000 + int(s) * 1000 + int(ms) # remove events that are not in given time interval, process the others if (timeTo == ""): if ((timeFrom != "") & (time < timeFromMs)): root.remove(event) elif ((timeFrom != "") & (time >= timeFromMs)): parseEvent(event) elif (timeFrom == ""): if ((timeTo != "") & (time > timeToMs)): root.remove(event) elif ((timeTo != "") & (time <= timeToMs)): parseEvent(event) elif ((time < timeFromMs) | (time > timeToMs)): root.remove(event) elif ((time >= timeFromMs) & (time <= timeToMs)): parseEvent(event) # Create png image with heat map def createHeatMap(): global mat maxVal = 0; newMat = [[0 for x in range(windowWidth*2)] for y in range(windowHeight)] # copy value in matrix (which is bigger than 0) to 3x3 neighborhood (for better visibility in final image) for x in range(1, windowHeight-1): for y in range(2, windowWidth*2, 2): val = mat[x][y] if (val > 0): for k in range(-1, 2): for j in range(-2, 3, 2): if (mat[x+k][y+j] <= val): newMat[x+k][y+j] = val # get max click count for x in range(windowHeight): for y in range(0, windowWidth*2, 2): if (newMat[x][y] > maxVal): maxVal = newMat[x][y] # convert click counts to intensity value if (maxVal != 0): for x in range(windowHeight): for y in range(0, windowWidth*2, 2): newMat[x][y] *= int(255/maxVal) if (newMat[x][y] > 0): newMat[x][y+1] = 255; # save image png.from_array(newMat, 'LA').save("heat_map.png") # Main def main(argv): processParameters(argv) parseFile() createHeatMap() # write modified xml to output file tree.write(outputFile) # write statistics print("Clicks count: " + str(clickCnt)) print(" Left mouse button clicks count: " + str(leftClickCnt)) print(" Right mouse button clicks count: " + str(rightClickCnt)) print(" Middle mouse button clicks count: " + str(middleClickCnt)) print("\n") print("Doubleclicks count: " + str(dblClickCnt)) print(" Left mouse button doubleclicks count: " + str(leftDblClickCnt)) print(" Right mouse button doubleclicks count: " + str(rightDblClickCnt)) print(" Middle mouse button doubleclicks count: " + str(middleDblClickCnt)) print("\n") print("Drag length: " + str(dragLength)) print(" Left mouse button drag length: " + str(leftDragLength)) print(" Right mouse button drag length: " + str(rightDragLength)) print(" Middle mouse button drag length: " + str(middleDragLength)) if __name__ == "__main__": main(sys.argv[1:])
SindenDev/3dimviewer
applications/3DimViewer/tools/activity_logging/logProcessing.py
logProcessing.py
py
11,807
python
en
code
9
github-code
36
[ { "api_name": "getopt.getopt", "line_number": 83, "usage_type": "call" }, { "api_name": "getopt.GetoptError", "line_number": 84, "usage_type": "attribute" }, { "api_name": "sys.exit", "line_number": 86, "usage_type": "call" }, { "api_name": "sys.exit", "line_n...
14267295600
from typing import Any from data_structures.stacks.stack import Stack, PopEmpty class StackWithBottom(Stack): def __init__(self): self._bottom = None super(StackWithBottom, self).__init__() def push(self, value: Any): super(StackWithBottom, self).push(value) if not self._bottom: self._bottom = self._top def pop(self): value = super(StackWithBottom, self).pop() if self.is_empty(): self._bottom = None return value def pop_bottom(self): if not self._bottom: raise PopEmpty() value = self._bottom.value self._bottom = self._bottom.before return value @property def bottom(self): return self._bottom class StackOfStacks(object): def __init__(self, limit): self._limit = limit self.stacks = list() self.stacks.append(StackWithBottom()) def push(self, value): if not self.stacks: self.stacks.append(StackWithBottom()) if len(self.stacks[-1]) >= self._limit: self.stacks.append(StackWithBottom()) self.stacks[-1].push(value) def pop(self) -> Any: if not self.stacks: raise PopEmpty value = self.stacks[-1].pop() if self.stacks[-1].is_empty(): # Remove empty stack self.stacks.pop() return value def pop_at(self, index): if len(self.stacks) < index: raise Exception("No such stack") stack = self.stacks[index] value = stack.pop() if not stack.bottom: del self.stacks[index] else: self.left_shift(index) return value def left_shift(self, index): if len(self.stacks) > index + 1: value = self.stacks[index + 1].pop_bottom() self.stacks[index].push(value) index += 1 if not self.stacks[index].bottom: del self.stacks[index] else: self.left_shift(index)
goncalossantos/CtCI
chapter_3/stack_of_stacks.py
stack_of_stacks.py
py
2,062
python
en
code
0
github-code
36
[ { "api_name": "data_structures.stacks.stack.Stack", "line_number": 6, "usage_type": "name" }, { "api_name": "typing.Any", "line_number": 11, "usage_type": "name" }, { "api_name": "data_structures.stacks.stack.PopEmpty", "line_number": 25, "usage_type": "call" }, { ...
5063097451
from intervaltree import Interval as interval, IntervalTree class OutputExporter(object): def __init__( self, mz_prec ): self.mz_prec = mz_prec self.BG = None def iBG(self, node_type): '''Iterate over all nodes of a given type in the whole big graph **BG** of solved subproblems. node_type - either ''' assert node_type in ('G','I','M'), "specified wrong type of node. Was %s. Should be G, I, M" % node_type for r in self.BG: SG = r['SG'] for N in SG: N_D = SG.node[N] if N_D['type'] == node_type: yield N, N_D def add_mz_ranges_to_results(self, masstodon_res): '''Add information about the m/z ranges for the G nodes.''' self.BG = masstodon_res prec = self.mz_prec I_tree = IntervalTree(interval(I_D['mz']-prec,I_D['mz']+prec) for _,I_D in self.iBG('I')) I_tree.split_overlaps() for G, G_D in self.iBG('G'): min_mz, max_mz = G_D['min_mz'], G_D['max_mz'] if min_mz == max_mz: ## This copes with stupid border issues. ## iso_intervals = I_tree[II(min_mz-prec/10., max_mz+prec/10.)] # set digits to mz_prec/10 iso_intervals = I_tree[min_mz] else: iso_intervals = I_tree[interval(min_mz, max_mz)] if len(iso_intervals) == 1: mz = iso_intervals.pop() G_D['mz_L'] = mz.begin G_D['mz_R'] = mz.end else: G_D['mz_L'] = G_D['mz_R'] = None def iter_G(self): '''Iterate over information on experimental groupings G.''' for cluster_id, r in enumerate(self.BG): SG = r['SG'] for G in SG: if SG.node[G]['type'] == 'G': G_D = SG.node[G] if G_D['mz_L'] and G_D['mz_R']: yield { 'mz_L': G_D['mz_L'], 'mz_R': G_D['mz_R'], 'tot_estimate': G_D['estimate'], 'tot_intensity':G_D['intensity'], 'cluster_id': cluster_id, 'G_tag': G } def iter_MIG(self): '''Iterate over information on pathways MIG.''' for cluster_id, r in enumerate(self.BG): SG = r['SG'] for M in SG: if SG.node[M]['type'] == 'M': M_D = SG.node[M] for I in SG[M]: I_D = SG.node[I] for G in SG[I]: if SG.node[G]['type'] == 'G': G_D = SG.node[G] yield { 'formula': M_D['formula'], 'molType': M_D['molType'], 'q': M_D['q'], 'g': M_D['g'], 'mz_L': G_D['mz_L'], 'mz_R': G_D['mz_R'], 'estimate': SG.edge[G][I]['estimate'], 'tot_estimate_tmp': G_D['estimate'], # these are repeating 'tot_intensity_tmp':G_D['intensity'], # these are repeating 'cluster_id': cluster_id, 'G_tag': G, 'I_tag': I, 'M_tag': M } def make_data_for_spectrum_plot(self): return {'G_nodes_data': list(self.iter_G()), 'MIG_paths_data': list(self.iter_MIG()) }
MatteoLacki/MassTodonPy
MassTodonPy/Outputting/export_outputs.py
export_outputs.py
py
3,880
python
en
code
1
github-code
36
[ { "api_name": "intervaltree.IntervalTree", "line_number": 28, "usage_type": "call" }, { "api_name": "intervaltree.Interval", "line_number": 28, "usage_type": "call" }, { "api_name": "intervaltree.Interval", "line_number": 38, "usage_type": "call" } ]
5314308477
import plotly.express as px import pandas as pd import numpy as np import plotly.graph_objs as go from numpy.core.fromnumeric import shape def bar_chart(df): df2 = df[(df['homelessness'] == 'Overall Homeless') & (df['state'] == 'Total')] barchart = px.bar(df2, x = 'year' , y = 'number' , title = 'Year wise count of Overall Homeless people in USA' , color='year') barchart.update_layout({'title_x': 0.5}) return barchart def line_chart1(df): df3 = df[(df['state'] != 'Total')] df3 = df3.groupby(['state','year'])['number'].sum().reset_index() #df4 = df3.groupby('state')['number'].sum().reset_index() line_chart_1 = px.line(df3, x = 'year', y = 'number',color='state', title= 'Year on Year Homeless Trend statewise') line_chart_1.update_layout({'title_x': 0.5}) return line_chart_1 def corrplot(df): corr_plot = px.imshow(df.corr(), zmin=-1, zmax=1, color_continuous_scale='rdbu', title='Master Correlation Plot') corr_plot.update_layout({'title_x': 0.5}) return corr_plot def pie1(df): df_1 = df[(df['homelessness'] == 'Chronically Homeless Individuals' ) & (df['state'] != 'Total')] df_1 = df_1.groupby(['year','state','region'])['number'].sum().reset_index() pie_1= px.pie( data_frame=df_1, names='region', values='number', color='region', title='Region wise Chronically Homeless Individuals', template=None, width=None, height=None, opacity=None, hole=0.8 ) pie_1.update_layout({'title_x': 0.5}) return pie_1 def pie2(df): df_1 = df[(df['homelessness'] == 'Chronically Homeless Individuals' ) & (df['state'] != 'Total')] df_1 = df_1.groupby(['year','state','region'])['number'].sum().reset_index() pie_2= px.pie( data_frame=df_1, names='state', values='number', color='region', title='State wise Chronically Homeless Individuals', color_discrete_sequence=px.colors.sequential.RdBu, template=None, width=1000, height=1000, opacity=None, hole=0.3 ) pie_2.update_layout({'title_x': 0.5}) return pie_2 def scat1(df): df_2 = df[(df['homelessness'] == 'Chronically Homeless People in Families')|(df['homelessness'] =='Unsheltered Chronically Homeless' )|(df['homelessness'] =='Sheltered Total Chronically Homeless') | (df['homelessness'] == 'Chronically Homeless Individuals') & (df['region'] != 'Total')] scat_1 = px.scatter(df_2, x="homelessness", y="number", title="Scatterplot of Chronically homeless population",color="year", size='number' ) scat_1.update_layout({'title_x': 0.5}) return scat_1 def scat2(df): scat_2 = px.scatter(df, x="year", y="number", title="Scatterplot of homeless population through years",color="homelessness", size='number' ) scat_2.update_layout({'title_x': 0.5}) return scat_2 def scat3(df): df_1 = df[(df['homelessness'] == 'Chronically Homeless Individuals' ) & (df['state'] != 'Total')] df_1 = df_1.groupby(['year','state','region'])['number'].sum().reset_index() scat_3 = px.scatter(df_1, x="year", y="number", color="region", facet_row=None, facet_col="region", title='Scatterplot of Homeless Population through Years Across Regions') scat_3.update_layout({'title_x': 0.5}) return scat_3 def chlor(df): overall=df[(df.homelessness=='Sheltered ES Homeless') & ((df.state!='Total') & (df.state != 'CA') & (df.state != 'NY') & (df.state != 'MA') & (df.state != 'PA'))] overall=overall.sort_values(by = 'year', ascending = True) choro = px.choropleth(overall, locations='state', locationmode="USA-states", color='number', animation_frame="year", scope="usa", color_continuous_scale="oranges", title='Homeless count on Region level for all States') choro.update_layout({'title_x': 0.5}) return choro def get_ratio(df): shel = 'Sheltered Total Homeless' totl = 'Overall Homeless' def minidf(df, count_type): temp_df = df.loc[df.homelessness == count_type] return temp_df.drop(labels='homelessness', axis=1).rename({'number': count_type}, axis=1) ratio_df = pd.merge( minidf(df, shel), minidf(df, totl), on=['year', 'state', 'state_new', 'region'] ) # Ratio DF building complete ratio_df.insert(len(ratio_df.columns), 'pct_sheltered', ratio_df.apply(lambda x: x[shel] / x[totl], axis=1)) return ratio_df def implot(df,rdf): # Turn to np for better vis of timelines use in px.imshow statecodes = df.loc[df.state_new == 'State'].state.unique() matrix = np.array([rdf.loc[rdf.state == ST].sort_values(by='year').pct_sheltered.to_numpy() for ST in statecodes]) imf = px.imshow( np.transpose(matrix), y=np.linspace(2007,2018,12), x=statecodes, range_color=[0,1], origin='lower', labels={ 'x': 'State', 'y': 'Year' } ) imf.update_layout(title={'text': 'Sheltered Ratio', 'x': 0.5}) imf.update_xaxes(dtick=1) imf.update_yaxes(dtick=1) return (imf, matrix, statecodes) def sidbox(df): df_1 = df[(df['homelessness'] == 'Chronically Homeless Individuals' ) & (df['state'] != 'Total')] df_1 = df_1.groupby(['year','state','region'])['number'].sum().reset_index() sid_box = px.box(df_1, x="region", y="number", title = "Boxplot analyis in each region with the count") sid_box.update_layout( font_family="Courier New", font_color="blue", title_font_family="Times New Roman", title_font_color="red", legend_title_font_color="green", title_x = 0.5 ) return sid_box def stackbar(df): #stacked - bar chronically_homeless = ['Chronically Homeless','Chronically Homeless Individuals','Chronically Homeless People in Families'] Overall_homeless = ['Overall Homeless'] Homeless_individuals = ['Homeless Children of Parenting Youth', 'Homeless Family Households', 'Homeless Individuals', 'Homeless Parenting Youth (Under 25)', 'Homeless Parenting Youth Age 18-24', 'Homeless Parenting Youth Under 18', 'Homeless People in Families', 'Homeless Unaccompanied Youth (Under 25)', 'Homeless Unaccompanied Youth Age 18-24', 'Homeless Unaccompanied Youth Under 18', 'Homeless Veterans'] Sheltered_Chronically_homeless = ['Sheltered ES Chronically Homeless', 'Sheltered ES Chronically Homeless Individuals', 'Sheltered ES Chronically Homeless People in Families'] Sheltered_homeless = ['Sheltered ES Homeless', 'Sheltered ES Homeless Children of Parenting Youth', 'Sheltered ES Homeless Family Households', 'Sheltered ES Homeless Individuals', 'Sheltered ES Homeless Parenting Youth (Under 25)', 'Sheltered ES Homeless Parenting Youth Age 18-24', 'Sheltered ES Homeless Parenting Youth Under 18', 'Sheltered ES Homeless People in Families', 'Sheltered ES Homeless Unaccompanied Youth (Under 25)', 'Sheltered ES Homeless Unaccompanied Youth Age 18-24', 'Sheltered ES Homeless Unaccompanied Youth Under 18', 'Sheltered ES Homeless Veterans', 'Sheltered SH Chronically Homeless', 'Sheltered SH Chronically Homeless Individuals', 'Sheltered SH Homeless', 'Sheltered SH Homeless Individuals', 'Sheltered SH Homeless Unaccompanied Youth (Under 25)', 'Sheltered SH Homeless Unaccompanied Youth Age 18-24', 'Sheltered SH Homeless Unaccompanied Youth Under 18', 'Sheltered SH Homeless Veterans', 'Sheltered TH Homeless', 'Sheltered TH Homeless Children of Parenting Youth', 'Sheltered TH Homeless Family Households', 'Sheltered TH Homeless Individuals', 'Sheltered TH Homeless Parenting Youth (Under 25)', 'Sheltered TH Homeless Parenting Youth Age 18-24', 'Sheltered TH Homeless Parenting Youth Under 18', 'Sheltered TH Homeless People in Families', 'Sheltered TH Homeless Unaccompanied Youth (Under 25)', 'Sheltered TH Homeless Unaccompanied Youth Age 18-24', 'Sheltered TH Homeless Unaccompanied Youth Under 18', 'Sheltered TH Homeless Veterans', 'Sheltered Total Chronically Homeless', 'Sheltered Total Chronically Homeless Individuals', 'Sheltered Total Chronically Homeless People in Families', 'Sheltered Total Homeless', 'Sheltered Total Homeless Children of Parenting Youth', 'Sheltered Total Homeless Family Households', 'Sheltered Total Homeless Individuals', 'Sheltered Total Homeless Parenting Youth (Under 25)', 'Sheltered Total Homeless Parenting Youth Age 18-24', 'Sheltered Total Homeless Parenting Youth Under 18', 'Sheltered Total Homeless People in Families', 'Sheltered Total Homeless Unaccompanied Youth (Under 25)', 'Sheltered Total Homeless Unaccompanied Youth Age 18-24', 'Sheltered Total Homeless Unaccompanied Youth Under 18', 'Sheltered Total Homeless Veterans'] Unsheltered_homeless = ['Unsheltered Homeless', 'Unsheltered Homeless Children of Parenting Youth', 'Unsheltered Homeless Family Households', 'Unsheltered Homeless Individuals', 'Unsheltered Homeless Parenting Youth (Under 25)', 'Unsheltered Homeless Parenting Youth Age 18-24', 'Unsheltered Homeless Parenting Youth Under 18', 'Unsheltered Homeless People in Families', 'Unsheltered Homeless Unaccompanied Youth (Under 25)', 'Unsheltered Homeless Unaccompanied Youth Age 18-24', 'Unsheltered Homeless Unaccompanied Youth Under 18', 'Unsheltered Homeless Veterans' ] unsheltered_chronically_homeless = ['Unsheltered Chronically Homeless', 'Unsheltered Chronically Homeless Individuals', 'Unsheltered Chronically Homeless People in Families'] df.loc[df['homelessness'].isin(chronically_homeless) , 'homeless_type'] = 'chronically_homeless' df.loc[df['homelessness'].isin(Homeless_individuals) , 'homeless_type'] = 'Homeless_individuals' df.loc[df['homelessness'].isin(Unsheltered_homeless) , 'homeless_type'] = 'Unsheltered_homeless' df.loc[df['homelessness'].isin(unsheltered_chronically_homeless) , 'homeless_type'] = 'Unsheltered_chronically_homeless' df.loc[df['homelessness'].isin(Sheltered_Chronically_homeless) , 'homeless_type'] = 'Sheltered_Chronically_homeless' df.loc[df['homelessness'].isin(Sheltered_homeless) , 'homeless_type'] = 'Sheltered_homeless' df.loc[df['homelessness'].isin(Overall_homeless) , 'homeless_type'] = 'Overall_homeless' # df.head(2) df8 = df.groupby(['year','homeless_type'])['number'].sum().reset_index() # df8.head(10) # stacked = df8[(df8['state'] == 'Total')] stacked = px.bar( df8, x = 'year' , y = 'number' , title = 'Year on Year Proportions of Homeless Type' , color='homeless_type', pattern_shape_sequence=[".", "x", "+"], pattern_shape='homeless_type' ) stacked.update_layout(title_text='year on Year Proportions of Homeless Type', title_x=0.5, title_font_color="magenta") return stacked def line_2(df): df_3 = df[(df['region'] == 'west') & ((df['homelessness'] == 'Chronically Homeless People in Families')|(df['homelessness'] =='Unsheltered Chronically Homeless' ) | (df['homelessness'] =='Sheltered Total Chronically Homeless') | (df['homelessness'] == 'Chronically Homeless Individuals')) ] df_3 = df_3.groupby(['year','state'])['number'].sum().reset_index() line2 = px.line(df_3, x="year", y="number",color='state',title='Chronical Homelessness trend spawning over years in west region of USA') line2.update_layout(title_x=0.5) return line2 def area1(df): df_4 = df[(df['region'] == 'southwest') & ((df['homelessness'] == 'Chronically Homeless People in Families')|(df['homelessness'] =='Unsheltered Chronically Homeless' ) | (df['homelessness'] =='Sheltered Total Chronically Homeless') | (df['homelessness'] == 'Chronically Homeless Individuals')) ] df_4 = df_4.groupby(['year','state'])['number'].sum().reset_index() area_1=px.area(df_4, x="year", y="number", color="state", line_group="state") title='Chronical Homelessness trend spawning over years in southwest region of USA' area_1.update_layout(title_text='Chronical Homelessness trend spawning over years in southwest region of USA', title_x=0.5, title_font_color="blue") return area_1 def vio_plot(df): df_4 = df[(df['region'] == 'southwest') & ((df['homelessness'] == 'Chronically Homeless People in Families')|(df['homelessness'] =='Unsheltered Chronically Homeless' ) | (df['homelessness'] =='Sheltered Total Chronically Homeless') | (df['homelessness'] == 'Chronically Homeless Individuals')) ] df_4 = df_4.groupby(['year','state'])['number'].sum().reset_index() vio=px.violin(df_4, x="state", y="number",title='Statistical attributes of Southwest region states ', color='state') vio.update_layout(title_x=0.5) return vio def sun_plot(df): df7 = df[df['state']!= 'Total'] sun = px.sunburst(df7, path=['region', 'state'], values='number', height=600, title='State wise homeless population distribution') sun.update_layout(title_x=0.5) return sun def sun_plot_1(df): df_2 = df[ ( (df['homelessness'] == 'Chronically Homeless People in Families') | (df['homelessness'] =='Unsheltered Chronically Homeless' ) | (df['homelessness'] =='Sheltered Total Chronically Homeless') | (df['homelessness'] == 'Chronically Homeless Individuals') ) & ( df['region'] != 'Total' ) ] sun_1 = px.sunburst( df_2, values='number', path=['region','homelessness'], ids=None, color=None, color_continuous_scale=None, range_color=None, color_continuous_midpoint=None, color_discrete_sequence=None, color_discrete_map=None, hover_name=None, hover_data=None, custom_data=None, labels=None, title='Chronical data distribution data in various regions', template=None, width=None, height=750, branchvalues=None, maxdepth=None ) sun_1.update_layout(title_x=0.5) return sun_1 def mjbox(df): df_m1 = df[(df['homelessness'] == 'Overall Homeless' ) & (df['region'] == 'west')] bx1=px.box(df_m1,x='year',y='number',color='year',title='Descriptive Statistics of Overall Homeless in West') return bx1
MSidda/Plotly-Dashboard
utilities/vis.py
vis.py
py
13,487
python
en
code
0
github-code
36
[ { "api_name": "plotly.express.bar", "line_number": 9, "usage_type": "call" }, { "api_name": "plotly.express", "line_number": 9, "usage_type": "name" }, { "api_name": "plotly.express.line", "line_number": 17, "usage_type": "call" }, { "api_name": "plotly.express", ...
43751035063
from __future__ import unicode_literals import os from collections import OrderedDict, namedtuple from operator import itemgetter from pathlib import Path import six if six.PY2: from collections import MutableSequence, Sized elif six.PY3: from collections.abc import MutableSequence, Sized class Table(MutableSequence): def __init__(self, fields, meta=None): from rows.fields import slug # TODO: should we really use OrderedDict here? # TODO: should use slug on each field name automatically or inside each # plugin? self.fields = OrderedDict( [ (slug(field_name), field_type) for field_name, field_type in OrderedDict(fields).items() ] ) # TODO: should be able to customize row return type (namedtuple, dict # etc.) self.Row = namedtuple("Row", self.field_names) self._rows = [] self.meta = dict(meta) if meta is not None else {} @classmethod def copy(cls, table, data): table = cls(fields=table.fields, meta=table.meta) table._rows = list(data) # TODO: verify data? return table def head(self, n=10): return Table.copy(self, self._rows[:n]) def tail(self, n=10): return Table.copy(self, self._rows[-n:]) def _repr_html_(self): import rows.plugins convert_to_html = rows.plugins.html.export_to_html total = len(self) if total <= 20: result = convert_to_html(self, caption=True) else: # Show only head and tail representation = Table( fields=OrderedDict( [ (field_name, rows.fields.TextField) for field_name in self.field_names ] ), meta={"name": self.name}, ) for row in self.head(): representation.append( { field_name: field_type.serialize(getattr(row, field_name)) for field_name, field_type in self.fields.items() } ) representation.append( {field_name: "..." for field_name in self.field_names} ) for row in self.tail(): representation.append( { field_name: field_type.serialize(getattr(row, field_name)) for field_name, field_type in self.fields.items() } ) result = convert_to_html(representation, caption=True).replace( b"</caption>", b" (showing 20 rows, out of " + str(total).encode("ascii") + b")</caption>", ) return result.decode("utf-8") @property def field_names(self): return list(self.fields.keys()) @property def field_types(self): return list(self.fields.values()) @property def name(self): """Define table name based on its metadata (filename used on import) If `filename` is not available, return `table1`. """ from rows.fields import slug name = self.meta.get("name", None) if name is not None: return slug(name) source = self.meta.get("source", None) if source and source.uri: return slug(os.path.splitext(Path(source.uri).name)[0]) return "table1" def __repr__(self): length = len(self._rows) if isinstance(self._rows, Sized) else "?" imported = "" if "imported_from" in self.meta: imported = " (from {})".format(self.meta["imported_from"]) return "<rows.Table{} {} fields, {} rows>".format( imported, len(self.fields), length ) def _make_row(self, row): # TODO: should be able to customize row type (namedtuple, dict etc.) return [ field_type.deserialize(row.get(field_name, None)) for field_name, field_type in self.fields.items() ] def append(self, row): """Add a row to the table. Should be a dict""" self._rows.append(self._make_row(row)) def __len__(self): return len(self._rows) def __getitem__(self, key): key_type = type(key) if key_type == int: return self.Row(*self._rows[key]) elif key_type == slice: return Table.copy(self, self._rows[key]) elif key_type is six.text_type: try: field_index = self.field_names.index(key) except ValueError: raise KeyError(key) # TODO: should change the line below to return a generator exp? return [row[field_index] for row in self._rows] else: raise ValueError("Unsupported key type: {}".format(type(key).__name__)) def __setitem__(self, key, value): key_type = type(key) if key_type == int: self._rows[key] = self._make_row(value) elif key_type is six.text_type: from rows import fields values = list(value) # I'm not lazy, sorry if len(values) != len(self): raise ValueError( "Values length ({}) should be the same as " "Table length ({})".format(len(values), len(self)) ) field_name = fields.slug(key) is_new_field = field_name not in self.field_names field_type = fields.detect_types( [field_name], [[value] for value in values] )[field_name] self.fields[field_name] = field_type self.Row = namedtuple("Row", self.field_names) if is_new_field: for row, value in zip(self._rows, values): row.append(field_type.deserialize(value)) else: field_index = self.field_names.index(field_name) for row, value in zip(self._rows, values): row[field_index] = field_type.deserialize(value) else: raise ValueError("Unsupported key type: {}".format(type(key).__name__)) def __delitem__(self, key): key_type = type(key) if key_type == int: del self._rows[key] elif key_type is six.text_type: try: field_index = self.field_names.index(key) except ValueError: raise KeyError(key) del self.fields[key] self.Row = namedtuple("Row", self.field_names) for row in self._rows: row.pop(field_index) else: raise ValueError("Unsupported key type: {}".format(type(key).__name__)) def insert(self, index, row): self._rows.insert(index, self._make_row(row)) def __radd__(self, other): if other == 0: return self raise ValueError() def __iadd__(self, other): return self + other def __add__(self, other): if other == 0: return self if not isinstance(self, type(other)) or self.fields != other.fields: raise ValueError("Tables have incompatible fields") else: table = Table(fields=self.fields) table._rows = self._rows + other._rows return table def order_by(self, key): # TODO: implement locale # TODO: implement for more than one key reverse = False if key.startswith("-"): key = key[1:] reverse = True field_names = self.field_names if key not in field_names: raise ValueError('Field "{}" does not exist'.format(key)) key_index = field_names.index(key) self._rows.sort(key=itemgetter(key_index), reverse=reverse) class FlexibleTable(Table): def __init__(self, fields=None, meta=None): if fields is None: fields = {} super(FlexibleTable, self).__init__(fields, meta) def __getitem__(self, key): if isinstance(key, int): return self.Row(**self._rows[key]) elif isinstance(key, slice): return [self.Row(**row) for row in self._rows[key]] else: raise ValueError("Unsupported key type: {}".format(type(key).__name__)) def _add_field(self, field_name, field_type): self.fields[field_name] = field_type self.Row = namedtuple("Row", self.field_names) def _make_row(self, row): from rows import fields for field_name in row.keys(): if field_name not in self.field_names: self._add_field(field_name, fields.identify_type(row[field_name])) return { field_name: field_type.deserialize(row.get(field_name, None)) for field_name, field_type in self.fields.items() } def insert(self, index, row): self._rows.insert(index, self._make_row(row)) def __setitem__(self, key, value): self._rows[key] = self._make_row(value) def append(self, row): """Add a row to the table. Should be a dict""" self._rows.append(self._make_row(row))
turicas/rows
rows/table.py
table.py
py
9,338
python
en
code
851
github-code
36
[ { "api_name": "six.PY2", "line_number": 10, "usage_type": "attribute" }, { "api_name": "six.PY3", "line_number": 12, "usage_type": "attribute" }, { "api_name": "collections.abc.MutableSequence", "line_number": 16, "usage_type": "name" }, { "api_name": "collections...
14719000244
from multiprocessing.sharedctypes import Value from xmlrpc.client import Boolean from source.dataloaders.data_loaders_factory import DataLoaderFactory import torch import torchaudio import os import numpy as np import csv from source.dataloaders.project_2_dataset import Project_2_Dataset from source.utils.config_manager import ConfigManager UNKNOWN_DIRS = ["bed", "bird", "cat", "dog", "eight", "five", "four", "happy", "house", "marvin", "nine", "one", "seven", "sheila", "six", "three", "tree", "two", "wow", "zero"] class OneVsAllDataLoadersFactory(DataLoaderFactory): def __init__(self, dataset_path, transform_train: torch.nn.Sequential = None, transform_test: torch.nn.Sequential = None, one='silence', from_file_path=None, labels=None, no_workers=4, no_workers_eden=16): super().__init__(dataset_path) self.train_transformer = transform_train self.test_transfomer = transform_test self.one = one self.from_file_path = from_file_path self.labels = labels if one == 'silence': self.with_silence = 'extra' self.labels = {'silence' : 0, 'silence_extra': 0, 'unknown': 1 } elif one == 'unknown': self.with_silence = False self.labels = {'unknown': 0, 'yes': 1, 'no': 1, 'up': 1, 'down': 1, 'left': 1, 'right': 1, 'on': 1, 'off': 1, 'stop': 1, 'go': 1, 'silence': 1, 'silence_extra': 1} else: print("one should be one of ['silence', 'unknown']") raise ValueError() if ConfigManager.is_eden(): self.no_workers = no_workers_eden else: self.no_workers = no_workers def __str__(self): return f'Silence vs. speech: Train_transformer:{self.train_transformer.__str__()}; Silence vs. speech: Test_transformer:{self.test_transfomer.__str__()}'.format(self=self) def get_train_loader(self, batch_size: int): self.__load_train_data( self.dataset_path, self.train_transformer) sampler = self.__get_sampler_to_balance_classes(self.train_ds._walker) return torch.utils.data.DataLoader(self.train_ds, batch_size, shuffle=False, drop_last=True, sampler = sampler, num_workers=self.no_workers) def get_train_valid_loader(self, batch_size: int): raise NotImplemented() def get_valid_loader(self, batch_size: int): self.__load_valid_data( self.dataset_path, self.test_transfomer) return torch.utils.data.DataLoader(self.valid_ds, batch_size, shuffle=False, drop_last=True, num_workers=self.no_workers) def get_test_loader(self, batch_size: int): self.__load_test_data( self.dataset_path, self.test_transfomer) return torch.utils.data.DataLoader(self.test_ds, batch_size, shuffle=False, drop_last=False, num_workers=self.no_workers) def __load_train_data(self, data_dir: str, transform_train: torch.nn.Sequential): self.train_ds = Project_2_Dataset( with_silence=self.with_silence, with_unknown=True, root=data_dir, subset='training', transform=transform_train, labels=self.labels) def __load_valid_data(self, data_dir: str, transform_valid: torch.nn.Sequential): self.valid_ds = Project_2_Dataset( with_silence=self.with_silence, with_unknown=True, root=data_dir, subset='validation', transform=transform_valid, labels=self.labels) def __load_test_data(self, data_dir: str, transform_test: torch.nn.Sequential): self.test_ds = Project_2_Dataset( True, True, data_dir, 'testing', transform=transform_test, from_file_path=self.from_file_path) def __get_sampler_to_balance_classes(self, samples_filenames): if self.one == 'silence': zeros_for_one_class = [0 if 'silence' in x else 1 for x in samples_filenames] else: zeros_for_one_class = [0 if any(unknown in x for unknown in UNKNOWN_DIRS) else 1 for x in samples_filenames] samples_count = len(samples_filenames) rest_count = np.count_nonzero(zeros_for_one_class) one_class_count = samples_count - rest_count class_sample_count = [one_class_count, rest_count] weights = 1 / torch.Tensor(class_sample_count) weights = weights.double() sample_weights = weights[zeros_for_one_class] sampler = torch.utils.data.sampler.WeightedRandomSampler(sample_weights, len(sample_weights)) return sampler
Shaveek23/cifar10-computer_vision
source/dataloaders/onevsall_dataloadersfactory.py
onevsall_dataloadersfactory.py
py
4,491
python
en
code
0
github-code
36
[ { "api_name": "source.dataloaders.data_loaders_factory.DataLoaderFactory", "line_number": 15, "usage_type": "name" }, { "api_name": "torch.nn", "line_number": 17, "usage_type": "attribute" }, { "api_name": "source.utils.config_manager.ConfigManager.is_eden", "line_number": 38...
24997436439
"""empty message Revision ID: 60ec815b1cea Revises: e20eb33302a2 Create Date: 2023-01-28 01:32:26.058698 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '60ec815b1cea' down_revision = 'e20eb33302a2' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### with op.batch_alter_table('user', schema=None) as batch_op: batch_op.alter_column('id', existing_type=sa.INTEGER(), server_default=None, existing_nullable=False, autoincrement=True) batch_op.alter_column('created_on', existing_type=sa.DATE(), nullable=True) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### with op.batch_alter_table('user', schema=None) as batch_op: batch_op.alter_column('created_on', existing_type=sa.DATE(), nullable=False) batch_op.alter_column('id', existing_type=sa.INTEGER(), server_default=sa.Identity(always=True, start=1, increment=1, minvalue=1, maxvalue=2147483647, cycle=False, cache=1), existing_nullable=False, autoincrement=True) # ### end Alembic commands ###
gaelzarco/aihub
flask/migrations/versions/60ec815b1cea_.py
60ec815b1cea_.py
py
1,371
python
en
code
1
github-code
36
[ { "api_name": "alembic.op.batch_alter_table", "line_number": 21, "usage_type": "call" }, { "api_name": "alembic.op", "line_number": 21, "usage_type": "name" }, { "api_name": "sqlalchemy.INTEGER", "line_number": 23, "usage_type": "call" }, { "api_name": "sqlalchemy...
30490693575
# encoding: utf-8 from paddlelite.lite import * import cv2 as cv import numpy as np from matplotlib import pyplot as plt from time import time from PIL import Image from PIL import ImageFont from PIL import ImageDraw from PIL import ImageEnhance class PPYOLO_Detector(object): def __init__(self, nb_path=None, # nb路径 label_list=None, # 类别list input_size=[320, 320], # 输入图像大小 img_means=[0., 0., 0.], # 图片归一化均值 img_stds=[0., 0., 0.], # 图片归一化方差 threshold=0.1, # 预测阈值 num_thread=1, # ARM CPU工作线程数 ): # 验证必要的参数格式 assert nb_path is not None, \ "Please make sure the model_nb_path has inputed!(now, nb_path is None.)" assert len(input_size) == 2, \ "Please make sure the input_shape length is 2, but now its length is {0}".format(len(input_size)) assert len(img_means) == 3, \ "Please make sure the image_means shape is [3], but now get image_means' shape is [{0}]".format( len(img_means)) assert len(img_stds) == 3, \ "Please make sure the image_stds shape is [3], but now get image_stds' shape is [{0}]".format(len(img_stds)) assert len([i for i in img_stds if i <= 0]) < 1, \ "Please make sure the image_stds data is more than 0., but now get image_stds' data exists less than or equal 0." assert threshold > 0. and threshold < 1., \ "Please make sure the threshold value > 0. and < 1., but now get its value is {0}".format(threshold) assert num_thread > 0 and num_thread <= 4, \ "Please make sure the num_thread value > 1 and <= 4., but now get its value is {0}".format(num_thread) # 模型nb文件路径 self.model_path = nb_path # ARM CPU工作线程数 self.num_thread = num_thread # 预测显示阈值 self.threshold = threshold # 预测输入图像大小 self.input_size = input_size # 图片归一化参数 # 均值 self.img_means = img_means # 方差 self.img_stds = img_stds # 预测类别list self.label_list = label_list # 预测类别数 self.num_class = len(label_list) if (label_list is not None) and isinstance(label_list, list) else 1 # 类别框颜色map self.box_color_map = self.random_colormap() # 记录模型加载参数的开始时间 self.prepare_time = self.runtime() # 配置预测 self.config = MobileConfig() # 设置模型路径 self.config.set_model_from_file(nb_path) # 设置线程数 self.config.set_threads(num_thread) # 构建预测器 self.predictor = create_paddle_predictor(self.config) # 模型加载参数的总时间花销 self.prepare_time = self.runtime() - self.prepare_time print("The Prepare Model Has Cost: {0:.4f} s".format(self.prepare_time)) def get_input_img(self, input_img): '''输入预测图片 input_img: 图片路径或者np.ndarray图像数据 - [h, w, c] ''' assert isinstance(input_img, str) or isinstance(input_img, np.ndarray), \ "Please enter input is Image Path or numpy.ndarray, but get ({0}) ".format(input_img) # 装载图像到预测器上的开始时间 self.load_img_time = self.runtime() if isinstance(input_img, str): # 读取图片路径下的图像数据 self.input_img = Image.open(input_img) elif isinstance(input_img, np.ndarray): # 读取ndarray数据下的图像数据 self.input_img = Image.fromarray(input_img) # 获取图片原始高宽 : h,w self.input_shape = np.asarray(self.input_img).shape[:-1] # 重置图片大小为指定的输入大小 input_data = self.input_img.resize(self.input_size, Image.BILINEAR) # 转制图像shape为预测指定shape input_data = np.array(input_data).transpose(2, 0, 1).reshape([1, 3] + self.input_size).astype('float32') # 将图像数据进行归一化 input_data = self.normlize(input_data) self.scale_factor = [1., 1.] # [1., 1.] # 配置输入tensor # 输入[[shape, shape]]的图片大小 self.input_tensor0 = self.predictor.get_input(0) self.input_tensor0.from_numpy(np.asarray([self.input_size], dtype=np.int32)) # 输入[1, 3, shape, shape]的归一化后的图片数据 self.input_tensor1 = self.predictor.get_input(1) self.input_tensor1.from_numpy(input_data) # 输入模型处理图像大小与实际图像大小的比例 self.input_tensor2 = self.predictor.get_input(2) self.input_tensor2.from_numpy(np.asarray(self.scale_factor, dtype=np.int32)) # 装载图像到预测器上的总时间花销 self.load_img_time = self.runtime() - self.load_img_time # print("The Load Image Has Cost: {0:.4f} s".format(self.load_img_time)) def get_output_img(self): '''获取输出标注图片 num_bbox: 最大标注个数 ''' # 预测器开始预测的时间 self.predict_time = self.runtime() # 根据get_input_img的图像进行预测 self.predictor.run() # 获取输出预测bbox结果 self.output_tensor = self.predictor.get_output(0) # 转化为numpy格式 output_bboxes = self.output_tensor.numpy() # 根据阈值进行筛选,大于等于阈值的保留 output_bboxes = output_bboxes[output_bboxes[:, 1] >= self.threshold] # 根据预测结果进行框绘制,返回绘制完成的图片 # self.output_img = self.load_bbox(output_bboxes, num_bbox) # 预测器预测的总时间花销 self.predict_time = self.runtime() - self.predict_time print("The Predict Image Has Cost: {0:.4f} s".format(self.predict_time)) # return self.output_img return output_bboxes def normlize(self, input_img): '''数据归一化 input_img: 图像数据--numpy.ndarray ''' # 对RGB通道进行均值-方差的归一化 input_img[0, 0] = (input_img[0, 0] / 255. - self.img_means[0]) / self.img_stds[0] input_img[0, 1] = (input_img[0, 1] / 255. - self.img_means[1]) / self.img_stds[1] input_img[0, 2] = (input_img[0, 2] / 255. - self.img_means[2]) / self.img_stds[2] return input_img def load_bbox(self, input_bboxs, num_bbox): '''根据预测框在原始图片上绘制框体,并标注 input_bboxs: 预测框 num_bbox: 允许的标注个数 ''' # 创建间绘图参数:[cls_id, score, x1, y1, x2, y2] self.draw_bboxs = [0] * 6 # 绘图器 -- 根据get_input_img的输入图像 draw = ImageDraw.Draw(self.input_img) # 根据最大标注个数进行实际标注个数的确定 # input_bboxs.shape[0]: 表示预测到的有效框个数 if len(input_bboxs) != 0: # 存在有效框时 num_bbox = input_bboxs.shape[0] if num_bbox > input_bboxs.shape[0] else num_bbox else: num_bbox = 0 # 没有有效框,直接不标注 # 遍历框体,并进行标注 for i in range(num_bbox): # 类别信息 self.draw_bboxs[0] = input_bboxs[i][0] # 类别得分 self.draw_bboxs[1] = input_bboxs[i][1] print(self.label_list[int(self.draw_bboxs[0])], '- score{', self.draw_bboxs[1], "} : ", input_bboxs[i][2], input_bboxs[i][3], input_bboxs[i][4], input_bboxs[i][5]) # 框体左上角坐标 # max(min(input_bboxs[i][2] / self.input_size[0], 1.), 0.):保证当前预测坐标始终在图像内(比例,0.-1.) # max(min(input_bboxs[i][2] / self.input_size[0], 1.), 0.) * self.input_shape[1]: 直接预测得到的坐标 # min(max(min(input_bboxs[i][2] / self.input_size[0], 1.), 0.) * self.input_shape[1], self.input_shape[1]):保证坐标在图像内(h, w) self.draw_bboxs[2] = min(max(min(input_bboxs[i][2] / self.input_size[0], 1.), 0.) * self.input_shape[1], self.input_shape[1]) self.draw_bboxs[3] = min(max(min(input_bboxs[i][3] / self.input_size[1], 1.), 0.) * self.input_shape[0], self.input_shape[0]) # 框体右下角坐标 self.draw_bboxs[4] = min(max(min(input_bboxs[i][4] / self.input_size[0], 1.), 0.) * self.input_shape[1], self.input_shape[1]) self.draw_bboxs[5] = min(max(min(input_bboxs[i][5] / self.input_size[1], 1.), 0.) * self.input_shape[0], self.input_shape[0]) # print(self.draw_bboxs[2], self.draw_bboxs[3], self.draw_bboxs[4], self.draw_bboxs[5]) # 绘制框体 # self.box_color_map[int(self.draw_bboxs[i][0])]: 对应类别的框颜色 draw.rectangle(((self.draw_bboxs[2], self.draw_bboxs[3]), (self.draw_bboxs[4], self.draw_bboxs[5])), outline=tuple(self.box_color_map[int(self.draw_bboxs[0])]), width=2) # 框体位置写上类别和得分信息 draw.text((self.draw_bboxs[2], self.draw_bboxs[3] + 1), "{0}:{1:.4f}".format(self.label_list[int(self.draw_bboxs[0])], self.draw_bboxs[1]), tuple(self.box_color_map[int(self.draw_bboxs[0])])) # 返回标注好的图像数据 return np.asarray(self.input_img) def random_colormap(self): '''获取与类别数量等量的color_map ''' np.random.seed(2021) color_map = [[np.random.randint(20, 255), np.random.randint(64, 200), np.random.randint(128, 255)] for i in range(self.num_class)] return color_map def runtime(self): '''返回当前计时 ''' return time()
Feng1909/PPYOLO-Tiny
Tiny.py
Tiny.py
py
10,384
python
en
code
2
github-code
36
[ { "api_name": "numpy.ndarray", "line_number": 84, "usage_type": "attribute" }, { "api_name": "PIL.Image.open", "line_number": 92, "usage_type": "call" }, { "api_name": "PIL.Image", "line_number": 92, "usage_type": "name" }, { "api_name": "numpy.ndarray", "line...
31641438007
import requests from bs4 import BeautifulSoup import category site_url = 'https://books.toscrape.com/index.html' # global var def save_all_categories(site_url): """ Save all data of the books of the entire category (it handles pagination) and for each site's category """ global links # reutilisation apres boucle url = site_url # preserve global var response = requests.get(url) # 200 si ok print(response) # afficher code retour if response.ok: # si justement ok soup = BeautifulSoup(response.text, features='html.parser') # format txt, delete warnings for x in soup.find_all('ul', {'class': 'nav nav-list'}): # unique classe 'nav nav-list' mais find_all iteration links = x.find('ul').find_all('a') # autre ul, lister tous les lien des iterations for n in range(len(links)): # parcourir toute la liste de liens récupérés link = links[n]['href'].replace('catalogue', 'http://books.toscrape.com/catalogue') # affecter dans variable category.save_one_category(link) # même variable pour appeler fonction save_all_categories(site_url) if __name__ == "__main__": book_data = get_book_data(EXAMPLE_URL) save_book_csv(book_data) save_one_category(index_url) save_all_categories(site_url) save_image_file(url_image)
o0nekov0o/OpenClassrooms_P2
main.py
main.py
py
1,351
python
en
code
1
github-code
36
[ { "api_name": "requests.get", "line_number": 16, "usage_type": "call" }, { "api_name": "bs4.BeautifulSoup", "line_number": 19, "usage_type": "call" }, { "api_name": "category.save_one_category", "line_number": 24, "usage_type": "call" } ]
70295411304
import torch.utils.data from torch.utils.data import DataLoader from torchvision import datasets import torchvision.transforms as T def load_cifar10(): train_data = datasets.CIFAR10( root='../data', train=True, download=True, transform=T.Compose([ T.ToTensor(), T.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)), T.Resize(size=(128, 128), antialias=True) ]), target_transform=None ) splits = torch.utils.data.random_split(train_data, [40000, 10000]) train_data = splits[0] val_data = splits[1] test_data = datasets.CIFAR10( root='../data', train=False, download=True, transform=T.Compose([ T.ToTensor(), T.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)), T.Resize(size=(128, 128), antialias=True) ]), ) return train_data, val_data, test_data def create_dataloaders(train_data, val_data, test_data, batch_size): train_dataloader = DataLoader(train_data, batch_size=batch_size, shuffle=True) val_dataloader = DataLoader(val_data, batch_size=batch_size, shuffle=True) test_dataloader = DataLoader(test_data, batch_size=batch_size, shuffle=False) return train_dataloader, val_dataloader, test_dataloader
simogiovannini/DLA-lab1
utils/data_loader.py
data_loader.py
py
1,311
python
en
code
0
github-code
36
[ { "api_name": "torchvision.datasets.CIFAR10", "line_number": 8, "usage_type": "call" }, { "api_name": "torchvision.datasets", "line_number": 8, "usage_type": "name" }, { "api_name": "torchvision.transforms.Compose", "line_number": 12, "usage_type": "call" }, { "ap...
20456498612
import discum import json import os.path import random import time from rich import print def load_from_data_else_ask(field, message): global data if data is not None and field in data.keys(): return data[field] return input(message) data = None if os.path.exists("data.json"): data = json.loads(open("data.json").read()) if data is not None and "token" in data.keys(): token = data["token"] else: token = input('ur token: ') bot = discum.Client(token=token, log=False) memberz = [] guildz = load_from_data_else_ask("guildid", "Please input guild ID: ") if data is not None and "channelids" in data.keys(): channelz = data["channelids"] else: channelz = [load_from_data_else_ask("channelid", "Please input a channel ID in that guild: ")] if data is not None and "messages" in data.keys(): messagz = data["messages"] else: messagz = [load_from_data_else_ask("message", "Please input your message: ")] timez = load_from_data_else_ask("time", "How long between DMs: ") if data is not None and "ignoreRoles" in data.keys(): ignores = data["ignoreRoles"] else: ignores = [] @bot.gateway.command def memberTest(resp): if resp.event.ready_supplemental: for channel in channelz: bot.gateway.fetchMembers(guildz, channel) if bot.gateway.finishedMemberFetching(guildz): bot.gateway.removeCommand(memberTest) bot.gateway.close() bot.gateway.run() badMemberz = set() print("Getting members not to message") for role in ignores: for mem in bot.getRoleMemberIDs(guildz, role).json(): badMemberz.add(mem) print(badMemberz) print("Starting add members.") for memberID in bot.gateway.session.guild(guildz).members: if memberID in badMemberz: continue memberz.append(memberID) print("Starting to DM.") for x in memberz: try: rand = random.randint(0, 20) if rand == 20: print(f'Sleeping for 45 seconds to prevent rate-limiting.') time.sleep(45) print(f'Done sleeping!') print(f"Preparing to DM {x}.") time.sleep(int(timez)) newDM = bot.createDM([f"{x}"]).json()["id"] bot.sendMessage(newDM, f"{random.choice(messagz)} DM bot by https://github.com/Apophis52/Python-Mass-DM-Selfbot/") print(f'DMed {x}.') except Exception as E: print(E) print(f'Couldn\'t DM {x}.')
Apophis52/Python-Mass-DM-Selfbot
index.py
index.py
py
2,499
python
en
code
21
github-code
36
[ { "api_name": "os.path.path.exists", "line_number": 17, "usage_type": "call" }, { "api_name": "os.path.path", "line_number": 17, "usage_type": "attribute" }, { "api_name": "os.path", "line_number": 17, "usage_type": "name" }, { "api_name": "json.loads", "line_...
34338203362
from p111 import Solution from common.tree import buildTreeFromList test_cases = [ ([3,9,20,None,None,15,7], 2), ([2,None,3,None,4,None,5,None,6], 5), ([], 0), ] def test_minDepth(): s = Solution() for case in test_cases: assert s.minDepth(buildTreeFromList(case[0])) == case[1], case
0x0400/LeetCode
p111_test.py
p111_test.py
py
315
python
en
code
0
github-code
36
[ { "api_name": "p111.Solution", "line_number": 11, "usage_type": "call" }, { "api_name": "common.tree.buildTreeFromList", "line_number": 13, "usage_type": "call" } ]
75310096425
import random import re import socket import uuid from scapy.all import IP, TCP, wrpcap, Raw, Ether from sys import version_info if version_info.major == 2: from BaseHTTPServer import BaseHTTPRequestHandler from StringIO import StringIO else: from http.server import BaseHTTPRequestHandler from io import StringIO class HTTPRequest(BaseHTTPRequestHandler): def __init__(self, request_text): self.rfile = StringIO(request_text) self.raw_requestline = self.rfile.readline() self.error_code = self.error_message = None self.parse_request() def send_error(self, code, message): self.error_code = code self.error_message = message DOMAIN_REGEX = re.compile( r"^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([a-zA-Z0-9\-]+\.[a-zA-Z]{2,})(?:[\/\w\.-]*)*\/?$" ) def get_ip(): """get local ip""" ssc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # doesn't even have to be reachable ssc.connect(("10.255.255.255", 1)) local_ip = ssc.getsockname()[0] except: local_ip = "127.0.0.1" finally: ssc.close() return local_ip def gen_pkt( dst, dst_port, random_port=43454, http_request_text="", http_response_text="", src_mac="18:26:3a:30:3c:e8", dst_mac="02:42:AC:11:00:03", ): """gen pcap packet""" http_request_bytes = bytes(http_request_text) if not http_request_bytes.endswith("\n"): http_request_bytes = http_request_bytes + b"\n" http_response_bytes = bytes(http_response_text) if not http_response_bytes.endswith("\n"): http_response_bytes = http_response_bytes + b"\n" http_request = (Ether(src=src_mac, dst=dst_mac) / IP(dst=dst) / TCP( dport=dst_port, sport=random_port, flags="A", ) / Raw(http_request_bytes)) # http_request.show() (http_response, ) = (Ether(dst=src_mac, src=dst_mac) / IP( src=dst, dst=get_ip(), ) / TCP( dport=random_port, sport=dst_port, seq=http_request[TCP].ack, ack=http_request[TCP].seq + len(http_request[Raw]), flags="PA", ) / Raw(http_response_bytes)) # http_response.show() return http_request, http_response def get_mac_address(): """get interface mac address""" mac_address = uuid.getnode() return ":".join([ "{:02x}".format((mac_address >> ele) & 0xFF) for ele in range(0, 8 * 6, 8) ][::-1]) def get_host_and_port(request=""): """get host and port""" host = "" port = 80 req = HTTPRequest(request) host_str = req.headers.get("host", "") if ":" in host_str: tmp = host_str.replace("http://", "").replace("https://","").split(":") if len(tmp) >= 2: host = tmp[0] port = int(tmp[1]) else: host = host_str if re.search(DOMAIN_REGEX, host): host = get_ip() return host, port def gen_all_packet(multi_http_packet): """gen all http text to http packet""" result = [] for req, resp in multi_http_packet: host, port = get_host_and_port(req) http_pkt = gen_pkt( host, port, random.randint(23456, 65500), req, resp, src_mac=get_mac_address(), ) result.append(http_pkt) return result def test_from_files(): """test http request and response from file""" with open("http-req.txt", "r") as f: http_request_text = f.read() # Read the HTTP response from a file with open("http-resp.txt", "r") as f: http_response_text = f.read() pkts = gen_all_packet([(http_request_text, http_response_text)]) # Write the request and response packets to a PCAP file wrpcap( "http.pcap", pkts, )
b40yd/security
http_text_to_pcap.py
http_text_to_pcap.py
py
3,848
python
en
code
96
github-code
36
[ { "api_name": "sys.version_info.major", "line_number": 10, "usage_type": "attribute" }, { "api_name": "sys.version_info", "line_number": 10, "usage_type": "name" }, { "api_name": "http.server.BaseHTTPRequestHandler", "line_number": 18, "usage_type": "name" }, { "a...
12567632552
import torch from torch.utils.data import DataLoader from torchvision import transforms, datasets from torch import nn, optim from ae import AE import visdom from vae import VAE from torchvision import models def main(): vis = visdom.Visdom() tf = transforms.Compose([ transforms.ToTensor(), # 转换成tensor 格式,并且压缩到[0 ,1] ]) # 构建训练集 测试集 mnist_train = datasets.MNIST('mnist', train=True, transform=tf, download=True) mnist_train = DataLoader(mnist_train, batch_size=32, shuffle=True) mnist_test = datasets.MNIST('mnist', train=False, transform=tf, download=True) mnist_test = DataLoader(mnist_test, batch_size=32, shuffle=True) x, _ = next(iter(mnist_train)) print("x:", x.shape) # ************************** train ************************** device = torch.device('cuda:0') model_vae = VAE().to(device) criteon = nn.MSELoss().to(device) optimizer = optim.Adam(model_vae.parameters(), lr=1e-3) print(model_vae) loss = None kld=None for epoch in range(20 ): for idx, (x, _) in enumerate(mnist_train): x = x.to(device) x_hat,kld = model_vae(x) # print(x.shape , x_hat.shape) loss = criteon(x, x_hat)+1.0*kld optimizer.zero_grad() loss.backward() optimizer.step() print('epoch {} loss: {} include kld loss: {}'.format(epoch, loss.item(),kld.item())) if epoch % 1 == 0: # 每1次epoch做一次可视化 vis.line([loss.item()], [epoch], win='train loss', update='append', opts=dict( title='train loss', xlabel='epoch', ylabel='loss' )) #******************** test ************************ x,_=next(iter(mnist_test)) x=x.to(device) with torch.no_grad(): x_hat,_ = model_vae(x) # x : [32,1,28,28] 32 张图片 vis.images(x,nrow=8,win='x source',opts=dict( title = 'x source' )) vis.images(x_hat,win='x hat',nrow=8,opts=dict(title = 'x hat')) if __name__ == '__main__': main()
wy171205/DeepLearning
AutoEncoder/main.py
main.py
py
2,114
python
en
code
0
github-code
36
[ { "api_name": "visdom.Visdom", "line_number": 12, "usage_type": "call" }, { "api_name": "torchvision.transforms.Compose", "line_number": 14, "usage_type": "call" }, { "api_name": "torchvision.transforms", "line_number": 14, "usage_type": "name" }, { "api_name": "t...
30981112855
#!/usr/bin/python # <bitbar.title>Stock Ticker</bitbar.title> # <bitbar.version>1.0</bitbar.version> # <bitbar.author>Robert Kanter</bitbar.author> # <bitbar.author.github>rkanter</bitbar.author.github> # <bitbar.desc>Provides a rotating stock ticker in your menu bar, with color and percentage changes</bitbar.desc> # <bitbar.dependencies>python</bitbar.dependencies> # <bitbar.image>https://i.imgur.com/Nf4jiRd.png</bitbar.image> # <bitbar.abouturl>https://github.com/rkanter</bitbar.abouturl> import urllib2 import json #----------------------------------------------------------------------------- # IMPORTANT: You will need an API Token. Follow these steps # 1. Create a free account at https://iexcloud.io/cloud-login#/register/ # 2. Select the free "START" tier # 3. Verify your email address # 4. Click "API Tokens" in the left menu # 5. Enter the "Publishable" Token in the quotes below (it should start with "pk_") api_token = "" # Enter your stock symbols here in the format: ["symbol1", "symbol2", ...] stock_symbols = ["MSFT", "AAPL", "AMZN"] #----------------------------------------------------------------------------- response = urllib2.urlopen("https://cloud.iexapis.com/stable/stock/market/batch?symbols=" + ','.join(stock_symbols) + "&types=quote&filter=symbol,latestPrice,change,changePercent&displayPercent=true&token=" + api_token) json_data = json.loads(response.read()) for stock_symbol in stock_symbols: stock_quote = json_data[stock_symbol]["quote"] price_current = stock_quote["latestPrice"] price_changed = stock_quote["change"] price_percent_changed = stock_quote["changePercent"] if price_changed is not None: color = "red" if float(price_changed) < 0 else "green" print("{} {:.2f} {:.2f} ({:.2f}%) | color={}".format(stock_symbol, price_current, price_changed, price_percent_changed, color)) else: color = "black" print("{} {:.2f} | color={}".format(stock_symbol, price_current, color))
damncabbage/dotfiles
macOS/BitBar/Plugins/Finance/stock-ticker.30s.py
stock-ticker.30s.py
py
1,981
python
en
code
3
github-code
36
[ { "api_name": "urllib2.urlopen", "line_number": 26, "usage_type": "call" }, { "api_name": "json.loads", "line_number": 27, "usage_type": "call" } ]
16155659298
import json import logging import os import re from pathlib import Path from cdi_forms.forms import BackgroundForm, BackpageBackgroundForm from cdi_forms.models import BackgroundInfo, Instrument_Forms, Zipcode from django.conf import settings from django.http import Http404 from django.utils import translation from researcher_UI.models import administration_data, Instrument from researcher_UI.models import Administration logger = logging.getLogger("debug") PROJECT_ROOT = str( Path(os.path.dirname(__file__)).parent.absolute() ) # Declare root folder for project and files. Varies between Mac and Linux installations. # This function is not written properly... def language_map(language): with translation.override("en"): available_langs = dict(settings.LANGUAGES) trimmed_lang = re.sub(r"(\s+)?\([^)]*\)", "", language).strip() lang_code = None for code, language in available_langs.items(): if language == trimmed_lang: lang_code = code assert lang_code, ( "'%s' not available in language mapping function (language_map, cdi_forms/views.py)" % trimmed_lang ) return lang_code def has_backpage(filename): back_page = 0 if os.path.isfile(filename): pages = json.load(open(filename, encoding="utf-8")) for page in pages: if page["page"] == "back": back_page = 1 return back_page # Map name of instrument model to its string title def model_map(name): assert Instrument.objects.filter(name=name).exists(), ( "%s is not registered as a valid instrument" % name ) instrument_obj = Instrument.objects.get(name=name) cdi_items = Instrument_Forms.objects.filter(instrument=instrument_obj).order_by( "item_order" ) assert cdi_items.count() > 0, ( "Could not find any CDI items registered with this instrument: %s" % name ) return cdi_items # Prepare items with prefilled reponses for later rendering. Dependent on cdi_items def prefilled_cdi_data(administration_instance): prefilled_data_list = administration_data.objects.filter( administration=administration_instance ).values( "item_ID", "value" ) # Grab a list of prefilled responses instrument_name = ( administration_instance.study.instrument.name ) # Grab instrument name instrument_model = model_map( instrument_name ) # Grab appropriate model given the instrument name associated with test if ( not prefilled_data_list and administration_instance.repeat_num > 1 and administration_instance.study.prefilled_data >= 2 ): word_items = instrument_model.filter(item_type="word").values_list( "itemID", flat=True ) old_admins = Administration.objects.filter( study=administration_instance.study, subject_id=administration_instance.subject_id, completed=True, ) if old_admins: old_admin = old_admins.latest("last_modified") old_admin_data = administration_data.objects.filter( administration=old_admin, item_ID__in=word_items ).values("item_ID", "value") new_data_objs = [] for admin_data_obj in old_admin_data: new_data_objs.append( administration_data( administration=administration_instance, item_ID=admin_data_obj["item_ID"], value=admin_data_obj["value"], ) ) administration_data.objects.bulk_create(new_data_objs) prefilled_data_list = administration_data.objects.filter( administration=administration_instance ).values("item_ID", "value") prefilled_data = { x["item_ID"]: x["value"] for x in prefilled_data_list } # Store prefilled data in a dictionary with item_ID as the key and response as the value. with open( PROJECT_ROOT + "/form_data/" + instrument_name + "_meta.json", "r", encoding="utf-8", ) as content_file: # Open associated json file with section ordering and nesting # Read json file and store additional variables regarding the instrument, study, and the administration data = json.loads(content_file.read()) data["object"] = administration_instance data["title"] = administration_instance.study.instrument.verbose_name instrument_name = data[ "instrument_name" ] = administration_instance.study.instrument.name data["completed"] = administration_instance.completed data["due_date"] = administration_instance.due_date.strftime( "%b %d, %Y, %I:%M %p" ) data["page_number"] = administration_instance.page_number data["hash_id"] = administration_instance.url_hash data["study_waiver"] = administration_instance.study.waiver data["confirm_completion"] = administration_instance.study.confirm_completion try: data["back_page"] = has_backpage( PROJECT_ROOT + administration_instance.study.demographic.path ) except: data["back_page"] = 0 raw_objects = [] field_values = [ "itemID", "item", "item_type", "category", "definition", "choices__choice_set", ] field_values += [ "choices__choice_set_" + settings.LANGUAGE_DICT[administration_instance.study.instrument.language] ] # As some items are nested on different levels, carefully parse and store items for rendering. for part in data["parts"]: for item_type in part["types"]: if "sections" in item_type: for section in item_type["sections"]: group_objects = instrument_model.filter( category__exact=section["id"] ).values(*field_values) if "type" not in section: section["type"] = item_type["type"] x = cdi_items( group_objects, section["type"], prefilled_data, item_type["id"], ) section["objects"] = x if administration_instance.study.show_feedback: raw_objects.extend(x) if any(["*" in x["definition"] for x in section["objects"]]): section["starred"] = "*Or the word used in your family" else: group_objects = instrument_model.filter( item_type__exact=item_type["id"] ).values(*field_values) x = cdi_items( group_objects, item_type["type"], prefilled_data, item_type["id"], ) item_type["objects"] = x if administration_instance.study.show_feedback: raw_objects.extend(x) # print (raw_objects) data["cdi_items"] = json.dumps(raw_objects) # , cls=DjangoJSONEncoder) # If age is stored in database, add it to dictionary try: age = BackgroundInfo.objects.values_list("age", flat=True).get( administration=administration_instance ) except: age = "" data["age"] = age return data # Stitch section nesting in cdi_forms/form_data/*.json and instrument models together and prepare for CDI form rendering def cdi_items(object_group, item_type, prefilled_data, item_id): for obj in object_group: if "textbox" in obj["item"]: obj["text"] = obj["definition"] if obj["itemID"] in prefilled_data: obj["prefilled_value"] = prefilled_data[obj["itemID"]] elif item_type == "checkbox": obj["prefilled_value"] = obj["itemID"] in prefilled_data # print ( obj['itemID'] ) obj["definition"] = ( obj["definition"][0] + obj["definition"][1:] if obj["definition"][0].isalpha() else obj["definition"][0] + obj["definition"][1] + obj["definition"][2:] ) obj["choices"] = obj["choices__choice_set"] elif item_type in ["radiobutton", "modified_checkbox"]: raw_split_choices = [ i.strip() for i in obj["choices__choice_set"].split(";") ] # split_choices_translated = map(str.strip, [value for key, value in obj.items() if 'choice_set_' in key][0].split(';')) split_choices_translated = [ value for key, value in obj.items() if "choice_set_" in key ][0].split(";") prefilled_values = [ False if obj["itemID"] not in prefilled_data else x == prefilled_data[obj["itemID"]] for x in raw_split_choices ] obj["text"] = ( obj["definition"][0] + obj["definition"][1:] if obj["definition"][0].isalpha() else obj["definition"][0] + obj["definition"][1] + obj["definition"][2:] ) if ( obj["definition"] is not None and obj["definition"].find("\\") >= 0 and item_id in ["complexity", "pronoun_usage"] ): instruction = re.search("<b>(.+?)</b>", obj["definition"]) if instruction: obj_choices = obj["definition"].split( instruction.group(1) + "</b><br />" )[1] else: obj_choices = obj["definition"] # split_definition = map(str.strip, obj_choices.split('\\')) split_definition = obj_choices.split("\\") obj["choices"] = list( zip(split_definition, raw_split_choices, prefilled_values) ) else: obj["choices"] = list( zip(split_choices_translated, raw_split_choices, prefilled_values) ) if obj["definition"] is not None: obj["text"] = ( obj["definition"][0] + obj["definition"][1:] if obj["definition"][0].isalpha() else obj["definition"][0] + obj["definition"][1] + obj["definition"][2:] ) elif item_type == "textbox": if obj["itemID"] in prefilled_data: obj["prefilled_value"] = prefilled_data[obj["itemID"]] return object_group def safe_harbor_zip_code(obj): zip_prefix = "" raw_zip = obj.zip_code if raw_zip and raw_zip != "None": zip_prefix = raw_zip[:3] if Zipcode.objects.filter(zip_prefix=zip_prefix).exists(): zip_prefix = Zipcode.objects.filter(zip_prefix=zip_prefix).first().state else: zip_prefix = zip_prefix + "**" return zip_prefix # Find the administration object for a test-taker based on their unique hash code. def get_administration_instance(hash_id): try: administration_instance = Administration.objects.get(url_hash=hash_id) except: raise Http404("Administration not found") return administration_instance # If the BackgroundInfo model was filled out before, populate BackgroundForm with responses based on administation object def prefilled_background_form(administration_instance, front_page=True): background_instance = BackgroundInfo.objects.get( administration=administration_instance ) context = {} context["language"] = administration_instance.study.instrument.language context["instrument"] = administration_instance.study.instrument.name context["min_age"] = administration_instance.study.min_age context["max_age"] = administration_instance.study.max_age context["birthweight_units"] = administration_instance.study.birth_weight_units context["study_obj"] = administration_instance.study context["study"] = administration_instance.study context["source_id"] = administration_instance.backgroundinfo.source_id if front_page: background_form = BackgroundForm( instance=background_instance, context=context, page="front" ) else: background_form = BackpageBackgroundForm( instance=background_instance, context=context, page="back" ) return background_form
langcog/web-cdi
webcdi/cdi_forms/views/utils.py
utils.py
py
13,035
python
en
code
7
github-code
36
[ { "api_name": "logging.getLogger", "line_number": 15, "usage_type": "call" }, { "api_name": "pathlib.Path", "line_number": 18, "usage_type": "call" }, { "api_name": "os.path.dirname", "line_number": 18, "usage_type": "call" }, { "api_name": "os.path", "line_nu...
14152007415
import requests import json import sys from .ui import print_success from requests.auth import HTTPBasicAuth def find_github_emails(organization,organization_domain,github_api,github_username,github_token): github_emails = [] print_success("[+] Searching GitHub") page_number = 1 while page_number < 2: orgquery = requests.get((github_api + "/orgs/{0}/members?per_page=100&page={1}".format( organization,page_number)), auth=HTTPBasicAuth(github_username,github_token)) results = json.loads(orgquery.text) for result in results: try: username = result["login"] userquery = requests.get((github_api + "/users/{0}".format(username)), auth=HTTPBasicAuth(github_username,github_token)) userdata = json.loads(userquery.text) email = userdata["email"] if email: check_domain = email.split("@") if check_domain[1] == organization_domain: github_emails.append(",,{0},".format(email)) except: break page_number += 1 return github_emails
highmeh/lure
resources/github.py
github.py
py
1,007
python
en
code
148
github-code
36
[ { "api_name": "ui.print_success", "line_number": 10, "usage_type": "call" }, { "api_name": "requests.get", "line_number": 13, "usage_type": "call" }, { "api_name": "requests.auth.HTTPBasicAuth", "line_number": 14, "usage_type": "call" }, { "api_name": "json.loads"...
19989138110
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import gallery.models class Migration(migrations.Migration): dependencies = [ ('gallery', '0004_exhibit'), ] operations = [ migrations.AlterField( model_name='exhibit', name='image', field=models.ImageField(null=True, upload_to=gallery.models.upload_image_to, blank=True), preserve_default=True, ), ]
andrewhead/Gallery-Paths
server/gallery/migrations/0005_auto_20141206_2124.py
0005_auto_20141206_2124.py
py
499
python
en
code
0
github-code
36
[ { "api_name": "django.db.migrations.Migration", "line_number": 8, "usage_type": "attribute" }, { "api_name": "django.db.migrations", "line_number": 8, "usage_type": "name" }, { "api_name": "django.db.migrations.AlterField", "line_number": 15, "usage_type": "call" }, {...
4134355956
import pygame import sys import time from RobotLib.Math import * import math import argparse from RobotLib.FrontEnd import * from RobotLib.IO import * import numpy as np class MyFrontEnd(FrontEnd): """ Custom sub-class of FrontEnd You can write custom sub-routines here to respond to UI events and calculate updates """ #global variables because i couldn't make a class work. global velocity global omega global theta global sparkiCenter global sonarReadingS velocity = 0 omega = 0 theta = 0 sparkiCenter = vec(128.,128.) sonarReadingS = vec(15.,0.) def __init__(self,width,height,sparki): FrontEnd.__init__(self,width,height) self.sparki = sparki def mouseup(self,x,y,button): # x,y is position of mouse click print('mouse clicked at %d, %d'%(x,y)) def keydown(self,key): # see https://www.pygame.org/docs/ref/key.html for pygame key names, such as pygame.K_UP global velocity global omega #set velocities based on pressing of keys. 90% forward and back. small angular velocity to test if ( pygame.key.get_pressed()[pygame.K_UP] != 0 ): print('up pressed') velocity = 3.42 if ( pygame.key.get_pressed()[pygame.K_DOWN] != 0): print('down pressed') velocity = -3.42 if ( pygame.key.get_pressed()[pygame.K_LEFT] != 0): print('left pressed') omega += .2 if ( pygame.key.get_pressed()[pygame.K_RIGHT] != 0 ): print('right pressed') omega += -.2 def keyup(self,key): # see https://www.pygame.org/docs/ref/key.html for pygame key names, such as pygame.K_UP print('key released') global velocity global omega #set velocities to 0 on release of keys if (key == 273): velocity = 0 if (key == 274): velocity = 0 if (key == 275): omega = 0 if (key == 276): omega = 0 def draw(self,surface): # draw robot here # # draw a rectangle for the robot # draw a red line from the sonar to the object it is pinging # # use pygame.draw.line(surface,color,point1,point2) to draw a line # for example, pygame.draw.line(surface,(0,0,0),(0,0),(10,10)) # draws a black line from (0,0) to (10,0) #circumference of wheel = 15.71 cm #4096 steps per revolution. #1 step =.0038 cm /step #max speed is 1000 steps per sec or 3.8 cm per sec #90% is 900 or 3.42 cm per sec #find all 6 points in child frame #set transformation matrix based on center and orientation global sparkiCenter global sonarReadingS #use this for sonar if it won't work #transform matrixes transRtoM = transform(sparkiCenter[0],sparkiCenter[1],theta) transStoR = transform(2.5,0.,0.) transMtoR = invert(transRtoM) transRtoS = invert(transStoR) #points of sparki in robot frame frontRightR = vec(5.,-4.5) frontLeftR = vec(5.,4.5) backRightR = vec(-5.,-4.5) backLeftR = vec(-5.,4.5) centerR = vec(0.,0.) sonarR = vec(2.5,0.) #calculate all points of the robot and sonar using transform matrixes centerM = mul(transRtoM,frontRightR) frontRightM = mul(transRtoM,frontRightR) frontLeftM = mul(transRtoM,frontLeftR) backRightM = mul(transRtoM,backRightR) backLeftM = mul(transRtoM,backLeftR) sonarM = mul(transRtoM,sonarR) sonarReadingM = mul(transRtoM,mul(transStoR,sonarReadingS)) #draw robot and sonar, red for front of robot pygame.draw.line(surface,(255,0,0),frontRightM,frontLeftM) pygame.draw.line(surface,(0,255,0),frontRightM,backRightM) pygame.draw.line(surface,(0,255,0),backRightM,backLeftM) pygame.draw.line(surface,(0,255,0),frontLeftM,backLeftM) pygame.draw.line(surface,(255,0,0),sonarM,sonarReadingM) def update(self,time_delta): # this function is called approximately every 50 milliseconds # time_delta is the time in seconds since the last update() call # # you can send an update command to sparki here # use self.sparki.send_command(left_speed,left_dir,right_speed,right_dir,servo,gripper_status) # see docs in RobotLib/IO.py for more information, #0 for forward. #0 for strop gripper_status # # if you send a message more than once per millisecond, the message will be dropped # so, only call send_command() once per update() # # you can also calculate dead reckoning (forward kinematics) and other things like PID control here global theta global omega global velocity global sparkiCenter global sonarReadingS #integrating over time theta += omega * time_delta #calculate center given known velocity and direction sparkiCenter[0] += velocity * math.cos(theta) * time_delta sparkiCenter[1] += velocity * math.sin(theta) * time_delta #specific wheel velocity velocityRight = velocity + (omega * (8.51/2)) velocityLeft = velocity - (omega * (8.52/2)) #reverse flags and logic rightReverse = 0 leftReverse = 0 if velocityRight < 0: rightReverse = 1 velocityRight = abs(velocityRight) if velocityLeft < 0: leftReverse = 1 velocityLeft = abs(velocityLeft) #debugging output #print(sparkiCenter[0],sparkiCenter[1],theta,omega,velocity) #this will show a point if there is no reading, should show a line when readings come in #comment this out to show a static line pointing in the direction of the sonar sonarReadingS[0] = self.sparki.dist #tell sparki how to move self.sparki.send_command(int(velocityRight),rightReverse,int(velocityLeft),rightReverse,0,0) def main(): # parse arguments parser = argparse.ArgumentParser(description='Template') parser.add_argument('--width', type=int, default=256, help='map width') parser.add_argument('--height', type=int, default=256, help='map height') parser.add_argument('--port', type=str, default='', help='port for serial communication') args = parser.parse_args() with SparkiSerial(port=args.port) as sparki: # make frontend frontend = MyFrontEnd(args.width,args.height,sparki) # run frontend frontend.run() if __name__ == '__main__': main()
jeffherbst/sparki
template.py
template.py
py
6,840
python
en
code
0
github-code
36
[ { "api_name": "pygame.key.get_pressed", "line_number": 42, "usage_type": "call" }, { "api_name": "pygame.key", "line_number": 42, "usage_type": "attribute" }, { "api_name": "pygame.K_UP", "line_number": 42, "usage_type": "attribute" }, { "api_name": "pygame.key.ge...
2725915163
from os import scandir, rename from os.path import splitext, exists from shutil import move from time import sleep import logging from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler src_path = "" #local path to folder source_dir = src_path + "Downloads" dest_dir_docs = src_path + "Documents" dest_dir_pics = src_path + "Pictures" dest_dir_vid = src_path + "Movies" dest_dir_mus = src_path + "Music" # ? supported image types image_extensions = [".jpg", ".jpeg", ".jpe", ".jif", ".jfif", ".jfi", ".png", ".gif", ".webp", ".tiff", ".tif", ".psd", ".raw", ".arw", ".cr2", ".nrw", ".k25", ".bmp", ".dib", ".heif", ".heic", ".ind", ".indd", ".indt", ".jp2", ".j2k", ".jpf", ".jpf", ".jpx", ".jpm", ".mj2", ".svg", ".svgz", ".ai", ".eps", ".ico"] # ? supported Video types video_extensions = [".webm", ".mpg", ".mp2", ".mpeg", ".mpe", ".mpv", ".ogg", ".mp4", ".mp4v", ".m4v", ".avi", ".wmv", ".mov", ".qt", ".flv", ".swf", ".avchd"] # ? supported Audio types audio_extensions = [".m4a", ".flac", "mp3", ".wav", ".wma", ".aac"] # ? supported Document types document_extensions = [".doc", ".docx", ".odt", ".pdf", ".xls", ".xlsx", ".ppt", ".pptx"] def makeUnique(dest, name): filename, extension = splitext(name) counter = 1 # * IF FILE EXISTS, ADDS NUMBER TO THE END OF THE FILENAME while exists(f"{dest}/{name}"): name = f"{filename}({str(counter)}){extension}" counter += 1 return name def move(dest, entry, name): file_exists = path.exists(dest + "/" + name) if file_exists: unique_name = makeUnique(name) rename(entry, unique_name) move(entry, dest) class MoveHandler(FileSystemEventHandler): def on_modified(self, event): with scandir(source_dir) as entries: for entry in entries: name = entry.name dest = source_dir if name.endswith(audio_extensions): dest = dest_dir_mus elif name.endswith(document_extensions) : dest = dest_dir_docs elif name.endswith(video_extensions): dest = dest_dir_vid elif name.endswith(image_extensions) : dest = dest_dir_pics if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') path = source_dir event_handler = MoveHandler() observer = Observer() observer.schedule(event_handler, path, recursive=True) observer.start() try: while True: sleep(1) finally: observer.stop() observer.join()
zastasja/automate_stuff
moving_from_download.py
moving_from_download.py
py
2,787
python
en
code
0
github-code
36
[ { "api_name": "os.path.splitext", "line_number": 29, "usage_type": "call" }, { "api_name": "os.path.exists", "line_number": 32, "usage_type": "call" }, { "api_name": "os.rename", "line_number": 42, "usage_type": "call" }, { "api_name": "shutil.move", "line_num...
20350466819
try: import json except ImportError: import simplejson as json import requests import pandas import datetime import time # Please enter the file's path of the URLs to be checked file_path = str(input('Please Enter The File Path: ')) input_CSV = pandas.read_csv(file_path) Urls = input_CSV['Domain'].tolist() API_key = '7459dcceaae97bf8fbed29997d9b05003db3e42c92e4de20ddde4e9bf2cb053f' url = 'https://www.virustotal.com/vtapi/v2/url/report' # A function that classifies a site as safe or risk def check_if_url_safe(j_response): results = [] if_risk = "Safe" for x in j_response['scans']: get_result = j_response['scans'].get(x).get("result") results.append(get_result) #print(results) for y in results: if y == 'malicious site' or y == 'phishing site' or y == 'malware site': if_risk = "Risk" return if_risk # A function that receives a site and checks whether it has been queried in the last 30 minutes def if_checked_in_30_last_minutes(site): if_to_check_site = True now_time = datetime.datetime.now() output_CSV = pandas.read_csv("URLs_Status.csv") site_list = output_CSV['URL'].tolist() #print(site_list) if site in site_list: index = site_list.index(site) last_sample_time = datetime.datetime.strptime(output_CSV['Sample_Time'][index], '%Y-%m-%d %H:%M:%S.%f') last_sample_and_now_diff = (now_time - last_sample_time).total_seconds() / 60 # If 30 minutes have not passed since the last check, the site will not check if last_sample_and_now_diff < 30: if_to_check_site = False # Otherwise, the test data will be updated in the file else: if_to_check_site = False update_site_info(site, index) return if_to_check_site # If a site has not been queried in the last 30 minutes and already appears in the output file, will update the test fields for it def update_site_info(site, index): up_parameters = {'apikey': API_key, 'resource': site} up_response = requests.get(url=url, params=up_parameters) up_json_response = json.loads(up_response.text) up_sites_risk = check_if_url_safe(up_json_response) up_total_voting = up_json_response['total'] up_sample_time = datetime.datetime.now() output_CSV = pandas.read_csv("URLs_Status.csv") output_CSV.at[index, 'Sample_Time'] = up_sample_time output_CSV.at[index, 'Sites_Risk'] = up_sites_risk output_CSV.at[index, 'Total_Voting'] = up_total_voting output_CSV.to_csv("URLs_Status.csv", index=False) # Check the list of the sites obtained from the URLs file for i in Urls: check_site = if_checked_in_30_last_minutes(i) # A new site that has not been queried yet if check_site: parameters = {'apikey': API_key, 'resource': i} response = requests.get(url=url, params=parameters) json_response = json.loads(response.text) sites_risk = check_if_url_safe(json_response) total_voting = json_response['total'] sample_time = datetime.datetime.now() row_in = pandas.DataFrame([[i, sample_time, sites_risk, total_voting]], columns=['URL', 'Sample_Time', 'Sites_Risk', 'Total_Voting']) row_in.to_csv('URLs_Status.csv', mode='a', header=False, index=False) # we can check up to 4 sites per minute time.sleep(15)
dorintu/VirusTotal
VirusTotal_Assignment.py
VirusTotal_Assignment.py
py
3,484
python
en
code
0
github-code
36
[ { "api_name": "pandas.read_csv", "line_number": 12, "usage_type": "call" }, { "api_name": "datetime.datetime.now", "line_number": 36, "usage_type": "call" }, { "api_name": "datetime.datetime", "line_number": 36, "usage_type": "attribute" }, { "api_name": "pandas.r...
10489171606
# -*- coding: utf-8 -*- from flask import Blueprint, Response, g blueprint = Blueprint('property-tax-assessments-broken-model-scatterplots', __name__) @blueprint.app_template_filter('get_length') def get_length(thing): return len(thing) """ Tarbell project configuration """ # Google spreadsheet key SPREADSHEET_KEY = "1fRWsDwi4-lmdS6r61JB44Zrlb6GR9-21DTpQkgTPBdw" # Exclude these files from publication EXCLUDES = ['*.md', '*.ai', 'requirements.txt', 'node_modules', 'sass', 'js/src', 'package.json', 'Gruntfile.js'] # Spreadsheet cache lifetime in seconds. (Default: 4) # SPREADSHEET_CACHE_TTL = 4 # Create JSON data at ./data.json, disabled by default # CREATE_JSON = True # Get context from a local file or URL. This file can be a CSV or Excel # spreadsheet file. Relative, absolute, and remote (http/https) paths can be # used. # CONTEXT_SOURCE_FILE = "" # EXPERIMENTAL: Path to a credentials file to authenticate with Google Drive. # This is useful for for automated deployment. This option may be replaced by # command line flag or environment variable. Take care not to commit or publish # your credentials file. # CREDENTIALS_PATH = "" # S3 bucket configuration S3_BUCKETS = { # Provide target -> s3 url pairs, such as: # "mytarget": "mys3url.bucket.url/some/path" # then use tarbell publish mytarget to publish to it "production": "apps.chicagotribune.com/property-tax-assessments-broken-model-scatterplots", "staging": "apps.beta.tribapps.com/property-tax-assessments-broken-model-scatterplots", } # Default template variables DEFAULT_CONTEXT = { 'name': 'property-tax-assessments-broken-model-scatterplots', 'title': 'Property tax assessments - How the model broke', 'OMNITURE': { 'domain': 'chicagotribune.com', 'section': 'news', 'sitename': 'Chicago Tribune', 'subsection': 'watchdog', 'subsubsection': '', 'type': 'dataproject' } }
ryanbmarx/cook-county-property-tax-broken-model
tarbell_config.py
tarbell_config.py
py
1,937
python
en
code
0
github-code
36
[ { "api_name": "flask.Blueprint", "line_number": 5, "usage_type": "call" } ]
24843377512
' Script to for association analysis of clusters. Created by S Brueningk 2023 ' import pandas as pd import numpy as np from IPython.core.display import display, Markdown import os.path from pathlib import Path from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt import statsmodels.api as sm import scipy.stats as st ########################################################################################################### # Functions def logistic_regression(X, X_additional, Y, n_proteins): pvals = [] for i in range(n_proteins): # a protein each time X_i = X[:, i] X_tot = np.c_[X_additional, X_i] model = sm.Logit(Y, X_tot).fit(disp=0) pvals.append(model.pvalues[-1]) return pvals def linear_regression(X, X_additional, Y, n_proteins): pvals = [] for i in range(n_proteins): # a protein each time X_i = X[:, i] X_tot = np.c_[X_additional, X_i] model = sm.OLS(Y, X_tot).fit() pvals.append(model.pvalues[-1]) return pvals ########################################################################################################### ########################################################################################################## # INPUTS (fixed) useScaler = True stratfield = 'Patient_Care' # Account for COVID19 severity stratify_for = ['age_group', stratfield] inputData = '6M' # Options: '6M', '1M','1Mand6M' endpoint = 'PACS_6M_woDys' # Options: 'PACS_6M_woDys', 'PACS_12M' usehealthy = True # Options: True = include healthy controls, False: no healthy controls # Use reduced feature set in case of external validation reduceFeaturestoexternal = True external_features_keep = 'Data/external_usedClustersAndProteins.csv' # Paths data_file_1M = 'Data/Proteomics_Clinical_Data_220902_Acute_plus_healthy_v5.xlsx' data_file_6M = 'Data/Proteomics_Clinical_Data_220902_6M_timepoint_v4.xlsx' label_file = 'Data/Proteomics_Clinical_Data_220902_Labels_v2.xlsx' output_folder = 'Association_output' protein_clusters = 'Data/Table S2 Biological protein cluster compositions.xlsx' do_clusterAssociation = True do_singleProteinAssociation = False ########################################################################################################### # Run # Prepare output df_threshs = pd.DataFrame(columns = ['sig thresh']) output = os.path.join(output_folder) Path(output).mkdir(parents=True, exist_ok=True) # Create name if usehealthy: healthy = 'withHealthy' name = endpoint+'_withHealthy' else: healthy = 'noHealthy' name = endpoint+'_noHealthy' print('Working on '+ name) # Get label data endpoint_label = pd.read_excel(label_file, index_col=0) endpoint_label.set_index('SubjectID', inplace=True) label = endpoint_label[endpoint] # Get all features data_1M = pd.read_excel(data_file_1M) data_1M.set_index('SubjectID', inplace=True) data_6M = pd.read_excel(data_file_6M) data_6M.set_index('SubjectID', inplace=True) data_healthy = data_1M[data_1M['COVID'] == 'Healthy'] data_1M = data_1M.drop(data_healthy.index) # Get clinical data related to the COVID19 infection cols_clinical6M = ['Age', 'Sex','Post_Vaccine'] cols_clinical_nonBin = ['Age', 'BMI','Acute_Nr_Symptoms'] cols_clinical = ['Age', 'Sex','Post_Vaccine','Asthma', 'Lung','Diabetes','BMI','Cerebro','Heart', 'Hypertonia','Autoimmune_diseases','Malignancy','Kidney','Fatigue', 'Oxygen','Cough','Steroids','GI_symptoms','Remdesivir','Immuno', 'ICU','Tocilizumab','Hydroxychloroquin','Dyspnoe','Allergic_disease', 'Acute_Nr_Symptoms','Immunosuppressives','ACE_inhibitor','Fever'] cols_drop_fromFeatures = ['SampleId','Sampling_month','COVID', 'Days', 'Patient_Care','COVID19_Severity', 'COVID19_Severity_Grade','Index'] cols_clinical_keep = cols_clinical # Separate features used for association analysis severity_1M = data_1M[ ['Patient_Care','COVID19_Severity','COVID19_Severity_Grade']] severity_6M = data_6M[ ['Patient_Care','COVID19_Severity','COVID19_Severity_Grade']] severity_healthy = data_healthy[ ['Patient_Care','COVID19_Severity','COVID19_Severity_Grade']] # Clinical data (here only age and sex are used) data_clin_pats = data_1M[cols_clinical] data_clin_healthy = data_healthy[cols_clinical] for c in cols_clinical: if c in cols_clinical_nonBin: data_clin_pats.loc[:, c] = data_1M.loc[:, c] data_clin_healthy.loc[:, c] = data_healthy.loc[:, c] else: data_clin_pats.loc[:,c] = data_1M.loc[:,c].map({'YES':1,'NO':0,'male':1,'female':0}) data_clin_healthy.loc[:,c] = data_healthy.loc[:,c].map({'YES':1,'NO':0,'male':1,'female':0}) cols_not_not_in_healthy = list(set(data_clin_pats.columns)-set(data_clin_healthy.columns)) data_clin_healthy[cols_not_not_in_healthy] = 0 # Protein data data_1M = data_1M.drop(cols_clinical+cols_drop_fromFeatures, axis=1) data_healthy = data_healthy.drop(cols_clinical+cols_drop_fromFeatures, axis=1) data_6M = data_6M.drop(cols_clinical6M + cols_drop_fromFeatures, axis=1) # Get ratios of some proteins - note: Data are already log10 transformed!!! ratio1 = ['seq.2602.2','seq.3050.7','seq.2381.52','seq.4482.66'] ratio2 = ['seq.2811.27','seq.3175.51','seq.2888.49','seq.2888.49'] ratio_name = [] for i in range(0,len(ratio1)): ratio_name = 'ratio_'+ratio1[i]+ '_'+ratio2[i] data_1M[ratio_name] = np.log10(10**(data_1M[ratio1[i]])/10**(data_1M[ratio2[i]])) data_6M[ratio_name] = np.log10(10**(data_6M[ratio1[i]]) / 10**(data_6M[ratio2[i]])) data_healthy[ratio_name] = np.log10(10**(data_healthy[ratio1[i]]) / 10**(data_healthy[ratio2[i]])) # Now get the input data used in this run severity = severity_1M if inputData == '1M': data = data_1M elif inputData == '6M': data = data_6M elif inputData == '1Mand6M': cols_6M = [c+'_6M' for c in data_6M.columns] data_6M_app = data_6M.copy() data_6M_app.columns = cols_6M data_delta1M6M = data_1M-data_6M cols_1M6M= [c+'_1M-6M' for c in data_6M.columns] data_delta1M6M.columns = cols_1M6M # Concatenation of 1M and 6M data data = pd.concat([data_1M,data_6M_app,data_delta1M6M], axis=1) else: raise('Invalid choice of model inputData!') # Include healthy controls if wanted if usehealthy: if inputData == '1Mand6M': data_healthy_app = data_healthy.copy() data_healthy_app.columns = cols_6M data_healthy_delta1M6M = data_healthy-data_healthy data_healthy_delta1M6M.columns = cols_1M6M data_healthy = pd.concat([data_healthy, data_healthy_app, data_healthy_delta1M6M], axis=1) data = data.append(data_healthy) data_clin = data_clin_pats.append(data_clin_healthy) severity = severity.append(severity_healthy) # Check data and exclude patients with missing proteomics data = data.dropna() # Should not make any differene for our data data_clin = data_clin.loc[data.index,cols_clinical_keep] label = label.loc[data.index] label = label.dropna() data = data.loc[label.index] # Scale each protein (as used later) sc = StandardScaler() npx_reform_train = pd.DataFrame(sc.fit_transform( data.loc[:, :].values), index=data.loc[:, :].index, columns=data.columns) # scale age COVs = data_clin[['Age', 'Sex']] COVs[stratfield] = severity.loc[data_clin.index, stratfield].map(dict(Outpatient=0, Hospitalized=1, Healthy=0)) scaler = StandardScaler() COVs_sc = COVs.copy() COVs_sc['Age'] = scaler.fit_transform(COVs_sc['Age'].values.reshape(-1, 1)) # Prepare n, n_proteins = npx_reform_train.shape X_additional = np.c_[np.ones(n), COVs_sc.values] X = npx_reform_train.values phenotype = label.values.astype(np.float64) if do_singleProteinAssociation: # Single protein association if len(np.unique(phenotype)) == 2: pvals = logistic_regression(X, X_additional, phenotype, n_proteins) else: pvals = linear_regression(X, X_additional, phenotype, n_proteins) pvals = pd.Series(pvals, index=npx_reform_train.columns) else: pvals = pd.Series() # Clusters if do_clusterAssociation: df_prots = pd.read_excel(protein_clusters) if reduceFeaturestoexternal: df_prots_external = pd.read_csv(external_features_keep, index_col=0) missing = [] features_keep = [] keep_index = [] for p in df_prots_external.index: if p not in df_prots['AptamerName'].values: missing.append(p) else: features_keep.append(p) keep_index += list(df_prots[df_prots['AptamerName'] == p].index) df_prots = df_prots.loc[np.unique(keep_index)] # Association covariates only model_Cov = sm.Logit(phenotype, X_additional).fit(disp=0, method='bfgs') pvals_Cov = model_Cov.llr_pvalue pvals.loc['COVs'] = pvals_Cov # Association cluster with COVs clusters = df_prots['Group'].unique() for this_cl in clusters: # get protein group ids_use = list(df_prots[df_prots['Group']==this_cl]['AptamerName'].values) prots_use = [p for p in ids_use] # get the relevant data X_i = npx_reform_train.loc[:, prots_use].values X_tot = np.c_[X_additional, X_i] # Association try: model = sm.Logit(phenotype, X_tot).fit(disp=0, method='bfgs') # Use p-value for whole model here pvals.loc[this_cl] = model.llr_pvalue print(this_cl + ': ' + str(model.llr_pvalue)) except: print('Failed Single Group ' + this_cl) pvals.loc[this_cl] = np.nan # Organize and save results pvals = pvals.sort_values() pvals.sort_values().to_csv(os.path.join(output_folder, name + '_singleSomamer_pvals.csv'))
BorgwardtLab/LongCOVID
associationClusters.py
associationClusters.py
py
9,990
python
en
code
0
github-code
36
[ { "api_name": "numpy.c_", "line_number": 19, "usage_type": "attribute" }, { "api_name": "statsmodels.api.Logit", "line_number": 20, "usage_type": "call" }, { "api_name": "statsmodels.api", "line_number": 20, "usage_type": "name" }, { "api_name": "numpy.c_", "l...
18573856316
import numpy as np import matplotlib.pyplot as plt N = 50 # Nb of steps dt = 0.01 kv = 0.1 tau = 0.05 lamb = 0 ns = 6 ############################### ## Complete the code below #### ############################### A = np.array([[1,0,dt,0,0,0],[0,1,0,dt,0,0],[0,0,1-kv*dt,0,dt,0],[0,0,0,1-kv*dt,0,dt],[0,0,0,0,1-dt/tau,0],[0,0,0,0,0,1-dt/tau]]) B = np.zeros((6,2)) B[4,:]=np.array([dt/tau,0]) B[5,:]=np.array([0,dt/tau]) w1 = 10 w2 = 10 w3 = 0.1 w4 = 0.1 QN = np.zeros((6,6)) QN[0,0]=w1 QN[1,1]=w2 QN[2,2]=w3 QN[3,3]=w4 # We set the R matrix as follows, later on you can change it to see its effect on the controller R = np.array([(10 ** -4, 0), (0, 10 ** -4)]) L = np.zeros((N, 2, ns)) S = np.zeros((N, ns, ns)) Q = np.zeros((N, ns, ns)) ############################### ## Complete the code below #### ############################### # (hint : fill in L and S matrices in the backward loop) Q[N - 1, :, :] = QN S[N - 1, :, :] = QN for i in range(N - 1, 0, -1): L[i,:,:]=np.linalg.solve(R+B.T@S[i,:,:]@B,B.T@S[i,:,:]@A) S[i-1,:,:]=A.T@S[i,:,:]@(A-B@L[i,:,:]) X = np.zeros((N, ns, 1)) #Change the first entries of the vector below to investigate different starting position print(L[45,:,:]) X[0, :, :] = [[0.2], [0.3], [0], [0], [0], [0]] #Computation of the motor noise Xi = np.random.normal(loc=0, scale=10 ** -4, size=(N, 6, 1)) ############################### ## Complete the code below #### ############################### for j in range(0, N - 1): X[j+1,:,:]=(A-B@L[j,:,:])@X[j,:,:]+Xi[j,:,:] ############################### ## Complete the code below #### ############################### #Create a representation of positions and speeds with respect to time and characterise their evolution fig, ax=plt.subplots() ax.plot(X[:,0,:],X[:,1,:],'r') fig, ax=plt.subplots() ax.plot(range(N),X[:,0,:],'b') ax.plot(range(N),X[:,1,:],'r') fig, ax=plt.subplots() ax.plot(range(N),X[:,2,:],'r') ax.plot(range(N),X[:,3,:],'b') #Initialize the state estimation... What is the size of hte matrix? How would you complete the information corresponding to the first time step? Xhat = np.zeros_like(X) Xhat[0, :, :] = X[0,:,:] + np.random.normal(loc=0, scale=10 ** -6, size=(6, 1)) #Initialization of the command and observable Y = np.zeros((N, ns, 1)) U = np.zeros((N,2,1)) #Initialization of the covariance matrix of the state, how would you initialize the first covariance matrix? Sigma = np.zeros((N, ns, ns)) Sigma[0,:,:] = np.random.normal(loc=0, scale=10 ** -2, size=(1, ns, 1)) #Some more initialization (nothing to do for you here) K = np.zeros((N, ns, ns)) H = np.eye(ns) Xi = np.random.normal(loc=0, scale=10 ** -4, size=(N, ns, 1)) Omega = np.random.normal(loc=0, scale=10 ** -2, size=(N, ns, 1)) oXi = 0.1 * (B @ B.T) oOmega = 0.1 * np.max(np.max(oXi)) * np.eye(ns) #Fill in the following loop to complete # # state evolution # observatoin evolutino # computation of K and Sigma # computation of the command # evolution of the state estimation for j in range(0, N - 1): X[j+1,:,:]=A@X[j,:,:]-B@L[j,:,:]@Xhat[j,:,:]+Xi[j,:,:] Y[j+1,:,:] = H@X[j,:,:]+Omega[j+1,:,:] K[j,:,:] = A@Sigma[j,:,:]@H.T@np.linalg.inv(H@Sigma[j,:,:]@H.T+oOmega) Sigma[j+1,:,:] = oXi + (A-K[j,:,:]@H)@Sigma[j,:,:]@A.T Xhat[j+1,:,:] = (A-B@L[j,:,:])@Xhat[j,:,:] + K[j,:,:]@(Y[j,:,:]-H@Xhat[j,:,:]) #Plot the time evolution of the state, its observation and its estimation.. What do you observe? fig, ax=plt.subplots() ax.plot(X[:,0,:],X[:,1,:],'r') fig, ax=plt.subplots() ax.plot(range(N),X[:,0,:],'b') ax.plot(range(N),X[:,1,:],'r') ax.plot(range(N),Xhat[:,0,:],'b:') ax.plot(range(N),Xhat[:,1,:],'r:') fig, ax=plt.subplots() ax.plot(range(N),X[:,2,:],'r') ax.plot(range(N),X[:,3,:],'b') plt.show()
decomiteA/ReachRLToolbox
OFC_2D/OFC2D_Reaching.py
OFC2D_Reaching.py
py
3,838
python
en
code
0
github-code
36
[ { "api_name": "numpy.array", "line_number": 16, "usage_type": "call" }, { "api_name": "numpy.zeros", "line_number": 17, "usage_type": "call" }, { "api_name": "numpy.array", "line_number": 18, "usage_type": "call" }, { "api_name": "numpy.array", "line_number": ...
2358896940
"""empty message Revision ID: bc7b1dd477a1 Revises: d7ad318a76d9 Create Date: 2021-08-24 19:22:40.497985 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'bc7b1dd477a1' down_revision = 'd7ad318a76d9' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('aboutme', sa.Column('user_id', sa.Integer(), nullable=True)) op.create_foreign_key(None, 'aboutme', 'user', ['user_id'], ['id']) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, 'aboutme', type_='foreignkey') op.drop_column('aboutme', 'user_id') # ### end Alembic commands ###
nickcao123456/blog
migrations/versions/bc7b1dd477a1_.py
bc7b1dd477a1_.py
py
788
python
en
code
0
github-code
36
[ { "api_name": "alembic.op.add_column", "line_number": 21, "usage_type": "call" }, { "api_name": "alembic.op", "line_number": 21, "usage_type": "name" }, { "api_name": "sqlalchemy.Column", "line_number": 21, "usage_type": "call" }, { "api_name": "sqlalchemy.Integer...
3954152863
from PIL import Image img = Image.open("PDI/folha.png").convert('L') adj = 8 # 4 para adj-8, 8 para adj-m visited = [[False for col in range(img.height)] for row in range(img.width)] dx = [0, 0, 1, -1, 1, 1, -1, -1] dy = [1, -1, 0, 0, 1, -1, 1, -1] def isEdge(x, y): for i in range(adj): if(img.getpixel((x + dx[i], y + dy[i])) == 0): return True return False def dfs(i, j): st = [(i, j)] while(len(st) > 0): pixel = st.pop() x = pixel[0] y = pixel[1] if(visited[x][y]): continue visited[x][y] = True for i in range(adj): # verifica se os pixels adjacentes sao validos if(x + dx[i] < 0 or x + dx[i] >= img.width or y + dy[i] < 0 or y + dy[i] >= img.height): continue # se a imagem for branca e estiver na borda if(img.getpixel((x + dx[i], y + dy[i])) == 255 and isEdge(x + dx[i], y + dy[i])): st.append((x + dx[i], y + dy[i])) # pinta o pixel de cinza img.putpixel((x + dx[i], y + dy[i]), 128) for i in range(img.width): for j in range(img.height): if(visited == True): continue if(img.getpixel((i, j)) == 255): dfs(i, j) visited[i][j] = True for i in range(img.width): for j in range(img.height): if(img.getpixel((i, j)) == 255): img.putpixel((i, j), 0) elif(img.getpixel((i, j)) == 128): img.putpixel((i, j), 255) img.save("adjacenciam.png")
Pedroffda/Digital-Image-Processing
Pratica-01/code/adj_border.py
adj_border.py
py
1,417
python
en
code
0
github-code
36
[ { "api_name": "PIL.Image.open", "line_number": 3, "usage_type": "call" }, { "api_name": "PIL.Image", "line_number": 3, "usage_type": "name" } ]
14032964317
from django.http import JsonResponse, HttpResponse from .models import Template, Field import re from .utils import check_db def post(request): check_db() form = type_form(request.GET) name = "" for name_f, val in form.items(): res = Field.objects.filter(name_field=name_f, type_field=val).values_list() if not res: continue name = Template.objects.get(id=res[0][1]) if not name: return JsonResponse(form) return HttpResponse(name) def validate(val): validators = { 'email': r'^\S+@\w+.\w{2,4}$', 'date': r'^\d\d\.\d\d\.\d{4}$', 'phone': r'^79\s*\d{2}\s*\d{3}\s*\d{2}\s*\d{2}$', } for t, regex in validators.items(): if re.fullmatch(regex, val): return t return 'text' def type_form(d): res = {} d = d.dict() for k, v in d.items(): res[k] = validate(v) return res
krlns/forms_template
test_task/app/views.py
views.py
py
924
python
en
code
0
github-code
36
[ { "api_name": "utils.check_db", "line_number": 8, "usage_type": "call" }, { "api_name": "models.Field.objects.filter", "line_number": 12, "usage_type": "call" }, { "api_name": "models.Field.objects", "line_number": 12, "usage_type": "attribute" }, { "api_name": "m...
25107350000
from OpenGL.GL import * from Masks import * from ObjectLoader import ObjectLoader from Model import Model from Shaders.ColoredObjectShader import ColoredObjectShader import pyrr class MazeCore: def __init__(self, shader : ColoredObjectShader): # self.transparentShader = TransparentShader() # self.shader = ColoredObjectShader() self.loadModels(shader) self.modelMatrix = self.__getModelMatrix([0, 0, 0]) self.alpha_value = 0.5 def loadModels(self, shader : ColoredObjectShader): mazeLoader = ObjectLoader(VERTEX_COORDINATES | VERTEX_COLORS, INDICES) mazeLoader.loadModel("maze/", "fmaze") self.mazeModel = Model() self.mazeModel.pushData( shader, VERTEX_COORDINATES = mazeLoader.vertex_coords_array, VERTEX_COLORS = mazeLoader.vertex_colors_array, INDICES = mazeLoader.indices ) # Assume shader is binded def render(self, camera, shader : ColoredObjectShader): # self.transparentShader.bind() # shader.bind() self.mazeModel.bindVAO() shader.setModelMatrix(self.modelMatrix) shader.setViewMatrix(camera.get_view_matrix()) shader.setProjectionMatrix(camera.get_projection_matrix()) shader.setAlphaValue(self.alpha_value) glDepthMask(GL_FALSE); glEnable(GL_CULL_FACE) glCullFace(GL_FRONT) glDrawElements(GL_TRIANGLES, self.mazeModel.indicesCount, GL_UNSIGNED_INT, None) glCullFace(GL_BACK) glDrawElements(GL_TRIANGLES, self.mazeModel.indicesCount, GL_UNSIGNED_INT, None) glDisable(GL_CULL_FACE) glDepthMask(GL_TRUE) def __getModelMatrix(self, position): return pyrr.matrix44.create_from_translation(pyrr.Vector3(position))
VolodymyrVakhniuk/Pacman
src/Core/MazeCore.py
MazeCore.py
py
1,878
python
en
code
1
github-code
36
[ { "api_name": "Shaders.ColoredObjectShader.ColoredObjectShader", "line_number": 10, "usage_type": "name" }, { "api_name": "Shaders.ColoredObjectShader.ColoredObjectShader", "line_number": 20, "usage_type": "name" }, { "api_name": "ObjectLoader.ObjectLoader", "line_number": 22...
17849581957
from .config import np, Vector, Keyword, ParameterName, ZOrderConfig, TextConfig, HorizontalAlignment, \ VerticalAlignment, ColorConfig from .config import BentChevronArrow, ChevronArrow, CompositeFigure, Rectangle, TextBox, RoundRectangle from .config import MIDDiagram, NetworkDiagram, CulturedCell, Mice, Human, CarbonBackbone, CommonElementConfig class NoisyDataDiagramConfig(object): normal_document_size = CommonElementConfig.normal_document_size smaller_document_size = normal_document_size - 1 smallest_document_size = normal_document_size - 4 text_z_order = CommonElementConfig.text_z_order background_z_order = ZOrderConfig.default_patch_z_order child_diagram_base_z_order = CommonElementConfig.child_diagram_base_z_order child_diagram_z_order_increment = CommonElementConfig.child_diagram_z_order_increment document_text_width = 0.18 document_text_width2 = 0.12 document_text_height = 0.06 document_text_height2 = 0.04 smaller_document_text_height = 0.04 document_text_config = { ParameterName.font: TextConfig.main_text_font, ParameterName.font_size: normal_document_size, ParameterName.width: document_text_width, ParameterName.height: document_text_height, ParameterName.horizontal_alignment: HorizontalAlignment.center, ParameterName.vertical_alignment: VerticalAlignment.center_baseline, ParameterName.z_order: text_z_order, # ParameterName.text_box: True, } mid_title_text_common_config_dict = { **document_text_config, ParameterName.font_size: 10, } normal_chevron_width = CommonElementConfig.normal_chevron_width chevron_config = { **CommonElementConfig.chevron_config, ParameterName.width: normal_chevron_width - 0.015 } bend_chevron_to_main_distance = normal_chevron_width / 2 + 0.015 bend_chevron_config = { **chevron_config, ParameterName.radius: 0.03, ParameterName.width: normal_chevron_width - 0.02 } predicted_mid_text_config_dict = { **document_text_config, ParameterName.font_size: smallest_document_size, ParameterName.width: document_text_width2, ParameterName.height: smaller_document_text_height, } final_experimental_mid_text_config = { **document_text_config, ParameterName.font_size: smaller_document_size, ParameterName.width: document_text_width, ParameterName.height: document_text_height2, ParameterName.vertical_alignment: VerticalAlignment.top, } final_experimental_mid_background_config = { ParameterName.radius: 0.05, ParameterName.width: document_text_width, ParameterName.edge_width: None, ParameterName.face_color: ColorConfig.super_light_blue, ParameterName.z_order: background_z_order } background_rectangle_config_dict = { ParameterName.face_color: ColorConfig.light_gray, ParameterName.edge_width: None, ParameterName.z_order: 0 } class NoisyDataDiagram(CompositeFigure): total_width = 1.2 total_height = 0.5 height_to_width_ratio = total_height / total_width def __init__(self, **kwargs): text_obj_list, chevron_arrow_obj_list, constructed_obj_list = noisy_data_diagram_generator() size = Vector(self.total_width, self.total_height) optimization_diagram_dict = { ParameterName.text: {text_obj.name: text_obj for text_obj in text_obj_list}, ParameterName.chevron_arrow: { chevron_arrow_obj.name: chevron_arrow_obj for chevron_arrow_obj in chevron_arrow_obj_list}, ParameterName.constructed_obj: { constructed_obj.name: constructed_obj for constructed_obj in constructed_obj_list}, } super().__init__( optimization_diagram_dict, Vector(0, 0), size, **kwargs) def generate_evenly_distributed_mid_diagram( element_config_list, text_config_list, x_mid_location, data_y_vector, primary_data_array, noise_data_array, color_name, mid_diagram_scale, title_text_common_config_dict): mid_carbon_num = len(primary_data_array[0]) primary_data_previous_center_loc = MIDDiagram.calculate_center( MIDDiagram, mid_diagram_scale, mid_carbon_num) for mid_data_index, primary_mid_data_vector in enumerate(primary_data_array): if noise_data_array is not None: noise_data_vector = noise_data_array[mid_data_index] mid_data_vector = np.array([primary_mid_data_vector, noise_data_vector]) else: mid_data_vector = primary_mid_data_vector target_center_vector = Vector(x_mid_location, data_y_vector[mid_data_index]) predicted_mid_diagram_bottom_left_offset = target_center_vector - primary_data_previous_center_loc final_experimental_mid_diagram_dict = { ParameterName.data_vector: mid_data_vector, ParameterName.scale: mid_diagram_scale, ParameterName.color_name: color_name, ParameterName.bottom_left_offset: predicted_mid_diagram_bottom_left_offset, ParameterName.base_z_order: NoisyDataDiagramConfig.child_diagram_base_z_order, ParameterName.z_order_increment: NoisyDataDiagramConfig.child_diagram_z_order_increment } element_config_list.append((MIDDiagram, final_experimental_mid_diagram_dict)) text_config_list.append({ **title_text_common_config_dict, ParameterName.string: f'Metabolite {mid_data_index + 1}', ParameterName.center: target_center_vector + Vector(0, 0.056), }) def noisy_data_diagram_generator(): main_horiz_axis = 0.22 # width = 1, height = height_to_width_ratio, all absolute number are relative to width upper_horiz_axis = main_horiz_axis + 0.12 bottom_horiz_axis = main_horiz_axis - 0.12 text_horiz_axis = main_horiz_axis + 0.23 vert_axis_list = [0.11, 0.43, 0.75, 1.08] chevron_start_end_x_value_list = [ Vector(0.22, 0.32), Vector(0.54, 0.64), Vector(0.86, 0.96), ] primary_data_array = np.array([ [0.60, 0.049, 0.051, 0.3], [0.37, 0.052, 0.048, 0.53], [0.22, 0.043, 0.057, 0.68], ]) noise_data_array = np.array([ [-0.12, -0.009, 0.006, 0.1], [-0.08, 0.005, -0.003, 0.09], [0.11, -0.002, -0.008, -0.1] ]) absolute_noise_array = np.abs(noise_data_array) primary_data_exclude_noise_array = primary_data_array + np.clip(noise_data_array, None, 0) data_include_noise_array = primary_data_array + noise_data_array mid_diagram_scale = 0.08 top_text_distance = 0.015 mid_data_y_vector = [upper_horiz_axis, main_horiz_axis, bottom_horiz_axis] mid_data_height = mid_diagram_scale * MIDDiagram.total_height top_text_y_value = upper_horiz_axis + mid_data_height / 2 + top_text_distance other_element_config_list = [] text_config_list = [ { ParameterName.string: 'Precise simulated data', ParameterName.center: Vector(vert_axis_list[0], text_horiz_axis), **NoisyDataDiagramConfig.document_text_config, }, { ParameterName.string: 'Introducing random noise\nand normalization', ParameterName.center: Vector(vert_axis_list[1], text_horiz_axis), **NoisyDataDiagramConfig.document_text_config, }, { ParameterName.string: 'Noisy simulated data', ParameterName.center: Vector(vert_axis_list[2], text_horiz_axis), **NoisyDataDiagramConfig.document_text_config, }, { ParameterName.string: 'MFA and\nfollowing analysis', ParameterName.center: Vector(vert_axis_list[3], main_horiz_axis), **NoisyDataDiagramConfig.document_text_config, }, ] generate_evenly_distributed_mid_diagram( other_element_config_list, text_config_list, vert_axis_list[0], mid_data_y_vector, primary_data_array, None, Keyword.blue, mid_diagram_scale, NoisyDataDiagramConfig.mid_title_text_common_config_dict) chevron_1_config = { ParameterName.tail_end_center: Vector(chevron_start_end_x_value_list[0][0], main_horiz_axis), ParameterName.head: Vector(chevron_start_end_x_value_list[0][1], main_horiz_axis), **NoisyDataDiagramConfig.chevron_config, } generate_evenly_distributed_mid_diagram( other_element_config_list, text_config_list, vert_axis_list[1], mid_data_y_vector, primary_data_exclude_noise_array, absolute_noise_array, [Keyword.blue, Keyword.gray], mid_diagram_scale, NoisyDataDiagramConfig.mid_title_text_common_config_dict) chevron_2_config = { ParameterName.tail_end_center: Vector(chevron_start_end_x_value_list[1][0], main_horiz_axis), ParameterName.head: Vector(chevron_start_end_x_value_list[1][1], main_horiz_axis), **NoisyDataDiagramConfig.chevron_config, } generate_evenly_distributed_mid_diagram( other_element_config_list, text_config_list, vert_axis_list[2], mid_data_y_vector, data_include_noise_array, None, Keyword.orange, mid_diagram_scale, NoisyDataDiagramConfig.mid_title_text_common_config_dict) chevron_3_config = { ParameterName.tail_end_center: Vector(chevron_start_end_x_value_list[2][0], main_horiz_axis), ParameterName.head: Vector(chevron_start_end_x_value_list[2][1], main_horiz_axis), **NoisyDataDiagramConfig.chevron_config, } chevron_arrow_config_list = [chevron_1_config, chevron_2_config, chevron_3_config] text_obj_list = [] for text_config_dict in text_config_list: text_obj = TextBox(**text_config_dict) text_obj_list.append(text_obj) chevron_obj_list = [] for chevron_arrow_config_dict in chevron_arrow_config_list: if ParameterName.radius in chevron_arrow_config_dict: chevron_class = BentChevronArrow else: chevron_class = ChevronArrow chevron_arrow_obj = chevron_class(**chevron_arrow_config_dict) chevron_obj_list.append(chevron_arrow_obj) other_element_obj_list = [] for other_element_class, other_element_config in other_element_config_list: other_element_obj = other_element_class(**other_element_config) other_element_obj_list.append(other_element_obj) return text_obj_list, chevron_obj_list, other_element_obj_list
LocasaleLab/Automated-MFA-2023
figures/figure_plotting/figure_elements/diagrams/diagrams/noisy_data_diagram.py
noisy_data_diagram.py
py
10,532
python
en
code
0
github-code
36
[ { "api_name": "config.CommonElementConfig.normal_document_size", "line_number": 8, "usage_type": "attribute" }, { "api_name": "config.CommonElementConfig", "line_number": 8, "usage_type": "name" }, { "api_name": "config.CommonElementConfig.text_z_order", "line_number": 12, ...
18521700070
import pandas as pd import pickle import numpy as np from tqdm import tqdm import os, sys, inspect from collections import defaultdict from processing_utils import make_aggregate_df, make_yearly_df, make_class_df, make_df_by_decade, make_parent_df MIN_FREQ = 20 # folders for reading and writing data raw_data_folder = '../../data/raw_data/' output_folder = '../../data/bootstrapped_data/' # number of bootstrapped instances to create n_iter = 10000 def filter_min_freq(df): return df[df["freq"] >= MIN_FREQ].reset_index(drop=True) if __name__ == "__main__": # random seed for reproducibility np.random.seed(3937) # AGGREGATE AND YEARLY ANALYSIS with open(raw_data_folder + 'm_words_cds.p', 'rb') as fp: m_words_cds = pickle.load(fp) with open(raw_data_folder + 'f_words_cds.p', 'rb') as fp: f_words_cds = pickle.load(fp) with open(raw_data_folder + 'm_words_cs.p', 'rb') as fp: m_words_cs = pickle.load(fp) with open(raw_data_folder + 'f_words_cs.p', 'rb') as fp: f_words_cs = pickle.load(fp) # get total word count all_words = [] downsample_n_cds = 0 downsample_n_cs = 0 for age in range(1,6): all_words += m_words_cds[str(age)] all_words += f_words_cds[str(age)] all_words += m_words_cs[str(age)] all_words += f_words_cs[str(age)] downsample_n_cds += len(f_words_cds[str(age)]) + len(m_words_cds[str(age)]) downsample_n_cs += len(f_words_cs[str(age)]) + len(m_words_cs[str(age)]) # compute the number of words to include per age-gender pair downsample_n_cds = int(downsample_n_cds / 10) downsample_n_cs = int(downsample_n_cs / 10) print(f"CDS downsample number: {downsample_n_cds}") print(f"CS downsample number: {downsample_n_cs}") for iteration in tqdm(range(n_iter)): m_cds_ds = {} f_cds_ds = {} m_cs_ds = {} f_cs_ds = {} # downsample equally for each age-gender pair for age in range(1,6): m_cds_ds[str(age)] = np.random.choice(m_words_cds[str(age)], size=downsample_n_cds, replace=True) f_cds_ds[str(age)] = np.random.choice(f_words_cds[str(age)], size=downsample_n_cds, replace=True) m_cs_ds[str(age)] = np.random.choice(m_words_cs[str(age)], size=downsample_n_cs, replace=True) f_cs_ds[str(age)] = np.random.choice(f_words_cs[str(age)], size=downsample_n_cs, replace=True) # compute yearly word statistics df_cds_yearly = make_yearly_df(m_cds_ds, f_cds_ds) df_cs_yearly = make_yearly_df(m_cs_ds, f_cs_ds) # compute aggregate word statistics df_cds_agg = make_aggregate_df(m_cds_ds, f_cds_ds) df_cs_agg = make_aggregate_df(m_cs_ds, f_cs_ds) # filter out the words that have fewer instances than the minimum frequency df_cds_yearly = filter_min_freq(df_cds_yearly) df_cs_yearly = filter_min_freq(df_cs_yearly) df_cds_agg = filter_min_freq(df_cds_agg) df_cs_agg = filter_min_freq(df_cs_agg) # save data to csv df_cds_yearly.to_csv(f'{output_folder}/df_cds_yearly_bs{iteration}.csv') df_cs_yearly.to_csv(f'{output_folder}/df_cs_yearly_bs{iteration}.csv') df_cds_agg.to_csv(f'{output_folder}/df_cds_agg_bs{iteration}.csv') df_cs_agg.to_csv(f'{output_folder}/df_cs_agg_bs{iteration}.csv')
benpry/gender-associations-child-language
code/bootstrap/bootstrap_aggregate_yearly.py
bootstrap_aggregate_yearly.py
py
3,396
python
en
code
0
github-code
36
[ { "api_name": "numpy.random.seed", "line_number": 23, "usage_type": "call" }, { "api_name": "numpy.random", "line_number": 23, "usage_type": "attribute" }, { "api_name": "pickle.load", "line_number": 28, "usage_type": "call" }, { "api_name": "pickle.load", "li...
39479742836
# -*- coding: utf-8 -*- from django.urls import path, re_path, include from decks import views from decks.views import TournamentListView urlpatterns = [ re_path(r'^$', views.index, name='index'), re_path(r'^(?P<deck_id>[0-9]+)/$', views.deck, name='deck'), re_path(r'^cluster/(?P<cluster_id>[0-9]+)/$', views.cluster, name='cluster'), re_path(r'^cluster/(?P<cluster_id>[0-9]+)/cards/$', views.cluster_cards, name='cluster_cards'), re_path(r'^cluster/(?P<cluster_id>[0-9]+)/close/$', views.cluster_close, name='cluster_close'), re_path(r'^cluster/(?P<cluster_id>[0-9]+)/far/$', views.cluster_far, name='cluster_far'), re_path(r'^cluster/$', views.clusters, name='clusters'), re_path(r'^tournament/$', TournamentListView.as_view(), name='tournaments'), re_path(r'^tournament/(?P<tournament_id>[0-9]+)/$', views.tournament, name='tournament'), re_path(r'^crafter/$', views.recommendations, name='recommendations'), re_path(r'^manabase/$', views.manabaseanalysis, name='manabaseanalysis'), ]
jcrickmer/mtgdbpy
decks/urls.py
urls.py
py
1,036
python
en
code
0
github-code
36
[ { "api_name": "django.urls.re_path", "line_number": 9, "usage_type": "call" }, { "api_name": "decks.views.index", "line_number": 9, "usage_type": "attribute" }, { "api_name": "decks.views", "line_number": 9, "usage_type": "name" }, { "api_name": "django.urls.re_pa...
28924497501
""" 프로그래머스 Lv2 -뉴스 클러스터링 """ # 아이디어가 맘에 들었음!@ """ 20 Minute :: flood fill """ from collections import Counter import math def make_window_size2(string): windows = [] for i in range(len(string)-1): if string[i].isalpha() and string[i+1].isalpha(): windows.append(string[i:i+2].lower()) return windows def solution(str1, str2): window1 = make_window_size2(str1) window2 = make_window_size2(str2) total_window = window1+ window2 #Processing counter1 = Counter(window1) counter2 = Counter(window2) union_counter = {} intersection_counter = {} for phrase in total_window: cnt1 = counter1.get(phrase, 0) cnt2 = counter2.get(phrase, 0) union_counter[phrase] = max(cnt1, cnt2) if min(cnt1, cnt2) > 0: intersection_counter[phrase] = min(cnt1, cnt2) print("union_cnt:", union_counter) print("intersection_cnt:", intersection_counter) if union_counter: answer = math.floor((sum(intersection_counter.values()) * 65536 / sum(union_counter.values()))) else: answer = 65536 return answer
GuSangmo/BOJ_practice
programmers/level2/뉴스클러스터링.py
뉴스클러스터링.py
py
1,199
python
en
code
0
github-code
36
[ { "api_name": "collections.Counter", "line_number": 29, "usage_type": "call" }, { "api_name": "collections.Counter", "line_number": 30, "usage_type": "call" }, { "api_name": "math.floor", "line_number": 44, "usage_type": "call" } ]