content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
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)
[ 11748, 28686, 198, 198, 11748, 2603, 29487, 8019, 355, 285, 489, 198, 11748, 28034, 198, 11748, 28034, 10178, 198, 198, 6738, 1366, 62, 27604, 1330, 314, 5760, 265, 292, 316, 11, 449, 1967, 11, 3184, 5039, 47384, 902, 198, 6738, 7686, ...
2.288229
1,818
#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()
[ 2, 11748, 279, 9945, 201, 198, 51, 796, 357, 15, 13, 16, 11, 657, 13, 16, 8, 201, 198, 87, 796, 657, 13, 15, 201, 198, 1640, 1312, 287, 2837, 7, 11925, 7, 51, 8, 2599, 201, 198, 220, 220, 220, 329, 474, 287, 309, 25, 201, ...
1.670588
85
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)
[ 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 4738, 355, 374, 67, 198, 11748, 640, 198, 11748, 1822, 29572, 198, 198, 11748, 28034, 198, 11748, 28034, 13, 26791, 13, 7890, 198, 6738, 28034, 1330, 6436, 198, 198, 11748, 2...
2.141315
2,038
#!/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"]
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 33918, 198, 11748, 640, 198, 11748, 7007, 198, 6738, 1190, 538, 13, 1069, 4516, 1330, 9455, 12331, 11, 2563...
3.129032
93
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
[ 6738, 12972, 86, 862, 1330, 4809, 198, 6738, 12972, 86, 862, 13, 41989, 1330, 6818, 62, 26209, 62, 13138, 198, 198, 6738, 764, 11321, 1330, 5456, 62, 1640, 11, 651, 62, 22915, 198, 6738, 795, 84, 13, 14681, 274, 13, 86, 862, 62, 6...
3.285714
49
#!/usr/bin/env python import rospy from std_msgs.msg import String if __name__ == '__main__': try: talker() except rospy.ROSInterruptException: pass
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 686, 2777, 88, 198, 6738, 14367, 62, 907, 14542, 13, 19662, 1330, 10903, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1949, 25, ...
2.25641
78
# 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
[ 2, 47044, 7730, 1677, 1137, 11617, 0, 8410, 5626, 48483, 0, 9220, 284, 4370, 25, 299, 1443, 14, 2999, 62, 19849, 13, 541, 2047, 65, 357, 25252, 4306, 7368, 737, 198, 198, 834, 439, 834, 796, 37250, 36, 5632, 33711, 3256, 705, 25690,...
3.234234
111
#!/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)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 7031, 7653, 220, 362, 1511, 25, 2931, 25, 2816, 2864, 198, 198, 31, 9800, 25, 6428, 72, ...
1.788673
4,273
""" 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')
[ 37811, 198, 35, 73, 14208, 6460, 329, 502, 2782, 4265, 1628, 13, 198, 198, 8645, 515, 416, 705, 28241, 14208, 12, 28482, 923, 16302, 6, 1262, 37770, 513, 13, 16, 13, 16, 13, 198, 198, 1890, 517, 1321, 319, 428, 2393, 11, 766, 198,...
2.310478
2,596
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)
[ 6738, 1341, 35720, 1330, 662, 36948, 11, 264, 14761, 198, 6738, 1341, 35720, 13, 29127, 62, 19849, 1330, 44800, 8081, 2234, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 4512, 62, 9288, 62, 35312, 198, 6738, 1341, 35720, 1330, 327...
2.39738
458
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)
[ 11748, 4818, 8079, 198, 11748, 28686, 198, 11748, 331, 43695, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 11748, 14470, 198, 11748, 14470, 62, 7295, 62, 5589, 3906, 355, 288, 535, 198, 11748,...
1.764895
4,347
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
[ 11748, 12972, 9288, 198, 198, 6738, 6468, 28338, 13, 952, 1330, 11414, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 1657, 74, 333, 303, 13, 952, 13, 365, 7752, 1042, 291, 1330, 1100, 62, 365, 7752, 1042, 291, 62, 2971, 22019, ...
2.95
60
__author__ = 'Samara Cardoso'
[ 834, 9800, 834, 796, 705, 16305, 3301, 5172, 28213, 6, 628, 198 ]
2.666667
12
# # 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 #
[ 198, 2, 198, 2, 2221, 1332, 2438, 198, 2, 198, 198, 6738, 4738, 1330, 43720, 600, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 628, 197, 64, 8053, 796, 685, 66, 7, 16, 828, 269, 7, 17, 828, 269, 7, 18, 8...
1.985119
336
# -*- 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
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 42625, 14208, 1330, 5107, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 651, 5239, 62, 75, 12582, 355, 4808, 198, 6738, 42625, 14208, 13, 26791, 13, 12...
3.484211
95
# 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
[ 2, 6937, 198, 11748, 33918, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 3859, 198, 11748, 850, 14681, 198, 6738, 4818, 8079, 1330, 3128, 198, 6738, 28686, 13, 6978, 1330, 7160, 11, 4292, 7220, 11, 318, 15908, 11, 318, 7753, 11, ...
2.340895
1,631
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())
[ 6738, 308, 70, 29487, 1330, 257, 274, 11, 4903, 296, 62, 4122, 11, 308, 70, 29487, 11, 285, 23047, 945, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 6738, 19798, 292, 1330, 6060, 19778, 198, 198, 6738, 148...
2.518987
158
#!/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")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 2, 554, 58, 16, 5974, 628, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 198, 198, 11748, 1822, 29572...
2.368794
2,256
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
[ 6738, 4818, 8079, 1330, 3128, 198, 198, 6738, 42625, 14208, 1330, 5107, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 23914, 1330, 11787, 12443, 341, 8479, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 117...
3.75
84
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())
[ 11748, 25064, 198, 11748, 613, 13655, 631, 355, 23241, 198, 6738, 613, 13655, 631, 13, 4703, 2072, 1330, 2547, 325, 27660, 15854, 2072, 198, 11748, 4738, 198, 2, 422, 764, 1330, 15942, 198, 11748, 15942, 198, 198, 39494, 9936, 796, 4654...
1.94499
1,018
from typing import Callable, Union from kaggle import KaggleApi from kaggle.models.kaggle_models_extended import Competition, Kernel
[ 6738, 19720, 1330, 4889, 540, 11, 4479, 198, 198, 6738, 479, 9460, 293, 1330, 509, 9460, 293, 32, 14415, 198, 6738, 479, 9460, 293, 13, 27530, 13, 74, 9460, 293, 62, 27530, 62, 2302, 1631, 1330, 27348, 11, 32169, 628 ]
3.375
40
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'), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 6738, 764, 1330, 5009, 198, 198, 1324, 62, 3672, 796, 705, 39813, 6, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 3108, 10786, 3256, 5009, 13, 9630, 11, 1438, 11639, 9630, 33...
2.635802
486
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
[ 11748, 30351, 952, 198, 11748, 18931, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 257, 952, 62, 79, 9232, 1330, 16000, 11, 2018, 62, 22609, 436, 198, 6738, 257, 952, 62, 79, 9232, 13, 1069, 11755, 1330, 28682, 12331, 198, 6738, 257,...
3
100
# 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
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 15069, 1946, 41689, 1628, 20420, 357, 3826, 27342, 9865, 3843, 20673, 13, 9132, 737, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 3826, 38559, 24290, 737, 198, 198, 6738, 1...
3.238889
180
#!/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
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 198, 37811, 59, 198, 10987, 3224, 16628, 319, 257, 9483, 286, 279, 67, 1443, 290, 4866, 262, 2482, 736, 198, 20424, 262, 2656, 279, 9945, 13, 198, 198, 28350, 25, 198, 220, 220, ...
3.011364
440
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', ], )
[ 6738, 1233, 26791, 13, 7295, 1330, 9058, 198, 40406, 7, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 1438, 796, 705, 565, 18, 332, 3256, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 10392, 796, 37250, 565, 18, 332, 6, ...
2.104326
393
# -*- 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"
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 302, 198, 198, 6738, 12176, 261, 13, 21950, 1330, 7515, 198, 6738, 509, 1689, 25418, 13, 18274, 346, 13, 7282, 14382, 1330, 8525, 1836, 2514, 11, 19808, 2514, 198...
2.670429
443
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()
[ 11748, 28686, 201, 198, 11748, 33918, 201, 198, 6738, 28034, 27372, 13, 4164, 10466, 1330, 45835, 33986, 278, 26595, 201, 198, 6738, 28034, 27372, 13, 2213, 10613, 1330, 45835, 33986, 278, 2898, 10613, 201, 198, 6738, 28034, 27372, 13, 47...
2.343648
614
# Create your views here. from django.urls import reverse_lazy from django.views import generic from forms.forms import UserCreateForm
[ 2, 13610, 534, 5009, 994, 13, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 62, 75, 12582, 198, 6738, 42625, 14208, 13, 33571, 1330, 14276, 198, 198, 6738, 5107, 13, 23914, 1330, 11787, 16447, 8479, 628 ]
3.702703
37
# -*- 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*******")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 3300, 5267, 1160, 5534, 25, 2091, 25, 1507, 13130, 198, 198, 31, 9800, 25, 1312, 80, 65, 874, 549, 27299, 198, 37811, 198, 198, 6738, 22092, 13...
2.646209
554
# -*- 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
[ 2, 532, 9, 12, 1332, 12, 7442, 12, 3672, 25, 19074, 13, 6404, 1362, 13, 9288, 13, 9288, 62, 952, 532, 9, 12, 198, 2, 15069, 357, 66, 8, 40006, 24936, 46779, 13, 198, 2, 4091, 38559, 24290, 329, 3307, 13, 198, 198, 37811, 198, ...
2.37069
928
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))
[ 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 2, 422, 279, 4798, 1330, 279, 4798, 198, 198, 11748, 257, 952, 4023, 198, 11748, 36446, 198, 6738, 36446, 13, 2302, 1330, 9729, 198, 198, 6738, 10214, 1330, 38491, 198, 198, 17614, ...
2.508108
185
""" 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
[ 37811, 198, 23873, 2350, 326, 15456, 657, 338, 503, 262, 4296, 1619, 83, 292, 329, 1123, 11507, 198, 37811, 198, 198, 11748, 262, 5733, 198, 11748, 262, 5733, 13, 83, 22854, 355, 309, 198, 6738, 262, 5733, 13, 38142, 3524, 13, 81, 7...
2.963415
82
import os import os.path from datetime import datetime import time from stat import * import pathlib import json
[ 11748, 28686, 198, 11748, 28686, 13, 6978, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 640, 198, 6738, 1185, 1330, 1635, 198, 11748, 3108, 8019, 198, 11748, 33918, 198 ]
3.766667
30
from enum import Enum
[ 6738, 33829, 1330, 2039, 388, 628 ]
3.833333
6
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()
[ 11748, 555, 715, 395, 198, 11748, 28686, 198, 6738, 2237, 1330, 10903, 9399, 198, 6738, 5301, 62, 37153, 1330, 7736, 628, 198, 50084, 50, 5883, 62, 51, 25010, 796, 366, 1129, 1314, 324, 65, 40035, 15197, 67, 42780, 41948, 1157, 68, 22...
2.644138
725
########################################################################## # 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";
[ 29113, 29113, 7804, 2235, 198, 2, 1002, 407, 5081, 4306, 287, 428, 2393, 393, 428, 7515, 338, 10483, 4541, 13, 14116, 198, 2, 2393, 262, 1708, 6634, 290, 16625, 4174, 25, 198, 2, 198, 2, 15069, 1584, 31475, 42, 8549, 198, 2, 198, ...
2.917813
3,200
# -*- 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')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 19480, 8621, 5534, 1478, 25, 2931, 25, 3070, 2177, 198, 198, 31, 9800, 25, 47204, 198, 37811, 198, 198, 11748, 269, 85, 17, 198, 11748, 28686, ...
3.076761
951
# Generated by Django 2.2.1 on 2022-02-25 15:50 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 16, 319, 33160, 12, 2999, 12, 1495, 1315, 25, 1120, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.766667
30
# 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
[ 2, 220, 24843, 13789, 10628, 362, 13, 15, 198, 2, 198, 2, 220, 15069, 357, 66, 8, 33448, 1539, 2297, 271, 23500, 198, 2, 220, 1439, 2489, 10395, 13, 198, 2, 198, 198, 2, 770, 11688, 318, 262, 691, 530, 1295, 326, 262, 2196, 1271...
3.20915
153
# 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
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 198, 11748, 2237, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 1330, 9104, 198, ...
3.6
50
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()
[ 11748, 7007, 198, 6738, 3384, 4487, 1330, 17594, 8979, 11, 1366, 32750, 198, 11748, 28686, 198, 11748, 4818, 8079, 198, 6738, 3128, 22602, 13, 2411, 265, 1572, 12514, 1330, 48993, 1572, 12514, 198, 11748, 33918, 198, 6738, 3384, 4487, 13,...
2.852713
129
#!/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:])
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 2, 15069, 357, 66, 8, 2864, 532, 289, 84, 42990, 1279, 13415, 42990, 31, 70, 295, 1453, 13, 785, 29, 198, 37811, 198, ...
2.677333
375
# 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``.
[ 2, 21004, 25, 3384, 69, 12, 23, 198, 198, 11748, 334, 27112, 198, 11748, 814, 8019, 198, 6738, 4818, 8079, 1330, 3128, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 334, 1136, 5239...
3.556017
241
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])
[ 11748, 33918, 198, 11748, 28686, 198, 198, 6738, 19720, 1330, 4377, 11, 360, 713, 11, 32233, 198, 198, 11748, 284, 4029, 15813, 198, 11748, 331, 43695, 198, 198, 6738, 302, 3919, 343, 13, 499, 271, 1330, 7152, 10840, 11, 40251, 2969, ...
2.303178
409
# 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
[ 2, 15069, 357, 66, 8, 33448, 1215, 15355, 350, 1228, 261, 357, 324, 15355, 13, 79, 1228, 261, 31, 14816, 13, 785, 8, 198, 2, 220, 198, 2, 770, 3788, 318, 2716, 739, 262, 17168, 13789, 13, 198, 2, 3740, 1378, 44813, 1668, 13, 239...
3
104
# 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()) }
[ 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921, 743, 7330, 198, 2, 220, 220, ...
2.669708
548
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)
[ 6738, 44161, 282, 26599, 13, 18392, 13, 8692, 1330, 26923, 198, 6738, 44161, 282, 26599, 13, 25410, 13, 19738, 540, 1330, 9683, 11, 3082, 633, 17563, 198, 6738, 44161, 282, 26599, 13, 18392, 13, 20274, 1330, 25414, 198, 6738, 44161, 282...
2.565725
2,655
import pytest from moto import mock_ec2 from moto.ec2.models import AMIS from aec.command.ami import delete, describe, share
[ 11748, 12972, 9288, 198, 6738, 285, 2069, 1330, 15290, 62, 721, 17, 198, 6738, 285, 2069, 13, 721, 17, 13, 27530, 1330, 3001, 1797, 198, 198, 6738, 257, 721, 13, 21812, 13, 6277, 1330, 12233, 11, 6901, 11, 2648, 628, 628, 628 ]
3.119048
42
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
[ 6738, 42625, 14208, 13, 33571, 13, 41357, 1330, 7343, 7680, 198, 6738, 1334, 62, 30604, 13, 525, 8481, 1330, 22507, 7149, 198, 6738, 1334, 62, 30604, 13, 1177, 28709, 1330, 9104, 7680, 7248, 198, 198, 6738, 1388, 1324, 13, 27530, 1330, ...
4.177419
62
# 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))
[ 2, 554, 428, 8265, 356, 481, 651, 262, 4508, 954, 290, 262, 2985, 583, 4508, 355, 257, 1351, 13, 198, 2, 3060, 517, 3307, 355, 10762, 3306, 198, 198, 2, 314, 1101, 1262, 4017, 3212, 419, 994, 2427, 286, 627, 3378, 419, 355, 262, ...
3.038251
183
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_)
[ 11748, 334, 310, 9497, 355, 269, 83, 198, 198, 44, 5105, 62, 796, 1391, 198, 220, 705, 25216, 6, 197, 25, 357, 657, 87, 405, 11, 1391, 198, 220, 220, 220, 705, 2301, 6, 197, 25, 220, 220, 657, 87, 405, 930, 269, 83, 13, 52, ...
1.576202
2,933
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)
[ 11748, 28034, 198, 6738, 9195, 13, 26791, 1330, 318, 62, 1845, 29363, 198, 11748, 299, 32152, 355, 45941, 198, 37659, 13, 2617, 62, 4798, 25811, 7, 400, 10126, 28, 37659, 13, 10745, 8, 198, 11748, 269, 85, 17, 198, 6738, 1341, 35720, ...
2.015714
2,100
name = "ada lovelace" print(name.title())
[ 3672, 796, 366, 4763, 2376, 626, 558, 1, 201, 198, 4798, 7, 3672, 13, 7839, 28955, 201, 198 ]
2.444444
18
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)
[ 11748, 25064, 198, 11748, 850, 14681, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 11748, 1822, 29572, 198, 11748, 33918, 198, 11748, 302, 198, 6738, 33829, 1330, 2039, 388, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 1174...
2.662711
1,601
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()
[ 28311, 25, 198, 220, 220, 220, 422, 24580, 13, 69, 315, 942, 1330, 14122, 27201, 23002, 38409, 198, 220, 220, 220, 1330, 4738, 11, 640, 11, 28686, 11, 2638, 87, 198, 220, 220, 220, 422, 3124, 1689, 1330, 4558, 11, 17738, 198, 16341,...
2.727941
136
#!/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'))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 6738, 41306, 8019, 1330, 3661, 32512, 17401, 198, 198, 6649, 796, 3661, 32512, 17401, 10786, 2637, 8, 198, 198, 8135, 32512, 796, 1017, 13, 1136, 62, 8135, 32512, 62, 4480, 62...
2.892308
130
from django.views.generic import View from django.http import HttpResponse from django.shortcuts import render
[ 6738, 42625, 14208, 13, 33571, 13, 41357, 1330, 3582, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543 ]
3.928571
28
""" 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", ], )
[ 37811, 2124, 82, 2363, 9058, 37227, 198, 11748, 40481, 82, 198, 6738, 28686, 1330, 3108, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 6738, 31841, 13, 10414, 13, 11250, 1330, 23210, 62, 50, 2969, 62, 47, 56, 62,...
2.405286
908
# 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
[ 2, 15069, 33160, 2488, 49, 1734, 20366, 278, 622, 527, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, ...
3.781726
197
"""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)
[ 37811, 15514, 329, 10880, 39, 397, 3335, 11812, 526, 15931, 198, 6738, 4818, 8079, 1330, 28805, 12514, 198, 11748, 18931, 198, 198, 11748, 279, 893, 3876, 400, 397, 198, 6738, 7007, 13, 1069, 11755, 1330, 3862, 448, 198, 198, 6738, 1363...
3.333333
96
#!/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])) '''
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 28686, 11, 33918, 198, 198, 4798, 7203, 19746, 12, 4906, 25, 2420, 14, 6494, 59, 81, 59, 77, 59, 81, 59, 77, 4943, 198, 4798, 3419, 198, 4798, 7203, 27, 19160, 29, 14402...
2.293785
177
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 ###############################
[ 11748, 28686, 13, 6978, 355, 267, 2777, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 198, 11748, 28034, 198, 6738, 28034, 10178, 13, 26791, 1330, 787, 62, 25928, 198, 6738, 569, 8610, 13, 26791, 13, 25695, 62, 26791, 1...
2.421553
1,262
#! 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""
[ 2, 0, 21015, 18, 198, 198, 37811, 9485, 9288, 12, 38532, 5254, 329, 12351, 14, 37724, 13, 9078, 37227, 198, 198, 11748, 25064, 198, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 4866, 1330, 2769, 30073, 198, 6738, 555, 715, 395, 1330...
3.097983
347
# -*- 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
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 16024, 30516, 2390, 25, 383, 8436, 382, 69, 15451, 41798, 290, 5429, 78, 12, 48307, 14691, 3401, 5028, 198, 2, 15069, 357, 34, 8, 12131, 11, 25455, 417, 18418, 274,...
2.004922
3,657
""" 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)
[ 37811, 198, 694, 86, 70, 1343, 3132, 198, 15269, 1584, 416, 10897, 1574, 11, 3457, 13, 198, 3237, 2489, 10395, 13, 198, 198, 7738, 396, 3890, 290, 779, 287, 2723, 290, 13934, 5107, 11, 351, 393, 1231, 198, 4666, 2649, 11, 389, 10431...
2.38217
2,894
from lanzou.api import LanZouCloud import urllib.parse final_files = [] final_share_infos = [] cookies = ''' ''' if __name__ == '__main__': test()
[ 6738, 26992, 89, 280, 13, 15042, 1330, 14730, 57, 280, 18839, 198, 11748, 2956, 297, 571, 13, 29572, 198, 198, 20311, 62, 16624, 796, 17635, 198, 20311, 62, 20077, 62, 10745, 418, 796, 17635, 628, 628, 628, 198, 198, 27916, 444, 796, ...
2.439394
66
import numpy as np import util.data
[ 11748, 299, 32152, 355, 45941, 198, 11748, 7736, 13, 7890, 628, 628, 628 ]
3.153846
13
# -*- 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))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 31, 9800, 25, 55, 84, 44, 278, 87, 12595, 21, 1731, 31, 38227, 13, 785, 8, 198, 31, 11213, 25, 779, 275, 861, 4886, 442, 3762, 1149, 4049, 198, 37811, ...
2.190736
367
from pydantic import BaseModel
[ 6738, 279, 5173, 5109, 1330, 7308, 17633, 628 ]
4
8
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',]
[ 9288, 796, 685, 198, 220, 220, 220, 705, 77, 404, 1343, 15, 3256, 198, 220, 220, 220, 705, 4134, 1343, 16, 3256, 198, 220, 220, 220, 705, 73, 3149, 1343, 19, 3256, 198, 220, 220, 220, 705, 4134, 1343, 18, 3256, 198, 220, 220, 22...
1.59459
6,026
#----------------------------------# ######### 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)
[ 2, 3880, 438, 2, 198, 7804, 2, 5923, 15972, 2767, 42, 406, 3698, 1137, 46424, 2235, 198, 2, 3880, 438, 2, 198, 198, 2, 1343, 220, 220, 284, 489, 1689, 198, 2, 532, 220, 220, 31789, 198, 2, 1635, 220, 220, 610, 79, 2611, 220, 1...
2.237482
7,449
# -*- 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
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 26796, 15738, 23157, 326, 552, 16746, 257, 4269, 351, 308, 13344, 198, 37811, 198, 6738, 4732, 8019, 1330, 4732, 37153, 198, 6738, 850, 14681, 1330, 8099, 268,...
3.323077
65
# 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')
[ 2, 15069, 1946, 8180, 11421, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921, 743, 7330, 19...
3.763514
296
from .PyrezException import PyrezException
[ 6738, 764, 20519, 21107, 16922, 1330, 9485, 21107, 16922, 198 ]
4.3
10
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
[ 11748, 2878, 198, 6738, 2237, 1330, 13934, 62, 4906, 198, 198, 6738, 1451, 77, 9078, 1330, 50116, 198, 6738, 1451, 77, 9078, 13, 41291, 1330, 616, 354, 81, 198, 6738, 1451, 77, 9078, 13, 1050, 3849, 1330, 3601, 62, 22252, 198, 198, ...
3.228916
83
# -*- 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
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 1485, 319, 2864, 12, 2713, 12, 1415, 8753, 25, 1238, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198,...
2.754386
57
''' 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
[ 7061, 6, 198, 220, 220, 220, 9432, 286, 2393, 13, 9078, 25, 628, 220, 220, 220, 8160, 262, 2134, 1398, 329, 2393, 11, 220, 220, 220, 628, 220, 220, 220, 1321, 284, 2291, 25, 628, 220, 220, 220, 1438, 198, 220, 220, 220, 2546, 28...
2.786325
117
import unittest.mock as mock from app import utils
[ 11748, 555, 715, 395, 13, 76, 735, 355, 15290, 198, 198, 6738, 598, 1330, 3384, 4487, 628 ]
3.117647
17
#!/usr/bin/env python3 import argparse import datetime import os import matplotlib.pyplot as plt import pandas as pd if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 1822, 29572, 198, 11748, 4818, 8079, 198, 11748, 28686, 198, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 19798, 292, 355, 279, 67, 628, 19...
2.666667
60
# 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'
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 15069, 12131, 383, 309, 22854, 37535, 16092, 292, 1039, 46665, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 77...
3.628989
752
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"])
[ 11748, 19798, 292, 355, 279, 67, 198, 198, 11748, 384, 397, 1211, 355, 3013, 82, 198, 198, 82, 5907, 13, 2617, 3419, 198, 198, 2, 1343, 15940, 28, 14692, 17143, 7307, 8973, 198, 929, 5532, 796, 14631, 15002, 62, 11249, 654, 8973, 19...
2.474227
194
#!/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
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 7061, 6, 198, 15269, 2864, 9966, 2892, 13331, 198, 198, 26656, 15385, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 5832, 743, 407, 779, 428, 2393, 2845, ...
3.789809
157
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()
[ 6738, 28493, 13414, 7483, 13, 528, 4125, 6359, 13, 3642, 50221, 13, 528, 37724, 1330, 28493, 9487, 274, 198, 198, 834, 9800, 834, 796, 705, 69, 5171, 292, 6, 198, 198, 11748, 555, 715, 395, 198, 198, 6738, 28493, 13414, 7483, 13, 52...
2.792035
226
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
[ 6738, 17331, 22163, 70, 17, 13, 7742, 1330, 14122, 276, 32048, 27201, 198, 11748, 17331, 22163, 70, 17, 13, 2302, 8847, 198, 11748, 17331, 22163, 70, 17, 13, 25410, 355, 44161, 198, 6738, 4732, 8019, 1330, 4732, 37153, 198, 6738, 4704, ...
3.241379
116
"""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
[ 37811, 42, 2171, 477, 8787, 422, 257, 1813, 49246, 4382, 526, 15931, 628, 198, 11748, 18931, 198, 11748, 302, 198, 198, 11748, 3904, 198, 11748, 479, 1031, 2238, 198, 198, 6738, 49246, 1330, 4931, 198, 6738, 49246, 1330, 3384, 4487, 198...
2.441322
1,210
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"), ]
[ 11748, 28686, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 198, 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 13, 72, 1507, 77, 1330, 1312, 1507, 77, 62, 33279, 82, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 2291, 11, 3108, 11, 3...
2.340892
1,367
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
[ 6738, 10558, 88, 1330, 357, 28532, 452, 876, 11, 38357, 8, 198, 6738, 10558, 88, 13, 7295, 13, 77, 17024, 1330, 314, 198, 6738, 10558, 88, 13, 7295, 13, 2411, 864, 1330, 412, 80, 198, 6738, 10558, 88, 13, 7295, 13, 1837, 23650, 13...
2.34708
8,511
import os EAGER_MODE_DEBUG = os.environ.get("EAGER_MODE_DEBUG", 'False').lower() in ('true', '1', 't')
[ 11748, 28686, 198, 198, 36, 4760, 1137, 62, 49058, 62, 30531, 796, 28686, 13, 268, 2268, 13, 1136, 7203, 36, 4760, 1137, 62, 49058, 62, 30531, 1600, 705, 25101, 27691, 21037, 3419, 287, 19203, 7942, 3256, 705, 16, 3256, 705, 83, 11537...
2.418605
43
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
[ 11748, 25064, 198, 11748, 28686, 198, 11748, 20218, 7753, 198, 6738, 3108, 8019, 1330, 10644, 198, 11748, 12972, 9288, 198, 198, 17597, 13, 6978, 13, 28463, 7, 16, 11, 28686, 13, 6978, 13, 22179, 7, 17597, 13, 6978, 58, 15, 4357, 366,...
2.859649
57
""" 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
[ 37811, 198, 30150, 966, 329, 262, 43749, 198, 37811, 198, 198, 11748, 18931, 198, 11748, 3904, 198, 198, 6738, 6072, 44506, 1330, 11593, 9641, 834, 198, 6738, 764, 25811, 1330, 14257, 62, 18076, 198, 6738, 764, 22866, 1330, 30532, 198, ...
2.884058
207
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()
[ 11748, 6468, 198, 11748, 19720, 355, 256, 198, 11748, 3146, 198, 11748, 33918, 198, 6738, 266, 271, 538, 88, 13, 48186, 1330, 33445, 198, 6738, 2297, 88, 13, 33637, 13, 15235, 25835, 1330, 10644, 198, 48186, 796, 33445, 3419, 628, 628, ...
3.177419
62
# 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")
[ 2, 15069, 33448, 41689, 1628, 20420, 357, 3826, 27342, 9865, 3843, 20673, 13, 9132, 737, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 3826, 38559, 24290, 737, 198, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, ...
2.953419
1,009
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
[ 11748, 33829, 198, 6738, 44161, 282, 26599, 1330, 29201, 11, 8708, 9218, 11, 10903, 11, 19449, 11, 34142, 11, 2039, 388, 198, 6738, 44161, 282, 26599, 13, 579, 1330, 2776, 198, 198, 6738, 1382, 62, 5832, 13, 27530, 13, 8692, 1330, 730...
3.867925
53
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
[ 6738, 764, 19849, 1330, 10766, 17822, 4965, 7934, 17633, 198, 6738, 764, 71, 66, 62, 67, 1453, 489, 397, 1330, 15079, 39470, 62, 35, 1453, 489, 397, 85, 17, 198, 6738, 764, 9060, 62, 46862, 1330, 7412, 33634, 11, 1100, 62, 7890, 62,...
2.959596
99
# 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']
[ 2, 17923, 3519, 3307, 198, 4871, 2649, 62, 19608, 292, 1039, 796, 37250, 320, 11286, 316, 3256, 705, 66, 25634, 20520, 198, 4871, 2649, 62, 1416, 704, 377, 364, 796, 37250, 34021, 3256, 705, 565, 81, 3256, 705, 12114, 10236, 3256, 705...
2.780083
241
# 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
[ 2, 21004, 25, 3384, 69, 12, 23, 198, 2, 8265, 1592, 2624, 13317, 198, 2, 422, 327, 7479, 37906, 1983, 59, 8019, 59, 15654, 12, 43789, 59, 5404, 2624, 59, 5404, 2624, 13317, 13, 79, 5173, 198, 2, 416, 17301, 352, 13, 20198, 198, ...
3.387283
519
# !/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)
[ 2, 5145, 14, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 7575, 220, 220, 220, 220, 1058, 12131, 14, 18, 14, 19, 38326, 362, 25, 2931, 198, 2, 2488, 13838, 220, ...
2.5189
291
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())
[ 11748, 18931, 198, 198, 6738, 1822, 29572, 1330, 45751, 46677, 198, 198, 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 11, 1064, 62, 26518, 24330, 198, 6738, 764, 11250, 1330, 3440, 198, 6738, 764, 7295, 13, 11499, 1330, 923, 62, 26...
3.077253
233
#!/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()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 201, 198, 2, 19617, 28, 40477, 12, 23, 201, 198, 201, 198, 11748, 15095, 201, 198, 11748, 3904, 201, 198, 11748, 28686, 201, 198, 11748, 33918, 201, 198, 11748, 4818, 8079, 201, 198, 11748,...
2.747212
269