hexsha
stringlengths
40
40
size
int64
5
2.06M
ext
stringclasses
11 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
251
max_stars_repo_name
stringlengths
4
130
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
251
max_issues_repo_name
stringlengths
4
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
251
max_forks_repo_name
stringlengths
4
130
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.05M
avg_line_length
float64
1
1.02M
max_line_length
int64
3
1.04M
alphanum_fraction
float64
0
1
96484d835344ea1b7665583dd26015806d06751a
4,233
py
Python
ellipses/script_train_radon_tiramisu_jitter_v6.py
jmaces/robust-nets
25d49302f9fa5fcc9ded2727de75e96e25243d09
[ "MIT" ]
14
2020-11-10T07:37:23.000Z
2022-03-21T15:19:22.000Z
ellipses/script_train_radon_tiramisu_jitter_v6.py
jmaces/robust-nets
25d49302f9fa5fcc9ded2727de75e96e25243d09
[ "MIT" ]
null
null
null
ellipses/script_train_radon_tiramisu_jitter_v6.py
jmaces/robust-nets
25d49302f9fa5fcc9ded2727de75e96e25243d09
[ "MIT" ]
2
2021-03-13T14:39:36.000Z
2022-02-17T06:44:29.000Z
import os import matplotlib as mpl import torch import torchvision from data_management import IPDataset, Jitter, SimulateMeasurements from networks import IterativeNet, Tiramisu from operators import Radon # ----- load configuration ----- import config # isort:skip # ----- global configuration ----- mpl.use("agg") device = torch.device("cuda:0") torch.cuda.set_device(0) # ----- measurement configuration ----- theta = torch.linspace(0, 180, 61)[:-1] # 60 lines, exclude endpoint OpA = Radon(config.n, theta) # ----- network configuration ----- subnet_params = { "in_channels": 1, "out_channels": 1, "drop_factor": 0.0, "down_blocks": (5, 7, 9, 12, 15), "up_blocks": (15, 12, 9, 7, 5), "pool_factors": (2, 2, 2, 2, 2), "bottleneck_layers": 20, "growth_rate": 16, "out_chans_first_conv": 16, } subnet = Tiramisu it_net_params = { "num_iter": 1, "lam": 0.0, "lam_learnable": False, "final_dc": False, "resnet_factor": 1.0, "operator": OpA, "inverter": OpA.inv, } # ----- training configuration ----- mseloss = torch.nn.MSELoss(reduction="sum") train_phases = 1 train_params = { "num_epochs": [19], "batch_size": [10], "loss_func": loss_func, "save_path": [ os.path.join( config.RESULTS_PATH, "Radon_Tiramisu_jitter_v6_" "train_phase_{}".format((i + 1) % (train_phases + 1)), ) for i in range(train_phases + 1) ], "save_epochs": 1, "optimizer": torch.optim.Adam, "optimizer_params": [{"lr": 8e-5, "eps": 2e-4, "weight_decay": 5e-4}], "scheduler": torch.optim.lr_scheduler.StepLR, "scheduler_params": {"step_size": 1, "gamma": 1.0}, "acc_steps": [1], "train_transform": torchvision.transforms.Compose( [SimulateMeasurements(OpA), Jitter(5e2, 0.0, 1.0)] ), "val_transform": torchvision.transforms.Compose( [SimulateMeasurements(OpA)], ), "train_loader_params": {"shuffle": True, "num_workers": 0}, "val_loader_params": {"shuffle": False, "num_workers": 0}, } # ----- data configuration ----- train_data_params = { "path": config.DATA_PATH, "device": device, } train_data = IPDataset val_data_params = { "path": config.DATA_PATH, "device": device, } val_data = IPDataset # ------ save hyperparameters ------- os.makedirs(train_params["save_path"][-1], exist_ok=True) with open( os.path.join(train_params["save_path"][-1], "hyperparameters.txt"), "w" ) as file: for key, value in subnet_params.items(): file.write(key + ": " + str(value) + "\n") for key, value in it_net_params.items(): file.write(key + ": " + str(value) + "\n") for key, value in train_params.items(): file.write(key + ": " + str(value) + "\n") for key, value in train_data_params.items(): file.write(key + ": " + str(value) + "\n") for key, value in val_data_params.items(): file.write(key + ": " + str(value) + "\n") file.write("train_phases" + ": " + str(train_phases) + "\n") # ------ construct network and train ----- subnet_tmp = subnet(**subnet_params).to(device) it_net_tmp = IterativeNet( subnet_tmp, **{ "num_iter": 1, "lam": 0.0, "lam_learnable": False, "final_dc": False, "resnet_factor": 1.0, "operator": OpA, "inverter": OpA.inv, } ).to(device) it_net_tmp.load_state_dict( torch.load( "results/Radon_Tiramisu_jitter_v4_train_phase_1/model_weights.pt", map_location=torch.device(device), ) ) subnet = it_net_tmp.subnet it_net = IterativeNet(subnet, **it_net_params).to(device) train_data = train_data("train", **train_data_params) val_data = val_data("val", **val_data_params) for i in range(train_phases): train_params_cur = {} for key, value in train_params.items(): train_params_cur[key] = ( value[i] if isinstance(value, (tuple, list)) else value ) print("Phase {}:".format(i + 1)) for key, value in train_params_cur.items(): print(key + ": " + str(value)) it_net.train_on(train_data, val_data, **train_params_cur)
27.309677
75
0.617056
964933bf3abeb9eecd5bbbd430d2ba1f1f9daec5
142
py
Python
Python practice/Mit opencourceware(2.7)/quiz1_p2.py
chiranjeevbitp/Python27new
d366efee57857402bae16cabf1df94c657490750
[ "bzip2-1.0.6" ]
null
null
null
Python practice/Mit opencourceware(2.7)/quiz1_p2.py
chiranjeevbitp/Python27new
d366efee57857402bae16cabf1df94c657490750
[ "bzip2-1.0.6" ]
null
null
null
Python practice/Mit opencourceware(2.7)/quiz1_p2.py
chiranjeevbitp/Python27new
d366efee57857402bae16cabf1df94c657490750
[ "bzip2-1.0.6" ]
null
null
null
#import pdb T = (0.1, 0.1) x = 0.0 for i in range(len(T)): for j in T: x += i + j print x print i #pdb.set_trace()
14.2
24
0.464789
964a16c465623ad04aac69e828d235990e03190f
13,029
py
Python
invMLEnc_toy/main.py
Lupin1998/inv-ML
9f3db461911748292dff18024587538eb66d44bf
[ "MIT" ]
1
2021-12-14T09:16:17.000Z
2021-12-14T09:16:17.000Z
invMLEnc_toy/main.py
Lupin1998/inv-ML
9f3db461911748292dff18024587538eb66d44bf
[ "MIT" ]
null
null
null
invMLEnc_toy/main.py
Lupin1998/inv-ML
9f3db461911748292dff18024587538eb66d44bf
[ "MIT" ]
2
2021-12-14T09:10:00.000Z
2022-01-21T16:57:44.000Z
import os import numpy as np import random as rd import time import argparse import torch import torch.utils.data from torch import optim import dataset import gifploter from trainer.InvML_trainer import InvML_trainer from generator.samplegenerater import SampleIndexGenerater def PlotLatenSpace(model, batch_size, datas, labels, loss_caler, gif_ploter, device, path='./', name='no name', indicator=True, full=True, save_plot=True): """use to test the model and plot the latent space Arguments: model {torch model} -- a model need to train batch_size {int} -- batch size datas {tensor} -- the train data labels {label} -- the train label, for unsuprised method, it is only used in plot fig Keyword Arguments: path {str} -- the path to save the fig (default: {'./'}) name {str} -- the name of current fig (default: {'no name'}) indicator {bool} -- a flag to calculate the indicator (default: {True}) """ model.eval() train_loss_sum = [0, 0, 0, 0, 0, 0] num_train_sample = datas.shape[0] if full == True: for batch_idx in torch.arange(0, (num_train_sample-1)//batch_size + 1): start_number = (batch_idx * batch_size).int() end_number = torch.min(torch.tensor( [batch_idx*batch_size+batch_size, num_train_sample])).int() data = datas[start_number:end_number].float() label = labels[start_number:end_number] data = data.to(device) label = label.to(device) # train info train_info = model(data) loss_dict = loss_caler.CalLosses(train_info) if type(train_info) == type(dict()): train_info = train_info['output'] for i, k in enumerate(list(loss_dict.keys())): train_loss_sum[i] += loss_dict[k].item() if batch_idx == 0: latent_point = [] for train_info_item in train_info: latent_point.append(train_info_item.detach().cpu().numpy()) label_point = label.cpu().detach().numpy() else: for i, train_info_item in enumerate(train_info): latent_point_c = train_info_item.detach().cpu().numpy() latent_point[i] = np.concatenate( (latent_point[i], latent_point_c), axis=0) label_point = np.concatenate( (label_point, label.cpu().detach().numpy()), axis=0) gif_ploter.AddNewFig( latent_point, label_point, title_=path+'/'+name + '__AE_' + str(4)[:4] + '__MAE_'+ str(4)[:4], loss=train_loss_sum, save=save_plot ) else: data = datas.to(device) label = labels.to(device) eval_info = model(data) if type(eval_info) == type(dict()): eval_info = eval_info['output'] latent_point = [] for info_item in eval_info: latent_point.append(info_item.detach().cpu().numpy()) label_point = label.cpu().detach().numpy() gif_ploter.AddNewFig( latent_point, label_point, title_=path+'/'+'result', loss=None, save=save_plot ) def SaveParam(path, param): """save the current param in the path """ for v, k in param.items(): print('{v}:{k}'.format(v=v, k=k)) print('{v}:{k}'.format(v=v, k=k), file=open(path+'/param.txt', 'a')) def SetSeed(seed): """function used to set a random seed """ SEED = seed torch.manual_seed(SEED) torch.cuda.manual_seed(SEED) rd.seed(SEED) np.random.seed(SEED) if __name__ == '__main__': device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # 1. test encoder new_param = {} expName, testName = single_test(new_param, "encoder", device) # expName, testName = "Orth", 1 # decoder for 1 # expName, testName = "Orth2", 2 # decoder for 2 # expName, testName = "Orth3", 3 # decoder for 3 # expName, testName = "Orth4", 4 # decoder for 4 # test decoder based on encoder param new_param = {"ExpName": expName+"_Dec", "Test": testName} # 2. test decoder _,_ = single_test(new_param, "decoder", device)
34.468254
126
0.523985
964a55bd656809ac77520d02fe3eb7d52ed867d8
16,896
py
Python
backend/openweathermap.py
tangb/cleepmod-openweathermap
cbef1cad7af36ac6b801cb0df6651dd732b4a160
[ "MIT" ]
null
null
null
backend/openweathermap.py
tangb/cleepmod-openweathermap
cbef1cad7af36ac6b801cb0df6651dd732b4a160
[ "MIT" ]
null
null
null
backend/openweathermap.py
tangb/cleepmod-openweathermap
cbef1cad7af36ac6b801cb0df6651dd732b4a160
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import time import requests from cleep.exception import CommandError, MissingParameter from cleep.libs.internals.task import Task from cleep.core import CleepModule from cleep.common import CATEGORIES __all__ = ["Openweathermap"]
32
113
0.533381
964a8ebce3df5d896031c77dad18e3a15b609702
527
py
Python
tests/test_wps_dummy.py
f-PLT/emu
c0bb27d57afcaa361772ce99eaf11f706983b3b2
[ "Apache-2.0" ]
3
2015-11-10T10:08:07.000Z
2019-09-09T20:41:25.000Z
tests/test_wps_dummy.py
f-PLT/emu
c0bb27d57afcaa361772ce99eaf11f706983b3b2
[ "Apache-2.0" ]
76
2015-02-01T23:17:17.000Z
2021-12-20T14:17:59.000Z
tests/test_wps_dummy.py
f-PLT/emu
c0bb27d57afcaa361772ce99eaf11f706983b3b2
[ "Apache-2.0" ]
8
2016-10-13T16:44:02.000Z
2020-12-22T18:36:53.000Z
from pywps import Service from pywps.tests import assert_response_success from .common import client_for, get_output from emu.processes.wps_dummy import Dummy
31
68
0.705882
964ae4268e2f7a93ee8eacf634fa2376a1e04d95
476
py
Python
test/talker.py
cjds/rosgo
2a832421948707baca6413fe4394e28ed0c36d86
[ "Apache-2.0" ]
148
2016-02-16T18:29:34.000Z
2022-03-18T13:13:46.000Z
test/talker.py
cjds/rosgo
2a832421948707baca6413fe4394e28ed0c36d86
[ "Apache-2.0" ]
24
2018-12-21T19:32:15.000Z
2021-01-20T00:27:51.000Z
test/talker.py
cjds/rosgo
2a832421948707baca6413fe4394e28ed0c36d86
[ "Apache-2.0" ]
45
2015-11-16T06:31:10.000Z
2022-03-28T12:46:44.000Z
#!/usr/bin/env python import rospy from std_msgs.msg import String if __name__ == '__main__': try: talker() except rospy.ROSInterruptException: pass
22.666667
73
0.628151
964b60ee1051cb3579b95c9af76b42037448ddeb
9,365
py
Python
point_to_box/model.py
BavarianToolbox/point_to_box
6769739361410499596f53a60704cbedae56bd81
[ "Apache-2.0" ]
null
null
null
point_to_box/model.py
BavarianToolbox/point_to_box
6769739361410499596f53a60704cbedae56bd81
[ "Apache-2.0" ]
null
null
null
point_to_box/model.py
BavarianToolbox/point_to_box
6769739361410499596f53a60704cbedae56bd81
[ "Apache-2.0" ]
null
null
null
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/02_model.ipynb (unless otherwise specified). __all__ = ['EfficientLoc', 'CIoU'] # Cell #export from efficientnet_pytorch import EfficientNet import copy import time import math import torch import torch.optim as opt from torch.utils.data import DataLoader from torchvision import transforms # Cell # Cell
33.091873
112
0.553017
964d531f50577c7580159804463196dbab58e21c
7,643
py
Python
Receptive_Field_PyNN/2rtna_connected_to_4ReceptiveFields/anmy_TDXY.py
mahmoud-a-ali/Thesis_sample_codes
02a912dd012291b00c89db195b4cba2ebb4d35fe
[ "MIT" ]
null
null
null
Receptive_Field_PyNN/2rtna_connected_to_4ReceptiveFields/anmy_TDXY.py
mahmoud-a-ali/Thesis_sample_codes
02a912dd012291b00c89db195b4cba2ebb4d35fe
[ "MIT" ]
null
null
null
Receptive_Field_PyNN/2rtna_connected_to_4ReceptiveFields/anmy_TDXY.py
mahmoud-a-ali/Thesis_sample_codes
02a912dd012291b00c89db195b4cba2ebb4d35fe
[ "MIT" ]
null
null
null
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Jun 2 13:09:55 2018 @author: mali """ #import time import pickle import pyNN.utility.plotting as plot import matplotlib.pyplot as plt import comn_conversion as cnvrt import prnt_plt_anmy as ppanmy # file and folder names ======================================================= fldr_name = 'rslts/icub64x64/' pickle_filename = 'TDXY.pickle' file_pth = cnvrt.read_flenfldr_ncrntpth(fldr_name, pickle_filename ) with open(file_pth , 'rb') as tdxy: TDXY = pickle.load( tdxy ) print '### lenght of TDXY : {}'.format( len(TDXY) ) # 2+ 2*n_orn ) pop = TDXY[0] t_ist = 1040 print 'check pop: L_rtna_TDXY' print '### T : {}'.format(pop[0][t_ist]) # dimension 4 x t_stp x depend print '### 1D : {}'.format(pop[1][t_ist]) # dimension 4 x t_stp x depend print '### X : {}'.format(pop[2][t_ist]) # dimension 4 x t_stp x depend print '### Y : {}'.format(pop[3][t_ist]) # dimension 4 x t_stp x depend print pop[0] print pop[1] #required variables============================================================ n_rtna = 2 # till now should be two n_orn = 4 rtna_w = 64 rtna_h = 64 krnl_sz = 5 rf_w = rtna_w - krnl_sz +1 rf_h = rtna_h - krnl_sz +1 subplt_rws = n_rtna subplt_cls = n_orn+1 ########### to make animation fast as scale now in micro second ############### #first to scale be divide over 10 or 100 ====================================== T=TDXY[0][0] t10u=T [0:T[-1]:100] #print '### t_10u : {}'.format(t10u) # second find all times has spikes any one of the rtna or rf ================== t_spks=[] for pop in range ( len(TDXY) ): for inst in range( len(TDXY[pop][0]) ): if TDXY[pop][2][inst]!=[] : t_spks.append( TDXY[pop][0][inst] ) print pop, TDXY[pop][0][inst] t_spks.sort() for each in t_spks: count = t_spks.count(each) if count > 1: t_spks.remove(each) print 't_spks : {}'.format( t_spks ) #animate the rtna_rf ========================================================= #print 'abplt_rw, sbplt_cl, rtna_w, rtna_h, rf_w, rf_h: {}, {}, {}, {}, {}, {} '.format(subplt_rws, subplt_cls, rtna_w, rtna_h, rf_w, rf_h) fig, axs = plt.subplots(subplt_rws, subplt_cls, sharex=False, sharey=False) #, figsize=(12,5)) axs = ppanmy.init_fig_mxn_sbplt_wxh_res (fig, axs, rtna_h, rtna_w, rf_w, rf_h, subplt_rws, subplt_cls) plt.grid(True) plt.show(block=False) plt.pause(.01) #for i in t_spks: #t10u: # axs = ppanmy.init_fig_mxn_sbplt_wxh_res (fig, axs, rtna_h, rtna_w, rf_w, rf_h, subplt_rws, subplt_cls) # plt.suptitle('rtna_rf_orn_3: t= {} usec'.format( i ) ) # if subplt_rws==1: # axs[0].scatter( TDXY[0][2][i], TDXY[0][3][i] ) # for col in range (subplt_cls): # axs[col].scatter( TDXY[col+1][2][i], TDXY[col+1][3][i] ) ## plt.savefig( 'fgrs/anmy_1/{}_t{}.png'.format(vrjn, i) ) # plt.show(block=False) # plt.pause(2) # for col in range(subplt_cls): # axs[col].cla() # # elif subplt_rws==2: # for col in range (subplt_cls): # axs[0][0].scatter( TDXY[0][2][i], TDXY[0][3][i] ) # axs[1][0].scatter( TDXY[1][2][i], TDXY[1][3][i] ) # for col in range(1,n_orn+1): # row=0 # axs[row][col].scatter( TDXY[col+1][2][i], TDXY[col+1][3][i] ) # for col in range(1,n_orn): # row=1 # axs[row][col].scatter( TDXY[n_orn+1+col][2][i], TDXY[n_orn+1+col][3][i] ) ## plt.savefig( 'fgrs/anmy_1/{}_t{}.png'.format(vrjn, i) ) # plt.show(block=False) # plt.pause(2) # for row in range(subplt_rws): # for col in range (subplt_cls): # axs[row][col].cla() # print '##### required variables: \n n_rtna={}, TDXY_len={}, rtna_w={}, rtna_h={}, krnl_sz={}, rf_w={} , rf_h={}'.format( n_rtna , len(TDXY), rtna_w, rtna_h, krnl_sz, rf_w , rf_h ) plt.show(block=False) last_t_spks=-310 for i in range( len(t_spks) ): #t10u: # plt.pause(2) if t_spks[i]-last_t_spks > 300: #clear if subplt_rws==2: for row in range(subplt_rws): for col in range (subplt_cls): axs[row][col].cla() elif subplt_rws==1: for col in range(subplt_cls): axs[col].cla() axs = ppanmy.init_fig_mxn_sbplt_wxh_res (fig, axs, rtna_h, rtna_w, rf_w, rf_h, subplt_rws, subplt_cls) plt.suptitle('rtna_rf_orn: t= {} usec'.format( t_spks[i] ) ) plt.pause(1.5) #-------------------------------------------------------------------------- if subplt_rws==1: axs[0].scatter( TDXY[0][2][t_spks[i]], TDXY[0][3][t_spks[i]] ) for col in range (subplt_cls): axs[col].scatter( TDXY[col+1][2][t_spks[i]], TDXY[col+1][3][t_spks[i]] ) # plt.savefig( 'fgrs/anmy_1/{}_t{}.png'.format(vrjn, i) ) elif subplt_rws==2: for col in range (subplt_cls): axs[0][0].scatter( TDXY[0][2][t_spks[i]], TDXY[0][3][t_spks[i]] ) axs[1][0].scatter( TDXY[1][2][t_spks[i]], TDXY[1][3][t_spks[i]] ) for col in range(1,n_orn+1): row=0 axs[row][col].scatter( TDXY[col+1][2][t_spks[i]], TDXY[col+1][3][t_spks[i]] ) for col in range(1,n_orn+1): row=1 axs[row][col].scatter( TDXY[n_orn+1+col][2][t_spks[i]], TDXY[n_orn+1+col][3][t_spks[i]] ) # plt.savefig( 'fgrs/anmy_1/{}_t{}.png'.format(vrjn, i) ) #-------------------------------------------------------------------------- plt.pause(.5) else: #==================================================================== #-------------------------------------------------------------------------- if subplt_rws==1: axs[0].scatter( TDXY[0][2][t_spks[i]], TDXY[0][3][t_spks[i]] ) for col in range (subplt_cls): axs[col].scatter( TDXY[col+1][2][t_spks[i]], TDXY[col+1][3][t_spks[i]] ) # plt.savefig( 'fgrs/anmy_1/{}_t{}.png'.format(vrjn, i) ) elif subplt_rws==2: for col in range (subplt_cls): axs[0][0].scatter( TDXY[0][2][t_spks[i]], TDXY[0][3][t_spks[i]] ) axs[1][0].scatter( TDXY[1][2][t_spks[i]], TDXY[1][3][t_spks[i]] ) for col in range(1,n_orn+1): row=0 axs[row][col].scatter( TDXY[col+1][2][t_spks[i]], TDXY[col+1][3][t_spks[i]] ) for col in range(1,n_orn+1): row=1 axs[row][col].scatter( TDXY[n_orn+1+col][2][t_spks[i]], TDXY[n_orn+1+col][3][t_spks[i]] ) # plt.savefig( 'fgrs/anmy_1/{}_t{}.png'.format(vrjn, i) ) #-------------------------------------------------------------------------- plt.pause(.5) last_t_spks = t_spks[i] # suing builtin animation function =========================================== #strt_tm = TDXY[0][0][0] #stop_tm = TDXY[0][0][-1] #print '\n### n_orn x n_rtna : {}x{}'.format(n_orn, n_rtna) #print '\n### strt_tm - stop_tm : {} - {}'.format(strt_tm, stop_tm) #ppanmy.anmy_rtna_rf_orn( TDXY, rtna_h, rtna_w, n_rtna, krnl_sz, strt_tm , stop_tm)
37.282927
180
0.483056
964d60906285ddfcdeb808da94455db7bd3067ea
5,998
py
Python
meAdota/settings.py
guipeeix7/website
4081899060e69688314a5577ceab5c7b840e7b7f
[ "MIT" ]
6
2020-10-19T23:13:07.000Z
2020-12-02T19:08:32.000Z
meAdota/settings.py
guipeeix7/website
4081899060e69688314a5577ceab5c7b840e7b7f
[ "MIT" ]
69
2020-10-23T03:52:47.000Z
2020-12-04T01:12:49.000Z
meAdota/settings.py
guipeeix7/website
4081899060e69688314a5577ceab5c7b840e7b7f
[ "MIT" ]
1
2020-12-08T22:10:08.000Z
2020-12-08T22:10:08.000Z
""" Django settings for meAdota project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Load dotenv import os from dotenv import load_dotenv load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] STATIC_ROOT = '' STATIC_URL = '/static/' STATICFILES_DIRS = ('static',) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'django_countries', 'cpf_field', 'django_filters', # AllAuth [custom providers] 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.twitter', #my apps 'users', 'pets', 'crispy_forms', ] CRISPY_TEMPLATE_PACK = 'bootstrap4' SITE_ID = 1 AUTH_USER_MODEL = 'users.User' #verify email EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' #check email on console ACCOUNT_EMAIL_VERIFICATION = True ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_LOGOUT_ON_GET = True MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'meAdota.urls' ACCOUNT_FORMS = { 'login': 'users.forms.MyLoginForm', # 'signup': 'allauth.account.forms.SignupForm', 'signup': 'users.forms.MyCustomSignupForm', 'add_email': 'allauth.account.forms.AddEmailForm', 'change_password': 'allauth.account.forms.ChangePasswordForm', 'set_password': 'allauth.account.forms.SetPasswordForm', 'reset_password': 'allauth.account.forms.ResetPasswordForm', 'reset_password_from_key': 'allauth.account.forms.ResetPasswordKeyForm', 'disconnect': 'allauth.socialaccount.forms.DisconnectForm', } SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'METHOD': 'oauth2', 'SDK_URL': '//connect.facebook.net/{locale}/sdk.js', 'SCOPE': ['email', 'public_profile'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'INIT_PARAMS': {'cookie': True}, 'FIELDS': [ 'id', 'first_name', 'last_name', 'middle_name', 'name', 'name_format', 'picture', 'short_name' ], 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': lambda request: 'en_US', 'VERIFIED_EMAIL': False, 'VERSION': 'v7.0', }, 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } LOGIN_REDIRECT_URL ='/' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [str(BASE_DIR / "templates"), str(BASE_DIR / "templates/account")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] WSGI_APPLICATION = 'meAdota.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.getenv("DATABASE_NAME"), 'USER': os.getenv("DATABASE_USER"), 'PASSWORD': os.getenv("DATABASE_PASSWORD"), 'HOST': os.getenv("DATABASE_HOST"), 'PORT': os.getenv("DATABASE_PORT"), } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
27.140271
91
0.672391
964eca76f4c35f59907bf26e2512971b1aa50b0f
1,098
py
Python
Machine Learning/Regression/reg.py
brett-harvey/Brett-s-AI-Library
43f9bfd5eca92b9e28c6d4532afb943d03d80b67
[ "MIT" ]
null
null
null
Machine Learning/Regression/reg.py
brett-harvey/Brett-s-AI-Library
43f9bfd5eca92b9e28c6d4532afb943d03d80b67
[ "MIT" ]
null
null
null
Machine Learning/Regression/reg.py
brett-harvey/Brett-s-AI-Library
43f9bfd5eca92b9e28c6d4532afb943d03d80b67
[ "MIT" ]
null
null
null
from sklearn import preprocessing, svm from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn import cross_validation import pandas as pd import numpy as np import quandl import math df = quandl.get('WIKI/GOOGL') df = df[['Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume']] df['HL_PCT'] = (df['Adj. High'] - df['Adj. Low']) / df['Adj. Close'] * 100.0 df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) / df['Adj. Open'] * 100.0 df = df[['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj. Volume']] forecast_col = 'Adj. Close' df.fillna(-99999, inplace = True) forecast_out = int(math.ceil(0.01 * len(df))) print(forecast_out) df['label'] = df[forecast_col].shift(-forecast_out) df.dropna(inplace = True) X = np.array(df.drop(['label'],1)) y = np.array(df['label']) X = preprocessing.scale(X) y = np.array(df['label']) X_train, X_test, y_train, y_test = cross_validation.train_test_split(X,y, test_size = 0.2) clf = LinearRegression() clf.fit(X_train, y_train) accuracy = clf.score(X_test,y_test) print(accuracy)
29.675676
90
0.6949
964ed654a2da39f4913b8a0e948783cdb15246e1
12,126
py
Python
src/app.py
tatianamaia/Corona
d944395d8b7b7a740b57e9bb7895f0835bc63d10
[ "MIT" ]
null
null
null
src/app.py
tatianamaia/Corona
d944395d8b7b7a740b57e9bb7895f0835bc63d10
[ "MIT" ]
null
null
null
src/app.py
tatianamaia/Corona
d944395d8b7b7a740b57e9bb7895f0835bc63d10
[ "MIT" ]
null
null
null
import datetime import os import yaml import numpy as np import pandas as pd import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output from scipy.integrate import solve_ivp from scipy.optimize import minimize import plotly.graph_objs as go ENV_FILE = '../env.yaml' with open(ENV_FILE) as f: params = yaml.load(f, Loader=yaml.FullLoader) # Initialisation des chemins vers les fichiers ROOT_DIR = os.path.dirname(os.path.abspath(ENV_FILE)) DATA_FILE = os.path.join(ROOT_DIR, params['directories']['processed'], params['files']['all_data']) #Lecture du fihcier de donnes epidemie_df = (pd.read_csv(DATA_FILE, parse_dates=['Last Update']) .assign(day=lambda _df:_df['Last Update'].dt.date) .drop_duplicates(subset=['Country/Region', 'Province/State', 'day']) [lambda df: df['day'] <= datetime.date(2020,3,20)] ) # replacing Mainland china with just China cases = ['Confirmed', 'Deaths', 'Recovered'] # After 14/03/2020 the names of the countries are quite different epidemie_df['Country/Region'] = epidemie_df['Country/Region'].replace('Mainland China', 'China') # filling missing values epidemie_df[['Province/State']] = epidemie_df[['Province/State']].fillna('') epidemie_df[cases] = epidemie_df[cases].fillna(0) countries=[{'label':c, 'value': c} for c in epidemie_df['Country/Region'].unique()] app = dash.Dash('C0VID-19 Explorer') app.layout = html.Div([ html.H1(['C0VID-19 Explorer'], style={'textAlign': 'center', 'color': 'navy', 'font-weight': 'bold'}), dcc.Tabs([ dcc.Tab(label='Time', children=[ dcc.Markdown(""" Select a country: """,style={'textAlign': 'left', 'color': 'navy', 'font-weight': 'bold'} ), html.Div([ dcc.Dropdown( id='country', options=countries, placeholder="Select a country...", ) ]), html.Div([ dcc.Markdown("""You can select a second country:""", style={'textAlign': 'left', 'color': 'navy', 'font-weight': 'bold'} ), dcc.Dropdown( id='country2', options=countries, placeholder="Select a country...", ) ]), html.Div([dcc.Markdown("""Cases: """, style={'textAlign': 'left', 'color': 'navy', 'font-weight': 'bold'} ), dcc.RadioItems( id='variable', options=[ {'label':'Confirmed', 'value': 'Confirmed'}, {'label':'Deaths', 'value': 'Deaths'}, {'label':'Recovered', 'value': 'Recovered'} ], value='Confirmed', labelStyle={'display': 'inline-block'} ) ]), html.Div([ dcc.Graph(id='graph1') ]) ]), dcc.Tab(label='Map', children=[ #html.H6(['COVID-19 in numbers:']), dcc.Markdown(""" **COVID-19** This is a graph that shows the evolution of the COVID-19 around the world ** Cases:** """, style={'textAlign': 'left', 'color': 'navy', 'font-weight': 'bold'} ), dcc.Dropdown(id="value-selected", value='Confirmed', options=[{'label': "Deaths ", 'value': 'Deaths'}, {'label': "Confirmed", 'value': 'Confirmed'}, {'label': "Recovered", 'value': 'Recovered'}], placeholder="Select a country...", style={"display": "inline-block", "margin-left": "auto", "margin-right": "auto", "width": "70%"}, className="six columns"), dcc.Graph(id='map1'), dcc.Slider( id='map_day', min=0, max=(epidemie_df['day'].max() - epidemie_df['day'].min()).days, value=0, marks={i:str(i) for i, date in enumerate(epidemie_df['day'].unique())} ) ]), dcc.Tab(label='SIR Model', children=[ dcc.Markdown(""" **SIR model** S(Susceptible)I(Infectious)R(Recovered) is a model describing the dynamics of infectious disease. The model divides the population into compartments. Each compartment is expected to have the same characteristics. SIR represents the three compartments segmented by the model. **Select a country:** """, style={'textAlign': 'left', 'color': 'navy'}), html.Div([ dcc.Dropdown( id='Country', value='Portugal', options=countries), ]), dcc.Markdown("""Select:""", style={'textAlign': 'left', 'color': 'navy'}), dcc.Dropdown(id='cases', options=[ {'label': 'Confirmed', 'value': 'Confirmed'}, {'label': 'Deaths', 'value': 'Deaths'}, {'label': 'Recovered', 'value': 'Recovered'}], value=['Confirmed','Deaths','Recovered'], multi=True), dcc.Markdown(""" **Select your paramaters:** """, style={'textAlign': 'left', 'color': 'navy'}), html.Label( style={'textAlign': 'left', 'color': 'navy', "width": "20%"}), html.Div([ dcc.Markdown(""" Beta: """, style={'textAlign': 'left', 'color': 'navy'}), dcc.Input( id='input-beta', type ='number', placeholder='Input Beta', min =-50, max =100, step =0.01, value=0.45 ) ]), html.Div([ dcc.Markdown(""" Gamma: """, style={'textAlign': 'left', 'color': 'navy'}), dcc.Input( id='input-gamma', type ='number', placeholder='Input Gamma', min =-50, max =100, step =0.01, value=0.55 ) ]), html.Div([ dcc.Markdown(""" Population: """, style={'textAlign': 'left', 'color': 'navy'}), dcc.Input( id='input-pop',placeholder='Population', type ='number', min =1000, max =1000000000000000, step =1000, value=1000, ) ]), html.Div([ dcc.RadioItems(id='variable2', options=[ {'label':'Optimize','value':'optimize'}], value='Confirmed', labelStyle={'display':'inline-block','color': 'navy', "width": "20%"}) ]), html.Div([ dcc.Graph(id='graph2') ]), ]) ]), ]) if __name__ == '__main__': app.run_server(debug=True)
34.547009
289
0.455303
964f51bb97bc51b17e213093a0a26eca6712c8ec
1,014
py
Python
tests/io/test_kepseismic.py
jorgemarpa/lightkurve
86320a67eabb3a93f60e9faff0447e4b235bccf2
[ "MIT" ]
235
2018-01-22T01:22:10.000Z
2021-02-02T04:57:26.000Z
tests/io/test_kepseismic.py
jorgemarpa/lightkurve
86320a67eabb3a93f60e9faff0447e4b235bccf2
[ "MIT" ]
847
2018-01-22T05:49:16.000Z
2021-02-10T17:05:19.000Z
tests/io/test_kepseismic.py
jorgemarpa/lightkurve
86320a67eabb3a93f60e9faff0447e4b235bccf2
[ "MIT" ]
121
2018-01-22T01:11:19.000Z
2021-01-26T21:07:07.000Z
import pytest from astropy.io import fits import numpy as np from lightkurve.io.kepseismic import read_kepseismic_lightcurve from lightkurve.io.detect import detect_filetype
32.709677
155
0.757396
964fab6dbeeb71e25e526001be717823ea172dc3
32
py
Python
backend/appengine/routes/gallerys/model.py
SamaraCardoso27/eMakeup
02c3099aca85b5f54214c3a32590e80eb61621e7
[ "MIT" ]
null
null
null
backend/appengine/routes/gallerys/model.py
SamaraCardoso27/eMakeup
02c3099aca85b5f54214c3a32590e80eb61621e7
[ "MIT" ]
null
null
null
backend/appengine/routes/gallerys/model.py
SamaraCardoso27/eMakeup
02c3099aca85b5f54214c3a32590e80eb61621e7
[ "MIT" ]
null
null
null
__author__ = 'Samara Cardoso'
8
29
0.71875
965034c03fdf2183dfe02406617dfa08e3bd353a
1,153
py
Python
recipes/Python/223585_Stable_deep_sorting_dottedindexed_attributes/recipe-223585.py
tdiprima/code
61a74f5f93da087d27c70b2efe779ac6bd2a3b4f
[ "MIT" ]
2,023
2017-07-29T09:34:46.000Z
2022-03-24T08:00:45.000Z
recipes/Python/223585_Stable_deep_sorting_dottedindexed_attributes/recipe-223585.py
unhacker/code
73b09edc1b9850c557a79296655f140ce5e853db
[ "MIT" ]
32
2017-09-02T17:20:08.000Z
2022-02-11T17:49:37.000Z
recipes/Python/223585_Stable_deep_sorting_dottedindexed_attributes/recipe-223585.py
unhacker/code
73b09edc1b9850c557a79296655f140ce5e853db
[ "MIT" ]
780
2017-07-28T19:23:28.000Z
2022-03-25T20:39:41.000Z
# # begin test code # from random import randint if __name__ == '__main__': aList = [c(1), c(2), c(3), c(4), c(5), c(6)] print '\n...to be sorted by obj.y.y[1].x[1]' print ' then, as needed, by obj.y.x' print ' then, as needed, by obj.x\n\n ', for i in range(6): print '(' + str(aList[i].y.y[1].x[1]) + ',', print str(aList[i].y.x) + ',', print str(aList[i].x) + ') ', sortByAttrs(aList, ['y.y[1].x[1]', 'y.x', 'x']) print '\n\n...now sorted by listed attributes.\n\n ', for i in range(6): print '(' + str(aList[i].y.y[1].x[1]) + ',', print str(aList[i].y.x) + ',', print str(aList[i].x) + ') ', print # # end test code #
18.015625
58
0.542064
9650401ec27713e595c5dbc7faa0b1080d66e16e
1,710
py
Python
spirit/topic/forms.py
ImaginaryLandscape/Spirit
58b563c1b2290a95219257045afaa4f08ac94cbf
[ "MIT" ]
974
2015-01-02T12:56:00.000Z
2022-03-24T00:01:54.000Z
spirit/topic/forms.py
ImaginaryLandscape/Spirit
58b563c1b2290a95219257045afaa4f08ac94cbf
[ "MIT" ]
247
2015-01-07T02:59:26.000Z
2022-02-23T08:27:57.000Z
spirit/topic/forms.py
ImaginaryLandscape/Spirit
58b563c1b2290a95219257045afaa4f08ac94cbf
[ "MIT" ]
366
2015-01-08T10:22:25.000Z
2022-02-21T12:58:31.000Z
# -*- coding: utf-8 -*- from django import forms from django.utils.translation import gettext_lazy as _ from django.utils.encoding import smart_bytes from django.utils import timezone from ..core import utils from ..core.utils.forms import NestedModelChoiceField from ..category.models import Category from .models import Topic
29.482759
81
0.64269
965076565be0243a0d0b837e3affc60f4cce7858
7,931
py
Python
OST_helper/parameter.py
HomeletW/OST
5e359d00a547af194a2a1a2591a53c93d8f40b84
[ "MIT" ]
1
2020-07-31T16:43:13.000Z
2020-07-31T16:43:13.000Z
OST_helper/parameter.py
HomeletW/OST
5e359d00a547af194a2a1a2591a53c93d8f40b84
[ "MIT" ]
null
null
null
OST_helper/parameter.py
HomeletW/OST
5e359d00a547af194a2a1a2591a53c93d8f40b84
[ "MIT" ]
null
null
null
# constant import json import logging import os import platform import subprocess from datetime import date from os.path import exists, expanduser, isdir, isfile, join, abspath, dirname from PIL import Image logging.basicConfig( style="{", format="{threadName:<10s} <{levelname:<7s}> [{asctime:<15s}] {message}", level=logging.DEBUG ) # paths CCCL_PATH = None SETTING_PATH = None APP_LOGO = None OST_SAMPLE = None DEFAULT_OST_PATH = None TFONT = None DEFAULT_COORDINATES_PATH = None # os DEVICE_OS = platform.system() # ost sample OST_SAMPLE_IMAGE = None # today today = None PRODUCTION_SUCCESS = 0 PRODUCTION_FILE_EXISTS = 1 PRODUCTION_FILE_NOT_RECOGNIZED = 2 update_today() DEFAULT_DIR = get_desktop_directory() # "course_code": ["course_title", "course_level", "credit", "compulsory"] default_common_course_code_library = { } default_setting = { "draw_ost_template": True, "smart_fill": True, "train": True, "json_dir": DEFAULT_DIR, "img_dir": DEFAULT_DIR, "last_session": None, } default_ost = { "OST_date_of_issue": today, "name": ["", ""], "OEN": "", "student_number": "", "gender": "", "date_of_birth": ["", "", ""], "name_of_district_school_board": "Toronto Private Inspected", "district_school_board_number": "", "name_of_school": "", "school_number": "", "date_of_entry": ["", "", ""], "community_involvement_flag": False, "provincial_secondary_school_literacy_requirement_flag": False, "specialized_program": "", "diploma_or_certificate": "Ontario Secondary School Diploma", "diploma_or_certificate_date_of_issue": ["", ""], "authorization": "", "course_list": [], "course_font_size": 50, "course_spacing": 5, } default_coordinates = { "Size": (3300, 2532), "Offset": (0, 0), # (x, y, width, height) "OST_DateOfIssue": (2301, 73, 532, 85, 55), "Page_1": (2826, 73, 183, 85, 50), "Page_2": (3046, 73, 183, 85, 50), "Surname": (85, 204, 645, 94, 50), "GivenName": (730, 204, 772, 94, 50), "OEN": (1502, 204, 537, 94, 50), "StudentNumber": (2039, 204, 538, 94, 50), "Gender": (2577, 204, 136, 94, 50), "DateOfBirth_Y": (2713, 228, 202, 70, 40), "DateOfBirth_M": (2915, 228, 202, 70, 40), "DateOfBirth_D": (3117, 228, 147, 70, 40), "NameOfDSB": (85, 336, 1023, 100, 50), "NumberOfDSB": (1108, 338, 397, 100, 50), "NameOfSchool": (1505, 338, 807, 100, 50), "NumberOfSchool": (2311, 338, 402, 100, 50), "DateOfEntry_Y": (2713, 368, 202, 70, 40), "DateOfEntry_M": (2915, 368, 202, 70, 40), "DateOfEntry_D": (3117, 368, 147, 70, 40), # (x, y, width, height) "Course": (35, 564, 3230, 1419), # (x_offset, width) "Course_date_offset": (35 - 35, 268), "Course_level_offset": (306 - 35, 183), "Course_title_offset": (491 - 35, 1637), "Course_code_offset": (2131 - 35, 244), "Course_percentage_offset": (2378 - 35, 175), "Course_credit_offset": (2563 - 35, 183), "Course_compulsory_offset": (2748 - 35, 207), "Course_note_offset": (2965 - 35, 299), "SummaryOfCredit": (2562, 1992, 184, 69, 55), "SummaryOfCompulsory": (2748, 1992, 207, 69, 55), "CommunityInvolvement_True": (75, 2125), "CommunityInvolvement_False": (385, 2125), "ProvincialSecondarySchoolLiteracy_True": (623, 2125), "ProvincialSecondarySchoolLiteracy_False": (1173, 2125), "SpecializedProgram": (1436, 2104, 1828, 96, 40), "DiplomaOrCertificate": (77, 2240, 1622, 90, 40), "DiplomaOrCertificate_DateOfIssue_Y": (1702, 2273, 180, 57, 40), "DiplomaOrCertificate_DateOfIssue_M": (1885, 2273, 180, 57, 40), "Authorization": (2070, 2240, 1148, 90, 40), } COMMON_COURSE_CODE_LIBRARY = None SETTING = None DEFAULT_OST_INFO = None COORDINATES = None
30.980469
80
0.651998
96519d3044209db1a7fd83988e9afafa3678e598
398
py
Python
examples/compat/ggplot_point.py
azjps/bokeh
13375db53d4c60216f3bcf5aacccb081cf19450a
[ "BSD-3-Clause" ]
1
2017-04-27T09:15:48.000Z
2017-04-27T09:15:48.000Z
app/static/libs/bokeh/examples/compat/ggplot_point.py
TBxy/bokeh_start_app
755494f6bc60e92ce17022bbd7f707a39132cbd0
[ "MIT" ]
null
null
null
app/static/libs/bokeh/examples/compat/ggplot_point.py
TBxy/bokeh_start_app
755494f6bc60e92ce17022bbd7f707a39132cbd0
[ "MIT" ]
1
2021-09-09T03:33:04.000Z
2021-09-09T03:33:04.000Z
from ggplot import aes, geom_point, ggplot, mtcars import matplotlib.pyplot as plt from pandas import DataFrame from bokeh import mpl from bokeh.plotting import output_file, show g = ggplot(mtcars, aes(x='wt', y='mpg', color='qsec')) + geom_point() g.make() plt.title("Point ggplot-based plot in Bokeh.") output_file("ggplot_point.html", title="ggplot_point.py example") show(mpl.to_bokeh())
23.411765
69
0.751256
965346317a700c60ccb16c29a2836bf7e207f10e
14,194
py
Python
src/train_tune.py
vanang/korquad-challenge
c5df887aaa7f6b68edb5d46ad12d42097132df46
[ "Apache-2.0" ]
null
null
null
src/train_tune.py
vanang/korquad-challenge
c5df887aaa7f6b68edb5d46ad12d42097132df46
[ "Apache-2.0" ]
null
null
null
src/train_tune.py
vanang/korquad-challenge
c5df887aaa7f6b68edb5d46ad12d42097132df46
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # coding: utf-8 # In[1]: from __future__ import absolute_import, division, print_function import argparse import logging import os import random import sys from io import open import numpy as np import torch import json from torch.utils.data import (DataLoader, SequentialSampler, RandomSampler, TensorDataset) from tqdm import tqdm, trange import ray from ray import tune from ray.tune.schedulers import HyperBandScheduler from models.modeling_bert import QuestionAnswering, Config from utils.optimization import AdamW, WarmupLinearSchedule from utils.tokenization import BertTokenizer from utils.korquad_utils import (read_squad_examples, convert_examples_to_features, RawResult, write_predictions) from debug.evaluate_korquad import evaluate as korquad_eval if sys.version_info[0] == 2: import cPickle as pickle else: import pickle # In[2]: logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO) logger = logging.getLogger(__name__) # In[3]: # In[4]: from ray import tune from ray.tune import track from ray.tune.schedulers import HyperBandScheduler from ray.tune.suggest.bayesopt import BayesOptSearch ray.shutdown() ray.init(webui_host='127.0.0.1') # In[5]: search_space = { "max_seq_length": 512, "doc_stride": 128, "max_query_length": tune.sample_from(lambda _: int(np.random.uniform(50, 100))), #tune.uniform(50, 100), "train_batch_size": 32, "learning_rate": tune.loguniform(5e-4, 5e-7, 10), "num_train_epochs": tune.grid_search([4, 8, 12, 16]), "max_grad_norm": 1.0, "adam_epsilon": 1e-6, "warmup_proportion": 0.1, "n_best_size": tune.sample_from(lambda _: int(np.random.uniform(50, 100))), #tune.uniform(50, 100), "max_answer_length": tune.sample_from(lambda _: int(np.random.uniform(12, 25))), #tune.uniform(12, 25), "seed": tune.sample_from(lambda _: int(np.random.uniform(1e+6, 1e+8))) } # In[ ]: # In[ ]: def evaluate(predict_file, batch_size, device, output_dir, n_best_size, max_answer_length, model, eval_examples, eval_features): """ Eval """ all_input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long) all_input_mask = torch.tensor([f.input_mask for f in eval_features], dtype=torch.long) all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long) all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long) dataset = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_example_index) sampler = SequentialSampler(dataset) dataloader = DataLoader(dataset, sampler=sampler, batch_size=batch_size) logger.info("***** Evaluating *****") logger.info(" Num features = %d", len(dataset)) logger.info(" Batch size = %d", batch_size) model.eval() all_results = [] # set_seed(args) # Added here for reproductibility (even between python 2 and 3) logger.info("Start evaluating!") for input_ids, input_mask, segment_ids, example_indices in tqdm(dataloader, desc="Evaluating"): input_ids = input_ids.to(device) input_mask = input_mask.to(device) segment_ids = segment_ids.to(device) with torch.no_grad(): batch_start_logits, batch_end_logits = model(input_ids, segment_ids, input_mask) for i, example_index in enumerate(example_indices): start_logits = batch_start_logits[i].detach().cpu().tolist() end_logits = batch_end_logits[i].detach().cpu().tolist() eval_feature = eval_features[example_index.item()] unique_id = int(eval_feature.unique_id) all_results.append(RawResult(unique_id=unique_id, start_logits=start_logits, end_logits=end_logits)) output_prediction_file = os.path.join(output_dir, "predictions.json") output_nbest_file = os.path.join(output_dir, "nbest_predictions.json") write_predictions(eval_examples, eval_features, all_results, n_best_size, max_answer_length, False, output_prediction_file, output_nbest_file, None, False, False, 0.0) expected_version = 'KorQuAD_v1.0' with open(predict_file) as dataset_file: dataset_json = json.load(dataset_file) read_version = "_".join(dataset_json['version'].split("_")[:-1]) if (read_version != expected_version): logger.info('Evaluation expects ' + expected_version + ', but got dataset with ' + read_version, file=sys.stderr) dataset = dataset_json['data'] with open(os.path.join(output_dir, "predictions.json")) as prediction_file: predictions = json.load(prediction_file) _eval = korquad_eval(dataset, predictions) logger.info(json.dumps(_eval)) return _eval # In[6]: # In[ ]: analysis = tune.run(train_korquad, config=search_space, scheduler=HyperBandScheduler(metric='f1', mode='max'), resources_per_trial={'gpu':1}) # In[ ]: dfs = analysis.trial_dataframes # In[ ]: # ax = None # for d in dfs.values(): # ax = d.mean_loss.plot(ax=ax, legend=True) # ax.set_xlabel("Epochs") # ax.set_ylabel("Mean Loss")
38.994505
193
0.659222
9655150c478e5c7edceea8519f955d5cbf7c2792
3,604
py
Python
BuyandBye_project/users/forms.py
sthasam2/BuyandBye
07a998f289f9ae87b234cd6ca653a4fdb2765b95
[ "MIT" ]
1
2019-12-26T16:52:10.000Z
2019-12-26T16:52:10.000Z
BuyandBye_project/users/forms.py
sthasam2/buyandbye
07a998f289f9ae87b234cd6ca653a4fdb2765b95
[ "MIT" ]
13
2021-06-02T03:51:06.000Z
2022-03-12T00:53:22.000Z
BuyandBye_project/users/forms.py
sthasam2/buyandbye
07a998f289f9ae87b234cd6ca653a4fdb2765b95
[ "MIT" ]
null
null
null
from datetime import date from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from phonenumber_field.formfields import PhoneNumberField from .models import Profile from .options import STATE_CHOICES, YEARS from .utils import AgeValidator
29.064516
92
0.59434
96565fe229818a242f95852b7feea959f0bbeb31
10,110
py
Python
kolab/tokibi/tokibi.py
oshiooshi/kolab
5f34614a995b2a31156b65e6eb9d512b9867540e
[ "MIT" ]
null
null
null
kolab/tokibi/tokibi.py
oshiooshi/kolab
5f34614a995b2a31156b65e6eb9d512b9867540e
[ "MIT" ]
null
null
null
kolab/tokibi/tokibi.py
oshiooshi/kolab
5f34614a995b2a31156b65e6eb9d512b9867540e
[ "MIT" ]
null
null
null
import sys import pegtree as pg from pegtree.visitor import ParseTreeVisitor import random # from . import verb import verb EMPTY = tuple() # OPTION = { 'Simple': False, # 'Block': False, # Expression <e> </e> 'EnglishFirst': False, # 'ShuffleSynonym': True, # 'MultipleSentence': False, # 'ShuffleOrder': True, # 'Verbose': True, # } # {|} # :[|] -> # : -> (synonyms) -> () # -> NSuffix() # [||] -> # <- BERT # A B A -> B -> A # randomize RandomIndex = 0 # def conjugate(w, mode=0, vpos=None): # suffix = '' # if mode & verb.CASE == verb.CASE: # if RandomIndex % 2 != 0: # mode = (mode & ~verb.CASE) | verb.NOUN # suffix = alt('||') # else: # suffix = '' # if mode & verb.THEN == verb.THEN: # if RandomIndex % 2 != 0: # mode = (mode & ~verb.THEN) | verb._I # suffix = '' # return verb.conjugate(w, mode, vpos) + suffix # NExpr def grouping(e): if isinstance(e, NPhrase): return '{' + repr(e) + '}' return repr(e) neko = NWord('||') print('@', neko, neko.generate()) wo = NSuffix(neko, '') print('@', wo, wo.generate()) ni = NSuffix(neko, '') print('@', ni, ni.generate()) ageru = NVerb('', 'V1', 0) e = NPhrase(NOrdered(ni, wo), ageru) print('@', e, e.generate()) ## ## NExpr () peg = pg.grammar('tokibi.pegtree') tokibi_parser = pg.generate(peg) tokibi_reader = TokibiReader() # t = parse('{|}') # print(t, t.generate()) # t = parse('{}') # print(t) # if __name__ == '__main__': # if len(sys.argv) > 1: # read_tsv(sys.argv[1]) # else: # e = parse('/{[|Puppy]}[|]') # print(e, e.generate()) # e2 = parse('[|]/[|]') # #e2, _ = parse('{A/B()//[]}') # e = parse('A') # e = e.apply({0: e2}) # print(e, e.generate()) # e = parse('A()') # e = e.apply({0: e2}) # print(e, e.generate())
24.128878
114
0.559149
96566f3a27305df43ef46e729f0d4af5e2007006
1,275
py
Python
kaggle_downloader/kaggle_downloader.py
lars-reimann/kaggle-downloader
583e68ee1c4860a153ae38f2a1cdba108ea8cb5a
[ "MIT" ]
null
null
null
kaggle_downloader/kaggle_downloader.py
lars-reimann/kaggle-downloader
583e68ee1c4860a153ae38f2a1cdba108ea8cb5a
[ "MIT" ]
3
2021-08-05T11:05:32.000Z
2022-03-01T13:05:18.000Z
kaggle_downloader/kaggle_downloader.py
lars-reimann/kaggle-downloader
583e68ee1c4860a153ae38f2a1cdba108ea8cb5a
[ "MIT" ]
null
null
null
from typing import Callable, Union from kaggle import KaggleApi from kaggle.models.kaggle_models_extended import Competition, Kernel
27.717391
69
0.614902
96578d44622fea775471eea152128045fac7dede
1,281
py
Python
trip/urls.py
tboonma/thairepose
89aff7836a29bfee58a633db10c19d5e1ce4475f
[ "MIT" ]
4
2021-11-07T05:50:41.000Z
2021-12-01T08:57:12.000Z
trip/urls.py
tboonma/thairepose
89aff7836a29bfee58a633db10c19d5e1ce4475f
[ "MIT" ]
111
2021-10-19T09:24:14.000Z
2021-11-28T18:02:21.000Z
trip/urls.py
tboonma/thairepose
89aff7836a29bfee58a633db10c19d5e1ce4475f
[ "MIT" ]
2
2021-11-28T06:37:03.000Z
2022-01-16T18:17:02.000Z
from django.urls import path from . import views app_name = 'trip' urlpatterns = [ path('', views.index, name='index'), path('tripblog/', views.AllTrip.as_view(), name="tripplan"), path('likereview/', views.like_comment_view, name="like_comment"), path('tripdetail/<int:pk>/', views.trip_detail, name="tripdetail"), path('addpost/', views.add_post, name="addpost"), path('likepost/', views.like_post, name="like_trip"), path('tripdetail/edit/<int:pk>', views.edit_post, name='editpost'), path('tripdetail/<int:pk>/remove', views.delete_post, name='deletepost'), path('category/<category>', views.CatsListView.as_view(), name='category'), path('addcomment/', views.post_comment, name="add_comment"), path('action/gettripqueries', views.get_trip_queries, name='get-trip-query'), # 127.0.0.1/domnfoironkwe_0394 path('place/<str:place_id>/', views.place_info, name='place-detail'), path('place/<str:place_id>/like', views.place_like, name='place-like'), path('place/<str:place_id>/dislike', views.place_dislike, name='place-dislike'), path('place/<str:place_id>/addreview', views.place_review, name='place-review'), path('place/<str:place_id>/removereview', views.place_remove_review, name='place-remove-review'), ]
53.375
101
0.698673
9657e65ccf97f075f8a25b19bf95a3ca2e2decf0
5,010
py
Python
tests/test_rpc.py
tzoiker/aio-pika
5a04853006310d2fbf458c449b0ea98427668fe8
[ "Apache-2.0" ]
null
null
null
tests/test_rpc.py
tzoiker/aio-pika
5a04853006310d2fbf458c449b0ea98427668fe8
[ "Apache-2.0" ]
null
null
null
tests/test_rpc.py
tzoiker/aio-pika
5a04853006310d2fbf458c449b0ea98427668fe8
[ "Apache-2.0" ]
null
null
null
import asyncio import logging import pytest from aio_pika import Message, connect_robust from aio_pika.exceptions import DeliveryError from aio_pika.patterns.rpc import RPC, log as rpc_logger from tests import AMQP_URL from tests.test_amqp import BaseTestCase pytestmark = pytest.mark.asyncio
28.146067
76
0.633533
96588284712f2b02b4c2431118e6f0abd22431a0
8,331
py
Python
tests/python/pants_test/base/test_cmd_line_spec_parser.py
dturner-tw/pants
3a04f2e46bf2b8fb0a7999c09e4ffdf9057ed33f
[ "Apache-2.0" ]
null
null
null
tests/python/pants_test/base/test_cmd_line_spec_parser.py
dturner-tw/pants
3a04f2e46bf2b8fb0a7999c09e4ffdf9057ed33f
[ "Apache-2.0" ]
null
null
null
tests/python/pants_test/base/test_cmd_line_spec_parser.py
dturner-tw/pants
3a04f2e46bf2b8fb0a7999c09e4ffdf9057ed33f
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re from pants.base.cmd_line_spec_parser import CmdLineSpecParser from pants.build_graph.address import Address from pants.build_graph.build_file_aliases import BuildFileAliases from pants.build_graph.target import Target from pants_test.base_test import BaseTest
42.723077
101
0.680471
965a2d366a9e0c3114e09f3517d25bed152a9d40
2,363
py
Python
pull_into_place/commands/run_additional_metrics.py
Kortemme-Lab/pull_into_place
0019a6cec2a6130ebbaa49d7ab67d4c840fbe33c
[ "MIT" ]
3
2018-05-31T18:46:46.000Z
2020-05-04T03:27:38.000Z
pull_into_place/commands/run_additional_metrics.py
Kortemme-Lab/pull_into_place
0019a6cec2a6130ebbaa49d7ab67d4c840fbe33c
[ "MIT" ]
14
2016-09-14T00:16:49.000Z
2018-04-11T03:04:21.000Z
pull_into_place/commands/run_additional_metrics.py
Kortemme-Lab/pull_into_place
0019a6cec2a6130ebbaa49d7ab67d4c840fbe33c
[ "MIT" ]
1
2017-11-27T07:35:56.000Z
2017-11-27T07:35:56.000Z
#!/usr/bin/env python2 """\ Run additional filters on a folder of pdbs and copy the results back into the original pdb. Usage: pull_into_place run_additional_metrics <directory> [options] Options: --max-runtime TIME [default: 12:00:00] The runtime limit for each design job. The default value is set pretty low so that the short queue is available by default. This should work fine more often than not, but you also shouldn't be surprised if you need to increase this. --max-memory MEM [default: 2G] The memory limit for each design job. --mkdir Make the directory corresponding to this step in the pipeline, but don't do anything else. This is useful if you want to create custom input files for just this step. --test-run Run on the short queue with a limited number of iterations. This option automatically clears old results. --clear Clear existing results before submitting new jobs. To use this class: 1. You need to initiate it with the directory where your pdb files to be rerun are. 2. You need to use the setters for the Rosetta executable and the metric. """ from klab import docopt, scripting, cluster from pull_into_place import pipeline, big_jobs
28.130952
77
0.66314
965a870632eb281fc73c846d9b482a54e2ad0de9
827
py
Python
setup.py
japherwocky/cl3ver
148242feb676cc675bbdf11ae39c3179b9a6ffe1
[ "MIT" ]
1
2017-04-01T00:15:38.000Z
2017-04-01T00:15:38.000Z
setup.py
japherwocky/cl3ver
148242feb676cc675bbdf11ae39c3179b9a6ffe1
[ "MIT" ]
null
null
null
setup.py
japherwocky/cl3ver
148242feb676cc675bbdf11ae39c3179b9a6ffe1
[ "MIT" ]
null
null
null
from distutils.core import setup setup( name = 'cl3ver', packages = ['cl3ver'], license = 'MIT', install_requires = ['requests'], version = '0.2', description = 'A python 3 wrapper for the cleverbot.com API', author = 'Japhy Bartlett', author_email = 'cl3ver@pearachute.com', url = 'https://github.com/japherwocky/cl3ver', download_url = 'https://github.com/japherwocky/cl3ver/tarball/0.2.tar.gz', keywords = ['cleverbot', 'wrapper', 'clever', 'chatbot', 'cl3ver'], classifiers =[ 'Programming Language :: Python :: 3 :: Only', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Natural Language :: English', ], )
39.380952
84
0.541717
966165e75931deeaee2d1ab429f5cda6020e085f
19,860
py
Python
linux-distro/package/nuxleus/Source/Vendor/Microsoft/IronPython-2.0.1/Lib/headstock/example/microblog/microblog/jabber/pubsub.py
mdavid/nuxleus
653f1310d8bf08eaa5a7e3326c2349e56a6abdc2
[ "BSD-3-Clause" ]
1
2017-03-28T06:41:51.000Z
2017-03-28T06:41:51.000Z
linux-distro/package/nuxleus/Source/Vendor/Microsoft/IronPython-2.0.1/Lib/headstock/example/microblog/microblog/jabber/pubsub.py
mdavid/nuxleus
653f1310d8bf08eaa5a7e3326c2349e56a6abdc2
[ "BSD-3-Clause" ]
null
null
null
linux-distro/package/nuxleus/Source/Vendor/Microsoft/IronPython-2.0.1/Lib/headstock/example/microblog/microblog/jabber/pubsub.py
mdavid/nuxleus
653f1310d8bf08eaa5a7e3326c2349e56a6abdc2
[ "BSD-3-Clause" ]
1
2016-12-13T21:08:58.000Z
2016-12-13T21:08:58.000Z
# -*- coding: utf-8 -*- import re from Axon.Component import component from Kamaelia.Util.Backplane import PublishTo, SubscribeTo from Axon.Ipc import shutdownMicroprocess, producerFinished from Kamaelia.Protocol.HTTP.HTTPClient import SimpleHTTPClient from headstock.api.jid import JID from headstock.api.im import Message, Body from headstock.api.pubsub import Node, Item, Message from headstock.api.discovery import * from headstock.lib.utils import generate_unique from bridge import Element as E from bridge.common import XMPP_CLIENT_NS, XMPP_ROSTER_NS, \ XMPP_LAST_NS, XMPP_DISCO_INFO_NS, XMPP_DISCO_ITEMS_NS,\ XMPP_PUBSUB_NS from amplee.utils import extract_url_trail, get_isodate,\ generate_uuid_uri from amplee.error import ResourceOperationException from microblog.atompub.resource import ResourceWrapper from microblog.jabber.atomhandler import FeedReaderComponent __all__ = ['DiscoHandler', 'ItemsHandler', 'MessageHandler'] publish_item_rx = re.compile(r'\[(.*)\] ([\w ]*)') retract_item_rx = re.compile(r'\[(.*)\] ([\w:\-]*)') geo_rx = re.compile(r'(.*) ([\[\.|\d,|\-\]]*)') GEORSS_NS = u"http://www.georss.org/georss" GEORSS_PREFIX = u"georss"
39.72
127
0.507049
96616a7644cba49b6924d5d5a5b5f061a8473987
7,865
py
Python
examples/task_sequence_labeling_ner_lstm_crf.py
lonePatient/TorchBlocks
4a65d746cc8a396cb7df73ed4644d97ddf843e29
[ "MIT" ]
82
2020-06-23T05:51:08.000Z
2022-03-29T08:11:08.000Z
examples/task_sequence_labeling_ner_lstm_crf.py
lonePatient/TorchBlocks
4a65d746cc8a396cb7df73ed4644d97ddf843e29
[ "MIT" ]
null
null
null
examples/task_sequence_labeling_ner_lstm_crf.py
lonePatient/TorchBlocks
4a65d746cc8a396cb7df73ed4644d97ddf843e29
[ "MIT" ]
22
2020-06-23T05:51:10.000Z
2022-03-18T07:01:43.000Z
import os import json from torchblocks.metrics import SequenceLabelingScore from torchblocks.trainer import SequenceLabelingTrainer from torchblocks.callback import TrainLogger from torchblocks.processor import SequenceLabelingProcessor, InputExample from torchblocks.utils import seed_everything, dict_to_text, build_argparse from torchblocks.utils import prepare_device, get_checkpoints from torchblocks.data import CNTokenizer from torchblocks.data import Vocabulary, VOCAB_NAME from torchblocks.models.nn.lstm_crf import LSTMCRF from torchblocks.models.bases import TrainConfig from torchblocks.models.bases import WEIGHTS_NAME MODEL_CLASSES = { 'lstm-crf': (TrainConfig, LSTMCRF, CNTokenizer) } def build_vocab(data_dir, vocab_dir): ''' vocab ''' vocab = Vocabulary() vocab_path = os.path.join(vocab_dir, VOCAB_NAME) if os.path.exists(vocab_path): vocab.load_vocab(str(vocab_path)) else: files = ["train.json", "dev.json", "test.json"] for file in files: with open(os.path.join(data_dir, file), 'r') as fr: for line in fr: line = json.loads(line.strip()) text = line['text'] vocab.update(list(text)) vocab.build_vocab() vocab.save_vocab(vocab_path) print("vocab size: ", len(vocab)) if __name__ == "__main__": main()
46.264706
118
0.614495
966233a14411c83da996b856512cb5f8c21c76c2
277
py
Python
teachers/views.py
xuhairmeer/school-management
36394c841a61e46bc00e1dc21bcfcdd5fa6f6918
[ "bzip2-1.0.6" ]
null
null
null
teachers/views.py
xuhairmeer/school-management
36394c841a61e46bc00e1dc21bcfcdd5fa6f6918
[ "bzip2-1.0.6" ]
9
2021-03-19T08:15:07.000Z
2022-03-12T00:13:19.000Z
teachers/views.py
muhammadzuhair95/school-management
36394c841a61e46bc00e1dc21bcfcdd5fa6f6918
[ "bzip2-1.0.6" ]
null
null
null
# Create your views here. from django.urls import reverse_lazy from django.views import generic from forms.forms import UserCreateForm
23.083333
38
0.776173
9662ad75421db9c9fefe25e938e00f34ee4e0c42
1,466
py
Python
Code/Main.py
iqbalsublime/EPCMS
d2a745bda9a1d256d8834d1fa1105bb2bab79e3f
[ "MIT" ]
null
null
null
Code/Main.py
iqbalsublime/EPCMS
d2a745bda9a1d256d8834d1fa1105bb2bab79e3f
[ "MIT" ]
null
null
null
Code/Main.py
iqbalsublime/EPCMS
d2a745bda9a1d256d8834d1fa1105bb2bab79e3f
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Wed Nov 20 01:33:18 2019 @author: iqbalsublime """ from Customer import Customer from Restaurent import Restaurent from Reserve import Reserve from Menu import Menu from Order import Order cust1= Customer(1,"Iqbal", "0167****671") rest1= Restaurent(1,"Farmgate", "102 Kazi Nazrul Islam Ave, Dhaka") reserve1=Reserve(1, "20-11-2019",cust1, rest1) """ print("******Reservation*******") print("Reserve ID:{}, Date: {} Customer Name: {}, Mobile:{}, Branch: {}".format(reserve1.reserveid, reserve1.date, reserve1.customer.name, reserve1.customer.mobile, reserve1.restaurent.bname)) #print(reserve1.description()) print("******Reservation*******") """ menu1= Menu(1,"Burger", 160,"Fast Food",4) menu2= Menu(2,"Pizza", 560,"Fast Food",2) menu3= Menu(3,"Biriani", 220,"Indian",1) menu4= Menu(4,"Pitha", 50,"Bangla",5) order1= Order(1,"20-11-2019", cust1) order1.addMenu(menu1) order1.addMenu(menu2) order1.addMenu(menu3) order1.addMenu(menu4) print("******Invoice*******") print("Order ID:{}, Date: {} Customer Name: {}, Mobile:{}".format(order1.oid, order1.date, order1.Customer.name, order1.Customer.mobile)) totalBill=0.0 serial=1 print("SL---Food----Price---Qy----total") for order in order1.menus: print(serial,order.name, order.price, order.quantity, (order.price*order.quantity)) totalBill=totalBill+(order.price*order.quantity) print("Grand Total :", totalBill) print("******Invoice*******")
30.541667
100
0.680764
966342122018d47e80bbaf5398de1bb1a30423a0
4,544
py
Python
venv/Lib/site-packages/twisted/logger/_io.py
AironMattos/Web-Scraping-Project
89290fd376e2b42258c49e3ce2c3669932e03ad3
[ "MIT" ]
2
2021-05-30T16:35:00.000Z
2021-06-03T12:23:33.000Z
Lib/site-packages/twisted/logger/_io.py
Jriszz/guacamole-python
cf0dfcaaa7d85c3577571954fc5b2b9dcf55ba17
[ "MIT" ]
20
2021-05-03T18:02:23.000Z
2022-03-12T12:01:04.000Z
Lib/site-packages/twisted/logger/_io.py
fochoao/cpython
3dc84b260e5bced65ebc2c45c40c8fa65f9b5aa9
[ "bzip2-1.0.6", "0BSD" ]
2
2021-05-29T21:12:22.000Z
2021-05-30T04:56:50.000Z
# -*- test-case-name: twisted.logger.test.test_io -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ File-like object that logs. """ import sys from typing import AnyStr, Iterable, Optional from constantly import NamedConstant from incremental import Version from twisted.python.deprecate import deprecatedProperty from ._levels import LogLevel from ._logger import Logger def close(self) -> None: """ Close this file so it can no longer be written to. """ self._closed = True def flush(self) -> None: """ No-op; this file does not buffer. """ pass def fileno(self) -> int: """ Returns an invalid file descriptor, since this is not backed by an FD. @return: C{-1} """ return -1 def isatty(self) -> bool: """ A L{LoggingFile} is not a TTY. @return: C{False} """ return False def write(self, message: AnyStr) -> None: """ Log the given message. @param message: The message to write. """ if self._closed: raise ValueError("I/O operation on closed file") if isinstance(message, bytes): text = message.decode(self._encoding) else: text = message lines = (self._buffer + text).split("\n") self._buffer = lines[-1] lines = lines[0:-1] for line in lines: self.log.emit(self.level, format="{log_io}", log_io=line) def writelines(self, lines: Iterable[AnyStr]) -> None: """ Log each of the given lines as a separate message. @param lines: Data to write. """ for line in lines: self.write(line) def _unsupported(self, *args: object) -> None: """ Template for unsupported operations. @param args: Arguments. """ raise OSError("unsupported operation") read = _unsupported next = _unsupported readline = _unsupported readlines = _unsupported xreadlines = _unsupported seek = _unsupported tell = _unsupported truncate = _unsupported
24.170213
80
0.567342
96636c79f61d2c52c4c27582d3d3210f08ece747
3,547
py
Python
bot/exts/cricket.py
ShakyaMajumdar/ShaqqueBot
f618ae21e4bf700d86674399670634e8d1cc1dc9
[ "MIT" ]
null
null
null
bot/exts/cricket.py
ShakyaMajumdar/ShaqqueBot
f618ae21e4bf700d86674399670634e8d1cc1dc9
[ "MIT" ]
null
null
null
bot/exts/cricket.py
ShakyaMajumdar/ShaqqueBot
f618ae21e4bf700d86674399670634e8d1cc1dc9
[ "MIT" ]
null
null
null
from dataclasses import dataclass # from pprint import pprint import aiohttp import discord from discord.ext import commands from bot import constants API_URL = "https://livescore6.p.rapidapi.com/matches/v2/" LIVE_MATCHES_URL = API_URL + "list-live" HEADERS = { "x-rapidapi-key": constants.RAPIDAPI_KEY, "x-rapidapi-host": constants.RAPIDAPI_LIVESCORE6_HOST, } def setup(bot: commands.Bot): """Add Cricket Cog.""" bot.add_cog(Cricket(bot))
32.842593
120
0.480124
96640311a4d3b46c933f3f768041f09fa3a2cb24
3,588
py
Python
u24_lymphocyte/third_party/treeano/sandbox/nodes/update_dropout.py
ALSM-PhD/quip_classification
7347bfaa5cf11ae2d7a528fbcc43322a12c795d3
[ "BSD-3-Clause" ]
45
2015-04-26T04:45:51.000Z
2022-01-24T15:03:55.000Z
u24_lymphocyte/third_party/treeano/sandbox/nodes/update_dropout.py
ALSM-PhD/quip_classification
7347bfaa5cf11ae2d7a528fbcc43322a12c795d3
[ "BSD-3-Clause" ]
8
2018-07-20T20:54:51.000Z
2020-06-12T05:36:04.000Z
u24_lymphocyte/third_party/treeano/sandbox/nodes/update_dropout.py
ALSM-PhD/quip_classification
7347bfaa5cf11ae2d7a528fbcc43322a12c795d3
[ "BSD-3-Clause" ]
22
2018-05-21T23:57:20.000Z
2022-02-21T00:48:32.000Z
""" technique that randomly 0's out the update deltas for each parameter """ import theano import theano.tensor as T from theano.sandbox.rng_mrg import MRG_RandomStreams import treeano import treeano.nodes as tn fX = theano.config.floatX
36.612245
75
0.593924
966403bf90394bfb6b137e41500328a65675b400
822
py
Python
zeromq/test/manifest.py
brettin/liquidhandling
7a96e2881ffaa0326514cf5d97ba49d65ad42a14
[ "MIT" ]
null
null
null
zeromq/test/manifest.py
brettin/liquidhandling
7a96e2881ffaa0326514cf5d97ba49d65ad42a14
[ "MIT" ]
null
null
null
zeromq/test/manifest.py
brettin/liquidhandling
7a96e2881ffaa0326514cf5d97ba49d65ad42a14
[ "MIT" ]
null
null
null
import os import os.path from datetime import datetime import time from stat import * import pathlib import json
26.516129
102
0.611922
9665d6688a28f3e81d1997d0e6bd30513e85d853
1,111
py
Python
shops/shop_util/test_shop_names.py
ikp4success/shopasource
9a9ed5c58a8b37b6ff169b45f7fdfcb44809fd88
[ "Apache-2.0" ]
3
2019-12-04T07:08:55.000Z
2020-12-08T01:38:46.000Z
shops/shop_util/test_shop_names.py
ikp4success/shopasource
9a9ed5c58a8b37b6ff169b45f7fdfcb44809fd88
[ "Apache-2.0" ]
null
null
null
shops/shop_util/test_shop_names.py
ikp4success/shopasource
9a9ed5c58a8b37b6ff169b45f7fdfcb44809fd88
[ "Apache-2.0" ]
null
null
null
from enum import Enum
25.25
45
0.568857
9666c26fde73b6b01161a9c3fc47311bfae3372e
2,477
py
Python
package_manager/util_test.py
shahriak/dotnet5
6b96c38b0f351b79750bd2b8bc0f77dc434afe00
[ "Apache-2.0" ]
10,302
2018-04-17T17:06:57.000Z
2022-03-31T17:29:36.000Z
package_manager/util_test.py
unasuke/distroless
859ce06093a899f31fffc1cd151cf9867faf49d5
[ "Apache-2.0" ]
623
2018-04-17T20:43:43.000Z
2022-03-30T13:08:57.000Z
package_manager/util_test.py
unasuke/distroless
859ce06093a899f31fffc1cd151cf9867faf49d5
[ "Apache-2.0" ]
726
2018-05-09T16:20:46.000Z
2022-03-31T15:09:07.000Z
import unittest import os from six import StringIO from package_manager import util CHECKSUM_TXT = "1915adb697103d42655711e7b00a7dbe398a33d7719d6370c01001273010d069" DEBIAN_JESSIE_OS_RELEASE = """PRETTY_NAME="Distroless" NAME="Debian GNU/Linux" ID="debian" VERSION_ID="8" VERSION="Debian GNU/Linux 8 (jessie)" HOME_URL="https://github.com/GoogleContainerTools/distroless" SUPPORT_URL="https://github.com/GoogleContainerTools/distroless/blob/master/README.md" BUG_REPORT_URL="https://github.com/GoogleContainerTools/distroless/issues/new" """ DEBIAN_STRETCH_OS_RELEASE = """PRETTY_NAME="Distroless" NAME="Debian GNU/Linux" ID="debian" VERSION_ID="9" VERSION="Debian GNU/Linux 9 (stretch)" HOME_URL="https://github.com/GoogleContainerTools/distroless" SUPPORT_URL="https://github.com/GoogleContainerTools/distroless/blob/master/README.md" BUG_REPORT_URL="https://github.com/GoogleContainerTools/distroless/issues/new" """ DEBIAN_BUSTER_OS_RELEASE = """PRETTY_NAME="Distroless" NAME="Debian GNU/Linux" ID="debian" VERSION_ID="10" VERSION="Debian GNU/Linux 10 (buster)" HOME_URL="https://github.com/GoogleContainerTools/distroless" SUPPORT_URL="https://github.com/GoogleContainerTools/distroless/blob/master/README.md" BUG_REPORT_URL="https://github.com/GoogleContainerTools/distroless/issues/new" """ # VERSION and VERSION_ID aren't set on unknown distros DEBIAN_UNKNOWN_OS_RELEASE = """PRETTY_NAME="Distroless" NAME="Debian GNU/Linux" ID="debian" HOME_URL="https://github.com/GoogleContainerTools/distroless" SUPPORT_URL="https://github.com/GoogleContainerTools/distroless/blob/master/README.md" BUG_REPORT_URL="https://github.com/GoogleContainerTools/distroless/issues/new" """ osReleaseForDistro = { "jessie": DEBIAN_JESSIE_OS_RELEASE, "stretch": DEBIAN_STRETCH_OS_RELEASE, "buster": DEBIAN_BUSTER_OS_RELEASE, "???": DEBIAN_UNKNOWN_OS_RELEASE, } if __name__ == '__main__': unittest.main()
34.887324
86
0.774727
9667f9974ca754b017d3785df5cd5e5a88c0fff5
9,337
py
Python
testscripts/RDKB/component/TAD/TS_TAD_Download_SetInvalidDiagnosticsState.py
cablelabs/tools-tdkb
1fd5af0f6b23ce6614a4cfcbbaec4dde430fad69
[ "Apache-2.0" ]
null
null
null
testscripts/RDKB/component/TAD/TS_TAD_Download_SetInvalidDiagnosticsState.py
cablelabs/tools-tdkb
1fd5af0f6b23ce6614a4cfcbbaec4dde430fad69
[ "Apache-2.0" ]
null
null
null
testscripts/RDKB/component/TAD/TS_TAD_Download_SetInvalidDiagnosticsState.py
cablelabs/tools-tdkb
1fd5af0f6b23ce6614a4cfcbbaec4dde430fad69
[ "Apache-2.0" ]
null
null
null
########################################################################## # If not stated otherwise in this file or this component's Licenses.txt # file the following copyright and licenses apply: # # Copyright 2016 RDK Management # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ########################################################################## ''' <?xml version='1.0' encoding='utf-8'?> <xml> <id></id> <!-- Do not edit id. This will be auto filled while exporting. If you are adding a new script keep the id empty --> <version>2</version> <!-- Do not edit version. This will be auto incremented while updating. If you are adding a new script you can keep the vresion as 1 --> <name>TS_TAD_Download_SetInvalidDiagnosticsState</name> <!-- If you are adding a new script you can specify the script name. Script Name should be unique same as this file name with out .py extension --> <primitive_test_id> </primitive_test_id> <!-- Do not change primitive_test_id if you are editing an existing script. --> <primitive_test_name>TADstub_Get</primitive_test_name> <!-- --> <primitive_test_version>3</primitive_test_version> <!-- --> <status>FREE</status> <!-- --> <synopsis>To check if Diagnostics state of download can be set with invalid value. Requested and Canceled are the only writable values.If the test fails,set any writable parameter and check if the DiagnosticsState changes to None</synopsis> <!-- --> <groups_id /> <!-- --> <execution_time>1</execution_time> <!-- --> <long_duration>false</long_duration> <!-- --> <advanced_script>false</advanced_script> <!-- execution_time is the time out time for test execution --> <remarks>RDKB doesn't support Download Diagnostics feature till now</remarks> <!-- Reason for skipping the tests if marked to skip --> <skip>false</skip> <!-- --> <box_types> </box_types> <rdk_versions> <rdk_version>RDKB</rdk_version> <!-- --> </rdk_versions> <test_cases> <test_case_id>TC_TAD_34</test_case_id> <test_objective>To check if Diagnostics state of download can be set with invalid value. Requested and Canceled are the only writable values.If the test fails,set any writable parameter and check if the DiagnosticsState changes to None</test_objective> <test_type>Positive</test_type> <test_setup>XB3,Emulator</test_setup> <pre_requisite>1.Ccsp Components should be in a running state else invoke cosa_start.sh manually that includes all the ccsp components. 2.TDK Agent should be in running state or invoke it through StartTdk.sh script</pre_requisite> <api_or_interface_used>TADstub_Get</api_or_interface_used> <input_parameters>Device.IP.Diagnostics.DownloadDiagnostics.DiagnosticsState Device.IP.Diagnostics.DownloadDiagnostics.Interface Device.IP.Diagnostics.DownloadDiagnostics.DownloadURL</input_parameters> <automation_approch>1. Load TAD modules 2. From script invoke TADstub_Set to set all the writable parameters 3. Check whether the result params get changed along with the download DignosticsState 4. Validation of the result is done within the python script and send the result status to Test Manager. 5.Test Manager will publish the result in GUI as PASS/FAILURE based on the response from TAD stub.</automation_approch> <except_output>CheckPoint 1: The output should be logged in the Agent console/Component log CheckPoint 2: Stub function result should be success and should see corresponding log in the agent console log CheckPoint 3: TestManager GUI will publish the result as PASS in Execution/Console page of Test Manager</except_output> <priority>High</priority> <test_stub_interface>None</test_stub_interface> <test_script>TS_TAD_Download_SetInvalidDiagnosticsState</test_script> <skipped>No</skipped> <release_version></release_version> <remarks></remarks> </test_cases> <script_tags /> </xml> ''' # use tdklib library,which provides a wrapper for tdk testcase script import tdklib; #Test component to be tested obj = tdklib.TDKScriptingLibrary("tad","1"); #IP and Port of box, No need to change, #This will be replaced with correspoing Box Ip and port while executing script ip = <ipaddress> port = <port> obj.configureTestCase(ip,port,'TS_TAD_SetInvalidDownloadDiagnosticsState'); #Get the result of connection with test component and DUT loadmodulestatus =obj.getLoadModuleResult(); print "[LIB LOAD STATUS] : %s" %loadmodulestatus ; if "SUCCESS" in loadmodulestatus.upper(): #Set the result status of execution obj.setLoadModuleStatus("SUCCESS"); tdkTestObj = obj.createTestStep('TADstub_Set'); tdkTestObj.addParameter("ParamName","Device.IP.Diagnostics.DownloadDiagnostics.DiagnosticsState"); tdkTestObj.addParameter("ParamValue","Completed"); tdkTestObj.addParameter("Type","string"); expectedresult="FAILURE"; tdkTestObj.executeTestCase(expectedresult); actualresult = tdkTestObj.getResult(); details = tdkTestObj.getResultDetails(); if expectedresult in actualresult: #Set the result status of execution tdkTestObj.setResultStatus("SUCCESS"); print "TEST STEP 1:Set DiagnosticsState of download as completed"; print "EXPECTED RESULT 1: DiagnosticsState of download must be Requested or Canceled"; print "ACTUAL RESULT 1: Can not set diagnosticsState of download as completed, details : %s" %details; #Get the result of execution print "[TEST EXECUTION RESULT] : SUCCESS"; tdkTestObj = obj.createTestStep('TADstub_Set'); tdkTestObj.addParameter("ParamName","Device.IP.Diagnostics.DownloadDiagnostics.Interface"); tdkTestObj.addParameter("ParamValue","Interface_erouter0"); tdkTestObj.addParameter("Type","string"); expectedresult="SUCCESS"; tdkTestObj.executeTestCase(expectedresult); actualresult = tdkTestObj.getResult(); details = tdkTestObj.getResultDetails(); if expectedresult in actualresult: #Set the result status of execution tdkTestObj.setResultStatus("SUCCESS"); print "TEST STEP 2: Set the interface of Download"; print "EXPECTED RESULT 2: Should set the interface of Download "; print "ACTUAL RESULT 2: %s" %details; #Get the result of execution print "[TEST EXECUTION RESULT] : SUCCESS"; tdkTestObj = obj.createTestStep('TADstub_Get'); tdkTestObj.addParameter("paramName","Device.IP.Diagnostics.DownloadDiagnostics.DiagnosticsState"); expectedresult="SUCCESS"; tdkTestObj.executeTestCase(expectedresult); actualresult = tdkTestObj.getResult(); details= tdkTestObj.getResultDetails(); if expectedresult in actualresult and details=="None": #Set the result status of execution tdkTestObj.setResultStatus("SUCCESS"); print "TEST STEP 3 :Get DiagnosticsState of download as None"; print "EXPECTED RESULT 3 :Should get the DiagnosticsState of download as None "; print "ACTUAL RESULT 3 :The DiagnosticsState of download is , details : %s" %details; #Get the result of execution print "[TEST EXECUTION RESULT] : SUCCESS"; else: #Set the result status of execution tdkTestObj.setResultStatus("FAILURE"); print "TEST STEP 3 :Get DiagnosticsState of download as None"; print "EXPECTED RESULT 3 :Should get the Diagnostics State of download as None"; print "ACTUAL RESULT 3 :The DiagnosticsState of download is , details : %s" %details; #Get the result of execution print "[TEST EXECUTION RESULT] : FAILURE"; else: #Set the result status of execution tdkTestObj.setResultStatus("FAILURE"); print "TEST STEP 2: Set the interface of Download"; print "EXPECTED RESULT 2: Should set the interface of Download "; print "ACTUAL RESULT 2: %s" %details; #Get the result of execution print "[TEST EXECUTION RESULT] : FAILURE"; else: #Set the result status of execution tdkTestObj.setResultStatus("FAILURE"); print "TEST STEP 1:Set DiagnosticsState of download as completed"; print "EXPECTED RESULT 1: DiagnosticsState of download must be Requested or Canceled"; print "ACTUAL RESULT 1: DiagnosticsState of download is set as completed, details : %s" %details; #Get the result of execution print "[TEST EXECUTION RESULT] : FAILURE"; obj.unloadModule("tad"); else: print "Failed to load tad module"; obj.setLoadModuleStatus("FAILURE"); print "Module loading failed";
49.402116
256
0.698297
966918b396e78cd0cc9c87fbc4a01ea21e115709
2,926
py
Python
Tutorials/tutorial_01_intro.py
mseinstein/openCV
94bfd55e0d77fd78f2669244bbab5d9ea8f32666
[ "MIT" ]
null
null
null
Tutorials/tutorial_01_intro.py
mseinstein/openCV
94bfd55e0d77fd78f2669244bbab5d9ea8f32666
[ "MIT" ]
null
null
null
Tutorials/tutorial_01_intro.py
mseinstein/openCV
94bfd55e0d77fd78f2669244bbab5d9ea8f32666
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Fri Sep 01 14:09:03 2017 @author: BJ """ import cv2 import os from matplotlib import pyplot as plt os.chdir('E:\\GitHub\\openCV\\Tutorials') # %% IMAGES # Load color image # Add the flags 1, 0 or -1, to load a color image, load an image in # grayscale mode or load image as is, respectively img = cv2.imread('LegoAd.jpg',1) # Display an image # The first argument is the window name (string), the second argument is the image cv2.imshow('image',img) # You can display multiple windows using different window names cv2.imshow('image2',img) # Displaying an image using Matplotlib # OpenCV loads color in BGR, while matplotlib displays in RGB, so to use # matplotlib you need to reverse the order of the color layers plt.imshow(img[:,:,::-1],interpolation = 'bicubic') # note there is an argument in imshow to set the colormap, this is ignored if # the input is 3D as it assumes the third dimension directly specifies the RGB # values plt.imshow(img[:,:,::-1], cmap= "Greys", interpolation = 'bicubic') # you can remove the tick marks using the following code plt.xticks([]), plt.yticks([]) # Here is a list of the full matplot lib colormaps # https://matplotlib.org/examples/color/colormaps_reference.html # Closing an image # To close a specific window use the following command withi its name as the argument cv2.destroyWindow('image2') # To close all windows use the following command with no arguments cv2.destroyAllWindows() # Writing an image # The first argument is the name of the file to write and the second arguemnt # is the image cv2.imwrite('testimg.jpg',img) # Resizing and image img = cv2.imread('LegoAd.jpg',1) # need to declare window before showing image cv2.namedWindow('image',cv2.WINDOW_NORMAL) cv2.imshow('image',img) img_height = 600 img_width = int(img_height*float(img.shape[0])/img.shape[1]) cv2.resizeWindow('image', img_height,img_width) # %% VIDEO # You first need to create a capture object with the argument either being the # name of the video file or the index of the capture device (starting from 0) # only need more indexes when have additional video capture equipment attached cap = cv2.VideoCapture(0) while(True): # Capture frame-by-frame # frame returns the captured image and ret is a boolean which returns TRUE # if frame is read correctly ret, frame = cap.read() # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # gray2 = frame # Display the resulting frame cv2.imshow('frame',gray) # Wait for the signal to stop the capture # The argument is waitKey is the length of time to wait for the input before # moving onto the next line of code # when running on 64-bit you need to add 0xFF if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture cap.release() #cv2.destroyWindow('frame')
31.462366
85
0.726931
966a5cfd248281b2c96521b02313c0a59ac99d4a
625
py
Python
mutational_landscape/migrations/0003_auto_20220225_1650.py
protwis/Protwis
fdcad0a2790721b02c0d12d8de754313714c575e
[ "Apache-2.0" ]
null
null
null
mutational_landscape/migrations/0003_auto_20220225_1650.py
protwis/Protwis
fdcad0a2790721b02c0d12d8de754313714c575e
[ "Apache-2.0" ]
null
null
null
mutational_landscape/migrations/0003_auto_20220225_1650.py
protwis/Protwis
fdcad0a2790721b02c0d12d8de754313714c575e
[ "Apache-2.0" ]
null
null
null
# Generated by Django 2.2.1 on 2022-02-25 15:50 from django.db import migrations
22.321429
60
0.5712
966a7103f706d3acd97c7d32abf73b5779105922
491
py
Python
redis_benchmarks_specification/__init__.py
LaudateCorpus1/redis-benchmarks-specification
71a7e28cd130499f02dacc00bdeca2eadfa62619
[ "Apache-2.0" ]
4
2022-01-24T10:15:55.000Z
2022-03-15T09:40:16.000Z
redis_benchmarks_specification/__init__.py
LaudateCorpus1/redis-benchmarks-specification
71a7e28cd130499f02dacc00bdeca2eadfa62619
[ "Apache-2.0" ]
27
2021-08-13T14:20:36.000Z
2021-09-21T16:49:40.000Z
redis_benchmarks_specification/__init__.py
LaudateCorpus1/redis-benchmarks-specification
71a7e28cd130499f02dacc00bdeca2eadfa62619
[ "Apache-2.0" ]
1
2022-02-02T14:07:55.000Z
2022-02-02T14:07:55.000Z
# Apache License Version 2.0 # # Copyright (c) 2021., Redis Labs # All rights reserved. # # This attribute is the only one place that the version number is written down, # so there is only one place to change it when the version number changes. import pkg_resources PKG_NAME = "redis-benchmarks-specification" try: __version__ = pkg_resources.get_distribution(PKG_NAME).version except (pkg_resources.DistributionNotFound, AttributeError): __version__ = "99.99.99" # like redis
30.6875
79
0.763747
966aec55e4c71e579f2f8dad4a1f0d280f90e1cf
1,354
py
Python
rest_framework_helpers/fields/relation.py
Apkawa/django-rest-framework-helpers
f4b24bf326e081a215ca5c1c117441ea8f78cbb4
[ "MIT" ]
null
null
null
rest_framework_helpers/fields/relation.py
Apkawa/django-rest-framework-helpers
f4b24bf326e081a215ca5c1c117441ea8f78cbb4
[ "MIT" ]
null
null
null
rest_framework_helpers/fields/relation.py
Apkawa/django-rest-framework-helpers
f4b24bf326e081a215ca5c1c117441ea8f78cbb4
[ "MIT" ]
null
null
null
# coding: utf-8 from __future__ import unicode_literals from collections import OrderedDict import six from django.db.models import Model from rest_framework import serializers
30.088889
78
0.655096
966b4317dba886d84d6b354c4c49cfcc2476c374
10,426
py
Python
examples/guojiadianwang/devops/devopsPro.py
peng5550/DecryptLogin
43be0f3d9b68e4ea171cd4c3c200d29a4409d2e4
[ "MIT" ]
null
null
null
examples/guojiadianwang/devops/devopsPro.py
peng5550/DecryptLogin
43be0f3d9b68e4ea171cd4c3c200d29a4409d2e4
[ "MIT" ]
null
null
null
examples/guojiadianwang/devops/devopsPro.py
peng5550/DecryptLogin
43be0f3d9b68e4ea171cd4c3c200d29a4409d2e4
[ "MIT" ]
null
null
null
import requests from utils import loginFile, dataAnalysis import os import datetime from dateutil.relativedelta import relativedelta import json from utils.logCls import Logger dirpath = os.path.dirname(__file__) cookieFile = f"{dirpath}/utils/cookies.txt" dataFile = f"{dirpath}/datas" if __name__ == '__main__': demo = DevopsProject("test") demo.main()
45.929515
464
0.579513
966b98dbd5e0be6079948a6cd3ac31f277a97210
6,186
py
Python
ezalor.py
WellerV/EzalorTools
8279c401c9970087af955ac094fe4ebd105e8174
[ "Apache-2.0" ]
13
2018-02-07T06:34:14.000Z
2020-03-04T08:12:08.000Z
ezalor.py
WellerV/EzalorTools
8279c401c9970087af955ac094fe4ebd105e8174
[ "Apache-2.0" ]
null
null
null
ezalor.py
WellerV/EzalorTools
8279c401c9970087af955ac094fe4ebd105e8174
[ "Apache-2.0" ]
2
2018-03-01T09:02:38.000Z
2021-02-16T12:16:28.000Z
#!/usr/bin/env python # -*- coding:utf-8 -*- # Copyright (c) 2018 - huwei <huwei@gionee.com> """ This is a python script for the ezalor tools which is used to io monitor. You can use the script to open or off the switch, or point the package name which you want to monitor it only. The core function is to export data what ezalor is record. """ import os import re import sys, getopt import sqlite3 import subprocess import xlsxwriter as xw from markhelper import MarkHelper from record import Record from style import Style from datetime import datetime DB_NAME_REG = "^ezalor_{0}(.*).db$" tableheaders = ["path", "process", "thread", "processId", "threadId", "readCount", "readBytes", "readTime", "writeCount", "writeBytes", "writeTime", "stacktrace", "openTime", "closeTime", "mark"] envDir = "/sdcard/ezalor/" AUTOCOLUMN_WIDTH_INDEXS = [0, 1, 2, 12, 13, 14] # os.system("rm " + path + "ezalor.db") if __name__ == "__main__": main(sys.argv[1:])
32.387435
120
0.624313
966b9c223ecd09480f1a0fd34d6be56ce22a2ada
11,772
py
Python
revisions/models.py
debrouwere/django-revisions
d5b95806c65e66a720a2d9ec2f5ffb16698d9275
[ "BSD-2-Clause-FreeBSD" ]
6
2015-11-05T11:48:46.000Z
2021-04-14T07:10:16.000Z
revisions/models.py
debrouwere/django-revisions
d5b95806c65e66a720a2d9ec2f5ffb16698d9275
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
revisions/models.py
debrouwere/django-revisions
d5b95806c65e66a720a2d9ec2f5ffb16698d9275
[ "BSD-2-Clause-FreeBSD" ]
1
2019-02-13T21:01:48.000Z
2019-02-13T21:01:48.000Z
# encoding: utf-8 import uuid import difflib from datetime import date from django.db import models from django.utils.translation import ugettext as _ from django.core.exceptions import ImproperlyConfigured, ValidationError from django.db import IntegrityError from django.contrib.contenttypes.models import ContentType from revisions import managers, utils import inspect # the crux of all errors seems to be that, with VersionedBaseModel, # doing setattr(self, self.pk_name, None) does _not_ lead to creating # a new object, and thus versioning as a whole doesn't work # the only thing lacking from the VersionedModelBase is a version id. # You may use VersionedModelBase if you need to specify your own # AutoField (e.g. using UUIDs) or if you're trying to adapt an existing # model to ``django-revisions`` and have an AutoField not named # ``vid``.
39.503356
123
0.641777
966c228f07ae23bcd47d41a07f74a33292ad5f8f
1,260
py
Python
noir/templating.py
gi0baro/noir
b187922d4f6055dbcb745c5299db907aac574398
[ "BSD-3-Clause" ]
2
2021-06-10T13:09:27.000Z
2021-06-11T09:37:02.000Z
noir/templating.py
gi0baro/noir
b187922d4f6055dbcb745c5299db907aac574398
[ "BSD-3-Clause" ]
null
null
null
noir/templating.py
gi0baro/noir
b187922d4f6055dbcb745c5299db907aac574398
[ "BSD-3-Clause" ]
null
null
null
import json import os from typing import Any, Dict, Optional import tomlkit import yaml from renoir.apis import Renoir, ESCAPES, MODES from renoir.writers import Writer as _Writer from .utils import adict, obj_to_adict def _indent(text: str, spaces: int = 2) -> str: offset = " " * spaces rv = f"\n{offset}".join(text.split("\n")) return rv def _to_json(obj: Any, indent: Optional[int] = None) -> str: return json.dumps(obj, indent=indent) def _to_toml(obj: Any) -> str: return tomlkit.dumps(obj) def _to_yaml(obj: Any) -> str: return yaml.dump(obj) def base_ctx(ctx: Dict[str, Any]): ctx.update( env=obj_to_adict(os.environ), indent=_indent, to_json=_to_json, to_toml=_to_toml, to_yaml=_to_yaml ) yaml.add_representer(adict, yaml.representer.Representer.represent_dict) templater = Templater(mode=MODES.plain, adjust_indent=True, contexts=[base_ctx])
21.355932
80
0.666667
966d171d2b44d0254f7759c28f9717f4faa2dc4c
3,904
py
Python
GUI/lib/plotData.py
apajon/GUIPythonEncodeur
05b58809ed7a287369c5bfa04b5fb69f5d9e36aa
[ "MIT" ]
null
null
null
GUI/lib/plotData.py
apajon/GUIPythonEncodeur
05b58809ed7a287369c5bfa04b5fb69f5d9e36aa
[ "MIT" ]
4
2021-06-03T23:34:17.000Z
2021-06-04T21:31:19.000Z
GUI/lib/plotData.py
apajon/GUIPythonEncodeur
05b58809ed7a287369c5bfa04b5fb69f5d9e36aa
[ "MIT" ]
null
null
null
# Copyright (c) 2021 Adrien Pajon (adrien.pajon@gmail.com) # # This software is released under the MIT License. # https://opensource.org/licenses/MIT import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches from api_phidget_n_MQTT.src.lib_global_python import searchLoggerFile
38.27451
116
0.619365
966d9c6d207cc79829fc35c116bf0cff41eb5f9c
4,945
py
Python
nova/tests/unit/objects/test_resource.py
Nexenta/nova
ccecb507ff4bdcdd23d90e7b5b02a22c5a46ecc3
[ "Apache-2.0" ]
1
2021-06-10T17:08:15.000Z
2021-06-10T17:08:15.000Z
nova/tests/unit/objects/test_resource.py
Nexenta/nova
ccecb507ff4bdcdd23d90e7b5b02a22c5a46ecc3
[ "Apache-2.0" ]
2
2021-03-31T20:04:16.000Z
2021-12-13T20:45:03.000Z
nova/tests/unit/objects/test_resource.py
Nexenta/nova
ccecb507ff4bdcdd23d90e7b5b02a22c5a46ecc3
[ "Apache-2.0" ]
1
2021-11-12T03:55:41.000Z
2021-11-12T03:55:41.000Z
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock from oslo_serialization import jsonutils from oslo_utils.fixture import uuidsentinel as uuids import six from nova.objects import resource from nova.tests.unit.objects import test_objects fake_resources = resource.ResourceList(objects=[ resource.Resource(provider_uuid=uuids.rp, resource_class='CUSTOM_RESOURCE', identifier='foo'), resource.Resource(provider_uuid=uuids.rp, resource_class='CUSTOM_RESOURCE', identifier='bar')]) fake_vpmems = [ resource.LibvirtVPMEMDevice( label='4GB', name='ns_0', devpath='/dev/dax0.0', size=4292870144, align=2097152), resource.LibvirtVPMEMDevice( label='4GB', name='ns_1', devpath='/dev/dax0.0', size=4292870144, align=2097152)] fake_instance_extras = { 'resources': jsonutils.dumps(fake_resources.obj_to_primitive()) }
39.879032
79
0.651769
966e2e4f01ba505a9a223a3984ad9d961a218e79
11,532
py
Python
mandala/storages/rel_impl/psql_utils.py
amakelov/mandala
a9ec051ef730ada4eed216c62a07b033126e78d5
[ "Apache-2.0" ]
9
2022-02-22T19:24:01.000Z
2022-03-23T04:46:41.000Z
mandala/storages/rel_impl/psql_utils.py
amakelov/mandala
a9ec051ef730ada4eed216c62a07b033126e78d5
[ "Apache-2.0" ]
null
null
null
mandala/storages/rel_impl/psql_utils.py
amakelov/mandala
a9ec051ef730ada4eed216c62a07b033126e78d5
[ "Apache-2.0" ]
null
null
null
from sqlalchemy.engine.base import Connection from sqlalchemy.sql.selectable import Select, CompoundSelect from sqlalchemy.engine.result import Result from sqlalchemy.dialects import postgresql from .utils import transaction from ...common_imports import * from ...util.common_ut import get_uid from ...core.config import PSQLConfig ################################################################################ ### helper functions ################################################################################ ################################################################################ ### interface to postgres ################################################################################ ################################################################################ ### fast operations ################################################################################ def fast_select(query:TUnion[str, Select]=None, qual_table:str=None, index_col:str=None, cols:TList[str]=None, conn:Connection=None) -> pd.DataFrame: """ Some notes: - loading an empty table with an index (index_col=something) will not display the index name(s), but they are in the (empty) index """ logging.debug('Fastread does not handle dtypes') # quote table name if query is None: assert qual_table is not None if '.' in qual_table: schema, table = qual_table.split('.') quoted_table = f'"{schema}"."{table}"' else: quoted_table = f'"{qual_table}"' if cols is not None: cols_string = ', '.join([f'"{col}"' for col in cols]) query = f'SELECT {cols_string} FROM {quoted_table}' else: query = f'SELECT * FROM {quoted_table}' head = 'HEADER' if isinstance(query, (Select, CompoundSelect)): #! the query object must be converted to a pure postgresql-compatible #! string for this to work, and in particular to render bound parameters # in-line using the literal_binds kwarg and the particular dialect query_string = query.compile(bind=conn.engine, compile_kwargs={'literal_binds': True}, dialect=postgresql.dialect()) elif isinstance(query, str): query_string = query else: raise NotImplementedError() copy_sql = f"""COPY ({query_string}) TO STDOUT WITH CSV {head}""" buffer = io.StringIO() # Note that we need to use a *raw* connection in this method, which can be # accessed as conn.connection with conn.connection.cursor() as curs: curs.copy_expert(copy_sql, buffer) buffer.seek(0) df:pd.DataFrame = pd.read_csv(buffer) if index_col is not None: df = df.set_index(index_col) return df def fast_insert(df:pd.DataFrame, qual_table:str, conn:Connection=None, columns:TList[str]=None, include_index:bool=True): """ In psycopg 2.9, they changed the .copy_from() method, so that table names are now quoted. This means that it won't work with a schema-qualified name. This method fixes this by using copy_expert(), as directed by the psycopg2 docs. """ if columns is None: columns = df.columns if '.' in qual_table: schema, table = qual_table.split('.') quoted_table = f'"{schema}"."{table}"' else: quoted_table = f'"{qual_table}"' start_time = time.time() # save dataframe to an in-memory buffer buffer = io.StringIO() if include_index: df = df.reset_index() df.to_csv(buffer, header=False, index=False, columns=columns, na_rep='') buffer.seek(0) columns_string = ', '.join('"{}"'.format(k) for k in columns) query = f"""COPY {quoted_table}({columns_string}) FROM STDIN WITH CSV""" # Note that we need to use a *raw* connection in this method, which can be # accessed as conn.connection with conn.connection.cursor() as curs: curs.copy_expert(sql=query, file=buffer) end_time = time.time() nrows = df.shape[0] total_time = end_time - start_time logging.debug(f'Inserted {nrows} rows, {nrows/total_time} rows/second') def fast_upsert(df:pd.DataFrame, qual_table:str, index_cols:TList[str], columns:TList[str]=None, include_index:bool=True, conn:Connection=None): """ code based on https://stackoverflow.com/questions/46934351/python-postgresql-copy-command-used-to-insert-or-update-not-just-insert """ if include_index: df = df.reset_index() #! importantly, columns are set after potentially resetting the index if columns is None: columns = list(df.columns) if '.' in qual_table: schema, table = qual_table.split('.') quoted_table = f'"{schema}"."{table}"' else: schema = '' table = qual_table quoted_table = f'"{qual_table}"' # create a temporary table with same columns as target table # temp_qual_table = f'{schema}.{table}__copy' temp_uid = get_uid()[:16] temp_qual_table = f'{schema}_{table}__copy_{temp_uid}' temp_index_name = f'{schema}_{table}__temp_index_{temp_uid}' create_temp_table_query = f""" create temporary table {temp_qual_table} as (select * from {quoted_table} limit 0); """ conn.execute(create_temp_table_query) # if provided, create indices on the table if index_cols is not None: create_temp_index_query = f""" CREATE INDEX {temp_index_name} ON {temp_qual_table}({','.join(index_cols)}); """ conn.execute(create_temp_index_query) # copy data into this table fast_insert(df=df, qual_table=temp_qual_table, conn=conn, columns=columns, include_index=include_index) # comma-separated lists of various things target_cols_string = f"{', '.join(columns)}" source_cols_string = f"{', '.join([f'{temp_qual_table}.{col}' for col in columns])}" index_cols_string = f"{', '.join([f'{col}' for col in index_cols])}" # update existing records index_conditions = ' AND '.join([f'{qual_table}.{col} = {temp_qual_table}.{col}' for col in index_cols]) update_query = f""" UPDATE {quoted_table} SET ({target_cols_string}) = ({source_cols_string}) FROM {temp_qual_table} WHERE {index_conditions} """ conn.execute(update_query) # insert new records insert_query = f""" INSERT INTO {quoted_table}({target_cols_string}) ( SELECT {source_cols_string} FROM {temp_qual_table} LEFT JOIN {quoted_table} USING({index_cols_string}) WHERE {table} IS NULL); """ conn.execute(insert_query)
40.893617
129
0.583593
966fe34cabbdf144b4795af99c630f2fed4590e1
1,484
py
Python
tests/test_ami.py
seek-oss/aec
13a75c690542eec61727b9d92a2c11a3dbd1caba
[ "MIT" ]
6
2019-09-10T11:23:18.000Z
2021-03-25T04:37:28.000Z
tests/test_ami.py
seek-oss/aec
13a75c690542eec61727b9d92a2c11a3dbd1caba
[ "MIT" ]
162
2019-12-05T10:21:00.000Z
2022-03-27T06:00:45.000Z
tests/test_ami.py
seek-oss/aec
13a75c690542eec61727b9d92a2c11a3dbd1caba
[ "MIT" ]
6
2019-10-27T22:59:35.000Z
2021-02-10T22:36:59.000Z
import pytest from moto import mock_ec2 from moto.ec2.models import AMIS from aec.command.ami import delete, describe, share
31.574468
97
0.735849
96702b58ef9f60b2130e8a0e754ad89b97258e50
691
py
Python
mainapp/views.py
H0oxy/sportcars
dcd76736bfe88630b3ccce7e4ee0ad9398494f08
[ "MIT" ]
null
null
null
mainapp/views.py
H0oxy/sportcars
dcd76736bfe88630b3ccce7e4ee0ad9398494f08
[ "MIT" ]
null
null
null
mainapp/views.py
H0oxy/sportcars
dcd76736bfe88630b3ccce7e4ee0ad9398494f08
[ "MIT" ]
null
null
null
from django.views.generic import ListView from rest_framework.permissions import AllowAny from rest_framework.viewsets import ModelViewSet from mainapp.models import Manufacturer, Car from mainapp.serializers import ManufacturerSerializer, CarSerializer
25.592593
69
0.797395
96708ac825e30302b84cfd4e3368984095dd810a
3,168
py
Python
BrandDetails.py
p10rahulm/brandyz-reco
95d5e3f291cdb5b951e0c7d83ff30c59f8a3797f
[ "MIT" ]
null
null
null
BrandDetails.py
p10rahulm/brandyz-reco
95d5e3f291cdb5b951e0c7d83ff30c59f8a3797f
[ "MIT" ]
null
null
null
BrandDetails.py
p10rahulm/brandyz-reco
95d5e3f291cdb5b951e0c7d83ff30c59f8a3797f
[ "MIT" ]
null
null
null
# In this module we will get the brand count and the users per brand as a list. # Add more details as deemed necessary # I'm using mergesort here instead of quicksort as the size of data is much larger than for users import Mergesort import numpy as np # Below was using list of tuples for storage, now going to convert to dictionary of np.arrays or lists. This could be more R or database style. if __name__== "__main__": customers = [0,0,1,1,1,2,2,2,2] purchases = [0,3,5,1,2,4,1,3,5] print(get_brand_purchase_deets(customers, purchases))
40.615385
143
0.669192
96709cd14fd89b69849ecd83f84c39ac23149ad2
4,623
py
Python
ATSAMD51P19A/libsrc/ATSAMD51P19A/MPU_.py
t-ikegami/WioTerminal-CircuitPython
efbdc2e13ad969fe009d88f7ec4b836ca61ae973
[ "MIT" ]
null
null
null
ATSAMD51P19A/libsrc/ATSAMD51P19A/MPU_.py
t-ikegami/WioTerminal-CircuitPython
efbdc2e13ad969fe009d88f7ec4b836ca61ae973
[ "MIT" ]
1
2022-01-19T00:16:02.000Z
2022-01-26T03:43:34.000Z
ATSAMD51P19A/libsrc/ATSAMD51P19A/MPU_.py
t-ikegami/WioTerminal-CircuitPython
efbdc2e13ad969fe009d88f7ec4b836ca61ae973
[ "MIT" ]
null
null
null
import uctypes as ct MPU_ = { 'TYPE' : ( 0x00, { 'reg' : 0x00 | ct.UINT32, 'SEPARATE' : 0x00 | ct.BFUINT32 | 0 << ct.BF_POS | 1 << ct.BF_LEN, 'DREGION' : 0x00 | ct.BFUINT32 | 8 << ct.BF_POS | 8 << ct.BF_LEN, 'IREGION' : 0x00 | ct.BFUINT32 | 16 << ct.BF_POS | 8 << ct.BF_LEN, }), 'CTRL' : ( 0x04, { 'reg' : 0x00 | ct.UINT32, 'ENABLE' : 0x00 | ct.BFUINT32 | 0 << ct.BF_POS | 1 << ct.BF_LEN, 'HFNMIENA' : 0x00 | ct.BFUINT32 | 1 << ct.BF_POS | 1 << ct.BF_LEN, 'PRIVDEFENA' : 0x00 | ct.BFUINT32 | 2 << ct.BF_POS | 1 << ct.BF_LEN, }), 'RNR' : ( 0x08, { 'reg' : 0x00 | ct.UINT32, 'REGION' : 0x00 | ct.BFUINT32 | 0 << ct.BF_POS | 8 << ct.BF_LEN, }), 'RBAR' : ( 0x0C, { 'reg' : 0x00 | ct.UINT32, 'REGION' : 0x00 | ct.BFUINT32 | 0 << ct.BF_POS | 4 << ct.BF_LEN, 'VALID' : 0x00 | ct.BFUINT32 | 4 << ct.BF_POS | 1 << ct.BF_LEN, 'ADDR' : 0x00 | ct.BFUINT32 | 5 << ct.BF_POS | 27 << ct.BF_LEN, }), 'RASR' : ( 0x10, { 'reg' : 0x00 | ct.UINT32, 'ENABLE' : 0x00 | ct.BFUINT32 | 0 << ct.BF_POS | 1 << ct.BF_LEN, 'SIZE' : 0x00 | ct.BFUINT32 | 1 << ct.BF_POS | 1 << ct.BF_LEN, 'SRD' : 0x00 | ct.BFUINT32 | 8 << ct.BF_POS | 8 << ct.BF_LEN, 'B' : 0x00 | ct.BFUINT32 | 16 << ct.BF_POS | 1 << ct.BF_LEN, 'C' : 0x00 | ct.BFUINT32 | 17 << ct.BF_POS | 1 << ct.BF_LEN, 'S' : 0x00 | ct.BFUINT32 | 18 << ct.BF_POS | 1 << ct.BF_LEN, 'TEX' : 0x00 | ct.BFUINT32 | 19 << ct.BF_POS | 3 << ct.BF_LEN, 'AP' : 0x00 | ct.BFUINT32 | 24 << ct.BF_POS | 3 << ct.BF_LEN, 'XN' : 0x00 | ct.BFUINT32 | 28 << ct.BF_POS | 1 << ct.BF_LEN, }), 'RBAR_A1' : ( 0x14, { 'reg' : 0x00 | ct.UINT32, 'REGION' : 0x00 | ct.BFUINT32 | 0 << ct.BF_POS | 4 << ct.BF_LEN, 'VALID' : 0x00 | ct.BFUINT32 | 4 << ct.BF_POS | 1 << ct.BF_LEN, 'ADDR' : 0x00 | ct.BFUINT32 | 5 << ct.BF_POS | 27 << ct.BF_LEN, }), 'RASR_A1' : ( 0x18, { 'reg' : 0x00 | ct.UINT32, 'ENABLE' : 0x00 | ct.BFUINT32 | 0 << ct.BF_POS | 1 << ct.BF_LEN, 'SIZE' : 0x00 | ct.BFUINT32 | 1 << ct.BF_POS | 1 << ct.BF_LEN, 'SRD' : 0x00 | ct.BFUINT32 | 8 << ct.BF_POS | 8 << ct.BF_LEN, 'B' : 0x00 | ct.BFUINT32 | 16 << ct.BF_POS | 1 << ct.BF_LEN, 'C' : 0x00 | ct.BFUINT32 | 17 << ct.BF_POS | 1 << ct.BF_LEN, 'S' : 0x00 | ct.BFUINT32 | 18 << ct.BF_POS | 1 << ct.BF_LEN, 'TEX' : 0x00 | ct.BFUINT32 | 19 << ct.BF_POS | 3 << ct.BF_LEN, 'AP' : 0x00 | ct.BFUINT32 | 24 << ct.BF_POS | 3 << ct.BF_LEN, 'XN' : 0x00 | ct.BFUINT32 | 28 << ct.BF_POS | 1 << ct.BF_LEN, }), 'RBAR_A2' : ( 0x1C, { 'reg' : 0x00 | ct.UINT32, 'REGION' : 0x00 | ct.BFUINT32 | 0 << ct.BF_POS | 4 << ct.BF_LEN, 'VALID' : 0x00 | ct.BFUINT32 | 4 << ct.BF_POS | 1 << ct.BF_LEN, 'ADDR' : 0x00 | ct.BFUINT32 | 5 << ct.BF_POS | 27 << ct.BF_LEN, }), 'RASR_A2' : ( 0x20, { 'reg' : 0x00 | ct.UINT32, 'ENABLE' : 0x00 | ct.BFUINT32 | 0 << ct.BF_POS | 1 << ct.BF_LEN, 'SIZE' : 0x00 | ct.BFUINT32 | 1 << ct.BF_POS | 1 << ct.BF_LEN, 'SRD' : 0x00 | ct.BFUINT32 | 8 << ct.BF_POS | 8 << ct.BF_LEN, 'B' : 0x00 | ct.BFUINT32 | 16 << ct.BF_POS | 1 << ct.BF_LEN, 'C' : 0x00 | ct.BFUINT32 | 17 << ct.BF_POS | 1 << ct.BF_LEN, 'S' : 0x00 | ct.BFUINT32 | 18 << ct.BF_POS | 1 << ct.BF_LEN, 'TEX' : 0x00 | ct.BFUINT32 | 19 << ct.BF_POS | 3 << ct.BF_LEN, 'AP' : 0x00 | ct.BFUINT32 | 24 << ct.BF_POS | 3 << ct.BF_LEN, 'XN' : 0x00 | ct.BFUINT32 | 28 << ct.BF_POS | 1 << ct.BF_LEN, }), 'RBAR_A3' : ( 0x24, { 'reg' : 0x00 | ct.UINT32, 'REGION' : 0x00 | ct.BFUINT32 | 0 << ct.BF_POS | 4 << ct.BF_LEN, 'VALID' : 0x00 | ct.BFUINT32 | 4 << ct.BF_POS | 1 << ct.BF_LEN, 'ADDR' : 0x00 | ct.BFUINT32 | 5 << ct.BF_POS | 27 << ct.BF_LEN, }), 'RASR_A3' : ( 0x28, { 'reg' : 0x00 | ct.UINT32, 'ENABLE' : 0x00 | ct.BFUINT32 | 0 << ct.BF_POS | 1 << ct.BF_LEN, 'SIZE' : 0x00 | ct.BFUINT32 | 1 << ct.BF_POS | 1 << ct.BF_LEN, 'SRD' : 0x00 | ct.BFUINT32 | 8 << ct.BF_POS | 8 << ct.BF_LEN, 'B' : 0x00 | ct.BFUINT32 | 16 << ct.BF_POS | 1 << ct.BF_LEN, 'C' : 0x00 | ct.BFUINT32 | 17 << ct.BF_POS | 1 << ct.BF_LEN, 'S' : 0x00 | ct.BFUINT32 | 18 << ct.BF_POS | 1 << ct.BF_LEN, 'TEX' : 0x00 | ct.BFUINT32 | 19 << ct.BF_POS | 3 << ct.BF_LEN, 'AP' : 0x00 | ct.BFUINT32 | 24 << ct.BF_POS | 3 << ct.BF_LEN, 'XN' : 0x00 | ct.BFUINT32 | 28 << ct.BF_POS | 1 << ct.BF_LEN, }), } MPU = ct.struct(0xe000ed90, MPU_)
48.663158
76
0.499459
96724dd749d0959e504802c78aa325cae8171f97
8,550
py
Python
lib/core/postprocess.py
Chris1nexus/tmp
a76b477d491688add434f1ef84bcc0e2dbedbef3
[ "BSD-3-Clause" ]
null
null
null
lib/core/postprocess.py
Chris1nexus/tmp
a76b477d491688add434f1ef84bcc0e2dbedbef3
[ "BSD-3-Clause" ]
null
null
null
lib/core/postprocess.py
Chris1nexus/tmp
a76b477d491688add434f1ef84bcc0e2dbedbef3
[ "BSD-3-Clause" ]
null
null
null
import torch from lib.utils import is_parallel import numpy as np np.set_printoptions(threshold=np.inf) import cv2 from sklearn.cluster import DBSCAN def build_targets(cfg, predictions, targets, model, bdd=True): ''' predictions [16, 3, 32, 32, 85] [16, 3, 16, 16, 85] [16, 3, 8, 8, 85] torch.tensor(predictions[i].shape)[[3, 2, 3, 2]] [32,32,32,32] [16,16,16,16] [8,8,8,8] targets[3,x,7] t [index, class, x, y, w, h, head_index] ''' # Build targets for compute_loss(), input targets(image,class,x,y,w,h) if bdd: if is_parallel(model): det = model.module.det_out_bdd else: det = model.det_out_bdd else: if is_parallel(model): det = model.module.det_out_bosch else: det = model.det_out_bosch # print(type(model)) # det = model.model[model.detector_index] # print(type(det)) na, nt = det.na, targets.shape[0] # number of anchors, targets tcls, tbox, indices, anch = [], [], [], [] gain = torch.ones(7, device=targets.device) # normalized to gridspace gain ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt) targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices g = 0.5 # bias off = torch.tensor([[0, 0], [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm ], device=targets.device).float() * g # offsets for i in range(det.nl): anchors = det.anchors[i] #[3,2] gain[2:6] = torch.tensor(predictions[i].shape)[[3, 2, 3, 2]] # xyxy gain # Match targets to anchors t = targets * gain if nt: # Matches r = t[:, :, 4:6] / anchors[:, None] # wh ratio j = torch.max(r, 1. / r).max(2)[0] < cfg.TRAIN.ANCHOR_THRESHOLD # compare # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2)) t = t[j] # filter # Offsets gxy = t[:, 2:4] # grid xy gxi = gain[[2, 3]] - gxy # inverse j, k = ((gxy % 1. < g) & (gxy > 1.)).T l, m = ((gxi % 1. < g) & (gxi > 1.)).T j = torch.stack((torch.ones_like(j), j, k, l, m)) t = t.repeat((5, 1, 1))[j] offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j] else: t = targets[0] offsets = 0 # Define b, c = t[:, :2].long().T # image, class gxy = t[:, 2:4] # grid xy gwh = t[:, 4:6] # grid wh gij = (gxy - offsets).long() gi, gj = gij.T # grid xy indices # Append a = t[:, 6].long() # anchor indices indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices tbox.append(torch.cat((gxy - gij, gwh), 1)) # box anch.append(anchors[a]) # anchors tcls.append(c) # class return tcls, tbox, indices, anch def morphological_process(image, kernel_size=5, func_type=cv2.MORPH_CLOSE): """ morphological process to fill the hole in the binary segmentation result :param image: :param kernel_size: :return: """ if len(image.shape) == 3: raise ValueError('Binary segmentation result image should be a single channel image') if image.dtype is not np.uint8: image = np.array(image, np.uint8) kernel = cv2.getStructuringElement(shape=cv2.MORPH_ELLIPSE, ksize=(kernel_size, kernel_size)) # close operation fille hole closing = cv2.morphologyEx(image, func_type, kernel, iterations=1) return closing def connect_components_analysis(image): """ connect components analysis to remove the small components :param image: :return: """ if len(image.shape) == 3: gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) else: gray_image = image # print(gray_image.dtype) return cv2.connectedComponentsWithStats(gray_image, connectivity=8, ltype=cv2.CV_32S)
36.228814
119
0.535906
96736097d0c8c249aee5be77f87a2ac3b77a5f45
44
py
Python
name.py
dachuanz/crash-course
f7068e3ea502c1859e01f81772eafb179e5d2536
[ "MIT" ]
null
null
null
name.py
dachuanz/crash-course
f7068e3ea502c1859e01f81772eafb179e5d2536
[ "MIT" ]
null
null
null
name.py
dachuanz/crash-course
f7068e3ea502c1859e01f81772eafb179e5d2536
[ "MIT" ]
null
null
null
name = "ada lovelace" print(name.title())
14.666667
22
0.659091
96740cc6a710cea9535394b9dcdca4bd9278e075
11,578
py
Python
buildbot/runCI.py
DenisBakhvalov/perf-ninja
d9d0a7ff3984e7cc3823bca3a3f106e7fbc00da0
[ "CC-BY-3.0" ]
1
2021-08-06T08:54:55.000Z
2021-08-06T08:54:55.000Z
buildbot/runCI.py
DenisBakhvalov/perf-ninja
d9d0a7ff3984e7cc3823bca3a3f106e7fbc00da0
[ "CC-BY-3.0" ]
null
null
null
buildbot/runCI.py
DenisBakhvalov/perf-ninja
d9d0a7ff3984e7cc3823bca3a3f106e7fbc00da0
[ "CC-BY-3.0" ]
null
null
null
import sys import subprocess import os import shutil import argparse import json import re from enum import Enum from dataclasses import dataclass import gbench from gbench import util, report from gbench.util import * parser = argparse.ArgumentParser(description='test results') parser.add_argument("-workdir", type=str, help="working directory", default="") parser.add_argument("-v", help="verbose", action="store_true", default=False) args = parser.parse_args() workdir = args.workdir verbose = args.v Labs = dict() Labs["memory_bound"] = dict() Labs["core_bound"] = dict() Labs["bad_speculation"] = dict() Labs["frontend_bound"] = dict() Labs["data_driven"] = dict() Labs["misc"] = dict() Labs["memory_bound"]["data_packing"] = LabParams(threshold=15.0) Labs["memory_bound"]["loop_interchange_1"] = LabParams(threshold=85.0) Labs["memory_bound"]["loop_interchange_2"] = LabParams(threshold=75.0) Labs["misc"]["warmup"] = LabParams(threshold=50.0) Labs["core_bound"]["function_inlining_1"] = LabParams(threshold=35.0) Labs["core_bound"]["compiler_intrinsics_1"] = LabParams(threshold=60.0) Labs["core_bound"]["vectorization_1"] = LabParams(threshold=90.0) if not workdir: print ("Error: working directory is not provided.") sys.exit(1) os.chdir(workdir) checkAll = False benchLabPath = 0 DirLabPathRegex = re.compile(r'labs/(.*)/(.*)/') try: outputGitLog = subprocess.check_output("git log -1 --oneline" , shell=True) # If the commit message has '[CheckAll]' substring, benchmark everything if b'[CheckAll]' in outputGitLog: checkAll = True print("Will benchmark all the labs") # Otherwise, analyze the changes made in the last commit and identify which lab to benchmark else: outputGitShow = subprocess.check_output("git show -1 --dirstat --oneline" , shell=True) lines = outputGitShow.split(b'\n') # Expect at least 2 lines in the output if (len(lines) < 2 or len(lines[1]) == 0): print("Can't figure out which lab was changed in the last commit. Will benchmark all the labs.") checkAll = True elif changedMultipleLabs(lines): print("Multiple labs changed. Will benchmark all the labs.") checkAll = True else: # Skip the first line that has the commit hash and message percent, path = lines[1].split(b'%') GitShowLabPath = DirLabPathRegex.search(str(path)) if (GitShowLabPath): benchLabPath = LabPath(GitShowLabPath.group(1), GitShowLabPath.group(2)) print("Will benchmark the lab: " + getLabNameStr(benchLabPath)) else: print("Can't figure out which lab was changed in the last commit. Will benchmark all the labs.") checkAll = True except: print("Error: can't fetch the last commit from git history") sys.exit(1) result = False if checkAll: if not checkAllLabs(workdir): sys.exit(1) print(bcolors.HEADER + "\nLab Assignments Summary:" + bcolors.ENDC) allSkipped = True for category in Labs: print(bcolors.HEADER + " " + category + ":" + bcolors.ENDC) for lab in Labs[category]: if ScoreResult.SKIPPED == Labs[category][lab].result: print(bcolors.OKCYAN + " " + lab + ": Skipped" + bcolors.ENDC) else: allSkipped = False if ScoreResult.PASSED == Labs[category][lab].result: print(bcolors.OKGREEN + " " + lab + ": Passed" + bcolors.ENDC) # Return true if at least one lab succeeded result = True if ScoreResult.BENCH_FAILED == Labs[category][lab].result: print(bcolors.FAIL + " " + lab + ": Failed: not fast enough" + bcolors.ENDC) if ScoreResult.BUILD_FAILED == Labs[category][lab].result: print(bcolors.FAIL + " " + lab + ": Failed: build error" + bcolors.ENDC) if allSkipped: result = True else: labdir = os.path.join(workdir, benchLabPath.category, benchLabPath.name) if not buildLab(labdir, "solution"): sys.exit(1) if not checkoutBaseline(workdir): sys.exit(1) if not buildLab(labdir, "baseline"): sys.exit(1) if noChangesToTheBaseline(labdir): print(bcolors.OKCYAN + "The solution and the baseline are identical. Skipped." + bcolors.ENDC) result = True else: result = benchmarkLab(benchLabPath) if not result: sys.exit(1) else: sys.exit(0)
34.458333
175
0.70228
967557de1befe9d5c89674990959f86af65d7c4c
1,156
py
Python
main.py
TheSkidSlayer/VissageMassBanner
38f0a83ad9d625930cef5004787f8c4966312fd0
[ "BSL-1.0" ]
1
2021-12-31T23:15:47.000Z
2021-12-31T23:15:47.000Z
main.py
TheSkidSlayer/VissageMassBanner
38f0a83ad9d625930cef5004787f8c4966312fd0
[ "BSL-1.0" ]
null
null
null
main.py
TheSkidSlayer/VissageMassBanner
38f0a83ad9d625930cef5004787f8c4966312fd0
[ "BSL-1.0" ]
null
null
null
try: from concurrent.futures import ThreadPoolExecutor import random, time, os, httpx from colorama import Fore, Style except ImportError: print("Error [!] -> Modules Are not installed") token, guild = input("Token -> "), input("\nGuild ID -> ") threads = [] apiv = [6, 7, 8, 9] codes = [200, 201, 204] if __name__ == "__main__": theadpool()
24.083333
87
0.553633
9676900dd098082bdefdd8316547347e26bd4ef9
376
py
Python
panos/example_with_output_template/loader.py
nembery/Skillets
4c0a259d4fb49550605c5eb5316d83f109612271
[ "Apache-2.0" ]
1
2019-04-17T19:30:46.000Z
2019-04-17T19:30:46.000Z
panos/example_with_output_template/loader.py
nembery/Skillets
4c0a259d4fb49550605c5eb5316d83f109612271
[ "Apache-2.0" ]
null
null
null
panos/example_with_output_template/loader.py
nembery/Skillets
4c0a259d4fb49550605c5eb5316d83f109612271
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 from skilletlib import SkilletLoader sl = SkilletLoader('.') skillet = sl.get_skillet_with_name('panos_cli_example') context = dict() context['cli_command'] = 'show system info' context['username'] = 'admin' context['password'] = 'NOPE' context['ip_address'] = 'NOPE' output = skillet.execute(context) print(output.get('output_template', 'n/a'))
19.789474
55
0.723404
967705c9e8a9fd17fb6a029cb268db7aef64d726
198
py
Python
treasurehunt/views.py
code-haven/Django-treasurehunt-demo
c22aa88486d57fa97363d9d57dbbb7bc68a8ddd4
[ "MIT" ]
1
2017-04-30T05:46:40.000Z
2017-04-30T05:46:40.000Z
treasurehunt/views.py
code-haven/Django-treasurehunt-demo
c22aa88486d57fa97363d9d57dbbb7bc68a8ddd4
[ "MIT" ]
null
null
null
treasurehunt/views.py
code-haven/Django-treasurehunt-demo
c22aa88486d57fa97363d9d57dbbb7bc68a8ddd4
[ "MIT" ]
null
null
null
from django.views.generic import View from django.http import HttpResponse from django.shortcuts import render
33
66
0.823232
9677e8577eb71d6a56fc8178b8340df0cf85efc4
2,184
py
Python
setup.py
pletnes/cloud-pysec
4f91e3875ee36cb3e9b361e8b598070ce9523128
[ "Apache-2.0" ]
null
null
null
setup.py
pletnes/cloud-pysec
4f91e3875ee36cb3e9b361e8b598070ce9523128
[ "Apache-2.0" ]
null
null
null
setup.py
pletnes/cloud-pysec
4f91e3875ee36cb3e9b361e8b598070ce9523128
[ "Apache-2.0" ]
null
null
null
""" xssec setup """ import codecs from os import path from setuptools import setup, find_packages from sap.conf.config import USE_SAP_PY_JWT CURRENT_DIR = path.abspath(path.dirname(__file__)) README_LOCATION = path.join(CURRENT_DIR, 'README.md') VERSION = '' with open(path.join(CURRENT_DIR, 'version.txt'), 'r') as version_file: VERSION = version_file.read() with codecs.open(README_LOCATION, 'r', 'utf-8') as readme_file: LONG_DESCRIPTION = readme_file.read() sap_py_jwt_dep = '' if USE_SAP_PY_JWT: sap_py_jwt_dep = 'sap_py_jwt>=1.1.1' else: sap_py_jwt_dep = 'cryptography' setup( name='sap_xssec', url='https://github.com/SAP/cloud-pysec', version=VERSION.strip(), author='SAP SE', description=('SAP Python Security Library'), packages=find_packages(include=['sap*']), data_files=[('.', ['version.txt', 'CHANGELOG.md'])], test_suite='tests', install_requires=[ 'deprecation>=2.1.0', 'requests>=2.21.0', 'six>=1.11.0', 'pyjwt>=1.7.0', '{}'.format(sap_py_jwt_dep) ], long_description=LONG_DESCRIPTION, long_description_content_type="text/markdown", classifiers=[ # http://pypi.python.org/pypi?%3Aaction=list_classifiers "Development Status :: 5 - Production/Stable", "Topic :: Security", "License :: OSI Approved :: Apache Software License", "Natural Language :: English", "Operating System :: MacOS :: MacOS X", "Operating System :: POSIX", "Operating System :: POSIX :: BSD", "Operating System :: POSIX :: Linux", "Operating System :: Microsoft :: Windows", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", ], )
34.125
70
0.628663
96785881acee4c6b6e5fbf6dfa6bcd4a371b2db4
1,957
py
Python
mutators/implementations/mutation_change_proto.py
freingruber/JavaScript-Raider
d1c1fff2fcfc60f210b93dbe063216fa1a83c1d0
[ "Apache-2.0" ]
91
2022-01-24T07:32:34.000Z
2022-03-31T23:37:15.000Z
mutators/implementations/mutation_change_proto.py
zeusguy/JavaScript-Raider
d1c1fff2fcfc60f210b93dbe063216fa1a83c1d0
[ "Apache-2.0" ]
null
null
null
mutators/implementations/mutation_change_proto.py
zeusguy/JavaScript-Raider
d1c1fff2fcfc60f210b93dbe063216fa1a83c1d0
[ "Apache-2.0" ]
11
2022-01-24T14:21:12.000Z
2022-03-31T23:37:23.000Z
# Copyright 2022 @ReneFreingruber # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import utils import tagging_engine.tagging as tagging from tagging_engine.tagging import Tag import mutators.testcase_mutators_helpers as testcase_mutators_helpers
40.770833
131
0.772611
9678930e9778ab9e49deebe9a98a3436e67de53f
1,809
py
Python
homeassistant/components/smarthab/light.py
tbarbette/core
8e58c3aa7bc8d2c2b09b6bd329daa1c092d52d3c
[ "Apache-2.0" ]
22,481
2020-03-02T13:09:59.000Z
2022-03-31T23:34:28.000Z
homeassistant/components/smarthab/light.py
jagadeeshvenkatesh/core
1bd982668449815fee2105478569f8e4b5670add
[ "Apache-2.0" ]
31,101
2020-03-02T13:00:16.000Z
2022-03-31T23:57:36.000Z
homeassistant/components/smarthab/light.py
jagadeeshvenkatesh/core
1bd982668449815fee2105478569f8e4b5670add
[ "Apache-2.0" ]
11,411
2020-03-02T14:19:20.000Z
2022-03-31T22:46:07.000Z
"""Support for SmartHab device integration.""" from datetime import timedelta import logging import pysmarthab from requests.exceptions import Timeout from homeassistant.components.light import LightEntity from . import DATA_HUB, DOMAIN _LOGGER = logging.getLogger(__name__) SCAN_INTERVAL = timedelta(seconds=60)
26.602941
82
0.6534
9679546d86fe3d9ab266b6fcd96932146df7b271
406
py
Python
hello.py
AaronTrip/cgi-lab
cc932dfe21c27f3ca054233fe5bc73783facee6b
[ "Apache-2.0" ]
null
null
null
hello.py
AaronTrip/cgi-lab
cc932dfe21c27f3ca054233fe5bc73783facee6b
[ "Apache-2.0" ]
null
null
null
hello.py
AaronTrip/cgi-lab
cc932dfe21c27f3ca054233fe5bc73783facee6b
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 import os, json print("Content-type: text/html\r\n\r\n") print() print("<Title>Test CGI</title>") print("<p>Hello World cmput404 class!<p/>") print(os.environ) json_object = json.dumps(dict(os.environ), indent = 4) print(json_object) '''for param in os.environ.keys(): if(param == "HTTP_USER_AGENT"): print("<b>%20s<b/>: %s<br>" % (param, os.environ[param])) '''
18.454545
65
0.640394
96797b706de9c91fb5c25b82dfacdb6b113734eb
14,277
py
Python
VCD/utils/utils.py
Xingyu-Lin/VCD
46ca993f79b23e5c73f5a7eb72b39dfacf3b282c
[ "MIT" ]
25
2022-01-28T02:13:42.000Z
2022-03-19T15:33:38.000Z
VCD/utils/utils.py
Xingyu-Lin/VCD
46ca993f79b23e5c73f5a7eb72b39dfacf3b282c
[ "MIT" ]
2
2022-01-28T05:58:32.000Z
2022-01-30T11:37:50.000Z
VCD/utils/utils.py
Xingyu-Lin/VCD
46ca993f79b23e5c73f5a7eb72b39dfacf3b282c
[ "MIT" ]
4
2022-01-31T08:22:49.000Z
2022-02-17T16:28:32.000Z
import os.path as osp import numpy as np import cv2 import torch from torchvision.utils import make_grid from VCD.utils.camera_utils import project_to_image import pyflex import re import h5py import os from softgym.utils.visualization import save_numpy_as_gif from chester import logger import random # Function to extract all the numbers from the given string ################## Pointcloud Processing ################# import pcl # def get_partial_particle(full_particle, observable_idx): # return np.array(full_particle[observable_idx], dtype=np.float32) from softgym.utils.misc import vectorized_range, vectorized_meshgrid ################## IO ################################# def transform_info(all_infos): """ Input: All info is a nested list with the index of [episode][time]{info_key:info_value} Output: transformed_infos is a dictionary with the index of [info_key][episode][time] """ if len(all_infos) == 0: return [] transformed_info = {} num_episode = len(all_infos) T = len(all_infos[0]) for info_name in all_infos[0][0].keys(): infos = np.zeros([num_episode, T], dtype=np.float32) for i in range(num_episode): infos[i, :] = np.array([info[info_name] for info in all_infos[i]]) transformed_info[info_name] = infos return transformed_info ################## Visualization ###################### def visualize(env, particle_positions, shape_positions, config_id, sample_idx=None, picked_particles=None, show=False): """ Render point cloud trajectory without running the simulation dynamics""" env.reset(config_id=config_id) frames = [] for i in range(len(particle_positions)): particle_pos = particle_positions[i] shape_pos = shape_positions[i] p = pyflex.get_positions().reshape(-1, 4) p[:, :3] = [0., -0.1, 0.] # All particles moved underground if sample_idx is None: p[:len(particle_pos), :3] = particle_pos else: p[:, :3] = [0, -0.1, 0] p[sample_idx, :3] = particle_pos pyflex.set_positions(p) set_shape_pos(shape_pos) rgb = env.get_image(env.camera_width, env.camera_height) frames.append(rgb) if show: if i == 0: continue picked_point = picked_particles[i] phases = np.zeros(pyflex.get_n_particles()) for id in picked_point: if id != -1: phases[sample_idx[int(id)]] = 1 pyflex.set_phases(phases) img = env.get_image() cv2.imshow('picked particle images', img[:, :, ::-1]) cv2.waitKey() return frames ############################ Other ######################## def updateDictByAdd(dict1, dict2): ''' update dict1 by dict2 ''' for k1, v1 in dict2.items(): for k2, v2 in v1.items(): dict1[k1][k2] += v2.cpu().item() return dict1 ############### for planning ###############################
35.426799
128
0.6397
967f854c2cc3d7839a4210800ff6ac34aa126d0b
3,493
py
Python
tests/test_classes.py
fossabot/RPGenie
eb3ee17ede0dbbec787766d607b2f5b89d65533d
[ "MIT" ]
32
2017-09-03T21:14:17.000Z
2022-01-12T04:26:28.000Z
tests/test_classes.py
fossabot/RPGenie
eb3ee17ede0dbbec787766d607b2f5b89d65533d
[ "MIT" ]
9
2017-09-12T13:16:43.000Z
2022-01-19T18:53:48.000Z
tests/test_classes.py
fossabot/RPGenie
eb3ee17ede0dbbec787766d607b2f5b89d65533d
[ "MIT" ]
19
2017-10-12T03:14:54.000Z
2021-06-12T18:30:33.000Z
#! python3 """ Pytest-compatible tests for src/classes.py """ import sys from pathlib import Path from copy import deepcopy from unittest import mock # A workaround for tests not automatically setting # root/src/ as the current working directory path_to_src = Path(__file__).parent.parent / "src" sys.path.insert(0, str(path_to_src)) from classes import Item, Inventory, Player, Character from settings import * def initialiser(testcase): """ Initialises all test cases with data """ return inner def test_char_levelmixin(): """ Test for level-up functionality """ char = Character('John Doe', max_level = 5) assert 1 == char.level assert 85 == char.next_level assert char.give_exp(85) == f"Congratulations! You've levelled up; your new level is {char.level}\nEXP required for next level: {int(char.next_level-char.experience)}\nCurrent EXP: {char.experience}" for _ in range(char.max_level - char.level): char.give_exp(char.next_level) assert char.level == char.max_level assert char.give_exp(char.next_level) == f""
36.768421
203
0.678214
967fc22994b7e8387bc0009833f00fda8cc5c3ce
18,675
py
Python
biosteam/units/_shortcut_column.py
tylerhuntington222/biosteam
234959180a3210d95e39a012454f455723c92686
[ "MIT" ]
null
null
null
biosteam/units/_shortcut_column.py
tylerhuntington222/biosteam
234959180a3210d95e39a012454f455723c92686
[ "MIT" ]
null
null
null
biosteam/units/_shortcut_column.py
tylerhuntington222/biosteam
234959180a3210d95e39a012454f455723c92686
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # BioSTEAM: The Biorefinery Simulation and Techno-Economic Analysis Modules # Copyright (C) 2020, Yoel Cortes-Pena <yoelcortes@gmail.com> # # This module is under the UIUC open-source license. See # github.com/BioSTEAMDevelopmentGroup/biosteam/blob/master/LICENSE.txt # for license details. """ """ from ._binary_distillation import BinaryDistillation import flexsolve as flx from thermosteam.exceptions import InfeasibleRegion from thermosteam.equilibrium import DewPoint, BubblePoint import numpy as np __all__ = ('ShortcutColumn',) # %% Functions # %% class ShortcutColumn(BinaryDistillation, new_graphics=False): r""" Create a multicomponent distillation column that relies on the Fenske-Underwood-Gilliland method to solve for the theoretical design of the distillation column and the separation of non-keys [1]_.The Murphree efficiency (i.e. column efficiency) is based on the modified O'Connell correlation [2]_. The diameter is based on tray separation and flooding velocity [1]_ [3]_. Purchase costs are based on correlations compiled by Warren et. al. [4]_. Parameters ---------- ins : streams Inlet fluids to be mixed into the feed stage. outs : stream sequence * [0] Distillate * [1] Bottoms product LHK : tuple[str] Light and heavy keys. y_top : float Molar fraction of light key to the light and heavy keys in the distillate. x_bot : float Molar fraction of light key to the light and heavy keys in the bottoms product. Lr : float Recovery of the light key in the distillate. Hr : float Recovery of the heavy key in the bottoms product. k : float Ratio of reflux to minimum reflux. Rmin : float, optional User enforced minimum reflux ratio. If the actual minimum reflux ratio is less than `Rmin`, this enforced value is ignored. Defaults to 0.6. specification="Composition" : "Composition" or "Recovery" If composition is used, `y_top` and `x_bot` must be specified. If recovery is used, `Lr` and `Hr` must be specified. P=101325 : float Operating pressure [Pa]. vessel_material : str, optional Vessel construction material. Defaults to 'Carbon steel'. tray_material : str, optional Tray construction material. Defaults to 'Carbon steel'. tray_type='Sieve' : 'Sieve', 'Valve', or 'Bubble cap' Tray type. tray_spacing=450 : float Typically between 152 to 915 mm. stage_efficiency=None : User enforced stage efficiency. If None, stage efficiency is calculated by the O'Connell correlation [2]_. velocity_fraction=0.8 : float Fraction of actual velocity to maximum velocity allowable before flooding. foaming_factor=1.0 : float Must be between 0 to 1. open_tray_area_fraction=0.1 : float Fraction of open area to active area of a tray. downcomer_area_fraction=None : float Enforced fraction of downcomer area to net (total) area of a tray. If None, estimate ratio based on Oliver's estimation [1]_. is_divided=False : bool True if the stripper and rectifier are two separate columns. References ---------- .. [1] J.D. Seader, E.J. Henley, D.K. Roper. (2011) Separation Process Principles 3rd Edition. John Wiley & Sons, Inc. .. [2] M. Duss, R. Taylor. (2018) Predict Distillation Tray Efficiency. AICHE .. [3] Green, D. W. Distillation. In Perrys Chemical Engineers Handbook, 9 ed.; McGraw-Hill Education, 2018. .. [4] Seider, W. D., Lewin, D. R., Seader, J. D., Widagdo, S., Gani, R., & Ng, M. K. (2017). Product and Process Design Principles. Wiley. Cost Accounting and Capital Cost Estimation (Chapter 16) Examples -------- >>> from biosteam.units import ShortcutColumn >>> from biosteam import Stream, settings >>> settings.set_thermo(['Water', 'Methanol', 'Glycerol']) >>> feed = Stream('feed', flow=(80, 100, 25)) >>> bp = feed.bubble_point_at_P() >>> feed.T = bp.T # Feed at bubble point T >>> D1 = ShortcutColumn('D1', ins=feed, ... outs=('distillate', 'bottoms_product'), ... LHK=('Methanol', 'Water'), ... y_top=0.99, x_bot=0.01, k=2, ... is_divided=True) >>> D1.simulate() >>> # See all results >>> D1.show(T='degC', P='atm', composition=True) ShortcutColumn: D1 ins... [0] feed phase: 'l', T: 76.129 degC, P: 1 atm composition: Water 0.39 Methanol 0.488 Glycerol 0.122 -------- 205 kmol/hr outs... [0] distillate phase: 'g', T: 64.91 degC, P: 1 atm composition: Water 0.01 Methanol 0.99 -------- 100 kmol/hr [1] bottoms_product phase: 'l', T: 100.06 degC, P: 1 atm composition: Water 0.754 Methanol 0.00761 Glycerol 0.239 -------- 105 kmol/hr >>> D1.results() Distillation Units D1 Cooling water Duty kJ/hr -7.9e+06 Flow kmol/hr 5.4e+03 Cost USD/hr 2.64 Low pressure steam Duty kJ/hr 1.43e+07 Flow kmol/hr 368 Cost USD/hr 87.5 Design Theoretical feed stage 8 Theoretical stages 16 Minimum reflux Ratio 1.06 Reflux Ratio 2.12 Rectifier stages 13 Stripper stages 26 Rectifier height ft 31.7 Stripper height ft 50.9 Rectifier diameter ft 4.53 Stripper diameter ft 3.67 Rectifier wall thickness in 0.312 Stripper wall thickness in 0.312 Rectifier weight lb 6.46e+03 Stripper weight lb 7.98e+03 Purchase cost Rectifier trays USD 1.52e+04 Stripper trays USD 2.02e+04 Rectifier tower USD 8.44e+04 Stripper tower USD 1.01e+05 Condenser USD 4.17e+04 Boiler USD 2.99e+04 Total purchase cost USD 2.92e+05 Utility cost USD/hr 90.1 """ line = 'Distillation' _ins_size_is_fixed = False _N_ins = 1 _N_outs = 2
42.636986
148
0.584257
9681b53ab62bfb5ddd55b122e2a997c7da50a56f
11,477
py
Python
vital/bindings/python/vital/types/camera_intrinsics.py
dstoup/kwiver
a3a36317b446baf0feb6274235ab1ac6b4329ead
[ "BSD-3-Clause" ]
null
null
null
vital/bindings/python/vital/types/camera_intrinsics.py
dstoup/kwiver
a3a36317b446baf0feb6274235ab1ac6b4329ead
[ "BSD-3-Clause" ]
null
null
null
vital/bindings/python/vital/types/camera_intrinsics.py
dstoup/kwiver
a3a36317b446baf0feb6274235ab1ac6b4329ead
[ "BSD-3-Clause" ]
null
null
null
""" ckwg +31 Copyright 2016 by Kitware, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither name of Kitware, Inc. nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ============================================================================== Interface to VITAL camera_intrinsics objects """ import collections import ctypes import numpy from vital.types.eigen import EigenArray from vital.util import VitalErrorHandle, VitalObject def as_matrix(self): """ Access the intrinsics as an upper triangular matrix **Note:** *This matrix includes the focal length, principal point, aspect ratio, and skew, but does not model distortion.* :return: 3x3 upper triangular matrix """ f = self.VITAL_LIB['vital_camera_intrinsics_as_matrix'] f.argtypes = [self.C_TYPE_PTR, VitalErrorHandle.C_TYPE_PTR] f.restype = EigenArray.c_ptr_type(3, 3, ctypes.c_double) with VitalErrorHandle() as eh: m_ptr = f(self, eh) return EigenArray(3, 3, from_cptr=m_ptr, owns_data=True) def map_2d(self, norm_pt): """ Map normalized image coordinates into actual image coordinates This function applies both distortion and application of the calibration matrix to map into actual image coordinates. :param norm_pt: Normalized image coordinate to map to an image coordinate (2-element sequence). :type norm_pt: collections.Sequence[float] :return: Mapped 2D image coordinate :rtype: EigenArray[float] """ assert len(norm_pt) == 2, "Input sequence was not of length 2" f = self.VITAL_LIB['vital_camera_intrinsics_map_2d'] f.argtypes = [self.C_TYPE_PTR, EigenArray.c_ptr_type(2, 1, ctypes.c_double), VitalErrorHandle.C_TYPE_PTR] f.restype = EigenArray.c_ptr_type(2, 1, ctypes.c_double) p = EigenArray(2) p.T[:] = norm_pt with VitalErrorHandle() as eh: m_ptr = f(self, p, eh) return EigenArray(2, 1, from_cptr=m_ptr, owns_data=True) def map_3d(self, norm_hpt): """ Map a 3D point in camera coordinates into actual image coordinates :param norm_hpt: Normalized coordinate to map to an image coordinate (3-element sequence) :type norm_hpt: collections.Sequence[float] :return: Mapped 2D image coordinate :rtype: EigenArray[float] """ assert len(norm_hpt) == 3, "Input sequence was not of length 3" f = self.VITAL_LIB['vital_camera_intrinsics_map_3d'] f.argtypes = [self.C_TYPE_PTR, EigenArray.c_ptr_type(3, 1, ctypes.c_double), VitalErrorHandle.C_TYPE_PTR] f.restype = EigenArray.c_ptr_type(2, 1, ctypes.c_double) p = EigenArray(3) p.T[:] = norm_hpt with VitalErrorHandle() as eh: m_ptr = f(self, p, eh) return EigenArray(2, 1, from_cptr=m_ptr, owns_data=True) def unmap_2d(self, pt): """ Unmap actual image coordinates back into normalized image coordinates This function applies both application of the inverse calibration matrix and undistortion of the normalized coordinates :param pt: Actual image 2D point to un-map. :return: Un-mapped normalized image coordinate. """ assert len(pt) == 2, "Input sequence was not of length 2" f = self.VITAL_LIB['vital_camera_intrinsics_unmap_2d'] f.argtypes = [self.C_TYPE_PTR, EigenArray.c_ptr_type(2, 1, ctypes.c_double), VitalErrorHandle.C_TYPE_PTR] f.restype = EigenArray.c_ptr_type(2, 1, ctypes.c_double) p = EigenArray(2) p.T[:] = pt with VitalErrorHandle() as eh: m_ptr = f(self, p, eh) return EigenArray(2, 1, from_cptr=m_ptr, owns_data=True) def distort_2d(self, norm_pt): """ Map normalized image coordinates into distorted coordinates :param norm_pt: Normalized 2D image coordinate. :return: Distorted 2D coordinate. """ assert len(norm_pt) == 2, "Input sequence was not of length 2" f = self.VITAL_LIB['vital_camera_intrinsics_distort_2d'] f.argtypes = [self.C_TYPE_PTR, EigenArray.c_ptr_type(2, 1, ctypes.c_double), VitalErrorHandle.C_TYPE_PTR] f.restype = EigenArray.c_ptr_type(2, 1, ctypes.c_double) p = EigenArray(2) p.T[:] = norm_pt with VitalErrorHandle() as eh: m_ptr = f(self, p, eh) return EigenArray(2, 1, from_cptr=m_ptr, owns_data=True) def undistort_2d(self, dist_pt): """ Unmap distorted normalized coordinates into normalized coordinates :param dist_pt: Distorted 2D coordinate to un-distort. :return: Normalized 2D image coordinate. """ assert len(dist_pt) == 2, "Input sequence was not of length 2" f = self.VITAL_LIB['vital_camera_intrinsics_undistort_2d'] f.argtypes = [self.C_TYPE_PTR, EigenArray.c_ptr_type(2, 1, ctypes.c_double), VitalErrorHandle.C_TYPE_PTR] f.restype = EigenArray.c_ptr_type(2, 1, ctypes.c_double) p = EigenArray(2) p.T[:] = dist_pt with VitalErrorHandle() as eh: m_ptr = f(self, p, eh) return EigenArray(2, 1, from_cptr=m_ptr, owns_data=True)
38.773649
80
0.640673
9681c77a186723aca18c1c0fe154bf16a7a4024b
2,333
py
Python
utils/lanzouyun.py
Firesuiry/jdmm-client
33defde409222ae49c6301cec3389ca72d19953c
[ "BSD-3-Clause" ]
null
null
null
utils/lanzouyun.py
Firesuiry/jdmm-client
33defde409222ae49c6301cec3389ca72d19953c
[ "BSD-3-Clause" ]
null
null
null
utils/lanzouyun.py
Firesuiry/jdmm-client
33defde409222ae49c6301cec3389ca72d19953c
[ "BSD-3-Clause" ]
null
null
null
from lanzou.api import LanZouCloud import urllib.parse final_files = [] final_share_infos = [] cookies = ''' ''' if __name__ == '__main__': test()
25.637363
110
0.582512
9681dcb1c6a4a00147da8d82baecc6e355120cf5
1,948
py
Python
util/ndcg.py
voschezang/Data-Mining
0762df1d9a63f81d6f44d8a35cc61802baad4c37
[ "MIT" ]
null
null
null
util/ndcg.py
voschezang/Data-Mining
0762df1d9a63f81d6f44d8a35cc61802baad4c37
[ "MIT" ]
null
null
null
util/ndcg.py
voschezang/Data-Mining
0762df1d9a63f81d6f44d8a35cc61802baad4c37
[ "MIT" ]
null
null
null
import numpy as np import util.data
27.828571
75
0.569302
9681fb5a4ab9afe1cfd4688c372d7a335ae0a5d6
4,364
py
Python
pycorrector/bert/bert_detector.py
zouning68/pycorrector
4daaf13e566f2cecc724fb5a77db5d89f1f25203
[ "Apache-2.0" ]
45
2020-01-18T03:46:07.000Z
2022-03-26T13:06:36.000Z
pycorrector/bert/bert_detector.py
zouning68/pycorrector
4daaf13e566f2cecc724fb5a77db5d89f1f25203
[ "Apache-2.0" ]
1
2020-08-16T12:42:05.000Z
2020-08-16T12:42:05.000Z
pycorrector/bert/bert_detector.py
zouning68/pycorrector
4daaf13e566f2cecc724fb5a77db5d89f1f25203
[ "Apache-2.0" ]
9
2020-01-04T09:09:01.000Z
2022-01-17T08:56:23.000Z
# -*- coding: utf-8 -*- """ @author:XuMingxuming624@qq.com) @description: use bert detect chinese char error """ import sys import time import numpy as np import torch from pytorch_transformers import BertForMaskedLM from pytorch_transformers import BertTokenizer sys.path.append('../..') from pycorrector.detector import ErrorType from pycorrector.utils.logger import logger from pycorrector.bert import config if __name__ == "__main__": d = BertDetector() error_sentences = ['', '', ' ', ' ', '', ''] t1 = time.time() for sent in error_sentences: err = d.detect(sent) print("original sentence:{} => detect sentence:{}".format(sent, err))
35.770492
107
0.613886
968244c4e4821aa3176a5163d517e2a86b8ed427
98
py
Python
example_app/core/models/input.py
dazza-codes/serverless-fast-api
c4cdce62326a22778157a8555b7cdaafc2519b8d
[ "MIT" ]
2
2021-01-22T12:27:59.000Z
2021-09-09T14:54:11.000Z
example_app/core/models/input.py
dazza-codes/serverless-fast-api
c4cdce62326a22778157a8555b7cdaafc2519b8d
[ "MIT" ]
4
2020-05-03T01:54:53.000Z
2021-01-21T18:20:27.000Z
example_app/core/models/input.py
dazza-codes/serverless-fast-api
c4cdce62326a22778157a8555b7cdaafc2519b8d
[ "MIT" ]
1
2021-09-09T14:49:54.000Z
2021-09-09T14:49:54.000Z
from pydantic import BaseModel
14
30
0.622449
9683761b0e8ad668daa9ae8b7d5e998f46a35736
9,609
py
Python
2020/8/input.py
sishtiaq/aoc
1c200ebed048bbd8ad6a684aaef8921d826f3d1b
[ "Apache-2.0" ]
null
null
null
2020/8/input.py
sishtiaq/aoc
1c200ebed048bbd8ad6a684aaef8921d826f3d1b
[ "Apache-2.0" ]
null
null
null
2020/8/input.py
sishtiaq/aoc
1c200ebed048bbd8ad6a684aaef8921d826f3d1b
[ "Apache-2.0" ]
null
null
null
test = [ 'nop +0', 'acc +1', 'jmp +4', 'acc +3', 'jmp -3', 'acc -99', 'acc +1', 'jmp -4', 'acc +6', ] actual = [ 'acc +17', 'acc +37', 'acc -13', 'jmp +173', 'nop +100', 'acc -7', 'jmp +447', 'nop +283', 'acc +41', 'acc +32', 'jmp +1', 'jmp +585', 'jmp +1', 'acc -5', 'nop +71', 'acc +49', 'acc -18', 'jmp +527', 'jmp +130', 'jmp +253', 'acc +11', 'acc -11', 'jmp +390', 'jmp +597', 'jmp +1', 'acc +6', 'acc +0', 'jmp +588', 'acc -17', 'jmp +277', 'acc +2', 'nop +163', 'jmp +558', 'acc +38', 'jmp +369', 'acc +13', 'jmp +536', 'acc +38', 'acc +39', 'acc +6', 'jmp +84', 'acc +11', 'nop +517', 'acc +48', 'acc +47', 'jmp +1', 'acc +42', 'acc +0', 'acc +2', 'acc +24', 'jmp +335', 'acc +44', 'acc +47', 'jmp +446', 'nop +42', 'nop +74', 'acc +45', 'jmp +548', 'jmp +66', 'acc +1', 'jmp +212', 'acc +18', 'jmp +1', 'acc +4', 'acc -16', 'jmp +366', 'acc +0', 'jmp +398', 'acc +45', 'jmp +93', 'acc +40', 'acc +38', 'acc +21', 'nop +184', 'jmp -46', 'nop -9', 'jmp +53', 'acc +46', 'acc +36', 'jmp +368', 'acc +16', 'acc +8', 'acc -9', 'acc -4', 'jmp +328', 'acc -15', 'acc -5', 'acc +21', 'jmp +435', 'acc -5', 'acc +36', 'jmp +362', 'acc +26', 'jmp +447', 'jmp +1', 'jmp +412', 'acc +11', 'acc +41', 'nop -32', 'acc +17', 'jmp -63', 'jmp +1', 'nop +393', 'jmp +62', 'acc +18', 'acc +30', 'nop +417', 'jmp +74', 'acc +29', 'acc +23', 'jmp +455', 'jmp +396', 'jmp +395', 'acc +33', 'nop +137', 'nop +42', 'jmp +57', 'jmp +396', 'acc +7', 'acc +0', 'jmp +354', 'acc +15', 'acc +50', 'jmp -12', 'jmp +84', 'nop +175', 'acc +5', 'acc -2', 'jmp -82', 'acc +1', 'acc +26', 'jmp +288', 'nop -113', 'nop +366', 'acc +45', 'jmp +388', 'acc +21', 'acc +38', 'jmp +427', 'acc +33', 'jmp -94', 'nop -118', 'nop +411', 'jmp +472', 'nop +231', 'nop +470', 'acc +48', 'jmp -124', 'jmp +1', 'acc +5', 'acc +37', 'acc +42', 'jmp +301', 'acc -11', 'acc -17', 'acc +14', 'jmp +357', 'acc +6', 'acc +20', 'acc +13', 'jmp +361', 'jmp -65', 'acc +29', 'jmp +26', 'jmp +329', 'acc +32', 'acc +32', 'acc +17', 'jmp -102', 'acc -6', 'acc +33', 'acc +9', 'jmp +189', 'acc +3', 'jmp -128', 'jmp -142', 'acc +24', 'acc -5', 'jmp +403', 'acc +28', 'jmp +310', 'acc +34', 'acc +4', 'acc +33', 'acc +18', 'jmp +227', 'acc -8', 'acc -15', 'jmp +112', 'jmp +54', 'acc +21', 'acc +23', 'acc +20', 'jmp +320', 'acc +13', 'jmp -77', 'acc +15', 'nop +310', 'nop +335', 'jmp +232', 'acc -3', 'nop +50', 'acc +41', 'jmp +112', 'nop -10', 'acc +29', 'acc +27', 'jmp +52', 'acc +40', 'nop -132', 'acc -16', 'acc +27', 'jmp +309', 'acc -8', 'nop +147', 'acc +20', 'acc +46', 'jmp +202', 'acc +27', 'jmp -43', 'jmp +1', 'acc +33', 'acc -13', 'jmp +300', 'acc +1', 'jmp -202', 'acc -17', 'acc +0', 'acc +34', 'jmp -5', 'nop +335', 'acc -16', 'acc -17', 'jmp -120', 'acc -19', 'acc -13', 'acc +4', 'jmp +368', 'jmp +21', 'acc +39', 'acc +39', 'acc -18', 'jmp -157', 'nop +280', 'acc +33', 'nop -37', 'jmp +32', 'acc -16', 'acc +18', 'acc +46', 'jmp -121', 'acc -19', 'jmp +195', 'acc +28', 'jmp +124', 'jmp +331', 'jmp -228', 'jmp -146', 'jmp +85', 'jmp +60', 'acc +20', 'acc -9', 'jmp +303', 'jmp -122', 'jmp +111', 'acc +32', 'acc +0', 'acc +39', 'acc +29', 'jmp -31', 'nop +320', 'jmp -63', 'jmp +223', 'nop -149', 'acc -12', 'acc -11', 'acc +32', 'jmp +309', 'jmp -13', 'acc -19', 'jmp -123', 'acc +21', 'acc +18', 'acc +49', 'jmp +175', 'acc -14', 'nop -129', 'acc -2', 'acc +31', 'jmp +79', 'acc +23', 'acc +50', 'acc +39', 'acc +7', 'jmp -235', 'jmp -166', 'acc +9', 'jmp +293', 'acc -11', 'jmp +76', 'acc +44', 'acc +3', 'acc +37', 'jmp +123', 'nop -104', 'jmp -157', 'acc +14', 'acc +10', 'acc +28', 'jmp +25', 'acc +37', 'jmp +188', 'jmp -49', 'acc -11', 'jmp -90', 'acc -8', 'jmp +197', 'acc +5', 'jmp +115', 'acc +44', 'jmp -228', 'nop -2', 'acc +46', 'jmp +130', 'nop +183', 'nop +106', 'acc +27', 'acc +37', 'jmp -309', 'acc +28', 'acc -4', 'acc -12', 'acc +38', 'jmp +93', 'acc +8', 'acc +23', 'acc -9', 'acc +6', 'jmp -42', 'acc +10', 'acc +35', 'acc +4', 'jmp -231', 'acc +19', 'acc +7', 'acc +23', 'acc +11', 'jmp -90', 'acc +0', 'nop +158', 'nop -150', 'acc +33', 'jmp +107', 'acc +48', 'acc -2', 'jmp -104', 'acc +6', 'nop -57', 'nop +172', 'acc -11', 'jmp -7', 'acc +6', 'acc +50', 'acc -9', 'acc +12', 'jmp -171', 'acc +3', 'jmp +26', 'acc +42', 'acc +31', 'acc +20', 'acc +32', 'jmp -48', 'acc +13', 'jmp -6', 'jmp +178', 'acc +47', 'jmp -153', 'acc +28', 'nop +74', 'jmp -162', 'acc -15', 'nop -104', 'acc -9', 'jmp -227', 'acc +49', 'acc -19', 'acc +41', 'jmp -318', 'acc +9', 'acc +12', 'acc +7', 'jmp +34', 'jmp +137', 'nop -143', 'acc -8', 'acc +5', 'acc +31', 'jmp -20', 'jmp -237', 'acc +39', 'acc +0', 'jmp -298', 'acc +45', 'acc -19', 'acc +11', 'jmp -151', 'acc +40', 'acc +27', 'nop +150', 'nop -391', 'jmp -341', 'acc +1', 'acc +11', 'acc +18', 'nop -234', 'jmp +77', 'nop +104', 'jmp -65', 'acc +32', 'jmp -27', 'nop -317', 'nop +159', 'acc +14', 'acc -10', 'jmp -348', 'acc +29', 'jmp +32', 'acc +48', 'acc -19', 'jmp +17', 'jmp -201', 'jmp -224', 'nop +26', 'acc -7', 'acc +23', 'acc +46', 'jmp -6', 'acc +22', 'acc +39', 'acc +9', 'acc +23', 'jmp -30', 'jmp -243', 'acc +47', 'acc -15', 'jmp -298', 'jmp -393', 'jmp +1', 'acc +3', 'nop -24', 'acc +7', 'jmp -59', 'acc -6', 'acc +26', 'jmp -102', 'acc +34', 'acc +24', 'jmp -207', 'acc +36', 'acc +40', 'acc +41', 'jmp +1', 'jmp -306', 'jmp +57', 'jmp +1', 'nop +99', 'acc +28', 'jmp -391', 'acc +50', 'jmp -359', 'acc -5', 'jmp +9', 'jmp -355', 'acc +5', 'acc +2', 'jmp -77', 'acc +40', 'acc +28', 'acc +22', 'jmp -262', 'nop -287', 'acc +34', 'acc -4', 'nop +112', 'jmp -195', 'acc +29', 'nop -94', 'nop -418', 'jmp +24', 'jmp -190', 'acc +2', 'jmp -311', 'jmp -178', 'jmp -276', 'acc -12', 'acc -18', 'jmp +62', 'jmp -174', 'nop +31', 'acc +33', 'nop -158', 'jmp -417', 'acc +3', 'acc +21', 'acc +47', 'jmp +87', 'acc +45', 'jmp -77', 'acc +6', 'acc -10', 'jmp +1', 'jmp -240', 'acc +7', 'acc +47', 'jmp -379', 'acc -14', 'acc +50', 'nop -75', 'acc +30', 'jmp +70', 'jmp -392', 'jmp -430', 'acc +22', 'acc -2', 'jmp -492', 'jmp +1', 'acc -6', 'acc +38', 'jmp -36', 'nop -336', 'jmp -32', 'jmp +61', 'acc +20', 'acc -9', 'acc +2', 'jmp -175', 'acc +21', 'acc -2', 'jmp -6', 'jmp -527', 'acc +11', 'acc +16', 'jmp -262', 'jmp +1', 'nop -327', 'acc +29', 'jmp -114', 'acc +11', 'acc +17', 'acc +26', 'nop -104', 'jmp -428', 'nop -178', 'nop -242', 'acc +29', 'acc +5', 'jmp -245', 'jmp -417', 'jmp -278', 'acc +35', 'acc +21', 'jmp +1', 'nop -263', 'jmp +8', 'acc +42', 'jmp -95', 'nop -312', 'acc -11', 'acc +34', 'acc +0', 'jmp +19', 'acc +8', 'acc -13', 'acc +32', 'acc +21', 'jmp -208', 'acc +15', 'acc +39', 'nop -194', 'jmp -280', 'jmp +24', 'nop -516', 'acc +21', 'acc +48', 'jmp -367', 'jmp -121', 'acc +49', 'acc -16', 'jmp -136', 'acc +0', 'jmp -148', 'jmp -85', 'jmp -103', 'nop -446', 'jmp -242', 'acc -12', 'acc +13', 'acc +31', 'acc -1', 'jmp -435', 'nop -420', 'acc +22', 'acc -5', 'jmp -567', 'nop -354', 'acc +11', 'acc +33', 'acc +45', 'jmp -76', 'acc -2', 'acc +0', 'acc +25', 'acc +46', 'jmp -555', 'acc +0', 'acc +11', 'nop -2', 'jmp -394', 'jmp -395', 'acc +8', 'acc +14', 'acc +47', 'acc +22', 'jmp +1',]
15.037559
15
0.338329
96856b2747e7c36d91fb23b1dc5b4f022aab0d68
17,925
py
Python
islecler.py
mrtyasar/PythonLearn
b8fa5d97b9c811365db8457f42f1e1d04e4dc8a4
[ "Apache-2.0" ]
null
null
null
islecler.py
mrtyasar/PythonLearn
b8fa5d97b9c811365db8457f42f1e1d04e4dc8a4
[ "Apache-2.0" ]
null
null
null
islecler.py
mrtyasar/PythonLearn
b8fa5d97b9c811365db8457f42f1e1d04e4dc8a4
[ "Apache-2.0" ]
null
null
null
#----------------------------------# ######### ARTMETK LELER ####### #----------------------------------# # + toplama # - karma # * arpma # / blme # ** kuvvet # % modls/kalan bulma # // taban blme/ tam blme #aritmetik ileler saysal ilemler yapmamz salar print(45+57)#102 #yalnz + ve * iaretleri karakter dizileri iinde kullanlabilir #karakter dizilerini birletirmek iin + iareti print("Selam "+"Bugn "+"Hava ok gzel.")#Selam Bugn Hava ok gzel. # * iareti karakter dizileri tekrarlamak iin kullanlabilir print("w"*3+".tnbc1"+".com")#www.tnbc1.com # % ileci saynn blmnden kalan bulur print(30 % 4)#2 #saynn kalann bularak tek mi ift mi olduunu bulabiliriz sayi = int(input("Bir say giriniz: ")) if sayi % 2 == 0: print("Girdiiniz say bir ift saydr.") else: print("Girdiiniz say bir tek saydr.") #eer bir saynn 2 ye blmnden kalan 0 ise o say ift bir saydr #veya bu % ileci ile saynn baka bir say ile tam blnp blnmediini # bulabiliriz print(36 % 9)#0 #yani 36 9 a tam blnyor #program yazalm: bolunen = int(input("Herhangi bir say giriniz: ")) bolen = int(input("Herhangi bir say daha giriniz: ")) sablon = "{} says {} saysna tam".format(bolunen,bolen) if bolunen % bolen == 0: print(sablon,"blnyor!") else: print(sablon,"blnmyor!") #kt: #Herhangi bir say giriniz: 2876 #Herhangi bir say daha giriniz: 123 #2876 says 123 saysna tam blnmyor! # bir saynn son basaman elde etmek iinde kullanabiliriz #bu yzden bir saynn 10 blmnde kalann buluruz print(65 % 10)#5 print(543 % 10)#3 #----------------# #--//-tam blme--# #----------------# a = 6 / 3 print(type(a))#float # 2.0 #pythonda saylarn blmelerin sonucu kesirli olur yani float tipinde b = 6 // 3 print(b)#3 print(type(b))#int #tam blebildik print(int(a))#2 # bu ekilde de float tipini inte evirebildik #----------------# # ROUND # #----------------# #round() bir gml fonksiyondur #bu fonksiyonun bir saynn deerini yuvarlamamz salar print(round(2.70))#3 print(round(2.30))#2 print(round(5.68,1))#5.7 print(round(5.68,2))#5.68 print(round(7.9,2))#7.9 #-----------------# # ** # #-----------------# #bir saynn karesini bulmak #bunun iin 2 rakamna ihityacmz vardr print(124**2)#15376 #bir saynn karakkn bulmak #karakkn bulmak iin 0.5 e ihtiyacmz vardr print(625 ** 0.5)#25.0 #eer ondalkl say yani float tipli say istemiyorsak #ifadeyi ilemi int tipine evirmemiz gerekir print(int(625 ** 0.5))#25 #bir saynn kpn bulmak #kpn bulmak iin 3 rakamna ihtiyacmz vardr print(124 ** 3)#1906624 #bu ilemleri pow() fonksiyonlar ile de yapabiliriz print(pow(24,3))#13824 print(pow(96,2))#9216 #-------------------------------------# # KARILATIRMA LELER # #-------------------------------------# #ilenenler arasnda bir karlatrma ilikisi kuran ilelerdir # == eittir # != eit deildir # > byktr # < kktr # >= byk eittir # <= kk eittir parola = "xyz05" soru = input("parolanz: ") if soru == parola: print("doru parola!") elif soru != parola: print("yanl parola!") #baka bir rnek: sayi = input("say: ") if int(sayi) <= 100: print("say 100 veya 100'den kk") elif int(sayi) >= 100: print("say 100 veya 100'den byk") #-------------------------# # BOOL LELER # #-------------------------# #bool da sadece iki deer vardr true ve false #bilgisayar biliminde olduu gibi 0 false dir 1 true dur a = 1 print(a == 1)#a deeri 1 e eit midir? #True print(a == 2)#False # o deeri ve bo veri tipleri False'Dir # bunun haricinde kalan her ey True #bu durumu bool() adl fonksiyondan yararlanarak renebiliriz print(bool(4))#True print(bool("armut"))#True print(bool(" "))#True print(bool(2288281))#True print(bool("0"))#True print(bool(0))#False print(bool(""))#False #bool deerleri yazlm dnyasnda nemli bir yeri vardr #daha nce kullandm koul bloglarnda koulun gereklemesi #veya gereklememesi bool a baldr yan, true ve false isim = input("isminiz: ") if isim == "Ferhat": print("Ne gzel bir isminiz vardr") else: print(isim,"ismini pek sevmem!") #isminiz: caner #caner ismini pek sevmem! # eer diyoruz isim ferhat ifadesi true ise unu gster diyoruz # eer true deeri dnda herhangi bir ey yani false ise unu gster diyoruz isim = input("isminiz: ") print(isim == "Ferhat")#True # b = "" print(bool(b))#False #ii bo veri tiplerin her zaman false olacan bilerek yle #program yazabiliriz: kullanici = input("Kullanc adnz: ") if bool(kullanici) == True: print("Teekkrler") else: print("Kullanc ad alan bo braklamaz!") # eer kullanc bir eyler yazarsa bool(kullanici) komutu true verecek # ekrana teekkrler yazs yazlacak # eer kullanc bir ey yazmadan entera tklar ise false olacak ve else alacaktr #bu ilemi genellikle u ekilde yazarz: kullaniciOne = input("Kullanc adnz yaznz: ") if kullaniciOne: print("Teekkrler") else: print("kullanc ad bo braklamaz") #---------------------------------# # BOOL LELER # #---------------------------------# #AND #OR #NOT #and #gmail giri sistemi yazalm #gmail giri sisteminde kullanc ad ve parola yani her ikisi de doru olmaldr kullaniciAdi = input("Kullanc adnz: ") parola = input("Parolannz: ") if kullaniciAdi == "AliVeli": if parola == "123456": print("Sisteme hogeldiniz") else : print("Yanl kullanc ad veya parola!") else: print("Yanl kullanc ad veya parola") #bu ilemi daha kolay yazabiliriz kullanici = input("Kullanc adnz yaznz: ") sifre = input("ifrenizi yaznz: ") if kullanici == "aliveli" and sifre == "12345": print("programa hogeldiniz") else: print("Yanl kullanc ad veya parola") #and ilecini kullanarak iki durumu baladk #and ilecinin mant her iki durumun gereklemesidir #btn koullar gerekleiyorsa true dner #onun haricinde tm sonular false dir a = 23 b = 10 print(a == 23)#True print(b == 10)#True print(a == 23 and b == 10)#True print(a == 23 and b == 15)#False # OR #or veya demektir #her iki kouldan biri true olursa yine de alr c = 10 d = 100 print(c == 10)#True print(d == 100)#True print(c == 1 or d == 100)#True # c koulu yanl olsa da d koulu doru olduu iin kt True oldu # snavdan alnan notlarn harf karln gsteren program x = int(input("Notunuz: ")) if x > 100 or x < 0: print("Byle bir not yok") elif x >= 90 and x <= 100: print("A aldnz") elif x >= 80 and x <= 89: print("B aldnz.") elif x >= 70 and x <= 79: print("C aldnz") elif x >=60 and x <= 69: print("D aldnz.") elif x >= 0 and x <= 59: print("F aldnz.") #u ekilde daha ksa biimde yazabiliriz z = int(input("notunuz: ")) if x > 100 or x < 0: print("Byle bir not yoktur.") elif z >= 90 <= 100: print("A aldnz") elif z >=80 <= 89: print("B aldnz") elif z >= 70 <= 79: print("C aldnz") elif z >= 60 <=69: print("D aldnz") elif z >=0 <=59: print("F aldnz") # and i kaldrdmzda ayn sonucu alabiliyoruz ## not ## # not bir bool ilecidir. trke karl deil demektir # zellikle kullanc tarafndan deer girilip girilmediini #denetlmek iin kullanlr #eer kullanc deer girilise not deeri alacak #eer kullanc bo braklsa true deeri alacak parola = input("ifrenizi giriniz Ltfen: ") if not parola: print("ifre bo braklamaz") #ifrenizi giriniz yazs geldiinizde cevap vermeyip entera tkladm #deer true olunca print fonksiyonu alt print(bool(parola))#false #makineye unu soruyoruz aslnda: #parola bo braklmam deil mi? #makinede bize: hayr bo braklm diyor print(bool(not parola))#True #makineye parola bo braklm deil mi? sorusunu soruyoruz #makine de bize true evet bo braklm diyor #yani ikisinin arasndaki fark braklmam/braklm deil? midir #yani not islei makineye "bo braklm deil mi?" sorusunu soruyor #eer bo brakldysa cevap True oluyor evet braklm demek oluyor #----------------------------------# # Deer Atama leleri # #----------------------------------# # deer atama ilemi "=" ileciyle yaplr a = 25 #a deikenin iine 25 deerini atadk ## += ileci #deikenin deerine deer eklemek iin kullanlr a += 10 # a deikenin deerine 10 deeri daha ekledik print(a) # 35 ## -= #deikenin deerinin drmek yani karmak iin kullanlr a -= 5 #a deikeninden 5 deer kardk print(a)#30 ## /= # deikenin deeriyle blme ilemi yapmak iin kullanlr a /= 2 #a deikenin deerini 2 saysyla bldk print(a)#15.0 ## *= #deikenin deerini arpmak iin kullanlr a *= 4 # a deikenin deerini 4 ile arptk print(a)#60.0 ## %= #deikenin deerinin blme ileminde kalann bulmak iin kullanlr a %= 7 #a deikenin deerinin 7 ile blnmesinden kalann bulduk print(a)#4.0 ## **= #deikenin deerinin kuvvetini, kpn ve karakkn bulmak iin kullanlr a **= 2#a deikenin kuvvetini bulduk print(a)#16.0 ## //= #deikenin deerinin tam blnmesini bulmak iin kullanlr a //= 2 print(a)#8 #bu ileler normalde u ilemi yapar rnein #a = a + 5 #print(a)#5 #fakat bu ilem hzl bir seenek deildir ama mantksal olarak bu ekilde ilem yapar #ilelerin sa ve solda olma fark # += veya =+ -= veya =- a =- 5 print(a) # -5 # a deerine -5 deerini verdik ## := (walrus operatr) #rnek: giris = len(input("Adn ne?")) if giris < 4: print("Adn ksaym") elif giris < 6: print("Adn biraz uzunmu") else: print("Uzun bir adn varm.") #bu kodu := ilecini kullanarakta yazabiliriz if (giris := len(input("Adnz nedir?"))) < 4: print("Adn ksaym") elif giris < 6: print("Adn biraz uzunmu") else: print("ok uzun bir adn varm.") # := tek avantaj ilemimizi tek satra sdrmas # ok kullanlmaz #zaten yeni bir ile olduundan sadece python 3.8.1 de alr #--------------------------------# # ATLK LELER # #--------------------------------# #bir karakter dizisinin deikenin iinde bulunup bulunmadn #kontrol edebilmemizi salar #bu ilemi in adl ile sayesinde yaparz a = "asdfg" print("a" in a)#True #makineye "a" deeri a deikenin iinde var m? sorruyoruz print("A" in a)#False print("j" in a)#False # "j" deeri a deikenin iinde var m? cevap: Hayr yok False #--------------------------------# # KMLK LELER # #--------------------------------# #pythonda her eyin yani her nesnenin arka planda bir kimlik numaras vardr #bunu renmek iin id() adl fonskiyondan yararlanrz a = 50 print(id(a))#140705130925248 # a nn kimlik numarasn yazdr dedik name = "Hello my name is Murat" print(id(name))#2704421625648 #pythonda her nesenin esiz tek ve benzersiz bir kimlikleri vardr #python belli bir deere kadar nbellekte ayn kimlik numarasyla tutar nameOr = 100 print(id(nameOr))#140705130926848 nameOrOne = 100 print(id(nameOrOne))#140705130926848 #belli bir deeri artan deerleri nbellekte farkl kimlik no laryla tutar y = 1000 print(id(y))#2467428862544 u = 1000 print(id(u))#1586531830352 #ayn deere sahip olarak gzkselerde python farkl kimlikle tantyor #bunun nedeni python sadece ufak nesneleri nbellekte tutar #dier byk nesneleri ise yeni bir depolama ilemi yapar #ufak ve byk deerleri renmek iin: for k in range(-1000,1000): for v in range(-1000,1000): if k is v: print(k) #kan sonuca gre -5 ila 256 arasndaki deerleri nbellekte tutabiliyor ## is number = 1000 numberOne = 1000 print(id(number))#2209573079632 print(id(numberOne))#2756858382928 print(number is 1000)#False print(numberOne is 1000)#False #is kimlikliklerine gre eit midir ayn mdr sorusunu sorar #is ve == ileci ok kere kartlr ikisinin arasndaki fark: #is nesnelerin kimliklerine bakarak ayn m olduklarn inceler # == ise nesnelerin deerlerine bakarak ayn m olduklarn inceler print(number is 1000)#false #ayr kimlikleri olduklarndan cevap false print(number == 1000)#True #a 1000 deerine sahip olduklar iin cevap true #is in arka planda yapt ey kabaca bu: print(id(number)==id(1000))#false ornek = "Python" print(ornek is "Python") #True ornekOne = "Python gl ve kolay bir proglama dilidir" print(ornekOne is "Python gl ve kolay bir proglama dilidir")#False print(ornekOne == "Python gl ve kolay bir proglama dilidir")#True #saysal deerlerde olduu gibi karakter dizilerinde de kk olanlar nbellekte #byk olan karakter dizileri iinde yeni bir kimlik ve depolama tannmaktadr ## UYGULAMA RNEKLER ## #------------------------------------# # BAST BR HESAP MAKNES # #------------------------------------# #programmz bir hesap makinesi olacak #kullanya bir say girecek ve bu say ile topla m karma m yapacak karar verecek #buna gre ise ilemler yapacak #kullancya baz seenekler sunalm: giris = """ (1) topla (2) kar (3) arp (4) bl (5) karesini hesapla (6) karakkn hesapla """ print(giris) soru = input("Yapmak istediiniz ilemin numarasn giriniz: ")#kullancan hangi ilemi yapacan soracaz if soru == "1": sayi1 = int(input("Toplama ilemi iin ilk sayy giriniz: ")) sayi2 = int(input("Toplama ilemi iin ikinci sayy giriniz: ")) print(sayi1,"+",sayi2,"=",sayi1+sayi2) elif soru == "2": sayi3 = int(input("karma ilemi iin ilk sayy giriniz: ")) sayi4 = int(input("karma ilemi iin ikinci sayy giriniz: ")) print(sayi3,"-",sayi4,"=",sayi3-sayi4) elif soru == "3": sayi5 = int(input("arpma ilemi iin ilk sayy giriniz: ")) sayi6 = int(input("arpma ilemi iin ikinci sayy giriniz:")) print(sayi5,"*",sayi6,"=",sayi5*sayi6) elif soru == "4": sayi7 = int(input("Blme ilemi iin ilk sayy giriniz: ")) sayi8 = int(input("Blme ilemi iin ikinci sayy giriniz: ")) print(sayi7,"/",sayi8,"=",sayi7/sayi8) elif soru == "5": sayi9 = int(input("Karesini hesaplamak istediiniz bir sayy giriniz: ")) print(sayi9,"saynn karesi =",sayi9 ** 2) elif soru == "6": sayi10 = int(input("Karekkn hesaplamak iin istediiniz sayy giriniz: ")) print(sayi10,"saysnn karakk =",sayi10 ** 0.5) else: print("Yanl giri.") print("Aadaki seeneklerden birini giriniz: ",giris) """ Temel olarak program u ekilde: eer byle bir durum varsa: yle bir ilem yap yok eer yle bir durum varsa: byle bir ilem yap eer bambaka bir durum varsa: yle bir ey yap """ #-----------------------------------# # SRME GRE LEM YAPAN PROGRAM #-----------------------------------# #Pythonda 3.x serisinde yazlan kodlar 2.x serinde almaz #yazdmz kodlarn hangi python srmnde altrlmasn isteyebilirz #veya 3.x de yazdmz kodlarn 2.x altrlmas haline kullanya hata mesaj verdilebiliriz #sys moduln aralm ie aktaralm import sys #modl iindeki istediimiz deikene erielim print(sys.version_info) #sys.version_info(major=3, minor=7, micro=4, releaselevel='final', serial=0) #birde version deikenin verecei ktya bakalm print(sys.version)#3.7.4 (default, Aug 9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)] #fakat iimize version_info deikeni yaryor #version_info nun verdii kt gzken baz eyler: #major, python serisinin ana srm numaras #minor, alt srm numaras #micro, en alt srm numarasn verir #bu deerlere ulamak iin: print(sys.version_info.major)#3 print(sys.version_info.minor)#7 print(sys.version_info.micro)#4 #Programmz hangi srm ile altrlmas gerektiini kontrol eden bir program yazalm #bu program iin major ve minor u kullanacaz ihtiya dahilinde micro da kullanabiliriz import sys _2x_metni = """ Python'n 2.x srmlerinden birini kullanyorsunuz Program altrabilmek iin sisteminizde Python'n 3.x srmlerinden biri kurulu olmal.""" _3x_metni = "Programa Hogeldiniz!" if sys.version_info.major < 3: print(_2x_metni) else: print(_3x_metni) #burada ilk bata modl iindeki aralar kullanmak iin import ediyoruz #daha sonra 2.x serisini kullanan biri iin hata mesaj oluturuyoruz #deikenlerin adlar sayyla balayamayaca iin alt izgi ile baladk #sonra python3 kullanclar iin merhaba metni yarattk #eer dedik major numaras yani ana srm 3 ten kkse unu yazdr #bunun dndaki btn durumlar iin ise _3x_metnini bastr dedik # 2.x srmlerinde trke karakterleri makine alglayamyordu #bunu zmek iin ise : # -*- coding: utf-8 -*- #bu kodu yaptryorduk 3.x te bu sorun kalkmt #fakat bu sadece programn kmesini engeller trke karakterler bozuk gzkr #rnein _2x_metin 2.x srmlerinde alnca yle gzkr: """ Python'n 2.x srmlerinden birini kullanyorsunuz. Program altrabilmek iin sisteminizde Python'n 3.x srmlerinden biri kurulu olmal.""" #bunu engellemek iin karakter dizimizin nne u eklemek # u ise unicode kavramndan gelmektedir _2x_metni = u""" Python'n 2.x srmlerinden birini kullanyorsunuz. Program altrabilmek iin sisteminizde Python'n 3.x srmlerinden biri kurulu olmal.""" #3 ten kk srmlere hata mesaj yazdrabildik #imdi ise 3.4 gibi kk srmlere hata mesaj yazdrabiliriz hataMesaj3 = u""" uan Python'un eski srmn kullanyorsunuz. Ltfen gncelleyiniz! """ if sys.version_info.major == 3 and sys.version_info.minor == 8: print("bla bla") else: print(hataMesaj3) #bylece 3.8 alt kullanan kullanclara bir heta mesaj gsterdik #bu ilemi iin version deikenini de kullanabiliriz if "3.7" in sys.version: print("Gncel versiyondasnz") else: print(hataMesaj3)
27.283105
108
0.699749
9685eb2eb0a92cde4c6bccfdc2397e3ea1a606c7
1,056
py
Python
twindb_backup/modifiers/gzip.py
akuzminsky/twindb-mysql-backup
35755f18efb372dd05f856ca4732fba796de2549
[ "Apache-2.0" ]
1
2019-03-22T00:04:40.000Z
2019-03-22T00:04:40.000Z
twindb_backup/modifiers/gzip.py
akuzminsky/twindb-mysql-backup
35755f18efb372dd05f856ca4732fba796de2549
[ "Apache-2.0" ]
null
null
null
twindb_backup/modifiers/gzip.py
akuzminsky/twindb-mysql-backup
35755f18efb372dd05f856ca4732fba796de2549
[ "Apache-2.0" ]
1
2019-03-21T16:03:11.000Z
2019-03-21T16:03:11.000Z
# -*- coding: utf-8 -*- """ Module defines modifier that compresses a stream with gzip """ from contextlib import contextmanager from subprocess import Popen, PIPE from twindb_backup.modifiers.base import Modifier
27.076923
70
0.604167
968781224af215504c720d13564d694353e11612
8,795
py
Python
heat/objects/resource.py
larsks/heat
11064586e90166a037f8868835e6ce36f7306276
[ "Apache-2.0" ]
null
null
null
heat/objects/resource.py
larsks/heat
11064586e90166a037f8868835e6ce36f7306276
[ "Apache-2.0" ]
null
null
null
heat/objects/resource.py
larsks/heat
11064586e90166a037f8868835e6ce36f7306276
[ "Apache-2.0" ]
null
null
null
# Copyright 2014 Intel Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Resource object.""" from oslo_config import cfg from oslo_serialization import jsonutils from oslo_versionedobjects import base from oslo_versionedobjects import fields import retrying import six from heat.common import crypt from heat.common import exception from heat.common.i18n import _ from heat.db import api as db_api from heat.objects import base as heat_base from heat.objects import fields as heat_fields from heat.objects import resource_data cfg.CONF.import_opt('encrypt_parameters_and_properties', 'heat.common.config')
37.909483
79
0.648778
96897393cb06471fec8c0393bde8aeb577d2894c
228
py
Python
pyrez/exceptions/IdOrAuthEmpty.py
CLeendert/Pyrez
598d72d8b6bb9484f0c42c6146a262817332c666
[ "MIT" ]
25
2018-07-26T02:32:14.000Z
2021-09-20T03:26:17.000Z
pyrez/exceptions/IdOrAuthEmpty.py
CLeendert/Pyrez
598d72d8b6bb9484f0c42c6146a262817332c666
[ "MIT" ]
93
2018-08-26T11:44:25.000Z
2022-03-28T08:22:18.000Z
pyrez/exceptions/IdOrAuthEmpty.py
CLeendert/Pyrez
598d72d8b6bb9484f0c42c6146a262817332c666
[ "MIT" ]
13
2018-09-05T09:38:07.000Z
2021-08-16T04:39:41.000Z
from .PyrezException import PyrezException
38
73
0.763158
968a0ed358f9602c37b149e837fd6e25f4d5114f
4,492
py
Python
capnpy/segment/builder.py
GambitResearch/capnpy
3b8d9ed0623e160f69dee07ec2fc6303683c2a3c
[ "MIT" ]
45
2016-10-28T10:16:07.000Z
2022-03-06T20:16:57.000Z
capnpy/segment/builder.py
GambitResearch/capnpy
3b8d9ed0623e160f69dee07ec2fc6303683c2a3c
[ "MIT" ]
42
2016-12-20T18:10:53.000Z
2021-09-08T12:29:04.000Z
capnpy/segment/builder.py
GambitResearch/capnpy
3b8d9ed0623e160f69dee07ec2fc6303683c2a3c
[ "MIT" ]
21
2017-02-28T06:39:15.000Z
2021-09-07T05:30:46.000Z
import struct from six import binary_type from capnpy import ptr from capnpy.packing import mychr from capnpy.printer import print_buffer from capnpy.segment._copy_pointer import copy_pointer, _copy_struct_inline from capnpy.segment._copy_list import copy_from_list
33.274074
86
0.629564
968a32ab6cc052ecd19269370677c3356ed68536
1,028
py
Python
test_project/test_app/migrations/0002_auto_20180514_0720.py
iCHEF/queryfilter
0ae4faf525e162d2720d328b96fa179d68277f1e
[ "Apache-2.0" ]
4
2018-05-11T18:07:32.000Z
2019-07-30T13:38:49.000Z
test_project/test_app/migrations/0002_auto_20180514_0720.py
iCHEF/queryfilter
0ae4faf525e162d2720d328b96fa179d68277f1e
[ "Apache-2.0" ]
6
2018-02-26T04:46:36.000Z
2019-04-10T06:17:12.000Z
test_project/test_app/migrations/0002_auto_20180514_0720.py
iCHEF/queryfilter
0ae4faf525e162d2720d328b96fa179d68277f1e
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-05-14 07:20 from __future__ import unicode_literals from django.db import migrations, models
25.073171
50
0.535992
968a7365ef23f40cb8759f1ce7dce18d8b7a6114
6,371
py
Python
file.py
AllenGao6/P2P-File-Sharing
059f9ec75d10b7802d1a363f718ade640ac18223
[ "MIT" ]
null
null
null
file.py
AllenGao6/P2P-File-Sharing
059f9ec75d10b7802d1a363f718ade640ac18223
[ "MIT" ]
null
null
null
file.py
AllenGao6/P2P-File-Sharing
059f9ec75d10b7802d1a363f718ade640ac18223
[ "MIT" ]
null
null
null
''' objective of file.py: define the object class for file, information to include: name size of file chunk list (should automaticlly be splitted into chunks, each chunk should have indicator) ''' import base64 import sys import hashlib JPG, PNG, PDF, MP3, MP4, UNKNOWN = 1, 2, 3, 4, 5, 0
33.888298
125
0.605086
968afeca8b633bb5b9753043627e7d2f6a06eb50
360
py
Python
pdx-extract/tests/test_utils.py
michaelheyman/PSU-Code-Review
5a55d981425aaad69dc9ee06baaaef22bc426893
[ "MIT" ]
null
null
null
pdx-extract/tests/test_utils.py
michaelheyman/PSU-Code-Review
5a55d981425aaad69dc9ee06baaaef22bc426893
[ "MIT" ]
null
null
null
pdx-extract/tests/test_utils.py
michaelheyman/PSU-Code-Review
5a55d981425aaad69dc9ee06baaaef22bc426893
[ "MIT" ]
null
null
null
import unittest.mock as mock from app import utils
25.714286
73
0.802778
968b59a333622be17af9c9620da7baac069e951b
1,328
py
Python
.my_scripts/network/analyze_speedtest.py
infokiller/config-public
73fd61a0ad4d2f1ac7e7a73b13de8c4f1b80e5c4
[ "MIT" ]
17
2020-06-01T14:18:49.000Z
2022-03-23T04:32:52.000Z
.my_scripts/network/analyze_speedtest.py
Laworigin/config-public
527c42e0c5c274dd23c537674d789499b03ef912
[ "MIT" ]
1
2021-11-28T10:43:08.000Z
2021-11-28T10:43:08.000Z
.my_scripts/network/analyze_speedtest.py
Laworigin/config-public
527c42e0c5c274dd23c537674d789499b03ef912
[ "MIT" ]
3
2020-07-02T12:37:27.000Z
2021-12-15T17:03:54.000Z
#!/usr/bin/env python3 import argparse import datetime import os import matplotlib.pyplot as plt import pandas as pd if __name__ == '__main__': main()
30.883721
78
0.610693
968b5a9ecbc7c7427f6fc38ea644b75122f74f7f
5,403
py
Python
tensorflow_datasets/text/wikipedia_toxicity_subtypes.py
stwind/datasets
118d3d2472a3bf2703d1374e25c2223dc7942c13
[ "Apache-2.0" ]
1
2020-10-11T19:15:49.000Z
2020-10-11T19:15:49.000Z
tensorflow_datasets/text/wikipedia_toxicity_subtypes.py
cbaront/datasets
b097e0985eaaadc6b0c1f4dfa3b3cf88d116c607
[ "Apache-2.0" ]
1
2021-02-23T20:16:05.000Z
2021-02-23T20:16:05.000Z
tensorflow_datasets/text/wikipedia_toxicity_subtypes.py
cbaront/datasets
b097e0985eaaadc6b0c1f4dfa3b3cf88d116c607
[ "Apache-2.0" ]
1
2022-03-14T16:17:53.000Z
2022-03-14T16:17:53.000Z
# coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """WikipediaToxicitySubtypes from Jigsaw Toxic Comment Classification Challenge.""" import csv import os import tensorflow.compat.v2 as tf import tensorflow_datasets.public_api as tfds _CITATION = """ @inproceedings{10.1145/3038912.3052591, author = {Wulczyn, Ellery and Thain, Nithum and Dixon, Lucas}, title = {Ex Machina: Personal Attacks Seen at Scale}, year = {2017}, isbn = {9781450349130}, publisher = {International World Wide Web Conferences Steering Committee}, address = {Republic and Canton of Geneva, CHE}, url = {https://doi.org/10.1145/3038912.3052591}, doi = {10.1145/3038912.3052591}, booktitle = {Proceedings of the 26th International Conference on World Wide Web}, pages = {1391-1399}, numpages = {9}, keywords = {online discussions, wikipedia, online harassment}, location = {Perth, Australia}, series = {WWW '17} } """ _DESCRIPTION = """ This version of the Wikipedia Toxicity Subtypes dataset provides access to the primary toxicity label, as well the five toxicity subtype labels annotated by crowd workers. The toxicity and toxicity subtype labels are binary values (0 or 1) indicating whether the majority of annotators assigned that attributes to the comment text. The comments in this dataset come from an archive of Wikipedia talk pages comments. These have been annotated by Jigsaw for toxicity, as well as a variety of toxicity subtypes, including severe toxicity, obscenity, threatening language, insulting language, and identity attacks. This dataset is a replica of the data released for the Jigsaw Toxic Comment Classification Challenge on Kaggle, with the training set unchanged, and the test dataset merged with the test_labels released after the end of the competition. Test data not used for scoring has been dropped. This dataset is released under CC0, as is the underlying comment text. See the Kaggle documentation or https://figshare.com/articles/Wikipedia_Talk_Labels_Toxicity/4563973 for more details. """ _DOWNLOAD_URL = 'https://storage.googleapis.com/jigsaw-unintended-bias-in-toxicity-classification/wikipedia_toxicity_subtypes.zip'
38.049296
130
0.713122
968b8d46ee387fdd215e0605696e260154647af3
480
py
Python
estimate-retrofit-impact-on-heat-pump-viability/plot_uvalue_distribution.py
rdmolony/projects
8cbbe215710cb9f1b1bf80f8c6a39153181d61a0
[ "MIT" ]
3
2021-09-02T16:38:27.000Z
2022-01-19T13:11:09.000Z
estimate-retrofit-impact-on-heat-pump-viability/plot_uvalue_distribution.py
rdmolony/projects
8cbbe215710cb9f1b1bf80f8c6a39153181d61a0
[ "MIT" ]
5
2021-10-17T16:25:47.000Z
2021-11-14T17:51:24.000Z
estimate-retrofit-impact-on-heat-pump-viability/plot_uvalue_distribution.py
rdmolony/projects
8cbbe215710cb9f1b1bf80f8c6a39153181d61a0
[ "MIT" ]
3
2021-10-04T08:34:26.000Z
2022-02-06T15:56:03.000Z
import pandas as pd import seaborn as sns sns.set() # + tags=["parameters"] upstream = ["download_buildings"] product = None # - buildings = pd.read_csv(upstream["download_buildings"]) buildings["wall_uvalue"].plot.hist(bins=30) buildings["roof_uvalue"].plot.hist(bins=30) buildings["window_uvalue"].plot.hist(bins=30) buildings["wall_uvalue"].to_csv(product["wall"]) buildings["roof_uvalue"].to_csv(product["roof"]) buildings["window_uvalue"].to_csv(product["window"])
19.2
55
0.739583
968d0a57d12d55c489796f697b6f5c53a64a6d4e
925
py
Python
src/core/base/Logging.py
albertmonfa/Banhmi
30052155316d3ba65e9bc7261f13f7e081c14ab2
[ "Apache-2.0" ]
null
null
null
src/core/base/Logging.py
albertmonfa/Banhmi
30052155316d3ba65e9bc7261f13f7e081c14ab2
[ "Apache-2.0" ]
1
2021-06-01T22:54:10.000Z
2021-06-01T22:54:10.000Z
src/core/base/Logging.py
albertmonfa/Banhmi
30052155316d3ba65e9bc7261f13f7e081c14ab2
[ "Apache-2.0" ]
1
2018-11-08T10:18:19.000Z
2018-11-08T10:18:19.000Z
#!/usr/bin/python ''' Copyright 2018 Albert Monfa Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' import logging
27.205882
72
0.701622
968d107ac6d19ef65f3e2a523c368a10dd9ff203
8,243
py
Python
IzVerifier/test/test_izverifier.py
ahmedlawi92/IzVerifier
b367935f66810b4c4897cc860c5a3e2070f1890f
[ "MIT" ]
null
null
null
IzVerifier/test/test_izverifier.py
ahmedlawi92/IzVerifier
b367935f66810b4c4897cc860c5a3e2070f1890f
[ "MIT" ]
null
null
null
IzVerifier/test/test_izverifier.py
ahmedlawi92/IzVerifier
b367935f66810b4c4897cc860c5a3e2070f1890f
[ "MIT" ]
null
null
null
from IzVerifier.izspecs.containers.izclasses import IzClasses __author__ = 'fcanas' import unittest from IzVerifier.izspecs.containers.izconditions import IzConditions from IzVerifier.izspecs.containers.izstrings import IzStrings from IzVerifier.izspecs.containers.izvariables import IzVariables from IzVerifier.izverifier import IzVerifier from IzVerifier.izspecs.containers.constants import * path1 = 'data/sample_installer_iz5/izpack/' path2 = 'data/sample_installer_iz5/resources/' source_path2 = 'data/sample_code_base/src/' pom = 'data/sample_installer_iz5/pom.xml' if __name__ == '__main__': unittest.main()
35.076596
123
0.605241
968e31be6937f07c12c6da1be7d293d1db2611e3
5,690
py
Python
src/envoxy/postgresql/client.py
muzzley/envoxy
b70f2d19ee27f7b4b12e68d441b1317966d87041
[ "MIT" ]
2
2018-10-29T09:39:43.000Z
2019-06-18T11:29:00.000Z
src/envoxy/postgresql/client.py
muzzley/envoxy
b70f2d19ee27f7b4b12e68d441b1317966d87041
[ "MIT" ]
null
null
null
src/envoxy/postgresql/client.py
muzzley/envoxy
b70f2d19ee27f7b4b12e68d441b1317966d87041
[ "MIT" ]
null
null
null
from psycopg2.pool import ThreadedConnectionPool import psycopg2.extras import psycopg2.sql as sql from contextlib import contextmanager from threading import Semaphore from ..db.exceptions import DatabaseException from ..utils.logs import Log from ..constants import MIN_CONN, MAX_CONN, TIMEOUT_CONN, DEFAULT_OFFSET_LIMIT, DEFAULT_CHUNK_SIZE from ..asserts import assertz
31.787709
119
0.564323
968eb0ff0a358625bf80189ad1c3b24c8d3d2439
4,380
py
Python
treadmill/cli/admin/blackout.py
gaocegege/treadmill
04325d319c0ee912c066f07b88b674e84485f154
[ "Apache-2.0" ]
2
2017-03-20T07:13:33.000Z
2017-05-03T03:39:53.000Z
treadmill/cli/admin/blackout.py
gaocegege/treadmill
04325d319c0ee912c066f07b88b674e84485f154
[ "Apache-2.0" ]
12
2017-07-10T07:04:06.000Z
2017-07-26T09:32:54.000Z
treadmill/cli/admin/blackout.py
gaocegege/treadmill
04325d319c0ee912c066f07b88b674e84485f154
[ "Apache-2.0" ]
2
2017-05-04T11:25:32.000Z
2017-07-11T09:10:01.000Z
"""Kills all connections from a given treadmill server.""" import logging import re import click import kazoo from treadmill import presence from treadmill import utils from treadmill import zkutils from treadmill import context from treadmill import cli from treadmill import zknamespace as z _LOGGER = logging.getLogger(__name__) _ON_EXCEPTIONS = cli.handle_exceptions([ (kazoo.exceptions.NoAuthError, 'Error: not authorized.'), (context.ContextError, None), ]) def _gen_formatter(mapping, formatter): """Generate real formatter to have item index in position.""" pattern = re.compile(r'(%(\w))') match = pattern.findall(formatter) # (symbol, key) should be ('%t', 't') for (symbol, key) in match: index = mapping[key] formatter = formatter.replace(symbol, '{%d}' % index, 1) return formatter def _list_server_blackouts(zkclient, fmt): """List server blackouts.""" # List currently blacked out nodes. blacked_out = [] try: blacked_out_nodes = zkclient.get_children(z.BLACKEDOUT_SERVERS) for server in blacked_out_nodes: node_path = z.path.blackedout_server(server) data, metadata = zkutils.get(zkclient, node_path, need_metadata=True) blacked_out.append((metadata.created, server, data)) except kazoo.client.NoNodeError: pass # [%t] %h %r will be printed as below # [Thu, 05 May 2016 02:59:58 +0000] <hostname> - mapping = {'t': 0, 'h': 1, 'r': 2} formatter = _gen_formatter(mapping, fmt) for when, server, reason in reversed(sorted(blacked_out)): reason = '-' if reason is None else reason print(formatter.format(utils.strftime_utc(when), server, reason)) def _clear_server_blackout(zkclient, server): """Clear server blackout.""" path = z.path.blackedout_server(server) zkutils.ensure_deleted(zkclient, path) def _blackout_server(zkclient, server, reason): """Blackout server.""" if not reason: raise click.UsageError('--reason is required.') path = z.path.blackedout_server(server) zkutils.ensure_exists( zkclient, path, acl=[zkutils.make_host_acl(server, 'rwcda')], data=str(reason) ) presence.kill_node(zkclient, server) def _blackout_app(zkclient, app, clear): """Blackout app.""" # list current blacklist blacklisted_node = z.path.blackedout_app(app) if clear: zkutils.ensure_deleted(zkclient, blacklisted_node) else: zkutils.ensure_exists(zkclient, blacklisted_node) def _list_blackedout_apps(zkclient): """List blackedout apps.""" try: for blacklisted in zkclient.get_children(z.BLACKEDOUT_APPS): print(blacklisted) except kazoo.client.NoNodeError: pass def init(): """Top level command handler.""" del server_cmd del app_cmd return blackout
29.594595
73
0.638128
9690871dfe5b99b44cb726d4b08a75cadca848bb
3,200
py
Python
tests/view_tests/urls.py
peteralexandercharles/django
61c7350f41f2534daf3888709f3c987b7d779a29
[ "BSD-3-Clause", "0BSD" ]
null
null
null
tests/view_tests/urls.py
peteralexandercharles/django
61c7350f41f2534daf3888709f3c987b7d779a29
[ "BSD-3-Clause", "0BSD" ]
null
null
null
tests/view_tests/urls.py
peteralexandercharles/django
61c7350f41f2534daf3888709f3c987b7d779a29
[ "BSD-3-Clause", "0BSD" ]
null
null
null
import os from functools import partial from django.conf.urls.i18n import i18n_patterns from django.urls import include, path, re_path from django.utils.translation import gettext_lazy as _ from django.views import defaults, i18n, static from . import views base_dir = os.path.dirname(os.path.abspath(__file__)) media_dir = os.path.join(base_dir, "media") locale_dir = os.path.join(base_dir, "locale") urlpatterns = [ path("", views.index_page), # Default views path("nonexistent_url/", partial(defaults.page_not_found, exception=None)), path("server_error/", defaults.server_error), # a view that raises an exception for the debug view path("raises/", views.raises), path("raises400/", views.raises400), path("raises400_bad_request/", views.raises400_bad_request), path("raises403/", views.raises403), path("raises404/", views.raises404), path("raises500/", views.raises500), path("custom_reporter_class_view/", views.custom_reporter_class_view), path("technical404/", views.technical404, name="my404"), path("classbased404/", views.Http404View.as_view()), # i18n views path("i18n/", include("django.conf.urls.i18n")), path("jsi18n/", i18n.JavaScriptCatalog.as_view(packages=["view_tests"])), path("jsi18n/app1/", i18n.JavaScriptCatalog.as_view(packages=["view_tests.app1"])), path("jsi18n/app2/", i18n.JavaScriptCatalog.as_view(packages=["view_tests.app2"])), path("jsi18n/app5/", i18n.JavaScriptCatalog.as_view(packages=["view_tests.app5"])), path( "jsi18n_english_translation/", i18n.JavaScriptCatalog.as_view(packages=["view_tests.app0"]), ), path( "jsi18n_multi_packages1/", i18n.JavaScriptCatalog.as_view(packages=["view_tests.app1", "view_tests.app2"]), ), path( "jsi18n_multi_packages2/", i18n.JavaScriptCatalog.as_view(packages=["view_tests.app3", "view_tests.app4"]), ), path( "jsi18n_admin/", i18n.JavaScriptCatalog.as_view(packages=["django.contrib.admin", "view_tests"]), ), path("jsi18n_template/", views.jsi18n), path("jsi18n_multi_catalogs/", views.jsi18n_multi_catalogs), path("jsoni18n/", i18n.JSONCatalog.as_view(packages=["view_tests"])), # Static views re_path( r"^site_media/(?P<path>.*)$", static.serve, {"document_root": media_dir, "show_indexes": True}, ), ] urlpatterns += i18n_patterns( re_path(_(r"^translated/$"), views.index_page, name="i18n_prefixed"), ) urlpatterns += [ path("template_exception/", views.template_exception, name="template_exception"), path( "raises_template_does_not_exist/<path:path>", views.raises_template_does_not_exist, name="raises_template_does_not_exist", ), path("render_no_template/", views.render_no_template, name="render_no_template"), re_path( r"^test-setlang/(?P<parameter>[^/]+)/$", views.with_parameter, name="with_parameter", ), # Patterns to test the technical 404. re_path(r"^regex-post/(?P<pk>[0-9]+)/$", views.index_page, name="regex-post"), path("path-post/<int:pk>/", views.index_page, name="path-post"), ]
38.095238
88
0.684688
969196b838a5ad3282e2d2bf20e3669c40ce0f82
20,323
py
Python
sympy/solvers/ode/systems.py
nsfinkelstein/sympy
cf87897234ad0d7eaac705ba47267caec2a6bcb1
[ "BSD-3-Clause" ]
2
2019-05-18T22:36:49.000Z
2019-05-24T05:56:16.000Z
sympy/solvers/ode/systems.py
mmelotti/sympy
bea29026d27cc50c2e6a5501b6a70a9629ed3e18
[ "BSD-3-Clause" ]
1
2020-04-22T12:45:26.000Z
2020-04-22T12:45:26.000Z
sympy/solvers/ode/systems.py
mmelotti/sympy
bea29026d27cc50c2e6a5501b6a70a9629ed3e18
[ "BSD-3-Clause" ]
3
2021-02-16T16:40:49.000Z
2022-03-07T18:28:41.000Z
from sympy import (Derivative, Symbol) from sympy.core.numbers import I from sympy.core.relational import Eq from sympy.core.symbol import Dummy from sympy.functions import exp, im, cos, sin, re from sympy.functions.combinatorial.factorials import factorial from sympy.matrices import zeros, Matrix from sympy.simplify import simplify, collect from sympy.solvers.deutils import ode_order from sympy.solvers.solveset import NonlinearError from sympy.utilities import numbered_symbols, default_sort_key from sympy.utilities.iterables import ordered, uniq def linear_ode_to_matrix(eqs, funcs, t, order): r""" Convert a linear system of ODEs to matrix form Explanation =========== Express a system of linear ordinary differential equations as a single matrix differential equation [1]. For example the system $x' = x + y + 1$ and $y' = x - y$ can be represented as .. math:: A_1 X' + A_0 X = b where $A_1$ and $A_0$ are $2 \times 2$ matrices and $b$, $X$ and $X'$ are $2 \times 1$ matrices with $X = [x, y]^T$. Higher-order systems are represented with additional matrices e.g. a second-order system would look like .. math:: A_2 X'' + A_1 X' + A_0 X = b Examples ======== >>> from sympy import (Function, Symbol, Matrix, Eq) >>> from sympy.solvers.ode.systems import linear_ode_to_matrix >>> t = Symbol('t') >>> x = Function('x') >>> y = Function('y') We can create a system of linear ODEs like >>> eqs = [ ... Eq(x(t).diff(t), x(t) + y(t) + 1), ... Eq(y(t).diff(t), x(t) - y(t)), ... ] >>> funcs = [x(t), y(t)] >>> order = 1 # 1st order system Now ``linear_ode_to_matrix`` can represent this as a matrix differential equation. >>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, t, order) >>> A1 Matrix([ [1, 0], [0, 1]]) >>> A0 Matrix([ [-1, -1], [-1, 1]]) >>> b Matrix([ [1], [0]]) The original equations can be recovered from these matrices: >>> eqs_mat = Matrix([eq.lhs - eq.rhs for eq in eqs]) >>> X = Matrix(funcs) >>> A1 * X.diff(t) + A0 * X - b == eqs_mat True If the system of equations has a maximum order greater than the order of the system specified, a ODEOrderError exception is raised. >>> eqs = [Eq(x(t).diff(t, 2), x(t).diff(t) + x(t)), Eq(y(t).diff(t), y(t) + x(t))] >>> linear_ode_to_matrix(eqs, funcs, t, 1) Traceback (most recent call last): ... ODEOrderError: Cannot represent system in 1-order form If the system of equations is nonlinear, then ODENonlinearError is raised. >>> eqs = [Eq(x(t).diff(t), x(t) + y(t)), Eq(y(t).diff(t), y(t)**2 + x(t))] >>> linear_ode_to_matrix(eqs, funcs, t, 1) Traceback (most recent call last): ... ODENonlinearError: The system of ODEs is nonlinear. Parameters ========== eqs : list of sympy expressions or equalities The equations as expressions (assumed equal to zero). funcs : list of applied functions The dependent variables of the system of ODEs. t : symbol The independent variable. order : int The order of the system of ODEs. Returns ======= The tuple ``(As, b)`` where ``As`` is a tuple of matrices and ``b`` is the the matrix representing the rhs of the matrix equation. Raises ====== ODEOrderError When the system of ODEs have an order greater than what was specified ODENonlinearError When the system of ODEs is nonlinear See Also ======== linear_eq_to_matrix: for systems of linear algebraic equations. References ========== .. [1] https://en.wikipedia.org/wiki/Matrix_differential_equation """ from sympy.solvers.solveset import linear_eq_to_matrix if any(ode_order(eq, func) > order for eq in eqs for func in funcs): msg = "Cannot represent system in {}-order form" raise ODEOrderError(msg.format(order)) As = [] for o in range(order, -1, -1): # Work from the highest derivative down funcs_deriv = [func.diff(t, o) for func in funcs] # linear_eq_to_matrix expects a proper symbol so substitute e.g. # Derivative(x(t), t) for a Dummy. rep = {func_deriv: Dummy() for func_deriv in funcs_deriv} eqs = [eq.subs(rep) for eq in eqs] syms = [rep[func_deriv] for func_deriv in funcs_deriv] # Ai is the matrix for X(t).diff(t, o) # eqs is minus the remainder of the equations. try: Ai, b = linear_eq_to_matrix(eqs, syms) except NonlinearError: raise ODENonlinearError("The system of ODEs is nonlinear.") As.append(Ai) if o: eqs = [-eq for eq in b] else: rhs = b return As, rhs def matrix_exp(A, t): r""" Matrix exponential $\exp(A*t)$ for the matrix ``A`` and scalar ``t``. Explanation =========== This functions returns the $\exp(A*t)$ by doing a simple matrix multiplication: .. math:: \exp(A*t) = P * expJ * P^{-1} where $expJ$ is $\exp(J*t)$. $J$ is the Jordan normal form of $A$ and $P$ is matrix such that: .. math:: A = P * J * P^{-1} The matrix exponential $\exp(A*t)$ appears in the solution of linear differential equations. For example if $x$ is a vector and $A$ is a matrix then the initial value problem .. math:: \frac{dx(t)}{dt} = A \times x(t), x(0) = x0 has the unique solution .. math:: x(t) = \exp(A t) x0 Examples ======== >>> from sympy import Symbol, Matrix, pprint >>> from sympy.solvers.ode.systems import matrix_exp >>> t = Symbol('t') We will consider a 2x2 matrix for comupting the exponential >>> A = Matrix([[2, -5], [2, -4]]) >>> pprint(A) [2 -5] [ ] [2 -4] Now, exp(A*t) is given as follows: >>> pprint(matrix_exp(A, t)) [ -t -t -t ] [3*e *sin(t) + e *cos(t) -5*e *sin(t) ] [ ] [ -t -t -t ] [ 2*e *sin(t) - 3*e *sin(t) + e *cos(t)] Parameters ========== A : Matrix The matrix $A$ in the expression $\exp(A*t)$ t : Symbol The independent variable See Also ======== matrix_exp_jordan_form: For exponential of Jordan normal form References ========== .. [1] https://en.wikipedia.org/wiki/Jordan_normal_form .. [2] https://en.wikipedia.org/wiki/Matrix_exponential """ P, expJ = matrix_exp_jordan_form(A, t) return P * expJ * P.inv() def matrix_exp_jordan_form(A, t): r""" Matrix exponential $\exp(A*t)$ for the matrix *A* and scalar *t*. Explanation =========== Returns the Jordan form of the $\exp(A*t)$ along with the matrix $P$ such that: .. math:: \exp(A*t) = P * expJ * P^{-1} Examples ======== >>> from sympy import Matrix, Symbol >>> from sympy.solvers.ode.systems import matrix_exp, matrix_exp_jordan_form >>> t = Symbol('t') We will consider a 2x2 defective matrix. This shows that our method works even for defective matrices. >>> A = Matrix([[1, 1], [0, 1]]) It can be observed that this function gives us the Jordan normal form and the required invertible matrix P. >>> P, expJ = matrix_exp_jordan_form(A, t) Here, it is shown that P and expJ returned by this function is correct as they satisfy the formula: P * expJ * P_inverse = exp(A*t). >>> P * expJ * P.inv() == matrix_exp(A, t) True Parameters ========== A : Matrix The matrix $A$ in the expression $\exp(A*t)$ t : Symbol The independent variable References ========== .. [1] https://en.wikipedia.org/wiki/Defective_matrix .. [2] https://en.wikipedia.org/wiki/Jordan_matrix .. [3] https://en.wikipedia.org/wiki/Jordan_normal_form """ N, M = A.shape if N != M: raise ValueError('Needed square matrix but got shape (%s, %s)' % (N, M)) elif A.has(t): raise ValueError('Matrix A should not depend on t') def jordan_chains(A): '''Chains from Jordan normal form analogous to M.eigenvects(). Returns a dict with eignevalues as keys like: {e1: [[v111,v112,...], [v121, v122,...]], e2:...} where vijk is the kth vector in the jth chain for eigenvalue i. ''' P, blocks = A.jordan_cells() basis = [P[:,i] for i in range(P.shape[1])] n = 0 chains = {} for b in blocks: eigval = b[0, 0] size = b.shape[0] if eigval not in chains: chains[eigval] = [] chains[eigval].append(basis[n:n+size]) n += size return chains eigenchains = jordan_chains(A) # Needed for consistency across Python versions: eigenchains_iter = sorted(eigenchains.items(), key=default_sort_key) isreal = not A.has(I) blocks = [] vectors = [] seen_conjugate = set() for e, chains in eigenchains_iter: for chain in chains: n = len(chain) if isreal and e != e.conjugate() and e.conjugate() in eigenchains: if e in seen_conjugate: continue seen_conjugate.add(e.conjugate()) exprt = exp(re(e) * t) imrt = im(e) * t imblock = Matrix([[cos(imrt), sin(imrt)], [-sin(imrt), cos(imrt)]]) expJblock2 = Matrix(n, n, lambda i,j: imblock * t**(j-i) / factorial(j-i) if j >= i else zeros(2, 2)) expJblock = Matrix(2*n, 2*n, lambda i,j: expJblock2[i//2,j//2][i%2,j%2]) blocks.append(exprt * expJblock) for i in range(n): vectors.append(re(chain[i])) vectors.append(im(chain[i])) else: vectors.extend(chain) fun = lambda i,j: t**(j-i)/factorial(j-i) if j >= i else 0 expJblock = Matrix(n, n, fun) blocks.append(exp(e * t) * expJblock) expJ = Matrix.diag(*blocks) P = Matrix(N, N, lambda i,j: vectors[j][i]) return P, expJ def _neq_linear_first_order_const_coeff_homogeneous(match_): r""" System of n first-order constant-coefficient linear homogeneous differential equations .. math:: y'_k = a_{k1} y_1 + a_{k2} y_2 +...+ a_{kn} y_n; k = 1,2,...,n or that can be written as `\vec{y'} = A . \vec{y}` where `\vec{y}` is matrix of `y_k` for `k = 1,2,...n` and `A` is a `n \times n` matrix. Since these equations are equivalent to a first order homogeneous linear differential equation. So the general solution will contain `n` linearly independent parts and solution will consist some type of exponential functions. Assuming `y = \vec{v} e^{rt}` is a solution of the system where `\vec{v}` is a vector of coefficients of `y_1,...,y_n`. Substituting `y` and `y' = r v e^{r t}` into the equation `\vec{y'} = A . \vec{y}`, we get .. math:: r \vec{v} e^{rt} = A \vec{v} e^{rt} .. math:: r \vec{v} = A \vec{v} where `r` comes out to be eigenvalue of `A` and vector `\vec{v}` is the eigenvector of `A` corresponding to `r`. There are three possibilities of eigenvalues of `A` - `n` distinct real eigenvalues - complex conjugate eigenvalues - eigenvalues with multiplicity `k` 1. When all eigenvalues `r_1,..,r_n` are distinct with `n` different eigenvectors `v_1,...v_n` then the solution is given by .. math:: \vec{y} = C_1 e^{r_1 t} \vec{v_1} + C_2 e^{r_2 t} \vec{v_2} +...+ C_n e^{r_n t} \vec{v_n} where `C_1,C_2,...,C_n` are arbitrary constants. 2. When some eigenvalues are complex then in order to make the solution real, we take a linear combination: if `r = a + bi` has an eigenvector `\vec{v} = \vec{w_1} + i \vec{w_2}` then to obtain real-valued solutions to the system, replace the complex-valued solutions `e^{rx} \vec{v}` with real-valued solution `e^{ax} (\vec{w_1} \cos(bx) - \vec{w_2} \sin(bx))` and for `r = a - bi` replace the solution `e^{-r x} \vec{v}` with `e^{ax} (\vec{w_1} \sin(bx) + \vec{w_2} \cos(bx))` 3. If some eigenvalues are repeated. Then we get fewer than `n` linearly independent eigenvectors, we miss some of the solutions and need to construct the missing ones. We do this via generalized eigenvectors, vectors which are not eigenvectors but are close enough that we can use to write down the remaining solutions. For a eigenvalue `r` with eigenvector `\vec{w}` we obtain `\vec{w_2},...,\vec{w_k}` using .. math:: (A - r I) . \vec{w_2} = \vec{w} .. math:: (A - r I) . \vec{w_3} = \vec{w_2} .. math:: \vdots .. math:: (A - r I) . \vec{w_k} = \vec{w_{k-1}} Then the solutions to the system for the eigenspace are `e^{rt} [\vec{w}], e^{rt} [t \vec{w} + \vec{w_2}], e^{rt} [\frac{t^2}{2} \vec{w} + t \vec{w_2} + \vec{w_3}], ...,e^{rt} [\frac{t^{k-1}}{(k-1)!} \vec{w} + \frac{t^{k-2}}{(k-2)!} \vec{w_2} +...+ t \vec{w_{k-1}} + \vec{w_k}]` So, If `\vec{y_1},...,\vec{y_n}` are `n` solution of obtained from three categories of `A`, then general solution to the system `\vec{y'} = A . \vec{y}` .. math:: \vec{y} = C_1 \vec{y_1} + C_2 \vec{y_2} + \cdots + C_n \vec{y_n} """ eq = match_['eq'] func = match_['func'] fc = match_['func_coeff'] n = len(eq) t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] constants = numbered_symbols(prefix='C', cls=Symbol, start=1) # This needs to be modified in future so that fc is only of type Matrix M = -fc if type(fc) is Matrix else Matrix(n, n, lambda i,j:-fc[i,func[j],0]) P, J = matrix_exp_jordan_form(M, t) P = simplify(P) Cvect = Matrix(list(next(constants) for _ in range(n))) sol_vector = P * (J * Cvect) sol_vector = [collect(s, ordered(J.atoms(exp)), exact=True) for s in sol_vector] sol_dict = [Eq(func[i], sol_vector[i]) for i in range(n)] return sol_dict def _matrix_is_constant(M, t): """Checks if the matrix M is independent of t or not.""" return all(coef.as_independent(t, as_Add=True)[1] == 0 for coef in M) def _canonical_equations(eqs, funcs, t): """Helper function that solves for first order derivatives in a system""" from sympy.solvers.solvers import solve # For now the system of ODEs dealt by this function can have a # maximum order of 1. if any(ode_order(eq, func) > 1 for eq in eqs for func in funcs): msg = "Cannot represent system in {}-order canonical form" raise ODEOrderError(msg.format(1)) canon_eqs = solve(eqs, *[func.diff(t) for func in funcs], dict=True) if len(canon_eqs) != 1: raise ODENonlinearError("System of ODEs is nonlinear") canon_eqs = canon_eqs[0] canon_eqs = [Eq(func.diff(t), canon_eqs[func.diff(t)]) for func in funcs] return canon_eqs def neq_nth_linear_constant_coeff_match(eqs, funcs, t): r""" Returns a dictionary with details of the eqs if every equation is constant coefficient and linear else returns None Explanation =========== This function takes the eqs, converts it into a form Ax = b where x is a vector of terms containing dependent variables and their derivatives till their maximum order. If it is possible to convert eqs into Ax = b, then all the equations in eqs are linear otherwise they are non-linear. To check if the equations are constant coefficient, we need to check if all the terms in A obtained above are constant or not. To check if the equations are homogeneous or not, we need to check if b is a zero matrix or not. Parameters ========== eqs: List List of ODEs funcs: List List of dependent variables t: Symbol Independent variable of the equations in eqs Returns ======= match = { 'no_of_equation': len(eqs), 'eq': eqs, 'func': funcs, 'order': order, 'is_linear': is_linear, 'is_constant': is_constant, 'is_homogeneous': is_homogeneous, } Dict or None Dict with values for keys: 1. no_of_equation: Number of equations 2. eq: The set of equations 3. func: List of dependent variables 4. order: A dictionary that gives the order of the dependent variable in eqs 5. is_linear: Boolean value indicating if the set of equations are linear or not. 6. is_constant: Boolean value indicating if the set of equations have constant coefficients or not. 7. is_homogeneous: Boolean value indicating if the set of equations are homogeneous or not. This Dict is the answer returned if the eqs are linear and constant coefficient. Otherwise, None is returned. """ # Error for i == 0 can be added but isn't for now # Removing the duplicates from the list of funcs # meanwhile maintaining the order. This is done # since the line in classify_sysode: list(set(funcs) # cause some test cases to fail when gives different # results in different versions of Python. funcs = list(uniq(funcs)) # Check for len(funcs) == len(eqs) if len(funcs) != len(eqs): raise ValueError("Number of functions given is not equal to the number of equations %s" % funcs) # ValueError when functions have more than one arguments for func in funcs: if len(func.args) != 1: raise ValueError("dsolve() and classify_sysode() work with " "functions of one variable only, not %s" % func) # Getting the func_dict and order using the helper # function order = _get_func_order(eqs, funcs) if not all(order[func] == 1 for func in funcs): return None else: # TO be changed when this function is updated. # This will in future be updated as the maximum # order in the system found. system_order = 1 # Not adding the check if the len(func.args) for # every func in funcs is 1 # Linearity check try: canon_eqs = _canonical_equations(eqs, funcs, t) As, b = linear_ode_to_matrix(canon_eqs, funcs, t, system_order) # When the system of ODEs is non-linear, an ODENonlinearError is raised. # When system has an order greater than what is specified in system_order, # ODEOrderError is raised. # This function catches these errors and None is returned except (ODEOrderError, ODENonlinearError): return None A = As[1] is_linear = True # Constant coefficient check is_constant = _matrix_is_constant(A, t) # Homogeneous check is_homogeneous = True if b.is_zero_matrix else False match = { 'no_of_equation': len(eqs), 'eq': eqs, 'func': funcs, 'order': order, 'is_linear': is_linear, 'is_constant': is_constant, 'is_homogeneous': is_homogeneous, } # The match['is_linear'] check will be added in the future when this # function becomes ready to deal with non-linear systems of ODEs if match['is_constant']: # Converting the equation into canonical form if the # equation is first order. There will be a separate # function for this in the future. if all([order[func] == 1 for func in funcs]) and match['is_homogeneous']: match['func_coeff'] = A match['type_of_equation'] = "type1" return match return None
32.310016
104
0.59814
96929dbf83193019e408fa5ab401d32d84324a98
104
py
Python
python/torch_mlir/eager_mode/__init__.py
burntfalafel/torch-mlir-internal
d3ef58450fc94e9337dc0434fa3af6dd7b54b37f
[ "Apache-2.0" ]
2
2022-02-16T21:56:00.000Z
2022-02-20T17:34:47.000Z
python/torch_mlir/eager_mode/__init__.py
burntfalafel/torch-mlir-internal
d3ef58450fc94e9337dc0434fa3af6dd7b54b37f
[ "Apache-2.0" ]
null
null
null
python/torch_mlir/eager_mode/__init__.py
burntfalafel/torch-mlir-internal
d3ef58450fc94e9337dc0434fa3af6dd7b54b37f
[ "Apache-2.0" ]
null
null
null
import os EAGER_MODE_DEBUG = os.environ.get("EAGER_MODE_DEBUG", 'False').lower() in ('true', '1', 't')
26
92
0.673077
96930cd599eda3b260c1fca7b9aaa84eeb3c1530
985
py
Python
docs/rips/tests/test_surfaces.py
OPM/ResInsight-UserDocumentation
2af2c3a5ef297c0061d842944360a83bf8e49c36
[ "MIT" ]
1
2020-04-25T21:24:45.000Z
2020-04-25T21:24:45.000Z
docs/rips/tests/test_surfaces.py
OPM/ResInsight-UserDocumentation
2af2c3a5ef297c0061d842944360a83bf8e49c36
[ "MIT" ]
7
2020-02-11T07:42:10.000Z
2020-09-28T17:18:01.000Z
docs/rips/tests/test_surfaces.py
OPM/ResInsight-UserDocumentation
2af2c3a5ef297c0061d842944360a83bf8e49c36
[ "MIT" ]
2
2020-04-02T09:33:45.000Z
2020-04-09T19:44:53.000Z
import sys import os import tempfile from pathlib import Path import pytest sys.path.insert(1, os.path.join(sys.path[0], "../../")) import rips import dataroot
28.142857
85
0.722843
96935625868f5df6499326134d54ac7ad8bc8a3f
1,172
py
Python
samcli/cli/main.py
langn/aws-sam-cli
160d87ff3c07f092315e1ac71ddc00257fde011b
[ "Apache-2.0" ]
null
null
null
samcli/cli/main.py
langn/aws-sam-cli
160d87ff3c07f092315e1ac71ddc00257fde011b
[ "Apache-2.0" ]
1
2018-05-23T19:51:18.000Z
2018-05-23T19:51:18.000Z
samcli/cli/main.py
langn/aws-sam-cli
160d87ff3c07f092315e1ac71ddc00257fde011b
[ "Apache-2.0" ]
null
null
null
""" Entry point for the CLI """ import logging import click from samcli import __version__ from .options import debug_option from .context import Context from .command import BaseCommand logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') pass_context = click.make_pass_decorator(Context) def common_options(f): """ Common CLI options used by all commands. Ex: --debug :param f: Callback function passed by Click :return: Callback function """ f = debug_option(f) return f
26.636364
116
0.740614
9693a5d83793a6353d6917bc38d706bca8e15158
1,816
py
Python
ast_to_json.py
visr/Py2Jl.jl
b2dee947299d064da2e443d0b1ad2ca90bbd1753
[ "MIT" ]
53
2018-08-20T12:47:47.000Z
2022-03-17T02:21:07.000Z
ast_to_json.py
visr/Py2Jl.jl
b2dee947299d064da2e443d0b1ad2ca90bbd1753
[ "MIT" ]
14
2019-01-24T15:27:15.000Z
2021-06-13T13:24:18.000Z
ast_to_json.py
visr/Py2Jl.jl
b2dee947299d064da2e443d0b1ad2ca90bbd1753
[ "MIT" ]
9
2019-02-12T01:07:11.000Z
2021-11-11T19:33:36.000Z
import ast import typing as t import numbers import json from wisepy.talking import Talking from Redy.Tools.PathLib import Path talking = Talking() if __name__ == '__main__': talking.on()
25.942857
73
0.55837
96940da789aefea52af00e66e63f6bfcc1df6521
18,232
py
Python
src/python/pants/backend/docker/util_rules/docker_build_context_test.py
pantsbuild/pants
22c566e78b4dd982958429813c82e9f558957817
[ "Apache-2.0" ]
1,806
2015-01-05T07:31:00.000Z
2022-03-31T11:35:41.000Z
src/python/pants/backend/docker/util_rules/docker_build_context_test.py
pantsbuild/pants
22c566e78b4dd982958429813c82e9f558957817
[ "Apache-2.0" ]
9,565
2015-01-02T19:01:59.000Z
2022-03-31T23:25:16.000Z
src/python/pants/backend/docker/util_rules/docker_build_context_test.py
pantsbuild/pants
22c566e78b4dd982958429813c82e9f558957817
[ "Apache-2.0" ]
443
2015-01-06T20:17:57.000Z
2022-03-31T05:28:17.000Z
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from textwrap import dedent from typing import Any, ContextManager import pytest from pants.backend.docker.goals import package_image from pants.backend.docker.subsystems import dockerfile_parser from pants.backend.docker.subsystems.dockerfile_parser import DockerfileInfo from pants.backend.docker.target_types import DockerImageTarget from pants.backend.docker.util_rules import ( dependencies, docker_binary, docker_build_args, docker_build_context, docker_build_env, dockerfile, ) from pants.backend.docker.util_rules.docker_build_args import DockerBuildArgs from pants.backend.docker.util_rules.docker_build_context import ( DockerBuildContext, DockerBuildContextRequest, ) from pants.backend.docker.util_rules.docker_build_env import DockerBuildEnvironment from pants.backend.docker.value_interpolation import ( DockerBuildArgsInterpolationValue, DockerInterpolationContext, DockerInterpolationValue, ) from pants.backend.python import target_types_rules from pants.backend.python.goals import package_pex_binary from pants.backend.python.goals.package_pex_binary import PexBinaryFieldSet from pants.backend.python.target_types import PexBinary from pants.backend.python.util_rules import pex_from_targets from pants.backend.shell.target_types import ShellSourcesGeneratorTarget, ShellSourceTarget from pants.backend.shell.target_types import rules as shell_target_types_rules from pants.core.goals.package import BuiltPackage from pants.core.target_types import FilesGeneratorTarget from pants.core.target_types import rules as core_target_types_rules from pants.engine.addresses import Address from pants.engine.fs import EMPTY_DIGEST, EMPTY_SNAPSHOT, Snapshot from pants.engine.internals.scheduler import ExecutionError from pants.testutil.pytest_util import no_exception from pants.testutil.rule_runner import QueryRule, RuleRunner def test_create_docker_build_context() -> None: context = DockerBuildContext.create( build_args=DockerBuildArgs.from_strings("ARGNAME=value1"), snapshot=EMPTY_SNAPSHOT, build_env=DockerBuildEnvironment.create({"ENVNAME": "value2"}), dockerfile_info=DockerfileInfo( address=Address("test"), digest=EMPTY_DIGEST, source="test/Dockerfile", putative_target_addresses=(), version_tags=("base latest", "stage1 1.2", "dev 2.0", "prod 2.0"), build_args=DockerBuildArgs.from_strings(), from_image_build_arg_names=(), copy_sources=(), ), ) assert list(context.build_args) == ["ARGNAME=value1"] assert dict(context.build_env.environment) == {"ENVNAME": "value2"} assert context.dockerfile == "test/Dockerfile" assert context.stages == ("base", "dev", "prod")
32.042179
99
0.557975
969769f903879e83d04d75567c8891aa3f6d52df
726
py
Python
build_you/models/company.py
bostud/build_you
258a336a82a1da9efc102770f5d8bf83abc13379
[ "MIT" ]
null
null
null
build_you/models/company.py
bostud/build_you
258a336a82a1da9efc102770f5d8bf83abc13379
[ "MIT" ]
null
null
null
build_you/models/company.py
bostud/build_you
258a336a82a1da9efc102770f5d8bf83abc13379
[ "MIT" ]
null
null
null
import enum from sqlalchemy import Column, ForeignKey, String, JSON, Integer, Enum from sqlalchemy.orm import relationship from build_you.models.base import BaseModel from build_you.database import Base
30.25
75
0.717631
9697bf800b99049dd85751a04350650f26e3d26b
293
py
Python
deeplab_resnet/__init__.py
tramper2/SIGGRAPH18SSS
9bf22fa242044edfcf11cc4a58b93c63fcc71ff0
[ "MIT" ]
390
2018-07-30T08:41:49.000Z
2022-03-29T15:44:13.000Z
deeplab_resnet/__init__.py
tramper2/SIGGRAPH18SSS
9bf22fa242044edfcf11cc4a58b93c63fcc71ff0
[ "MIT" ]
20
2018-08-15T14:51:29.000Z
2020-04-21T09:49:49.000Z
deeplab_resnet/__init__.py
tramper2/SIGGRAPH18SSS
9bf22fa242044edfcf11cc4a58b93c63fcc71ff0
[ "MIT" ]
109
2018-08-04T05:58:23.000Z
2021-10-17T12:02:29.000Z
from .model import DeepLabResNetModel from .hc_deeplab import HyperColumn_Deeplabv2 from .image_reader import ImageReader, read_data_list, get_indicator_mat, get_batch_1chunk, read_an_image_from_disk, tf_wrap_get_patch, get_batch from .utils import decode_labels, inv_preprocess, prepare_label
73.25
145
0.880546
9697d247dc37a959099c3ca64ced69e9f31cf6d0
670
py
Python
ESPNet/commons/general_details.py
sanket1414/Priority-Based-Alert-System
89d61d43eab8d7251fe99796e657bc95da1cc48c
[ "MIT" ]
1
2019-10-24T03:19:14.000Z
2019-10-24T03:19:14.000Z
ESPNet/commons/general_details.py
sanket1414/Priority-Based-Alert-System
89d61d43eab8d7251fe99796e657bc95da1cc48c
[ "MIT" ]
null
null
null
ESPNet/commons/general_details.py
sanket1414/Priority-Based-Alert-System
89d61d43eab8d7251fe99796e657bc95da1cc48c
[ "MIT" ]
null
null
null
# classification related details classification_datasets = ['imagenet', 'coco'] classification_schedulers = ['fixed', 'clr', 'hybrid', 'linear', 'poly'] classification_models = ['espnetv2', 'dicenet', 'shufflenetv2'] classification_exp_choices = ['main', 'ablation'] # segmentation related details segmentation_schedulers = ['poly', 'fixed', 'clr', 'linear', 'hybrid'] segmentation_datasets = ['pascal', 'city'] segmentation_models = ['espnetv2', 'dicenet'] segmentation_loss_fns = ['ce', 'bce'] # detection related details detection_datasets = ['coco', 'pascal'] detection_models = ['espnetv2', 'dicenet'] detection_schedulers = ['poly', 'hybrid', 'clr', 'cosine']
35.263158
72
0.720896
9699ab49dc0c20db4bb4ee78fa2411605bb8f673
1,758
py
Python
resources/dot_PyCharm/system/python_stubs/-762174762/win32profile.py
basepipe/developer_onboarding
05b6a776f8974c89517868131b201f11c6c2a5ad
[ "MIT" ]
1
2020-04-20T02:27:20.000Z
2020-04-20T02:27:20.000Z
resources/dot_PyCharm/system/python_stubs/cache/9edeeb97ae7c1ec358f9620843984323739bcf3221eaa5ee1fd68961c7a6b26a/win32profile.py
basepipe/developer_onboarding
05b6a776f8974c89517868131b201f11c6c2a5ad
[ "MIT" ]
null
null
null
resources/dot_PyCharm/system/python_stubs/cache/9edeeb97ae7c1ec358f9620843984323739bcf3221eaa5ee1fd68961c7a6b26a/win32profile.py
basepipe/developer_onboarding
05b6a776f8974c89517868131b201f11c6c2a5ad
[ "MIT" ]
null
null
null
# encoding: utf-8 # module win32profile # from C:\Python27\lib\site-packages\win32\win32profile.pyd # by generator 1.147 # no doc # no imports # Variables with simple values PI_APPLYPOLICY = 2 PI_NOUI = 1 PT_MANDATORY = 4 PT_ROAMING = 2 PT_TEMPORARY = 1 # functions def CreateEnvironmentBlock(*args, **kwargs): # real signature unknown """ Retrieves environment variables for a user """ pass def DeleteProfile(*args, **kwargs): # real signature unknown """ Remove a user's profile """ pass def ExpandEnvironmentStringsForUser(*args, **kwargs): # real signature unknown """ Replaces environment variables in a string with per-user values """ pass def GetAllUsersProfileDirectory(*args, **kwargs): # real signature unknown """ Retrieve All Users profile directory """ pass def GetDefaultUserProfileDirectory(*args, **kwargs): # real signature unknown """ Retrieve profile path for Default user """ pass def GetEnvironmentStrings(*args, **kwargs): # real signature unknown """ Retrieves environment variables for current process """ pass def GetProfilesDirectory(*args, **kwargs): # real signature unknown """ Retrieves directory where user profiles are stored """ pass def GetProfileType(*args, **kwargs): # real signature unknown """ Returns type of current user's profile """ pass def GetUserProfileDirectory(*args, **kwargs): # real signature unknown """ Returns profile directory for a logon token """ pass def LoadUserProfile(*args, **kwargs): # real signature unknown """ Load user settings for a login token """ pass def UnloadUserProfile(*args, **kwargs): # real signature unknown """ Unload profile loaded by LoadUserProfile """ pass # no classes
27.46875
78
0.711035
9699da91536be3b5f7938a488f2471ecc9d269c7
1,318
py
Python
app/web/obtain_url.py
gpp0725/EchoProxy
0273f47397b76fa0292db267d99eeb9dccc4e869
[ "Apache-2.0" ]
null
null
null
app/web/obtain_url.py
gpp0725/EchoProxy
0273f47397b76fa0292db267d99eeb9dccc4e869
[ "Apache-2.0" ]
null
null
null
app/web/obtain_url.py
gpp0725/EchoProxy
0273f47397b76fa0292db267d99eeb9dccc4e869
[ "Apache-2.0" ]
null
null
null
# !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/3/4 0004 2:09 # @Author : Gpp # @File : obtain_url.py from app.web import api from flask_restful import Resource from flask import make_response, send_from_directory, jsonify from app.helper.encrypt import two_encrypting from app.crud.proxy_crud import ProtocolCrud from app.helper.get_one_encrypt import get_one_encrypt_data from app.helper.update_subscribe import add_proxy # @api.resource('/generate') # class Generate(Resource): # def get(self): # proxies = ProtocolCrud.get_all_share() # one_encrypt = get_one_encrypt_data(proxies) # result = add_proxy(two_encrypting(''.join(one_encrypt))) # return jsonify(result)
33.794872
113
0.707132
969a1ae2aa1e6f093f672d0dc08a8182fddc7227
920
py
Python
oshino/run.py
CodersOfTheNight/oshino
08e35d004aa16a378d87d5e548649a1bc1f5dc17
[ "MIT" ]
6
2016-11-06T17:47:57.000Z
2020-04-08T12:20:59.000Z
oshino/run.py
CodersOfTheNight/oshino
08e35d004aa16a378d87d5e548649a1bc1f5dc17
[ "MIT" ]
24
2016-11-15T06:20:50.000Z
2019-02-08T18:54:57.000Z
oshino/run.py
CodersOfTheNight/oshino
08e35d004aa16a378d87d5e548649a1bc1f5dc17
[ "MIT" ]
null
null
null
import logging from argparse import ArgumentParser from dotenv import load_dotenv, find_dotenv from .config import load from .core.heart import start_loop logger = logging.getLogger(__name__) try: load_dotenv(find_dotenv()) except Exception as ex: logger.error("Error while loading .env: '{}'. Ignoring.".format(ex)) if __name__ == "__main__": parser = ArgumentParser() parser.add_argument("--config", help="Config file", default="config.yaml") parser.add_argument("--noop", action="store_true", default=False, help="Events will be processed, but not sent to Riemann") parser.add_argument("--debug", action="store_true", default=False, help="Debug mode") main(parser.parse_args())
27.058824
127
0.71413
969aa0f8463c5dac76a29b27b5b12bf01e79a4cf
4,113
py
Python
sendmail_win_cs.py
Fatman13/gta_swarm
1c4603f39cd7831f5907fd619594452b3320f75f
[ "MIT" ]
null
null
null
sendmail_win_cs.py
Fatman13/gta_swarm
1c4603f39cd7831f5907fd619594452b3320f75f
[ "MIT" ]
null
null
null
sendmail_win_cs.py
Fatman13/gta_swarm
1c4603f39cd7831f5907fd619594452b3320f75f
[ "MIT" ]
null
null
null
#!/usr/bin/env python # coding=utf-8 import glob import click import os import json import datetime import re import csv from requests.exceptions import ConnectionError from exchangelib import DELEGATE, IMPERSONATION, Account, Credentials, ServiceAccount, \ EWSDateTime, EWSTimeZone, Configuration, NTLM, CalendarItem, Message, \ Mailbox, Attendee, Q, ExtendedProperty, FileAttachment, ItemAttachment, \ HTMLBody, Build, Version sendmail_secret = None with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'secrets.json')) as data_file: sendmail_secret = (json.load(data_file))['sendmail_win'] TO_REGISTER = 'Confirmed (to register)' if __name__ == '__main__': sendmail_win_cs()
34.855932
102
0.706054