diff --git "a/4457.jsonl" "b/4457.jsonl" new file mode 100644--- /dev/null +++ "b/4457.jsonl" @@ -0,0 +1,631 @@ +{"seq_id":"368023011","text":"#!/usr/bin/python3.5\n#\n# updated by ...: Loreto Notarantonio\n# Version ......: 03-12-2017 08.33.41\n# -----------------------------------------------\n\nimport sys\nimport Source as Prj\nimport LnLib as Ln; C = Ln.Color()\n\n\nclass LnClass(): pass\n\n#######################################################\n# USER ParseInput\n# identificare il numero di parametri posizionali\n# e creare le funzioni che verranno chiamate automaticamente:\n# nPosizARGS == 0: programOptions()\n# nPosizARGS == 1: posizParam.upper()\n# nPosizARGS == 2: posizParam1.upper()_posizParam2.upper()\n# che dovranno essere tutti raggiungibili tramite:\n# Prj.function()\n#######################################################\ndef ParseInput(description='Ln-RS485 protocol', programVersion='V0.1'):\n\n nPosizARGS = 2\n positionalParametersDict = {\n 'analog' : {\n 'read': \"read analog bit\",\n 'write': \"write analog bit\",\n },\n 'digital' : {\n 'read': \"read digital bit\",\n 'write': \"write digital bit\",\n 'toggle': \"toggle digital bit\",\n },\n 'monitor' : {\n 'rs485': \"read RS485-bus traffic\",\n 'raw': \"read RS485-bus raw traffic\",\n },\n }\n\n\n # ----------------------------------\n # - dict da passare alle funzioni\n # ----------------------------------\n gVar = LnClass()\n\n gVar.projectDir = None\n gVar.prjName = None\n gVar.programVersion = programVersion\n gVar.description = description\n\n gVar.nPosizARGS = nPosizARGS\n gVar.positionalParametersDict = positionalParametersDict\n\n args = Ln.processInput(gVar, prjRoot=Prj)\n\n return args\n Ln.Exit(9999)\n\n","sub_path":"LnProtocol/py485/Source/Setup/Main_ParseInput.py","file_name":"Main_ParseInput.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"65868736","text":"import psycopg2\nimport serial\nimport struct\n\ninsert_reading = (\n 'insert into sens.sensor_data (sensor_id, device_id, reading) '\n 'values (%s, %s, %s)'\n)\n\n\ndef main():\n ser = serial.Serial('/dev/ttyACM0', 9600)\n connection = psycopg2.connect(\n \"host=hdtv dbname=sens user=sensuser password='senspassword'\"\n )\n cursor = connection.cursor()\n\n while True:\n vcc_raw = struct.unpack('H', ser.read(2))[0]\n cursor.execute(\n insert_reading,\n ('vcc', 0, vcc_raw)\n )\n connection.commit()\n temp_raw = struct.unpack('H', ser.read(2))[0]\n cursor.execute(\n insert_reading,\n ('temp', 0, temp_raw)\n )\n connection.commit()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/sensor-store/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"608984256","text":"from toontown.building.DistributedCFOElevatorAI import DistributedCFOElevatorAI\n\n\nclass DistributedDeadlyCFOElevatorAI(DistributedCFOElevatorAI):\n notify = directNotify.newCategory('DistributedDeadlyCFOElevatorAI')\n\n def sendAvatarsToDestination(self, avIdList):\n if len(avIdList) > 0:\n bossZone = self.bldg.createBossOffice(avIdList, isDeadly=True)\n for avId in avIdList:\n if avId:\n self.sendUpdateToAvatarId(avId, 'setBossOfficeZoneForce', [bossZone])\n","sub_path":"toontown/building/DistributedDeadlyCFOElevatorAI.py","file_name":"DistributedDeadlyCFOElevatorAI.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"360124426","text":"\n\n#calss header\nclass _FOOD():\n\tdef __init__(self,): \n\t\tself.name = \"FOOD\"\n\t\tself.definitions = [u'something that people and animals eat, or plants absorb, to keep them alive: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_food.py","file_name":"_food.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"109801466","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 4 19:34:32 2021\n\n@author: User\n\"\"\"\nimport tkinter as tki\nimport tkinter.ttk as ttk\nimport pandas as pd\n\ndb_1 = pd.read_excel('C:/Work/Data/Pokname.xlsx',sheet_name='Sheet1', index_col=(0))\ndb_3 = pd.read_excel('C:/Work/Data/pdx.xlsx',sheet_name='Sheet1', index_col=(0))\n\ndef clck():\n '''\n Parameters\n ----------\n -------\n None.\n '''\n df_1 = pd.read_excel('C:/Work/Data/Pokname.xlsx',sheet_name='Sheet1', index_col=(0))\n df_3 = pd.read_excel('C:/Work/Data/pdx.xlsx',sheet_name='Sheet1', index_col=(0))\n\n df_1 = df_1.drop(db_1[db_1['Name']==cmb_1.get()].index[0])\n df_3 = df_3.drop(db_1[db_1['Name']==cmb_1.get()].index[0])\n\n df_1.to_excel('C:/Work/Data/Pokname.xlsx',sheet_name='Sheet1')\n df_3.to_excel('C:/Work/Data/pdx.xlsx', sheet_name='Sheet1')\n win1.destroy()\n\nwin1= tki.Tk()\nwin1.title('Удаление покемона из базы данных')\nwin1.geometry('400x250+300+200')\nvar_3 = []\nlist_id =[]\nc = []\nlen_ = db_1[\"Name\"]\n\nlbl_3 = tki.Label(win1, text = 'Выберите покемона для удаления', font = ('Times', 12))\nlbl_3.place(x = 0, y = 0)\n\ncmb_1 = ttk.Combobox(win1)\ncmb_1['values'] = list(len_)\ncmb_1.current(0)\ncmb_1.focus()\ncmb_1.place(x=0, y = 30)\n\nbtn_6 = tki.Button(win1, text = \"Удалить\", font = ('Times', 12), command = clck)\nbtn_6.place(x = 250, y =0, width = 100, height = 35 )\n\nwin1.mainloop()\n","sub_path":"Library/win_del.py","file_name":"win_del.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"556827328","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# __coconut_hash__ = 0x8319fbcb\n\n# Compiled with Coconut version 1.4.3-post_dev46 [Ernest Scribbler]\n\n\"\"\"\nThe mixture backend. Lets you specify a distribution over different possible algorithms.\n\"\"\"\n\n# Coconut Header: -------------------------------------------------------------\n\nfrom __future__ import print_function, absolute_import, unicode_literals, division\nimport sys as _coconut_sys, os.path as _coconut_os_path\n_coconut_file_path = _coconut_os_path.dirname(_coconut_os_path.dirname(_coconut_os_path.abspath(__file__)))\n_coconut_cached_module = _coconut_sys.modules.get(str(\"__coconut__\"))\nif _coconut_cached_module is not None and _coconut_os_path.dirname(_coconut_cached_module.__file__) != _coconut_file_path:\n del _coconut_sys.modules[str(\"__coconut__\")]\n_coconut_sys.path.insert(0, _coconut_file_path)\nfrom __coconut__ import *\nfrom __coconut__ import _coconut, _coconut_MatchError, _coconut_igetitem, _coconut_base_compose, _coconut_forward_compose, _coconut_back_compose, _coconut_forward_star_compose, _coconut_back_star_compose, _coconut_forward_dubstar_compose, _coconut_back_dubstar_compose, _coconut_pipe, _coconut_star_pipe, _coconut_dubstar_pipe, _coconut_back_pipe, _coconut_back_star_pipe, _coconut_back_dubstar_pipe, _coconut_none_pipe, _coconut_none_star_pipe, _coconut_none_dubstar_pipe, _coconut_bool_and, _coconut_bool_or, _coconut_none_coalesce, _coconut_minus, _coconut_map, _coconut_partial, _coconut_get_function_match_error, _coconut_base_pattern_func, _coconut_addpattern, _coconut_sentinel, _coconut_assert, _coconut_mark_as_match\nif _coconut_sys.version_info >= (3,):\n _coconut_sys.path.pop(0)\n\n# Compiled Coconut: -----------------------------------------------------------\n\n\n\nimport random\n\nfrom bbopt.registry import alg_registry\nfrom bbopt.registry import init_backend\nfrom bbopt.backends.util import Backend\n\n\nclass MixtureBackend(Backend):\n \"\"\"Mixture backend. Takes in a distribution over different possible algorithms\n of the form [(algorithm, weight)]. The properties selected_alg and selected_backend\n can be used to retrieve which alg/backend is currently being used.\"\"\"\n backend_name = \"mixture\"\n\n def __init__(self, examples, params, distribution):\n total_weight = sum((weight for alg, weight in distribution))\n\n# generate cutoff points\n self.cum_probs = []\n prev_cutoff = 0\n for alg, weight in distribution:\n cutoff = prev_cutoff + weight / total_weight\n self.cum_probs.append((alg, cutoff))\n prev_cutoff = cutoff\n\n self.backend_store = {}\n self.tell_examples(examples, params)\n\n def tell_examples(self, examples, params):\n \"\"\"Special method that allows fast updating of the backend with new examples.\"\"\"\n# randomly select algorithm\n rand_val = random.random()\n self.selected_alg = None\n for alg, cutoff in self.cum_probs:\n if rand_val <= cutoff:\n self.selected_alg = alg\n break\n\n# initialize backend\n self.selected_backend, options = alg_registry[self.selected_alg]\n self.current_backend = init_backend(self.selected_backend, examples, params, attempt_to_update_backend=self.backend_store.get(self.selected_alg), **options)\n self.backend_store[self.selected_alg] = self.current_backend\n\n def param(self, name, func, *args, **kwargs):\n \"\"\"Defer parameter selection to the selected backend.\"\"\"\n return self.current_backend.param(name, func, *args, **kwargs)\n\n\n# Registered names:\n\nMixtureBackend.register()\n","sub_path":"bbopt/backends/mixture.py","file_name":"mixture.py","file_ext":"py","file_size_in_byte":3609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"139521794","text":"\n\n#calss header\nclass _PEACH():\n\tdef __init__(self,): \n\t\tself.name = \"PEACH\"\n\t\tself.definitions = [u'a round fruit with sweet yellow flesh that has a lot of juice, a slightly furry red and yellow skin, and a large seed in its centre: ', u'someone or something that is excellent or very pleasing: ', u'a pale colour between pink and orange']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_peach.py","file_name":"_peach.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"567666743","text":"import h5py\r\nimport numpy as np\r\nimport os\r\nimport tensorflow as tf\r\nimport tensorflow.keras.models as Model\r\nfrom tensorflow.keras.layers import Input, Reshape, Conv2D, Flatten, Dense, Activation, MaxPooling2D, AlphaDropout, AveragePooling2D, BatchNormalization, UpSampling2D\r\nimport matplotlib.pyplot as plt\r\nimport json\r\nimport pandas as pd\r\nimport time\r\n## 环境配置\r\ntf.compat.v1.get_default_graph\r\ntf.compat.v1.disable_v2_behavior()\r\ntf.compat.v1.enable_eager_execution()\r\n# 使用GUP运行\r\ngpu_options = tf.GPUOptions(allow_growth=True)\r\ngpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.9, allow_growth=True) #每个gpu占用0.9的显存\r\nconfig = tf.ConfigProto(gpu_options=gpu_options, allow_soft_placement=True)\r\nsess = tf.Session(config=config)#如果电脑有多个GPU,tensorflow默认全部使用。如果想只使用部分GPU,可以设置CUDA_VISIBLE_DEVICES。\r\nos.environ[\"KERAS_BACKEND\"] = \"tensorflow\"\r\nplt.rcParams['font.sans-serif'] = ['SimHei']\r\nplt.rcParams['axes.unicode_minus'] = False\r\n############################################\r\nepochs_num = 50\r\nFloor = 3\r\nL = 128\r\nfor i in range(0, 4):\r\n ########打开文件#######\r\n filename = 'C:/Users/Administrator/Desktop/CL_project/CL_project/test_data' + str(i) + '.h5' # 数据集地址\r\n filename1 = 'C:/Users/Administrator/Desktop/CL_project/CL_project/test_data' + str(i) + '.h5' # 标签集地址\r\n filename2 = 'C:/Users/Administrator/Desktop/CL_project/CL_project/test_data' + str(i) + '.h5' # 信噪比集地址\r\n print(filename)\r\n print(filename1)\r\n print(filename2)\r\n f = h5py.File(filename, 'r')\r\n f1 = h5py.File(filename1, 'r')\r\n f2 = h5py.File(filename2, 'r')\r\n ########读取数据#######\r\n ####以上步骤通过matlab存成h5文件,存成三维,x为训练数据,y为训练数据标签,z为信噪比。\r\n X_data = f['X'][:, :]\r\n Y_data = f1['Y'][:, :]\r\n Z_data = f2['Z'][:, :]\r\n f.close()\r\n f1.close()\r\n f2.close()\r\n #########分割训练集和测试集#########\r\n #每读取到一个数据文件就直接分割为训练集和测试集,防止爆内存\r\n n_examples = X_data.shape[0]\r\n n_train = int(n_examples * 0.85)\r\n train_idx = np.random.choice(range(0, n_examples), size=n_train, replace=False)#随机选取训练样本下标\r\n # train_idx = range(0, n_examples)# 随机选取训练样本下标\r\n test_idx = list(set(range(0, n_examples))-set(train_idx)) #测试样本下标\r\n if i == 0:\r\n X_train = X_data[train_idx]\r\n Y_train = Y_data[train_idx]\r\n Z_train = Z_data[train_idx]\r\n X_test = X_data[test_idx]\r\n Y_test = Y_data[test_idx]\r\n Z_test = Z_data[test_idx]\r\n else:\r\n X_train = np.vstack((X_train, X_data[train_idx]))\r\n Y_train = np.vstack((Y_train, Y_data[train_idx]))\r\n Z_train = np.vstack((Z_train, Z_data[train_idx]))\r\n X_test = np.vstack((X_test, X_data[test_idx]))\r\n Y_test = np.vstack((Y_test, Y_data[test_idx]))\r\n Z_test = np.vstack((Z_test, Z_data[test_idx]))\r\nprint('Dimension of training set X:', X_train.shape)\r\nprint('Dimension of training set Y:', Y_train.shape)\r\nprint('Dimension of training set Z:', Z_train.shape)\r\nprint('Dimension of test set X:', X_test.shape)\r\nprint('Dimension of test set Y:', Y_test.shape)\r\nprint('Dimension of test set Z:', Z_test.shape)\r\n\r\n\"\"\"建立模型\"\"\"\r\nclasses = ['Num_Sig_1', 'Num_Sig_2', 'Num_Sig_3', 'Num_Sig_4']\r\ndata_format = 'channels_first'\r\n# 以上的标签需要与MATLAB所输出的标签打成一致\r\n\r\n# 定义每个epoch的训练时间\r\nclass TimeHistory(tf.keras.callbacks.Callback):\r\n def on_train_begin(self, logs={}):\r\n self.times = []\r\n self.totaltime = time.time()\r\n\r\n def on_train_end(self, logs={}):\r\n self.totaltime = time.time() - self.totaltime\r\n\r\n def on_epoch_begin(self, batch, logs={}):\r\n self.epoch_time_start = time.time()\r\n\r\n def on_epoch_end(self, batch, logs={}):\r\n self.times.append(time.time() - self.epoch_time_start)\r\n\r\ndef residual_stack(Xm, filter_num, kennel_size,Seq,pool_size):\r\n #1*1 Conv Linear\r\n Xm = tf.keras.layers.Conv2D(filter_num, (1, 1), padding='same', name=Seq+\"_conv1\", kernel_initializer='glorot_normal',data_format=data_format, kernel_regularizer=tf.keras.regularizers.l2(0.03))(Xm)\r\n #Residual Unit 1\r\n Xm_shortcut = Xm\r\n Xm = tf.keras.layers.Conv2D(filter_num, kennel_size, padding='same', activation=\"relu\",name=Seq+\"_conv2\", kernel_initializer='glorot_normal', data_format=data_format, kernel_regularizer=tf.keras.regularizers.l2(0.03))(Xm)\r\n Xm = tf.keras.layers.Conv2D(filter_num, kennel_size, padding='same', name=Seq+\"_conv3\", kernel_initializer='glorot_normal', data_format=data_format, kernel_regularizer=tf.keras.regularizers.l2(0.03))(Xm)\r\n\r\n Xm = tf.keras.layers.add([Xm, Xm_shortcut])\r\n Xm = Activation(\"relu\")(Xm)\r\n Xm = tf.keras.layers.BatchNormalization(axis=1, scale=True)(Xm)\r\n #Residual Unit 2\r\n Xm_shortcut = Xm\r\n Xm = tf.keras.layers.Conv2D(filter_num, kennel_size, padding='same', activation=\"relu\", name=Seq+\"_conv4\", kernel_initializer='glorot_normal', data_format=data_format, kernel_regularizer=tf.keras.regularizers.l2(0.03))(Xm)\r\n Xm = tf.keras.layers.Conv2D(filter_num, kennel_size, padding='same', name=Seq + \"_conv5\", kernel_initializer='glorot_normal', data_format=data_format, kernel_regularizer=tf.keras.regularizers.l2(0.03))(Xm)\r\n\r\n Xm = tf.keras.layers.add([Xm, Xm_shortcut]) # 网络分别处理后的融合\r\n Xm = Activation(\"relu\")(Xm)\r\n Xm = tf.keras.layers.BatchNormalization(axis=1, scale=True)(Xm)\r\n #MaxPooling\r\n Xm = MaxPooling2D(pool_size=pool_size, strides=pool_size, padding='valid', data_format=data_format)(Xm)\r\n return Xm\r\n\r\n## FPN类型\r\ndef FPN(Xm, filter_num, UP_size, UP_name):#定义残差块\r\n Xm = tf.keras.layers.Conv2D(filter_num, (1, 1), name='line'+UP_name)(Xm)\r\n Xm = tf.keras.layers.UpSampling2D(size=UP_size, name=UP_name)(Xm)\r\n return Xm\r\n## PAN类型\r\ndef PAN(Xm, filter_num, kennel_size, Conv_name, pool_size, strides, upsample=True):# 定义PAN中的GAU,每次调用时需要对卷积核大小进行定义,以及条件语句的限定\r\n if upsample:\r\n Xm = tf.keras.layers.Conv2D(filter_num, kennel_size, padding='same', activation=\"relu\", name=Conv_name)(Xm)\r\n Xm = tf.keras.layers.BatchNormalization(axis=1, scale=True)(Xm)\r\n Xm = tf.keras.layers.MaxPooling2D(pool_size=pool_size, strides=strides)(Xm)\r\n else:\r\n Xm = tf.keras.layers.AveragePooling2D(pool_size=(1, 1), strides=1)(Xm)\r\n Xm = tf.keras.layers.Conv2D(filter_num, kennel_size, padding='same', activation=\"relu\", name=Conv_name)(Xm)\r\n Xm = tf.keras.layers.Conv2D(filter_num, (1, 1), padding='same', activation=\"relu\")(Xm)\r\n Xm = tf.keras.layers.BatchNormalization(axis=1, scale=True)(Xm)\r\n Xm = tf.keras.layers.MaxPooling2D(pool_size=pool_size, strides=strides)(Xm)\r\n return Xm\r\nin_shp = X_train.shape[1:] #每个样本的维度[1024,2]\r\n#input layer\r\nXm_input = Input(in_shp)\r\n# Xm = Xm_input\r\nXm = Reshape([1, L, 10], input_shape=in_shp)(Xm_input)\r\n#Residual Stack\r\nXm = residual_stack(Xm, 32, kennel_size=(2, 2), Seq=\"ReStk0\", pool_size=(2, 1))#shape:(512,1,32),卷积核为3×2,代表每次维度递减一半,列数减少为1\r\nsqueeze = tf.keras.layers.GlobalAveragePooling2D()(Xm)\r\nexcitation = Dense(16, activation='relu', kernel_initializer='glorot_normal')(squeeze)\r\nexcitation = Dense(32, kernel_initializer='glorot_normal')(excitation)\r\nexcitation = Activation('sigmoid')(excitation)\r\nexcitation = Reshape([32, 1, 1])(excitation)\r\nXm = Xm*excitation\r\nXm_R1 = Xm\r\nXm = residual_stack(Xm, 32, kennel_size=(2, 2), Seq=\"ReStk1\", pool_size=(2, 1))#shape:(256,1,32),\r\nsqueeze = tf.keras.layers.GlobalAveragePooling2D()(Xm)\r\nexcitation = Dense(16, activation='relu', kernel_initializer='glorot_normal')(squeeze)\r\nexcitation = Dense(32, kernel_initializer='glorot_normal')(excitation)\r\nexcitation = Activation('sigmoid')(excitation)\r\nexcitation = Reshape([32, 1, 1])(excitation)\r\nXm = Xm*excitation\r\nXm_R2 = Xm\r\nXm = residual_stack(Xm, 32, kennel_size=(2, 2), Seq=\"ReStk2\", pool_size=(2, 1))#shape:(128,1,32)\r\nsqueeze = tf.keras.layers.GlobalAveragePooling2D()(Xm)\r\nexcitation = Dense(16, activation='relu', kernel_initializer='glorot_normal')(squeeze)\r\nexcitation = Dense(32, kernel_initializer='glorot_normal')(excitation)\r\nexcitation = Activation('sigmoid')(excitation)\r\nexcitation = Reshape([32, 1, 1])(excitation)\r\nXm = Xm*excitation\r\nXm_R3 = Xm\r\nXm = residual_stack(Xm, 32, kennel_size=(2, 2), Seq=\"ReStk3\", pool_size=(2, 1))#shape:(64,1,32)\r\nsqueeze = tf.keras.layers.GlobalAveragePooling2D()(Xm)\r\nexcitation = Dense(16, activation='relu', kernel_initializer='glorot_normal')(squeeze)\r\nexcitation = Dense(32, kernel_initializer='glorot_normal')(excitation)\r\nexcitation = Activation('sigmoid')(excitation)\r\nexcitation = Reshape([32, 1, 1])(excitation)\r\nXm = Xm*excitation\r\nXm_Y = Xm\r\nprint(Xm_Y.shape)\r\n## FPN结构添加 FPN(Xm, filter_num, kennel_size, UP_name)\r\nXm = FPN(Xm, filter_num=10, UP_size=(1, 2), UP_name=\"p5_up\")\r\nXm_Conv1 = tf.keras.layers.Conv2D(10, (2, 2), padding=\"SAME\", name=\"p5_cov\")(Xm)\r\nXm = Xm+Xm_R3\r\nXm = FPN(Xm, filter_num=10, UP_size=(1, 2), UP_name=\"p4_up\")\r\nprint(Xm.shape)\r\nXm_Conv2 = tf.keras.layers.Conv2D(10, (2, 2), padding=\"SAME\", name=\"p4_cov\")(Xm)\r\nprint(Xm.shape)\r\nprint(Xm_R2.shape)\r\nXm = Xm+Xm_R2\r\nXm = FPN(Xm, filter_num=10, UP_size=(1, 2), UP_name=\"p3_up\")\r\nXm_Conv3 = tf.keras.layers.Conv2D(10, (2, 2), padding=\"SAME\", name=\"p3_cov\")(Xm)\r\nXm = Xm+Xm_R1\r\nXm = FPN(Xm, filter_num=10, UP_size=(1, 2), UP_name=\"p2_up\")\r\nXm_Conv4 = tf.keras.layers.Conv2D(10, (2, 2), padding=\"SAME\", name=\"p2_cov\")(Xm)\r\n## PAN结构的搭建,不仅是下采样,对分别从高维语义特征与低维语义特征进行分析处理print(Xm.shape),print(Xm_Conv4.shape)\r\nXm = PAN(Xm, filter_num=10, kennel_size=(1, 2), Conv_name=\"PAN_Conv1\", pool_size=(1, 1), strides=(1, 1), upsample=True)\r\nXm = Xm+Xm_Conv4\r\nXm = PAN(Xm, filter_num=10, kennel_size=(1, 2), Conv_name=\"PAN_Conv2\", pool_size=(1, 2), strides=(1, 2), upsample=True)\r\nXm = Xm+Xm_Conv3\r\nXm = PAN(Xm, filter_num=10, kennel_size=(1, 2), Conv_name=\"PAN_Conv3\", pool_size=(1, 2), strides=(1, 2), upsample=True)\r\nXm = Xm+Xm_Conv2\r\nXm = PAN(Xm, filter_num=10, kennel_size=(1, 2), Conv_name=\"PAN_Conv4\", pool_size=(1, 2), strides=(1, 2), upsample=False)\r\nXm = Xm+Xm_Conv1\r\nXm = PAN(Xm, filter_num=10, kennel_size=(1, 2), Conv_name=\"PAN_Conv5\", pool_size=(1, 2), strides=(1, 2), upsample=False)\r\nXm = Xm+Xm_Y\r\nprint(Xm.shape)\r\n\r\n#Full Con 1\r\nXm = Flatten(data_format=data_format)(Xm)\r\n# Xm = Dense(32, activation='selu', kernel_initializer='glorot_normal', name=\"dense1\")(Xm)\r\nXm = AlphaDropout(0.3)(Xm)# 丢弃率\r\n#Full Con 2\r\nXm = Dense(len(classes), kernel_initializer='glorot_normal', name=\"dense2\")(Xm)\r\n#SoftMax\r\nXm = Activation('softmax')(Xm)\r\n#Create Model\r\nmodel = Model.Model(inputs=Xm_input, outputs=Xm)\r\nadam = tf.keras.optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)\r\nmodel.compile(loss='categorical_crossentropy', optimizer=adam)\r\nmodel.summary()\r\n\r\n\"\"\"训练模型\"\"\"\r\n\r\nprint(tf.test.gpu_device_name())\r\nfilepath = 'C:/pycharm/ResNet-for-Radio-Recognition/own_models/ResNet_Model_72w.h5'\r\n\r\nmodel.compile(loss='categorical_crossentropy',\r\n optimizer=adam,\r\n metrics=['categorical_accuracy'])\r\n\r\ntime_callback = TimeHistory()\r\nhistory = model.fit(X_train,\r\n Y_train,\r\n batch_size=128,\r\n epochs=epochs_num,#100\r\n verbose=2,\r\n validation_data=(X_test, Y_test),\r\n callbacks=[\r\n tf.keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=0, save_best_only=True, mode='auto'),\r\n tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='auto'), time_callback\r\n ])\r\nscores = model.evaluate(X_train, Y_train)\r\nmodel.load_weights(filepath)\r\n\r\nwith open('model_struct_1_R.json', 'w') as f:\r\n json.dump(model.to_json(), f)\r\nmodel.save_weights('model_weights_1_R.h5')\r\n\r\nloss_list = history.history['loss']\r\nval_loss_list = history.history['val_loss']\r\nplt.plot(range(len(loss_list)), loss_list, linewidth=2)\r\nplt.plot(range(len(loss_list)), val_loss_list, linewidth=2)\r\n# plt.title(\"Loss\", fontsize=18)\r\nplt.ylabel(\"loss\", fontsize=15)\r\nplt.xlabel(\"Number of iterations\", fontsize=15)\r\nplt.legend([\"training loss\", \"test loss\"], loc=\"upper right\")\r\nplt.savefig(\"loss and val_loss.png\", format='png', dpi=300, bbox_inches = 'tight')\r\nplt.show()\r\n\r\ndef plot_confusion_matrix(cm, title, cmap=plt.cm.gray_r, labels=[]):\r\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\r\n # plt.title(title, fontsize=15)\r\n plt.colorbar()\r\n tick_marks = np.arange(len(labels))\r\n plt.xticks(tick_marks, labels, rotation=45)\r\n plt.yticks(tick_marks, labels)\r\n plt.tight_layout()\r\n plt.ylabel('True label', fontsize=12)\r\n plt.xlabel('Predicted label', fontsize=12)\r\n plt.savefig(title, format='png', dpi=300, bbox_inches = 'tight')\r\n plt.show()\r\n# Plot.confusion matrix\r\nbatch_size = 1024\r\ntest_Y_hat = model.predict(X_test, batch_size=1024)\r\nconf = np.zeros([len(classes), len(classes)])\r\nconfnorm = np.zeros([len(classes), len(classes)])\r\nfor i in range(0, X_test.shape[0]):\r\n j = list(Y_test[i, :]).index(1)\r\n k = int(np.argmax(test_Y_hat[i, :]))\r\n conf[j, k] = conf[j, k] + 1\r\nfor i in range(0, len(classes)):\r\n confnorm[i, :] = conf[i, :] / np.sum(conf[i, :])\r\nplot_confusion_matrix(confnorm, title='Confusion matrix.png', labels=classes)\r\n\r\nfor i in range(len(confnorm)):\r\n print(classes[i], confnorm[i, i])\r\n\r\nacc = {}\r\nZ_test = Z_test.reshape((len(Z_test)))\r\nSNRs = np.unique(Z_test)\r\nfor snr in SNRs:\r\n X_test_snr = X_test[Z_test == snr]\r\n Y_test_snr = Y_test[Z_test == snr]\r\n\r\n pre_Y_test = model.predict(X_test_snr)\r\n conf = np.zeros([len(classes), len(classes)])\r\n confnorm = np.zeros([len(classes), len(classes)])\r\n for i in range(0, X_test_snr.shape[0]): # 该信噪比下测试数据量\r\n j = list(Y_test_snr[i, :]).index(1) # 正确类别下标\r\n j = classes.index(classes[j])\r\n k = int(np.argmax(pre_Y_test[i, :])) # 预测类别下标\r\n k = classes.index(classes[k])\r\n conf[j, k] = conf[j, k] + 1\r\n for i in range(0, len(classes)):\r\n confnorm[i, :] = conf[i, :] / np.sum(conf[i, :])\r\n\r\n # plt.figure()\r\n plot_confusion_matrix(confnorm, labels=classes, title=\"ConvNet Confusion Matrix (SNR=%d).png\" % (snr))\r\n cor = np.sum(np.diag(conf))\r\n ncor = np.sum(conf) - cor\r\n print(\"Overall Accuracy %s: \" % snr, cor / (cor + ncor))\r\n acc[snr] = 1.0 * cor / (cor + ncor)\r\n\r\n# 图形绘制\r\nplt.plot(acc.keys(), acc.values(), 'o-', color='blue', linewidth=2)\r\nplt.ylabel('Recognition accuracy', fontsize=12)\r\nplt.xlabel('SNR', fontsize=12)\r\nplt.savefig(\"model_acc.png\", format='png', dpi=300, bbox_inches='tight')\r\nres = np.vstack((acc.keys(), acc.values()))\r\nsavefile_name = 'Layer_num=' + str(Floor) + '.txt'\r\nnp.savetxt(savefile_name, res, delimiter=',', fmt='%s')\r\nplt.show()\r\n\r\n#存储训练与测试损失值与精度\r\npd.DataFrame.from_dict(history.history).to_csv(\"Loss_ACC.csv\", float_format=\"%.5f\", index=False)\r\n\r\nplt.plot(history.history['categorical_accuracy'], 'o-', color='blue', linewidth=2)\r\nplt.xlim((0, epochs_num))\r\nplt.ylim((0, 1))\r\nplt.ylabel(\"Recognition accuracy\", fontsize=15)\r\nplt.xlabel(\"Number of iterations\", fontsize=15)\r\nplt.savefig(\"model_acc.png\", format='png', dpi=300, bbox_inches = 'tight')\r\nX = list(range(0, epochs_num))# 迭代次数\r\nres1 = np.vstack((X, history.history['categorical_accuracy']))\r\nnp.savetxt('epochs_acc.txt', res1)\r\nplt.show()\r\n# 运行时间打印\r\nprint(time_callback.times)\r\nprint(time_callback.totaltime)\r\n# # 计算每次迭代的损失值与识别率\r\npd.DataFrame.from_dict(history.history).to_csv(\"Loss_ACC.csv\", float_format=\"%.5f\", index=False)","sub_path":"MFFNet-master/main_demo/ResNet_SEnet_PAN_FPN.py","file_name":"ResNet_SEnet_PAN_FPN.py","file_ext":"py","file_size_in_byte":16009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"422064143","text":"#!/bin/python\n# -*- coding: utf-8 -*-\n\nimport requests\nfrom datetime import datetime\n\nCITY = \"Auckland\"\nCOUNTRY = \"NZ\"\nSCHOOL = 3\nURL = \"https://api.aladhan.com/v1/timingsByCity?city={}&country={}&method={}\".format(CITY, COUNTRY, SCHOOL)\n\ndef tdelta(time1, time2):\n # calculate difference\n tdelta = str(datetime.strptime(time2,'%H:%M') - datetime.strptime(time1,'%H:%M')).split(\":\")\n hours = int(tdelta[0].split(\",\")[-1])\n minutes = tdelta[1]\n\n return hours, minutes\n\nREQ = requests.get(URL)\ntry:\n # HTTP CODE = OK\n if REQ.status_code == 200:\n timings = REQ.json()[\"data\"][\"timings\"]\n # remove extra timings\n del timings['Imsak']\n # del timings['Sunrise']\n del timings['Sunset']\n del timings['Midnight']\n \n current = datetime.now().time().strftime(\"%H:%M\")\n\n for time in timings.items():\n # format time\n formatted_time = datetime.strptime(time[1], \"%H:%M\").time().strftime(\"%H:%M\") \n # check for next timings\n if current < formatted_time:\n hours, minutes = tdelta(current, formatted_time)\n print(\"{} in {}:{}\".format(time[0], hours, minutes))\n break\n if current >= timings['Isha']:\n # edge case for time between isha and midnight\n hours, minutes = tdelta(current, timings['Fajr'])\n print(\"{} in {}:{}\".format(\"Fajr\", hours, minutes))\n else:\n print(\"Error: \" + str(REQ.status_code))\nexcept (ValueError, IOError):\n print(\"Error: Unable to print data\")","sub_path":"Athan/athan.py","file_name":"athan.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"347548342","text":"# -*- coding: utf-8 -*-\n\"\"\"\nPresence analyzer unit tests.\n\"\"\"\nimport os.path\nimport json\nfrom datetime import date, time\nimport unittest\n\nfrom presence_analyzer import main, views, utils\n\nimport flask\n\nTEST_DATA_CSV = os.path.join(\n os.path.dirname(__file__), '..', '..', 'runtime', 'data', 'test_data.csv'\n)\n\n\n# pylint: disable=maybe-no-member, too-many-public-methods\nclass PresenceAnalyzerViewsTestCase(unittest.TestCase):\n \"\"\"\n Views tests.\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Before each test, set up a environment.\n \"\"\"\n main.app.config.update({'DATA_CSV': TEST_DATA_CSV})\n self.client = main.app.test_client()\n\n def tearDown(self):\n \"\"\"\n Get rid of unused objects after each test.\n \"\"\"\n pass\n\n def test_mainpage(self):\n \"\"\"\n Test main page redirect.\n \"\"\"\n resp = self.client.get('/')\n self.assertEqual(resp.status_code, 302)\n assert resp.headers['Location'].endswith('/presence_weekday.html')\n\n def test_api_users(self):\n \"\"\"\n Test users listing.\n \"\"\"\n resp = self.client.get('/api/v1/users')\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(resp.content_type, 'application/json')\n data = json.loads(resp.data)\n self.assertEqual(len(data), 2)\n self.assertDictEqual(data[0], {u'user_id': 10, u'name': u'User 10'})\n\n def test_api_mean_time_weekday(self):\n \"\"\"\n Test calculating mean per day of week\n \"\"\"\n resp = self.client.get('/api/v1/mean_time_weekday/11')\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(resp.content_type, 'application/json')\n data = json.loads(resp.data)\n self.assertEqual(len(data), 7)\n self.assertListEqual(data[0], ['Mon', 24123.0])\n self.assertListEqual(data[6], ['Sun', 0])\n\n def test_api_presence_weekday(self):\n \"\"\"\n Test calculating sum per day of week\n \"\"\"\n resp = self.client.get('/api/v1/presence_weekday/11')\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(resp.content_type, 'application/json')\n data = json.loads(resp.data)\n self.assertEqual(len(data), 8)\n self.assertListEqual(data[0], [u'Weekday', u'Presence (s)'])\n self.assertListEqual(data[1], [u'Mon', 24123])\n self.assertListEqual(data[7], [u'Sun', 0])\n\n def test_api_presence_start_end(self):\n \"\"\"\n Test calculating of averages timepoints\n \"\"\"\n resp = self.client.get('/api/v1/presence_start_end/11')\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(resp.content_type, 'application/json')\n data = json.loads(resp.data)\n self.assertEqual(len(data), 7)\n self.assertListEqual(data[0], [u'Mon', 33134.0, 57257.0])\n self.assertListEqual(data[3], [u'Thu', 35602.0, 58586.0])\n\n\nclass PresenceAnalyzerUtilsTestCase(unittest.TestCase):\n \"\"\"\n Utility functions tests.\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Before each test, set up a environment.\n \"\"\"\n main.app.config.update({'DATA_CSV': TEST_DATA_CSV})\n\n def tearDown(self):\n \"\"\"\n Get rid of unused objects after each test.\n \"\"\"\n pass\n\n def test_get_data(self):\n \"\"\"\n Test parsing of CSV file.\n \"\"\"\n data = utils.get_data()\n self.assertIsInstance(data, dict)\n self.assertItemsEqual(data.keys(), [10, 11])\n sample_date = date(2013, 9, 10)\n self.assertIn(sample_date, data[10])\n self.assertItemsEqual(data[10][sample_date].keys(), ['start', 'end'])\n self.assertEqual(\n data[10][sample_date]['start'],\n time(9, 39, 5)\n )\n\n def test_jsonify(self):\n \"\"\"\n Test if jsonify wrapper creates proper JSON object\n \"\"\"\n\n some_dict = {'a': 'b', 'c': 'd'}\n\n @utils.jsonify\n def some_func():\n return some_dict\n resp = some_func()\n\n # if is function\n self.assertTrue(callable(utils.jsonify))\n # if got Flask Response as result\n self.assertTrue(isinstance(resp, flask.wrappers.Response))\n # if data are correct\n self.assertEqual(resp.data, json.dumps(some_dict))\n # if assigned mimetype is proper\n self.assertEqual(resp.mimetype, u'application/json')\n\n @classmethod\n def __secs_count(self, t):\n \"\"\"\n Helper for test_seconds_since_midnight\n \"\"\"\n return t[0] * 3600 + t[1] * 60 + t[2]\n\n def test_seconds_since_midnight(self):\n \"\"\"\n Test seconds counting\n \"\"\"\n s_array = [(15, 8, 6), (12, 0, 0), (0, 0, 0), (23, 59, 59)]\n secs_array = [\n (self.__secs_count(x), utils.seconds_since_midnight(time(*x)))\n for x in s_array\n ]\n for sa in secs_array:\n self.assertEqual(sa[0], sa[1])\n\n def test_mean(self):\n \"\"\"\n Test mean function\n \"\"\"\n self.assertEqual(utils.mean([]), 0)\n self.assertEqual(utils.mean([1, 2, 3, 4, 5]), 3.0)\n self.assertEqual(utils.mean([1000, 99999, 999999]), 366999.3333333333)\n\n def test_group_by_weekday(self):\n \"\"\"\n test if grouping is right\n \"\"\"\n user_id = 11\n data = utils.get_data()\n groups = [[24123], [16564], [25321], [22969, 22999], [6426], [], []]\n self.assertListEqual(groups, utils.group_by_weekday(data[user_id]))\n\n def group_timepoints_by_weekday(self):\n \"\"\"\n test if grouping is right\n \"\"\"\n user_id = 10\n data = utils.get_data()\n groups = [[24123], [16564], [25321], [22969, 22999], [6426], [], []]\n self.assertListEqual(groups,\n utils.group_timepoints_by_weekday(data[user_id]))\n\n\ndef suite():\n \"\"\"\n Default test suite.\n \"\"\"\n base_suite = unittest.TestSuite()\n base_suite.addTest(unittest.makeSuite(PresenceAnalyzerViewsTestCase))\n base_suite.addTest(unittest.makeSuite(PresenceAnalyzerUtilsTestCase))\n return base_suite\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"src/presence_analyzer/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":6190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"383507521","text":"\"\"\"Test tree classification.\"\"\"\n# import networkx as nx\n# import numpy as np\n# from minerminor import mm_generator as mmg\nfrom minerminor import mm_utils as mmu\nfrom minerminor import mm_representation as mmr\nfrom sklearn import ensemble, svm, neighbors, tree\nfrom sklearn.neural_network import MLPClassifier\n# from sklearn.model_selection import train_test_split\n# from sklearn.metrics import precision_recall_fscore_support\nimport matplotlib.pyplot as plt\nimport os\nimport argparse\nfrom sklearn.model_selection import ShuffleSplit\n\n\nparser = argparse.ArgumentParser(prog=\"P-Tree by DescTree classification\")\nparser.add_argument(\"-r\", \"--representation\", nargs='*',\n default=[mmr.adjacency,\n mmr.laplacian,\n mmr.A3_minus_D])\nparser.add_argument(\"-p\", \"--path\", default=\"base_from_jaguar\",\n help=\"Path de la learning base\")\nparser.add_argument(\"-t\", \"--title\", default=\"Sans Titre\",\n help=\"Curve title\")\nargs = parser.parse_args()\n\nfor directory in os.listdir(args.path):\n for representation in args.representation:\n learning_base = mmu.load_base(\"{0}/{1}\".format(args.path, directory))\n learning_base = representation(learning_base)\n # learning_base = mmr.labels_set_to_vec_laplacian_set(learning_base)\n # learning_base = mmr.labels_set_to_vec_adjacency_set(learning_base)\n # learning_base = mmr.learning_base_to_A3_minus_D(learning_base)\n\n data_set, label_set = mmu.create_sample_label_classification(learning_base)\n cv = ShuffleSplit(n_splits=100, test_size=0.2, random_state=0)\n\n # X_train, X_test, y_train, y_test = train_test_split(data_set, label_set,\n # test_size=0.1)\n # clf = svm.SVC()\n # clf = ensemble.RandomForestClassifier()\n # clf = neighbors.KNeighborsRegressor()\n\n clf = MLPClassifier()\n # clf = tree.DecisionTreeClassifier()\n title = \"{0}_{1}\".format(directory, representation.__name__)\n mmu.plot_learning_curve(clf, title, data_set, label_set, cv=cv, n_jobs=4)\n plt.savefig(\"learning_curve/{0}\".format(title))\n # pred, miss = mmu.learning(clf, X_train, X_test, y_train, y_test)\n\n # accu, recal, fmeasure, _ = precision_recall_fscore_support(y_test,\n # pred,\n # average=\"macro\")\n # print(directory, representation.__name__)\n # print(\"|{0}|{1}|{2}%|{3}|{4}|{5}|\\n\".format(directory,\n # representation.__name__,\n # miss,\n # accu,\n # recal,\n # fmeasure))\n","sub_path":"working_env/Scripts/4_Evaluations/validation_learning_curve.py","file_name":"validation_learning_curve.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"61341018","text":"from __future__ import print_function\nfrom sys import argv\nimport os.path\nimport cv2\nimport numpy as np\n\n\ndef calculate_sigma(cumulative_hist, cumulative_values, threshold):\n left_number = cumulative_hist[threshold]\n right_number = cumulative_hist[-1] - left_number\n left_value = cumulative_values[threshold]\n right_value = cumulative_values[-1] - left_value\n left_average = left_value / left_number\n right_average = right_value / right_number\n left_freq = left_number / (left_number + right_number)\n right_freq = right_number / (left_number + right_number)\n sigma = left_freq * right_freq * (left_average - right_average) * (left_average - right_average)\n return np.nan_to_num(sigma)\n\n\ndef apply_binarization(image, threshold):\n image[image > threshold] = 255\n image[image <= threshold] = 0\n return image\n\n\ndef otsu(src_path, dst_path):\n image = cv2.imread(src_path)\n image_shape = image.shape\n if len(image_shape) == 3:\n if image_shape[2] == 3:\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n elif image_shape[2] == 4:\n image = cv2.cvtColor(image, cv2.COLOR_RGBA2GRAY)\n hist, borders = np.histogram(image.flatten(), range(1, 257))\n borders = borders[:-1]\n values = hist * borders\n cumulative_values = np.cumsum(values)\n cumulative_hist = np.cumsum(hist)\n sigma = calculate_sigma(cumulative_hist, cumulative_values, 0)\n best_threshold = 0\n for threshold in range(1, 255):\n new_sigma = calculate_sigma(cumulative_hist, cumulative_values, threshold)\n if new_sigma > sigma:\n sigma = new_sigma\n best_threshold = threshold\n print(best_threshold, sigma)\n image = apply_binarization(image, best_threshold)\n cv2.imwrite(dst_path, image)\n\n\nif __name__ == '__main__':\n assert len(argv) == 3\n assert os.path.exists(argv[1])\n otsu(*argv[1:])\n","sub_path":"otsu.py","file_name":"otsu.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"552423150","text":"from modules.conv import *\r\nfrom modules.pool import *\r\nfrom modules.dense import *\r\nfrom modules.actvfn import *\r\nfrom modules.loss import *\r\n\r\n\r\nclass LeNet():\r\n def __init__(self):\r\n self.conv1 = Conv(nb_filters = 6, filter_size = 5, nb_channels = 1)\r\n self.pool1 = AvgPool(filter_size = 2, stride = 2)\r\n self.conv2 = Conv(nb_filters = 16, filter_size = 5, nb_channels = 6)\r\n self.pool2 = AvgPool(filter_size = 2, stride = 2)\r\n self.pool2_shape = None\r\n self.fc1 = layer(128, 400, \"tanh\")\r\n self.fc2 = layer(84, 128, \"tanh\")\r\n self.fc3 = layer(10,84,\"softmax\")\r\n self.A = []\r\n self.actCache = []\r\n self.layers = [self.conv1, self.conv2, self.fc1, self.fc2, self.fc3]\r\n \r\n \r\n def forward(self, X):\r\n self.A = []\r\n conv1 = self.conv1.forward(X) #(6x28x28)\r\n self.actCache.append(conv1)\r\n act1 = tanh(conv1)\r\n pool1 = self.pool1.forward(act1) #(6x14x14)\r\n\r\n conv2 = self.conv2.forward(pool1) #(16x10x10)\r\n self.actCache.append(conv2)\r\n act2 = tanh(conv2)\r\n pool2 = self.pool2.forward(act2) #(16x5x5)\r\n \r\n self.pool2_shape = pool2.shape #Need it in backpropagation.\r\n pool2_flatten = pool2.reshape(self.pool2_shape[0], -1) #(1x400)\r\n self.A.append(pool2_flatten.T)\r\n fc1 = self.fc1.forward_prop(pool2_flatten.T) #(1x120) \r\n self.A.append(fc1)\r\n fc2 = self.fc2.forward_prop(fc1) #(1x84) \r\n \r\n # print(fc2.shape)\r\n self.A.append(fc2)\r\n fc3 = self.fc3.forward_prop(fc2) #(1x10)\r\n self.A.append(fc3)\r\n\r\n y_pred = fc3\r\n\r\n return y_pred\r\n \r\n def backward(self, y_pred, y):\r\n deltaL = y_pred - y\r\n #Compute gradient for weight/bias between fc3 and fc2.\r\n deltaL, dW5, db5= self.fc3.backward_prop(self.A[2],0,y,output_layer = True)\r\n #Compute error at fc2 layer.\r\n #deltaL = self.tanh4.backward(deltaL) #(1x84) \r\n \r\n #Compute gradient for weight/bias between fc2 and fc1.\r\n deltaL, dW4, db4= self.fc2.backward_prop(self.A[1],deltaL,y,output_layer = False)\r\n #Compute error at fc1 layer.\r\n # deltaL = self.tanh3.backward(deltaL) #(1x120)\r\n \r\n #Compute gradient for weight/bias between fc1 and pool2 and compute \r\n #error too (don't need to backpropagate through tanh here).\r\n deltaL, dW3, db3 = self.fc1.backward_prop(self.A[0],deltaL,y,output_layer = False) #(1x400)\r\n deltaL = deltaL.reshape(self.pool2_shape) #(16x5x5)\r\n \r\n \r\n #Distribute error through pool2 to conv2.\r\n deltaL = self.pool2.backward(deltaL) #(16x10x10)\r\n #Distribute error through tanh.\r\n deltaL = derivative_tanh(self.actCache[1]) * deltaL\r\n \r\n #Compute gradient for weight/bias at conv2 layer and backpropagate\r\n #error to conv1 layer.\r\n deltaL, dW2, db2 = self.conv2.backward(deltaL) #(6x14x14)\r\n\r\n #Distribute error through pool1 by creating a temporary pooling layer\r\n #of conv1 shape.\r\n deltaL = self.pool1.backward(deltaL) #(6x28x28)\r\n #Distribute error through tanh.\r\n deltaL = derivative_tanh(self.actCache[0]) * deltaL\r\n \r\n #Compute gradient for weight/bias at conv1 layer and backpropagate\r\n #error at conv1 layer.\r\n deltaL, dW1, db1 = self.conv1.backward(deltaL) #(1x32x32)\r\n \r\n grads = { \r\n 'dW1': dW1, 'db1': db1,\r\n 'dW2': dW2, 'db2': db2, \r\n 'dW3': dW3, 'db3': db3,\r\n 'dW4': dW4, 'db4': db4,\r\n 'dW5': dW5, 'db5': db5\r\n }\r\n\r\n return grads\r\n \r\n \r\n def get_params(self):\r\n params = {}\r\n for i, layer in enumerate(self.layers):\r\n try:\r\n params['W' + str(i+1)] = layer.W['val']\r\n params['b' + str(i+1)] = layer.b['val']\r\n except:\r\n params['W' + str(i+1)] = layer.weights\r\n params['b' + str(i+1)] = layer.biases \r\n\r\n return params\r\n\r\n def set_params(self, params):\r\n for i, layer in enumerate(self.layers):\r\n try:\r\n layer.W['val'] = params['W'+ str(i+1)]\r\n layer.b['val'] = params['b' + str(i+1)]\r\n except:\r\n layer.weights = params['W'+ str(i+1)]\r\n layer.biases = params['b' + str(i+1)]\r\n \r\n \r\n def update_params(self,grads,learning_rate):\r\n for i, layer in enumerate(self.layers): \r\n try: \r\n layer.W['val'] = layer.W['val'] - learning_rate*grads['dW'+str(i+1)] \r\n layer.b['val'] = layer.b['val'] - learning_rate*grads['db'+str(i+1)]\r\n except:\r\n layer.weights = layer.weights - learning_rate*grads['dW'+str(i+1)] \r\n layer.biases = layer.biases - learning_rate*grads['db'+str(i+1)] \r\n \r\n def update_parameters_momentum(self, grads, learning_rate, gamma=0.9):\r\n \r\n for i, layer in enumerate(self.layers): \r\n try: \r\n \r\n layer.v_w = gamma * layer.v_w + (1 - gamma)* grads['dW'+str(i+1)]\r\n layer.v_b = gamma * layer.v_b + (1 - gamma)* grads['db'+str(i+1)]\r\n layer.W['val'] = layer.W['val'] - learning_rate * layer.v_w\r\n layer.b['val'] = layer.b['val'] - learning_rate * layer.v_b\r\n \r\n except:\r\n \r\n layer.v_w = gamma*layer.v_w + (1 - gamma)* layer.dW\r\n layer.v_b = gamma*layer.v_b + (1 - gamma)* layer.db\r\n layer.weights = layer.weights - learning_rate * layer.v_w\r\n layer.biases = layer.biases - learning_rate * layer.v_b\r\n \r\n def update_parameters_rmsprop(self, grads, learning_rate, beta=0.9):\r\n \r\n for i, layer in enumerate(self.layers): \r\n try: \r\n \r\n layer.s_w = beta * layer.s_w + (1 - beta)* np.power(grads['dW'+str(i+1)],2)\r\n layer.s_b = beta * layer.s_b + (1 - beta)* np.power(grads['db'+str(i+1)],2)\r\n layer.W['val'] = layer.W['val'] - learning_rate * np.divide(grads['dW'+str(i+1)],np.sqrt(layer.s_w))\r\n layer.b['val'] = layer.b['val'] - learning_rate * np.divide(grads['db'+str(i+1)],np.sqrt(layer.s_b))\r\n \r\n except:\r\n \r\n layer.s_w = beta*layer.s_w + (1 - beta)* np.power(grads['dW'+str(i+1)],2)\r\n layer.s_b = beta*layer.s_b + (1 - beta)* np.power(grads['db'+str(i+1)],2)\r\n layer.weights = layer.weights - learning_rate * np.divide(grads['dW'+str(i+1)],np.sqrt(layer.s_w))\r\n layer.biases = layer.biases - learning_rate * np.divide(grads['db'+str(i+1)],np.sqrt(layer.s_b))\r\n\r\n \r\n def update_parameters_adam(self, grads, learning_rate = 0.01, t = 2, beta1 = 0.9, beta2 = 0.999, epsilon = 1e-8):\r\n for i, layer in enumerate(self.layers): \r\n try: \r\n layer.v_w = beta1 * layer.v_w + (1 - beta1)* np.atleast_2d(grads['dW'+str(i+1)])\r\n layer.v_b = beta1 * layer.v_b + (1 - beta1)* grads['db'+str(i+1)]\r\n v_wcorrected = layer.v_w / (1-np.power(beta1,t))\r\n v_bcorrected = layer.v_b / (1-np.power(beta1,t))\r\n layer.s_w = beta2*layer.s_w + (1-beta2)*np.power(grads['dW'+str(i+1)],2)\r\n layer.s_b = beta2*layer.s_b + (1-beta2)*np.power(grads['db'+str(i+1)],2)\r\n s_wcorrected = layer.s_w / (1-np.power(beta2,t))\r\n s_bcorrected = layer.s_b / (1-np.power(beta2,t))\r\n layer.W['val'] = layer.W['val'] - learning_rate*v_wcorrected / np.sqrt(s_wcorrected + epsilon)\r\n layer.b['val'] = layer.b['val'] - learning_rate*v_bcorrected / np.sqrt(s_bcorrected + epsilon)\r\n\r\n except:\r\n layer.v_w = beta1*layer.v_w + (1 - beta1)* layer.dW\r\n layer.v_b = beta1*layer.v_b + (1 - beta1)* layer.db\r\n v_wcorrected = layer.v_w / (1-np.power(beta1,t))\r\n v_bcorrected = layer.v_b / (1-np.power(beta1,t))\r\n layer.s_w = beta2*layer.s_w + (1-beta2)*np.power(layer.dW,2)\r\n layer.s_b = beta2*layer.s_b + (1-beta2)*np.power(layer.db,2)\r\n s_wcorrected = layer.s_w / (1-np.power(beta2,t))\r\n s_bcorrected = layer.s_b / (1-np.power(beta2,t))\r\n layer.weights = layer.weights - learning_rate*v_wcorrected / np.sqrt(s_wcorrected + epsilon)\r\n layer.biases = layer.biases - learning_rate*v_bcorrected / np.sqrt(s_bcorrected + epsilon)\r\n \r\n \r\n\r\n def predict(self, X):\r\n output = self.forward(X)\r\n\r\n _pred = np.array(output[0]) \r\n pred = np.zeros((10,X.shape[1])) \r\n pred = np.argmax(output,axis=0)\r\n \r\n return np.atleast_2d(pred)\r\n\r\n def fit(self, X, Y, epochs, learning_rate, costt, batch_size, optimizer=\"adam\"):\r\n Y_class = np.zeros((10,Y.shape[1])) \r\n Y_class = np.atleast_2d(np.argmax(Y,axis=0))\r\n \r\n batch_number = int(-(-X.shape[0]/batch_size // 1))\r\n metrics_output = {}\r\n \r\n for i in range(epochs):\r\n \r\n current_batch=0\r\n print('\\repoch:{}/{} [{}] {}%'.format(i+1, epochs, '.' * (50), 0), end='\\r')\r\n for j in range(batch_number-1):\r\n\r\n current_batch += 1\r\n if j == batch_number-1:\r\n \r\n x = X[batch_size*(j):,:,:,:]\r\n y = Y[:,batch_size*(j):]\r\n \r\n else:\r\n x = X[batch_size*(j):batch_size*(j+1),:,:,:]\r\n y = Y[:,batch_size*(j):batch_size*(j+1)]\r\n \r\n y_hat = self.forward(x)\r\n \r\n # acc = accuracy_metrics(y_hat.T, y.T) * 100\r\n \r\n \r\n if (costt == \"multiclass\"):\r\n loss = compute_multiclass_loss(y, y_hat)\r\n elif (costt == \"mse\"):\r\n loss = compute_mse_loss(y, y_hat)\r\n \r\n grads = self.backward(y_hat, y)\r\n if optimizer == \"adam\":\r\n self.update_parameters_adam(grads, learning_rate)\r\n \r\n elif optimizer == \"rmsprop\":\r\n self.update_parameters_rmsprop(grads, learning_rate)\r\n \r\n elif optimizer == \"momentum\":\r\n self.update_parameters_momentum(grads, learning_rate)\r\n \r\n else:\r\n self.update_params(grads, learning_rate)\r\n\r\n done = int(100*current_batch/batch_number)\r\n print('\\repoch:{}/{} [{}{}] {}% '.format(i+1, epochs,'█' * int(done/2), '.' * int(50-int(done/2)), done, ), end='\\r')\r\n \r\n print(\"Epoch\", i+1, \"->\")\r\n print(\"\\t\\tLoss =\", (\"%.4f\" % loss ))\r\n metrics_output[\"loss\"+str(i)] = loss\r\n # print(\"\\t\\Acc =\", (\"%.4f\" % acc ))\r\n \r\n return metrics_output\r\n \r\n\r\n\r\n","sub_path":"Modules/LeNet.py","file_name":"LeNet.py","file_ext":"py","file_size_in_byte":11420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"2868264","text":"from Consumer import Consumer\nfrom Producer import Producer\nfrom SignalHandler import SignalHandler\nimport threading\nimport datetime\nimport locale\nimport signal\n\n\ndef main():\n # handle user input\n from_date_string = str(raw_input(\"Please specify a Start Date with format ddmmYYYY: \"))\n # raw input in python2 is the same as input in python3 (returns a string instead of a python expression)\n to_date_string = str(raw_input(\"Please specify a End Date with format ddmmYYYY: \"))\n locale.setlocale(locale.LC_ALL, '')\n from_date = datetime.datetime.strptime(from_date_string, '%d%m%Y').isoformat()\n to_date = datetime.datetime.strptime(to_date_string, '%d%m%Y')\n tmp_date = to_date + datetime.timedelta(1)\n to_date = tmp_date.isoformat()\n\n threads = list()\n stopper = threading.Event()\n\n consumer = Consumer()\n producer = Producer(from_date=from_date, to_date=to_date)\n\n threads.append(consumer)\n threads.append(producer)\n\n handler = SignalHandler(stopper, threads)\n signal.signal(signal.SIGINT, handler)\n\n producer.start()\n consumer.start()\n\n\nif __name__ == '__main__':\n main()","sub_path":"python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"238741111","text":"def find(s, a, n):\r\n global check\r\n if check:\r\n return\r\n if a == 7:\r\n if sum(ans) == 100:\r\n check = True\r\n return\r\n if s == 9:\r\n return\r\n ans[a] = arr1[s]\r\n find(s+1, a+1, n) # 선택을 한 경우\r\n find(s+1, a, n) # 선택을 안 한 경우\r\n\r\ncheck = False\r\narr1 = []\r\nfor i in range(9):\r\n height = int(input())\r\n arr1.append(height)\r\nans = [[0] for _ in range(7)] # 선택할 난쟁이가 들어가 있는 배열\r\nfind(0, 0, arr1)\r\nans.sort()\r\nfor x in range(7):\r\n print('{}'.format(ans[x]))","sub_path":"python_bms/0923/2309Āϰöģ­ĀïĀĖ.py","file_name":"2309Āϰöģ­ĀïĀĖ.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"212942044","text":"from django.conf import settings\nfrom django.contrib.gis.db.models.functions import GeometryDistance\nfrom django.contrib.messages.views import SuccessMessageMixin\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.core.mail import send_mail, EmailMultiAlternatives\nfrom django.db import IntegrityError\nfrom django.shortcuts import get_object_or_404\nfrom django.template.loader import render_to_string\nfrom django.urls import reverse\nfrom django.utils.encoding import force_bytes\nfrom django.utils.http import urlsafe_base64_encode\nfrom django.utils.translation import gettext, gettext_lazy\nfrom django.views.generic import (CreateView, DetailView, FormView, ListView,\n TemplateView)\nfrom email.mime.image import MIMEImage\n\nfrom base.models import User\nfrom postcode.models import Postcode\nfrom shop.forms import ShopContactForm, ShopRegisterForm\nfrom shop.models import Shop\nfrom shop.tokens import account_activation_token\n\n\nclass ShopsListView(ListView):\n \"\"\"\n Shop List View. Will list all active shops for enduser\n \"\"\"\n model = Shop\n template_name = 'shop/list.html'\n\n def get_queryset(self):\n queryset = self.model.objects.filter(active=True)\n code = self.request.session.get('postcode')\n if code:\n try:\n postcode = Postcode.objects.get(postcode=code['code'])\n queryset = queryset.order_by(GeometryDistance(\"location\", postcode.location))\n except Postcode.DoesNotExist:\n queryset = queryset.order_by('?')\n else:\n queryset = queryset.order_by('?')\n return queryset\n\n\nclass ShopsDetailView(DetailView):\n \"\"\"\n Shop Detail View. Will show detail for an active shop\n \"\"\"\n model = Shop\n template_name = 'shop/detail.html'\n\n def get_queryset(self):\n queryset = self.model.objects.filter(active=True)\n return queryset\n\n\nclass ShopContactView(SuccessMessageMixin, FormView):\n \"\"\"\n Contact shop form. Will send an email to the shop contact\n \"\"\"\n template_name = 'shop/contact.html'\n form_class = ShopContactForm\n success_message = gettext_lazy(\"Message sent to shop, they will get in touch.\")\n\n def get_success_url(self):\n return reverse('shop_detail', kwargs={'pk': self.kwargs.get('pk')})\n\n def form_valid(self, form):\n shop = get_object_or_404(Shop, pk=self.kwargs.get('pk'))\n send_mail(\n subject=form.cleaned_data.get('subject'),\n message=form.cleaned_data.get('message'),\n from_email=form.cleaned_data.get('email'),\n recipient_list=[shop.email],\n fail_silently=False,\n )\n return super().form_valid(form)\n\n\nclass ShopRegisterView(CreateView):\n \"\"\"\n Contact shop form. Will send an email to the shop contact\n \"\"\"\n model = Shop\n template_name = 'shop/register.html'\n form_class = ShopRegisterForm\n \n def get_success_url(self):\n return reverse('shop_registered')\n\n def form_valid(self, form):\n # Create a user, but remember to set inactive!\n user = User()\n user.username = form.cleaned_data.get('email')\n user.email = form.cleaned_data.get('email')\n user.is_active = False\n try:\n user.save()\n except IntegrityError:\n form.add_error('email', gettext('Shop with this email already exists.'))\n return super(ShopRegisterView, self).form_invalid(form)\n \n self.object = form.save(commit=False)\n self.object.user = user\n self.object.save()\n\n\n current_site = get_current_site(self.request)\n html_content = render_to_string('emails/account_activation.html', {\n 'shopname': self.object.name,\n 'user': user,\n 'domain': current_site.domain,\n 'uid': urlsafe_base64_encode(force_bytes(user.pk)),\n 'token': account_activation_token.make_token(user),\n })\n\n email = EmailMultiAlternatives(gettext('FOODBEE - Confirm email'), None) # TODO: Plain text version\n email.from_email = settings.DEFAULT_FROM_EMAIL\n email.to = [self.object.email] \n email.attach_alternative(html_content, \"text/html\")\n email.content_subtype = 'html'\n email.mixed_subtype = 'related'\n\n with open('base/static/base/img/fb_logo.png', mode='rb') as f: # TODO: Dynamic path\n image = MIMEImage(f.read())\n image.add_header('Content-ID', \"\")\n email.attach(image)\n\n email.send()\n\n return super().form_valid(form)\n\n\nclass ShopRegisteredView(TemplateView):\n template_name = 'shop/registered.html'\n","sub_path":"shop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"305756608","text":"# Proyecto Nayelly y Ricardo. Trivia de los temas vistos en clase\n\n# Variables Globales\nlist_jugadores = []\npreguntas_juego = dict()\n\n# Seleccion de Jugador y su nombre\ndef jugadores():\n \n for i in range(int(input(\"Seleccione el numero de jugadores: \"))):\n i = input(\"Ingrese nombre del jugador: \")\n list_jugadores.append(i)\n\n\n# Seleccion de nivel de dificultad del juego\ndef seleccion_dificultad():\n \n dificultad = (int(input(\"Seleccione la dificultad deseada 1, 2 o 3: \")))\n \n if dificultad == 1:\n preguntas_juego.update(preguntas_1)\n elif dificultad == 2:\n preguntas_juego.update(preguntas_2)\n elif dificultad == 3:\n preguntas_juego.update(preguntas_3)\n else:\n print('Nivel no identificado, vuelva a intentar')\n\n# Reglas del Juego\n\n# si la respuesta del usuario es igual al valor de la pregunta se suma un punto\n# al jugador. \n\n# El jugador que al final tenga mas puntos gana. \n# si quedan empate se muestra mensaje de empate.\n\n# Juego\n\n# Se van mostrando pregunta por pregunta y se recibe la respuesta del jugador. T o F en mayusculas. la respuesta del jugador debe de ser convertida a mayusculas\n\n# Puntaje del Juego\n\n# Tal vez esta parte se quite porque está en las reglas del juego. \n# se van almacenando las respuestas de cada jugador\n\n# Preguntas\n# Preguntas de muestra, pendiente por sustituir por las verdaderas\npreguntas_3 = {'pregunta1':True,\n 'pregunta2':False,\n 'pregunta3':True,\n 'pregunta4':False,\n 'pregunta5':True,\n 'pregunta6':False,\n 'pregunta7':True,\n 'pregunta8':False,\n 'pregunta9':True,\n 'pregunta10':False,\n 'pregunta11':True,\n 'pregunta12':False,\n 'pregunta13':True,\n 'pregunta14':False,\n 'pregunta15':True,\n 'pregunta16':False,\n 'pregunta17':True,\n 'pregunta18':False,\n 'pregunta19':True,\n 'pregunta20':False,\n 'pregunta21':True,\n 'pregunta22':False,\n 'pregunta23':True,\n 'pregunta24':False,\n 'pregunta25':True,\n 'pregunta26':False,\n 'pregunta27':True,\n 'pregunta28':False,\n 'pregunta29':True,\n 'pregunta30':False}\n\npreguntas_2 = {'pregunta1':True,\n 'pregunta2':False,\n 'pregunta3':True,\n 'pregunta4':False,\n 'pregunta5':True,\n 'pregunta6':False,\n 'pregunta7':True,\n 'pregunta8':False,\n 'pregunta9':True,\n 'pregunta10':False,\n 'pregunta11':True,\n 'pregunta12':False,\n 'pregunta13':True,\n 'pregunta14':False,\n 'pregunta15':True,\n 'pregunta16':False,\n 'pregunta17':True,\n 'pregunta18':False,\n 'pregunta19':True,\n 'pregunta20':False}\n\npreguntas_1 = {'pregunta1':True,\n 'pregunta2':False,\n 'pregunta3':True,\n 'pregunta4':False,\n 'pregunta5':True,\n 'pregunta6':False,\n 'pregunta7':True,\n 'pregunta8':False,\n 'pregunta9':True,\n 'pregunta10':False}","sub_path":"Proyecto-1.py","file_name":"Proyecto-1.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"99182205","text":"# Copyright (C) 2022, BatID.\n\n# This program is licensed under the Apache License version 2.\n# See LICENSE or go to for full license details.\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import inspect\nfrom geoalchemy2 import Geometry #to be able to handle geometry type\nimport pandas as pd\n\nimport src.db.config as cfg\n\nengine = create_engine(cfg.DATABASE_CONNECTION_URI)\n\ninspector = inspect(engine)\n\nwriter = pd.ExcelWriter('data_dict_batiment.xlsx')\n\ntables = pd.DataFrame(columns=['table', 'description'], dtype=object)\n\ndefault_schema = \"rnb\"\n\nfor t in inspector.get_table_names(default_schema):\n tables = tables.append({\"table\": t,\n \"description\":\n inspector.get_table_comment(t,\n schema=default_schema)[\"text\"]},\n ignore_index=True)\n\n df = pd.DataFrame(inspector.get_columns(table_name=t,\n schema=default_schema))\n df = df.drop(columns=['default', \"autoincrement\"])\n df.to_excel(writer, sheet_name=t, index=False)\n\ntables.to_excel(writer, sheet_name='TABLES DESCRIPTION', index=False)\nwriter.save()\n","sub_path":"src/db/utils/create_docs.py","file_name":"create_docs.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"575198553","text":"# setup.py - Builds and installs the TRE Python language bindings module\n#\n# Copyright (c) 2009 Ville Laurikari \n#\n\nimport distutils.sysconfig\nfrom distutils.core import setup, Extension\nimport sys\nimport os\nimport shutil\n\nversion = \"0.8.0\"\ndata_files = []\ninclude_dirs = [\"../lib\"]\nlibraries = [\"tre\"]\n\nif sys.platform == \"win32\":\n # Place tre.dll in site-packages, next to tre.pyd.\n data_files = [(distutils.sysconfig.get_python_lib(), [\"tre.dll\"])]\n include_dirs += [\"../win32\"]\n shutil.copy(\"../win32/Release/tre.dll\", \".\")\n libraries = [\"../win32/Release/tre\"]\n\nsetup(name = \"tre\",\n version = version,\n description = \"Python module for TRE\",\n author = \"Ville Laurikari\",\n author_email = \"ville@laurikari.net\",\n license = \"2-clause BSD\",\n url = \"http://laurikari.net/tre/\",\n data_files = data_files,\n ext_modules = [Extension(\"tre\",\n sources = [\"tre-python.c\"],\n define_macros = [(\"HAVE_CONFIG_H\", None)],\n include_dirs = include_dirs,\n libraries = libraries\n ),\n ],\n )\n","sub_path":"dependencies/tre/python/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"580862391","text":"# Simpler form\nimport string\n\n\nwith open(\"sample.txt\") as infile:\n book = infile.read()\n\n\ndef word_frequency(file):\n file = file.lower()\n for c in string.punctuation:\n file = file.replace(c, \"\")\n for c in string.whitespace:\n file = file.replace(c, \" \")\n word = file.split()\n word_dict = {}\n for word in word:\n if word in word_dict.keys():\n word_dict[word] += 1\n else:\n word_dict[word] = 1\n return word_dict\n\ndef word_list(dictionary):\n word_list = list(dictionary.items())\n return word_list\n\ndef sort_list(a_list, how_many):\n sorted_list = sorted(a_list, reverse=True, key=lambda x: x[1])[:how_many]\n for word, appears in sorted_list:\n print(\"{} {}\".format(word, appears))\n\nunsorted_mess = word_frequency(book)\nword_list = word_list(unsorted_mess)\nsort_list(word_list, 20)\n","sub_path":"word_frequency.py","file_name":"word_frequency.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"596164631","text":"from autograd import grad\nimport numpy as np\nfrom autograd import elementwise_grad as egrad\nimport matplotlib.pyplot as plt\n\n\ndef standardize(x):\n n = x.shape[0]\n mean_x = x.sum(axis=0) * (1.0/n) # D sized vector\n centered = x - mean_x\n squared = centered ** 2\n std = squared.sum(axis=0) * (1.0/n)\n istd = (std + 1e-10) ** -0.5\n x_stand = centered * istd\n return x_stand\n\ndef batchnorm_forward(x):\n\n N, D = x.shape\n\n #step1: calculate mean\n mu = 1./N * np.sum(x, axis = 0)\n\n #step2: subtract mean vector of every trainings example\n xmu = x - mu\n\n #step3: following the lower branch - calculation denominator\n sq = xmu ** 2\n\n #step4: calculate variance\n var = 1./N * np.sum(sq, axis = 0)\n\n #step5: add eps for numerical stability, then sqrt\n sqrtvar = np.sqrt(var + 1e-10)\n\n #step6: invert sqrtwar\n ivar = 1./sqrtvar\n\n #step7: execute normalization\n xhat = xmu * ivar\n\n #store intermediate\n cache = (xhat,xmu,ivar,sqrtvar,var,1e-10)\n\n return xhat, cache\n\ndef batchnorm_backward(dout, cache):\n\n #unfold the variables stored in cache\n xhat,xmu,ivar,sqrtvar,var,eps = cache\n\n #get the dimensions of the input/output\n N,D = dout.shape\n\n #step7\n divar = np.sum(dout*xmu, axis=0)\n dxmu1 = dout * ivar\n\n #step6\n dsqrtvar = -1. /(sqrtvar**2) * divar\n\n #step5\n dvar = 0.5 * 1. /np.sqrt(var+eps) * dsqrtvar\n\n #step4\n dsq = 1. /N * np.ones((N,D)) * dvar\n\n #step3\n dxmu2 = 2 * xmu * dsq\n\n #step2\n dx1 = (dxmu1 + dxmu2)\n dmu = -1 * np.sum(dxmu1+dxmu2, axis=0)\n\n #step1\n dx2 = 1. /N * np.ones((N,D)) * dmu\n\n #step0\n dx = dx1 + dx2\n\n return dx\n\n\n\n# data\nsample_data = np.array([\n [100,2],\n [20,1],\n [2,27],\n [86,0.9],\n [1,3]\n])\nones_sample = np.ones_like(sample_data)\n\nprint(sample_data.mean(axis=0))\nprint(sample_data.std(axis=0))\n# plt.scatter(sample_data[:,0],sample_data[:,0],color='green')\n# plt.show()\n# stand_grad = egrad(standardize)\n# print(stand_grad(ones_sample))\n\nprint('----------------')\nstand_data,cache = batchnorm_forward(sample_data)\ngrad = batchnorm_backward(stand_data,cache)\nprint(stand_data.mean(axis=0))\nprint(stand_data.std(axis=0))\nprint(grad)\n# plt.scatter(stand_data[:,0],stand_data[:,0],color='red')\n# plt.show()\n\nprint('----------------')\nmy_stand = standardize(sample_data)\ngrad_e = egrad(standardize)(my_stand)\nprint(my_stand.mean(axis=0))\nprint(my_stand.std(axis=0))\nprint(grad_e)\n# plt.scatter(my_stand[:,0],my_stand[:,0],color='red')\n# plt.show()\n\n\n\n\n\n\n\n\n\n# -- end code --\n","sub_path":"Understanding_Concepts/EIG_Layer/y_small_session/a_batch.py","file_name":"a_batch.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"30943355","text":"\n\nimport os,sys,string,random\nimport veri\nNewName = os.path.expanduser('~')\nsys.path.append('%s/verification_libs3'%NewName)\nimport logs\nMonitors=[]\ncycles=0\nGIVEUP_TIMEOUT = 10000 # how many cycles to run before retirment. \n\n\n\nimport axiMaster\nimport axiSlave\n\nma = axiMaster.axiMasterClass('tb',Monitors,'mst0_','','MA')\nmb = axiMaster.axiMasterClass('tb',Monitors,'mst1_','','MB')\nmc = axiMaster.axiMasterClass('tb',Monitors,'mst2_','','MC')\nmd = axiMaster.axiMasterClass('tb',Monitors,'mst3_','','MD')\nslvs = []\nfor II in range(16):\n slvs.append(axiSlave.axiSlaveClass('tb',Monitors,'slv%s_' % II,'','SLV%d' % II))\n\nimport sequenceClass\n\n\n\n\ndef sequence(TestName):\n Seq = logs.bin2string(TestName)\n seq.readfile(Seq)\n logs.setVar('sequence',Seq)\n Dir = os.path.dirname(Seq)\n logs.setVar('testsdir',Dir)\n logs.log_info('SEQUENCE %d'%len(seq.Sequence))\n\n\ndef pymonname(Name):\n logs.pymonname(Name)\n\n\n\ndef cannot_find_sig(Sig):\n logs.log_error('cannot find \"%s\" signal in the design'%Sig)\n\n\n\n\nclass driverMonitor(logs.driverClass):\n def __init__(self,Path,Monitors):\n logs.driverClass.__init__(self,Path,Monitors)\n self.Code = 100\n self.Prefs = list(range(16))\n self.Pref = 0\n\n def run(self):\n return\n def action(self,_):\n self.round()\n if self.Prefs != []:\n Pref = self.Prefs.pop(0)\n self.Pref = Pref<<28\n def round(self):\n ma.makeWrite(1,1,self.Pref+0x00001000,3,self.Code)\n mb.makeWrite(1,1,self.Pref+0x00002000,3,self.Code+1)\n mc.makeWrite(1,1,self.Pref+0x00003000,3,self.Code+2)\n md.makeWrite(1,1,self.Pref+0x00004000,3,self.Code+3)\n\n ma.makeRead(1,1,self.Pref+0x00001000,3,self.Code)\n mb.makeRead(1,1,self.Pref+0x00002000,3,self.Code+1)\n mc.makeRead(1,1,self.Pref+0x00003000,3,self.Code+2)\n md.makeRead(1,1,self.Pref+0x00004000,3,self.Code+3)\n self.Code += 4\n\ndrv = driverMonitor('tb',Monitors)\n\n\nseq = sequenceClass.sequenceClass('tb',Monitors,'',[('ma',ma),('mb',mb),('mc',mc),('md',md),('drv',drv)])\nseq.msgCode = 100\n\n\ndef negedge():\n global cycles\n cycles += 1\n veri.force('tb.cycles',str(cycles))\n if (cycles>GIVEUP_TIMEOUT):\n logs.log_info('finishing on default guard of %d'%GIVEUP_TIMEOUT)\n veri.finish()\n rst_n = veri.peek('tb.rst_n')\n if (rst_n!='1'):\n return\n\n if (cycles==30):\n veri.listing('tb','100','deep.list')\n if (cycles>30):\n for Mon in Monitors: Mon.run()\n\n","sub_path":"axi_noc/tb2/verilog.py","file_name":"verilog.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"187640561","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.3 (3230)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/trepan/processor/command/exit.py\n# Compiled at: 2018-02-01 07:53:21\n# Size of source mod 2**32: 2086 bytes\nimport os\nfrom trepan.processor.command import base_cmd as Mbase_cmd\n\nclass ExitCommand(Mbase_cmd.DebuggerCommand):\n __doc__ = '**exit** [*exitcode*]\\n\\nHard exit of the debugged program.\\n\\nThe program being debugged is exited via *sys.exit()*. If a return code\\nis given, that is the return code passed to *sys.exit()*, the\\nreturn code that will be passed back to the OS.\\n\\nSee also:\\n---------\\n\\nSee `quit` and `kill`.\\n'\n category = 'support'\n min_args = 0\n max_args = 1\n name = os.path.basename(__file__).split('.')[0]\n need_stack = False\n short_help = 'Exit program via sys.exit()'\n\n def run(self, args):\n self.core.stop()\n self.core.execution_status = 'Exit command'\n if len(args) <= 1:\n exit_code = 0\n else:\n exit_code = self.proc.get_int(args[1], default=0, cmdname='exit')\n if exit_code is None:\n return False\n else:\n import sys\n sys.exit(int(exit_code))\n return True\n\n\nif __name__ == '__main__':\n from trepan.processor.command import mock\n d, cp = mock.dbg_setup()\n command = ExitCommand(cp)\n command.run(['exit', 'wrong', 'number', 'of', 'args'])\n command.run(['exit', 'foo'])\n command.run(['exit', '10'])","sub_path":"pycfiles/trepan3k-0.8.6-py3.3/exit.cpython-33.py","file_name":"exit.cpython-33.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"397384462","text":"from setuptools import setup, find_packages\nimport distutils\nimport os\n\nclass LocalesCommand(distutils.cmd.Command):\n description='compile locale files'\n def run(self):\n command = [\"make\" \"update-langs\"]\n subprocess.check_call(command)\n\n\nversion_file = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'offlate', 'VERSION'))\nversion = version_file.read().strip()\n\nsetup (\n name=\"offlate\",\n version=version,\n packages=find_packages(exclude=['.guix-profile*']),\n python_requires = '>=3',\n install_requires=['polib', 'ruamel.yaml', 'python-dateutil', 'PyQt5', 'pygit2',\n 'python-gitlab', 'translation-finder', 'android-stringslib', 'watchdog',\n 'PyGithub', 'lxml', 'pyenchant'],\n entry_points={\n 'gui_scripts': [\n 'offlate=offlate.ui.main:main',\n ]\n },\n\n package_data={'offlate': ['data.json', 'locales/*.qm', 'locales/*.ts', 'icon.png', 'VERSION']},\n cmdclass={\n 'locales': LocalesCommand,\n },\n\n author=\"Julien Lepiller\",\n author_email=\"julien@lepiller.eu\",\n description=\"Offline translation interface for online translation tools.\",\n long_description=\"\"\"Offlate is a graphical interface designed for translators\nof free and open source software. Software projects in the free software community\nuse a wide range of online platforms (or no platform at all) to manage their\ntranslations. Offlate is able to connect to many different platforms, copy the\ntranslations locally, and let you work on them on your computer, offline and in\na unified interface.\"\"\",\n license=\"GPLv3+\",\n keywords=\"translation\",\n url=\"https://framagit.org/tyreunom/offlate\",\n classifiers=[\n # How mature is this project? Common values are\n # 3 - Alpha\n # 4 - Beta\n # 5 - Production/Stable\n 'Development Status :: 3 - Alpha',\n\n # Indicate who your project is intended for\n 'Intended Audience :: End Users/Desktop',\n 'Topic :: Software Development :: Localization',\n\n # Pick your license as you wish (should match \"license\" above)\n 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',\n\n # Specify the Python versions you support here. In particular, ensure\n # that you indicate whether you support Python 2, Python 3 or both.\n 'Programming Language :: Python :: 3',\n ],\n project_urls={\n \"Bug Tracker\": \"https://framagit.org/tyreunom/offlate/issues\",\n \"Source Code\": \"https://framagit.org/tyreunom/offlate\",\n #\"Documentation\": \"https://docs.example.com/HelloWorld/\",\n },\n)\n","sub_path":"pypi_install_script/offlate-0.5.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"429297142","text":"import socket\n\ntarget_host = \"127.0.01\"\ntarget_port = 9999\n\n# Create socket obj\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# connect client\nclient.connect((target_host, target_port))\n\n# send datas\nclient.send(\"GET / HTTP/1.1\\r\\nHost: www.google.com\\r\\n\\r\\n\")\n\n# recieve\nresponse = client.recv(4096)\n\nprint(response)","sub_path":"tcpclient.py","file_name":"tcpclient.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"169930811","text":"# -*- coding: utf-8 -*-\nimport matplotlib.pyplot as plt\nfrom random import randint\nimport timeit\nimport numpy as np\nimport scipy.interpolate as interpolate\nimport sys \n\nreload(sys) \nsys.setdefaultencoding('utf8')\n\nnumbers = [1000,10000,20000,30000,40000,50000,60000,70000,80000,90000,100000]\n\n#template to generate lists to be sorted\ndef generateList(size):\n listt = []\n for i in range(size):\n n = randint(1,100)\n if(n in listt):\n n = randint(1,100)\n listt.append(n)\n return listt\n\ndef listDesc(size):\n listt =[]\n while (size > 0):\n listt.append(size)\n size = size-1\n return listt\n\ndef listAsc(size):\n listt = []\n for i in range(size):\n listt.append(i+1)\n return listt\n\n#selectionsort\ndef sort(vetor):\n\tfor posi in range(len(vetor)-1,0,-1):\n\t\tposi_max = 0\n\t\tfor posi1 in range(1, posi+1):\n\t\t\tif vetor[posi1] > vetor[posi_max]:\n\t\t\t\tposi_max = posi1\n\n\t\taux = vetor[posi]\n\t\tvetor[posi] = vetor[posi_max]\n\t\tvetor[posi_max] = aux\n\n\treturn vetor\n\ndef drawGraph(x,y,l, n, xl = \"Nº de Elementos\", yl = \"Tempo(s)\"):\n xnew = np.linspace(min(x), max(x), 10 * (max(x) - min(x)))\n a, b, c = interpolate.splrep(x, y, s=0, k=2)\n suave = interpolate.BSpline(a, b, c, extrapolate=False)\n plt.subplot(n)\n plt.plot(xnew, suave(xnew), label=\"Curva Suave\")\n plt.plot(x,y, label=\"Curva Sem Suaveização\")\n plt.legend(bbox_to_anchor=(1, 1),bbox_transform=plt.gcf().transFigure)\n plt.ylabel(yl)\n plt.xlabel(xl)\n plt.title(l, fontsize=12)\n\n#template to sort list generated\ndef midCase(nums0):\n\tnums = nums0\n\ttime = []\n\tfor r in nums:\n\t print(r)\n\t vector = generateList(r)\n\t tempo = timeit.timeit(\"sort({})\".format(vector),setup=\"from __main__ import sort\",number=1)\n\t time.append(tempo)\n\n\tdrawGraph(nums, time,'Caso Medio',211, \"Nº de Elementos\", \"Tempo(s)\")\n\ndef worseCase(nums1):\n\tnums=nums1\n\ttime1=[]\n\tfor r in nums:\n\t\tprint (r)\n\t\tvector1 = listDesc(r)\n\t\ttempo = timeit.timeit(\"sort({})\".format(vector1),setup=\"from __main__ import sort\",number=1)\n\t\ttime1.append(tempo)\n\n\tdrawGraph(nums, time1, 'Pior Caso',212, \"Nº de Elementos\", \"Tempo(s)\")\n\ndef bestCase(nums2):\n\tnums=nums2\n\ttime2=[]\n\tfor r in nums:\n\t\tprint (r)\n\t\tvector1 = listAsc(r)\n\t\ttempo = timeit.timeit(\"sort({})\".format(vector1),setup=\"from __main__ import sort\",number=1)\n\t\ttime2.append(tempo)\n\n\tdrawGraph(nums, time2, 'Melhor Caso',212, \"Nº de Elementos\", \"Tempo(s)\")\n\nmidCase(numbers)\nworseCase(numbers)\nbestCase(numbers)\nplt.show()","sub_path":"selectsort/selectsort.py","file_name":"selectsort.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"639051328","text":"\"\"\"\r\n\n\nCreate a function that takes a dictionary of student names and returns a list\nof student names in **alphabetical order**.\n\n### Examples\n\n get_student_names({\n \"Student 1\" : \"Steve\",\n \"Student 2\" : \"Becky\",\n \"Student 3\" : \"John\"\n }) ➞ [\"Becky\", \"John\", \"Steve\"]\n\n### Notes\n\n * Don't forget to `return` your result.\n * If you get stuck on a challenge, find help in the **Resources** tab.\n * If you're _really_ stuck, unlock solutions in the **Solutions** tab.\n\n\"\"\"\r\n\ndef get_student_names(students):\n lst = []\n for x in students:\n lst.append(students[x])\n return sorted(lst)\n\n","sub_path":"HvkPdhijquecKASdF_14.py","file_name":"HvkPdhijquecKASdF_14.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"27341858","text":"\"\"\"CSC148 Assignment 1 - Simulation\n\n=== CSC148 Fall 2018 ===\nDepartment of Computer Science,\nUniversity of Toronto\n\n=== Module description ===\nThis contains the main Simulation class that is actually responsible for\ncreating and running the simulation. You'll also find the function `sample_run`\nhere at the bottom of the file, which you can use as a starting point to run\nyour simulation on a small configuration.\n\nNote that we have provided a fairly comprehensive list of attributes for\nSimulation already. You may add your own *private* attributes, but should not\nremove any of the existing attributes.\n\"\"\"\n# You may import more things from these modules (e.g., additional types from\n# typing), but you may not import from any other modules.\nfrom typing import Dict, List, Any\n\nimport algorithms\nfrom entities import Person, Elevator\nfrom visualizer import Visualizer\n\n\nclass Simulation:\n \"\"\"The main simulation class.\n\n === Attributes ===\n arrival_generator: the algorithm used to generate new arrivals.\n elevators: a list of the elevators in the simulation\n moving_algorithm: the algorithm used to decide how to move elevators\n num_floors: the number of floors\n visualizer: the Pygame visualizer used to visualize this simulation\n waiting: a dictionary of people waiting for an elevator\n (keys are floor numbers, values are the list of waiting people)\n num_iterations: number of rounds run\n people_completed: number of people arriving at their target\n people_wait_times: list of people - will extract wait times from them\n\n\n === Representation Invariants ===\n num_floors >= 2\n num_elevators >= 1\n\n \"\"\"\n arrival_generator: algorithms.ArrivalGenerator\n elevators: List[Elevator]\n moving_algorithm: algorithms.MovingAlgorithm\n num_floors: int\n visualizer: Visualizer\n waiting: Dict[int, List[Person]]\n\n num_iterations: int\n people_completed: int\n people_wait_times: List[Person]\n\n def __init__(self, config: Dict[str, Any]) -> None:\n \"\"\"Initialize a new simulation using the given configuration.\"\"\"\n\n self.arrival_generator = config['arrival_generator']\n self.elevators = []\n\n #create elevators\n i = 0\n while i < config['num_elevators']:\n new_elevator = Elevator([], 1, config['elevator_capacity'], 0)\n self.elevators.append(new_elevator)\n i += 1\n\n self.moving_algorithm = config['moving_algorithm']\n self.num_floors = config['num_floors']\n self.waiting = {} #initialize empty waiting dictionary\n self.people_completed = 0\n self.people_wait_times = []\n\n for floor in range(1, self.num_floors + 1):\n self.waiting[floor] = [] #create empty list for each floor\n\n # Initialize the visualizer.\n # Note that this should be called *after* the other attributes\n # have been initialized.\n self.visualizer = Visualizer(self.elevators, self.num_floors,\n config['visualize'])\n\n ############################################################################\n # Handle rounds of simulation.\n ############################################################################\n def run(self, num_rounds: int) -> Dict[str, Any]:\n \"\"\"Run the simulation for the given number of rounds.\n\n Return a set of statistics for this simulation run, as specified in the\n assignment handout.\n\n Precondition: num_rounds >= 1.\n\n Note: each run of the simulation starts from the same initial state\n (no people, all elevators are empty and start at floor 1).\n \"\"\"\n self.num_iterations = num_rounds\n\n for i in range(num_rounds):\n self.visualizer.render_header(i)\n\n # Stage 1: generate new arrivals\n self._generate_arrivals(i)\n\n # Stage 2: leave elevators\n self._handle_leaving()\n\n # Stage 3: board elevators\n self._handle_boarding()\n\n # Stage 4: move the elevators using the moving algorithm\n self._move_elevators()\n\n self._update_wait_times()\n\n\n # Pause for 1 second\n self.visualizer.wait(1)\n\n return self._calculate_stats()\n\n def _generate_arrivals(self, round_num: int) -> None:\n \"\"\"Generate and visualize new arrivals.\"\"\"\n generated_people = self.arrival_generator.generate(round_num)\n\n #add new people to track their wait times\n for floor in generated_people:\n for person in generated_people[floor]:\n self.people_wait_times.append(person)\n\n # update waiting dictionary so that waiting dict stores ppl\n # waiting from previous rounds\n for floor in generated_people:\n if len(generated_people[floor]) > 0:\n self.waiting[floor].extend(generated_people[floor])\n\n self.visualizer.show_arrivals(generated_people)\n\n def _handle_leaving(self) -> None:\n \"\"\"Handle people leaving elevators.\"\"\"\n\n for elevator in self.elevators:\n to_remove = []\n for person in elevator.passengers:\n if person.target == elevator.current_floor:\n person.arrived_on_floor = True\n elevator.num_passengers -= 1\n Visualizer.show_disembarking(self.visualizer, person,\n elevator)\n to_remove.append(person)\n\n self.people_completed += len(to_remove)\n for p in to_remove:\n elevator.passengers.remove(p)\n\n def _handle_boarding(self) -> None:\n \"\"\"Handle boarding of people and visualize.\"\"\"\n for floor in self.waiting:\n\n #list of people that board elevator and will be removed\n to_remove = []\n\n\n for person_waiting in self.waiting[floor]:\n\n elevator_index = self._available_elevator(person_waiting)\n if elevator_index != -1:\n #add person to available elevator\n elevator = self.elevators[elevator_index]\n\n elevator.passengers.append(person_waiting)\n elevator.num_passengers += 1\n\n #remove person from floor\n to_remove.append(person_waiting)\n\n #show visualization of person boarding\n Visualizer.show_boarding(self.visualizer,\n person_waiting, elevator)\n\n #remove all people that boarded an elevator from the waiting list\n for person in to_remove:\n self.waiting[floor].remove(person)\n\n #for the _handle_boarding class\n def _available_elevator(self, person: Person) -> int:\n \"\"\"Checks too see if there is an available elevator on the same floor\n as this person\n\n Returns index of available elevator in self.elevators or -1 if there\n is no elevator available\n \"\"\"\n\n for elevator_index in range(0, len(self.elevators)):\n elevator = self.elevators[elevator_index]\n if elevator.num_passengers < elevator.max_capacity and \\\n elevator.current_floor == person.start:\n return elevator_index\n\n return -1\n\n def _move_elevators(self) -> None:\n \"\"\"Move the elevators in this simulation.\n\n Use this simulation's moving algorithm to move the elevators.\n \"\"\"\n directions_list = self.moving_algorithm.move_elevators(self.elevators,\n self.waiting,\n self.num_floors)\n Visualizer.show_elevator_moves(self.visualizer, self.elevators,\n directions_list)\n\n def _update_wait_times(self) -> None:\n \"\"\" Update the wait time's of everyone waiting for an elevator,\n and everyone currently inside an elevator\n \"\"\"\n for elevator in self.elevators:\n for riding_person in elevator.passengers:\n riding_person.wait_time += 1\n\n for floor in self.waiting:\n for waiting_person in self.waiting[floor]:\n waiting_person.wait_time += 1\n\n def _max_time(self, people_wait_times: List[Person]) -> int:\n \"\"\"\n Return the person with the maximum waiting time\n \"\"\"\n maximum = -1\n for person in people_wait_times:\n if person.arrived_on_floor:\n if person.wait_time > maximum:\n maximum = person.wait_time\n return maximum\n\n def _min_time(self, people_wait_times: List[Person]) -> int:\n \"\"\"\n Return the person with the minimum waiting time\n \"\"\"\n found_min = False\n minimum = -1\n\n for person in people_wait_times:\n if person.arrived_on_floor:\n if not found_min:\n minimum = person.wait_time\n found_min = True\n else:\n if person.wait_time < minimum:\n minimum = person.wait_time\n return minimum\n\n def _avg_time(self, people_wait_times: List[Person]) -> int:\n \"\"\"\n Return the person with the maximum waiting time\n \"\"\"\n total_time = 0\n for person in people_wait_times:\n if person.arrived_on_floor:\n total_time += person.wait_time\n\n if self.people_completed != 0:\n return int(total_time / self.people_completed)\n else:\n return -1 #nobody completed so return -1\n\n ############################################################################\n # Statistics calculations\n ############################################################################\n def _calculate_stats(self) -> Dict[str, int]:\n \"\"\"Report the statistics for the current run of this simulation.\n \"\"\"\n\n return {\n 'num_iterations': self.num_iterations,\n 'total_people': self.arrival_generator.total_people,\n 'people_completed': self.people_completed,\n 'max_time': self._max_time(self.people_wait_times),\n 'min_time': self._min_time(self.people_wait_times),\n 'avg_time': self._avg_time(self.people_wait_times)\n }\n\ndef sample_run() -> Dict[str, int]:\n \"\"\"Run a sample simulation, and return the simulation statistics.\"\"\"\n\n\n config = {\n 'num_floors': 6,\n 'num_elevators': 6,\n 'elevator_capacity': 3,\n 'num_people_per_round': 2,\n # Random arrival generator with 6 max floors and 2 arrivals per round.\n 'arrival_generator': algorithms.FileArrivals(6, 'sample_arrivals.csv'),\n 'moving_algorithm': algorithms.ShortSighted(),\n 'visualize': True\n }\n\n\n\n sim = Simulation(config) #initializes simulation\n stats = sim.run(15) #runs simulation for num_rounds, returns stats\n return stats\n\n\nif __name__ == '__main__':\n # Uncomment this line to run our sample simulation (and print the\n # statistics generated by the simulation).\n print(sample_run())\n\n import python_ta\n python_ta.check_all(config={\n 'extra-imports': ['entities', 'visualizer', 'algorithms', 'time'],\n 'max-nested-blocks': 4,\n 'max-attributes': 12,\n 'disable': ['R0201']\n })\n","sub_path":"simulation (1).py","file_name":"simulation (1).py","file_ext":"py","file_size_in_byte":11467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"394489101","text":"# Finding lists of elements\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\nclass ListOfElements():\n\n def find(self):\n baseurl = \"https://letskodeit.teachable.com/pages/practice\"\n driver = webdriver.Firefox()\n driver.get(baseurl)\n\n elementsListByClassName = driver.find_elements(By.CLASS_NAME, \"inputs\")\n\n if elementsListByClassName is not None:\n lenght1 = len(elementsListByClassName)\n print(\"We found a list of elements by Class Name with size equal to \" + str(lenght1))\n\n elementsListByTagName = driver.find_elements(By.TAG_NAME, \"a\")\n\n if elementsListByTagName is not None:\n lenght2 = len(elementsListByTagName)\n print(\"We found a list of elements By Tag Name with size equal to \" + str(lenght2))\n\nff = ListOfElements()\nff.find()","sub_path":"FindingElements/ListOfElements.py","file_name":"ListOfElements.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"608680302","text":"# coding: utf-8 \nimport socketserver\nimport socket\nimport os\n# Copyright 2013 Abram Hindle, Eddie Antonio Santos\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n#\n# Furthermore it is derived from the Python documentation examples thus\n# some of the code is Copyright © 2001-2013 Python Software\n# Foundation; All Rights Reserved\n#\n# http://docs.python.org/2/library/socketserver.html\n#\n# run: python freetests.py\n\n# try: curl -v -X GET http://127.0.0.1:8080/\n\n\nclass MyWebServer(socketserver.BaseRequestHandler):\n def handle(self):\n self.data = self.request.recv(1024).strip()\n print (\"Got a request of: %s\\n\" % self.data)\n \n payload = self.data.decode()\n if payload:\n payload_data = payload.split()\n method,path = payload_data[0],payload_data[1]\n \n if method == \"GET\":\n \n if self.check_path(path):\n if os.path.exists(\"./www\"+path) and path.endswith(\"html\"):\n body = open(\"./www\"+path,'r').read()\n self.request.send(\"HTTP/1.1 200 OK\\r\\n\".encode())\n self.request.send(\"Content-Type: text/html;\\r\\n\".encode())\n self.request.send(\"{} {} {}\".format(\"Content-length: \",len(body),\"\\r\\n\").encode())\n self.request.send(\"Connection : close \\r\\n\\r\\n\".encode())\n self.request.send(body.encode())\n\n elif os.path.exists(\"./www\"+path) and path.endswith(\"css\"):\n body = open(\"./www\"+path,'r').read()\n self.request.send(\"HTTP/1.1 200 OK\\r\\n\".encode())\n self.request.send(\"Content-Type: text/CSS;\\r\\n\".encode())\n self.request.send(\"{} {} {}\".format(\"Content-length: \",len(body),\"\\r\\n\").encode())\n self.request.send(\"Connection : close \\r\\n\\r\\n\".encode())\n self.request.send(body.encode())\n\n elif os.path.exists(\"./www\"+path+\"index.html\") and path.endswith('/'):\n path += \"index.html\"\n if open(\"./www\"+path,'r').read():\n body = open(\"./www\"+path,'r').read()\n self.request.send(\"HTTP/1.1 200 OK\\r\\n\".encode())\n self.request.send(\"Content-Type: text/html;\\r\\n\".encode())\n self.request.send(\"{} {} {}\".format(\"Content-length: \",len(body),\"\\r\\n\").encode())\n self.request.send(\"Connection : close \\r\\n\\r\\n\".encode())\n self.request.send(body.encode())\n else: self.request.send(\"HTTP/1.1 404 Not Found\".encode()) \n \n else:\n \n try: \n body = open('./www'+path+'/index.html','r').read()\n self.request.send(\"HTTP/1.1 301 Moved Permanently\\r\\n\".encode())\n self.request.send(\"Content-Type: text/html;\\r\\n\".encode())\n addrs = \"Location: http://127.0.0.1:8080\"+path+'/\\r\\n\\r\\n'\n self.request.send(addrs.encode())\n\n except:\n self.request.send(\"HTTP/1.1 404 Not Found\\r\\n\\r\\n\".encode()) \n else : self.request.send(\"HTTP/1.1 404 Not Found\\r\\n\\r\\n\".encode()) \n else:self.request.send(\"HTTP/1.1 405 Method Not Allowed\".encode())\n \n def check_path(self,path):\n return os.path.realpath(os.getcwd()+'/www' +path).startswith(os.getcwd()+'/www')\n\n \nif __name__ == \"__main__\":\n HOST, PORT = \"localhost\", 8080\n\n socketserver.TCPServer.allow_reuse_address = True\n # Create the server, binding to localhost on port 8080\n server = socketserver.TCPServer((HOST, PORT), MyWebServer)\n\n # Activate the server; this will keep running until you\n # interrupt the program with Ctrl-C\n server.serve_forever()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"361358540","text":"#Import necessary Libraries\nimport cv2\nimport numpy as np\n\n#https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_colorspaces/py_colorspaces.html#converting-colorspaces\n\nvideo_recorder = cv2.VideoCapture(0)\n\nwhile True:\n ret, frame = video_recorder.read()\n\n #Convert the frame to grayscale\n gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n #Define the lower and upper range (HSV for yellow is 30 255 255\n upper = np.array([40,255,255])\n lower = np.array([20,128,128])\n\n #Create mask\n mask = cv2.inRange(hsv, lower, upper)\n\n res = cv2.bitwise_and(frame, frame , mask = mask)\n\n #Blur the image\n blur = cv2.GaussianBlur(res, (15, 15), 0)\n\n cv2.imshow('Video', frame)\n cv2.imshow('Black and White', gray_frame)\n cv2.imshow('Mask', mask)\n cv2.imshow('Yellow filtered', res)\n cv2.imshow('Blurred Image', blur)\n\n #https://www.youtube.com/watch?v=sARklx6sgDk&list=PLQVvvaa0QuDdttJXlLtAJxJetJcqmqlQq&index=8\n\n if(cv2.waitKey(1) & 0xFF == ord('q')):\n break\n\n#Release video capture\nvideo_recorder.release\n","sub_path":"Color_Filtering/mask.py","file_name":"mask.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"124621330","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.utils.timezone\nfrom django.conf import settings\nimport ckeditor_uploader.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('labels', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='BlogPost',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(max_length=150, verbose_name='title')),\n ('slug', models.SlugField(verbose_name='slug')),\n ('teaser', ckeditor_uploader.fields.RichTextUploadingField(verbose_name='teaser', blank=True)),\n ('body', ckeditor_uploader.fields.RichTextUploadingField(verbose_name='body', blank=True)),\n ('create_time', models.DateTimeField(default=django.utils.timezone.now, verbose_name='create_time', editable=False)),\n ('update_time', models.DateTimeField(verbose_name='update_time', null=True, editable=False, blank=True)),\n ('publish_time', models.DateTimeField(null=True, verbose_name='publish_time', blank=True)),\n ('state', models.IntegerField(default=2, verbose_name='state', choices=[(1, b'published'), (2, b'draft')])),\n ('secret_key', models.CharField(help_text='unique key for share url', unique=True, max_length=8, verbose_name='secret key', blank=True)),\n ('author', models.ForeignKey(related_name='blog_posts', verbose_name='author', to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)),\n ('labels', models.ManyToManyField(related_name='blog_posts', verbose_name='YmeLabel', to='labels.YmeLabel')),\n ],\n options={\n 'ordering': ('-publish_time',),\n 'get_latest_by': 'publish_time',\n 'verbose_name': 'BlogPost',\n 'verbose_name_plural': 'BlogPosts',\n },\n ),\n ]\n","sub_path":"blog/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"495432237","text":"import sqlite3, sys,os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style(\"whitegrid\")\ncolors = [\"#34495e\", \"#e74c3c\"]\nsns.set_palette(colors)\nos.chdir(sys.path[0])\n\n#TODO: RUNS BUT ONE PLOT CHANGED TO CAT_PLOT\n#\t\tSEABORNS DOES NOT HAVE FACTOR_PLOT ANYMORE\npd.set_option('display.width', 1000, 'display.precision', 2, 'display.max_rows', 999)\n\n\nexec(open('Imports.py').read())\nimport Modules.Funcs as funcs\n\n# import data\ncon = sqlite3.connect('../data/experiment.db')\ninfo = pd.read_sql_query(\"SELECT participant, condition from participants\", con)\nstats = pd.read_sql_query(\"SELECT * from betastats\", con)\ncon.close()\n\nstats = pd.merge(stats, info, on = 'participant')\n\nprint(stats[['condition','yrange']])\n#lll\n\nfh, axes = plt.subplots(1,3,figsize = (7.5,2.5))\n\nfor i, col in enumerate(['xrange','yrange','correlation']):\n\tax = axes[i]\n\ths = sns.catplot(x = 'condition', y = col, data= stats, ax = ax, kind = 'box', \n\t\torder = ['Bottom', 'Middle'])\n\n\tax.set_title(col, fontsize = 12)\n\tax.set_ylabel('')\n\n\tif 'range' in col:\n\t\tax.set_title(col[0].upper() + ' Range', fontsize = 12)\n\n\t\tax.set_yticks([0,2])\n\t\tax.set_yticklabels(['Min','Max'])\n\n\telse:\n\t\tax.set_title('Correlation', fontsize = 12)\n\t\tax.set_yticks([-1,-0.5,0,0.5,1])\n\t\tax.set_yticklabels(['-1','-0.5','0','0.5','1'])\n\tax.tick_params(labelsize = 11)\n\tax.set_xlabel('')\n\tax.xaxis.grid(False)\n\nfh.subplots_adjust(wspace=0.4)\n#fh.savefig('statsboxes.png', bbox_inches = 'tight')\n\n#path = '../../../Manuscripts/cog-psych/figs/e2-statsboxes.pgf'\n#funcs.save_as_pgf(fh, path)\n\n# hypothesis tests\nfrom scipy.stats import ttest_ind, ttest_rel, ttest_1samp, wilcoxon, ranksums\nfrom itertools import combinations\n\ndef print_ttest(g1, g2, fun):\n\tres = fun(g1,g2)\n\tS = 'T = ' + str(round(res.statistic, 4))\n\tS+= ', p = ' + str(round(res.pvalue, 10))\n\tS+= '\\tMeans:'\n\tfor j in [g1, g2]:\n\t\tS += ' ' + str(round(np.mean(j), 4))\n\t\tS += ' (' + str(round(np.std(j), 4)) + '),'\n\tprint(S)\n\n\nprint('\\n---- Bottom X vs. Y:')\ng1 = stats.loc[stats.condition == 'Bottom', 'xrange']\ng2 = stats.loc[stats.condition == 'Bottom', 'yrange']\nprint_ttest(g1,g2, ttest_rel)\n\nprint('\\n---- Middle X vs. Y:')\ng1 = stats.loc[stats.condition == 'Middle', 'xrange']\ng2 = stats.loc[stats.condition == 'Middle', 'yrange']\nprint_ttest(g1,g2, ttest_rel)\n\nprint('\\n---- Bottom positive correlation?')\ng1 = stats.loc[stats.condition == 'Bottom', 'correlation']\nprint(ttest_1samp(g1, 0).pvalue)\nprint(wilcoxon(g1).pvalue)\n\nprint('\\n---- within vs. between?')\nfor n, rows in stats.groupby('condition'):\n\tprint('\\t'+n+':')\n\tg1 = rows.loc[:,'between']\n\tg2 = rows.loc[:,'within']\n\tprint_ttest(g1,g2, ttest_rel)\n\n# between conditions\nfor j in ['xrange','yrange','correlation']:\n\tfor a, b in combinations(pd.unique(stats.condition), r=2):\n\t\tg1 = stats.loc[stats.condition == a, j]\n\t\tg2 = stats.loc[stats.condition == b, j]\n\t\tprint('\\n---- ' + ' ' + j + ': ' + a + ', ' + b)\n\t\tprint_ttest(g1,g2, ttest_ind)\n\ncols = ['condition', 'between', 'correlation', 'within', 'xrange', 'yrange']\nprint(stats[cols].groupby('condition').describe())\n","sub_path":"Experiments/middle_bottom/analysis/plot.stats.figs.py","file_name":"plot.stats.figs.py","file_ext":"py","file_size_in_byte":3105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"496144059","text":"from pymongo import MongoClient\nfrom pprint import pprint\nimport datetime\nimport boto3\n\n# connect to MongoDB, change the << MONGODB URL >> to reflect your own connection string\nclient = MongoClient(\"mongodb://heroku_24353wrj:tq5ltjpkpib8p3nbm17jcu6084@ds155278.mlab.com:55278/heroku_24353wrj\")\ns3 = boto3.resource('s3')\ndb = client.heroku_24353wrj\njournals = db.journals\n\njournal = {\n\"year\":\"2005\",\n\"month\":\"october\",\n\"journal_date\":\"30\",\n\"vol\":\"1\",\n\"content\":\"\",\n\"image_url\":\"https://s3.amazonaws.com/jee-journals/\",\n\"date_added\":datetime.datetime.utcnow()\n}\n\n#journals.insert(journal)\n#print (journal_id)\n\ndata = open('1.png', 'rb')\ns3.Bucket('jee-journals').put_object(Key='2005/10/1.png', Body=data)\n","sub_path":"OCR/pixelscan-test/functions/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"15688589","text":"\"\"\"Support for Renault ZE services.\"\"\"\n\nimport aiohttp\nimport asyncio\nimport json\nimport base64\nimport time\n\n\nclass RenaultZEServiceException(Exception):\n def __init__(self, value):\n sections = value.split(\".\")\n self.value = sections[len(sections)-1]\n\n def __str__(self):\n return repr(self.value)\n\n\nclass RenaultZEService:\n # API Gateway.\n servicesHost = 'https://www.services.renault-ze.com'\n\n def __init__(self, tokenPath=None, username=None, password=None):\n \"\"\"Initialize the sensor.\"\"\"\n self._tokenData = None\n self._tokenPath = tokenPath\n self._username = username\n self._password = password\n\n @property\n def tokenData(self):\n if (self._tokenPath is not None):\n try:\n with open(self._tokenPath, 'r') as tokenStorage:\n return json.load(tokenStorage)\n except FileNotFoundError:\n return None\n return self._tokenData\n\n @tokenData.setter\n def tokenData(self, value):\n if (self._tokenPath is not None):\n with open(self._tokenPath, 'w') as outfile:\n json.dump(value, outfile)\n return\n self._tokenData = value\n\n async def getAccessToken(self):\n currentTokenData = self.tokenData\n if currentTokenData is not None:\n # We could be using python_jwt but even the official ZE Services\n # (\"decodeToken\") does it this crude way, so why overcomplicate\n # things?\n splitToken = currentTokenData['token'].split('.')\n\n # Check it looks semi-valid.\n if len(splitToken) != 3:\n raise ValueError('Not a well formed JWT token')\n\n # Get the JSON payload of the JWT token.\n b64payload = splitToken[1]\n missing_padding = len(b64payload) % 4\n if missing_padding:\n b64payload += '=' * (4 - missing_padding)\n jsonPayload = base64.b64decode(b64payload).decode('utf-8')\n\n # Parse it as JSON.\n token = json.loads(jsonPayload)\n\n # Is the token still valid? If not, refresh it.\n if(time.gmtime() > time.gmtime(token['exp'])):\n url = RenaultZEService.servicesHost + '/api/user/token/refresh'\n payload = {'token': currentTokenData['token']}\n headers = {'X-XSRF-TOKEN': currentTokenData['xsrfToken']}\n cookies = {'refreshToken': currentTokenData['refreshToken']}\n\n async with aiohttp.ClientSession(\n skip_auto_headers=['User-Agent'],\n cookies=cookies\n ) as session:\n async with session.post(\n url,\n headers=headers,\n json=payload\n ) as response:\n jsonresponse = await response.json()\n\n if 'message' in jsonresponse:\n self.tokenData = None\n raise RenaultZEServiceException(jsonresponse['message'])\n\n # Overwrite the current token with\n # this newly returned one.\n currentTokenData['token'] = jsonresponse['token']\n\n # Save this refresh token and new JWT token so we are\n # nicer to Renault's authentication server.\n self.tokenData = currentTokenData\n\n # Return the token (as-is if valid, refreshed if not).\n return currentTokenData['token']\n\n # We have never cached an access token before.\n else:\n url = RenaultZEService.servicesHost + '/api/user/login'\n payload = {'username': self._username, 'password': self._password}\n async with aiohttp.ClientSession(\n skip_auto_headers=['User-Agent']\n ) as session:\n async with session.post(url, json=payload) as response:\n jsonresponse = await response.json()\n\n if 'message' in jsonresponse:\n self.tokenData = None\n raise RenaultZEServiceException(jsonresponse['message'])\n # We do not want to save all the user data returned on\n # login, so we create a smaller file of just the\n # mandatory information.\n currentTokenData = {\n 'refreshToken': response.cookies['refreshToken'].value,\n 'xsrfToken': jsonresponse['xsrfToken'],\n 'token': jsonresponse['token']\n }\n\n # Save this refresh token and JWT token for future use\n # so we are nicer to Renault's authentication server.\n self.tokenData = currentTokenData\n\n # The script will just want the token.\n return currentTokenData['token']\n\n async def apiGetCall(self, path):\n url = RenaultZEService.servicesHost + path\n headers = {'Authorization': 'Bearer ' + await self.getAccessToken()}\n async with aiohttp.ClientSession(\n skip_auto_headers=['User-Agent']\n ) as session:\n async with session.get(url, headers=headers) as response:\n responsetext = await response.text()\n if responsetext == '':\n responsetext = '{}'\n jsonresponse = json.loads(responsetext)\n if 'message' in jsonresponse:\n self.tokenData = None\n raise RenaultZEServiceException(jsonresponse['message'])\n return jsonresponse\n\n async def apiPostCall(self, path):\n url = RenaultZEService.servicesHost + path\n headers = {'Authorization': 'Bearer ' + await self.getAccessToken()}\n async with aiohttp.ClientSession(\n skip_auto_headers=['User-Agent']\n ) as session:\n async with session.post(url, headers=headers) as response:\n responsetext = await response.text()\n if responsetext == '':\n responsetext = '{}'\n jsonresponse = json.loads(responsetext)\n if 'message' in jsonresponse:\n self.tokenData = None\n raise RenaultZEServiceException(jsonresponse['message'])\n return jsonresponse\n","sub_path":"custom_components/sensor/renaultzeservice/renaultzeservice.py","file_name":"renaultzeservice.py","file_ext":"py","file_size_in_byte":6599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"284393697","text":"from sqlalchemy import create_engine, Column, Integer, Boolean, Unicode, Index\nfrom sqlalchemy.orm import scoped_session, sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\n\nimport settings\n\nif settings.db_type == \"sqlite\":\n engine = create_engine(\"sqlite:///data/sqlite.db\", echo=False, encoding=\"latin\")\nelif settings.db_type == \"postgres\":\n engine = create_engine(\"postgresql+psycopg2://%s:%s@%s/%s\" % (\n settings.db_user, settings.db_pass, settings.db_host, settings.db_name), echo=False, encoding=\"latin\")\nelse:\n raise Exception(\"u wot m8\")\n\nbase = declarative_base(name=\"Model\")\nsession = scoped_session(sessionmaker(autocommit=False,\n autoflush=False,\n bind=engine))\nbase.query = session.query_property()\n\n\nclass AsciiModel(base):\n __tablename__ = \"ascii\"\n id = Column(Integer, primary_key=True)\n name = Column(Unicode())\n path = Column(Unicode())\n html = Column(Unicode())\n numlines = Column(Integer())\n colored = Column(Boolean())\n scene = Column(Boolean())\n\n ix_colored = Index(\"ix_colored\", colored)\n ix_numlines = Index(\"ix_numlines\", numlines)\n ix_name = Index(\"ix_name\", name)\n ix_name_gin = Index(\"ix_name_gin\", name, postgresql_using=\"gin\", postgresql_ops={\"name\": \"gin_trgm_ops\"})\n\nbase.metadata.create_all(bind=engine)\n","sub_path":"trollascii/orm.py","file_name":"orm.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"104552835","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Aug 27 11:40:09 2019\r\n\r\n@author: USER\r\n\"\"\"\r\n\r\n#coding=utf-8\r\nimport threading\r\nimport time\r\nimport numpy as np\r\nimport math\r\nimport matplotlib.pyplot as plt\r\nfrom queue import Queue\r\nfrom numba import jit\r\nimport warnings\r\nimport sys\r\nsys.setrecursionlimit(9000000) #這裡設定大一些\r\nwarnings.filterwarnings('ignore')\r\n\r\n@jit\r\ndef thread_job(arr,q):\r\n daily_returns=np.random.normal(mu/T,vol/math.sqrt(T),T)+1\r\n arr = [S]\r\n for x in daily_returns:\r\n arr.append(arr[-1]*x)\r\n q.put(arr)\r\n #print(arr)\r\n \r\n@jit\r\ndef multithreading():\r\n q = Queue() # 宣告 Queue 物件\r\n threads = [] # 用來放 thread 的 array\r\n price_list=[[S] for i in range(times)]\r\n for i in range(times):\r\n t = threading.Thread(target=thread_job, args=(price_list[i],q)) \r\n t.start()\r\n threads.append(t)\r\n\r\n for thread in threads:\r\n thread.join() # 每個 thread 都要做 join\r\n \r\n results = [] # 用來接收與顯示結果的 array\r\n \r\n for _ in range(times):\r\n results.append(q.get())# 取出 queue 裡面的資料\r\n #plt.plot(results.pop())\r\n \r\nif __name__=='__main__':\r\n \r\n times = 10000\r\n S = 100 #初始價格\r\n T = 252 #交易日\r\n mu = 0.2 #報酬率\r\n vol = 0.33 #波動度\r\n \r\n tStart = time.time()\r\n multithreading()\r\n tEnd = time.time()#計時結束\r\n #列印結果\r\n print (\"耗時:\" , (tEnd - tStart))#會自動做近位","sub_path":"thread_with_numba.py","file_name":"thread_with_numba.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"332130502","text":"#!/usr/bin/env python3\nimport sys, time, math\n\ndef readInput():\n if( len( sys.argv ) == 2 ):\n file = open( sys.argv[1] , \"r\")\n else:\n file = open(\"input\", \"r\")\n lines = file.readlines()\n return lines\n\ndef partOne( lines ):\n goal = int( lines[0] )\n buses = list( map( int, list(filter( lambda a: a != \"x\", lines[1].replace(\"\\n\",\"\").split(\",\") ))) )\n minimum = [100, 100, 0]\n for bus in buses:\n multiplier = 1\n done = False\n while( not done ):\n result = bus * multiplier\n if( result == goal ):\n done = True\n elif( result > goal ):\n diff = result - goal\n if( diff < minimum[0] ):\n minimum[0] = diff\n minimum[1] = bus\n done = True\n multiplier += 1\n print( \"PartOne:\", minimum[0] * minimum[1] )\n\n\ndef partTwo( lines ):\n buses = lines[1].replace(\"\\n\",\"\").split(\",\")\n busIDs = list( map( int, list(filter( lambda a: a != \"x\", lines[1].replace(\"\\n\",\"\").split(\",\") ))) )\n busIDs.sort( reverse=True )\n busIDs = list( map( lambda x: str(x), busIDs ) )\n workArray = []\n for id in busIDs:\n workArray.append( [ int( id ) , buses.index(id) ] )\n done = False\n multiplier = 1#int( 100000000000000 / workArray[0][0])\n while( not done ):\n result = multiplier * workArray[0][0]\n cts = workArray[0][1]\n allTrue = True\n for i in range(1, len( workArray ) ):\n bus = workArray[i]\n if( (result + ( bus[1] - cts) % bus[0]) != 0 ):\n allTrue = False\n break\n if( allTrue ):\n print( \"PartTwo:\", str( result - cts ) )\n done = True\n multiplier += 1\n\ndef main():\n lines = readInput()\n partOne( lines )\n partTwo( lines )\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"13/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"291841787","text":"from scipy.interpolate import CubicSpline\nimport pandas as pd\nimport os\nimport numpy as np\nfrom functions import utility\nfrom constants import *\nfrom scipy.stats import bernoulli\nimport matplotlib.pyplot as plt\nimport sys\n\n# policy functions: C_t(W_t)\ndef c_func(c_df, w, age):\n \"\"\" Given the consumption functions and wealth at certain age, return the corresponding consumption \"\"\"\n w = np.where(w < UPPER_BOUND_W, w, UPPER_BOUND_W)\n w = np.where(w > 1, w, 1)\n spline = CubicSpline(c_df[str(END_AGE)], c_df[str(age)], bc_type='natural')\n c = spline(w)\n # set coeffs of 2nd and 3rd order term to 0, 1st order term to the slope between the first two points\n if any(c < 0):\n spline.c[:2, 0] = 0\n spline.c[2, 0] = (c_df.loc[1, str(age)] - c_df.loc[0, str(age)]) / (c_df.loc[1, str(END_AGE)] - c_df.loc[0, str(END_AGE)])\n c = spline(w)\n return c\n\n\ndef generate_consumption_process(income_bf_ret, sigma_perm_shock, sigma_tran_shock, c_func_df, flag):\n \"\"\" Calculating the certainty equivalent annual consumption and life time wealth\"\"\"\n\n YEARS = END_AGE - START_AGE + 1\n\n ###########################################################################\n # simulate income process #\n # include income risks and unemployment risks #\n ###########################################################################\n # add income risks - generate the random walk and normal r.v.\n # - before retirement\n rn_perm = np.random.normal(MU, sigma_perm_shock, (N_SIM, RETIRE_AGE - START_AGE + 1))\n rand_walk = np.cumsum(rn_perm, axis=1)\n rn_tran = np.random.normal(MU, sigma_tran_shock, (N_SIM, RETIRE_AGE - START_AGE + 1))\n inc_with_inc_risk = np.multiply(np.exp(rand_walk) * np.exp(rn_tran), income_bf_ret)\n\n # - retirement TODO: not right here but not affect the CE, get rid of the transitory shock\n ret_income_vec = ret_frac[AltDeg] * np.tile(inc_with_inc_risk[:, -1], (END_AGE - RETIRE_AGE, 1)).T\n inc_with_inc_risk = np.append(inc_with_inc_risk, ret_income_vec, axis=1)\n\n # add unemployment risks - generate bernoulli random variables\n p = 1 - unempl_rate[AltDeg]\n r = bernoulli.rvs(p, size=(RETIRE_AGE - START_AGE + 1, N_SIM)).astype(float)\n r[r == 0] = unemp_frac[AltDeg]\n\n ones = np.ones((END_AGE - RETIRE_AGE, N_SIM))\n bern = np.append(r, ones, axis=0)\n\n inc = np.multiply(inc_with_inc_risk, bern.T)\n\n # ISA, Loan or orig\n if flag == 'rho':\n inc[:, :TERM] *= rho\n elif flag == 'ppt':\n inc[:, :TERM] -= ppt\n else:\n pass\n\n ################################################################################\n # COH_t+1 = (1 + R)*(COH_t - C_t) + Y_t+1 #\n # wealth = (1 + R)*(COH_t - C_t) #\n ################################################################################\n cash_on_hand = np.zeros((N_SIM, YEARS))\n c = np.zeros((N_SIM, YEARS))\n\n cash_on_hand[:, 0] = INIT_WEALTH + inc[:, 0] # cash on hand at age 22\n\n # 0-77, calculate consumption from 22 to 99, cash on hand from 23 to 100\n for t in range(YEARS - 1):\n c[:, t] = c_func(c_func_df, cash_on_hand[:, t], t + START_AGE)\n cash_on_hand[:, t+1] = (1 + R) * (cash_on_hand[:, t] - c[:, t]) + inc[:, t+1] # 1-78\n c[:, -1] = c_func(c_func_df, cash_on_hand[:, -1], END_AGE) # consumption at age 100\n\n # # GRAPH - Average Cash-on-hand & consumption over lifetime\n # plt.plot(cash_on_hand.mean(axis=0), label='cash-on-hand')\n # plt.plot(c.mean(axis=0), label='consumption')\n # plt.title(f'Average Cash-on-hand and Consumption over the life cycle\\n UPPER_BOUND_W = {UPPER_BOUND_W}')\n # plt.xlabel('Age')\n # plt.ylabel('Dollar')\n # plt.legend()\n # plt.grid()\n # plt.show()\n\n return c, inc\n\n\ndef cal_certainty_equi(prob, c):\n # discount factor\n YEARS = END_AGE - START_AGE + 1\n delta = np.ones((YEARS, 1)) * DELTA\n delta[0] = 1\n delta = np.cumprod(delta)\n\n util_c = np.apply_along_axis(utility, 1, c, GAMMA)\n simu_util = np.sum(np.multiply(util_c[:, :44], (delta * prob)[:44]), axis=1)\n\n if GAMMA == 1:\n c_ce = np.exp(np.mean(simu_util) / np.sum((delta * prob)[:44]))\n else:\n c_ce = ((1 - GAMMA) * np.mean(simu_util) / np.sum((delta * prob)[:44]))**(1 / (1-GAMMA))\n total_w_ce = prob[:44].sum() * c_ce # 42.7\n\n return c_ce, total_w_ce\n","sub_path":"cal_ce.py","file_name":"cal_ce.py","file_ext":"py","file_size_in_byte":4488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"321848685","text":"from bisect import bisect\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom adaboost.common import constants, convert_type\r\nfrom adaboost.common.check import check_type\r\n\r\n# Calculate per feature (column) mean value\r\n# Return vertical feature list as a horizontal list\r\ndef calculate_mean(dataset_features):\r\n if constants.OUTPUT_DETAIL is True:\r\n print(\" --init PCA-Dataset-Mean\")\r\n\r\n raw_feature_mean = dataset_features.mean().values\r\n return raw_feature_mean.transpose()\r\n\r\n\r\n# Return a normalized dataset\r\ndef normalize_dataset(dataset_features, feature_mean, sample_size):\r\n if constants.OUTPUT_DETAIL is True:\r\n print(\" --init PCA-Dataset-Normalized\")\r\n\r\n mean_matrix = np.repeat(feature_mean[None, :], sample_size, axis=0)\r\n return dataset_features.values - mean_matrix\r\n\r\n\r\n# Calculate covariance matrix\r\ndef calculate_covariance(normalized_features, feature_count):\r\n if constants.OUTPUT_DETAIL is True:\r\n print(\" --init PCA-Covariance-Matrix\")\r\n\r\n return (1 / (feature_count - 1)) * np.dot(normalized_features.T, normalized_features)\r\n\r\n\r\n# Calculate eigenvalues and eigenvectors, along with its sorted eigenvalues.\r\ndef calculate_eigen_decomposition(covariance_matrix):\r\n if constants.OUTPUT_DETAIL is True:\r\n print(\" --init -order=descending PCA-Eigenvalue\")\r\n print(\" --init -order=descending PCA-Eigenvectors\")\r\n\r\n eigenvalue, eigenvector = np.linalg.eig(covariance_matrix)\r\n sorted_eigen_index = np.argsort(-eigenvalue.real)\r\n return eigenvalue, eigenvector, sorted_eigen_index\r\n\r\n\r\n# Reduce feature dataset dimensions based on either:\r\n# - A cumulative variance percentage of the total dataset up to a user specified variance threshold\r\n# - Default space by taking first x amount of features until a variance of 1 is reached\r\n# - A user specified feature range\r\ndef reduce_dimensionality(reduction_size, sorted_eigen_index, eigenvalue):\r\n if constants.OUTPUT_DETAIL is True:\r\n print(\" --init PCA-Dimensionality-Reduction\")\r\n\r\n reduced_feature_size = None\r\n reduced_projection = None\r\n reduced_eigen_index = None\r\n\r\n if check_type.is_float(reduction_size) or check_type.is_str(reduction_size):\r\n cumulative_variance = np.cumsum(eigenvalue[sorted_eigen_index].real / np.sum(eigenvalue.real))\r\n\r\n # Reduce dimension based on a cumlative variance totaling a variance threshold\r\n if check_type.is_float(reduction_size):\r\n feature_range = (bisect(cumulative_variance, reduction_size)) + 1\r\n if feature_range <= 1:\r\n print(\"Feature minimum threshold unreached. (min=2)\\n\"\r\n \"Please try again within reduction range [%s <-> 1].\"\r\n % (cumulative_variance[0]))\r\n return None\r\n else:\r\n reduced_feature_size = feature_range\r\n\r\n # Reduce dimensions based on the first instance of variance totaling 1.00000000\r\n elif reduction_size == \"default\":\r\n cumulative_variance = ['%.8f' % feature for feature in cumulative_variance]\r\n reduced_feature_size = cumulative_variance.index('1.00000000')\r\n \r\n # Reduce dimensions based on a specified feature range\r\n elif check_type.is_int(reduction_size):\r\n reduced_feature_size = reduction_size\r\n\r\n reduced_eigen_index = sorted_eigen_index[:reduced_feature_size]\r\n return [reduced_feature_size, reduced_eigen_index]\r\n\r\n\r\n# Project sorted eigenvectors onto initial feature dataset\r\ndef data_projection(normalized_features, eigenvector, sorted_eigen_index):\r\n if constants.OUTPUT_DETAIL is True:\r\n print(\" --init PCA-Projection-Matrix\")\r\n\r\n return np.dot(normalized_features, eigenvector[:, sorted_eigen_index].real)\r\n","sub_path":"adaboost/learning/dimension_reduction/pca/methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":3603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"483364138","text":"print('-----------------------------')\nprint('PROGRAM HITUNG RATA-RATA')\nprint('-----------------------------')\n\njumlah = 0\ndata = 0\nwhile True : \n try :\n bil = int(input('Masukkan bilangan bulat: '))\n tanya = input('Lagi (y/n)? : ')\n jumlah += bil\n data += 1\n if (tanya == 'y') :\n True\n elif (tanya == 'n') :\n False\n break\n else :\n print('Input tidak valid')\n continue\n except ValueError:\n print('Bukan bilangan bulat')\nrata_rata = jumlah/data\nprint('Rata-ratanya adalah ', rata_rata)\n","sub_path":"latihan03.py","file_name":"latihan03.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"482825722","text":"\n\ndef eh_primo(número):\n\tx=1\n\twhile x<=número and x%2!=0:\n\t\tif número==0 or 1:\n\t\t\tprint(\"False\")\n\t\telif número==2:\n\t\t\tprint(\"True\")\n\t\telse:\n\t\t\tprint(\"True\")\n\t\tx = x+1","sub_path":"backup/user_035/ch31_2020_03_20_15_25_27_203455.py","file_name":"ch31_2020_03_20_15_25_27_203455.py","file_ext":"py","file_size_in_byte":170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"177845844","text":"#!/usr/bin/env python\nfrom sortutils import by_last_name\n\nnums = [800, 80, 1000, 32, 255, 400, 5, 5000]\n\nn1 = sorted(nums)\nprint(\"n1:\", n1, '\\n')\n\nn2 = sorted(nums, reverse=True)\nprint(\"n2:\", n2, '\\n')\n\n\nfruits = [\"pomegranate\", \"cherry\", \"apricot\", \"date\", \"Apple\",\n\"lemon\", \"Kiwi\", \"ORANGE\", \"lime\", \"Watermelon\", \"guava\",\n\"Papaya\", \"FIG\", \"pear\", \"banana\", \"Tamarind\", \"Persimmon\",\n\"elderberry\", \"peach\", \"BLUEberry\", \"lychee\", \"GRAPE\" ]\n\nf1 = sorted(fruits)\nprint(\"f1:\", f1, '\\n')\n\ndef ignore_case(fruit):\n return fruit.lower()\n\nf2 = sorted(fruits, key=ignore_case)\nprint(\"f2:\", f2, '\\n')\n\ndef wacky(e):\n return e[-1]\n\nf3 = sorted(fruits, key=wacky)\nprint(\"f3:\", f3, '\\n')\n\nf3r = sorted(fruits, key=wacky, reverse=True)\nprint(\"f3r:\", f3r, '\\n')\n\n\nf4 = sorted(fruits, key=len)\nprint(\"f4:\", f4, '\\n')\n\ndef custom1(element):\n return len(element), element.lower()\n\nf5 = sorted(fruits, key=custom1)\nprint(\"f5:\", f5, '\\n')\n\npeople = [\n ('Melinda', 'Gates', 'Gates Foundation'),\n ('Steve', 'Jobs', 'Apple'),\n ('Larry', 'Wall', 'Perl'),\n ('Paul', 'Allen', 'Microsoft'),\n ('Larry', 'Ellison', 'Oracle'),\n ('Bill', 'Gates', 'Microsoft'),\n ('Mark', 'Zuckerberg', 'Facebook'),\n ('Sergey','Brin', 'Google'),\n ('Larry', 'Page', 'Google'),\n ('Linus', 'Torvalds', 'Linux'),\n]\n\nfor first_name, last_name, _ in sorted(people):\n print(first_name, last_name)\nprint('-' * 60)\n\nfrom sortutils import by_last_name\n\nfor first_name, last_name, _ in sorted(people, key=by_last_name):\n print(first_name, last_name)\nprint('-' * 60)\n\nairports = {\n 'EWR': 'Newark',\n 'SFO': 'San Francisco',\n 'RDU': 'Raleigh-Durham',\n 'SJC': 'San Jose',\n 'ABQ': 'Albuquerque',\n 'OAK': 'Oakland',\n 'SAC': 'Sacramento',\n 'IAD': 'Dulles',\n}\n\ndef by_name(airport):\n return airport[1]\n\nprint(airports.items())\n\nfor name, value in sorted(airports.items(), key=by_name):\n print(name, value)\nprint()\n\nfor name, value in sorted(airports.items(), key=by_last_name):\n print(name, value)\nprint()\n\nfrom operator import itemgetter\nfor name, value in sorted(airports.items(), key=itemgetter(1)):\n print(name, value)\nprint()\n\ndef spam(e):\n return e[0]\n\nfor first_name, last_name, product in sorted(people, key=lambda e: e[2]):\n print(first_name, last_name, product)\nprint('-' * 60)\n","sub_path":"sorting_examples.py","file_name":"sorting_examples.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"569942493","text":"import sys\nimport os\nfrom os.path import join\nfrom pathlib import Path\n\nimport cv2 as cv\nimport numpy as np\nimport imutils\nimport operator\n\nfrom src.utils import im_utils, logger_utils\nfrom src.models.bbox import BBox\nfrom src.settings import app_cfg\nfrom src.settings import types\n\n\nclass ObjectDetectorCVDNN:\n\n def __init__(self):\n self.log = logger_utils.Logger.getLogger()\n\n \nclass ObjectDetectorCVDNN_VOC(ObjectDetectorCVDNN):\n\n dnn_size = (300,300)\n dnn_mean = 127.5\n dnn_scale = 0.007843\n classes = [\"background\", \"aeroplane\", \"bicycle\", \"bird\", \"boat\",\n \"bottle\", \"bus\", \"car\", \"cat\", \"chair\", \"cow\", \"diningtable\",\n \"dog\", \"horse\", \"motorbike\", \"person\", \"pottedplant\", \"sheep\",\n \"sofa\", \"train\", \"tvmonitor\"]\n\n def __init__(self):\n super().__init__()\n fp_prototxt = join(app_cfg.DIR_MODELS_CAFFE, 'MobileNetSSD_deploy.prototxt')\n fp_model = join(app_cfg.DIR_MODELS_CAFFE, 'MobileNetSSD_deploy.caffemodel')\n self.net = cv.dnn.readNetFromCaffe(fp_prototxt, fp_model)\n\n def detect_count(self, im, opt_conf=0.85):\n '''Counts number of objects in an image\n '''\n (h, w) = im.shape[:2]\n im_resized = cv.resize(im, self.dnn_size)\n blob = cv.dnn.blobFromImage(im_resized, self.dnn_scale, self.dnn_size, self.dnn_mean)\n self.net.setInput(blob)\n detections = self.net.forward()\n\n\n objects = []\n\n for i in np.arange(0, detections.shape[2]):\n conf = detections[0, 0, i, 2] \n if conf > opt_conf:\n idx = int(detections[0, 0, i, 1])\n label = self.classes[idx]\n objects.append(label)\n self.log.info(f'Found: {label}')\n #box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n #(startX, startY, endX, endY) = box.astype(\"int\")\n \n object_counts = {}\n for object_name in objects:\n if object_name not in object_counts.keys():\n object_counts[object_name] = 1\n else:\n object_counts[object_name] += 1\n\n return object_counts\n\n\n\nclass DetectorDLIBHOG:\n\n pyramids = 0\n conf_thresh = 0.85\n\n def __init__(self):\n import dlib\n self.log = logger_utils.Logger.getLogger()\n self.detector = dlib.get_frontal_face_detector()\n\n def detect_count(self, im, opt_conf=0.85, opt_pyramids=0):\n '''Count the number of faces in an image\n '''\n pyramids = self.pyramids if opt_pyramids is None else opt_pyramids\n dim = im.shape[:2][::-1]\n im = im_utils.bgr2rgb(im)\n hog_results = self.detector.run(im, pyramids)\n \n num_faces = 1\n if len(hog_results[0]) > 0:\n for rect, score, direction in zip(*hog_results):\n if score > self.conf_thresh:\n num_faces += 1\n self.log.debug(f'found face: {rect}')\n \n return {'faces': num_faces}\n","sub_path":"vframe/src/processors/detectors.py","file_name":"detectors.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"496746","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/tpDcc/libs/qt/core/contexts.py\n# Compiled at: 2020-05-13 19:31:15\n# Size of source mod 2**32: 491 bytes\n\"\"\"\nModule that contains contexts for Qt\n\"\"\"\nfrom __future__ import print_function, division, absolute_import\nimport sys, contextlib\nfrom Qt.QtWidgets import *\nimport tpDcc\n\n@contextlib.contextmanager\ndef application():\n app = QApplication.instance()\n if not app:\n app = QApplication(sys.argv)\n yield app\n app.exec_()\n else:\n yield app\n if tpDcc.is_standalone():\n app.exec_()","sub_path":"pycfiles/tpDcc_libs_qt-0.0.13-py3.6/contexts.cpython-36.py","file_name":"contexts.cpython-36.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"397503069","text":"import sys\nimport time\n\n\nif len(sys.argv) < 3:\n msg = '\\n'\n msg += \"Usage 1: %s $INPUT_ROOT_FILE\\n\" % sys.argv[0]\n msg += '\\n'\n sys.stderr.write(msg)\n sys.exit(1)\n\n \nfrom ROOT import larlite as fmwk\nfrom ROOT import gRandom\n\n\nmy_proc = fmwk.ana_processor()\n\n\n#for i in xrange(1,len(sys.argv)):\n #my_proc.add_input_file(sys.argv[i])\nfor i in xrange(2,len(sys.argv)):\n with open(sys.argv[i]) as file:\n for line in file:\n line = line.strip('\\n')\n my_proc.add_input_file(line)\n \nmy_proc.set_io_mode(fmwk.storage_manager.kBOTH)\nmy_proc.set_output_file(sys.argv[1])\nmy_proc.enable_filter()\n\nmy_proc.add_process(fmwk.ccnc(True))\nmy_proc.add_process(fmwk.delta_rad_filter())\n\nmy_proc.run()\n","sub_path":"mctruth/mac/delta_rad_filter.py","file_name":"delta_rad_filter.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"190472527","text":"# -*- coding: utf-8 -*-\n\n\"\"\"turingmarkov - Turing machine and markov algorithm emulator.\"\"\"\n\nfrom .markov import Algorithm\nimport sys, pytest, os\n\ndef main():\n \"\"\"Execute, when user call turingmarkov.\"\"\"\n if len(sys.argv) == 2 and sys.argv[1] == 'compile-markov':\n algo = Algorithm(sys.stdin.readlines())\n print(algo.compile())\n elif len(sys.argv) == 2 and sys.argv[1] == 'test':\n path = os.path.abspath(os.path.dirname(__file__))\n sys.argv[1] = path\n pytest.main()\n else:\n print('Usage: {name} command'.format(name=sys.argv[0]))\n print('Available commands:')\n print(' compile-markov : make python code from markov stdin->stdout')\n print(' test : run internal tests')\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"turingmarkov/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"99489659","text":"# Bruce A. Maxwell\n# CS 251 Project 5\n# Test code for single linear regression\n\nimport sys\nimport data\nimport analysis\n\n# Reads in a file and executes a single linear regression using the specified columns\ndef main(argv):\n\n if len(argv) < 4:\n printf(\"Usage: python %s \")\n exit(-1)\n\n # read some data\n data_obj = data.Data( argv[1] )\n ind_header = argv[2]\n ind_header2 = argv[3]\n dep_header = argv[4]\n\n # call the analysis function\n results = analysis.linear_regression( data_obj, ind_header, dep_header)\n\n # print out the results\n print(\"Model: y = %.4fx + %.4f\" % (results[0], results[1]) )\n print(\"R-value: %.3f\" % (results[2]) )\n print(\"P-value: %.3f\" % (results[3]) )\n print(\"Stderr: %.3f\" % (results[4]) )\n\n return\n\n\nif __name__ == \"__main__\":\n main(sys.argv)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"226707726","text":"# 54. Write a program to reverse any given integer number and also find their sum.\n# [Example : If number input 567, Output is 765 and sum = 18]\n\n\nnum = input(\"Enter any number. I will reverse it for you!\\n\")\nre = num[::-1]\nprint(\"Ta-da! >>>> \", re)\nre = list(re)\nsum = 0\nfor i in re:\n i = int(i)\n sum += i\nprint(\"\\nAnd their sum is {}.\".format(sum))\n\n\n","sub_path":"py_practice/Problem54.py","file_name":"Problem54.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"171888942","text":"from adotecg.models import Animal\nfrom adotecg.models import Activist\nfrom adotecg.models import Photo\nfrom django.contrib.auth.models import User\nfrom rest_framework import serializers\n\nclass PhotoSerializer(serializers.ModelSerializer):\n \n class Meta:\n model = Photo\n fields = ('height', 'imgur', 'link', 'size', 'type', 'width')\n \n def create(self, validated_data):\n return Photo.objects.create(**validated_data)\n \n def update(self, instance, validated_data):\n instance.height = validated_data.get('height', instance.height)\n instance.imgur = validated_data.get('imgur', instance.imgur)\n instance.link = validated_data.get('link', instance.link)\n instance.size = validated_data.get('size', instance.size)\n instance.type = validated_data.get('type', instance.type)\n instance.width = validated_data.get('width', instance.width)\n instance.save()\n return instance\n\nclass AnimalSerializer(serializers.ModelSerializer):\n user = serializers.ReadOnlyField(source='user.id')\n photos = PhotoSerializer(many=True)\n \n class Meta:\n model = Animal\n fields = ('id', 'name', 'about', 'adopted', 'created', 'type', 'genre', 'stage', 'size', 'user', 'photos')\n \n def create(self, validated_data):\n photos_data = validated_data.pop('photos')\n animal = Animal.objects.create(**validated_data)\n \n for photo_data in photos_data:\n Photo.objects.create(animal=animal, **photo_data)\n \n return animal\n\n def update(self, instance, validated_data):\n instance.name = validated_data.get('name', instance.name)\n instance.about = validated_data.get('about', instance.about)\n instance.adopted = validated_data.get('adopted', instance.adopted)\n instance.created = validated_data.get('created', instance.created)\n instance.type_ = validated_data.get('type', instance.type_)\n instance.genre = validated_data.get('genre', instance.genre)\n instance.stage = validated_data.get('stage', instance.stage)\n instance.size = validated_data.get('size', instance.size)\n instance.save()\n return instance\n\nclass ActivistSerializer(serializers.ModelSerializer):\n user = serializers.ReadOnlyField(source='user.id')\n username = serializers.ReadOnlyField(source='user.username')\n email = serializers.ReadOnlyField(source='user.email')\n \n class Meta:\n model = Activist\n fields = ('id', 'user', 'username', 'email', 'name', 'type', 'color', 'phone')\n \n def create(self, validated_data):\n return Activist.objects.create(**validated_data)\n \n def update(self, instance, validated_data):\n instance.name = validated_data.get('name', instance.name)\n instance.type = validated_data.get('type', instance.type)\n instance.color = validated_data.get('color', instance.color)\n instance.phone = validated_data.get('phone', instance.phone)\n instance.save()\n return instance\n \n","sub_path":"petserver/adotecg/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"226545266","text":"\"\"\"\n* user: VR439308\n* fname: Gaia\n* lname: Dalla Benetta\n* task: conta_multipli\n* score: 0.0\n* date: 2018-12-05 12:28:17.596108\n\"\"\"\n#!/usr/bin/env python3\n# Template per soluzione conta_multipli\n\nfrom __future__ import print_function\nimport sys\n\nif sys.version_info < (3, 0):\n input = raw_input\n\n# Devi modificare l'implementazione di questa funzione per fare \n# quanto richiesto dal testo dell'esercizio\ndef conta_multipli(a, b, c):\n n=0\n for i in range (n+1):\n if (i % a ==0): \n if (i % b !=0):\n n=n\n else:\n n=n+1\n\n\n return n\n \n# Lettura raw_input: non devi modificare il codice sotto questa riga\na, b, c= map(int,input().split())\nprint(conta_multipli(a, b, c))\n","sub_path":"2018.12.05.provetta/all-CMS-submissions-2018-12-05/2018-12-05.12:28:17.596108.VR439308.conta_multipli.py","file_name":"2018-12-05.12:28:17.596108.VR439308.conta_multipli.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"26871855","text":"from astropy.coordinates import SkyCoord\nimport matplotlib.pyplot as plt \nfrom astropy import units as u\nimport numpy as np\n\n#Galactic coordinates of the RRab candidates and BEAM extinction map\n\ndef HMS(hours, pos):\n minutes = np.abs ((hours-int(hours) ) * 60.) \n seconds = 0\n hours = int(hours)\n if hours == 0:\n if minutes == 0:\n if seconds == 0:\n return r\"$%d^\\circ%02d'$\" % (hours, minutes)\n return \"%d''\" % (seconds)\n return \"%d'%02d''\" % (minutes, seconds)\n return r\"$%d^\\circ%02d'$\" % (hours, minutes)\n\nRA, DEC = np.genfromtxt('lb.dat', usecols=(1,2), unpack=True)\nl_neg, b_neg, AKs_neg = np.genfromtxt('beamn.dat', usecols=(0,1,5), unpack=True)\nl_pos, b_pos, AKs_pos = np.genfromtxt('beamp.dat', usecols=(0,1,5), unpack=True)\n\nplt.figure(figsize=(16,5))\nplt.gca().xaxis.set_major_formatter(plt.FuncFormatter(HMS))\nplt.gca().yaxis.set_major_formatter(plt.FuncFormatter(HMS))\n\nRRL = SkyCoord(ra=RA, dec=DEC ,unit=(u.degree, u.degree), frame='icrs')\ngal = RRL.galactic\nl = np.array([])\nfor i,ell in enumerate(gal.l.deg):\n if ell > 10.:\n l = np.append(l, ell - 360.)\n else:\n l = np.append(l, ell)\nb = gal.b.deg\n\nneg = plt.hexbin(l_neg, b_neg, AKs_neg, gridsize=80, cmap=plt.get_cmap('gist_yarg'), vmax=0.20)\npos = plt.hexbin(l_pos, b_pos, AKs_pos, gridsize=80, cmap=plt.get_cmap('gist_yarg'), vmax=0.20)\nplt.scatter(l, b, marker='*', color='r', label='RRab', s=50.)\n\ncb = plt.colorbar(pos, pad=0.01, shrink=1.0)\ncb.set_label(r'$\\langle A_{K_s} \\rangle$', fontsize=19)\n\nplt.xlabel(r'$\\ell$', fontsize=19)\nplt.ylabel('$b$', fontsize=19)\n\nplt.xlim(10.1,-10.1)\nplt.ylim(-10.35,-7.9)\nplt.savefig('lb.pdf', format='pdf')\n#plt.show()","sub_path":"python/lb.py","file_name":"lb.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"135986809","text":"import RPi.GPIO as GPIO\nimport time\n\n# variabelen\ndelay = 0.01\ndelay_display = 1\n\nlst_0 = [0, 0, 1, 1, 1, 1, 1, 1]\nlst_1 = [0, 0, 0, 0, 0, 1, 1, 0]\nlst_2 = [0, 1, 0, 1, 1, 0, 1, 1]\nlst_3 = [0, 1, 0, 0, 1, 1, 1, 1]\nlst_4 = [0, 1, 1, 0, 0, 1, 1, 0]\nlst_5 = [0, 1, 1, 0, 1, 1, 0, 1]\nlst_6 = [0, 1, 1, 1, 1, 1, 0, 1]\nlst_7 = [0, 0, 0, 0, 0, 1, 1, 1]\nlst_8 = [0, 1, 1, 1, 1, 1, 1, 1]\nlst_9 = [0, 1, 1, 0, 1, 1, 1, 1]\nlst_lijsten = [lst_0, lst_1, lst_2, lst_3, lst_4, lst_5, lst_6, lst_7, lst_8, lst_9] # inputs\n\n# declaratie pinnen\nDS = 16 # data set\nST_CP = 20 # storage\nSH_CP = 21 # shift\nReset = 19 # dit zet het dislplay op 0\nregister = 26 # dit wordt zet het schuifregister aan of uit\n\n# init I/O\nGPIO.setmode(GPIO.BCM)\n\n# init I/O shift register\nGPIO.setup(DS, GPIO.OUT)\nGPIO.setup(ST_CP, GPIO.OUT)\nGPIO.setup(SH_CP, GPIO.OUT)\nGPIO.setup(Reset, GPIO.OUT)\nGPIO.setup(register, GPIO.OUT)\n\n# resetten\nGPIO.output(Reset, GPIO.HIGH)\n\n# schuifregister aanzetten\nGPIO.output(register, GPIO.HIGH)\n\n\n# byte naar segment schrijven\ndef write_to_segment(lst_x):\n for index in range(0, len(lst_x)):\n if lst_x[index] == 1:\n GPIO.output(DS, GPIO.HIGH)\n else:\n GPIO.output(DS, GPIO.LOW)\n\n time.sleep(delay)\n GPIO.output(SH_CP, GPIO.HIGH)\n time.sleep(delay)\n GPIO.output(DS, GPIO.LOW)\n GPIO.output(SH_CP, GPIO.LOW)\n time.sleep(delay)\n copy_to_storage_register()\n return\n\n\n# data in schuifregister in storage register opslaan\ndef copy_to_storage_register():\n\n # GPIO.output(ST_CP, GPIO.HIGH)\n # time.sleep(0.01)\n # GPIO.output(ST_CP, GPIO.LOW)\n return\n\n\n# schuifregister aan- of uitzetten\ndef register_on_off(status):\n if status == \"on\":\n # schuifregister aanzetten\n GPIO.output(register, GPIO.HIGH)\n\n # clear display en save de data\n GPIO.output(Reset, GPIO.LOW)\n copy_to_storage_register()\n\n else:\n # clear display en save de data\n GPIO.output(Reset, GPIO.LOW)\n copy_to_storage_register()\n\n # schuifregister uitzetten\n GPIO.output(register, GPIO.LOW)\n return\n\n\n# menu printen\ndef print_menu():\n print(\"1. Teller van 0 tot 9\\n2. Display getal van gebruiker\\n3. Schuifregister aanzetten en display clearen\\n4. Schuifregister uitzetten\\n\")\n return\n\n\nprint(\"Program is running!!!\\n\")\n\ntry:\n print_menu()\n while True:\n keuze = input(\"Maak een keuze: \")\n\n if keuze == \"1\":\n for teller in range(0, len(lst_lijsten)): # lst_lijsten aflopen\n write_to_segment(lst_lijsten[teller]) # inhoud van de variabele op plaats teller in lst_lijsten tonen op display\n print(\"Display: %d\" % teller)\n time.sleep(delay_display)\n\n # clear display en save de data\n GPIO.output(Reset, GPIO.LOW)\n copy_to_storage_register()\n\n elif keuze == \"2\":\n getal = input(\"Geef getal in: \")\n write_to_segment(lst_lijsten[int(getal)]) # inhoud van de variabele op plaats getal in lst_lijsten tonen op display\n print(\"Display: %s\\n\" % getal)\n time.sleep(delay_display)\n\n elif keuze == \"3\":\n register_on_off(\"on\") # schuifregister aanzetten\n print(\"Schuifregister staat aan en display is clear.\\n\")\n\n elif keuze == \"4\":\n register_on_off(\"off\") # schuifregister uitzetten\n print(\"Schuifregister staat uit.\\n\")\n\n print_menu() # menu printen\n\nexcept KeyboardInterrupt:\n # clear display en save de data\n GPIO.output(Reset, GPIO.LOW)\n copy_to_storage_register()\n time.sleep(0.01)\n\nprint(\"EINDE\")\nGPIO.cleanup()\n","sub_path":"Week5/schuifregister.py","file_name":"schuifregister.py","file_ext":"py","file_size_in_byte":3682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"374772115","text":"class Solution:\n def findAnagrams(self, s, p):\n if not s:\n return []\n\n res = []\n # length_of_p = len(p)\n # refer = sorted(p)\n # for i in range(len(s) - len(p) + 1):\n # sub_str = sorted(s[i:i+length_of_p])\n # if refer == sub_str:\n # res.append(i)\n #\n # return res\n chars = [0] * 26\n\n for ch in p:\n chars[ord(ch) - ord('a')] += 1\n\n left, right = 0, 0\n cnt = len(p)\n\n while right < len(s):\n\n if chars[ord(s[right]) - ord('a')] >= 1:\n cnt -= 1\n chars[ord(s[right]) - ord('a')] -= 1\n right += 1\n\n if right - left == len(p):\n if cnt == 0:\n res.append(left)\n\n if chars[ord(s[left]) - ord('a')] >= 0:\n cnt += 1\n chars[ord(s[left]) - ord('a')] += 1\n left += 1\n\n return res","sub_path":"Week_09/2-2 找到字符串中所有字母异位词.py","file_name":"2-2 找到字符串中所有字母异位词.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"177028344","text":"from rest_framework.serializers import ModelSerializer\n\nfrom ..models import Avaliation\nfrom appuser.api.serializers import UserSimpleSerializer\n\n\nclass AvaliationSimpleSerializer(ModelSerializer):\n class Meta:\n model = Avaliation\n fields = '__all__'\n\n\nclass AvaliationDetailSerializer(ModelSerializer):\n user = UserSimpleSerializer()\n\n class Meta:\n model = Avaliation\n fields = '__all__'\n","sub_path":"backend/appavaliation/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"604538650","text":"import random\n\nclass Queue():\n def __init__(self):\n self.queue = []\n def enqueue(self, value):\n self.queue.append(value)\n def dequeue(self):\n if self.size() > 0:\n return self.queue.pop(0)\n else:\n return None\n def size(self):\n return len(self.queue)\n\nclass User:\n def __init__(self, name):\n self.name = name\n\nclass SocialGraph:\n def __init__(self):\n self.last_id = 0\n self.users = {}\n self.friendships = {}\n\n def add_friendship(self, user_id, friend_id):\n \"\"\"\n Creates a bi-directional friendship\n \"\"\"\n if user_id == friend_id:\n print(\"WARNING: You cannot be friends with yourself\")\n elif friend_id in self.friendships[user_id] or user_id in self.friendships[friend_id]:\n print(\"WARNING: Friendship already exists\")\n else:\n self.friendships[user_id].add(friend_id)\n self.friendships[friend_id].add(user_id)\n\n def add_user(self, name):\n \"\"\"\n Create a new user with a sequential integer ID\n \"\"\"\n self.last_id += 1 # automatically increment the ID to assign the new user\n self.users[self.last_id] = User(name)\n self.friendships[self.last_id] = set()\n\n def populate_graph(self, num_users, avg_friendships):\n \"\"\"\n Takes a number of users and an average number of friendships\n as arguments\n\n Creates that number of users and a randomly distributed friendships\n between those users.\n\n The number of users must be greater than the average number of friendships.\n \"\"\"\n # Reset graph\n self.last_id = 0\n self.users = {}\n self.friendships = {}\n # !!!! IMPLEMENT ME\n \n # Add users\n for i in range(0, num_users):\n self.add_user(f\"User {i+1}\")\n\n # Create friendships\n possible_friendships = []\n\n for user_id in self.users:\n for friend_id in range(user_id+1, self.last_id+1):\n possible_friendships.append((user_id, friend_id))\n\n random.shuffle(possible_friendships)\n\n for i in range(num_users * avg_friendships // 2):\n friendship = possible_friendships[i]\n self.add_friendship(friendship[0], friendship[1])\n\n # * Hint 1: To create N random friendships, you could create a\n # list with all possible friendship combinations, shuffle the\n # list, then grab the first N elements from the list. You will\n # need to `import random` to get shuffle.\n # * Hint 2: `add_friendship(1, 2)` is the same as\n # `add_friendship(2, 1)`. You should avoid calling one after\n # the other since it will do nothing but print a warning. You\n # can avoid this by only creating friendships where user1 < user2.\n\n def get_all_social_paths(self, user_id):\n \"\"\"\n Takes a user's user_id as an argument\n\n Returns a dictionary containing every user in that user's\n extended network with the shortest friendship path between them.\n\n The key is the friend's ID and the value is the path.\n \"\"\"\n visited = {} # Note that this is a dictionary, not a set\n \n # !!!! IMPLEMENT ME\n\n # \"shortest\" keyword tells us we must go breadth first, hence Queue\n # \"extended network\" - traversal, connected component\n\n # planning\n # start at input UID, do breadth first traversal, return path to each friend\n\n # instantiate queue with user_id as first addition\n qq = Queue()\n qq.enqueue([user_id])\n\n # while queue is not empty, loop\n while qq.size() > 0:\n # assigns queue - last element to path\n path = qq.dequeue()\n # assigns uid at the end of path to var uid\n uid = path[-1]\n # checks if the current uid has been visited, if not, assigns path as value to uid key in visited dictionary\n if uid not in visited:\n visited[uid] = path\n # loops through edges (friendly neighbors) of current uid \n for friend in self.friendships[uid]:\n # checks if given edge has been visited by looking at dict keys\n if friend not in visited:\n # if it is not present in our dict, update the path with the edge and enqueue it\n u_path = path.copy()\n u_path.append(friend)\n qq.enqueue(u_path)\n return visited\n\n def get_all_social_paths_recursive(self, user_id, visited=None, path=None):\n if visited == None:\n visited = {}\n if path == None:\n path = [user_id]\n # base case\n\n uid = path[-1]\n path.pop()\n if uid not in visited:\n visited[uid] = path\n for friend in self.friendships[uid]:\n if friend not in visited:\n new_path = list(path)\n new_path.append(friend)\n self.get_all_social_paths(uid, visited, new_path)\n \n\n\n\nif __name__ == '__main__':\n sg = SocialGraph()\n sg.populate_graph(10, 2)\n print(sg.friendships)\n connections = sg.get_all_social_paths(1)\n print(connections)\n","sub_path":"projects/social/social.py","file_name":"social.py","file_ext":"py","file_size_in_byte":5336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"32426098","text":"from Node import *\r\nimport math\r\n\r\nclass Network:\r\n\r\n\tdef __init__(self, name, choiceNodes=None, edges=None):\r\n\t\tself.name = name\r\n\t\tself.decisionNode = DecisionNode(5)\r\n\t\tself.utilityNode = UtilityNode(5)\r\n\r\n\t\tself.choices = choiceNodes\r\n\t\tif self.choices is None:\r\n\t\t\tself.choices = []\r\n\r\n\t\tself.edges = edges\r\n\t\tif self.edges is None:\r\n\t\t\tself.edges = {}\r\n\t\tself.edges['decision'] = ['utility']\r\n\r\n\tdef __str__(self):\r\n\t\t\"\"\"How this object is displayed when printed\"\"\"\r\n\t\treturn self.name + \" = \" \\\r\n\t\t\t+ \"{ clown: \" + str(self.getNode('clown').getValue()) \\\r\n\t\t\t+ \", magician: \" + str(self.getNode('magician').getValue()) \\\r\n\t\t\t+ \", acrobat: \" + str(self.getNode('acrobat').getValue()) + \" }\"\r\n\tdef __repr__(self):\r\n\t\treturn self.name\r\n\r\n\tdef addChoice(self, choiceNode):\r\n\t\t\"\"\"Adds a given choice node to this network\"\"\"\r\n\t\tself.choices = self.choices[:] + [choiceNode]\r\n\r\n\tdef addChoices(self, choicesToAdd):\r\n\t\t\"\"\"Adds a list of choice nodes to this network.\"\"\"\r\n\t\t[self.addChoice(choiceNode) for choiceNode in choicesToAdd]\r\n\r\n\tdef addConnection(self, node1, node2):\r\n\t\t\"\"\"Adds an edge from node1 to node2 in this Network.\r\n\r\n\t\tReturns:\r\n\t\t\tFalse if the nodes are equal or either do not exist, else True.\r\n\t\t\"\"\"\r\n\t\tif node1 == node2:\r\n\t\t\treturn False\r\n\t\tnode1Exists = False\r\n\t\tnode2Exists = False\r\n\t\tfor node in self.choices:\r\n\t\t\tif node.name == node1:\r\n\t\t\t\tnode1Exists = True\r\n\t\t\tif node.name == node2:\r\n\t\t\t\tnode2Exists = True\r\n\t\tif node1Exists and node2Exists:\r\n\t\t\t# add connection to edges\r\n\t\t\tif self.edges[node1] is None:\r\n\t\t\t\tself.edges[node1] = [node2]\r\n\t\t\telse:\r\n\t\t\t\tself.edges[node1] = self.edges[node1][:] + [node2]\r\n\t\t\treturn True\r\n\r\n\t\t# these nodes do not exist\r\n\t\treturn False\r\n\r\n\tdef getChoiceProbabilities(self):\r\n\t\t\"\"\"Finds all possible choices that need to be considered.\r\n\r\n\t\tThis is a helper procedure for calculating utility by providing all\r\n\t\tthe choices required to be taken into consideration. Each value in\r\n\t\tthe output comes with a probability indicating how sure we are that\r\n\t\tchoice is made. So if person A could be at either positions 1 or 2,\r\n\t\teach has a probability of 0.5 since there are only 2 unknowns.\r\n\r\n\t\tTODO: change how probability is calculated. If A can be at positions\r\n\t\t{1, 2, 3} and B can be at positions {3, 4, 5}, the probability can't\r\n\t\tbe calculated based on number of positions we know for sure, but the\r\n\t\tnumber of possible positions B can be given what positions we know.\r\n\r\n\t\tReturns:\r\n\t\t\tArray of objects providing 3 values mapped to keys:\r\n\t\t\t\t'likes': if this node is liked,\r\n\t\t\t\t'position': position corresponding to this choice,\r\n\t\t\t\t'probability': how sure we are this node made this choice.\r\n\t\t\"\"\"\r\n\t\toutput = []\r\n\t\ttakenPositions = []\r\n\t\tfor key, edges in self.edges.items():\r\n\t\t\tif 'decision' in edges:\r\n\t\t\t\tnode = self.getNode(key)\r\n\t\t\t\tif isinstance(node, ChoiceNode):\r\n\t\t\t\t\tposition = node.getValue()\r\n\t\t\t\t\toutput.append({\r\n\t\t\t\t\t\t'likes': node.likes,\r\n\t\t\t\t\t\t'position': position,\r\n\t\t\t\t\t\t'probability': 1.0\r\n\t\t\t\t\t})\r\n\t\t\t\t\ttakenPositions.append(position)\r\n\r\n\t\tnumTakenPositions = len(takenPositions)\r\n\t\tfor choiceNode in self.choices:\r\n\t\t\tedges = []\r\n\t\t\tif choiceNode.name in self.edges:\r\n\t\t\t\tedges = self.edges[choiceNode.name]\r\n\r\n\t\t\tif 'decision' not in edges:\r\n\t\t\t\tpossibleValues = choiceNode.possibleValues()\r\n\t\t\t\t# save length so it doesn't have to be calculated each iteration\r\n\t\t\t\tnumPossibleValues = len(possibleValues)\r\n\t\t\t\tfor position in possibleValues:\r\n\t\t\t\t\tif position not in takenPositions:\r\n\t\t\t\t\t\toutput.append({\r\n\t\t\t\t\t\t\t'likes': choiceNode.likes,\r\n\t\t\t\t\t\t\t'position': position,\r\n\t\t\t\t\t\t\t'probability': 1.0 / (numPossibleValues\r\n\t\t\t\t\t\t\t\t- numTakenPositions)\r\n\t\t\t\t\t\t})\r\n\t\treturn output\r\n\r\n\tdef calculateUtility(self, section, stagePostion, likesStage, free_param):\r\n\t\t\"\"\"Computes the utility of a given decision.\r\n\r\n\t\tUtility here is defined as the city block distance from one section\r\n\t\tto the stage. If the stage is liked, it is the inverse of the\r\n\t\tcity block distance.\r\n\r\n\t\tReturns:\r\n\t\t\tFloat valued utility of the given decision.\r\n\t\t\"\"\"\r\n\t\t# utility for disliking this stage\r\n\t\t# utilityOutput = math.sqrt(((section - stagePostion) ** 2) + 1.0)\r\n\t\t# print(\"Difference = {}\".format(section - stagePostion))\r\n\t\tutilityOutput = math.exp(-1 * abs(free_param * (section - stagePostion)))\r\n\t\t# print(\"Utility = {}\\n\".format(utilityOutput))\r\n\t\tif likesStage == 0:\r\n\t\t\t# we are indifferent about this stage\r\n\t\t\treturn 0\r\n\t\tif likesStage == 1:\r\n\t\t\t# we like this stage\r\n\t\t\treturn utilityOutput\r\n\t\treturn 1 - utilityOutput\r\n\r\n\tdef getAllUtilities(self, free_param):\r\n\t\t\"\"\"Computes the all utilities for all possible decisions.\r\n\r\n\t\tFirst identify what choices the decision knows about. Then for each\r\n\t\tone of these choices, sum together the utilities for each possible\r\n\t\tdecision.\r\n\r\n\t\tSince utility is additive, we are always summing them together.\r\n\r\n\t\tReturns:\r\n\t\t\tArray of float valued sums of utility where each index represents\r\n\t\t\tthe total sum for the decision at that index.\r\n\t\t\"\"\"\r\n\t\tutilities = [0.0] * len(self.decisionNode.possibleValues())\r\n\t\tfor choice in self.getChoiceProbabilities():\r\n\t\t\tif choice['likes'] != 0:\r\n\t\t\t\tfor value in self.decisionNode.possibleValues():\r\n\t\t\t\t\tutilities[value - 1] += choice['probability'] \\\r\n\t\t\t\t\t\t* self.calculateUtility(value, choice['position'],\r\n\t\t\t\t\t\t\tchoice['likes'], free_param)\r\n\t\treturn utilities\r\n\r\n\tdef probabilityOfDecision(self, decision, free_param):\r\n\t\t\"\"\"Computes the probability of a decision given this network.\r\n\r\n\t\tP(decision | N) = utility(decision) / sum(utilities for all decisions)\r\n\r\n\t\tReturns:\r\n\t\t\tFloat valued probability of this decision being made for this\r\n\t\t\tnetwork.\r\n\t\t\"\"\"\r\n\t\tallUtilities = self.getAllUtilities(free_param)\r\n\t\tutilitySum = float(sum(allUtilities))\r\n\t\tif utilitySum == 0.0:\r\n\t\t\treturn 0.0\r\n\t\treturn allUtilities[decision - 1] / float(sum(allUtilities))\r\n\r\n\r\n\tdef complexity(self):\r\n\t\t\"\"\"Computes the complexity of this network.\r\n\r\n\t\tComplexity for decision networks can be computed by their\r\n\t\tminimum description length (MDL).\r\n\r\n\t\tComplexity(N) = sum(x_i * q_i) for all nodes i in network N\r\n\t\twhere x_i is the number of values that node i can take on\r\n\t\tand q_i is the number of values that the parents of i can take on.\r\n\r\n\t\tReturns:\r\n\t\t\tInteger values complexity of this network.\r\n\t\t\"\"\"\r\n\t\toutput = 0\r\n\t\tfor node in self.choices[:] + [self.decisionNode, self.utilityNode]:\r\n\t\t\tparentValues = 0\r\n\t\t\tfor key, edges in self.edges.items():\r\n\t\t\t\tif node.name in edges:\r\n\t\t\t\t\tparentNode = self.getNode(key)\r\n\t\t\t\t\tif parentValues < 1:\r\n\t\t\t\t\t\tparentValues = len(parentNode.possibleValues())\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tparentValues *= len(parentNode.possibleValues())\r\n\t\t\toutput += len(node.possibleValues()) * parentValues\r\n\t\treturn output\r\n\r\n\tdef simplicity(self):\r\n\t\t\"\"\"Computes the simplicity of this network.\r\n\t\t\r\n\t\tSimplicity can be defined as the inverse of the complexity.\r\n\r\n\t\tReturns:\r\n\t\t\tFloat valued simplicity of this network.\r\n\t\t\"\"\"\r\n\t\treturn 1.0 / self.complexity()\r\n\r\n\tdef getNode(self, name):\r\n\t\t\"\"\"Fetches the node object of a given name.\r\n\r\n\t\tReturns:\r\n\t\t\tIf this network contains a node with the given name, the node\r\n\t\t\tobject itself, else None.\r\n\t\t\"\"\"\r\n\t\tif name == 'utility':\r\n\t\t\treturn self.utilityNode\r\n\t\tif name == 'decision':\r\n\t\t\treturn self.decisionNode\r\n\t\tfor choice in self.choices:\r\n\t\t\tif choice.name == name:\r\n\t\t\t\treturn choice\r\n\t\treturn None\r\n\r\n\tdef probabilityOfThisNetworkGivenDecision(self, decision, free_param):\r\n\t\t\"\"\"Computes the probability of this network given a decision.\r\n\r\n\t\tP(N | decision) ~ P(decision | N) * P(N)\r\n\r\n\t\tThe greater probability, the greater chance this network explains\r\n\t\twhy a person made the given decision.\r\n\r\n\t\tReturns:\r\n\t\t\tFloat valued probability of this network being the network\r\n\t\t\tused for a given decision.\r\n\t\t\"\"\"\r\n\t\t# use this to care about prior probability\r\n\t\t#return self.probabilityOfDecision(decision, free_param) * self.simplicity()\r\n\t\t\r\n\t\t# use this to not care about prior probability\r\n\t\t#return self.probabilityOfDecision(decision, free_param)\r\n\t\t\r\n\t\t# use this to only care about prior probability\r\n\t\t# (For Experiment 2B, we only care about computing simplicity)\r\n\t\treturn self.simplicity()","sub_path":"Experiment 4/Model/Network.py","file_name":"Network.py","file_ext":"py","file_size_in_byte":8149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"160904409","text":"'''\nGrading PROGRAM\n---------------\nCreate a program that asks the user for their semester grade, final exam grade, \nand final exam worth and then calculates the overall final grade. \nAsk your instructor if you don't know how to calculate weighted averages.\nYou don't have to print out the letter grade. We will do that in the next chapter.\n\nTest with the following:\n\nSem Grade: 86 Final Exam: 52 Exam worth: 15% Overall: 80.9\nSem Grade: 95 Final Exam: 32 Exam worth: 10% Overall: 88.7\nSem Grade: 72 Final Exam: 100 Exam worth: 20% Overall: 77.6\n'''\n\nprint(\"Hi, I hope you are not too worried about your overall grades!\\nHere's something to help, though.\")\nsem_grade=int(input(\"What is your semester grade? \"))\nfin_grade=int(input(\"What is your final exam grade? \"))\nfin_worth=float(input(\"What is your final exam worth written as a decimal? \"))\nsem_worth=1-fin_worth\novr_grade=(sem_grade*sem_worth)+(fin_grade*fin_worth)\nprint(\"Your overall grade is\",ovr_grade)","sub_path":"3.3_Grading.py","file_name":"3.3_Grading.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"323244201","text":"\n\ndef map_obj_to_xml_rpc(self):\n self._log_file_meta.update([('files', {\n 'xpath': 'syslog/files',\n 'tag': True,\n 'operation': 'edit',\n }), ('file', {\n 'xpath': 'syslog/files/file',\n 'tag': True,\n 'operation': 'edit',\n 'attrib': 'operation',\n }), ('a:name', {\n 'xpath': 'syslog/files/file/file-name',\n 'operation': 'edit',\n }), ('file-attrib', {\n 'xpath': 'syslog/files/file/file-log-attributes',\n 'tag': True,\n 'operation': 'edit',\n }), ('a:size', {\n 'xpath': 'syslog/files/file/file-log-attributes/max-file-size',\n 'operation': 'edit',\n }), ('a:level', {\n 'xpath': 'syslog/files/file/file-log-attributes/severity',\n 'operation': 'edit',\n })])\n self._log_host_meta.update([('host-server', {\n 'xpath': 'syslog/host-server',\n 'tag': True,\n 'operation': 'edit',\n }), ('vrfs', {\n 'xpath': 'syslog/host-server/vrfs',\n 'tag': True,\n 'operation': 'edit',\n }), ('vrf', {\n 'xpath': 'syslog/host-server/vrfs/vrf',\n 'tag': True,\n 'operation': 'edit',\n }), ('a:vrf', {\n 'xpath': 'syslog/host-server/vrfs/vrf/vrf-name',\n 'operation': 'edit',\n }), ('ipv4s', {\n 'xpath': 'syslog/host-server/vrfs/vrf/ipv4s',\n 'tag': True,\n 'operation': 'edit',\n }), ('ipv4', {\n 'xpath': 'syslog/host-server/vrfs/vrf/ipv4s/ipv4',\n 'tag': True,\n 'operation': 'edit',\n 'attrib': 'operation',\n }), ('a:name', {\n 'xpath': 'syslog/host-server/vrfs/vrf/ipv4s/ipv4/address',\n 'operation': 'edit',\n }), ('ipv4-sev', {\n 'xpath': 'syslog/host-server/vrfs/vrf/ipv4s/ipv4/ipv4-severity-port',\n 'tag': True,\n 'operation': 'edit',\n }), ('a:level', {\n 'xpath': 'syslog/host-server/vrfs/vrf/ipv4s/ipv4/ipv4-severity-port/severity',\n 'operation': 'edit',\n })])\n self._log_console_meta.update([('a:enable-console', {\n 'xpath': 'syslog/enable-console-logging',\n 'operation': 'edit',\n 'attrib': 'operation',\n }), ('console', {\n 'xpath': 'syslog/console-logging',\n 'tag': True,\n 'operation': 'edit',\n 'attrib': 'operation',\n }), ('a:console-level', {\n 'xpath': 'syslog/console-logging/logging-level',\n 'operation': 'edit',\n })])\n self._log_monitor_meta.update([('monitor', {\n 'xpath': 'syslog/monitor-logging',\n 'tag': True,\n 'operation': 'edit',\n 'attrib': 'operation',\n }), ('a:monitor-level', {\n 'xpath': 'syslog/monitor-logging/logging-level',\n 'operation': 'edit',\n })])\n self._log_buffered_size_meta.update([('buffered', {\n 'xpath': 'syslog/buffered-logging',\n 'tag': True,\n 'operation': 'edit',\n 'attrib': 'operation',\n }), ('a:size', {\n 'xpath': 'syslog/buffered-logging/buffer-size',\n 'operation': 'edit',\n })])\n self._log_buffered_level_meta.update([('buffered', {\n 'xpath': 'syslog/buffered-logging',\n 'tag': True,\n 'operation': 'edit',\n 'attrib': 'operation',\n }), ('a:level', {\n 'xpath': 'syslog/buffered-logging/logging-level',\n 'operation': 'edit',\n })])\n self._log_facility_meta.update([('facility', {\n 'xpath': 'syslog/logging-facilities',\n 'tag': True,\n 'operation': 'edit',\n 'attrib': 'operation',\n }), ('a:facility', {\n 'xpath': 'syslog/logging-facilities/facility-level',\n 'operation': 'edit',\n })])\n self._log_prefix_meta.update([('a:hostnameprefix', {\n 'xpath': 'syslog/host-name-prefix',\n 'operation': 'edit',\n 'attrib': 'operation',\n })])\n state = self._module.params['state']\n _get_filter = build_xml('syslog', opcode='filter')\n running = get_config(self._module, source='running', config_filter=_get_filter)\n file_ele = etree_findall(running, 'file')\n file_list = list()\n if len(file_ele):\n for file in file_ele:\n file_name = etree_find(file, 'file-name')\n file_list.append((file_name.text if (file_name is not None) else None))\n vrf_ele = etree_findall(running, 'vrf')\n host_list = list()\n for vrf in vrf_ele:\n host_ele = etree_findall(vrf, 'ipv4')\n for host in host_ele:\n host_name = etree_find(host, 'address')\n host_list.append((host_name.text if (host_name is not None) else None))\n console_ele = etree_find(running, 'console-logging')\n console_level = (etree_find(console_ele, 'logging-level') if (console_ele is not None) else None)\n have_console = (console_level.text if (console_level is not None) else None)\n monitor_ele = etree_find(running, 'monitor-logging')\n monitor_level = (etree_find(monitor_ele, 'logging-level') if (monitor_ele is not None) else None)\n have_monitor = (monitor_level.text if (monitor_level is not None) else None)\n buffered_ele = etree_find(running, 'buffered-logging')\n buffered_size = (etree_find(buffered_ele, 'buffer-size') if (buffered_ele is not None) else None)\n have_buffered = (buffered_size.text if (buffered_size is not None) else None)\n facility_ele = etree_find(running, 'logging-facilities')\n facility_level = (etree_find(facility_ele, 'facility-level') if (facility_ele is not None) else None)\n have_facility = (facility_level.text if (facility_level is not None) else None)\n prefix_ele = etree_find(running, 'host-name-prefix')\n have_prefix = (prefix_ele.text if (prefix_ele is not None) else None)\n file_params = list()\n host_params = list()\n console_params = dict()\n monitor_params = dict()\n buffered_params = dict()\n facility_params = dict()\n prefix_params = dict()\n opcode = None\n if (state == 'absent'):\n opcode = 'delete'\n for item in self._want:\n if ((item['dest'] == 'file') and (item['name'] in file_list)):\n item['level'] = severity_level[item['level']]\n file_params.append(item)\n elif ((item['dest'] == 'host') and (item['name'] in host_list)):\n item['level'] = severity_level[item['level']]\n host_params.append(item)\n elif ((item['dest'] == 'console') and have_console):\n console_params.update({\n 'console-level': item['level'],\n })\n elif ((item['dest'] == 'monitor') and have_monitor):\n monitor_params.update({\n 'monitor-level': item['level'],\n })\n elif ((item['dest'] == 'buffered') and have_buffered):\n buffered_params['size'] = (str(item['size']) if item['size'] else None)\n buffered_params['level'] = (item['level'] if item['level'] else None)\n elif ((item['dest'] is None) and (item['hostnameprefix'] is None) and (item['facility'] is not None) and have_facility):\n facility_params.update({\n 'facility': item['facility'],\n })\n elif ((item['dest'] is None) and (item['hostnameprefix'] is not None) and have_prefix):\n prefix_params.update({\n 'hostnameprefix': item['hostnameprefix'],\n })\n elif (state == 'present'):\n opcode = 'merge'\n for item in self._want:\n if (item['dest'] == 'file'):\n item['level'] = severity_level[item['level']]\n file_params.append(item)\n elif (item['dest'] == 'host'):\n item['level'] = severity_level[item['level']]\n host_params.append(item)\n elif (item['dest'] == 'console'):\n console_params.update({\n 'console-level': item['level'],\n })\n elif (item['dest'] == 'monitor'):\n monitor_params.update({\n 'monitor-level': item['level'],\n })\n elif (item['dest'] == 'buffered'):\n buffered_params['size'] = (str(item['size']) if item['size'] else None)\n buffered_params['level'] = (item['level'] if item['level'] else None)\n elif ((item['dest'] is None) and (item['hostnameprefix'] is None) and (item['facility'] is not None)):\n facility_params.update({\n 'facility': item['facility'],\n })\n elif ((item['dest'] is None) and (item['hostnameprefix'] is not None)):\n prefix_params.update({\n 'hostnameprefix': item['hostnameprefix'],\n })\n self._result['xml'] = []\n _edit_filter_list = list()\n if opcode:\n if len(file_params):\n _edit_filter_list.append(build_xml('syslog', xmap=self._log_file_meta, params=file_params, opcode=opcode))\n if len(host_params):\n _edit_filter_list.append(build_xml('syslog', xmap=self._log_host_meta, params=host_params, opcode=opcode))\n if len(console_params):\n _edit_filter_list.append(build_xml('syslog', xmap=self._log_console_meta, params=console_params, opcode=opcode))\n if len(monitor_params):\n _edit_filter_list.append(build_xml('syslog', xmap=self._log_monitor_meta, params=monitor_params, opcode=opcode))\n if len(buffered_params):\n _edit_filter_list.append(build_xml('syslog', xmap=self._log_buffered_size_meta, params=buffered_params, opcode=opcode))\n _edit_filter_list.append(build_xml('syslog', xmap=self._log_buffered_level_meta, params=buffered_params, opcode=opcode))\n if len(facility_params):\n _edit_filter_list.append(build_xml('syslog', xmap=self._log_facility_meta, params=facility_params, opcode=opcode))\n if len(prefix_params):\n _edit_filter_list.append(build_xml('syslog', xmap=self._log_prefix_meta, params=prefix_params, opcode=opcode))\n diff = None\n if len(_edit_filter_list):\n commit = (not self._module.check_mode)\n diff = load_config(self._module, _edit_filter_list, commit=commit, running=running, nc_get_filter=_get_filter)\n if diff:\n if self._module._diff:\n self._result['diff'] = dict(prepared=diff)\n self._result['xml'] = _edit_filter_list\n self._result['changed'] = True\n","sub_path":"Data Set/bug-fixing-2/7c704526f3429244ac8d6542d64cd0bc7c78bda0--fix.py","file_name":"7c704526f3429244ac8d6542d64cd0bc7c78bda0--fix.py","file_ext":"py","file_size_in_byte":10385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"27375964","text":"import click\nimport os\nfrom typing import Optional\nfrom types import SimpleNamespace\n\nfrom uceasy import __version__\nfrom uceasy.facade import AssemblyFacade, QualityControlFacade, UCEPhylogenomicsFacade\n\n\nTHREADS = os.cpu_count()\n\n\n@click.group(context_settings={\"help_option_names\": [\"-h\", \"--help\"]})\n@click.version_option(version=__version__)\ndef cli():\n \"\"\"A unified CLI for the PHYLUCE software package.\"\"\"\n pass\n\n\n@cli.command()\n@click.argument(\"raw-fastq\", required=True)\n@click.argument(\"csv-file\", required=True)\n@click.option(\n \"--threads\",\n \"-j\",\n type=int,\n default=THREADS,\n help=\"Number of computer threads to use. (default: all available)\",\n)\n@click.option(\n \"--min-len\",\n \"-m\",\n type=int,\n default=40,\n help=\"The minimum length of reads to keep. (default: 40)\",\n)\n@click.option(\"--log-dir\", \"-l\", type=str, default=os.getcwd(), help=\"Directory to save logs.\")\n@click.option(\n \"--output\", \"-o\", default=\"clean-fastq\", help=\"Output directory. (default: clean-fastq)\"\n)\n@click.option(\"--r1-pattern\", \"--r1\", help=\"An optional regex pattern to find R1 reads.\")\n@click.option(\"--r2-pattern\", \"--r2\", help=\"An optional regex pattern to find R2 reads.\")\n@click.option(\n \"--phred64\", \"-p\", is_flag=True, help=\"Use phred64 for fastq encoding. (default: phred33)\"\n)\n@click.option(\"--single-end\", \"--se\", is_flag=True, help=\"Single-end reads.\")\n@click.option(\"--single-index\", \"--si\", is_flag=True, help=\"Single-indexed for barcodes.\")\n@click.option(\n \"--no-merge\", \"-n\", is_flag=True, help=\"When trimming PE reads, do not merge singleton files.\"\n)\n@click.option(\"--verbose\", \"-v\", is_flag=True, help=\"Show output from PHYLUCE.\")\ndef quality_control(\n raw_fastq: str,\n csv_file: str,\n threads: int,\n single_end: bool,\n single_index: bool,\n log_dir: str,\n r1_pattern: Optional[str],\n r2_pattern: Optional[str],\n phred64: bool,\n output: str,\n min_len: int,\n no_merge: bool,\n verbose: bool,\n) -> None:\n \"\"\"Run quality control with illumiprocessor.\"\"\"\n context = SimpleNamespace(\n raw_fastq=raw_fastq,\n csv_file=csv_file,\n threads=threads,\n single_end=single_end,\n single_index=single_index,\n log_dir=log_dir,\n r1_pattern=r1_pattern,\n r2_pattern=r2_pattern,\n phred64=phred64,\n output=output,\n min_len=min_len,\n no_merge=no_merge,\n capture_output=not verbose,\n )\n facade = QualityControlFacade(context)\n facade.run()\n\n\n@cli.command()\n@click.argument(\"clean-fastq\", required=True)\n@click.option(\n \"--assembler\",\n \"-a\",\n type=str,\n default=\"spades\",\n help=\"Assembler program to use. (default: spades)\",\n)\n@click.option(\n \"--config\", \"-c\", type=str, help=\"Custom configuration file containing the reads to assemble.\"\n)\n@click.option(\"--kmer\", \"-k\", type=str, help=\"The kmer value to use.\")\n@click.option(\"--log-dir\", \"-l\", type=str, default=os.getcwd(), help=\"Directory to save logs.\")\n@click.option(\n \"--threads\",\n \"-j\",\n type=int,\n default=THREADS,\n help=\"Number of computer threads to use. (default: all available)\",\n)\n@click.option(\n \"--output\", \"-o\", type=str, default=\"assemblies\", help=\"Output directory. (default: assemblies)\"\n)\n@click.option(\"--no-clean\", \"-n\", is_flag=True, help=\"Do not clean intermediate files.\")\n@click.option(\n \"--subfolder\",\n \"-s\",\n type=str,\n help=\"A subdirectory, below the level of the group, containing the reads.\",\n)\n@click.option(\"--verbose\", \"-v\", is_flag=True, help=\"Show output from PHYLUCE.\")\ndef assembly(\n assembler: str,\n clean_fastq: str,\n log_dir: str,\n threads: int,\n output: str,\n config: Optional[str],\n kmer: Optional[str],\n no_clean: bool,\n subfolder: Optional[str],\n verbose: bool,\n) -> None:\n \"\"\"Run assembly with spades or trinity.\"\"\"\n context = SimpleNamespace(\n assembler=assembler,\n clean_fastq=clean_fastq,\n log_dir=log_dir,\n threads=threads,\n output=output,\n config=config,\n kmer=kmer,\n no_clean=no_clean,\n subfolder=subfolder,\n capture_output=not verbose,\n )\n facade = AssemblyFacade(context)\n facade.run()\n\n\n@cli.command()\n@click.argument(\"contigs\", required=True)\n@click.argument(\"probes\", required=True)\n@click.option(\"--aligner\", \"-a\", type=str, default=\"mafft\", help=\"Aligner program to use.\")\n@click.option(\"--charsets\", \"-c\", is_flag=True, help=\"Use charsets.\")\n@click.option(\n \"--threads\",\n \"-j\",\n type=int,\n default=THREADS,\n help=\"Number of computer threads to use. (default: all available)\",\n)\n@click.option(\n \"--output\",\n \"-o\",\n type=str,\n default=\"phylogenomics\",\n help=\"Output directory. (default: phylogenomics)\",\n)\n@click.option(\"--incomplete-matrix\", is_flag=True, help=\"Generate an incomplete matrix of data.\")\n@click.option(\"--internal-trimming\", \"-i\", is_flag=True, help=\"Internally trim the alignments.\")\n@click.option(\"--log-dir\", \"-l\", type=str, default=os.getcwd(), help=\"Directory to save logs.\")\n@click.option(\n \"--regex\", \"-r\", help=\"A regular expression to apply to the probe names for replacement.\"\n)\n@click.option(\n \"--percent\", \"-p\", default=0.75, help=\"The percent of taxa to require (default: 0.75)\"\n)\n@click.option(\"--verbose\", \"-v\", is_flag=True, help=\"Show output from PHYLUCE.\")\ndef phylogenomics(\n aligner: str,\n charsets: bool,\n contigs: str,\n incomplete_matrix: bool,\n internal_trimming: bool,\n output: str,\n log_dir: str,\n probes: str,\n percent: float,\n threads: int,\n regex: Optional[str],\n verbose: bool,\n):\n \"\"\"The phylogenomics pipeline discribed by PHYLUCE.\"\"\"\n context = SimpleNamespace(\n aligner=aligner,\n charsets=charsets,\n contigs=contigs,\n incomplete_matrix=incomplete_matrix,\n internal_trimming=internal_trimming,\n output=output,\n log_dir=log_dir,\n probes=probes,\n percent=percent,\n threads=threads,\n regex=regex,\n capture_output=not verbose,\n )\n facade = UCEPhylogenomicsFacade(context)\n facade.run()\n","sub_path":"src/uceasy/console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":6138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"234230281","text":"from dynaconf import settings\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import MetaData\n\n\ndef reset_db(db_url):\n engine = create_engine(db_url)\n meta = MetaData()\n meta.reflect(bind=engine)\n meta.drop_all(bind=engine)\n\n\nif __name__ == \"__main__\":\n assert settings.DB1, \"DB1 url is not configured\"\n reset_db(settings.DB1)\n","sub_path":"scripts/reset_db1.py","file_name":"reset_db1.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"465459957","text":"#!/bin/python3\n\n# https://www.hackerrank.com/challenges/taum-and-bday/problem\n\nimport sys\n\ndef taumBday(b, w, x, y, z):\n # Complete this function\n if x + z < y:\n return b * x + w * (x + z)\n if y + z < x:\n return b * (y + z) + w * y\n return b * x + w * y\n\nif __name__ == \"__main__\":\n t = int(input().strip())\n for a0 in range(t):\n b, w = input().strip().split(' ')\n b, w = [int(b), int(w)]\n x, y, z = input().strip().split(' ')\n x, y, z = [int(x), int(y), int(z)]\n result = taumBday(b, w, x, y, z)\n print(result)\n","sub_path":"hackerrank/algorithms/implementation/taum_and_bday.py","file_name":"taum_and_bday.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"328105113","text":"def max_num_in_file(filename):\n \"\"\"This function will return the maximum value of a list inside a file\n \"\"\"\n infile = open(filename, 'r')\n line = infile.readlines()\n infile.close()\n max_num = -1000000000000000000000000\n for line in line:\n number = int(line)\n if number >= max_num:\n max_num = number\n \n return max_num","sub_path":"2017/COSC121/Labs/Exam Revision/Exam 1.py","file_name":"Exam 1.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"242515071","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport os\nimport time\nimport datetime\nimport codecs\nimport multiprocessing as mp\nfrom os import makedirs\nfrom os.path import exists\nfrom selenium import webdriver\nfrom selenium.webdriver.common.proxy import *\n\n\n# site = 'http://flight.qunar.com'\nsite = 'http://www.howzf.com/esfn/EsfnSearch_csnew.jspx'\n# site = ''\n# hot_city_list = [u'上海', u'北京', u'广州', u'深圳']\n# num = len(hot_city_list)\n\n\n\"\"\"\n
  • \n\t\t不限\n\t\t\t\t \t\t上城\n\t\t \t\t下城\n\t\t \t\t江干\n\t\t \t\t拱墅\n\t\t \t\t西湖\n\t\t \t\t滨江\n\t\t \t\t之江\n\t\t \t\t下沙\n\t\t \t\t大江东\n\t\t \t\t萧山\n\t\t \t\t余杭\n\t\t \t\t富阳\n\t\t \t\t杭州周边\n\t
  • \n\"\"\"\n\narea_map = {\"上城\": \"area_330102\",\n \"下城\": \"area_330103\",\n \"江干\": \"area_330104\",\n \"拱墅\": \"area_330105\",\n \"西湖\": \"area_330106\",\n \"滨江\": \"area_330108\",\n \"之江\": \"area_330110\",\n \"下沙\": \"area_330186\",\n \"大江东\": \"area_330231\",\n \"萧山\": \"area_330181\",\n \"余杭\": \"area_330184\",\n \"富阳\": \"area_330187\",\n \"杭州周边\": \"area_330399\"\n }\n\n\nroom_map = {\"一室\": \"ro_1\",\n \"二室\": \"ro_2\",\n \"三室\": \"ro_3\",\n \"四室\": \"ro_4\",\n \"四室及以上\": \"ro_5\"}\n\nwylx_map = {\"住宅\": \"wylx_10\",\n \"非住宅\": \"wylx_20\"}\n\n# //*[@id=\"prh\"]\n\n# /html/body/div[4]/div[2]/div/div/ul[16]/li[5]/input\n\nareas_list = ['上城', '下城', '江干', '拱墅', '西湖', '滨江', '之江', '下沙', '萧山', '余杭']\n\n\ndef one_driver_ticket(driver, area):\n # time = datetime.datetime.now()\n date = datetime.date.today()\n # tomorrow = date+datetime.timedelta(days=1)\n # date格式转为string格式\n # tomorrow_string = tomorrow.strftime('%Y-%m-%d')\n\n # driver.find_element_by_name('fromCity').clear()\n # driver.find_element_by_name('fromCity').send_keys(from_city)\n # driver.find_element_by_name('toCity').clear()\n # driver.find_element_by_name('toCity').send_keys(to_city)\n # driver.find_element_by_name('fromDate').clear()\n # driver.find_element_by_name('fromDate').send_keys(tomorrow_string)\n # driver.find_element_by_xpath('//button[@type=\"submit\"]').click()\n # driver.find_element_by_id('aid_p')\n # username = driver.find_element_by_xpath(\"//li[@id='aid_p']/input[1]\")\n\n\n # driver.find_element_by_xpath('//*[@id=\"area_330102\"]')\n driver.find_element_by_id(area_map[area]).click()\n time.sleep(5)\n\n # 户型\n # driver.find_element_by_id('ro_2').click()\n # driver.find_element_by_id('ro_3').click()\n\n # 物业类型\n driver.find_element_by_id('wylx_10').click()\n time.sleep(5)\n\n # 总价\n # driver.find_element_by_id('pr_0_100').click()\n # driver.find_element_by_id('pr_100_150').click()\n # driver.find_element_by_id('pr_150_200').click()\n # driver.find_element_by_id('pr_200_300').click()\n # driver.find_element_by_id('ro_3')\n\n # driver.find_element_by_xpath('//*[@id=\"prh\"]').send_keys('250')\n driver.find_element_by_id('prh').send_keys('250')\n # driver.find_element_by_xpath('//*[@id=\"search_all\"]/div/ul[16]/li[7]/div').click()\n driver.find_element_by_class_name('queding ml10 CP').click()\n time.sleep(5) # 控制间隔时间,等待浏览器反映\n\n flag = True\n page_num = 0\n while flag:\n # 保存页面\n # print driver.page_source\n # source_code = driver.find_element_by_xpath(\"//*\").get_attribute(\"outerHTML\")\n # source_code = driver.find_element_by_xpath('/html/body/div[5]/div[2]/div[2]').get_attribute(\"outerHTML\")\n source_code = driver.find_element_by_class_name('picNews_list').get_attribute(\"outerHTML\")\n print(type(source_code))\n dstdir = './buyHouse/{}/'.format(date)\n if not exists(dstdir):\n makedirs(dstdir)\n f = codecs.open(dstdir + area + '-' + str(page_num+1) + '.html', 'w+', 'utf8')\n f.write(source_code)\n f.close()\n\n next_page = None\n try:\n # next_page = driver.find_element_by_id('/html/body/div[5]/div[2]/div[2]/div/ul/div[32]/div/a[10]')\n next_page = driver.find_element_by_link_text('下一页')\n except Exception as e:\n print(e)\n pass\n print(\"page: %d\" % (page_num+1))\n if next_page:\n try:\n next_page.click()\n time.sleep(2) # 控制间隔时间,等待浏览器反映\n page_num += 1\n except Exception as e:\n print('next_page could not be clicked')\n print(e)\n flag = False\n else:\n flag = False\n\ndef get_proxy_list(file_path):\n proxy_list = []\n try:\n f = open(file_path, 'r')\n all_lines = f.readlines() # readlines()每次按行读取整个文件内容,将读取到的内容放到一个列表中,返回list类型。\n for line in all_lines:\n proxy_list.append(line.replace('\\r', '').replace('\\n', ''))\n f.close()\n except Exception as e:\n print(e)\n return proxy_list\n\"\"\"\ndef ticket_worker_proxy(city_proxy):\n city = city_proxy.split(',')[0]\n proxy = city_proxy.split(',')[1]\n proxy = Proxy({\n 'proxyType': ProxyType.MANUAL,\n 'httpProxy': proxy,\n 'ftpProxy': proxy,\n 'sslProxy': proxy,\n 'noProxy': '' # 过滤不需要代理的地址\n })\n driver = webdriver.Firefox(proxy=proxy)\n driver.get(site)\n driver.maximize_window() # 将浏览器最大化显示\n for i in range(num):\n if city == hot_city_list[i]:\n continue\n from_city = city\n to_city = hot_city_list[i]\n one_driver_ticket(driver, from_city, to_city)\n driver.close()\n\ndef all_ticket_proxy():\n hot_city_proxy_list = []\n proxy_list = get_proxy_list('./proxy/proxy.txt') # ./表示当前目录,../表示上一级目录\n for i in range(num):\n hot_city_proxy_list.append(hot_city_list[i]+','+proxy_list[i])\n pool = mp.Pool(processes=1)\n pool.map(ticket_worker_proxy, hot_city_proxy_list) # map(f, [x1, x2, x3, x4]) = [f(x1), f(x2), f(x3), f(x4)]\n pool.close()\n pool.join()\n\"\"\"\n\n\ndef ticket_worker_no_proxy(area):\n chrome_driver = r\"D:\\Program Files\\chromedriver.exe\"\n driver = webdriver.Chrome(executable_path=chrome_driver)\n # chromedriver = r'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe'\n # os.environ['webdriver.chrome.driver'] = chromedriver\n # driver = webdriver.Chrome(chromedriver)\n driver.get(site)\n time.sleep(10)\n driver.refresh()\n time.sleep(5)\n driver.refresh()\n driver.maximize_window() # 将浏览器最大化显示\n time.sleep(10) # 控制间隔时间,等待浏览器反映\n # num = len(areas_list)\n # for i in range(num):\n # # if city == areas_list[i]:\n # # continue\n # # from_city = city\n # area = areas_list[i]\n # one_driver_ticket(driver, area)\n one_driver_ticket(driver, area)\n # one_driver_ticket(driver, area)\n driver.close()\n\n\ndef all_ticket_no_proxy():\n pool = mp.Pool(processes=1)\n pool.map(ticket_worker_no_proxy, areas_list) # map(f, [x1, x2, x3, x4]) = [f(x1), f(x2), f(x3), f(x4)]\n pool.close()\n pool.join()\n\n\nif __name__ == '__main__':\n print(\"start\")\n start = datetime.datetime.now()\n # all_ticket_proxy() # proxy\n all_ticket_no_proxy() # no proxy\n end = datetime.datetime.now()\n print(\"end\")\n print(\"time: \", end-start)\n","sub_path":"tmsfwSpider.py","file_name":"tmsfwSpider.py","file_ext":"py","file_size_in_byte":8421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"418444770","text":"'''\n\nAuthor: Elena Koubli\n\n\nThis module comprises some of the most used PV thermal models in literature for the translation \nof ambient to module temperature. \n\nCheck pvtester to have an idea how to run this module.\n\nMain reference:\n----------------\n\nSegado, Patricia, Mora J. Carretero, Sidrach-de-Cardona, Mariano, Models to predict the operating \ntemperature of different photovoltaic modules in outdoor conditions,Progress In Photovoltaics_ \nResearch And Applications,2014\n\n\n\n'''\n\ntry:\n import numpy as np\nexcept ImportError():\n raise ImportError(\"You need to install numpy\")\n\n\ndef servantThermal(thrmcoeff,Tamb,Geff,Ws):\n \n ''' \n Parameters\n ------------\n \n thrmcoeff: dict \n A dictionary containing the coefficients of the module\n It should contain the three fields required for this model \n \n Geff: numpy float or 1d array or list (Watt/m2)\n Effective irradiance i.e. irradiance reaching the surface of the module\n Either calculated or measured. The values need to be *positive*\n \n Tamb: numpy float or 1d array or list\n ambient temperature.\n \n \n Ws: numpy float or 1d array or list\n Windspeed\n \n \n \n \n Returns: Module temperature \n \n Tmod: or 1d array or series\n module temperature.\n \n \n \n ''' \n \n try:\n \n D = thrmcoeff['D']\n E = thrmcoeff['E']\n F = thrmcoeff['F']\n \n except KeyError:\n \n raise Exception('the required coefficients for this model are 3: D, E, F')\n \n Tmod = Tamb + D*Geff*(1+E*Tamb)*(1-F*Ws)\n \n return Tmod \n \n\n\ndef rossThermal(thrmcoeff,Tamb,Geff):\n \n ''' \n Parameters\n ------------\n \n thrmcoeff: dict \n A dictionary containing the coefficients of the module\n It should contain the three fields required for this model \n \n Geff: numpy float or 1d array or list (Watt/m2)\n Effective irradiance i.e. irradiance reaching the surface of the module\n Either calculated or measured. The values need to be *positive*\n \n Tamb: numpy float or 1d array or list\n ambient temperature (Celsius).\n \n \n \n Returns: Module temperature \n \n Tmod: or 1d array or list\n module temperature (in celcius).\n \n \n Note: The coefficients depend on the module mounting as shown below\n \n \n\n 1- well cooled (k= 0.02)\n 2- free standing (k=0.0208)\n 3- flat on roof (0.026)\n 4- not so well cooled (k=0.0342)\n 5- transparent PV (k=0.0455)\n 6- facade integrated (k=0.0538)\n 7- on sloped roof (k=0.0563)\n \n\n \n References:\n -----------\n \n Ross, Jr, R.G., Interface design considerations for terrestrial solar cell modules,12th Photovoltaic \n Specialists Conference, Baton Rouge, La. USA, 1976\n \n \n '''\n \n ross = thrmcoeff['ross'] \n Tmod = Tamb + ross*Geff\n \n \n return Tmod \n\n\n\n\ndef noctThermal(thrmcoeff, Tamb, Geff, units = \"celcius\"):\n \n ''' \n Parameters\n ------------\n \n thrmcoeff: dict \n A dictionary containing the coefficients of the module\n It should contain the three fields required for this model \n \n Geff: numpy float or 1d array or list (Watt/m2)\n Effective irradiance i.e. irradiance reaching the surface of the module\n Either calculated or measured. The values need to be *positive*\n \n Tamb: numpy float or 1d array or list\n ambient temperature.\n \n \n \n Returns: Module temperature \n ---------\n \n Tmod: or 1d array or list\n module temperature (in celcius).\n \n ''' \n \n noct = thrmcoeff['noct']\n \n if units.lower() == \"celcius\":\n \n Tmod = Tamb + (Geff/800)*(noct-20)\n \n elif units.lower() == \"kelvin\":\n \n Tmod = Tamb + (Geff/800)*(noct-293.0)\n \n \n return Tmod # NOCT model in Celsius\n \n\n\n\ndef kingThermal(thrmcoeff, Tamb, Geff, Ws):\n \n ''' \n Parameters\n ------------\n \n thrmcoeff: dict \n A dictionary containing the coefficients of the module\n It should contain the three fields required for this model \n \n Geff: numpy float or 1d array or list (Watt/m2)\n Effective irradiance i.e. irradiance reaching the surface of the module\n Either calculated or measured. The values need to be *positive*\n \n Tamb: numpy float or 1d array or list\n ambient temperature (in Celsius).\n \n Ws: numpy float or 1d array or list \n Wind speed\n \n Returns: Module temperature \n \n Tmod: or 1d array or list\n module temperature (in celcius).\n \n \n Taken from pvlib- python\n -------------------------\n Typical parameters:\n -------------------\n \n Module Type Mount a b deltat\n\n Glass/cell/glass Open rack -3.47 -0.0594 3\n Glass/cell/glass Close roof mount -2.98 -0.0471 1\n Glass/cell/glass Insulated back TBD TBD\n Glass/cell/polymer sheet Open rack -3.56 -0.0750 3\n Glass/cell/polymer sheet` Close roof mount TBD TBD\n Glass/cell/polymer sheet Insulated back -2.81 -0.0455 0\n 22X Linear Concentrator Tracker -3.23 -0.130 13\n \n \n \n \n \n Reference:\n ----------\n Kratochvil, Jay A Boyson, William Earl King, David L, Photovoltaic array performance model,\n SAND2004-3535, Sandia National Laboratories (SNL), 2004\n \n '''\n \n try: \n \n m = thrmcoeff['m']\n n = thrmcoeff['n']\n \n except KeyError:\n \n raise Exception('Two coefficients are needed for this model: m,n')\n \n \n Tmod = Tamb+Geff*np.exp(m+n*Ws)\n \n return Tmod\n\n \n\ndef kingModToCell(deltat, Geff, Tmod):\n \n ''' \n Parameters\n ------------\n This equation returns cell temperature from the back of module temperature\n \n thrmcoeff: dict \n A dictionary containing the coefficients of the module\n It should contain the three fields required for this model \n \n Geff: numpy float or 1d array or list (Watt/m2)\n Effective irradiance i.e. irradiance reaching the surface of the module\n Either calculated or measured. The values need to be *positive*\n \n \n deltaT: numpy float or 1d array or list\n Is taken for different configurations of module types (see documentation string of KingThermal)\n \n Returns: cell temperature \n \n \n Tcell: or 1d array or list\n module temperature (in celcius).\n \n \n \n *Check kingThermal for input coefficients*\n \n \n Reference:\n \n Kratochvil, Jay A Boyson, William Earl King, David L, Photovoltaic array performance model,\n SAND2004-3535, Sandia National Laboratories (SNL), 2004\n \n '''\n \n \n Tcell = Tmod + (Geff/1000)*deltat\n \n \n \n return Tcell\n\n\n\n# Need to add the draft 61853 model here\n\n\ndef therm61853_1(thrmcoeff, Tamb, Geff, Ws):\n \n ''' \n Parameters\n ------------\n This equation returns module temperature proposed in the IEC standard 61853 -2 (draft) \n \n thrmcoeff: dict \n A dictionary containing the coefficients of the module\n It should contain the three fields required for this model \n \n Geff: numpy float or 1d array or list\n Effective irradiance i.e. irradiance reaching the surface of the module\n Either calculated or measured. The values need to be *positive*\n \n Tamb: numpy float or 1d array or list\n ambient temperature (in Celsius)\n \n Ws: numpy float or 1d array or list \n Wind speed \n \n Returns: module temperature \n ---------\n \n Tmod: numpy float or 1d array or list\n module temperature (in celcius). \n \n \n Reference:\n \n D.Faiman \"Assessing the outdoor operating temperature of photovoltaic modules\" in prog. photovoltaics Res. Appl. pp 307-315, 2008\n \n '''\n \n try:\n \n u0 = thrmcoeff['u0']\n u1 = thrmcoeff['u1']\n \n except KeyError:\n \n raise Exception('Two coefficients are needed for this model: u0,u1')\n \n Tmod = Tamb + Geff*(u0 + u1*Ws)\n \n return Tmod\n\n\n\n","sub_path":"PVER/pvtherm.py","file_name":"pvtherm.py","file_ext":"py","file_size_in_byte":9186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"387499554","text":"import RPi.GPIO as GPIO\nfrom lib_nrf24 import NRF24\nimport time\nimport spidev\n\nGPIO.setmode(GPIO.BCM)\n\npipes = [[0xE8, 0xE8, 0xF0, 0xF0, 0xE1], [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]]\n\nradio = NRF24(GPIO, spidev.SpiDev())\nradio.begin(0, 17)\n\nradio.setPayloadSize(32)\nradio.setChannel(0x76)\nradio.setDataRate(NRF24.BR_1MBPS)\nradio.setPALevel(NRF24.PA_MIN)\n\nradio.setAutoAck(True)\nradio.enableDynamicPayloads()\nradio.enableAckPayload()\n\nradio.openReadingPipe(1, pipes[1])\nradio.printDetails()\nradio.startListening()\n\n#setup gpio 5, 6, 13, 19, 26\n\nGPIO.setup(5, GPIO.OUT)\nthumb_pwm = GPIO.PWM(5, 100)\nGPIO.setup(6, GPIO.OUT)\nindex_pwm = GPIO.PWM(6, 100)\nGPIO.setup(13, GPIO.OUT)\nmiddle_pwm = GPIO.PWM(13, 100)\nGPIO.setup(19, GPIO.OUT)\npinky_pwm = GPIO.PWM(19, 100)\n\nthumb_pwm.start(50)\nindex_pwm.start(50)\nmiddle_pwm.start(50)\npinky_pwm.start(50)\n\nGPIO.setwarnings(False)\n\nwhile True:\n\n while not radio.available(0):\n time.sleep(1/100)\n\n receivedMessage = []\n radio.read(receivedMessage, radio.getDynamicPayloadSize())\n\n print(receivedMessage)\n\n \n pinky_pwm.ChangeDutyCycle(receivedMessage[0])\n thumb_pwm.ChangeDutyCycle(receivedMessage[2])\n middle_pwm.ChangeDutyCycle(receivedMessage[4])\n index_pwm.ChangeDutyCycle(receivedMessage[6])\n\n \n \n \n","sub_path":"NRF24L01/receivearduino.py","file_name":"receivearduino.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"257943971","text":"import asyncio\nimport discord\nimport random\nfrom hourai import cogs\nfrom hourai.db import proto\nfrom discord.ext import commands\n\n\nclass Announce(cogs.BaseCog):\n\n def __init__(self, bot):\n self.bot = bot\n\n async def get_announce_config(self, guild):\n config = await self.bot.storage.announce_configs.get(guild.id)\n return config or proto.AnnouncementConfig()\n\n async def set_announce_config(self, guild, config):\n await self.bot.storage.announce_configs.set(guild.id, config)\n\n @commands.group(invoke_without_command=True)\n @commands.guild_only()\n @commands.has_permissions(manage_guild=True)\n @commands.bot_has_permissions(send_messages=True)\n async def announce(self, ctx):\n pass\n\n @announce.command(name='join')\n async def announce_join(self, ctx):\n announce_config = await self.get_announce_config(ctx.guild)\n result = self.__toggle_channel(ctx, announce_config.joins);\n await self.set_announce_config(ctx.guild, announce_config)\n suffix = 'enabled' if result else 'disabled'\n await ctx.send(f\":thumbsup: Join messages {suffix}\")\n\n @announce.command(name='leave')\n async def announce_leave(self, ctx):\n announce_config = await self.get_announce_config(ctx.guild)\n result = self.__toggle_channel(ctx, announce_config.leaves);\n await self.set_announce_config(ctx.guild, announce_config)\n suffix = 'enabled' if result else 'disabled'\n await ctx.send(f\":thumbsup: Leave messages {suffix}\")\n\n @announce.command(name='ban')\n async def announce_ban(self, ctx):\n announce_config = await self.get_announce_config(ctx.guild)\n result = self.__toggle_channel(ctx, announce_config.bans);\n await self.set_announce_config(ctx.guild, announce_config)\n suffix = 'enabled' if result else 'disabled'\n await ctx.send(f\":thumbsup: Ban messages {suffix}\")\n\n async def __toggle_channel(self, ctx, config):\n if ctx.channel.id in config.channel_ids:\n config.channel_ids.remove(ctx.channel.id)\n return False\n config.channel_ids.append(ctx.channel.id)\n return True\n\n @commands.Cog.listener()\n async def on_member_join(self, member):\n announce_config = await self.get_announce_config(member.guild)\n if not announce_config.HasField('joins'):\n return\n if len(announce_config.joins.messages) > 0:\n choices = list(announce_config.joins.messages)\n else:\n choices = [f'**{member.mention}** has joined the server.']\n await self.__make_announcement(member.guild, announce_config.joins,\n choices)\n\n @commands.Cog.listener()\n async def on_member_remove(self, member):\n announce_config = await self.get_announce_config(member.guild)\n if not announce_config.HasField('leaves'):\n return\n if len(announce_config.leaves.messages) > 0:\n choices = list(announce_config.leaves.messages)\n else:\n choices = [f'**{member.name}** has left the server.']\n await self.__make_announcement(member.guild, announce_config.leaves,\n choices)\n\n @commands.Cog.listener()\n async def on_member_ban(self, guild, user):\n announce_config = await self.get_announce_config(guild)\n if not announce_config.HasField('bans'):\n return\n if len(announce_config.bans.messages) > 0:\n choices = list(announce_config.bans.messages)\n else:\n choices = [f'**{user.name}** has been banned.']\n await self.__make_announcement(guild, announce_config.bans, choices)\n\n @commands.Cog.listener()\n async def on_voice_state_update(self, member, before, after):\n announce_config = await self.get_announce_config(member.guild)\n if not announce_config.HasField('voice'):\n return\n assert not (before.channel is None and after.channel is None)\n if before.channel == after.channel:\n return\n elif before.channel is None:\n choices = [f'**{member.display_name}** joined **{after.channel.name}**.']\n elif after.channel is None:\n choices = [f'**{member.display_name}** left **{before.channel.name}**.']\n else:\n choices = [f'**{member.display_name}** moved to **{after.channel.name}**'\n f' from **{before.channel.name}**.']\n await self.__make_announcement(member.guild, announce_config.voice,\n choices)\n\n async def __make_announcement(self, guild, config, choices):\n assert len(choices) > 0\n channels = [guild.get_channel(ch_id) for ch_id in config.channel_ids]\n channels = [ch for ch in channels\n if isinstance(ch, discord.TextChannel)]\n tasks = []\n for channel in channels:\n content = random.choice(choices)\n tasks.append(channel.send(content))\n await asyncio.gather(*tasks)\n\n\ndef setup(bot):\n bot.add_cog(Announce(bot))\n","sub_path":"hourai/extensions/announce.py","file_name":"announce.py","file_ext":"py","file_size_in_byte":5115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"545766818","text":"import re\n#\nwith open('/home/mrxu/Desktop/笑话.txt', 'r') as f:\n data = f.readlines()\n str = ''.join(data)\n print(str)\n ret = re.compile(r'
    (\\D*?)<.*?>')\n\n result = ret.findall(str)\n print(result)\n # str2 = ''.join(result)\n # print(str2)\n # with open('/home/mrxu/Desktop/笑话.txt','w+') as d:\n # d.write(str2)\n # print('这是字符串2',str2)\n # print('这是存进去的',f.readlines())\n # d.close()\n f.close()\n\n","sub_path":"自己自学的爬虫/01_day/获取有效数据.py","file_name":"获取有效数据.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"362402890","text":"import string\n\nimport pygame\nimport random\n\nfrom App.PathMaker import PathMaker\nfrom ObjectDictionary import ObjectDictionary\nfrom ToolTypes import ToolTypes\nfrom PaneManager import PaneManager\nfrom pygame.locals import *\n\nfrom Configuration import Configuration\nfrom XmlGenerator import XmlGenerator\n\n\nclass State(object):\n\n def __init__(self, mainLoop):\n self.loop = mainLoop\n # self.updater = Updater()\n # self.renderer = Renderer()\n # self.screenRenderer = ScreenRenderer()\n self.events = []\n \n self.clickPoint = None\n\n self.mainSurface = pygame.Surface(\n (Configuration.Resolution[0], Configuration.Resolution[1])\n )\n\n self.paneManager = PaneManager()\n\n self.outputPath = \"XMLOutput/\"\n self.outputFileName = \"\"\n\n def processInputs(self, events):\n\n for event in events:\n\n if event.type == QUIT:\n\n self._quit()\n\n elif event.type == KEYUP:\n\n if event.key == K_ESCAPE:\n self._quit()\n\n elif event.key == K_RETURN:\n self._loadLevel()\n\n elif event.type == KEYDOWN:\n\n if event.key in range(K_PERIOD, K_z):\n\n self.paneManager.openFileTextBox.addText(event.unicode)\n\n elif event.key == K_BACKSPACE:\n\n self.paneManager.openFileTextBox.backSpace()\n\n elif event.type == MOUSEBUTTONDOWN:\n\n self.clickPoint = event.pos\n \n elif event.type == MOUSEBUTTONUP:\n \n if self.clickPoint is not None:\n \n clickAndDragWidth = abs(self.clickPoint[0] - event.pos[0])\n clickAndDragHeight = abs(self.clickPoint[1] - event.pos[1])\n clickAndDragRect = pygame.Rect(self.clickPoint, (clickAndDragWidth, clickAndDragHeight))\n \n if self.paneManager.levelImagePane.rect.colliderect(clickAndDragRect):\n\n newGroupId = self._getNewGroupId()\n\n for pane in self.paneManager.tilePanes:\n\n if pane.rect.colliderect(clickAndDragRect):\n\n for tool in self.paneManager.tools:\n\n if tool.active:\n\n self.paneManager.levelImagePane.dirtyRects.append(pane.rect)\n\n pane.dirty = True\n\n if tool.type == ToolTypes.Eraser:\n\n pane.clear()\n self.paneManager.levelImagePane.dirtyRects.append(pane.rect)\n\n for object_ in self.paneManager.objects[:]:\n\n if object_.rect.colliderect(clickAndDragRect):\n\n self.paneManager.objects.remove(object_)\n\n elif tool.type == ToolTypes.Material:\n\n pane.material = tool.name\n pane.images[\"material\"] = tool.getImage()\n pane.groupId = newGroupId\n\n elif tool.type == ToolTypes.Solidity:\n\n pane.solidity = tool.name\n pane.images[\"solidity\"] = tool.getImage()\n pane.groupId = newGroupId\n\n elif tool.type == ToolTypes.Object:\n\n newObject = ObjectDictionary.Objects[tool.name](pane.rect.topleft)\n newObjectDoesntCollideWithOldOnes = True\n\n for object_ in self.paneManager.objects:\n\n if object_.rect.colliderect(newObject.rect):\n\n newObjectDoesntCollideWithOldOnes = False\n\n if newObjectDoesntCollideWithOldOnes:\n self.paneManager.objects.append(newObject)\n\n pane.dirty = True\n\n elif self.paneManager.buttonAreaRect.colliderect(clickAndDragRect):\n\n for buttonName in self.paneManager.buttons:\n\n button = self.paneManager.buttons[buttonName]\n\n if button.rect.colliderect(clickAndDragRect):\n\n if button.text == \"Quit\":\n\n self._quit()\n\n elif button.text == \"Open\":\n\n self._loadLevel()\n \n elif button.text == \"Clear\":\n \n for pane in self.paneManager.tilePanes:\n \n pane.clear()\n\n self.paneManager.levelImagePane.dirtyRects.append(pane.rect)\n\n self.paneManager.objects = []\n\n elif button.text == \"Export\":\n\n if self.outputFileName == \"\":\n self.outputFileName = \"XXtest\"\n\n outputFilePath = self.outputPath + self.outputFileName + \".xml\"\n XmlGenerator.WriteLevelToFile(self.paneManager, outputFilePath)\n\n elif self.paneManager.toolPane.rect.colliderect(clickAndDragRect):\n\n for tool in self.paneManager.tools:\n\n if tool.rect.collidepoint(self.clickPoint):\n\n if not tool.active:\n tool.activate()\n\n for otherTool in self.paneManager.tools:\n\n if otherTool is not tool:\n\n if tool.type == ToolTypes.Solidity and otherTool.active:\n\n if otherTool.type != ToolTypes.Material:\n otherTool.deactivate()\n\n elif tool.type == ToolTypes.Material and otherTool.active:\n\n if otherTool.type != ToolTypes.Solidity:\n otherTool.deactivate()\n\n else:\n otherTool.deactivate()\n else:\n tool.deactivate()\n\n self.clickPoint = None\n\n def _getNewGroupId(self):\n newGroupId = \"\"\n for x in range(10):\n newGroupId += random.choice(string.ascii_letters + string.digits)\n return newGroupId\n\n def _loadLevel(self):\n levelFileToOpen = self.paneManager.openFileTextBox.text[:]\n self.paneManager = PaneManager(levelFileToOpen)\n self.outputFileName = levelFileToOpen\n\n def update(self):\n\n pass\n\n def render(self, screen):\n\n self.paneManager.renderAll(screen)\n\n def _quit(self):\n self.loop.done = True\n\n\n\n\n\n","sub_path":"App/State.py","file_name":"State.py","file_ext":"py","file_size_in_byte":7663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"492929215","text":"import csv\nimport json\n\ncsvfile = open('candit.lf.csv', 'r', encoding=\"utf8\")\njsonfile = open('formated-lf.json', 'w')\n# \"N_Dossier\",\"Nom\",\"Prénom\",\"Nature_diplôme_obtenu\",\"Choix_1\",\"Choix_2\",\"Choix_3\",\"Choix_4\",\"Score\"\nfieldnames = (\"N_Dossier\",\"Nom\",\"Prenom\",\"Nature_diplome_obtenu\",\"Choix_1\",\"Choix_2\",\"Choix_3\",\"Choix_4\",\"Score\")\nreader = csv.DictReader( csvfile, fieldnames)\nout = json.dumps( [ row for row in reader ] )\njsonfile.write(out)","sub_path":"format.py","file_name":"format.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"556365541","text":"from app import mongo\nfrom random import randint\nfrom flask import Flask, flash, jsonify\nimport re, pdb, string, random, os, requests, base64, datetime, hmac, hashlib, time, imaplib, email\nfrom . import mongo\nfrom datetime import datetime, date\nfrom os.path import join, dirname, realpath\nfrom werkzeug.utils import secure_filename\nfrom PIL import Image\nimport requests, json\napps = Flask(__name__)\n\ndef resize_files(_user_id, _image):\n response = {}\n PATH_FOLDER = join(dirname(realpath(__file__)), '../inbox/')\n apps.config['PATH_FOLDER'] = PATH_FOLDER\n filename, filename_ext = os.path.splitext(_image.filename)\n allowed_img = set(['png', 'jpg', 'jpeg'])\n if filename_ext.rsplit('.', 1)[1].lower() in allowed_img:\n _filename = str(_user_id)+'-'+str(time.time()).replace('.', '')+filename_ext\n getImage = Image.open(_image)\n # image_size = getImage.size\n # width = int(image_size[0])\n # height = int(image_size[1])\n # while(width>1000 or height>1000):\n # width = int(width/2)\n # height = int(height/2)\n # imgresize = getImage.resize((width, height), Image.ANTIALIAS)\n getImage.save(os.path.join(apps.config['PATH_FOLDER'], _filename))\n response['allowed'] = 'Sukses'\n response['status'] = '00'\n # response['name'] = _filename\n # response['image_id'] = _typeimage\n else :\n response['allowed'] = 'file tidak diizinkan'\n response['status'] = '60'\n return response\n\n\ndef hmac_sha256(key, msg):\n hash_obj = hmac.new(key=key, msg=msg, digestmod=hashlib.sha256)\n return hash_obj.hexdigest()\n\ndef generateRefca(user_id):\n return str(int(time.time())) + '#' + str(user_id)\n\nclass trxLog:\n user_id = None\n refca = None\n refsb = None\n status = None\n timestamp = datetime.utcnow()\n _accno = None\n _accname = None\n _phone_number = None\n _uid = None\n _name = None\n _description = None\n _type = None\n _billperiode = None\n _provider = None\n _cost = None\n _price = None\n _total_trx = None\n _detail = None\n\n def _insert(self):\n response = {}\n _data = {}\n _trx_log = mongo.db.trx_log\n if self.user_id != None:\n _data['user_id'] = self.user_id\n if self.refca == None:\n _data['refca'] = generateRefca(self.user_id)\n else:\n _data['refca'] = self.refca\n _data['refsb'] = self.refsb\n _data['status'] = self.status\n _data['timestamp'] = self.timestamp\n _data['_accno'] = self._accno\n _data['_accname'] = self._accname\n _data['_phone_number'] = self._phone_number\n _data['_uid'] = self._uid\n _data['_name'] = self._name\n _data['_description'] = self._description\n _data['_type'] = self._type\n _data['_billperiode'] = self._billperiode\n _data['_provider'] = self._provider\n _data['_cost'] = self._cost\n _data['_price'] = self._price\n _data['_total_trx'] = self._total_trx\n _data['_detail'] = self._detail\n _trx_log.insert(_data)\n response['status'] = '50'\n response['id'] = _data['refca']\n else:\n response['status'] = '50'\n response['message'] = 'ID User tidak ditemukan!'\n return response\n\ndef ip(ip_list):\n if ip_list.count(', ') == 1:\n ip1, ip3 = ip_list.split(', ')\n ip2 = 'None'\n elif ip_list.count(',') == 1:\n ip1, ip3 = ip_list.split(',')\n ip2 = 'None'\n elif ip_list.count(',') > 1:\n ip1, ip2, ip3 = ip_list.split(',')\n elif ip_list.count(', ') > 1:\n ip1, ip2, ip3 = ip_list.split(', ')\n else:\n raise ValueError(ip_list)\n return [ip1, ip2, ip3]\n\ndef user_log(url, ip_list):\n iplist = ip(ip_list)\n index_log = mongo.db.index_log\n index_log.insert({\n 'user_id': current_user.id,\n 'url': url,\n 'ip_client': iplist[0],\n 'ip_proxy': iplist[1],\n 'ip_cloudflare': iplist[2],\n 'timestamp': datetime.utcnow()\n })\n\ndef send_notif(firebase_id, title, body,status_upgrade, count, notif):\n headers = {\n 'authorization' : 'key=AIzaSyAK1XTWAwyq-NGt38KHh9XdDPBTOeXImZo',\n 'Content-Type' : 'application/json'\n }\n values = {\n \"to\" : firebase_id,\n \"collapse_key\" : \"type_a\",\n \"notification\" : {\n \"title\": title,\n \"body\" : body,\n \"icon\" : \"notification_icon\"\n },\n \"data\" : {\n \"body\" : \"Body of Your Notification in Data\",\n \"title\": \"Title of Your Notification in Title\",\n \"status_upgrade\": status_upgrade,\n \"count\": count,\n \"notification\": notif\n }\n }\n _request = requests.post('https://fcm.googleapis.com/fcm/send', data=json.dumps(values), headers=headers)\n _data = _request.json()\n print(_data)\n\nclass apiBCA:\n ApiKey = '34bec438-9911-494c-9e29-d0041f941eec'\n ApiSecret = 'f6068d37-0fd8-456a-bced-61ac35af53da'\n ClientId = 'b66925de-d8ec-476e-a170-6cf06c863b78'\n ClientSecret = 'efc71ced-b0e7-4b47-8270-3c24829764aa'\n DataAuth = str.encode(ClientId + ':' + ClientSecret)\n Auth = base64.b64encode(DataAuth)\n Authorization = 'Basic ' + Auth.decode()\n isoTimestamp = datetime.now().isoformat(timespec='milliseconds')\n timestamp = isoTimestamp + '+07:00'\n today_date = date.today().isoformat()\n\n def __init__(self,\n CorporateID = 'h2hauto009' ,accNumber = '0613006572', url='https://devapi.klikbca.com:443',\n startdate=today_date, enddate=today_date):\n self.CorporateID = CorporateID\n self.accNumber = accNumber\n self.url = url\n self.headers = {}\n self.data = []\n self.AccessToken = None\n self.startdate = startdate\n self.enddate = enddate\n\n def oAuth(self):\n self.headers = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Authorization': self.Authorization,\n }\n self.data = [\n ('grant_type', 'client_credentials'),\n ]\n response = requests.post(self.url + '/api/oauth/token', headers=self.headers, data=self.data)\n return response.json()\n\n def generatesignature(self, accessToken, type='bi'):\n RelativeUrl = '/banking/v3/corporates/' + self.CorporateID + '/accounts/' + self.accNumber\n if type == 'as':\n RelativeUrl = '/banking/v3/corporates/' + self.CorporateID + '/accounts/' + self.accNumber + \\\n '/statements?EndDate=' + self.enddate + '&StartDate=' + self.startdate\n print(RelativeUrl)\n HTTPMethod = 'GET'\n RequestBody = hashlib.sha256(b\"\").hexdigest()\n StringToSign = str.encode(HTTPMethod + \":\" + RelativeUrl + \":\" + accessToken + \":\" + RequestBody + \":\" + self.timestamp)\n key = str.encode(self.ApiSecret)\n self.hmac_sha256(key, StringToSign)\n response = {\n 'hcam': self.hmac_sha256(key, StringToSign),\n 'timestamp': self.timestamp\n }\n print(StringToSign)\n return response\n\n def balanceInformation(self, accessToken, timestamp, signature):\n self.headers = {\n 'Authorization': 'Bearer ' + accessToken,\n 'Content-Type': 'application/json',\n 'Origin': 'vinaya.tech',\n 'X-BCA-Key': self.ApiKey,\n 'X-BCA-Timestamp': timestamp,\n 'X-BCA-Signature': signature,\n }\n\n response = requests.get(self.url + '/banking/v3/corporates/' + self.CorporateID + '/accounts/' + self.accNumber,\n headers=self.headers)\n return response.json()\n\n def acountStatement(self, accessToken, timestamp, signature):\n self.headers = {\n 'Authorization': 'Bearer ' + accessToken,\n 'Content-Type': 'application/json',\n 'Origin': 'vinaya.tech',\n 'X-BCA-Key': self.ApiKey,\n 'X-BCA-Timestamp': timestamp,\n 'X-BCA-Signature': signature,\n }\n print(self.headers)\n response = requests.get(self.url + '/banking/v3/corporates/' + self.CorporateID + '/accounts/'\n + self.accNumber + '/statements?EndDate=' + self.enddate + '&StartDate=' + self.startdate,\n headers=self.headers)\n return response.json()\n\n\n def hmac_sha256(self, key, msg):\n hash_obj = hmac.new(key=key, msg=msg, digestmod=hashlib.sha256)\n return hash_obj.hexdigest()\n\n def uniqueNumber(self, array, saldo='50000'):\n rand = randint(0, 999)\n data = {}\n data['rc'] = 0\n if int(saldo) >= 50000:\n status = True\n unique_status = False\n while status:\n uc = int(saldo[-3:]) + rand\n total = int(saldo) + int(uc)\n uqc = str(total)[-3:]\n if len(array) > 0:\n for i in array:\n if i['uniquecode'] == uqc:\n break\n else:\n unique_status = True\n break\n if unique_status == True:\n data['rc'] = 1\n data['saldo'] = total\n data['uniquecode'] = str(total)[-3:]\n else:\n data['rc'] = 1\n data['saldo'] = total\n data['uniquecode'] = str(total)[-3:]\n unique_status = True\n if unique_status == True:\n status = False\n return data\n\n\n\nclass _email:\n ORG_EMAIL = \"@ion-network.id\"\n _USER = None\n _PWD = None\n _SERVER = \"mx-s3.vivawebhost.com\"\n\n def _auth(self):\n con = None\n if self._USER != None:\n con = imaplib.IMAP4_SSL(self._SERVER)\n _email = self._USER + self.ORG_EMAIL\n con.login(_email, self._PWD)\n return con\n","sub_path":"hop/app/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"344664532","text":"\"\"\"\n构造一个3层的网络\n输入层一个结点,隐层10个结点,输出层一个结点\n\n输入层的维度是[n,1]\n隐层的维度是 [1,10]\n输出层的维度是[10,1]\n\nso,\n权值矩阵的维度是:\nweight1=[1,10]\nbais1=[10,1]\n\nweight2=[10,1]\nbais2=[1,1]\n\"\"\"\n\n\nimport tensorflow as tf\nimport numpy as np\n\ndef add_layer(inputs, in_size, out_size, activation_function=None):\n # add one more layer and return the output of this layer\n #我们给这一层加的权重是随机生成的\n Weights = tf.Variable(tf.random_normal([in_size, out_size]))\n #创建 【in_size * out_size】的矩阵,服从正态分部\n\n biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)\n #创建偏移函数 【1*outsize】 +0.1\n Wx_plus_b = tf.matmul(inputs, Weights) + biases\n #这一步设置了内部函数式如何转化的,这里是 利用矩阵乘法 + 矩阵加法\n #也就是可以理解线性函数\n #\n #tf.matmul是矩阵乘法\n\n # input的矩阵【N * input__size】 * 【in_size * out_size】\n # 返回 N * outsize\n if activation_function is None:\n outputs = Wx_plus_b\n else:\n outputs = activation_function(Wx_plus_b)\n return outputs\n\n# 构造一个数据集\nx_data = np.linspace(-1,1,300)[:, np.newaxis]\n#指定的间隔内返回均匀间隔的数字。即1 到 -1 间,300个数\n#np.newaxis在【,】前面时,变为列扩展的二维数组 1*n\n#np.newaxis在【,】后面时,变为行扩展的二维数组 n*1\n#所以是 【300*1】\nnoise = np.random.normal(0, 0.05, x_data.shape)\n#np.random.normal为高斯正态分布\n\n#y_data = np.square(x_data) - 0.5 + noise\n#y_data为 x**2 -0.5+ 噪声 noise\n#模拟y=x**2\ny_data = np.square(x_data)\n\n# placeholder 占个位\nxs = tf.placeholder(tf.float32, [None, 1]) # N * 1类型矩阵 ,N未知\nys = tf.placeholder(tf.float32, [None, 1])\n\n# add hidden layer 添加隐藏层(中间层\n\nl1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)\n# 矩阵乘法 【N*1】 * 【1 * 10】 =N* 10\n\n\n# add output layer,输出层\n# 上一层的输出是这一层的输入\nprediction = add_layer(l1, 10, 1, activation_function=None)\n# N* 10 10*1 --》N*1\n\n# the error between prediction and real data\n\n#loss函数和使用梯度下降的方式来求解\n#创建损失函数\nloss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),reduction_indices=[1]))\n#创建训练步骤\ntrain_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)\n\n# important step\n# tf.initialize_all_variables() no long valid from\n# 2017-03-02 if using tensorflow >= 0.12\n\nif int((tf.__version__).split('.')[1]) < 12:\n init = tf.initialize_all_variables()\nelse:\n init = tf.global_variables_initializer()\n#初始化\nsess = tf.Session()\nsess.run(init)\n#开始运行\nfor i in range(1000):\n # trainings\n sess.run(train_step, feed_dict={xs: x_data, ys: y_data})\n if i % 50 == 0:\n # to see the step improvement\n # 在带有placeholder的变量里面,每一次sess.run 都需要给一个feed_dict,这个不能省略啊!\n print(\"loss : \",sess.run(loss, feed_dict={xs: x_data, ys: y_data}))\n#现在开始进行模拟\nxx_data = np.linspace(-1,1,10)[:, np.newaxis]\nyy_data = np.square(xx_data)\nprint(xx_data)\nprint(\"XX : \",sess.run(prediction, feed_dict={xs: xx_data, ys: yy_data}))","sub_path":"tensorflow_tutorials/1.5 tf 构造简单的神经网络.py","file_name":"1.5 tf 构造简单的神经网络.py","file_ext":"py","file_size_in_byte":3322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"255723835","text":"# 问题描述 : 一维形式最近点对, 分治求解\n# 复杂度: nlogn\nA = [0, 1, 3, 6, 8, 10, 11, 14, 24, 27]\n\n\ndef solver_cross(a, mid):\n if abs(a[mid - 1] - a[mid]) < abs(a[mid] - a[mid + 1]):\n return mid - 1, abs(a[mid - 1] - a[mid])\n else:\n return mid, abs(a[mid] - a[mid + 1])\n\n\ndef solver(a, st, ed):\n if st == ed:\n return 0, st\n if abs(st - ed) == 1:\n return st, abs(a[st] - a[ed])\n else:\n mid = (st + ed) // 2\n left_loc, left_ans = solver(a, st, mid)\n right_loc, right_ans = solver(a, mid + 1, ed)\n cross_loc, cross_ans = solver_cross(a, mid)\n\n _min = min(left_ans, right_ans, cross_ans)\n if _min == left_ans:\n return left_loc, left_ans\n elif _min == right_ans:\n return right_loc, right_ans\n else:\n return cross_loc, cross_ans\n\n\nans = solver(A, 1, len(A) - 1)\nprint('最近点对: (', A[ans[0]], ',', A[ans[0] + 1], ') 最近点距离:', ans[1])\n","sub_path":"CodeBook/2018算法分析与设计作业/HW1.1.py","file_name":"HW1.1.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"105322147","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Feb 20 14:00:58 2017\r\n\r\n@author: strategy.intern.2\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport os\r\nimport datetime\r\n\r\nfrom analysis import CandleAnalysis\r\n#from utlity.utlity import CandleUtility\r\n\r\n#------------------------------------------------------------------------------\r\n# Initailize settings\r\n#------------------------------------------------------------------------------\r\n\r\n#curncyList = CandleUtility.GetCurncyList()\r\n \r\n#periodDict = {'t_full' : '2009-09-16 to 2017-02-06',\r\n# 't_2' : '2009-09-16 to 2012-12-31',\r\n# 't_1' : '2013-01-01 to 2015-12-31',\r\n# 't' : '2016-01-01 to 2017-02-06'}\r\n# \r\n#numOfDays = {'t_full' : (datetime.date(2017,2,6) - datetime.date(2009, 9, 16)).days,\r\n# 't_2' : (datetime.date(2012,12,31) - datetime.date(2009, 9, 16)).days,\r\n# 't_1' : (datetime.date(2015,12,31) - datetime.date(2013, 1, 1)).days,\r\n# 't' : (datetime.date(2017,2,6) - datetime.date(2016, 1, 1)).days}\r\n\r\nperiodDict = {'t_full' : '2009-01-01 to 2017-02-06',\r\n 't_2' : '2009-01-01 to 2012-01-01',\r\n 't_1' : '2012-01-01 to 2015-01-01',\r\n 't' : '2015-01-01 to 2017-02-06'}\r\n \r\nnumOfDays = {'t_full' : (datetime.date(2017,2,6) - datetime.date(2009, 1, 1)).days,\r\n 't_2' : (datetime.date(2012,1,1) - datetime.date(2009, 1, 1)).days,\r\n 't_1' : (datetime.date(2015,1,1) - datetime.date(2012, 1, 1)).days,\r\n 't' : (datetime.date(2017,2,6) - datetime.date(2015, 1, 1)).days}\r\n \r\n#------------------------------------------------------------------------------\r\n# Read backtest result from files\r\n#------------------------------------------------------------------------------\r\n#fileNames = CandleAnalysis.GetBacktestFileNames(os.getcwd())\r\n#result_df = CandleAnalysis.InterpretBacktestResult(fileNames)\r\n#filter_df = CandleAnalysis.FilterByHitRate(result_df, 0.55, 4)\r\n\r\n#------------------------------------------------------------------------------\r\n# Read Backtest result from HDF store\r\n#------------------------------------------------------------------------------\r\nresult_df = {}\r\nfiltered_df = {}\r\n\r\nstore = pd.HDFStore('WeeklyBacktest20170224.h5')\r\nresult_df[1] = store['weekly']\r\nstore.close()\r\n\r\n\r\n#store = pd.HDFStore('InsideBarCombBacktest20170220.h5')\r\n#result_df[2] = store['weekly']\r\n#store.close()\r\n\r\n\r\n#store = pd.HDFStore('insidebarcomb.h5')\r\n#result_df[3] = store['insidebarcomb']\r\n#store.close()\r\n#\r\n#filtered_df[3] = CandleAnalysis.FilterByHitRate(result_df[3], 0.55, 4)\r\n\r\n# concate data frame\r\nconcate_df = pd.concat([df for df in result_df.itervalues()], ignore_index = True)\r\n\r\n#------------------------------------------------------------------------------\r\n# Filter Signal Parameters\r\n#------------------------------------------------------------------------------\r\n# first filter\r\nfinal_df = CandleAnalysis.FilterByHitRate(concate_df, 0.501, 4)\r\n\r\n# second filter\r\ngroup = final_df.groupby(['Curncy', 'Signal'])\r\nfinal_df = group.filter(lambda x: len(x[(x.Period==periodDict['t_full']) & (x.CumReturn > 0)]) == 2)\r\n\r\n# third filter\r\ngroup = final_df.groupby(['Curncy', 'Signal'])\r\nfinal_df = group.filter(lambda x: np.mean(x.HitRate[x.Period==periodDict['t']]) > 0.5)\r\n\r\n#------------------------------------------------------------------------------\r\n# Save and Export Result\r\n#------------------------------------------------------------------------------\r\n\r\n# export backtest result summary\r\nfinal_df.groupby(['Curncy', 'Signal', 'Parameters', 'HoldingPeriod', \r\n 'Period', 'HitRate', 'TotalHits', 'CumReturn', \r\n 'MaxDrawdown']).sum().to_excel('WeeklySummary' + datetime.date.today().strftime('%Y%m%d') + '.xlsx')\r\n\r\n# save signals\r\nstore = pd.HDFStore('WeeklySignal' + datetime.date.today().strftime('%Y%m%d') + '.h5')\r\nstore['signal'] = final_df[final_df.Period == periodDict['t']].groupby(['Curncy', 'Signal', 'Parameters']).mean().reset_index()[['Curncy', 'Signal', 'Parameters', 'HitRate']] \r\nstore.close()\r\n \r\n# export result by curncy\r\nfor curncy in set(final_df.Curncy):\r\n print(curncy)\r\n curncy_df = final_df[final_df.Curncy == curncy]\r\n temp_df = curncy_df.groupby(['Curncy', 'Signal', 'Parameters', 'HoldingPeriod', \r\n 'Period', 'HitRate', 'TotalHits', 'CumReturn', 'MaxDrawdown']).sum()\r\n \r\n excel = os.path.join(os.getcwd(), 'Weekly', 'By Currency', curncy+'.xlsx')\r\n if not os.path.exists(os.path.dirname(excel)):\r\n os.makedirs(os.path.dirname(excel))\r\n temp_df.to_excel(excel)\r\n\r\n\r\nsignalList = ['Engulf0', 'InsideBar0', 'Hammer4', 'InsideBarComb0']\r\n \r\n# export result by signal\r\nfor curncy in set(final_df.Curncy):\r\n for signal in signalList:\r\n print(curncy + \":\" + signal)\r\n curncy_df = final_df[final_df.Curncy == curncy]\r\n signalIndex = np.array([signal in sig for sig in final_df[final_df.Curncy == curncy].Signal])\r\n if signalIndex.any() == True:\r\n curncy_df = curncy_df[signalIndex]\r\n temp_df = curncy_df.groupby(['Curncy', 'Signal', 'Parameters', 'HoldingPeriod', \r\n 'Period', 'HitRate', 'TotalHits', 'CumReturn', 'MaxDrawdown']).sum()\r\n \r\n excel = os.path.join(os.getcwd(), 'Weekly', 'By Signal' ,signal, curncy+'.xlsx')\r\n if not os.path.exists(os.path.dirname(excel)):\r\n os.makedirs(os.path.dirname(excel))\r\n temp_df.to_excel(excel)\r\n\r\n# print count\r\ncount_df = pd.DataFrame(columns = ['Curncy', 'Signal', 'Count'])\r\nfor curncy in set(final_df.Curncy):\r\n for signal in signalList:\r\n curncy_df = final_df[final_df.Curncy == curncy]\r\n signalIndex = np.array([signal in sig for sig in final_df[final_df.Curncy == curncy].Signal])\r\n if signalIndex.any() == True:\r\n curncy_df = curncy_df[signalIndex]\r\n temp_df = pd.DataFrame({'Curncy' : curncy,\r\n 'Signal' : signal,\r\n 'Count' : len(curncy_df)/8.0}, index = [0])\r\n count_df = count_df.append(temp_df, ignore_index = True)\r\n print(curncy + \",\" + signal + \",\" + str(len(curncy_df)/8.0))\r\n\r\ncount_df.groupby(['Curncy', 'Signal']).sum().to_excel('WeeklyCount' + datetime.date.today().strftime('%Y%m%d') + '.xlsx')","sub_path":"MagicCandle/optimization/analysisScriptWeekly.py","file_name":"analysisScriptWeekly.py","file_ext":"py","file_size_in_byte":6464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"509155460","text":"import numpy as np\r\nfrom sklearn import datasets\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.metrics import confusion_matrix, classification_report\r\n\r\nif __name__ == '__main__':\r\n iris = datasets.load_iris()\r\n X, y = iris['data'], iris['target'] # iris.data, iris.target\r\n\r\n # petal width만 데이터로 선택\r\n X = X[:, [3]] # (150, 1) 2D array\r\n\r\n # multi-class 분류: 0-setosa, 1-versicolor, 2-virginica\r\n log_reg = LogisticRegression() # 모델 생성\r\n log_reg.fit(X, y) # 모델 학습\r\n y_pred = log_reg.predict(X)\r\n\r\n conf_mat = confusion_matrix(y, y_pred)\r\n print(conf_mat)\r\n\r\n cls_report = classification_report(y, y_pred,\r\n target_names=iris.target_names)\r\n print(cls_report)\r\n\r\n sample0 = X[0]\r\n # sample0의 예측 확률\r\n sample0_probs = log_reg.predict_proba([sample0])\r\n print(sample0_probs, np.argmax(sample0_probs, axis=1))\r\n # [class0일 확률, class1일 확률, class2일 확률]\r\n print('class:', y_pred[0])\r\n\r\n bias, weights = log_reg.intercept_, log_reg.coef_\r\n print('\\nbias')\r\n print(bias)\r\n # [class0에서 필요한 bias, class1에서 필요한 bias, ...]\r\n print('\\nweights')\r\n print(weights)\r\n # [\r\n # [class0에서 필요한 theta1, theta2, ...]\r\n # [class1에서 필요한 theta1, theta2, ...]\r\n # ...\r\n # ]\r\n\r\n # sample0의 softmax 점수\r\n print('sample0:', sample0)\r\n # sample0가 class0(setosa)가 될 점수\r\n score_0 = bias[0] + weights[0, 0] * sample0[0]\r\n # sample0가 class1(versicolor)가 될 점수\r\n score_1 = bias[1] + weights[1, 0] * sample0[0]\r\n # sample0가 class2(virginica)가 될 점수\r\n score_2 = bias[2] + weights[2, 0] * sample0[0]\r\n print('\\nscores:')\r\n print(score_0, score_1, score_2)\r\n\r\n # sample0가 각 클래스에 속할 확률\r\n sum_scores = np.exp(score_0) + np.exp(score_1) + np.exp(score_2)\r\n p_0 = np.exp(score_0) / sum_scores\r\n p_1 = np.exp(score_1) / sum_scores\r\n p_2 = np.exp(score_2) / sum_scores\r\n print('\\nprobabilities:')\r\n print(p_0, p_1, p_2)\r\n\r\n # sample0의 cross-entropy\r\n print('\\nsample0의 실제 target 값:', y[0])\r\n y_0, y_1, y_2 = 1, 0, 0\r\n cross_ent = -(y_0 * np.log(p_0) + y_1 * np.log(p_1) +\r\n y_2 * np.log(p_2))\r\n print(cross_ent)\r\n\r\n\r\n","sub_path":"lab-ml/ch04/ex17_softmax.py","file_name":"ex17_softmax.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"126174082","text":"from django.http import HttpResponse\nfrom django.template import Template, Context\n# from Server.LoadEngine import load_template\n\ndef load_page(request):\n\tmain_page = Template(open('PhotoQuests/Pages/MainPage/index.html').read())\n\tcontext = Context({\n\t\t# \"header\": load_template('header.html'),\n\t\t# \"default_style_links\": load_template('default_style_links.html')\n\t})\n\tmain_page = main_page.render(context)\n\treturn HttpResponse(main_page)\n\n","sub_path":"PhotoQuests/Pages/MainPage/Handler.py","file_name":"Handler.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"223471397","text":"from __future__ import annotations\nfrom core.coingecko import EthPriceFetcher\nfrom datetime import datetime\nfrom utils.time import eth2_epoch_to_timestamp\nimport logging\n\nimport requests\nfrom core.constants import GWEI_PER_ETH, SLOTS_PER_EPOCH\nfrom clients.client import Client\n\nLIGHTHOUSE_ENDPOINTS = {\n \"validator_balances\": \"/eth/v1/beacon/states/{}/validator_balances\"\n}\n\nclass LighthouseClient(Client):\n def __init__(self, endpoint: str = \"http://localhost:5052\") -> None:\n super().__init__(endpoint)\n self.name = \"lighthouse\"\n\n def validator_balance(self, epoch: int, public_key: str) -> tuple[int, float]:\n if epoch < 0:\n raise Exception(\"Epoch must be positive\")\n\n eth_price = self.eth_price_at_epoch(epoch)\n\n slot_no = epoch * SLOTS_PER_EPOCH\n retries = 5\n logging.info(\"Fetching validator balance for {} at epoch {}...\".format(public_key, epoch))\n\n while retries != 0:\n r = requests.get(self.endpoint.geturl() + LIGHTHOUSE_ENDPOINTS[\"validator_balances\"].format(str(slot_no)), params={\n \"id\": public_key\n })\n if r.status_code == 200:\n break\n retries -= 1\n logging.info(\"validator_balance request failed with code {}, {} retries left\".format(str(r.status_code), str(retries)))\n\n if retries == 0:\n return 0, eth_price\n\n data = r.json().get(\"data\")\n if not data or len(data) != 1:\n logging.info(\"No validator balance for {} at epoch {}\".format(public_key, str(epoch)))\n return 0, eth_price\n\n balance = int(data[0].get(\"balance\")) / GWEI_PER_ETH\n\n return balance, eth_price\n","sub_path":"clients/lighthouse.py","file_name":"lighthouse.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"221053066","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api\n\n\n\n\nclass report(models.AbstractModel):\n _name = 'report.report_custom_template'\n \n def _get_picking(self):\n ordenes=self.env['stock.picking'].browse(self.env.context.get('active_ids'))\n return ordenes\n \n @api.model\n def render_html(self, docids, data=None):\n report_obj = self.env['report']\n report = report_obj._get_report_from_name('module.report_name')\n docargs = {\n 'doc_ids': docids,\n 'doc_model': report.model,\n 'docs': self._get_picking(),\n }\n return report_obj.render('module.report_name', docargs)\n","sub_path":"report/views/.ipynb_checkpoints/views-checkpoint.py","file_name":"views-checkpoint.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"29257331","text":"import socket\r\nimport threading\r\nimport sys\r\n\r\n# connection 192.168.0.102\r\nsoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\nsoc.bind((input(\"Enter the host ip address: \"), int(input(\"Enter the port number of the hosting: \"))))\r\nclient_list = [] # store all the active clients\r\nclient_name = [] # store corresponding nicknames\r\nFORMAT = 'utf-8'\r\nsoc.listen()\r\nprint(\"server online .... \\n\")\r\n\r\n\r\ndef broadcast(client, msg):\r\n if msg == \"LEFT\":\r\n for clients in client_list:\r\n if clients != client:\r\n clients.send(\r\n f\"[{str(client_name[client_list.index(client)])}] has left the chatroom...\".encode(FORMAT))\r\n else:\r\n for clients in client_list:\r\n if clients != client:\r\n clients.send((f\"[{str(client_name[client_list.index(client)])}]: \" + msg).encode(FORMAT))\r\n\r\n\r\ndef look_for_client():\r\n while True:\r\n client, address = soc.accept() # new client\r\n new_client = threading.Thread(target=accept_client, args=(client, address))\r\n new_client.start()\r\n\r\n\r\ndef accept_client(client, address):\r\n # client accepting\r\n print(f\"client address {address} has been connected. Total client : {threading.active_count() - 2}\")\r\n client.send(\"DONE\".encode(FORMAT)) # confirmation\r\n client.send(\"Enter the nickname:\".encode(FORMAT))\r\n name = client.recv(1024).decode(FORMAT)\r\n client_list.append(client)\r\n client_name.append(name)\r\n connected = True\r\n client.send(\"Nickname Registered....\".encode(FORMAT))\r\n\r\n # wait for client's message\r\n while connected:\r\n try:\r\n msg = client.recv(1024).decode(FORMAT)\r\n if not msg:\r\n index = client_list.index(client)\r\n print(f\"\"\"[{client_name[index]}] {address} disconnected... \r\nConnected client : {threading.active_count() - 3}\"\"\") # client left\r\n broadcast(client, \"LEFT\")\r\n client_name.pop(index)\r\n client_list.pop(index)\r\n break\r\n else:\r\n if msg != \"QUIT\":\r\n broadcast(client, msg)\r\n\r\n elif msg == \"QUIT\": # client wants to disconnect\r\n index = client_list.index(client)\r\n print(f\"\"\"[{client_name[index]}] {address} has left... \r\nConnected client : {threading.active_count() - 3}\"\"\")\r\n broadcast(client, \"LEFT\") # giving client's left notification\r\n client_list.pop(index) # remove client from client list\r\n\r\n client_name.pop(index) # remove client's name from name list\r\n client.shutdown(socket.SHUT_WR)\r\n\r\n client.close()\r\n connected = False\r\n sys.exit() # Thread close\r\n\r\n except Exception as e:\r\n print(e)\r\n try:\r\n print(f\"Remaining client : {threading.active_count() - 3}\")\r\n connected = False\r\n sys.exit() # Thread close\r\n except Exception as e:\r\n print(e)\r\n\r\n\r\nlook_thread = threading.Thread(target=look_for_client)\r\nlook_thread.start()\r\nlook_thread.join()\r\n","sub_path":"host.py","file_name":"host.py","file_ext":"py","file_size_in_byte":3210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"108490407","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nПодготовка списка слов для тренировки модели встраиваний слова wordchar2vector и\r\nи других моделей, где нужно оптимизировать данные под наши датасеты.\r\n\r\n(c) by Koziev Ilya для чат-бота https://github.com/Koziev/chatbot\r\n\"\"\"\r\n\r\nfrom __future__ import print_function\r\n\r\nimport codecs\r\nimport io\r\nimport itertools\r\nimport os\r\nfrom sys import platform\r\nimport pandas as pd\r\nimport csv\r\nimport yaml\r\n\r\nfrom ruchatbot.utils.tokenizer import Tokenizer\r\n\r\nresult_path = '../../tmp/known_words.txt' # путь к файлу, где будет сохранен полный список слов для обучения\r\nresult2_path = '../../tmp/dataset_words.txt' # путь к файлу со списком слов, которые употребляются в датасетах чатбота\r\n\r\ndata_folder = '../../data'\r\n\r\nn_misspelling_per_word = 0 # кол-во добавляемых вариантов с опечатками на одно исходное слово\r\n\r\n\r\n# Из этого текстового файла возьмем слова, на которых будем тренировать модель встраивания.\r\nif platform == \"win32\":\r\n corpus_path = r'f:\\Corpus\\word2vector\\ru\\SENTx.corpus.w2v.txt'\r\nelse:\r\n corpus_path = os.path.expanduser('~/corpora/Corpus/word2vector/ru/SENTx.corpus.w2v.txt')\r\n\r\nparaphrases_path = '../../data/premise_question_relevancy.csv'\r\nsynonymy_path = '../../data/synonymy_dataset.csv'\r\nsynonymy3_path = '../../data/synonymy_dataset3.csv'\r\npqa_path = '../../data/premise_question_answer.csv'\r\npqa_multy_path = '../../data/qa_multy.txt'\r\neval_path = '../../data/evaluate_relevancy.txt'\r\nsyntax_validator_path = '../../data/syntax_validator_dataset.csv'\r\npremises = ['../../data/profile_facts_1.dat', '../../data/profile_facts_2.dat']\r\ninterpretations = ['../../data/interpretation_auto_4.txt',\r\n '../../data/interpretation_auto_5.txt',\r\n '../../data/interpretation.txt',\r\n '../../data/entity_extraction.txt',\r\n '../../data/intents.txt']\r\n\r\npostagger_corpora = ['/home/inkoziev/polygon/rupostagger/tmp/samples.dat']\r\nyaml_path = '../../data/rules.yaml'\r\n\r\n\r\ngoodchars = set(u'абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ' +\r\n u'1234567890' +\r\n u'+.,-?!()[]{}*<>$&=~№/\\\\«»%:;|#\"\\'°')\r\n\r\nletters = set(u'абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ')\r\n\r\n\r\nstop_words = {u'_num_'}\r\n\r\n\r\nlexicon_words = set()\r\n\r\n\r\ndef is_punkt(c):\r\n return c in u'+.,-?!()[]{}*<>$&=~№/\\\\«»%:;|#\" \\'’–'\r\n\r\n\r\ndef normalize_word(word):\r\n return word.lower().replace(u'ё', u'е')\r\n\r\n\r\ndef collect_strings(d):\r\n res = []\r\n\r\n if isinstance(d, str):\r\n if u'[' not in d and u']' not in d:\r\n res.append(d)\r\n elif isinstance(d, list):\r\n for item in d:\r\n res.extend(collect_strings(item))\r\n elif isinstance(d, dict):\r\n for k, node in d.items():\r\n res.extend(collect_strings(node))\r\n\r\n return res\r\n\r\n\r\ndef is_good_word(word):\r\n if word in stop_words or word.startswith(u' ') or word == u'' or len(word) > 28 or len(word) == 0:\r\n return False\r\n\r\n if len(word) > 1:\r\n if is_punkt(word[0]):\r\n # В датасетах попадаются мусорные токены типа ((((, которые нет\r\n # смысл�� сохранять для тренировки wc2v модели.\r\n return False\r\n\r\n if any(c not in goodchars for c in word):\r\n return False\r\n\r\n return True\r\n\r\n\r\ntokenizer = Tokenizer()\r\ntokenizer.load()\r\n\r\nknown_words = set()\r\ndataset_words = set()\r\n\r\nwith io.open(os.path.join(data_folder, 'dict/word2lemma.dat'), 'r', encoding='utf-8') as rdr:\r\n for line in rdr:\r\n tx = line.replace(u'\\ufeff', '').strip().split('\\t')\r\n if len(tx) > 1:\r\n word = tx[0].lower().replace(' - ', '-')\r\n if word[0] in letters:\r\n lexicon_words.add(word)\r\n\r\nfor corpus in postagger_corpora:\r\n print(u'Processing {}'.format(corpus))\r\n with codecs.open(corpus, 'r', 'utf-8') as rdr:\r\n for line in rdr:\r\n line = line.strip()\r\n if line:\r\n tx = line.split('\\t')\r\n word = normalize_word(tx[1])\r\n known_words.add(word)\r\n dataset_words.add(word)\r\n\r\nprint('Parsing {}'.format(yaml_path))\r\nwith io.open(yaml_path, 'r', encoding='utf-8') as f:\r\n data = yaml.safe_load(f)\r\n strings = collect_strings(data)\r\n for phrase in strings:\r\n phrase = phrase.strip()\r\n if u'_' not in phrase and any((c in u'абвгдеёжзийклмнопрстуфхцчшщъыьэюя') for c in phrase):\r\n words = tokenizer.tokenize(phrase)\r\n known_words.update(words)\r\n dataset_words.update(words)\r\n\r\n# Берем слова из большого текстового файла, на котором тренируется w2v модели.\r\nprint('Parsing {}'.format(corpus_path))\r\nwith codecs.open(corpus_path, 'r', 'utf-8') as rdr:\r\n line_count = 0\r\n for line0 in rdr:\r\n line = line0.strip()\r\n words = [normalize_word(w) for w in line.split(u' ')]\r\n known_words.update(words)\r\n line_count += 1\r\n if line_count > 5000000:\r\n break\r\n\r\n# Добавим слова из основного тренировочного датасета\r\nprint('Parsing {}'.format(paraphrases_path))\r\ndf = pd.read_csv(paraphrases_path, encoding='utf-8', delimiter='\\t', quoting=3)\r\nfor phrase in itertools.chain(df['premise'].values, df['question'].values):\r\n words = tokenizer.tokenize(phrase.lower())\r\n known_words.update(words)\r\n dataset_words.update(words)\r\n\r\nprint('Parsing {}'.format(synonymy_path))\r\ndf = pd.read_csv(synonymy_path, encoding='utf-8', delimiter='\\t', quoting=3)\r\nfor phrase in itertools.chain(df['premise'].values, df['question'].values):\r\n words = tokenizer.tokenize(phrase.lower())\r\n known_words.update(words)\r\n dataset_words.update(words)\r\n\r\nprint('Parsing {}'.format(synonymy3_path))\r\ndf = pd.read_csv(synonymy3_path, encoding='utf-8', delimiter='\\t', quoting=3)\r\nfor phrase in itertools.chain(df['anchor'].values, df['positive'].values, df['negative'].values):\r\n words = tokenizer.tokenize(phrase.lower())\r\n known_words.update(words)\r\n dataset_words.update(words)\r\n\r\nprint('Parsing {}'.format(pqa_path))\r\ndf = pd.read_csv(pqa_path, encoding='utf-8', delimiter='\\t', quoting=3)\r\nfor phrase in itertools.chain(df['premise'].values, df['question'].values, df['answer'].values):\r\n words = tokenizer.tokenize(phrase)\r\n known_words.update(words)\r\n dataset_words.update(words)\r\n\r\nprint('Parsing {}'.format(syntax_validator_path))\r\ndf = pd.read_csv(syntax_validator_path, encoding='utf-8', delimiter='\\t', quoting=csv.QUOTE_NONE)\r\nfor phrase in df['sample'].values:\r\n words = phrase.split()\r\n known_words.update(words)\r\n dataset_words.update(words)\r\n\r\ndf = pd.read_csv('../../data/entities_dataset.tsv', encoding='utf-8', delimiter='\\t', quoting=3)\r\nfor phrase in df['phrase'].values:\r\n words = tokenizer.tokenize(phrase.lower())\r\n known_words.update(words)\r\n dataset_words.update(words)\r\n\r\ndf = pd.read_csv('../../data/relevancy_dataset3.csv', encoding='utf-8', delimiter='\\t', quoting=3)\r\nfor phrase in itertools.chain(df['anchor'].values, df['positive'].values, df['negative'].values):\r\n words = tokenizer.tokenize(phrase.lower())\r\n known_words.update(words)\r\n dataset_words.update(words)\r\n\r\nwith codecs.open('../../data/answer_relevancy_dataset.dat', 'r', 'utf-8') as rdr:\r\n for line in rdr:\r\n words = line.strip().split()\r\n known_words.update(words)\r\n dataset_words.update(words)\r\n\r\n# Добавим слова, которые употребляются в датасете для оценки\r\nprint('Parsing {}'.format(eval_path))\r\nwith codecs.open(eval_path, 'r', 'utf-8') as rdr:\r\n for line in rdr:\r\n phrase = line.replace(u'T:', u'').replace(u'Q:', u'').strip()\r\n words = tokenizer.tokenize(phrase)\r\n known_words.update(words)\r\n dataset_words.update(words)\r\n\r\n# Добавим слова, которые упот��ебляются в датасете с выводами\r\nprint('Parsing {}'.format(pqa_multy_path))\r\nwith codecs.open(pqa_multy_path, 'r', 'utf-8') as rdr:\r\n for line in rdr:\r\n phrase = line.replace(u'T:', u'').replace(u'Q:', u'').replace(u'A:', u'').strip()\r\n words = tokenizer.tokenize(phrase)\r\n known_words.update(words)\r\n dataset_words.update(words)\r\n\r\nfor p in premises:\r\n print('Parsing {}'.format(p))\r\n with codecs.open(p, 'r', 'utf-8') as rdr:\r\n for line in rdr:\r\n phrase = line.strip()\r\n if phrase.startswith('#'):\r\n continue\r\n words = tokenizer.tokenize(phrase)\r\n known_words.update(words)\r\n dataset_words.update(words)\r\n\r\n# Датасеты интерпретации\r\n# Датасеты определения интента и выделения сущностей\r\nfor p in interpretations:\r\n print('Parsing {}'.format(p))\r\n with codecs.open(p, 'r', 'utf-8') as rdr:\r\n for line in rdr:\r\n phrase2 = line.strip()\r\n if phrase2.startswith('#') or phrase2.startswith('entity'):\r\n continue\r\n for phrase in phrase2.split('|'):\r\n words = tokenizer.tokenize(phrase)\r\n known_words.update(words)\r\n dataset_words.update(words)\r\n\r\n\r\nprint('There are {} known words, {} dataset words'.format(len(known_words), len(dataset_words)))\r\n\r\nwith codecs.open(result_path, 'w', 'utf-8') as wrt:\r\n for word in sorted(known_words):\r\n if is_good_word(word):\r\n wrt.write(u'{}\\n'.format(word))\r\n\r\nwith codecs.open(result2_path, 'w', 'utf-8') as wrt:\r\n for word in sorted(dataset_words):\r\n if is_good_word(word):\r\n wrt.write(u'{}\\n'.format(word))\r\n","sub_path":"ruchatbot/preparation/prepare_wordchar_dataset.py","file_name":"prepare_wordchar_dataset.py","file_ext":"py","file_size_in_byte":10386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"599825866","text":"def sad_cycle(b,n):\n \"\"\"Function that determines the sad cycle of base b to power n.\n \n Args:\n b: Integer representing the base number.\n n: Integer representing the exponent.\n \n Returns:\n Returns a list containing the sad cycle.\n \"\"\"\n def determine_next(num):\n \"\"\"Determines the next number in the list.\n \n Args:\n num: Integer representing the current number in the list.\n \n Returns:\n Integer that is the next number in the list.\n \"\"\"\n str_num = str(num)\n output = 0\n for digit in str_num:\n output += int(digit)**n\n return output\n \n progress = [b]\n i = 0\n \n while True:\n progress.append(determine_next(progress[i]))\n i += 1\n \n if progress[-1] in progress[:-1]:\n lower = progress.index(progress[-1])\n cycle = progress[lower:i]\n return cycle\n\nl = [(2,6), (7,7), (14,3), (2,11)]\nfor pair in l:\n print('b = {}, n = {}\\n {}'.format(pair[0], pair[1],\n sad_cycle(pair[0], pair[1])))\n","sub_path":"3_sad_cycles.py","file_name":"3_sad_cycles.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"220769041","text":"#!/usr/bin/env python3\n\nimport sys, os, shutil\n\nclass files:\n\tls = \"\"\"export LS_OPTS=\\\"-C -w \\\\\\$COLUMNS --color=always --group-directories-first\\\"\nexport LC_COLLATE='C'\n\nalias {ls,LS,l,L}=\\\"\\\\ls \\$LS_OPTS\\\"\nalias la=\\\"\\ls -A\\\"\nalias ll=\\\"\\\\ls -l\\\"\nalias {lla,lal}=\\\"ls -lA\\\"\n\n## ls typos\nalias {ks,KS}='ls'\"\"\"\n\tgit = \"\"\"alias gc='git clone'\nalias gcm='git commit -m'\nalias ga='git add'\nalias gaa='git add --all'\nalias gcob='git checkout -b'\nalias gco='git checkout'\nalias gstat='git status'\nalias gpush='git push -u origin'\"\"\"\n\tmisc = \"\"\"alias n=nano\nalias e=echo\nalias less='less-r'\"\"\"\n\n\nHOME = os.getenv('HOME')\nDX2AKADIR = (HOME + '/.DX2/aliases/')\nLSAKA = (DX2AKADIR + 'ls.aka')\nGITAKA = (DX2AKADIR + 'git.aka')\nMISCAKA = (DX2AKADIR + 'misc.aka')\n\nif os.path.exists(LSAKA) == False:\n\tf = open(LSAKA, 'w')\n\tf.write(files.ls)\n\tf.close()\nelse:\n\tprint('ls.aka already exists')\n\nif os.path.exists(GITAKA) == False:\n\tf = open(GITAKA, 'w')\n\tf.write(files.git)\n\tf.close()\nelse:\n\tprint('git.aka already exists')\n\nif os.path.exists(MISCAKA) == False:\n\tf = open(MISCAKA, 'w')\n\tf.write(files.misc)\n\tf.close()\nelse:\n\tprint('ls.aka already exists')\n\n","sub_path":"addons/aliases.py","file_name":"aliases.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"112154166","text":"from django.db import models\n\n# Create your models here.\nclass Inversion(models.Model):\n id = models.AutoField(primary_key=True)\n descripcion = models.CharField(\"Motivo de Inversion\", max_length=400, default=\"\")\n interes = models.FloatField(\"Tasa de intres\",null=True, blank=True, default=None)\n monto = models.FloatField(\"Monto\",null=True, blank=True, default=None)\n creacion = models.DateField('Fecha agregada', auto_now_add=True)\n\n ","sub_path":"inversion/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"260992283","text":"#### per blocks Kronecker approximations (KFAC) ######\n# @author Melanie Ducoffe ############################\n# @date 26/04/2016 ###################################\n######################################################\nimport numpy as np\n#from invert_matrix import approximate_inverse\nfrom nys import approximate_inverse\n\n\n\"\"\"\ndef minibatch_product(M, batch_size, mean=True):\n\t# M => (minibatch, matrix)\n\tif M.ndim == 2:\n\t\tM = M.reshape((M.shape[0], 1, M.shape[1]))\n\n\tif mean:\n\t\tM = np.mean(M, axis=0)\n\t\tM_T = np.transpose(M)\n\t\treturn np.dot(M_T, M)\n\telse:\n\t\tM_T = M.transpose((0,2,1))\n\n\t\tR = None\n\t\tfor i in range(batch_size):\n\t\t\tif R is None:\n\t\t\t\tR = np.dot(M_T[i], M[i])\n\t\t\telse:\n\t\t\t\tR += np.dot(M_T[i], M[i])\n\t\treturn R\n\"\"\"\n\ndef kfac_labelled(X, Y, f, g, batch_size=32, dico=None):\n\tbatch_size = 32\n\tif len(X) < batch_size:\n\t\tbatch_size = len(X)\n\tfor minibatch in range(len(Y)/batch_size):\n\t\t# TO DO : need for reshape ???\n\t\tx_batch = X[minibatch*batch_size:(minibatch+1)*batch_size]\n\t\ty_batch = Y[minibatch*batch_size:(minibatch+1)*batch_size]\n\t\tdico_batch = f(x_batch, y_batch) # theano function + preprocessing blocks\n\t\tdico = {}\n\t\tfor key in dico_batch :\n\t\t\t\"\"\"\n\t\t\tif key[:-2]==\"conv_output\":\n\t\t\t\tdico_batch[key] = np.transpose(dico_batch[key], (1,0, 2,3))\n\t\t\t\tshape = dico_batch[key].shape\n\t\t\t\tdico_batch[key]=dico_batch[key].reshape((shape[0], shape[1], shape[2]*shape[3]))\n\t\t\t\tdico_batch[key]=dico_batch[key].reshape((shape[0], shape[1]*shape[2]*shape[3]))\n\t\t\t\tdico_batch[key] = np.transpose(dico_batch[key])\n\t\t\t\"\"\"\n\t\t\tif not(key) in dico:\n\t\t\t\tdico[key] = g(dico_batch[key])\n\t\t\telse:\n\t\t\t\tdico[key] += g(dico_batch[key])\n\t\t\t\n\t\tdel dico_batch\n\n\t# if len(Y) is not a multiple of batch_size, still take in account the last samples\n\tif len(Y) % batch_size !=0:\n\t\tminibatch = len(Y)/batch_size\n\t\tx_batch = X[minibatch*batch_size:]\n\t\ty_batch = Y[minibatch*batch_size:]\n\t\tdico_batch = f(x_batch, y_batch) # theano function + preprocessing blocks\n\t\tdico = {}\n\t\tfor key in dico_batch :\n\t\t\t\"\"\"\n\t\t\tif key[:-2]==\"conv_output\":\n\t\t\t\tdico_batch[key] = np.transpose(dico_batch[key], (1,0, 2,3))\n\t\t\t\tshape = dico_batch[key].shape\n\t\t\t\tdico_batch[key]=dico_batch[key].reshape((shape[0], shape[1], shape[2]*shape[3]))\n\t\t\t\tdico_batch[key]=dico_batch[key].reshape((shape[0], shape[1]*shape[2]*shape[3]))\n\t\t\t\tdico_batch[key] = np.transpose(dico_batch[key])\n\t\t\t\"\"\"\n\t\t\tif not(key) in dico:\n\t\t\t\tdico[key] = g(dico_batch[key])\n\t\t\telse:\n\t\t\t\tdico[key] += g(dico_batch[key])\n\n\treturn dico\n\ndef kfac_query(X, f_u, batch_size, dico=None):\n\n\tdico_batch = f(x_batch)\n\tqueries = []\n\tfor m in range(len(X)):\n\t\tempty_dico = dico([ (key, np.zeros_like(dico_batch[key][0])) for key in dico_batch.keys()])\n\t\tqueries.append(empty_dico)\n\treturn\n\t\"\"\"\n\tfor key in dico_batch.keys():\n\t\tdico_batch[key] = minibatch_product(dico_batch[key], batch_size, False)\n\t\t\n\tfor m in range(len(X)):\n\t\"\"\"\n\t\t\ndef kfac_unlabelled(X, f, g, batch_size=1024, dico=None):\n\tbatch_size = 32\n\tif len(X) < batch_size:\n\t\tbatch_size = len(X)\n\tfor minibatch in range(len(X)/batch_size):\n\t\t# TO DO : need for reshape ???\n\t\tx_batch = X[minibatch*batch_size:(minibatch+1)*batch_size]\n\t\tdico_batch = f(x_batch) # theano function + preprocessing blocks\n\t\tdico = {}\n\t\tfor key in dico_batch :\n\t\t\t\"\"\"\n\t\t\tif key[:-2]==\"conv_output\":\n\t\t\t\tdico_batch[key] = np.transpose(dico_batch[key], (1,0, 2,3))\n\t\t\t\tshape = dico_batch[key].shape\n\t\t\t\tdico_batch[key]=dico_batch[key].reshape((shape[0], shape[1], shape[2]*shape[3]))\n\t\t\t\tdico_batch[key]=dico_batch[key].reshape((shape[0], shape[1]*shape[2]*shape[3]))\n\t\t\t\tdico_batch[key] = np.transpose(dico_batch[key])\n\t\t\t\"\"\"\n\t\t\tif not(key) in dico:\n\t\t\t\tdico[key] = g(dico_batch[key])\n\t\t\telse:\n\t\t\t\tdico[key] += g(dico_batch[key])\n\t\t\t\n\t\tdel dico_batch\n\n\t# if len(Y) is not a multiple of batch_size, still take in account the last samples\n\tif len(X) % batch_size !=0:\n\t\tminibatch = len(X)/batch_size\n\t\tx_batch = X[minibatch*batch_size:]\n\t\tdico_batch = f(x_batch) # theano function + preprocessing blocks\n\t\tdico = {}\n\t\tfor key in dico_batch :\n\t\t\t\"\"\"\n\t\t\tif key[:-2]==\"conv_output\":\n\t\t\t\tdico_batch[key] = np.transpose(dico_batch[key], (1,0, 2,3))\n\t\t\t\tshape = dico_batch[key].shape\n\t\t\t\tdico_batch[key]=dico_batch[key].reshape((shape[0], shape[1], shape[2]*shape[3]))\n\t\t\t\tdico_batch[key]=dico_batch[key].reshape((shape[0], shape[1]*shape[2]*shape[3]))\n\t\t\t\tdico_batch[key] = np.transpose(dico_batch[key])\n\t\t\t\"\"\"\n\t\t\tif not(key) in dico:\n\t\t\t\tdico[key] = g(dico_batch[key])\n\t\t\telse:\n\t\t\t\tdico[key] += g(dico_batch[key])\n\n\treturn dico\n\n\ndef blocks_Fisher_Q(X, f_u, g):\n\tdico = f_u(X)\n\tfor key in dico.keys():\n\t\tdico[key] = g(dico[key])\n\timport pdb\n\tpdb.set_trace()\n\n\n# blocks for the Fisher of all data\ndef blocks_Fisher_P(X_L, Y_L, X_U, f_l, f_u, g, batch_size=512*2):\n\t#print 'dico_l'\n\tdico_l = kfac_labelled(X_L, Y_L, f_l, g, batch_size)\n\t#print 'dico_u'\n\tdico_u = kfac_unlabelled(X_U, f_u, g, batch_size)\n\tdico = {}\n\t#print 'union dico_l and dico_u'\n\tmean_inv = 1./(len(X_L)+len(X_U))\n\tfor key in dico_l:\n\t\tif key!=\"logistic_input\" and key!=\"logistic_output\":\n\t\t\tdico[key] = mean_inv*(dico_l[key]+ dico_u[key])\n\t\telse:\n\t\t\t# special preprocessing for logistic layer !\n\t\t\tdico[key] = dico_l[key]+dico_u[key]\n\t\t\t#raise NotImplementedError(\"logistic is not done yet but soon !\")\n\tif 'logistic_input' in dico.keys():\n\t\tdico['logistic_input'], dico['logistic_output'] = kronecker_logistic_decomposition(dico['logistic_input'],\n\t\t\t\t\t\t\t\t\t\t\t \tdico['logistic_output'])\n\t#print 'inverse'\n\tfor key in dico:\n\t\tshape = dico[key].shape[0]\n\t\tdico[key] = approximate_inverse(dico[key], np.min([shape, 2000]))\n\n\treturn dico, dico_l\n\n\n\"\"\"\ndef blocks_Fisher_Q(X, f_u):\n\t# for one sample only : for memory consumption we compute the coefficient directly\n\tassert len(X)==1, \"one sample only is required for memory consumption\"\n\tquery = kfac_unlabelled(X, f_u, 1)\n\tif \"logistic_input\" in query:\n\t\tquery[\"logistic_input\"] = query[\"logistic_input\"][0][0]\n\t\tquery[\"logistic_output\"] = query[\"logistic_output\"][0][0]\n\treturn query\n\"\"\"\n\n","sub_path":"old_version/kronecker_factor.py","file_name":"kronecker_factor.py","file_ext":"py","file_size_in_byte":5965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"506985260","text":"from django.conf.urls import url\n\nfrom home import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^app.json$', views.timetable, name='timetable'),\n url(r'^glossary$', views.tv_series_list, name='tv_series_list'),\n url(r'^list$', views.list, name='list'),\n\n url(r'^requestadaptation$', views.requestAdaptation, name='requestadaptation'),\n\n url(r'linkGameRanking', views.linkGameRanking, name='linkGameRanking'),\n\n url(r'adaptationList$', views.adaptation_list, name='adaptation_list'),\n url(r'^adaptationform$', views.adaptation_form, name='adaptation_form'),\n url(r'^adaptationdetail/(?P\\d+)$', views.adaptation_detail, name='adaptation_detail'),\n url(r'^valid/(?P\\d+)$', views.valid, name='valid'),\n url(r'^adapted/(?P\\d+)$', views.adapted, name='adapted'),\n url(r'^delete/(?P\\d+)$', views.delete, name='delete'),\n\n url(r'^adaptationapi$', views.adaptationapi, name='adaptationapi'),\n\n url(r'^v2ray$', views.v2ray, name='v2ray'),\n]\n","sub_path":"home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"314485257","text":"__author__ = 'Rhys'\n\n#Make sure that our module paths resolve when this is run as a daemon\nimport sys\nsys.path.insert(0, '/app')\nsys.path.insert(0, '/app/breaking')\n\nfrom batch.worker import *\nfrom apns import APNs, Payload\n\nclass InvalidDeviceException(WorkerException):\n\t@property\n\tdef action(self):\n\t\treturn self.deleteAction\n\nclass InvalidWorkException(WorkerException):\n\t@property\n\tdef action(self):\n\t\treturn self.deleteAction\n\nclass PushWorker(Worker):\n\t@property\n\tdef tube(self):\n\t\treturn \"push\"\n\n\tdef handle_job(self, work):\n\t\t#Process Pending Push Notifications\n\t\tif work is None or work.data is None:\n\t\t\traise InvalidWorkException()\n\n\t\tdevice = self.session.query(Device).filter(Device.uuid == work.message).first()\n\t\tif device is None:\n\t\t\traise InvalidDeviceException()\n\n\t\tif device.apnspushtoken is not None and device.apnspushtoken != \"\":\n\t\t\tcertfile = None\n\t\t\tkeyfile = None\n\n\t\t\tif __debug__:\n\t\t\t\tcertfile = 'certs/apns-dev-cert.pem'\n\t\t\t\tkeyfile = 'certs/apns-dev-key.pem'\n\t\t\telse:\n\t\t\t\tcertfile = 'certs/apns-prod-cert.pem'\n\t\t\t\tkeyfile = 'certs/apns-prod-key.pem'\n\n\t\t\tapns = APNs(use_sandbox=True, cert_file=certfile, key_file=keyfile)\n\t\t\tpayload = Payload()\n\t\t\tif 'alert' in work.data:\n\t\t\t\tpayload.alert = work.data['alert']\n\t\t\tif 'badge' in work.data:\n\t\t\t\tpayload.badge = work.data['badge']\n\t\t\tif 'sound' in work.data:\n\t\t\t\tpayload.sound = work.data['sound']\n\t\t\tif 'custom' in work.data:\n\t\t\t\tpayload.custom = work.data['custom']\n\n\t\t\tapns.gateway_server.send_notification(device.apnspushtoken, payload)\n\n\t\treturn True\n\ndef start():\n\tworker = PushWorker()\n\tworker.listen_forever()\n\nif __name__ == '__main__':\n\tif __debug__:\n\t\tstart()\n\telse:\n\t\timport daemon\n\n\t\twith daemon.DaemonContext():\n\t\t\tstart()\n","sub_path":"batch/pushworker.py","file_name":"pushworker.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"352298110","text":"\"\"\"GroupService API implemented using Google Cloud Endpoints.\"\"\"\n\n\nimport logging as logger\nimport endpoints\n\nfrom protorpc import messages\nfrom protorpc import message_types\nfrom protorpc import remote\n\nimport happy_meter.messages.group_messages as group_messages\n\n\n__author__ = 'jasonchilders'\n\n\nCLIENT_ID = 'happiemeter'\n\n\n# Replace GroupRequest with message_types.VoidMessage if no arguments will appear in the request body\nGROUP_HAPPINESS_RESOURCE_CONTAINER = endpoints.ResourceContainer(\n group_messages.GroupRequest, group_name=messages.StringField(1, variant=messages.Variant.STRING, required=True))\n\n#GROUP_HAPPINESS_RESOURCE_CONTAINER = endpoints.ResourceContainer(\n# message_types.VoidMessage,\n# group_name=messages.StringField(2, variant=messages.Variant.STRING,\n# required=True))\n\n\n@endpoints.api(name='groupservice', version='v1', description='Group Service API',\n allowed_client_ids=[CLIENT_ID, endpoints.API_EXPLORER_CLIENT_ID])\nclass GroupService(remote.Service):\n\n #@endpoints.method(YOUR_RESOURCE_CONTAINER, YourResponseMessageClass,\n # path='yourApi/{times}', http_method='GET',\n # name='greetings.getGreeting')\n\n #@endpoints.method(group_messages.GroupRequest, group_messages.GroupResponse, path='group', http_method='GET',\n # name='group.gethappiness')\n # invoke with: http://localhost:8080/_ah/api/groupservice/v1/group/${group_name}\n @endpoints.method(GROUP_HAPPINESS_RESOURCE_CONTAINER, group_messages.GroupResponse, path='group/{group_name}',\n http_method='GET', name='group.getgrouphappiness')\n def GetGroupHappiness(self, request):\n # do something with the request (like get the group's happiness\n group_name = request.group_name\n logger.info('getting happiness for group: %s' % group_name)\n group_message = group_messages.GroupResponse(group_name=group_name, happiness=350)\n return group_message\n\n #@endpoints.method(group_messages.GroupRequest, group_messages.GroupResponse, path='group', http_method='POST',\n # name='group.create')\n # invoke with: POST http://localhost:8080/_ah/api/groupservice/v1/group/create\n #\n # Content-Type: application/json\n # X-JavaScript-User-Agent: Google APIs Explorer\n #\n # {\n # \"group_name\": \"my friends\"\n # }\n @endpoints.method(GROUP_HAPPINESS_RESOURCE_CONTAINER, group_messages.GroupResponse, path='group/create',\n http_method='POST', name='group.create')\n def CreateGroup(self, request):\n # put the group into the database\n group_name = request.group_name\n logger.info('group_name: %s' % group_name)\n group_message = group_messages.GroupResponse(group_name=group_name, happiness=100)\n return group_message\n","sub_path":"happy_meter/services/group_service.py","file_name":"group_service.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"6545912","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.io.wavfile\nfrom bob import ap\n\n\nclass FeatureExtractor:\n def __init__(self):\n pass\n\n @staticmethod\n def plot(signal):\n plt.figure(1)\n plt.title('Signal Wave...')\n plt.plot(signal)\n plt.show()\n\n @staticmethod\n def mfcc(path):\n rate, signal = scipy.io.wavfile.read(str(path))\n # values to mfcc function\n win_length_ms = 20 # The window length of the cepstral analysis in milliseconds\n win_shift_ms = 10 # The window shift of the cepstral analysis in milliseconds\n n_filters = 24 # The number of filter bands\n n_ceps = 20 # The number of cepstral coefficients\n f_min = 0. # The minimal frequency of the filter bank\n f_max = 8000. # The maximal frequency of the filter bank\n delta_win = 2 # The integer delta value used for computing the first and second order derivatives\n pre_emphasis_coef = 0.97 # The coefficient used for the pre-emphasis\n dct_norm = True # A factor by which the cepstral coefficients are multiplied\n mel_scale = True # Tell whether cepstral features are extracted on a linear (LFCC) or Mel (MFCC) scale\n\n c = ap.Ceps(rate, win_length_ms, win_shift_ms, n_filters, n_ceps, f_min, f_max, delta_win, pre_emphasis_coef,\n mel_scale, dct_norm)\n csignal = np.cast['float'](signal) # vector should be in **float**\n mfcc = c(csignal)\n mfcc = np.delete(mfcc, 0, 1)\n\n plt.figure(1)\n plt.title('Signal Wave...')\n plt.plot(signal)\n plt.show()\n return mfcc\n\n\n'''\n# Plot the features\nfig = plt.figure()\nax = fig.gca(projection='3d')\nax.plot_surface(q_mfcc, q_mfcc, q_mfcc)\n'''\n","sub_path":"src/mfcc.py","file_name":"mfcc.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"605829582","text":"from .seemblock import SeemBlock\n\nfrom flor import flags\nfrom flor import shelf\nfrom flor.journal.entry import DataRef, DataVal, Bracket, LBRACKET, RBRACKET\n\nimport time\nfrom typing import Dict, List, Union\n\n\nclass WriteBlock(SeemBlock):\n scaling_factor = 1.38\n dynamic_identifiers: Dict[str, int] = dict()\n pda: List[Bracket] = []\n\n @staticmethod\n def step_into(block_name: str, probed=None):\n assert isinstance(block_name, str)\n dynamic_id = WriteBlock.dynamic_identifiers.get(block_name, 0)\n WriteBlock.dynamic_identifiers[block_name] = dynamic_id + 1\n\n lbracket = Bracket(\n block_name, dynamic_id, LBRACKET, predicate=True, timestamp=time.time()\n )\n WriteBlock.journal.as_tree().feed_entry(lbracket)\n\n WriteBlock.logger.append(lbracket)\n WriteBlock.pda.append(lbracket)\n return lbracket.predicate\n\n @staticmethod\n def end(*args, values=None):\n lbracket = WriteBlock.pda.pop()\n assert lbracket.timestamp is not None\n block_group = WriteBlock.journal.as_tree()[lbracket.sk]\n block = block_group.peek_block()\n assert block.global_key == lbracket.gk\n block_group.tick_execution(time.time() - lbracket.timestamp)\n if not args:\n rbracket = Bracket(lbracket.sk, lbracket.gk, RBRACKET)\n WriteBlock.journal.as_tree().feed_entry(rbracket)\n WriteBlock.logger.append(rbracket)\n block_group.set_mat_time(0)\n else:\n data_records = []\n\n start_time = time.time()\n for arg in args:\n data_record = val_to_record(arg, lbracket)\n data_records.append(data_record)\n block_group.should_time_mat() and data_record.would_mat()\n block_group.set_mat_time(time.time() - start_time)\n\n if WriteBlock._should_materialize(block_group):\n for data_record in data_records:\n WriteBlock.journal.as_tree().feed_entry(data_record)\n WriteBlock.logger.append(data_record)\n block_group.tick_materialization()\n else:\n rbracket = Bracket(lbracket.sk, lbracket.gk, RBRACKET)\n WriteBlock.journal.as_tree().feed_entry(rbracket)\n WriteBlock.logger.append(rbracket)\n\n @staticmethod\n def _should_materialize(block_group):\n assert block_group.materialization_time is not None\n assert block_group.computation_time is not None\n\n block = block_group.peek_block()\n\n # Must align successor checkpoints for periodic checkpointing\n if block.force_mat:\n return True\n\n # First consider atomic case (always/never)\n ratio = block_group.materialization_time / block_group.computation_time\n threshold = min(1 / (1 + WriteBlock.scaling_factor), flags.EPSILON)\n if ratio < threshold:\n return True\n\n # Then account for parallelism speedup\n if block.parent is None:\n threshold *= block_group.executions_count / (\n block_group.materializations_count + 1\n )\n if ratio < threshold:\n WriteBlock.journal.as_tree().add_sparse_checkpoint()\n block.force_mat_successors()\n return True\n\n return False\n\n\ndef val_to_record(arg, lbracket: Bracket) -> Union[DataRef, DataVal]:\n if hasattr(arg, \"state_dict\"):\n arg = getattr(arg, \"state_dict\")()\n\n if type(arg) in [type(None), int, float, bool, str]:\n return DataVal(lbracket.sk, lbracket.gk, arg)\n else:\n return DataRef(lbracket.sk, lbracket.gk, arg)\n","sub_path":"flor/skipblock/writeblock.py","file_name":"writeblock.py","file_ext":"py","file_size_in_byte":3677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"415614651","text":"from Classes import Stats\nfrom Classes import Item\nfrom Classes import Effect\n\nclass Actor:\n def __init__(self, name='Actor', **kwargs):\n self.name = name\n self.base_stats = Stats(**kwargs)\n self.items = []\n self.effects = []\n\n @property\n def stats(self):\n return (\n Stats.combine(\n self.base_stats,\n *self.items,\n *self.effects\n )\n )\n\n def drop_temp(self):\n [self.items.remove(x) for x in self.items if x.temporary]\n [self.effects.remove(x) for x in self.effects if x.temporary]\n\n def display(self):\n temp_stats = self.stats\n ll, nl = 80, len(self.name) # line length, name length\n print(\"\")\n print(f\"========== {self.name} \" + \"=\" * (ll - 10 - 6 - nl))\n print(\"Items: \", end='')\n [print('[' + str(i) + ']', end=' ') for i in self.items]\n print(\"\")\n print(\"Effects: \", end='')\n [print('[' + str(i) + ']', end=' ') for i in self.effects]\n print(\"\")\n print(self.stats)\n print(\"=\" * 80)\n\n\nif __name__ == '__main__':\n test_actor = Actor(name='Testronaut', strength=3,\n intellect=3, tenacity=3, speed=3)\n test_actor.items.append(Item('hose', strength=1))\n test_actor.items.append(Item('welder', tenacity=2))\n test_actor.effects.append(Effect(\"In Vacuum\", intellect=12))\n test_actor.display()\n","sub_path":"Classes/Actor.py","file_name":"Actor.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"538831994","text":"# -*- coding:utf-8 -*-\n\n# Scrapy settings for crawler project\n#\n# For simplicity, this file contains only the most important settings by\n# default. All the other settings are documented here:\n#\n# http://doc.scrapy.org/en/latest/topics/settings.html\n#\n\nBOT_NAME = 'crawler'\n\nSPIDER_MODULES = ['crawler.spiders']\nNEWSPIDER_MODULE = 'crawler.spiders'\n\n# Crawl responsibly by identifying yourself (and your website) on the user-agent\nUSER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'\n\nCOOKIES_ENABLED = False\nDOWNLOAD_DELAY = 0.1\nCONCURRENT_ITEMS = 400\nCONCURRENT_REQUESTS = 64\n#The maximum number of concurrent (ie. simultaneous) requests that will be performed to any single domain.\nCONCURRENT_REQUESTS_PER_DOMAIN = 256\nCONCURRENT_REQUESTS_PER_IP = 32\nDEPTH_LIMIT = 0\nDEPTH_PRIORITY = 0\nDNSCACHE_ENABLED = True\n\nNEWEST_TIME_THRESHOLD = 480 #2h, 120min\nNEWEST_PLAYED_THRESHOLD = 200\nHOTTEST_TIME_THRESHOLD = 10080 #7day, 10080min\nHOTTEST_PLAYED_THRESHOLD = 2000\nMAX_SEARCH_PAGE = 4 #max search page:no need to search all pages. but avaliable for auto spider\nMAX_MANUAL_SEARCH_PAGE = 40 #max manual search page:no need to search all pages. but avaliable for manual spider\nORDERED_PLAYED_THRESHOLD = 1000\n\nCATEGORY_FILTER_LIST = [u'新闻', u'资讯']\n\nITEM_PIPELINES = {\n 'crawler.pipelines.NewestItemPipeline': 90,\n 'crawler.pipelines.HottestItemPipeline': 91,\n 'crawler.pipelines.CategoryFilterPipeline': 92,\n 'crawler.pipelines.CategoryPipeline': 93,\n 'crawler.pipelines.MysqlStorePipeline': 100,\n}\n\nEXTENSIONS = {\n 'scrapy.contrib.feedexport.FeedExporter': None,\n}\n\n'''\n#AutoThrottle extension\nAUTOTHROTTLE_ENABLED = True\nAUTOTHROTTLE_START_DELAY = 3.0\nAUTOTHROTTLE_CONCURRENCY_CHECK_PERIOD = 10#How many responses should pass to perform concurrency adjustments.\n'''\n\n'''\nRETRY_HTTP_CODES = [500, 502, 503, 504, 400, 403, 404, 408]\nRETRY_TIMES = 5\n\nPROXY_LIST = ['/tmp/proxies.txt', '/tmp/proxies.txt.bak']\nUSER_AGENTS_LIST_FILE = '/tmp/ua.txt'\nDOWNLOADER_MIDDLEWARES = {\n 'scrapy.contrib.downloadermiddleware.useragent.UserAgentMiddleware' : None,\n 'crawler.middleware.ua_mw.RandomUserAgentMiddleware' :80,\n 'scrapy.contrib.downloadermiddleware.retry.RetryMiddleware': 90,\n 'crawler.middleware.proxy_mw.RandomProxy': 100,\n 'scrapy.contrib.downloadermiddleware.httpproxy.HttpProxyMiddleware': 110,\n}\n'''\n\nRETRY_HTTP_CODES = [500, 502, 503, 504, 400, 403, 404, 408]\nRETRY_TIMES = 5\n\nPROXY_HOST = 'http://125.88.157.200:40080'\nDOWNLOADER_MIDDLEWARES = {\n 'scrapy.contrib.downloadermiddleware.retry.RetryMiddleware': 90,\n 'crawler.middleware.proxy_mw.SpecificProxy': 100,\n #'scrapy.contrib.downloadermiddleware.httpproxy.HttpProxyMiddleware': 110,\n}\n\n\n\nLOG_LEVEL = 'INFO'\n'''\nLOG_ENABLED = True\nLOG_ENCODING = 'utf-8'\nLOG_FILE = '/tmp/crawler.log'\nLOG_STDOUT = True\n'''\n","sub_path":"crawler/crawler/crawler/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"650010345","text":"import json\n\nwith open(\"info.json\", \"r\") as f:\n birthdays_list = json.load(f)\n\ndef FindBirthdayPerson():\n name = input(\"Which is the name of the person you want to search for? \")\n try:\n if(birthdays_list[name]):\n print(birthdays_list[name])\n except KeyError:\n print(\"This person is not on the list \")\n\ndef AddNewPerson():\n name = input(\"Which person do you want to add in the database? \")\n date = input(\"Which is the birthday of the person you want to add? \")\n birthdays_list[name]=date\n with open('info.json', 'w') as f:\n json.dump(birthdays_list, f)\n\ndef DeletePerson():\n name = input(\"Which is the person you want to delete? \")\n del birthdays_list[name]\n with open('info.json', 'w') as f:\n json.dump(birthdays_list, f)\n\ndef PrintList():\n print(\"The current entries in the birthday list are: \")\n for key in birthdays_list:\n print(key.ljust(31),\":\",birthdays_list[key])\n\ndef SelectAction():\n action = input(\"What do you want to do? \").lower()\n if action == \"print\":\n PrintList()\n elif action == \"delete\":\n DeletePerson()\n elif action== \"find\":\n FindBirthdayPerson()\n elif action == \"add\":\n AddNewPerson()\n else:\n print(\"Please, try again, wrong action \")\n\n\nprint(\"Welcome to the birthday database, please select an action \")\nSelectAction()\n","sub_path":"ex34.py","file_name":"ex34.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"197339865","text":"import cv2 as cv\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n#import gambar\nasli = cv.imread('mario.jpg')\nimg = asli.copy()\nimg_g = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n\ntemp = cv.imread('tmp.jpg',0)\nw, h = temp.shape[::-1]\n\nres = cv.matchTemplate(img_g, temp, cv.TM_CCORR_NORMED)\nthreshold = 0.8\nloc = np.where( res >= threshold)\nfor pt in zip(*loc[::-1]):\n cv.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0,0,255), 1)\n\n#tampil gambar\ncv.imshow('ASLI', asli)\ncv.imshow('TEMPLATE', temp)\ncv.imshow('HASIL', img)\n\ncv.waitKey()\ncv.destroyAllWindows()\n","sub_path":"Python/MV/11.13.20 TEMPLATE MATCH.py","file_name":"11.13.20 TEMPLATE MATCH.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"95138887","text":"\"\"\"Palindrome\n\nThis module contains two functions that check\nwhether the argument is a palindrome or not.\n\n\"\"\"\n\n\ndef is_palindrome(string, spec=0):\n \"\"\"\n Check that given string is palindrome or not.\n\n :param string: Anything that can be converted to string line\n :param spec: 0 or 1. If 0 is given (by default), special symbols\n (spaces, comas, dots etc.) and cases are not\n considered.\n If 1 is given, function considers all symbols\n :return: Boolean\n\n \"\"\"\n\n if spec:\n _string = str(string)\n else:\n _string = ''.join([x for x in string\n if x.isalpha() or x.isdigit()]).lower()\n\n if string:\n _half_string = len(_string) // 2\n\n for i in range(0, _half_string):\n if _string[i] != _string[-1 - i]:\n return False\n\n return True\n else:\n return False\n\n\ndef is_int_palindrome(num):\n \"\"\"\n Check that given integer is palindrome or not.\n\n :param num: Anything that can be converted to integer\n :return: Boolean\n\n \"\"\"\n\n num = int(num)\n _old_num, _new_num = num, 0\n\n while num > 0:\n _new_num = _new_num * 10 + num % 10\n num //= 10\n\n if _old_num == _new_num:\n return True\n else:\n return False\n\n\nif __name__ == \"__main__\": # Checking\n _input = input(\"Please, enter some value: \")\n # print(is_palindrome(_input, spec=1))\n print(is_int_palindrome(_input))\n","sub_path":"AlgorithmsAndDS/palindrome.py","file_name":"palindrome.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"549821077","text":"#! /usr/bin/env python\n\nimport sys\nimport math\nimport logging\n#logging.getLogger(\"scapy.runtime\").setLevel(logging.ERROR)\nfrom scapy.all import send,Ether,IP,TCP,conf,ltoa,sendp\nfrom time import time,sleep\nfrom Queue import Queue\nfrom threading import Thread\nimport socket, struct\nimport argparse\n\n#sends packets to the IP to cover dataSize payload\ndef sendPerSecond(ip,dataSize,interface,mac):\n t=time();\n numPacket=int(dataSize/pktSize)\n plow=Ether(dst=mac)/IP(src=ip)/TCP();\n p=plow/completePayload;\n for i in range(numPacket):\n sendp(p,verbose=0,iface=interface)\n remainedData=dataSize-numPacket*pktSize\n if (remainedData>0):\n sendp(plow/''.zfill(remainedData),verbose=0,iface=interface)\n# print (time()-t)\n\n# load data from file f until timestamp is >=end\n# returns list of eligible packets and a packet that for the next round\ndef readFile(f,end):\n print(\"load until \"+str(end))\n global nextRoundPacket;\n output=[]\n if (nextRoundPacket[0]>0):\n output.append((nextRoundPacket[1],nextRoundPacket[2]));\n while (True):\n line=f.readline();\n if (len(line)==0):\n break;\n data=line.rstrip('\\n').split(',')\n t=int(data[0])/1000000;\n ip=int(data[1]);\n size=int(float(data[-1]));\n if (t>=end):\n nextRoundPacket=(t,ip,size)\n return output;\n output.append((ip,size));\n nextRoundPacket=(-1,0,0)\n return output;\n\n##############################################3\ndef findInterface():\n for r in conf.route.routes:\n if (r[3]!='lo'):\n return r[3];\n return '';\n\n###############################################\ndef fixRouting():\n for r in conf.route.routes:\n if (r[3]!='lo'):\n conf.route.delt(net=ltoa(r[0])+'/8',dev=r[3])\n conf.route.add(net='0.0.0.0/0',dev=r[3]);\n break;\n conf.route\n\n###########################################\ndef convertIP(ip):\n return socket.inet_ntoa(struct.pack('!L',ip));\n\n###########################3\ndef ip2long(ip):\n \"\"\"\n Convert an IP string to long\n \"\"\"\n packedIP = socket.inet_aton(ip)\n return struct.unpack(\"!L\", packedIP)[0]\n\n###########################\ndef getFirstTimestamp(filename):\n with open(filename,'r') as f:\n data=f.readline();\n return int(data.split(',')[0])/1000000\n\n#unsigned right binary shift\ndef rshift(val, n): return (val % 0x100000000) >> n\n\n#worker for multithreading\ndef worker():\n while True:\n (ip,size) = q.get()\n if (ip<0):\n q.task_done()\n return;\n sendPerSecond(convertIP(ip),size,interface,mac);\n q.task_done()\n#################################################################\ndef matchFilters(ip,srcFiltersZip):\n for d,w in srcFiltersZip: \n if (rshift(ip,w)==d):\n return True;\n return False; \n\n#################################################################\n#parse params\nparser = argparse.ArgumentParser(description='Generate traffic')\nparser.add_argument('--input', required=True)\nparser.add_argument('--srcFilter',default=['0.0.0.0/0'],nargs='*')\nparser.add_argument('--start',default=-1,type=int)\nparser.add_argument('--interface',default='')\nparser.add_argument('--mac',required=True)\n\nargs=vars(parser.parse_args());\ninputFile=args['input'];\nstartEvent=args['start'];\nmac=args['mac'];\nsrcFilters=args['srcFilter'];\nsrcFiltersZip=[];\nfor f in srcFilters:\n f2=f.split('/');\n if (len(f2)>1): #has a wildcard setting\n w=32-int(f2[1]);\n else:\n w=0;\n srcFiltersZip.append((rshift(ip2long(f2[0]),w),w));\n\ninterface=args['interface'];\nif (len(interface)==0):\n interface=findInterface();\n\n#constants\npktSize=1460\ncompletePayload=''.zfill(pktSize);\nnextRoundPacket=(-1,0,0);\nnum_worker_threads=2\n\nif (len(interface)==0):\n print(\"interface not found\");\n exit(1);\n#fixRouting(); //routing adds delay\n#print(conf.route)\n\ntimestamp=getFirstTimestamp(inputFile);\n\n#start workers\nq = Queue()\nfor i in range(num_worker_threads):\n t = Thread(target=worker)\n t.start()\ntry:\n with open(inputFile,'r') as f:\n while(True):\n t1=time();\n timestamp+=1;\n toSend=readFile(f,timestamp)\n if (len(toSend)==0):\n break;\n i=0;\n for ip,size in toSend:\n if (matchFilters(ip,srcFiltersZip)):\n i+=1;\n q.put((ip,size))\n# sendPerSecond(convertIP(ip),size);\n print('added '+str(i)+\" has now \"+str(q.qsize()))\n q.join();\n toSleep=1-(time()-t1);\n if (toSleep>0):\n sleep(toSleep);\n else:\n print('stay behind '+str(-toSleep));\n \nfinally:\n#instead of daemon let them finish clean\n for i in range(num_worker_threads):\n q.put((-1,0));\n\n q.join() # block until all tasks are done\n\n","sub_path":"scripts/generatecap/scapy/sendmanypkt2.py","file_name":"sendmanypkt2.py","file_ext":"py","file_size_in_byte":4613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"270238363","text":"# value of the first triangle number to have over five hundred divisors. \n# (1 and the number itself are counted as divisors)\n# should be 76576500\n# current alg computes in less than 5s\n\nimport math\n\ndef numberOfDivisors(n): # n >= 1\n count = 0\n for i in range(1, math.floor(math.sqrt(n))+1):\n if (n % i == 0):\n if (i**2 == n):\n count += 1\n else:\n count += 2\n return count\n\ntriangle = 1\ntriangleIndex = 1\n\nwhile (numberOfDivisors(triangle) < 500):\n triangleIndex += 1\n triangle += triangleIndex\n\nprint(triangle)","sub_path":"projectEuler/problem012.py","file_name":"problem012.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"300914478","text":"from avatar_sgg.dataset.ade20k import get_ade20k_split\nfrom avatar_sgg.config.util import get_config\nfrom avatar_sgg.image_retrieval.evaluation import compute_similarity, compute_average_similarity_against_generated_caption, \\\n compute_recall_on_category, compute_recall_johnson_feiefei, add_inferred_captions, merge_human_captions, \\\n use_merged_sequence, run_evaluation\nimport numpy as np\nimport os\n\n\n\n\nif __name__ == \"__main__\":\n print(\"Start\")\n output_dir = os.path.join(get_config()[\"output_dir\"], \"image_retrieval\")\n\n train, dev, test = get_ade20k_split()\n\n current = test\n threshold_list = [None]\n # This range has been chosen because the mean of the diagonal on the dev set was around 0.6X\n threshold_list.extend(np.linspace(0.55, 0.7, 15))\n\n eval_name = lambda caption_type, recall_type: f\"{caption_type}_{recall_type}\"\n ade20k_category_recall = \"ade20k_category_recall\"\n fei_fei_recall = \"feifei_johnson_recall\"\n\n human_caption = \"human_captions_query\"\n catr_caption = \"catr_captions_query\"\n merged_human_caption = \"merged_human_caption_catr_captions_query\"\n merged_sequences_captions = \"merged_sequences_catr_captions_query\"\n\n\n evaluation_name = eval_name(human_caption, fei_fei_recall)\n run_evaluation(evaluation_name, current, compute_similarity, threshold_list, compute_recall_johnson_feiefei,\n output_dir)\n\n evaluation_name = eval_name(human_caption, ade20k_category_recall)\n run_evaluation(evaluation_name, current, compute_similarity, threshold_list, compute_recall_on_category, output_dir)\n\n current_inferred_captions = add_inferred_captions(current)\n evaluation_name = eval_name(catr_caption, fei_fei_recall)\n run_evaluation(evaluation_name, current_inferred_captions, compute_average_similarity_against_generated_caption, threshold_list, compute_recall_johnson_feiefei,\n output_dir)\n\n evaluation_name = eval_name(catr_caption, ade20k_category_recall)\n run_evaluation(evaluation_name, current_inferred_captions, compute_average_similarity_against_generated_caption, threshold_list, compute_recall_on_category,\n output_dir)\n\n current_merged_human = merge_human_captions(current)\n evaluation_name = eval_name(merged_human_caption, fei_fei_recall)\n run_evaluation(evaluation_name, current_merged_human, compute_similarity, threshold_list, compute_recall_johnson_feiefei,\n output_dir)\n\n evaluation_name = eval_name(merged_human_caption, ade20k_category_recall)\n run_evaluation(evaluation_name, current_merged_human, compute_similarity, threshold_list, compute_recall_on_category, output_dir)\n\n\n current_merged_sequence = use_merged_sequence(current)\n evaluation_name = eval_name(merged_sequences_captions, fei_fei_recall)\n run_evaluation(evaluation_name, current_merged_sequence, compute_similarity, threshold_list, compute_recall_johnson_feiefei,\n output_dir)\n\n evaluation_name = eval_name(merged_sequences_captions, ade20k_category_recall)\n run_evaluation(evaluation_name, current_merged_sequence, compute_similarity, threshold_list, compute_recall_on_category, output_dir)\n\n\n print(\"Done\")\n","sub_path":"avatar_sgg/image_retrieval/baseline_ade20k.py","file_name":"baseline_ade20k.py","file_ext":"py","file_size_in_byte":3206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"288649286","text":"import device\nimport facts\n\n\nclass CommandFactory(object):\n \"\"\"\n CommandFactory takes a Device object and a list of NXAPI commands\n and runs them through the Facts processor returning the NXAPI\n result\n \"\"\"\n\n def __init__(self):\n self.device = None\n self.command_list = []\n self.cmd_response = {}\n\n def process_device(self, dev, commands):\n \"\"\"\n Receives a device object and command list and\n sends it to the Facts processor\n \"\"\"\n if isinstance(dev, device) and isinstance(commands, list):\n self.device = device\n self.commands = commands\n self.cmd_response = facts(self.device, self.commands)\n else:\n print(\"Invalid input to CommandFactory\")\n\n return self.cmd_response\n","sub_path":"L2Trace/cmdfactory.py","file_name":"cmdfactory.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"81224771","text":"from django.core.urlresolvers import reverse\nfrom django.test import TestCase\n\nfrom sherpa.apps.bladers.models import Blader\nfrom sherpa.apps.locations.models import City, Location\n\nfrom ..models import SpotType, Spot\n\n\ndef create_test_city():\n return City.objects.create(\n city='Newport',\n county='Washington',\n state='Minnesota',\n state_code='MN',\n country='United States',\n country_code='USA'\n )\n\n\ndef create_test_location():\n return Location.objects.create(\n latitude=44.12936,\n longitude=-90.74536,\n house='438',\n street='4th ave',\n neighborhood='West Side',\n suburb='Suburb',\n postal='55055',\n uzip='55055',\n city=create_test_city(),\n location_radius=400,\n location_quality=99\n )\n\n\ndef create_test_spottype():\n return SpotType.objects.create(obstacle='ledge', specific_type='angle iron')\n\n\nclass SpotTypeTest(TestCase):\n def setUp(self):\n self.spottype = create_test_spottype()\n\n def test_model_creation(self):\n self.assertTrue(isinstance(self.spottype, SpotType))\n\n\nclass SpotTest(TestCase):\n def setUp(self):\n self.user = Blader.objects.create(email='test@test.com', username='test')\n self.location = create_test_location()\n self.spottype = create_test_spottype()\n self.spot = Spot.objects.create(\n name='Test Spot',\n obstacle=self.spottype,\n location=self.location,\n device='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31',\n created_by=self.user\n )\n\n def test_model_creation(self):\n self.assertTrue(isinstance(self.spot, Spot))\n self.assertEqual(self.spot.__unicode__(), self.spot.name)\n\n def test_model_slug(self):\n self.assertFalse(all(char.isspace() for char in self.spot.slug))\n\n def test_model_permalink(self):\n self.assertEqual(self.spot.get_absolute_url(),\n reverse('spots_spot_detail', kwargs={'slug': self.spot.slug}))\n","sub_path":"sherpa/apps/spots/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"456735205","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\n'''\n@author: jack\n@license: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited.\n@contact: cn5036520@163.com\n@software: sign\n@file: logs3.py\n@time: 2019/4/4 5:58\n@desc:\n'''\n\n\n\"\"\"\n思路:\n0、导包\n 日志级别\n1、新建对象-日志的父类\n 设置日志父类对象的日志级别\n2、新建对象-文件handler\n 设置文件handler对象的日志级别\n3、新建对象-控制台handler\n 设置控制台handler对象的日志级别\n4、设置日志格式\n 日志格式生效\n5、将文件handler和控制台handler会报给大领导-日志父类对象\n6、定义日志的自定义消息--日志格式中的message\n\"\"\"\n\nimport logging\nimport os\n\n# 日志级别 CRITICAL(FATAL)>ERROR>WARN(WARNING)>INFO>DEBUG #日志级别必须是大写字母\n # 50>40 >30 >20 >10\n\n# 1、新建对象-日志的父类\n# 设置日志父类对象的日志级别\n# logger1 = logging.getLogger()\nlogger1 = logging.getLogger(\"my_logger1\")\nlogger1.setLevel(20)\n# logger1.setLevel(logging.INFO)\n\n# 2、新建对象-文件handler\n# 设置文件handler对象的日志级别\npath1 = r\"D:\\PycharmProjects\\xiaoqiang\\base_181027\\a1接口层框架设计1-0326\\src34\\logs\\log32.txt\"\nfh1 = logging.FileHandler(path1)\nfh1.setLevel(30)\n# fh1.setLevel(logging.INFO)\n\n# 3、新建对象-控制台handler\n# 设置控制台handler对象的日志级别\nsh1 = logging.StreamHandler()\nsh1.setLevel(30)\n# sh1.setLevel(logging.INFO)\n\n# 4、设置日志格式\n# 日志格式生效\n# log_format1 = \"%(asctime)s || %(filename)s || [lineno:%(lineno)s] || %(levername)s || %(message)s \"\n# #注意: levername拼写错误,应该是levelname 这里最好通过复制粘贴Formatter类源码的写法,避免拼写错误\n# 报错 KeyError: 'levername'\n# Logged from file logs32.py, line 73\nlog_format1 = \"%(asctime)s || %(filename)s || [lineno:%(lineno)s] || %(levelname)s || %(message)s \"\nformatter1 = logging.Formatter(log_format1) #日志格式生效\n\nfh1.setFormatter(formatter1) #给文件handler设置日志格式\nsh1.setFormatter(formatter1) #给控制台handler设置日志格式\n\n# 5、将文件handler和控制台handler会报给大领导-日志父类对象\nlogger1.addHandler(fh1)\nlogger1.addHandler(sh1)\n\n# 6、定义日志的自定义消息--日志格式中的message\n# logger1.error(\"打印详细错误信息\") #对应日志格式中的message\n# logger1.error(\"打印具体的日志error错误信息\")\n# logger1.debug(\"打印具体的日志debug调试信息\")\nlogger1.info(\"打印具体的日志info信息\")\n# logger1.warn(\"打印具体的日志warn信息\")\n# logger1.critical(\"打印具体的日志critical信息\")\n\n\"\"\"\n总结:\n1、关于日志级别,当父类的日志级别和子类(文件handler、控制台handler)不同的时候\n 哪个日志级别严格(数字更大的为准),以哪个为准\n 例如1:父类的日志级别是20--INFO\n 子类-文件handler的日志级别设置是30-WARN\n 此时,WARN级别的日志可以输出,而INFO级别的日志无法输出\n 例如2:父类的日志级别是30--WARN\n 子类-文件handler的日志级别设置是20-INFO\n 此时,WARN级别的日志可以输出,而INFO级别的日志无法输出\n\n\"\"\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"other/a1接口层框架设计1-0326/src34/commons/logs32-2.py","file_name":"logs32-2.py","file_ext":"py","file_size_in_byte":3351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"287472200","text":"##===============================================\n## Jiadong Mai (20557203)\n## CS 116 Winter 2018\n## Assignment 08, Question 4\n##===============================================\n\n#q4\nimport math\nimport check\n\nacute_cat = 'ACUTE'\nobtuse_cat = 'OBTUSE'\nright_cat = 'RIGHT'\npar_cat = 'PARALLEL'\n\nclass Vector:\n '''Fields: x(Int), y(Int)'''\n def __init__(self,xVal,yVal):\n self.x = xVal\n self.y = yVal\n \n def __eq__(self,other):\n if isinstance(other,Vector):\n return self.x == other.x and self.y == other.y\n else:\n return False\n \n def __repr__(self):\n return \"Vector({0},{1})\".format(self.x,self.y)\n \n def __add__(self,other):\n return Vector(self.x+other.x, self.y+other.y)\n \n def __mul__(self,other):\n return self.x*other.x + self.y*other.y\n \n def length(self):\n return math.sqrt(self.x**2 + self.y**2)\n \n def scale(self,k):\n self.x *= k\n self.y *= k\n\n\n# classify_angles(lov, vec): consumes a list of non_zero vectors, lov, and\n# a single non-zero vector, vec, and returns a dictionary contain 4 keys, \n# 'ACUTE', 'OBTUSE', 'RIGHT', 'PARALLEL'\n# classify_angles: (listof Vector) Vector -> (dictof Str (listof Vector))\n# Requires:\n# both lov and vec are non-zero vectors\n# Examples:\n# if vecs = [Vector(-4,0), Vector(0,-7), Vector(10,5), Vector(-1,7),\\\n# Vector(-5,-3), Vector(4,-6), Vector(-1,7),Vector(-9,3)]\n# classify_angles(vecs ,Vector(3,0)) => {'ACUTE': [Vector(10,5), Vector(4,-6)],\n# 'OBTUSE': [Vector(-1,7), Vector(-5,-3), Vector(-9,3)],\n# 'RIGHT': [Vector(0,-7)], 'PARALLEL': [Vector(-4,0)]}\n# classify_angles(vecs ,Vector(-2,3)) => {'ACUTE': [Vector(-4,0), Vector(-1,7), Vector(-5,-3), Vector(-9,3)],\n# 'OBTUSE': [Vector(0,-7), Vector(10,5)], 'RIGHT': [],\n# 'PARALLEL': [Vector(4,-6)]}\n\ndef classify_angles(lov,vec):\n result = {acute_cat: [], obtuse_cat: [], right_cat: [], par_cat: []}\n \n for k in lov:\n cos = (k * vec) / (k.length() * vec.length())\n if (k*vec)**2 == (k.x**2 + k.y**2)*(vec.x**2 + vec.y**2):\n if k in result[par_cat]:\n None\n else:\n result[par_cat].append(k)\n elif -10: self.xyz2val[(x,y,z)] = val\n log.info(str(len(self.xyz2val))+\" nonzero voxels obtained\")\n\n def fill_dummy(self):\n \"\"\"Fills in image with some dummy stuff.\"\"\"\n self.height = 100\n self.width = 100\n self.depth = 100\n for i in xrange(-50, 50):\n self.xyz2val[(i,0,0)] = abs(i)\n self.xyz2val[(0,i,0)] = abs(i)\n self.xyz2val[(0,0,i)] = abs(i)\n\n def clone(self):\n log.dbg(\"cloning SparseImage3D\")\n o = SparseImage3D()\n o.width = self.width\n o.height = self.height\n o.depth = self.depth\n o.xyz2val = dict( (xyz, val) for xyz, val in self.xyz2val.iteritems() )\n return o\n\n def limit_size(self, numvoxels=10000):\n \"\"\"Returns SparseImage3D built out of random subset of voxels of this image.\"\"\"\n newim = SparseImage3D()\n newim.width = self.width\n newim.height = self.height\n newim.depth = self.depth\n newim.xyz2val = dict( random.sample(list(self.xyz2val.iteritems()), min(numvoxels, len(self.xyz2val))) )\n log.info(\"number of voxels = \"+str(len(newim.xyz2val)))\n return newim\n \n def xs(self): \n return list(xyz[0] for xyz in self.xyz2val)\n\n def ys(self): \n return list(xyz[1] for xyz in self.xyz2val)\n\n def zs(self): \n return list(xyz[2] for xyz in self.xyz2val)\n\n def vals(self): \n return list(val for xyz,val in self.xyz2val.iteritems())\n\n def store(self, f):\n \"\"\"Writes content into file f.\"\"\"\n f.write(\"#dimensions:\\t\"+str(self.width)+\"\\t\"+str(self.height)+\"\\t\"+str(self.depth)+\"\\n\")\n f.write(\"x\\ty\\tz\\tvalue\\n\") \n for xyz,val in self.xyz2val.iteritems():\n f.write(str(xyz[0])); f.write(\"\\t\")\n f.write(str(xyz[1])); f.write(\"\\t\")\n f.write(str(xyz[2])); f.write(\"\\t\")\n f.write(str(int(val))); f.write(\"\\n\")\n \n\n def load(self, f):\n \"\"\"Loads content from file f.\"\"\"\n header_skipped = False\n self.xyz2val = {}\n for line in f.xreadlines():\n if line.startswith(\"#dimensions\"):\n p = line.strip().split(\"\\t\")\n self.width = int(p[1])\n self.height = int(p[2])\n self.depth = int(p[3])\n elif line.startswith(\"#\"): pass\n else:\n if not header_skipped: header_skipped=True; continue #skip header\n p = line.strip().split(\"\\t\")\n x = int(p[0])\n y = int(p[1])\n z = int(p[2])\n v = int(p[3])\n self.xyz2val[(x,y,z)] = v\n log.dbg(self.descritption())\n\n\n def xyz_array(self):\n xyz_array = np.zeros( (len(self.xyz2val), 3) )\n for ix, xyz in enumerate(self.xyz2val):\n xyz_array[ix][0] = xyz[0]\n xyz_array[ix][1] = xyz[1]\n xyz_array[ix][2] = xyz[2]\n return xyz_array\n\n# def dbscan_segmentation(self):\n# D = distance.squareform(distance.pdist(self.xyz_array()))\n# S = 1 - (D / np.max(D))\n# db = DBSCAN(eps=0.95, min_samples=10).fit(S)\n# core_samples = db.core_sample_indices_\n# labels = db.labels_\n\n # Number of clusters in labels, ignoring noise if present.\n# n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)\n\n# print('Estimated number of clusters: %d' % n_clusters_)\n# print len(labels),str(labels)[:100]\n# print len(core_samples),min(core_samples),max(core_samples),str(core_samples)[:100]\n\n def resample_z(self, times):\n \"\"\"Repeats all (x,y)-planes several times.\"\"\"\n log.info(\"resampling (x,y)-planes \"+str(times)+\" times along z-axis.\")\n self.depth = int( self.depth * times )\n new_xyz2val = {}\n for xyz,val in self.xyz2val.iteritems():\n for offset in xrange(times):\n new_xyz = xyz[0],xyz[1],int(round(times*xyz[2]+offset))\n new_xyz2val[new_xyz] = val\n self.xyz2val = new_xyz2val\n\n def descritption(self):\n return (\"[SparseImage3D] height=\"+str(self.height)+\" width=\"+str(self.width)+\" depth=\"+str(self.depth)+\" non-zero voxels=\"+str(len(self.xyz2val)))\n\n def hist(self, title='Histogram of voxels in channel', color='red', xlabel='Channel level', ylabel='Number of voxels'):\n \"\"\"Draws histogram of channel levels.\"\"\"\n pyplot.hist(self.xyz2val.values(), bins=255, facecolor=color); \n pyplot.title(title)\n pyplot.xlabel(xlabel); pyplot.ylabel(ylabel)\n pyplot.show()\n\n def build_hist(self):\n \"\"\"Returns dictionary {level: count}.\"\"\"\n h = {}\n for v in self.xyz2val.values():\n h[v] = h.get(v,0) + 1\n return h\n\n def show(self, title=\"\", colormap = cm.cool): \n \"\"\"Displays 3D plot of image.\"\"\"\n fig = pyplot.figure()\n a3d = Axes3D(fig)\n a3d.scatter(self.xs(), self.ys(), self.zs(), zdir='z', s=5, c=self.vals(), cmap = colormap, marker='x')\n pyplot.title(title)\n pyplot.xlabel('x'); pyplot.ylabel('y'); \n pyplot.show()\n\n def get_xy_plane(self, z):\n \"\"\"Returns single cross-section of the image for selected z.\"\"\"\n planearray = np.zeros((self.width, self.height))\n for xyz,val in self.xyz2val.iteritems():\n if xyz[2]!=z: continue\n planearray[xyz[1]][xyz[0]] = val\n return planearray\n\n\n def get_xy_plane_rgb(self, z, colormap = COLORMAP_GRAYSCALE):\n \"\"\"Returns single cross-section of the image for selected z.\"\"\"\n planearray = np.zeros((self.width, self.height, 3), dtype='uint8') #np.ndarray(shape=(self.width, self.height, 3), dtype=np.dtype('b')) #\n for xyz,val in self.xyz2val.iteritems():\n if xyz[2]!=z: continue\n r,g,b = colormap.get(val, (127,127,127))\n planearray[xyz[1]][xyz[0]][0] = r\n planearray[xyz[1]][xyz[0]][1] = g\n planearray[xyz[1]][xyz[0]][2] = b\n return planearray\n \n def fit_range_levels(self, minlevel=0, maxlevel=255):\n \"\"\"Moves/scales levels of voxels to fit range [minlevel, maxlevel].\"\"\" \n data = self.xyz2val.values(); minv = min(data); maxv = max(data) \n log.dbg(\"minv=\"+str(minv)+\" maxv=\"+str(maxv))\n scale = float(maxlevel-minlevel) / float(maxv-minv)\n for xyz,val in self.xyz2val.iteritems():\n self.xyz2val[xyz] = int( (self.xyz2val[xyz]-minv)*scale + minlevel )\n #data = self.data(); minv = min(data); maxv = max(data) \n #log.dbg(\"new minv=\"+str(minv)+\" new maxv=\"+str(maxv))\n log.dbg(\"new minv=\"+str(minlevel)+\" new maxv=\"+str(maxlevel))\n\n def normalize(self, newmean=127.0, newstd=40.0):\n \"\"\"Alters voxels values that mean is equal to ~newmean and sd is equal to ~newstd.\"\"\"\n m = np.mean( self.xyz2val.values() ) \n s = np.std( self.xyz2val.values() )\n log.info(\"old mean=\"+str(m)+\" old std=\"+str(s))\n for xyz,val in self.xyz2val.iteritems():\n self.xyz2val[xyz] = int( round( int( min(max(newmean + newstd * float(val - m) / s, 0.0), 255.0) ) ) )\n\n m = np.mean( self.xyz2val.values() ) \n s = np.std( self.xyz2val.values() )\n log.info(\"new mean=\"+str(m)+\" new std=\"+str(s))\n\n def xnormalize(self, newm=100.0, news=400.0, smooth_width=10):\n \"\"\"Alters voxels values that gauss center position is equal to ~newm and sd is equal to ~news.\"\"\"\n m,s = self.get_ms_stats(smooth_width)\n log.info(\"m=\"+str(m)+\" s=\"+str(s))\n log.info(\"required m=\"+str(newm)+\" required s=\"+str(news))\n\n for xyz,val in self.xyz2val.iteritems():\n newval = int( round( newm + float(val-m)/s*news ) )\n newval = max(0, newval) \n self.xyz2val[xyz] = newval\n\n m,s = self.get_ms_stats(smooth_width*float(news)/s)\n log.info(\"newm=\"+str(m)+\" news=\"+str(s))\n\n\n def threshold(self, level=127):\n \"\"\"Removes voxels with level under thershold.\"\"\"\n self.xyz2val = dict( (xyz,val) for xyz,val in self.xyz2val.iteritems() if val>=level)\n return self\n\n def get_voxels_num(self):\n return len(self.xyz2val)\n\n def get_voxels_levels_num(self):\n return len(set(self.xyz2val.values()))\n\n def get_ms_stats(self, smooth_width = 10):\n \"\"\"Return center and sd of (assumed to be gaussian!) histogram.\"\"\"\n hist = self.build_hist()\n bins = range(max(hist.keys())+1)\n vals = list(hist.get(k,0) for k in bins) \n\n vals = smooth_hist(vals, smooth_width)\n\n m = get_max_bin(bins, vals)\n s = get_right_sd(bins, vals)\n return m,s\n\n\n\n","sub_path":"sparseimage3d.py","file_name":"sparseimage3d.py","file_ext":"py","file_size_in_byte":9835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"390129508","text":"#!/usr/bin/python3\nimport os\nimport json\nimport time\nimport datetime\nimport requests\nimport argparse\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom typing import Optional\nimport numpy as np\nimport cv2\nfrom pytz import timezone\n\n\nclass SlackRequester:\n def __init__(self, url: Optional[str]):\n self.url = url\n\n def send_message(self, message: str):\n slack_response = requests.request(\"POST\", self.url, json={\"text\": message})\n\n\ndef get_crowd_percentage(image):\n image = cv2.imread(image)\n # cv2.imshow('image',image)\n # define the list of boundaries\n boundaries = [\n # G B R G B R\n # >= >= >= <= <= <=\n ([190, 190, 190], [254, 254, 254]) # white is 255 - in between\n ]\n\n # loop over the boundaries\n for (lower, upper) in boundaries:\n # create NumPy arrays from the boundaries\n lower = np.array(lower, dtype=\"uint8\")\n upper = np.array(upper, dtype=\"uint8\")\n # find the colors within the specified boundaries and apply\n # the mask\n mask = cv2.inRange(image, lower, upper)\n output = cv2.bitwise_and(image, image, mask=mask)\n # show the images\n # cv2.imshow(\"images\", output)\n # cv2.waitKey(0)\n height = len(output)\n length = len(output[int(height / 2)])\n progress = 0\n bar_offset = 1 # EDIT THIS WAS 7 BUT SCREENSHOT OF ELEMENT WITH NEW SITE IS 1- screenshot webelement has 7 pixels on the left before bars starts\n # loop through the horizontal pixels on the midline\n # increment until the first not black pixel is found.\n for x_pixel_bgr in output[int(height / 2)]:\n if not np.any(x_pixel_bgr):\n progress += 1\n else:\n break\n total_x_pixels = length - bar_offset\n x_pixels_until_gray_bar = max(progress - bar_offset, 0)\n return x_pixels_until_gray_bar, total_x_pixels\n\n\neastern = timezone(\"US/Eastern\")\nprint(f\"[*] {datetime.datetime.now(eastern)} :: Parsing cli options\")\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--poll\", type=int, default=3600)\nparser.add_argument(\n \"--image\", help=\"path to the image\", type=str, default=\"screen_shot.png\"\n)\n\nargs = parser.parse_args()\npoll = args.poll\nimage_path = args.image\n\nprint(f\"[*] {datetime.datetime.now(eastern)} :: Reading config\")\ncurrent_directory = os.path.dirname(os.path.realpath(__file__))\nwith open(f\"{current_directory}/config.json\") as json_file:\n config_data = json.load(json_file)\nslack_webhook_url = config_data.get(\"webhook_url\")\nslack_requester = SlackRequester(slack_webhook_url)\n\nslack_requester.send_message(\n f\" *{datetime.datetime.now(eastern)} Eastern* - initializing pf crowd bot\"\n)\n\nprint(f\"[*] {datetime.datetime.now(eastern)} :: Setting up webdriver options\")\noptions = Options()\noptions.headless = True\n# start-maximized flag doesnt work in headless - makes sense; instead explicitly set\n# options.add_argument(\"--start-maximized\")\noptions.add_argument(\"--window-size=1440x900\")\n\ntotal_bars = (\n 20 # this is the total number of bars in the graphic. ie. each bar worth 5%\n)\n\nprint(f\"[*] {datetime.datetime.now(eastern)} :: Initializing webdriver\")\ndriver = webdriver.Chrome(options=options)\n# driver.delete_all_cookies()\nurl = \"https://www.planetfitness.com/gyms/danvers-ma\"\nrunning = True\nwhile running:\n try:\n day = datetime.datetime.now(eastern).strftime(\"%A\")\n print(f\"[*] {datetime.datetime.now(eastern)} :: Visiting...\")\n driver.get(url)\n time.sleep(1)\n print(\n f\"[*] {datetime.datetime.now(eastern)} :: Finding current day ({day}), clicking and screenshot whole div...\"\n )\n try:\n day_btn = driver.find_element_by_id(day)\n day_btn.click()\n complete_crowd_div = driver.find_element_by_id(\"CrowdMeter\")\n complete_crowd_div.screenshot(\"complete_crowd.png\")\n except Exception as exc:\n print(\n f\"[!] {datetime.datetime.now(eastern)} :: Error in finding specific day element and clicking, screenshotting the crowd div: {exc}\"\n )\n try:\n # lol no opencv needed just grab number of masked bars\n crowd_bar_mask = driver.find_element_by_id(\"mask\")\n cap_bars = crowd_bar_mask.find_elements_by_tag_name(\"path\")\n print(\n f\"[!] {datetime.datetime.now(eastern)} :: Bars found by counting masked completed-item elements: {len(cap_bars)}/20\"\n )\n\n crowd_meter = driver.find_element_by_xpath(\n '//*[@id=\"CrowdMeter\"]/div[1]/div[2]'\n )\n crowd_meter.screenshot(\"screen_shot.png\")\n\n # complete_capacity_div = driver.find_element_by_class_name(\"club-capacity\")\n # complete_capacity_div.screenshot('screen_shot.png')\n\n # Website redesign ~7PM EST December 16th, 2020\n # capacity_meter_div = driver.find_element_by_class_name(\n # \"club-capacity-meter\"\n # )\n # capacity_meter_div.screenshot(\"screen_shot.png\")\n x_pixels_until_gray_bar, total_x_pixels = get_crowd_percentage(image_path)\n crowd_percentage = x_pixels_until_gray_bar / total_x_pixels\n print(\n f\"[!] {datetime.datetime.now(eastern)} :: Current Crowd Percentage: ~{round(crowd_percentage*100,2)}% - Filled Bar to Total Pixels: {x_pixels_until_gray_bar}/{total_x_pixels} - Bars: [{int(round(crowd_percentage,2)*total_bars)}] out of {total_bars}\"\n )\n slack_requester.send_message(\n f\" *{datetime.datetime.now(eastern)} Eastern* - Current Crowd Percentage: ~{round(crowd_percentage*100,2)}% - Filled Bar to Total Pixels: {x_pixels_until_gray_bar}/{total_x_pixels} - Bars: [{int(round(crowd_percentage,2)*total_bars)}] out of {total_bars}\"\n )\n except Exception as exc:\n print(\n f\"[!] {datetime.datetime.now(eastern)} :: Error in finding element, screenshotting, or getting percentage: {exc}\"\n )\n slack_requester.send_message(\n f\" *{datetime.datetime.now(eastern)} Eastern* - Exception was raised during runtime - pf crowd bot exiting\"\n )\n time.sleep(poll)\n except (Exception, KeyboardInterrupt) as exc:\n print(\n f\"[*] {datetime.datetime.now(eastern)} :: SIGINT caught - closing browser\"\n )\n slack_requester.send_message(\n f\" *{datetime.datetime.now(eastern)} Eastern* - Exception was raised during runtime - pf crowd bot exiting\"\n )\n running = False\n continue\n# driver.close() #raises an exception for some reason? (Failed to establish a new connection)\n","sub_path":"crowd.py","file_name":"crowd.py","file_ext":"py","file_size_in_byte":6856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"418137642","text":"\"\"\"\nWHAT: Primary entry point to application\nWHY: Need a primary entry point\nASSUMES: Invoked via \"python modMain.py\", either directly on an OS or via Docker\nFUTURE IMPROVEMENTS: N/A\nWHO: SL 2020-08-13\n\"\"\"\n\nimport logging\nimport modConfig\nfrom clsWordManager import clsWordManager\n\n\ndef main():\n \"\"\"\n The primary entry point to execute the program\n :return: None\n \"\"\"\n wordManager = clsWordManager()\n wordManager.execute()\n\n\nif __name__ == '__main__':\n\n import os\n from datetime import datetime\n\n startTime = datetime.now()\n\n if os.path.exists(modConfig.logFilePath):\n os.remove(modConfig.logFilePath)\n logging.basicConfig(\n filemode=\"a\",\n filename=modConfig.logFilePath,\n level=logging.INFO,\n format='%(asctime)s %(process)7s %(levelname)8s %(message)s')\n\n msg = \"Program started\"\n print(msg)\n logging.info(msg)\n\n try:\n main()\n except Exception as e:\n msg = \"Exception running main method\"\n print(msg)\n print(str(e))\n logging.error(msg)\n logging.error(e)\n raise\n\n msg = \"Program complete\"\n print(msg)\n logging.info(msg)\n\n endTime = datetime.now()\n totalTime = endTime - startTime\n msg = \"App run time: %s\" % str(totalTime)\n print(msg)\n logging.info(msg)\n","sub_path":"CBB/ETL_BioWords/src/modMain.py","file_name":"modMain.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"244028981","text":"import numpy as np\nimport math\nimport time\nW=20\nH=20\nbound_x=int(240/W)\nbound_y=int(320/H)\nnspr_v=np.zeros([bound_x,bound_y,bound_x,bound_y])\nclass PICT():\n def __init__(self,content,num_x,num_y,width,height,Mx=0,My=0):\n self.content=content\n self.num_x=num_x\n self.num_y=num_y\n self.Mx=Mx\n self.My=My\n if width*(num_x+1)<=240:\n self.coor_x=W*num_x\n if width*(num_y+1)<=320:\n self.coor_y=H*num_y\n self.width=width\n self.height=height\n def printPict(self):\n print('num_x:',self.num_x,'\\tnum_y:',self.num_y,'\\twidth:',self.width,'\\theight:',self.height)\n\ndef NSPR(pict1,pict2):\n sums=0\n if pict1.width!=pict2.width:\n return 0\n if pict1.height!=pict2.height:\n return 0\n if pict1.height!=H:\n return 0\n if pict1.width!=W:\n return 0\n ref_data=pict1.content[int(pict1.width*pict1.num_x):int(pict1.width*(pict1.num_x+1)),int(pict1.height*pict1.num_y):int(pict1.height*(pict1.num_y+1))]\n target_data=pict2.content[int(pict2.width*pict2.num_x):int(pict2.width*(pict2.num_x+1)),int(pict2.height*pict2.num_y):int(pict2.height*(pict2.num_y+1))]\n diff = ref_data - target_data\n diff=diff.flatten('C')\n rmse = math.sqrt( np.mean(diff ** 2.) )\n if rmse==0:\n return 10000\n return 20*math.log10(1.0/rmse)\n\ndef Diamond_Search(pict1,previous_image):\n#never think about corner, it would be added later\n x=pict1.num_x\n y=pict1.num_y\n Big_max=0\n Big_num=0\n Big_scale=[[x,y]]\n Big_score=[]\n if y-2>=0:\n Big_scale.append([x,y-2])\n if y-1>=0 and x-1>=1:\n Big_scale.append([x-1,y-1])\n if y-1>=0 and x+1=0:\n Big_scale.append([x-2,y])\n if y+1=0:\n Big_scale.append([x-1,y+1])\n if y-1>=0 and x+1=0:\n Small_scale.append([x_s,y_s-1])\n if y_s+1=0:\n Small_scale.append([x_s-1,y_s])\n Small_score=[]\n for i in range(len(Small_scale)):\n target=PICT(previous_image,Small_scale[i][0],Small_scale[i][1],W,H)\n score=NSPR(pict1,target)\n if Small_max=left and item.num_y>=top and item_right<=right and item_down<=down:\n effective+=1\n return (effective/cardinal)\n\n\ndef ComputeOverlay(picture1,picture2):\n tao=15\n total_num=0\n sum_x=0\n sum_y=0\n result=[]\n o_time=time.time()\n \n for i in range(bound_x):\n if i%2:\n for j in range(bound_y):\n if j%2==0:\n pict1=PICT(picture1,i,j,W,H)\n x,y=Diamond_Search(pict1,picture2)\n pict2=PICT(picture2,x,y,W,H)\n if NSPR(pict1,pict2)>tao :\n total_num+=1\n sum_x+=(pict1.num_x-pict2.num_x)\n sum_y+=(pict1.num_y-pict2.num_y)\n #step 3\n if total_num!=0:\n Mx=int(sum_x/total_num)\n My=int(sum_y/total_num)\n else:\n return np.array([0,0,0,0,0,0])\n #step into the fantastic great algorithm, the cube merge algorithm! time complexity n^2.....well it seems that it is not great but useful...\n next_cube=PICT(picture1,0,0,W,H)\n count=0\n effective_blocks=0\n s_time=time.time()\n for i in range(bound_x):\n if i%2:\n for j in range(bound_y):\n if j%2==0 and nspr_v[i,j,(i+Mx)%bound_x,(j+My)%bound_y]>tao:\n pict1=PICT(picture1,i,j,W,H,Mx,My)\n result.append(pict1)\n effective_blocks+=1\n '''\n while next_cube!=None:\n pict_s=next_cube\n pict_s.Mx=Mx\n pict_s.My=My\n if pict_s.width==W and pict_s.height==H:\n count+=1\n next_cube=PICT(picture1,pict_s.num_x+pict_s.width/W,pict_s.num_y-1+pict_s.height/H,W,H)\n if pict_s.num_x+(pict_s.width/W)>=bound_x:\n next_cube=PICT(picture1,0,pict_s.num_y+(pict_s.height/H),W,H)\n if pict_s.num_y+(pict_s.height/H)>=bound_y:\n next_cube=None\n\n if pict_s.num_x+Mx>=0 and pict_s.num_x+Mx<=bound_x and pict_s.num_y+My>=0 and pict_s.num_y+My<=bound_y:\n pict_t=PICT(picture2,pict_s.num_x+Mx,pict_s.num_y+My,W,H)\n if NSPR(pict_s,pict_t)>tao:\n if pict_s.width==W and pict_s.height==H:\n result.append(pict_s)\n effective_blocks+=1\n print('effective:',len(result))\n '''\n e_time=time.time()\n dens=0\n rate=0.20\n [left,top]=[0,0]\n [right,down]=[bound_x-1,bound_y-1]\n direction=0\n print('initial time:',1000*(s_time-o_time))\n print('extra time:',1000*(e_time-s_time))\n while(dens=rate):\n return np.array([left,top,(right-left+1)*W,(down-top+1)*H,Mx,My])\n [left,top]=[0,0]\n [right,down]=[bound_x-1,bound_y-1]\n while(dens=rate):\n return np.array([left,top,(right-left+1)*W,(down-top+1)*H,Mx,My])\n [left,top]=[0,0]\n [right,down]=[bound_x-1,bound_y-1]\n while(dens=1:\n right-=1\n else:\n break\n dens=density(result,left,top,right,down)\n if(dens>=rate):\n return np.array([left,top,(right-left+1)*W,(down-top+1)*H,Mx,My])\n [left,top]=[0,0]\n [right,down]=[bound_x-1,bound_y-1]\n while(dens=1:\n down-=1\n else:\n break\n dens=density(result,left,top,right,down)\n\n return np.array([left,top,(right-left+1)*H,(down-top+1)*W,Mx,My])\n","sub_path":"cache_utilities.py","file_name":"cache_utilities.py","file_ext":"py","file_size_in_byte":6905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"512696449","text":"import numpy as np\nimport argparse\nimport os\nimport random\n\ngap_ = lambda folder, x, y: 'find %s/ -name \"*.%s\" | sort | xargs grep -Rs \"Gap :\" {} > %s'%(folder, y, x)\nprimal_ = lambda folder, x, y: 'find %s/ -name \"*.%s\" | sort | xargs grep -Rs \"Primal Bound : \" {} > %s'%(folder, y, x)\nobj_ = lambda folder, x, y: 'find %s/ -name \"*.%s\" | sort | xargs grep -Rs \"#Objective*\" {} > %s'%(folder, y, x)\n\ntmpFile = '/tmp/tmp%s.txt'%(str(random.random()).strip('.'))\nSCRATCH=os.environ['COTRAIN_SCRATCH'].replace('//', '/')\n\ndef main(inpFolder, parse, ftype, flag=True, log='log'):\n if os.path.isdir(inpFolder):\n if 'log' in log:\n if not flag:\n os.system(primal_(inpFolder, tmpFile, log))\n else:\n os.system(gap_(inpFolder, tmpFile, log))\n else:\n os.system(obj_(inpFolder, tmpFile, log))\n else:\n print('Error: Input file does not exist')\n\n dual = []\n alldata = {}\n with open(tmpFile, 'r') as F:\n cdata = F.readlines()\n for cc in cdata:\n try:\n cc=cc.replace('//', '/')\n fname = os.path.basename(cc.split(':')[0])\n orig = '/' + cc.split(':')[0].replace(SCRATCH, '').replace('/' + ftype + '/', '/sol/').split(parse)[0]\n val = float(cc.split(': ')[1].strip('\\n ').strip('%').split('(')[0])\n except:\n val = 300\n\n dual.append(min(val, 300))\n alldata[fname] = val\n\n if ('lpfiles' in inpFolder) or ('gpickle' in inpFolder):\n ext = '.sol'\n else:\n ext = 'mps.sol'\n\n if not flag:\n opt = []\n for key, val in alldata.iteritems():\n fname = os.path.join(orig, key.replace('.log', ext))\n if val == 300:\n opt.append(300)\n else:\n with open(fname, 'r') as F:\n lines = F.readlines()\n optVal = None\n for cline in lines:\n cc = cline.lower()\n if 'objective value' in cc:\n optVal = float(cc.strip('# objective value = '))\n break\n\n assert optVal != None, \"Opt value not found\"\n opt.append(100*(np.abs(val-optVal)/np.abs(optVal)))\n else:\n opt = dual\n\n print(opt)\n opt = np.array(opt)\n idx = np.where(opt < 250)[0]\n goodopt = opt[idx].tolist()\n mean = np.mean(opt)\n goodmean = np.mean(goodopt)\n num = len(opt) - len(idx)\n return (mean, goodmean, num)\n\ndef firstPassCommandLine():\n\n # Creating the parser for the input arguments\n parser = argparse.ArgumentParser(description='Generate data for spatial model')\n\n # Positional argument - Input XML file\n parser.add_argument('--i', type=str, default=\"/Users/subrahma/proj/maverick-setup/co-training/scratch/Users/subrahma/proj/maverick-setup/co-training/data/psulu_test/lpfiles/test/nn_psulu_0.1_cotrain_search_lp_0/\",\n help='input file', dest='inp')\n parser.add_argument('--o', type=str, default=\"out.txt\",\n help='output file', dest='out')\n parser.add_argument('--g', action='store_true',\n help='Flag for only optimality gap', dest='graph')\n parser.add_argument('--s', type=str, default=\"lpfiles\",\n help='problem type', dest='ftype')\n\n # Parse input\n args = parser.parse_args()\n return args\n\nif __name__ == '__main__':\n args = firstPassCommandLine()\n fname = os.path.basename(os.path.dirname(args.inp))\n if not args.graph:\n dual_vals = main(args.inp, fname, args.ftype)\n else:\n dual_vals = (np.nan, np.nan, 0)\n\n if not args.graph:\n primal_vals = main(args.inp, fname, args.ftype, False)\n else:\n primal_vals = main(args.inp, fname, args.ftype, False, 'sol')\n\n row = dual_vals + primal_vals\n with open(args.out,'a') as f:\n f.write(fname + '\\t')\n for val in row:\n f.write('%.4f'%val + '\\t')\n f.write('\\n')\n\n","sub_path":"joint-pyscripts/getStats-gurobi.py","file_name":"getStats-gurobi.py","file_ext":"py","file_size_in_byte":3824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"331131229","text":"#\n# Copyright 2016 The BigDL Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport torch\nfrom torch import nn\nimport pytest\n\nfrom unittest import TestCase\nfrom bigdl.orca.torch import TorchModel, TorchLoss, TorchOptim\nfrom bigdl.dllib.nncontext import *\nfrom torch.utils.data import TensorDataset, DataLoader\nfrom bigdl.dllib.estimator import *\nfrom bigdl.dllib.optim.optimizer import MaxEpoch, EveryEpoch\nfrom bigdl.dllib.keras.metrics import Accuracy\nfrom bigdl.dllib.feature.common import FeatureSet\n\n\nclass TestPytorchOptim(TestCase):\n\n def setUp(self):\n \"\"\" setup any state tied to the execution of the given method in a\n class. setup_method is invoked for every test method of a class.\n \"\"\"\n self.sc = init_spark_on_local(4)\n\n def tearDown(self):\n \"\"\" teardown any state that was previously setup with a setup_method\n call.\n \"\"\"\n self.sc.stop()\n\n def test_torch_optim(self):\n class SimpleTorchModel(nn.Module):\n def __init__(self):\n super(SimpleTorchModel, self).__init__()\n self.dense1 = nn.Linear(2, 4)\n self.bn1 = torch.nn.BatchNorm1d(4)\n self.dense2 = nn.Linear(4, 1)\n\n def forward(self, x):\n x = self.dense1(x)\n x = self.bn1(x)\n x = torch.sigmoid(self.dense2(x))\n return x\n\n self.sc.stop()\n self.sc = init_nncontext()\n torch_model = SimpleTorchModel()\n loss_fn = torch.nn.BCELoss()\n torch_optim = torch.optim.Adam(torch_model.parameters())\n az_model = TorchModel.from_pytorch(torch_model)\n zoo_loss = TorchLoss.from_pytorch(loss_fn)\n\n def train_dataloader():\n inputs = torch.Tensor([[1, 2], [1, 3], [3, 2],\n [5, 6], [8, 9], [1, 9]])\n targets = torch.Tensor([[0], [0], [0],\n [1], [1], [1]])\n return DataLoader(TensorDataset(inputs, targets), batch_size=2)\n\n train_featureset = FeatureSet.pytorch_dataloader(train_dataloader)\n val_featureset = FeatureSet.pytorch_dataloader(train_dataloader)\n zoo_optimizer = TorchOptim.from_pytorch(torch_optim)\n estimator = Estimator(az_model, optim_methods=zoo_optimizer)\n estimator.train_minibatch(train_featureset, zoo_loss, end_trigger=MaxEpoch(4),\n checkpoint_trigger=EveryEpoch(),\n validation_set=val_featureset,\n validation_method=[Accuracy()])\n\n trained_model = az_model.to_pytorch()\n\n\nif __name__ == \"__main__\":\n pytest.main([__file__])\n","sub_path":"python/orca/test/bigdl/orca/torch/test_torch_optim.py","file_name":"test_torch_optim.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"477808796","text":"from smkTest import SmkTest\nfrom smkdata import ACCOUNT_NAME\n\nclass Account(SmkTest):\n '''东营E卡通App二类账户页面测试'''\n def test_a(self):\n '''二类账户页面检查'''\n self.logger.info('\\ntest_a:开始测试-我的账户')\n self.account()\n # 断言我的账户页面账户姓名\n text = self.my_find_element_by_id('com.chinaums.sddysmk:id/tv_account_name').text\n self.assertEqual(text, ACCOUNT_NAME)\n self.logger.info('我的账户-测试结束')\n","sub_path":"dysmk/cases/rm_test_account.py","file_name":"rm_test_account.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"85680899","text":"from izhikevich import izhikevich as neuron\nimport matplotlib.pyplot as plt\nimport math\nimport numpy as np\n\nSPIKE_THRESHOLD = 35\nK_SYN = 1\nTAU = 2\n\n################################################################################\n### Extract spike timings from spike train of 0's and 1's of single neuron\n################################################################################\ndef extract_single_spike_time(spike_train, time, tau = 0.1):\n\tsteps = int(time / tau)\n\tspike_time = []\n\tfor j in xrange(0,steps):\n\t\tif(spikes[j] > 0):\n\t\t\tspike_time.append(float(j) * tau) # convert index to timestamp\n\treturn spike_time\n\n################################################################################\n### Extract spike timings from spike train of 0's and 1's\n### Indices of 1's are convereted to spike time and returned as array of spikes\n### Rows represents neurons and columns represents time stamps\n################################################################################\ndef extract_spike_times(spikes, time, tau = 0.1):\n\tsteps = int(time / tau)\n\tspike_time = []\n\tfor i in xrange(0,len(spikes)):\n\t\ttemp_spike_time = [] # temp \n\t\tfor j in xrange(0,steps):\n\t\t\t\tif(spikes[i][j] > 0):\n\t\t\t\t\ttemp_spike_time.append(float(j) * tau) # convert index to timestamp\n\t\tspike_time.append(temp_spike_time)\n\treturn spike_time\n\n########################################################################\n### Extract spike trains of 0's and 1's from array of Izhikevich neurons\n########################################################################\ndef extract_spike_trains(neurons, threshold = SPIKE_THRESHOLD):\n\tspikes = []\n\tfor i in xrange(0,len(neurons)):\n\t\ttemp_spike_train = neurons[i].generate_spike_train(threshold) # generate individual spike train\n\t\tspikes.append(temp_spike_train)\n\treturn spikes\n\n############################################################################\n### Get synaptic current for the receiver neuron\n###\t\tspike_times : input spikes times to the receiver neuron\n###\t\tweights : calculated weight of each synapse\n###\t\ttime(in_ms) : simulation duration\n###\t\treceiver_neuron : if this is None than new neuron object is returned\n###\t\tV : default value of voltage -60\n###\t\tK_SYN : as per paper 1\n###\t\tTAU : as per paper 2\n###\t\tdelta_t : time increment\n############################################################################\ndef get_synaptic_current(spike_times, weights, time, receiver_neuron = None, V = -60, K_SYN = 1, TAU = 2, delta_t = 0.1):\n\tsteps = int(time / delta_t)\n\t# get conductance values for number of of steps\n\tG = conductance(spike_times, weights, steps, K_SYN, TAU, delta_t)\n\n\t# create new neuron object if needed\n\tif(receiver_neuron == None):\n\t\treceiver_neuron = neuron()\n\t\n\t# run simulation for one syanptic current value. I_SYN[i] = -V * G[i] \n\tfor i in xrange(0,steps):\n\t\treceiver_neuron.input_snn_one_step(-receiver_neuron.get_prev_voltage() * G[i])\n\n\treturn receiver_neuron, G\n\n############################################################################\n### Get synaptic conductance for the receiver neuron\n###\t\tspike_times : input spikes times to the receiver neuron\n###\t\tweights : calculated weight of each synapse\n###\t\tsteps : duration of simulation in terms of steps\n###\t\tK_SYN : as per paper 1\n###\t\tTAU : as per paper 2\n###\t\tdelta_t : time increment\n############################################################################\n\ndef conductance(spike_times, weights, steps, K_SYN = 1, TAU = 2, delta_t = 0.1):\n\tG = []\n\tfor t in xrange(0, steps):\n\t\ttime_increment = float(t) * delta_t\n\t\tsum = 0\n\t\tfor k in xrange(0,len(spike_times)):\n\t\t\tfor j in xrange(0,len(spike_times[k])):\n\t\t\t\tsum = sum + (weights[k] * (K_SYN * (time_increment - spike_times[k][j]) * math.exp(-(time_increment - spike_times[k][j]) / (TAU) / 1000.0)))\n\t\tG.append(sum)\n\treturn G\n\n#############################################################\n### plot spike coding and spike train for given neuron layer\n#############################################################\ndef plot_neurons(neuron_layer, i_inj, weights):\n\trow = len(neuron_layer)\n\tcol = 2\n\tplt.figure()\n\tif row > 4:\n\t\trow = 4\n\tfor i in xrange(0, row):\n\t\tplot = i*2 + 1\n\t\tplt.subplot(str(row) + str(col) + str(plot))\n\t\tplt.plot(neuron_layer[i].get_output())\n\t\tplt.title(\"Spike Coding \" + str(i) + \", i_inj : \" + str(i_inj[i]))\n\n\t\tplot = i*2 + 2\n\t\tplt.subplot(str(row) + str(col) + str(plot))\n\t\tplt.plot(neuron_layer[i].generate_spike_train(SPIKE_THRESHOLD))\n\t\tplt.title(\"Spike Train \" + str(i))\n\n\t'''\n\tfigure = plt.gcf() # get current figure\n\tfigure.set_size_inches(10, 10)\n\tplt.savefig(\"./results/\" + str(i_inj) + \", weights \" + str(weights) + \".jpg\",dpi = 100)\n\t'''\n\n#############################################################\n### conductance kernel\n#############################################################\ndef single_conductance(steps, spike_time):\n\tG = []\n\n\tfor i in xrange(0,steps):\n\t\tt = float(i)/10.0\n\t\ttemp = K_SYN * t * math.exp(-t/TAU)\n\t\tG.append(K_SYN * t * math.exp(-t/TAU))\n\n\tif spike_time == 0:\n\t\treturn G\n\treturn shift(int(spike_time/0.1), G)\n\ndef linear_additive_conductance(steps, spike_times, weights):\n\tall_conductance = []\n\tconductance = []\n\n\tfor i in xrange(0,len(spike_times)):\n\t\tconductance.append(conductance_for_spike_train(steps, spike_times[i]))\n\n\tall_conductance = add_array(conductance)\n\tall_weighted_conductance = add_weighted_array(conductance, weights)\n\n\treturn conductance, all_conductance, all_weighted_conductance\n\ndef conductance_for_spike_train(steps, spike_times):\n\tC = []\n\tfor i in range(len(spike_times)):\n\t\tC.append(single_conductance(steps, spike_times[i]))\n\n\treturn add_array(C)\n\n\n#############################################################\n### Shift an array right add #key elements as left padding\n#############################################################\ndef shift(key, array):\n\treturn ([0.0] * int(key)) + array[:-int(key)]\n\ndef find_min(array):\n\tx = []\n\tfor i in range(len(array)):\n\t\tx.append(min(array[i]))\n\treturn min(x)\n\ndef add_array(array):\n\tsum = []\n\tfor i in range(len(array[0])):\n\t\ttemp = 0\n\t\tfor j in range(len(array)):\n\t\t\ttemp = temp + array[j][i]\n\t\tsum.append(temp)\n\treturn sum\n\ndef add_weighted_array(array, weights):\n\tsum = []\n\n\tfor i in range(len(array[0])):\n\t\ttemp = 0.0\n\t\tfor j in range(len(array)):\n\t\t\ttemp = temp + float(weights[j]*array[j][i])\n\t\tsum.append(temp)\n\treturn sum\n\ndef get_marker(steps, marker):\n\tmark = ([0.0] * int(steps))\n\tmark[marker]= 0.7\n\treturn mark\n\n\ndef additive_synaptic_current(steps, conductance, receiver_neuron = None):\n\t# create new neuron object if needed\n\tif(receiver_neuron == None):\n\t\treceiver_neuron = neuron()\n\t\n\t# run simulation for one syanptic current value. I_SYN[i] = -V * G[i] \n\tfor i in xrange(0,steps):\n\t\treceiver_neuron.input_snn_one_step(-receiver_neuron.get_prev_voltage() * conductance[i])\n\n\treturn receiver_neuron\n\n\n#############################################################\n### plot spike coding and spike train for given neuron layer\n#############################################################\ndef plot_conductance(neuron_layer, conductance, i_inj):\n\trow = len(neuron_layer)\n\tcol = 1\n\tcolor = [\"r\", \"g\", \"b\", \"c\", \"r\", \"g\", \"b\", \"c\", \"r\", \"g\", \"b\", \"c\", \"r\", \"g\", \"b\", \"c\"]\n\tplt.figure()\n\tif row > 9:\n\t\trow = 9\n\tfor i in xrange(0, row):\n\t\tplt.subplot(str(row) + str(col) + str(i+1))\n\t\tplt.plot(neuron_layer[i].generate_spike_train(SPIKE_THRESHOLD),color[i+1])\n\t\tplt.plot(conductance[i], color[i])\n\t\tplt.title(\"Conductance of neuron \" + str(i+1) + \" - \" + str(i_inj[i]))","sub_path":"demo/examples/additive_conductance/prev_volage_research_paper/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":7483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"142605120","text":"from NeuralEmulator.Interfaces.CurrentSourceBase import CurrentSourceBase\r\nfrom NeuralEmulator.Interfaces.SynapseBase import SynapseBase\r\nfrom NeuralEmulator.Configurators.PulseSynapseConfigurator import PulseSynapseConfigurator\r\nfrom NeuralEmulator.Preprocessing.PreprocessingBlock import PreprocessingBlock\r\nfrom NeuralEmulator.Test.SimpleVoltageSource import SimpleVoltageSource\r\nfrom NeuralEmulator.Preprocessing.PosPreprocessingBlock import PosPreprocessingBlock\r\nfrom NeuralEmulator.Utils.Utils import getValueFromPoly, getObjID\r\nimport numpy as np\r\n\r\n\r\nclass PulseSynapse(CurrentSourceBase):\r\n def __init__(self, vin, configurator):\r\n self.vin = vin\r\n self.configurator = configurator\r\n\r\n self.cacheVinVal = self.vin.getVoltage()\r\n self.current = 0\r\n self.coef = np.array(self.configurator.getCoef())\r\n self.__updateCurrent()\r\n\r\n def __updateCurrent(self):\r\n self.cacheVinVal = self.vin.getVoltage()\r\n self.current = self.configurator.getCurrentForVoltage(self.cacheVinVal)\r\n\r\n def getCurrent(self):\r\n return self.current\r\n\r\n def run(self):\r\n vin = self.vin.getVoltage()\r\n if self.cacheVinVal != vin:\r\n self.__updateCurrent()\r\n\r\n\r\nclass PulseSynapseWeighted(CurrentSourceBase):\r\n def __init__(self, vinSource, vwSource, configurator, printLog=False):\r\n self.vinSource = vinSource\r\n self.vwSource = vwSource\r\n\r\n self.configurator = configurator\r\n self.printLog = printLog\r\n\r\n self.cacheVinVal = self.vinSource.getVoltage()\r\n self.cacheVwVal = self.vwSource.getVoltage()\r\n self.current = 0\r\n self.__updateCurrent()\r\n\r\n if self.printLog is True:\r\n print(\"PulseSynapseWeighted ID {} created with: idVin {}\".format(getObjID(self), getObjID(self.vinSource)))\r\n\r\n def __updateCurrent(self):\r\n self.cacheVinVal = self.vinSource.getVoltage()\r\n self.cacheVwVal = self.vwSource.getVoltage()\r\n\r\n self.current = self.configurator.getCurrentForVoltage(self.cacheVinVal, self.cacheVwVal)\r\n\r\n def getCurrent(self):\r\n return self.current\r\n\r\n def run(self):\r\n vin = self.vinSource.getVoltage()\r\n vw = self.vwSource.getVoltage()\r\n\r\n if self.printLog is True:\r\n print(\"PulseSynapseWeighted {}: idVin {} vin {} vw {}\".format(getObjID(self), getObjID(self.vinSource), vin, vw))\r\n\r\n if self.cacheVinVal != vin or self.cacheVwVal != vw:\r\n self.__updateCurrent()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import os\r\n\r\n os.environ[\"NERUSIM_CONF\"] = r\"C:\\Users\\Avi\\Desktop\\IntelliSpikesLab\\Emulator\\config\"\r\n\r\n vin = SimpleVoltageSource()\r\n p = PreprocessingBlock(vin)\r\n\r\n posPreprocessingBlock = PosPreprocessingBlock(p)\r\n cfg = PulseSynapseConfigurator()\r\n\r\n pulseSyn = PulseSynapse(posPreprocessingBlock, cfg)\r\n","sub_path":"PulseSynapse.py","file_name":"PulseSynapse.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"32843260","text":"# coding=UTF-8\nimport os\nimport re\nfrom functools import cmp_to_key\nimport sys\nimport getopt\nimport fnmatch\nimport shutil\nimport subprocess\n\nPGY_KEYS_C = {\n 'apiKey': '1a29c253e8fbfc5a829a1a86aba607ec',\n 'userKey': 'd4b66ee185fcf4470b979c6c304fc3ee'\n}\n\nPGY_KEYS_U = {\n 'apiKey': 'c6a5ea2c5a0a7836935e2cbedd66d614',\n 'userKey': '9cb7c5573344ccb88ce9c85954adc962'\n}\n\nPGY_KEYS_X = {\n 'apiKey': '0918e9928a7c6253920be90335ee4f37',\n 'userKey': '53da6e905a03e639f69d5e46da317879'\n}\n\nOUT_PUT_DIR = 'delivery\\\\build\\\\outputs'\nWHATSNEW_FILE = 'whatsnew.txt'\nglobal author_name\nglobal output_apk_file_path\nglobal output_mapping_file_path\nglobal whatsnew_file_path\n\ndef start_work(env_type=None, re_publish=False):\n print(\"当前选择的环境为:\" + env_type)\n # 1. remove existed output files, e.g apk file and mapping file.\n if not re_publish:\n shutil.rmtree(OUT_PUT_DIR, True)\n\n # 2. clean && build\n if not re_publish:\n execute('gradlew clean assembleRelease%s' % env_type.upper())\n\n # 3. preCommit\n prepare_for_commit()\n\n # 4. commit apk and mapping file to repo\n if not re_publish:\n commit_to_svn(env_type)\n\n # 5. publish to pgyer.com\n publish_to_pgy(env_type)\n\n\ndef prepare_for_commit():\n global author_name, output_apk_file_path, output_mapping_file_path, whatsnew_file_path\n # 提交者姓名\n temp = execute2('svn auth 192.168.1.28*pagoda_qgw')\n ret = re.search(\"Username:[ ]?(.*?)\\\\r\", temp)\n author_name = ret.group(1) if ret else None\n print(\"author name is [%s]\" % author_name)\n\n # 需要提交的apk文件\n files = list_files(OUT_PUT_DIR, \"*.apk\", recursive=True)\n if len(files) is 0:\n print(\"Error: apk file not found in ...\" + os.path.join(os.getcwd(), OUT_PUT_DIR))\n sys.exit()\n output_apk_file_path = files[0]\n\n # 需要提交的mapping文件\n mapping_files = list_files(OUT_PUT_DIR, \"mapping.txt\", recursive=True)\n output_mapping_file_path = mapping_files[0] if len(mapping_files) > 0 else None\n\n # 需要提交的whatsnew文件\n whatsnew_file_path = os.path.join(os.getcwd(), WHATSNEW_FILE)\n\n\ndef commit_to_svn(env_type=None):\n print(\"正在提交到svn...\")\n global author_name, output_apk_file_path, output_mapping_file_path, whatsnew_file_path\n\n output_apk_name = os.path.basename(output_apk_file_path)\n\n tmp_dir = os.path.join(os.getcwd(), 'tmp_commit')\n shutil.rmtree(tmp_dir, True)\n app_version_name = output_apk_name.split('_')[2][1:]\n app_bata_number = output_apk_name.split('_')[3]\n app_timestamp = output_apk_name.split('_')[4]\n app_version_code = output_apk_name.split('_')[5]\n\n print('%s, %s, %s, %s' % (app_version_name, app_bata_number, app_timestamp, app_version_code))\n if not os.path.exists(tmp_dir):\n os.mkdir('tmp_commit')\n # copy apk file\n shutil.copyfile(output_apk_file_path, os.path.join(tmp_dir, output_apk_name))\n # copy mapping file\n if output_mapping_file_path:\n shutil.copyfile(output_mapping_file_path, os.path.join(tmp_dir, ('mapping_%s.txt' % output_apk_name[:-4])))\n # copy whatsnew file\n if os.path.exists(whatsnew_file_path):\n shutil.copyfile(whatsnew_file_path, os.path.join(tmp_dir, ('whatsnew_%s.txt' % app_timestamp)))\n\n svn_url = 'svn://%s@192.168.1.28/pagoda_qgw/99code/tags/Delivery_Android/Delivery_android_V%s_%s' % (\n author_name, app_version_name, app_bata_number)\n print(\"begin to commit to svn:\\n url = %s\" % svn_url)\n\n commit_msg = '提交版本:%s' % output_apk_name[:-4]\n execute('svn import -m \"%s\" \"%s\" \"%s\"' % (commit_msg, tmp_dir, svn_url))\n\n print('提交svn成功!')\n\n # 删除临时目录\n shutil.rmtree(tmp_dir, True)\n\n\ndef publish_to_pgy(env_type=None):\n print(\"正在发布应用到 pgyer.com ...\")\n global author_name, output_apk_file_path, whatsnew_file_path\n if env_type == 'c':\n pgy_key = PGY_KEYS_C\n elif env_type == 'u':\n pgy_key = PGY_KEYS_U\n elif env_type == 'x':\n print('现网包需要加固后再发布到蒲公英.')\n sys.exit()\n else:\n print(\"不支持该类型环境的包发布, env=%s\" % env_type )\n sys.exit()\n\n output_apk_name = os.path.basename(output_apk_file_path)\n\n whatsnew = open(whatsnew_file_path, 'r', encoding='utf-8').read()\n whatsnew = 'sb 日志'\n publish_log = '%s_%s_%s' % (author_name, output_apk_name, whatsnew.replace('\\n', ' ##'))\n\n # print(publish_log)\n cmd = 'curl -F \"file=@%s\" -F \"uKey=%s\" -F \"_api_key=%s\" -F \"updateDescription=%s\" ' \\\n 'http://www.pgyer.com/apiv1/app/upload' \\\n % (output_apk_file_path, pgy_key['userKey'], pgy_key['apiKey'], publish_log)\n execute(cmd)\n\n\ndef list_files(path, pattern=None, sort_by_time=True, recursive=False):\n # returns a list of names (with extension, without full path) of all files in folder path\n files = []\n path = path if os.path.isabs(path) else os.path.join(os.getcwd(), path)\n pattern = \"*\" if pattern is None else pattern\n pathname = os.path.join(path+'\\*', pattern)\n # print(\"ls \" + pathname)\n if recursive:\n for root, dirnames, filenames in os.walk(path):\n for filename in fnmatch.filter(filenames, pattern):\n files.append(os.path.join(root, filename))\n else:\n for filename in fnmatch.filter(os.listdir(path), pattern):\n files.append(os.path.join(path, filename))\n\n files.sort(key=cmp_to_key(_compare_mtime), reverse=sort_by_time)\n # print(files)\n return files\n\n\ndef _compare_mtime(x, y):\n mtime_x = os.stat(x).st_mtime\n mtime_y = os.stat(y).st_mtime\n if mtime_x < mtime_y:\n return -1\n elif mtime_x > mtime_y:\n return 1\n else:\n return 0\n\n\ndef execute(cmd=None):\n print('execute: \"' + cmd + '\"')\n # cmd = 'curl www.baidu.com'\n # return subprocess.call(cmd, shell=True)\n ret = os.system(cmd)\n if ret != 0:\n sys.exit()\n print('------------- END -------------')\n\n\ndef execute2(cmd=None):\n print('execute2: \"' + cmd + '\"')\n p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n out = p.stdout.read().decode('utf-8', 'ignore')\n # print(out)\n return out\n # retval = p.wait()\n\n\ndef usage():\n print(\"usage:\" + sys.argv[0] + \" -t c\")\n message = \\\n ''' 编译 - 提交svn - 应用发布\n How to use the script:\n -t, --type the env type you want to build.\n c : Environmental of test\n k : Environmental of develop\n u : Environmental of UAT\n x : Environmental of production\n -r, --rePublish 仅发布应用,不会重新编译\n -h, --help show this help message\n e.g.\n build_publish.py -t c # 编译并发布测试环境的app\n build_publish.py --type c # 编译并发布测试环境的app\n build_publish.py -t c -r # 重新发布测试环境的app,不重新编译\n (针对场景:编译成功,但是发布失败,则使用该命令重新发布刚刚编译的app)\n build_publish.py -h # 查看帮助\n '''\n print(message)\n sys.exit()\n\n\ndef main(args):\n if os.getcwd() != sys.path[0]:\n print(\"The python script must run on the current directory!\")\n sys.exit()\n try:\n opts, args = getopt.getopt(args, \"ht:r\", [\"help\", \"type=\", \"rePublish\"])\n except getopt.GetoptError:\n usage()\n if len(opts) == 0 or len(args) != 0:\n usage()\n re_publish = False\n for op, value in opts:\n if op in ('-t', '--type'):\n if value not in ('c', 'x', 'u', 'k'):\n usage()\n env_type = value\n elif op in ('-r', '--rePublish'):\n re_publish = True\n elif op in ('-h', '--help'):\n usage()\n else:\n usage()\n start_work(env_type, re_publish)\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","sub_path":"build_publish.py","file_name":"build_publish.py","file_ext":"py","file_size_in_byte":7967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"622338897","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nAnalyze URL and Return data Object\r\nUpdate CSV data according to Data coming in\r\n\r\nNew Comment\r\n\r\n\"\"\"\r\n\r\nimport urllib2\r\nimport csv\r\n\r\ndef downloadData(url):\r\n \"\"\"Downloads data from URL\r\n\r\n Args:\r\n url (string): string value for URL data fetch\r\n\r\n Returns:\r\n data: something to return\r\n \"\"\"\r\n\r\n value = urllib2.Request(url)\r\n data = urllib2.urlopen(value)\r\n\r\n #print data.read()\r\n\r\n full_database = {}\r\n\r\n reader = csv.reader(data, delimiter=',')\r\n\r\n for row, item in enumerate(reader):\r\n full_database [row] = {\r\n 'Time_Value': item[0],\r\n 'Time_Spent': item[2],\r\n 'File': item[1]\r\n }\r\n\r\n #print row\r\n\r\n #print 'Image requests account for 45.3% of all requests', img_hit_counter\r\n #print data.read()\r\n\r\n return full_database\r\n","sub_path":"AnalyzeURL.py","file_name":"AnalyzeURL.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"408009373","text":"from ocds.storage.backends.fs import FSStorage\nfrom ocds.storage.backends.main import MainStorage\nfrom ocds.export.record import Record, Record_Package\nimport argparse\nimport yaml\nimport os\nimport time\n\n\ndef read_config(path):\n with open(path) as cfg:\n config = yaml.load(cfg)\n return config\n\n\ndef parse_args():\n parser = argparse.ArgumentParser('Release Packages')\n parser.add_argument('-c', '--config', required=True, help=\"Path to configuration file\")\n parser.add_argument('-p', '--record_pack', action='store_true', help=\"Choose for record pack generator\")\n parser.add_argument('-r', '--record', help=\"Choose for records generator\")\n return parser.parse_args()\n\n\ndef dump_to_file(config, record=None, package=None):\n if record:\n for records in gen_records(config):\n path = os.path.join(config.get('path_for_record'), 'record-{}.json'.format(time.time()))\n with open(path, 'w') as outfile:\n outfile.write(records.to_json())\n if package:\n for pack in gen_pack(config, config.get('release')):\n if not os.path.exists(config.get('path_for_record_package')):\n os.makedirs(config.get('path_for_record_package'))\n path = os.path.join(config.get('path_for_record_package'), 'record-{}.json'.format(time.time()))\n with open(path, 'w') as outfile:\n outfile.write(pack.to_json())\n\n\ndef gen_records(config):\n mstorage = MainStorage(config, config['path_for_release'])\n for releases in mstorage.get_rel_for_record():\n rec = Record(releases, releases[0]['ocid'])\n yield rec\n\n\ndef gen_pack(config, info):\n records = []\n count = 0\n for record in gen_records(config):\n if count == 1000:\n count = 0\n pack = Record_Package(records,\n info['publisher'],\n info['publicationPolicy'],\n info['license']\n )\n records = []\n yield pack\n else:\n records.append(record)\n count += 1\n\n\ndef run():\n args = parse_args()\n config = read_config(args.config)\n if args.record:\n dump_to_file(config, record=True)\n if args.record_pack:\n dump_to_file(config, package=True)\n","sub_path":"ocds/databridge/scripts/records.py","file_name":"records.py","file_ext":"py","file_size_in_byte":2347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"141238084","text":"\"\"\"\nAlex Motor imagery dataset.\n\"\"\"\n\nfrom .base import BaseDataset\nfrom mne.io import Raw\nimport os\n\nfrom . import download as dl\n\nALEX_URL = 'https://zenodo.org/record/806023/files/'\n\ndef data_path(subject, path=None, force_update=False, update_path=None,\n verbose=None):\n \"\"\"Get path to local copy of ALEX dataset URL.\n\n Parameters\n ----------\n subject : int\n Number of subject to use\n path : None | str\n Location of where to look for the data storing location.\n If None, the environment variable or config parameter\n ``MNE_DATASETS_INRIA_PATH`` is used. If it doesn't exist, the\n \"~/mne_data\" directory is used. If the dataset\n is not found under the given path, the data\n will be automatically downloaded to the specified folder.\n force_update : bool\n Force update of the dataset even if a local copy exists.\n update_path : bool | None\n If True, set the MNE_DATASETS_INRIA_PATH in mne-python\n config to the given path. If None, the user is prompted.\n verbose : bool, str, int, or None\n If not None, override default verbose level (see :func:`mne.verbose`).\n\n Returns\n -------\n path : list of str\n Local path to the given data file. This path is contained inside a list\n of length one, for compatibility.\n \"\"\" # noqa: E501\n if subject < 1 or subject > 8:\n raise ValueError(\"Valid subjects between 1 and 8, subject {:d} requested\".format(subject))\n url = '{:s}subject{:d}.raw.fif'.format(ALEX_URL, subject)\n\n\n return dl.data_path(url, 'ALEXEEG', path, force_update, update_path, verbose)\n \nclass AlexMI(BaseDataset):\n \"\"\"Alex Motor Imagery dataset\"\"\"\n\n def __init__(self):\n super().__init__(\n subjects=list(range(1,9)),\n sessions_per_subject=1,\n events=dict(right_hand=2, feet=3, rest=4),\n code='Alexandre Motor Imagery',\n interval=[0,3],\n paradigm='imagery'\n )\n\n def _get_single_subject_data(self, subject, stack_sessions):\n \"\"\"return data for a single subject\"\"\"\n raw = Raw(data_path(subject), preload=True, verbose='ERROR')\n if stack_sessions:\n return [[raw]]\n else:\n return [[[raw]]]\n","sub_path":"moabb/datasets/alex_mi.py","file_name":"alex_mi.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"568285150","text":"import os\nfrom keep_alive import keep_alive\nfrom discord.ext import commands\nimport discord\n\nintents = discord.Intents(\n guilds=True, members=True, messages=True, reactions=True,\n bans=False, emojis=False, integrations=False, webhooks=False, invites=False, voice_states=False, presences=False,\n typing=False\n)\n\nbot = commands.Bot(\n\tcommand_prefix=\"?\", # Change to desired prefix\n\tcase_insensitive=True, # Commands aren't case-sensitive\n intents=intents\n)\nbotauthor = os.environ.get(\"BOT_AUTHOR_ID\") \nbot.author_id = botauthor # Change to your discord id!!!\n\n@bot.event \nasync def on_ready(): # When the bot is ready\n print(\"I'm in\")\n print(bot.user) # Prints the bot's username and identifier\n\n\nextensions = [\n\t'cogs.devtools','cogs.usertools', 'cogs.admintools' # Same name as it would be if you were importing it\n]\n\nif __name__ == '__main__': # Ensures this is the file being ran\n\tfor extension in extensions:\n\t\tbot.load_extension(extension) # Loades every extension.\n\nkeep_alive() # Starts a webserver to be pinged.\ntoken = os.environ.get(\"DISCORD_BOT_SECRET\") \nbot.run(token) # Starts the bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"137149712","text":"from setuptools import setup, find_packages\nfrom morss import __version__\n\nif __name__ == '__main__':\n package_name = 'morss'\n setup(name=package_name,\n description='Get full-text RSS feeds',\n author='pictuga, Samuel Marks',\n author_email='contact at pictuga dot com',\n url='http://morss.it/',\n license='GPL 3+',\n version=__version__,\n package_dir={package_name: package_name},\n packages=find_packages(),\n package_data={package_name: ['feedify.ini']},\n test_suite=package_name + '.tests')\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"204482527","text":"import os\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.layers import Input, Dropout, Convolution2D, Flatten, Dense\nfrom tensorflow.python.keras.layers.merge import concatenate\n\nINPUT_SHAPE = (300, 300, 3) # 300x300 RGB\n\n\ndef create_dense(numerical_in):\n y = numerical_in\n y = Dense(14, activation='relu')(y)\n y = Dense(14, activation='relu')(y)\n y = Dense(14, activation='relu')(y)\n return y\n\n\ndef create_encoder(img_in, tag):\n x = img_in\n x = Convolution2D(24, (5, 5), strides=(2, 2), activation='relu')(x)\n x = Convolution2D(32, (5, 5), strides=(2, 2), activation='relu')(x)\n x = Convolution2D(64, (3, 3), strides=(2, 2), activation='relu')(x)\n x = Convolution2D(64, (3, 3), strides=(1, 1), activation='relu')(x)\n x = Convolution2D(64, (3, 3), strides=(1, 1), activation='relu')(x)\n x = Flatten(name='flattened_' + tag)(x)\n x = Dense(100, activation='relu')(x)\n x = Dropout(.1)(x)\n return x\n\n\ndef create_model(): # img_right_in, img_left_in, img_front_in\n\n # Dense layer inputs\n path_distance_in = Input(shape=(1,), name=\"path_distance_in\")\n bearing_in = Input(shape=(1,), name=\"bearing_in\")\n acc_x_in = Input(shape=(1,), name=\"acc_x_in\")\n acc_y_in = Input(shape=(1,), name=\"acc_y_in\")\n acc_z_in = Input(shape=(1,), name=\"acc_z_in\")\n alt_in = Input(shape=(1,), name=\"alt_in\")\n\n # Define camera inputs\n camera_DEPTH_in = Input(shape=INPUT_SHAPE, name='img_depth_in')\n camera_LEFT_in = Input(shape=INPUT_SHAPE, name='camera_LEFT_in')\n camera_RIGHT_in = Input(shape=INPUT_SHAPE, name='camera_RIGHT_in')\n\n outputs = []\n\n # Create layers\n cam_D = create_encoder(camera_DEPTH_in, 'depth_cam')\n cam_L = create_encoder(camera_LEFT_in, 'left_cam')\n cam_R = create_encoder(camera_RIGHT_in, 'right_cam')\n metadata = create_dense(alt_in)\n\n z = concatenate([cam_D, cam_L, cam_R, metadata])\n\n z = Dense(50, activation='relu')(z)\n z = Dropout(.1)(z)\n z = Dense(50, activation='relu')(z)\n z = Dropout(.1)(z)\n\n for i in range(3):\n outputs.append(Dense(1, activation='linear', name='out_' + str(i))(z))\n\n model = Model(inputs=[camera_DEPTH_in, camera_LEFT_in,\n camera_RIGHT_in, path_distance_in, bearing_in, acc_x_in, acc_y_in, acc_z_in, alt_in], outputs=outputs)\n\n return model\n\n\nmodel = create_model()\n\ndot_img_file = 'model_niek.png'\ntf.keras.utils.plot_model(model, to_file=dot_img_file, show_shapes=True)\n","sub_path":"modules/network_niek.py","file_name":"network_niek.py","file_ext":"py","file_size_in_byte":2503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"288466841","text":"#!/usr/bin/env python3\nimport time\n#import utime\nimport random\nimport atexit\nimport RPi.GPIO as GPIO\nfrom luma.core.interface.serial import spi, noop\nfrom luma.core.render import canvas\nfrom luma.core.legacy import show_message, text\nfrom luma.core.legacy.font import proportional, CP437_FONT, TINY_FONT, SINCLAIR_FONT, LCD_FONT\nfrom luma.led_matrix.device import max7219\nfrom multiprocessing import Process,Array,Value\nimport os,signal,sys\nimport tm1637\n #########################################################################################\n\nclass LedArray:\n serial = spi(port=0, device=0, gpio=noop())\n textList = ['']*5\n\n def __init__(self, numberOfBlocks, font = proportional(TINY_FONT)):\n self.device = max7219(self.serial,width=32*numberOfBlocks,hight=8, block_orientation=-90) #,blocks_arranged_in_reverse_order=\"inreverse\")\n self.textList = ['']*numberOfBlocks\n self.font = font\n\n def write(self, blockNum, itext):\n self.textList[blockNum] = itext\n with canvas(self.device) as draw:\n for mitem in range(len(self.textList)):\n text(draw, (32*mitem, 0), self.textList[mitem], fill=\"white\", font=self.font)\n\n def clear(self):\n self.device.clear()\n\n def settarget(self,target,d,timeupp,hitp):\n print(\"Target\")\n print(target)\n if target == 1:\n p0=(0,0)\n p1=(31,7)\n elif target==2:\n p0=(32,0)\n p1=(63,7)\n elif target==3:\n p0=(64,0)\n p1=(95,7)\n elif target==4:\n p0=(96,0)\n p1=(127,7)\n elif target==5:\n p0=(128,0)\n p1=(159,7)\n\n with canvas(self.device) as draw:\n draw.rectangle([p0,p1], outline=\"white\", fill=\"white\")\n\n time.sleep(0.5)\n for i in range(32):\n if hitp.value == 1 or timeupp.value == 1:\n hitp.value = 0\n break\n\n with canvas(self.device) as draw:\n draw.rectangle([p0, (p1[0]-i,p1[1])],fill=\"white\")\n time.sleep(0.0625)\n\n with canvas(d) as draw:\n draw.rectangle([p0, p1],fill=\"black\")\n\n print(\"target:\"+str(target))\n\nclass SevenSegment:\n def __init__(self):\n self.device = tm1637.TM1637(clk=3, dio=2)\n\n def write(self,val1,val2):\n self.val1 = val1\n self.val2 = val2\n\n self.device.numbers(val1,val2)\n\n\n\nclass Pin:\n pinNum = None\n def __init__(self,pinNum):\n self.pinNum = pinNum\n self.hasCallback = False\n GPIO.setup(self.pinNum, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n\n def registerHandler(self, handler):\n self.deregisterHandler()\n GPIO.add_event_detect(self.pinNum, GPIO.FALLING, callback=handler)\n self.hasCallback = True\n\n def deregisterHandler(self):\n if self.hasCallback:\n GPIO.remove_event_detect(self.pinNum)\n\nclass Board:\n def __init__(self):\n self.pins = []\n GPIO.setmode(GPIO.BCM)\n\n def getPin(self, pinNum):\n pin = list(filter(lambda p: p.pinNum == pinNum, self.pins))\n if not pin:\n pin.append(Pin(pinNum))\n self.pins = self.pins + pin\n return pin[0]\n\nclass Menu:\n def __init__(self, display, pins, items):\n self.display = display\n self.pins = pins\n self.items = items\n for i in items:\n i.menu = self\n\n def show(self, channel):\n for p in self.pins:\n p.deregisterHandler()\n for i in range(len(self.items)):\n self.pins[i].registerHandler(self.items[i].fn)\n for i in range(len(self.items)):\n self.display.write(i, self.items[i].label)\n\nclass MenuItem:\n def __init__(self, label, fn):\n self.fn = lambda c: self.execute(fn)\n self.label = label\n\n def execute(self,fn):\n fn(0)\n #self.menu.show(0)\n\n\n\nclass Port:\n def __init__(self, inputs):\n self.inputs = inputs\n\n\n\n\nclass Game:\n def __init__(self,display, pins, sevenseg):\n print(display)\n self.display = display\n self.pins = pins\n self.sevenseg = sevenseg\n self.target= None\n\n\n self.timep = Value('i',0)\n self.timeupp = Value('i',0)\n self.hitcountp = Value('i',0)\n self.hitp = Value('i',0)\n\n currentgame = RandT\n\n def setgame(self,igame):\n self.currentgame = igame\n\n\n def resetscore():\n sevenseg.numbers(0,0)\n\n def setscore(self,starttime, gametime,timeupp,hitcountp):\n while time.time()-starttime\\d+)/$', views.CartCompAdd, name='CartCompAdd'),\n url(r'^comp_remove/(?P\\d+)/$', views.CartCompRemove, name='CartCompRemove'),\n\n]\n","sub_path":"cart_comp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"311853073","text":"from flask import Flask, request\nfrom flask_restful import Resource, Api\nfrom json import dumps\nfrom flask import jsonify\nfrom contextlib import closing\nimport requests\n\napp = Flask(__name__)\napi = Api(app)\n\nclass Query(Resource):\n def post(self):\n url = 'http://transltr.io:7071/validate_querygraph'\n scaffoldUrl='https://raw.githubusercontent.com/NCATSTranslator/KnowledgeProviderScaffold/master/TranslatorKnowledgeProviderResponseScaffold.json'\n query = request.get_json(force = True)\n with closing(requests.post(url, json=query, stream=False)) as response:\n status_code = response.status_code\n if(status_code==200):\n response = requests.get(scaffoldUrl)\n result=response.text\n print(\"yo\")\n else:\n result = {'data':'bad'}\n print(str(status_code))\n\n return jsonify(result)\n\n\napi.add_resource(Query,'/query')\n\nif __name__=='__main__':\n app.run(\n port='7072',\n debug=True\n )\n \n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"432102954","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport os\nimport re\n'''\nadd sc verse labels to verses\n'''\nbase_dir = os.environ['HOME']+'/Desktop/'\nsuttadir = base_dir+'toconvert/'\nos.mkdir(base_dir+'converted/')\nscnr = 976\n\ndef addscversecode(line):\n global scnr\n if re.search('',line):\n line = line.replace('','')\n scnr += 1\n return line\n\nfor namenr in range(1,20):\n name = \"snp5.\"+str(namenr)+\".html\"\n print (name)\n fileOpen = open(suttadir+name,'r')\n fileWrite = open(base_dir+'converted/'+name, 'w')\n for line in fileOpen:\n fileWrite.write(line)\n if line.startswith(\"l 1st decrease num\n i=n-1\n while i>0 and num[i-1]>=num[i]:\n i-=1\n\n # none decrease num\n if i==0:\n num.reverse()\n return\n\n # r->l 1st > num[i-1]\n k=n-1\n while k>i-1 and num[k]<=num[i-1]:\n k-=1\n\n # swap i-1, k\n num[i-1],num[k]=num[k],num[i-1]\n\n # swap i:-1\n l, r=i,n-1\n while l= 0.0, 1, -1)\n\nimport pandas as pd\n\"\"\"\n读取数据源\n\"\"\"\ndf = pd.read_csv(\"/Users/a1/Downloads/iris.data\", header=None)\nprint(df.tail()) # 打印后几行\ny = df.iloc[0:100, 4].values # 取前100行数据的第4列,类标这一列,前100行就两类\nprint(y)\ny = np.where(y == 'Iris-setosa', -1, 1) # 将类标这一列的文本表示替换成数字表示,就分了两类\nX = df.iloc[0:100, [0, 2]].values # 获取前100行的第0列和第2列,即花瓣宽度和花萼宽度\nprint(X)\n\n\"\"\"\n对模型进行训练,查看训练时每次迭代的错误数量\n\"\"\"\nppn= Perceptron(eta=0.1, n_iter=10)\nppn.fit(X,y)","sub_path":"test/test3.py","file_name":"test3.py","file_ext":"py","file_size_in_byte":3184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"167423733","text":"import requests\nfrom flask import Flask, request, abort\nfrom bs4 import BeautifulSoup\nimport json\nfrom Project.flex import *\nfrom Project.Config import *\n\napp = Flask(__name__)\n\n\n@app.route('/vg', methods = ['POST','GET'])\ndef vg():\n if request.method == 'POST':\n payload = request.json\n\n Reply_token = payload['events'][0]['replyToken']\n message = payload['events'][0]['message']['text']\n url = \"https://en.cf-vanguard.com/cardlist/?cardno=\" + message + \"EN\"\n data = requests.get(url)\n soup = BeautifulSoup(data.text,'html.parser')\n card = soup.find(\"div\",{\"class\":\"effect\"})\n cardPic = soup.find(\"div\",{\"class\":\"main\"})\n print(\"___________________________________\")\n cardSkill = card.text\n cardImgSrc = \"\"\n cardName = \"\"\n print(card)\n for img in cardPic:\n print (img['src'])\n cardImgSrc = img['src']\n cardName = img['alt']\n\n\n \n ReplyMessageSearch (Reply_token, message, Channel_access_token, cardSkill, cardImgSrc, cardName)\n\n return request.json, 200\n\n elif request.method == 'GET' :\n return 'this is method GET!!!' , 200\n\n else:\n abort(400)\n\n\n\n\n\n\ndef ReplyMessageSearch(Reply_token, message, Line_Access_Token, cardSkill, cardImgSrc, cardName):\n LINE_API = 'https://api.line.me/v2/bot/message/reply'\n Authorization = 'Bearer {}'.format(Channel_access_token)\n print(Authorization)\n headers = {\n 'Content-Type': 'application/json; charset=UTF-8',\n 'Authorization': Authorization\n }\n data = {\n \"replyToken\":Reply_token,\n \"messages\":[\n flex(cardSkill,cardImgSrc,cardName)\n ]\n}\n \n \n\n data = json.dumps(data) ## dump dict >> Json Object\n requests.post(LINE_API, headers=headers, data=data) \n return 200","sub_path":"Project/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"527849318","text":"from client import Client\n\n\ndef main():\n client = Client(\"0.0.0.0\", 8080)\n\n result = client.scan(\n prefix=\"2020-02-08|KL|90\",\n columns={\"basic_info\": []},\n max_versions=1,\n table_name=\"flight_leg_departures\",\n table_namespace=\"flight720\"\n )\n\n print(result.get_row_df())\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python-client/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"510801029","text":"from SimpleCV import Display, Camera, time\nfrom SimpleCV import *\n\ndef movement_check(x = 0,t=1):\n\tdirectionX = \"\"\n\tif x > t:\n\t\tdirectionX = 'Encender el foco' #Right\n\tif x < -1*t:\n\t\tdirectionX = \"Apagar el foco\" #Left\n\n\tif directionX is not \"\":\n\t\treturn directionX\n\telse:\n\t\treturn \"No Motion\"\n\ndef control_by_cam():\n\tscale_amount = (200,150)\n\td = Display(scale_amount)\n\tcam = Camera(0)\n\tprev = cam.getImage().flipHorizontal().scale(scale_amount[0],scale_amount[1])\n\ttime.sleep(0.5)\n\tt = 0.5\n\tbuffer = 20\n\tcount = 0\n\twhile d.isNotDone():\n\t\tcurrent = cam.getImage().flipHorizontal()\n\t\tcurrent = current.scale(scale_amount[0],scale_amount[1])\n\t\tif( count < buffer ):\n\t\t\tcount = count + 1\n\t\telse:\n\t\t\tfs = current.findMotion(prev, window=15, method=\"BM\")\n\t\t\tlengthOfFs = len(fs)\n\t\t\tif fs:\n\t\t\t\tdx = 0\n\t\t\t\tfor f in fs:\n\t\t\t\t\tdx = dx + f.dx\n\t\t\t\tdx = (dx / lengthOfFs)\n\t\t\t\tmotionStr = movement_check(dx,t)\n\t\t\t\tcurrent.drawText(motionStr,10,10)\n\t\tprev = current\n\t\ttime.sleep(0.01)\n\t\tcurrent.save(d)\n\t\treturn motionStr\n\n","sub_path":"Proyecto Agente Inteligente/Project_os/agent_program/opencv.py","file_name":"opencv.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"210275361","text":"import torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport random\nfrom seq2seq.config import USE_CUDA\n\nfrom seq2seq.config import EOS_token,SOS_token\n\n\n\n\nclass EncoderRNN(nn.Module):\n def __init__(self, n_dict ,config):\n super(EncoderRNN, self).__init__()\n\n self.n_dict=n_dict\n self.input_dim = config.input_dim\n self.hidden_dim = config.hidden_dim\n self.n_layers = config.n_input_layers\n\n self.embedding = nn.Embedding(self.n_dict, self.input_dim)\n self.gru = nn.GRU(self.input_dim, self.hidden_dim, self.n_layers)\n\n def forward(self, word_inputs, hidden):\n # Note: we run this all at once (over the whole input sequence)\n seq_len = len(word_inputs)\n embedded = self.embedding(word_inputs).view(seq_len, 1, -1)\n output, hidden = self.gru(embedded, hidden)\n return output, hidden\n\n def init_hidden(self):\n hidden = Variable(torch.zeros(self.n_layers, 1, self.hidden_size))\n if USE_CUDA: hidden = hidden.cuda()\n return hidden\n\nclass Attn(nn.Module):\n def __init__(self,config):\n super(Attn, self).__init__()\n\n self.method = config.attn_model\n self.hidden_dim = config.hidden_dim\n self.max_length=config.max_length\n if self.method == 'general':\n self.attn = nn.Linear(self.hidden_dim, self.hidden_dim)\n\n elif self.method == 'concat':\n self.attn = nn.Linear(self.hidden_dim * 2, self.hidden_dim)\n self.other = nn.Parameter(torch.FloatTensor(1, self.hidden_dim))\n\n def forward(self, hidden, encoder_outputs):\n seq_len = len(encoder_outputs)\n\n # Create variable to store attention energies\n attn_energies = Variable(torch.zeros(seq_len)) # B x 1 x S\n if USE_CUDA: attn_energies = attn_energies.cuda()\n\n # Calculate energies for each encoder output\n for i in range(seq_len):\n attn_energies[i] = self.score(hidden, encoder_outputs[i])\n\n # Normalize energies to weights in range 0 to 1, resize to 1 x 1 x seq_len\n return F.softmax(attn_energies).unsqueeze(0).unsqueeze(0)\n\n def score(self, hidden, encoder_output):\n\n if self.method == 'dot':\n energy = hidden.dot(encoder_output)\n return energy\n\n elif self.method == 'general':\n energy = self.attn(encoder_output)\n energy = hidden.dot(energy)\n return energy\n\n elif self.method == 'concat':\n energy = self.attn(torch.cat((hidden, encoder_output), 1))\n energy = self.other.dot(energy)\n return energy\n\n\nclass AttnDecoderRNN(nn.Module):\n def __init__(self, n_dict,config):\n super(AttnDecoderRNN, self).__init__()\n\n # Keep parameters for reference\n self.config=config\n self.n_dict=n_dict\n self.attn_model = config.attn_model\n self.hidden_dim = config.hidden_dim\n self.output_dim = config.output_dim\n self.n_layers = config.n_output_layers\n self.dropout_p = config.dropout_p\n\n # Define layers\n self.embedding = nn.Embedding(self.n_dict, self.output_dim)\n #TODO : this is wrong\n self.gru = nn.GRU(self.output_dim + self.hidden_dim, self.hidden_dim, self.n_layers, dropout=self.dropout_p)\n #TODO : this is wrong\n self.out = nn.Linear(self.hidden_dim * 2, n_dict)\n\n # Choose attention model\n if self.attn_model != 'none':\n self.attn = Attn(self.config)\n\n def forward(self, word_input, last_context, last_hidden, encoder_outputs):\n # Note: we run this one step at a time\n\n # Get the embedding of the current input word (last output word)\n word_embedded = self.embedding(word_input).view(1, 1, -1) # S=1 x B x N\n\n # Combine embedded input word and last context, run through RNN\n rnn_input = torch.cat((word_embedded, last_context.unsqueeze(0)), 2)\n rnn_output, hidden = self.gru(rnn_input, last_hidden)\n\n # Calculate attention from current RNN state and all encoder outputs; apply to encoder outputs\n attn_weights = self.attn(rnn_output.squeeze(0), encoder_outputs)\n context = attn_weights.bmm(encoder_outputs.transpose(0, 1)) # B x 1 x N\n\n # Final output layer (next word prediction) using the RNN hidden state and context vector\n rnn_output = rnn_output.squeeze(0) # S=1 x B x N -> B x N\n context = context.squeeze(1) # B x S=1 x N -> B x N\n output = F.log_softmax(self.out(torch.cat((rnn_output, context), 1)))\n\n # Return final output, hidden state, and attention weights (for visualization)\n return output, context, hidden, attn_weights\n\n\ndef train(input_variable, target_variable, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion,\n teacher_forcing_ratio=0.1,clip=5.0,max_length=10):\n # Zero gradients of both optimizers\n encoder_optimizer.zero_grad()\n decoder_optimizer.zero_grad()\n loss = 0 # Added onto for each word\n\n # Get size of input and target sentences\n input_length = input_variable.size()[0]\n target_length = target_variable.size()[0]\n\n # Run words through encoder\n encoder_hidden = encoder.init_hidden()\n encoder_outputs, encoder_hidden = encoder(input_variable, encoder_hidden)\n\n # Prepare input and output variables\n decoder_input = Variable(torch.LongTensor([[SOS_token]]))\n decoder_context = Variable(torch.zeros(1, decoder.hidden_size))\n decoder_hidden = encoder_hidden # Use last hidden state from encoder to start decoder\n if USE_CUDA:\n decoder_input = decoder_input.cuda()\n decoder_context = decoder_context.cuda()\n\n # Choose whether to use teacher forcing\n use_teacher_forcing = random.random() < teacher_forcing_ratio\n if use_teacher_forcing:\n\n # Teacher forcing: Use the ground-truth target as the next input\n for di in range(target_length):\n decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input, decoder_context,\n decoder_hidden,\n encoder_outputs)\n loss += criterion(decoder_output[0], target_variable[di])\n decoder_input = target_variable[di] # Next target is next input\n\n else:\n # Without teacher forcing: use network's own prediction as the next input\n for di in range(target_length):\n decoder_output, decoder_context, decoder_hidden, decoder_attention = decoder(decoder_input, decoder_context,\n decoder_hidden,\n encoder_outputs)\n loss += criterion(decoder_output[0], target_variable[di])\n\n # Get most likely word index (highest value) from output\n topv, topi = decoder_output.data.topk(1)\n ni = topi[0][0]\n\n decoder_input = Variable(torch.LongTensor([[ni]])) # Chosen word is next input\n if USE_CUDA: decoder_input = decoder_input.cuda()\n\n # Stop at end of sentence (not necessary when using known targets)\n if ni == EOS_token: break\n\n # Backpropagation\n loss.backward()\n torch.nn.utils.clip_grad_norm(encoder.parameters(), clip)\n torch.nn.utils.clip_grad_norm(decoder.parameters(), clip)\n encoder_optimizer.step()\n decoder_optimizer.step()\n\n return loss.data[0] / target_length\n\n\nif __name__ == '__main__':\n pass","sub_path":"seq2seq/model/model1.py","file_name":"model1.py","file_ext":"py","file_size_in_byte":7722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"180430932","text":"\"\"\"drop column tag_len of tags\n\nRevision ID: 0f5713480f67\nRevises: 763767a279b6\nCreate Date: 2018-06-19 14:41:30.546193\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '0f5713480f67'\ndown_revision = '763767a279b6'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.drop_column('tags', 'tag_len')\n\n\ndef downgrade():\n op.add_column('tags', sa.Column('tag_len', sa.Integer))\n","sub_path":"test_dir/come_on_first/migrations/versions/20180619144130_drop_column_tag_len_of_tags.py","file_name":"20180619144130_drop_column_tag_len_of_tags.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"633060267","text":"from django.urls import path\n\nfrom mrsattachment.views import (\n MRSFileDeleteView,\n MRSFileDownloadView,\n MRSFileUploadView,\n)\n\nfrom .models import Bill\n\n\napp_name = 'transport'\nurlpatterns = [\n path(\n '/delete',\n MRSFileDeleteView.as_view(model=Bill),\n name='bill_destroy'\n ),\n path(\n '/download',\n MRSFileDownloadView.as_view(model=Bill),\n name='bill_download'\n ),\n path(\n '/upload',\n MRSFileUploadView.as_view(model=Bill),\n name='bill_upload'\n ),\n]\n","sub_path":"src/transport/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"233381829","text":"# Copyright 2020 Vectorized, Inc.\n#\n# Use of this software is governed by the Business Source License\n# included in the file licenses/BSL.md\n#\n# As of the Change Date specified in that file, in accordance with\n# the Business Source License, use of this software will be governed\n# by the Apache License, Version 2.0\nimport os\n\nfrom ducktape.tests.test import Test\nfrom rptest.services.redpanda import RedpandaService\nfrom rptest.clients.kafka_cli_tools import KafkaCliTools\n\n\nclass RedpandaTest(Test):\n \"\"\"\n Base class for tests that use the Redpanda service.\n \"\"\"\n\n # List of topics to be created automatically when the cluster starts. Each\n # topic is defined by an instance of a TopicSpec.\n topics = ()\n\n def __init__(self,\n test_context,\n num_brokers=3,\n extra_rp_conf=dict(),\n topics=None,\n enable_pp=False,\n enable_sr=False,\n num_cores=3):\n super(RedpandaTest, self).__init__(test_context)\n\n self.redpanda = RedpandaService(test_context,\n num_brokers,\n KafkaCliTools,\n extra_rp_conf=extra_rp_conf,\n enable_pp=enable_pp,\n enable_sr=enable_sr,\n topics=self.topics,\n num_cores=num_cores)\n\n @property\n def topic(self):\n \"\"\"\n Return the name of the auto-created initial topic. Accessing this\n property requires exactly one initial topic be configured.\n \"\"\"\n assert len(self.topics) == 1\n return self.topics[0].name\n\n def setUp(self):\n self.redpanda.start()\n","sub_path":"tests/rptest/tests/redpanda_test.py","file_name":"redpanda_test.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"478531915","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis tests standard behaviour of multilingual models\n\"\"\"\nfrom django.test import TestCase\n\nfrom multilingual.languages import lock, release\nfrom multilingual.db.models.query import MultilingualQuerySet\n\nfrom models import Basic, Managing, Untranslated\n\n\nclass ModelTest(TestCase):\n def tearDown(self):\n # Remove language locks if any remains\n release()\n\n # Model tests\n def test01_fixtures(self):\n # Just test whether fixtures were loaded properly\n obj = Basic.objects.get(pk=1)\n self.assertEqual(obj.description, u'regular ěščřžýáíé')\n\n def test02_proxy_fields(self):\n # Test proxy fields reading\n obj = Basic.objects.get(pk=1)\n self.assertEqual(obj.title, u'obsah ěščřžýáíé')\n self.assertEqual(obj.title_cs, u'obsah ěščřžýáíé')\n self.assertEqual(obj.title_en, u'content')\n\n def test03_proxy_fields_fallbacks(self):\n # Test proxy fields reading\n obj = Basic.objects.get(pk=2)\n self.assertEqual(obj.title, u'pouze čeština')\n self.assertEqual(obj.title_cs, u'pouze čeština')\n self.assertEqual(obj.title_en, None)\n lock('en')\n self.assertEqual(obj.title, u'pouze čeština')\n release()\n\n obj = Basic.objects.get(pk=3)\n # Do not forget we have activated czech language\n self.assertEqual(obj.title, None)\n self.assertEqual(obj.title_cs, None)\n self.assertEqual(obj.title_en, u'only english')\n\n obj = Basic.objects.get(pk=4)\n self.assertEqual(obj.title, None)\n self.assertEqual(obj.title_cs, None)\n self.assertEqual(obj.title_en, None)\n\n # Manager tests\n def test10_manager_filter(self):\n queryset = Managing.objects.filter(name_cs=u'č')\n self.assertEqual(len(queryset), 1)\n self.assertEqual(queryset[0].shortcut, u'c2')\n\n def test11_manager_exclude(self):\n queryset = Managing.objects.exclude(name_en__isnull=True)\n result = set(obj.shortcut for obj in queryset)\n self.assertEqual(len(queryset), 11)\n self.assertEqual(len(result), 11)\n self.assertEqual(result, set([u'a', u'b', u'c', u'd', u'e', u'h', u'i', u'w', u'x', u'y', u'z']))\n\n def test12_manager_create(self):\n obj = Managing.objects.create(shortcut=u'n2', name_cs=u'ň')\n self.assertEqual(obj.shortcut, u'n2')\n self.assertEqual(obj.name, u'ň')\n\n def test13_manager_get_or_create(self):\n Managing.objects.create(shortcut=u'n2', name_cs=u'ň')\n\n obj, created = Managing.objects.get_or_create(shortcut=u'n2', name_cs=u'ň')\n self.assertEqual(created, False)\n self.assertEqual(obj.shortcut, u'n2')\n self.assertEqual(obj.name, u'ň')\n\n def test14_manager_delete(self):\n Managing.objects.create(shortcut=u'n2', name_cs=u'ň')\n\n ManagingTranslation = Managing._meta.translation_model\n obj = ManagingTranslation.objects.get(name=u'ň')\n self.assertEqual(obj.master.shortcut, u'n2')\n Managing.objects.filter(shortcut=u'n2').delete()\n self.assertRaises(ManagingTranslation.DoesNotExist, ManagingTranslation.objects.get, name=u'ň')\n\n def test15_manager_order_by(self):\n # If you do not know it, ordering is dependent on locales.\n # So if you apply ordering rules on set of words from different language it will be\n # ordered differently than it should. That also may cause problems if application is run\n # with different locales than database.\n proper_result = [u'a', u'b', u'c', u'č', u'd', u'ď', u'e', u'é', u'ě', u'h', u'ch', u'i', u'ř', u'ž']\n # Re-sort to avoid false failure if your database does not run with czech locales\n proper_result.sort()\n queryset = Managing.objects.filter(name_cs__isnull=False).order_by('name_cs')\n result = list(obj.name_cs for obj in queryset)\n self.assertEqual(result, proper_result)\n\n def test16_manager_select_related(self):\n def query_without_select_related():\n obj = Managing.objects.get(pk=1)\n self.assertEqual(obj.name_cs, u'a')\n\n def query_with_select_related():\n obj = Managing.objects.select_related('translations').get(pk=1)\n self.assertEqual(obj.name_cs, u'a')\n\n # setup\n Untranslated.objects.create(name='u1', basic_id=1)\n\n # tests\n self.assertNumQueries(2, query_without_select_related)\n self.assertNumQueries(1, query_with_select_related)\n\n def test17_manager_values(self):\n names = [u'e', u'é', u'ě']\n values = Managing.objects.filter(shortcut__startswith=u'e').values('name')\n for item in values:\n names.pop(names.index(item['name']))\n self.assertEqual(names, [])\n\n def test18_manager_values_list(self):\n names = set([u'e', u'é', u'ě'])\n values = Managing.objects.filter(shortcut__startswith=u'e').values_list('name', flat=True)\n self.assertEqual(set(values), names)\n\n def test19_manager_prefetch_related(self):\n def query_from_untranslated_model():\n lock('en')\n try:\n # Use prefetch_related; start the query from an untranslated model\n qs = Untranslated.objects\\\n .select_related('basic')\\\n .prefetch_related('basic__translations')\n\n self.assertEqual(\n ','.join(\n '%s %s' % (u.name, u.basic.title) for u in qs\n ),\n 'u1 content,u2 only english'\n )\n finally:\n release()\n\n # setup\n Untranslated.objects.create(name='u1', basic_id=1)\n Untranslated.objects.create(name='u2', basic_id=3)\n\n self.assertNumQueries(2, query_from_untranslated_model)\n #TODO: test other manager methods\n","sub_path":"multilingual/tests/core/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":5924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"406308527","text":"from Tkinter import *\nfrom random import randint\n\n\nclass Abfrager(object):\n\n \"\"\"Die Klasse Abfrager dient dem Ueben der Malfolgen im Bereich 10 * 10.\"\"\"\n\n def __init__(self):\n self.fenster = Tk()\n self.fenster.title(\"Malfolgen\")\n\n self.aufgabe = Label(self.fenster, font=(\"Papyrus\", 30), width=10)\n self.neue_aufgabe_erstellen()\n\n self.antwort = Entry(self.fenster)\n self.antwort.bind(\"\", self.antwort_auswerten)\n\n self.auswertung = Label(\n self.fenster, text=\"Antwort eingeben ...\",\n font=(\"Papyrus\", 15), fg=\"grey\"\n )\n\n self.aufgabe.pack()\n self.antwort.pack()\n self.auswertung.pack()\n self.fenster.mainloop()\n\n def neue_aufgabe_erstellen(self):\n a, b = randint(2, 10), randint(2, 10)\n self.aufgabe.config(text=\"%i * %i\" % (a, b))\n self.loesung = str(a * b)\n\n def antwort_auswerten(self, event):\n if self.antwort.get() == self.loesung:\n self.auswertung.config(text=\"RICHTIG\", fg=\"#33CC33\")\n self.neue_aufgabe_erstellen()\n else:\n self.auswertung.config(text=\"FALSCH\", fg=\"red\")\n self.antwort.delete(0, END)\n\n\nAbfrager()\n","sub_path":"abfrager.py","file_name":"abfrager.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"149387419","text":"#!/usr/bin/env python3\n\n#\n# This file is part of Linux-on-LiteX-VexRiscv\n#\n# Copyright (c) 2019-2021, Linux-on-LiteX-VexRiscv Developers\n# SPDX-License-Identifier: BSD-2-Clause\n\nimport json\nimport argparse\n\nfrom litex.soc.cores.cpu import VexRiscvSMP\nfrom migen import *\n\nfrom litex.build.generic_platform import *\nfrom litex.build.sim import SimPlatform\nfrom litex.build.sim.config import SimConfig\n\nfrom litex.soc.interconnect.csr import *\nfrom litex.soc.integration.soc_core import *\nfrom litex.soc.integration.builder import *\nfrom litex.soc.interconnect import wishbone\n\nfrom litedram import modules as litedram_modules\nfrom litedram.phy.model import SDRAMPHYModel\nfrom litex.tools.litex_sim import sdram_module_nphases, get_sdram_phy_settings\nfrom litedram.core.controller import ControllerSettings\n\nfrom liteeth.phy.model import LiteEthPHYModel\nfrom liteeth.mac import LiteEthMAC\n\nfrom litex.tools.litex_json2dts_linux import generate_dts\n\n# IOs ----------------------------------------------------------------------------------------------\n\n_io = [\n (\"sys_clk\", 0, Pins(1)),\n (\"sys_rst\", 0, Pins(1)),\n (\"serial\", 0,\n Subsignal(\"source_valid\", Pins(1)),\n Subsignal(\"source_ready\", Pins(1)),\n Subsignal(\"source_data\", Pins(8)),\n\n Subsignal(\"sink_valid\", Pins(1)),\n Subsignal(\"sink_ready\", Pins(1)),\n Subsignal(\"sink_data\", Pins(8)),\n ),\n (\"eth_clocks\", 0,\n Subsignal(\"none\", Pins()),\n ),\n (\"eth\", 0,\n Subsignal(\"source_valid\", Pins(1)),\n Subsignal(\"source_ready\", Pins(1)),\n Subsignal(\"source_data\", Pins(8)),\n\n Subsignal(\"sink_valid\", Pins(1)),\n Subsignal(\"sink_ready\", Pins(1)),\n Subsignal(\"sink_data\", Pins(8)),\n ),\n]\n\n# Platform -----------------------------------------------------------------------------------------\n\nclass Platform(SimPlatform):\n def __init__(self):\n SimPlatform.__init__(self, \"SIM\", _io)\n\n# Supervisor ---------------------------------------------------------------------------------------\n\nclass Supervisor(Module, AutoCSR):\n def __init__(self):\n self._finish = CSR() # controlled from CPU\n self.finish = Signal() # controlled from logic\n self.sync += If(self._finish.re | self.finish, Finish())\n\n# SoCLinux -----------------------------------------------------------------------------------------\n\nclass SoCLinux(SoCCore):\n csr_map = {**SoCCore.csr_map, **{\n \"ctrl\": 0,\n \"uart\": 2,\n \"timer0\": 3,\n }}\n interrupt_map = {**SoCCore.interrupt_map, **{\n \"uart\": 0,\n \"timer0\": 1,\n }}\n mem_map = {**SoCCore.mem_map, **{\n \"ethmac\": 0xb0000000,\n \"spiflash\": 0xd0000000,\n \"csr\": 0xf0000000,\n }}\n\n def __init__(self,\n init_memories = False,\n sdram_module = \"MT48LC16M16\",\n sdram_data_width = 32,\n sdram_verbosity = 0,\n with_ethernet = False):\n platform = Platform()\n sys_clk_freq = int(100e6)\n\n ram_init = []\n if init_memories:\n ram_init = get_mem_data({\n \"images/Image\": \"0x00000000\",\n \"images/rv32.dtb\": \"0x00ef0000\",\n \"images/rootfs.cpio\": \"0x01000000\",\n \"images/opensbi.bin\": \"0x00f00000\"\n }, \"little\")\n\n # CRG --------------------------------------------------------------------------------------\n self.submodules.crg = CRG(platform.request(\"sys_clk\"))\n\n # SoCCore ----------------------------------------------------------------------------------\n SoCCore.__init__(self, platform, clk_freq=sys_clk_freq,\n cpu_type = \"vexriscv_smp\",\n cpu_variant = \"linux\",\n integrated_rom_size = 0x8000,\n uart_name = \"sim\")\n self.add_config(\"DISABLE_DELAYS\")\n\n # Add linker region for OpenSBI\n self.add_memory_region(\"opensbi\", self.mem_map[\"main_ram\"] + 0x00f00000, 0x80000, type=\"cached+linker\")\n self.add_constant(\"ROM_BOOT_ADDRESS\", self.bus.regions[\"opensbi\"].origin)\n\n # Supervisor -------------------------------------------------------------------------------\n self.submodules.supervisor = Supervisor()\n\n # SDRAM ------------------------------------------------------------------------------------\n sdram_clk_freq = int(100e6) # FIXME: use 100MHz timings\n sdram_module_cls = getattr(litedram_modules, sdram_module)\n sdram_rate = \"1:{}\".format(sdram_module_nphases[sdram_module_cls.memtype])\n sdram_module = sdram_module_cls(sdram_clk_freq, sdram_rate)\n phy_settings = get_sdram_phy_settings(\n memtype = sdram_module.memtype,\n data_width = sdram_data_width,\n clk_freq = sdram_clk_freq)\n self.submodules.sdrphy = SDRAMPHYModel(\n module = sdram_module,\n settings = phy_settings,\n clk_freq = sdram_clk_freq,\n verbosity = sdram_verbosity,\n init = ram_init)\n self.add_sdram(\"sdram\",\n phy = self.sdrphy,\n module = sdram_module,\n origin = self.mem_map[\"main_ram\"],\n l2_cache_size = 0)\n self.add_constant(\"SDRAM_TEST_DISABLE\") # Skip SDRAM test to avoid corrupting pre-initialized contents.\n\n # Ethernet ---------------------------------------------------------------------------------\n if with_ethernet:\n # eth phy\n self.submodules.ethphy = LiteEthPHYModel(self.platform.request(\"eth\", 0))\n # eth mac\n ethmac = LiteEthMAC(phy=self.ethphy, dw=32,\n interface=\"wishbone\", endianness=self.cpu.endianness)\n self.submodules.ethmac = ethmac\n self.add_memory_region(\"ethmac\", self.mem_map[\"ethmac\"], 0x2000, type=\"io\")\n self.add_wb_slave(self.mem_map[\"ethmac\"], self.ethmac.bus)\n self.add_interrupt(\"ethmac\")\n\n def generate_dts(self, board_name):\n json_src = os.path.join(\"build\", board_name, \"csr.json\")\n dts = os.path.join(\"build\", board_name, \"{}.dts\".format(board_name))\n with open(json_src) as json_file, open(dts, \"w\") as dts_file:\n dts_content = generate_dts(json.load(json_file))\n dts_file.write(dts_content)\n\n def compile_dts(self, board_name):\n dts = os.path.join(\"build\", board_name, \"{}.dts\".format(board_name))\n dtb = os.path.join(\"images\", \"rv32.dtb\")\n os.system(\"dtc -O dtb -o {} {}\".format(dtb, dts))\n\n# Build --------------------------------------------------------------------------------------------\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Linux on LiteX-VexRiscv Simulation\")\n parser.add_argument(\"--with-sdram\", action=\"store_true\", help=\"enable SDRAM support\")\n parser.add_argument(\"--sdram-module\", default=\"MT48LC16M16\", help=\"Select SDRAM chip\")\n parser.add_argument(\"--sdram-data-width\", default=32, help=\"Set SDRAM chip data width\")\n parser.add_argument(\"--sdram-verbosity\", default=0, help=\"Set SDRAM checker verbosity\")\n parser.add_argument(\"--with-ethernet\", action=\"store_true\", help=\"enable Ethernet support\")\n parser.add_argument(\"--local-ip\", default=\"192.168.1.50\", help=\"Local IP address of SoC (default=192.168.1.50)\")\n parser.add_argument(\"--remote-ip\", default=\"192.168.1.100\", help=\"Remote IP address of TFTP server (default=192.168.1.100)\")\n parser.add_argument(\"--trace\", action=\"store_true\", help=\"enable VCD tracing\")\n parser.add_argument(\"--trace-start\", default=0, help=\"cycle to start VCD tracing\")\n parser.add_argument(\"--trace-end\", default=-1, help=\"cycle to end VCD tracing\")\n parser.add_argument(\"--opt-level\", default=\"O3\", help=\"compilation optimization level\")\n parser.add_argument(\"--threads\", default=1, help=\"Set number of threads (default=1)\")\n VexRiscvSMP.args_fill(parser)\n args = parser.parse_args()\n\n VexRiscvSMP.args_read(args)\n sim_config = SimConfig(default_clk=\"sys_clk\")\n sim_config.add_module(\"serial2console\", \"serial\")\n if args.with_ethernet:\n sim_config.add_module(\"ethernet\", \"eth\", args={\"interface\": \"tap0\", \"ip\": args.remote_ip})\n\n for i in range(2):\n soc = SoCLinux( i!=0,\n sdram_module = args.sdram_module,\n sdram_data_width = int(args.sdram_data_width),\n sdram_verbosity = int(args.sdram_verbosity),\n with_ethernet = args.with_ethernet)\n if args.with_ethernet:\n for i in range(4):\n soc.add_constant(\"LOCALIP{}\".format(i+1), int(args.local_ip.split(\".\")[i]))\n for i in range(4):\n soc.add_constant(\"REMOTEIP{}\".format(i+1), int(args.remote_ip.split(\".\")[i]))\n board_name = \"sim\"\n build_dir = os.path.join(\"build\", board_name)\n builder = Builder(soc, output_dir=build_dir,\n compile_gateware = i != 0 ,\n csr_json = os.path.join(build_dir, \"csr.json\"))\n builder.build(sim_config=sim_config,\n run = i != 0,\n opt_level = args.opt_level,\n trace = args.trace,\n trace_start = int(args.trace_start),\n trace_end = int(args.trace_end),\n threads = args.threads)\n if i == 0:\n soc.generate_dts(board_name)\n soc.compile_dts(board_name)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"sim.py","file_name":"sim.py","file_ext":"py","file_size_in_byte":9746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"9465209","text":"from abc import abstractmethod\nimport hashlib\nimport pickle\nfrom pathlib import Path\nfrom os.path import abspath\nimport os\nimport logging\nimport json\nimport sys\nimport shutil\nfrom typing import List\n\nfrom prodmodel import util\nfrom prodmodel.model.files.input_file import InputFile\nfrom prodmodel.globals import TargetConfig\n\n\nOUTPUT_FILE_NAME = 'output_1.pickle'\n\n\nclass Target:\n # TODO List[Target]\n def __init__(self, sources: List[InputFile], deps: List, file_deps: List[InputFile]=[]):\n self.sources = sources\n self.deps = deps\n self.cached_output = None\n self.cached_hash_id = None\n try:\n self.lineno = str(util.build_file().lineno)\n except Exception as e:\n logging.warning(e)\n self.lineno = -1\n self.name = None\n self.file_deps = file_deps\n transitive_file_deps = set(file_deps)\n for dep in deps:\n transitive_file_deps.update(dep.transitive_file_deps)\n self.transitive_file_deps = transitive_file_deps\n\n\n @abstractmethod\n def execute(self) -> object:\n pass\n\n\n @abstractmethod\n def params(self) -> dict:\n pass\n\n\n def init_with_deps(self, args):\n for source in self.sources:\n source.init(args)\n for file_dep in self.file_deps:\n file_dep.init(args)\n for dep in self.deps:\n dep.init_with_deps(args)\n\n\n\n def hash_id(self) -> str:\n m = hashlib.sha256()\n m.update(util.lib_hash_id().encode('utf-8'))\n m.update(self.__class__.__name__.encode('utf-8'))\n m.update(json.dumps(self.params()).encode('utf-8'))\n for source in self.sources:\n m.update(source.hash_id().encode('utf-8'))\n for file_dep in self.file_deps:\n m.update(file_dep.hash_id().encode('utf-8'))\n for dep in self.deps:\n m.update(dep.hash_id().encode('utf-8'))\n return m.hexdigest()\n\n\n def _name(self):\n return self.name if self.name is not None else self.__class__.__name__\n\n\n def set_name(self, name: str):\n self.name = name\n\n\n def _output_dir(self, hash_id) -> Path:\n return TargetConfig.target_base_dir / 'output' / self._name() / hash_id\n\n\n def output_dir(self) -> Path:\n return self._output_dir(self.hash_id())\n\n\n def output_path(self) -> Path:\n return self.output_dir() / OUTPUT_FILE_NAME\n\n\n def _get_metadata_from_dep(self, target, files, targets):\n def _rel_path(input_file):\n return str(input_file.dest_file_path.relative_to(TargetConfig.target_base_dir))\n\n for source in target.sources:\n files[_rel_path(source)] = source.hash_id()\n for file_dep in target.file_deps:\n files[_rel_path(file_dep)] = file_dep.hash_id()\n for dep in target.deps:\n dep_hash_id = dep.hash_id()\n if dep_hash_id not in targets:\n targets[str(dep._name())] = dep_hash_id\n self._get_metadata_from_dep(dep, files, targets)\n\n\n def _save_metadata(self, hash_id):\n files = {}\n targets = {}\n self._get_metadata_from_dep(self, files, targets)\n\n with open(self._output_dir(hash_id) / 'metadata.json', 'w') as f:\n json.dump({'files': files, 'targets': targets}, f)\n\n\n def output(self, force=False):\n target_name = self._name()\n logging.debug(f'Executing {target_name} defined at build.py:{self.lineno}.')\n hash_id = self.hash_id()\n if hash_id == self.cached_hash_id and self.cached_output is not None:\n logging.debug(f' Re-using cached version {hash_id}.')\n return self.cached_output\n else:\n root_dir = self._output_dir(hash_id)\n os.makedirs(root_dir, exist_ok=True)\n file_path = root_dir / OUTPUT_FILE_NAME\n if not force and file_path.is_file():\n logging.debug(f' Loading cached version {hash_id}.')\n with open(file_path, 'rb') as f:\n output = pickle.load(f)\n else:\n logging.debug(f' Creating version {hash_id}.')\n lib_dir, mod_names = self._setup_modules()\n with util.IsolatedSysPath(mod_names):\n sys.path.append(str(lib_dir))\n output = self.execute()\n self._save_metadata(hash_id)\n with open(file_path, 'wb') as f:\n pickle.dump(output, f)\n self.cached_output = output\n self.cached_hash_id = hash_id\n return output\n\n\n def _setup_modules(self):\n lib_dir = self.output_dir() / 'lib'\n shutil.rmtree(lib_dir, ignore_errors=True)\n lib_dir.mkdir(parents=True, exist_ok=True)\n mod_names = []\n for f in self.transitive_file_deps:\n os.symlink(f.file_name, lib_dir / f.file_name.name)\n mod_names.append(f.mod_name())\n return lib_dir, mod_names\n \n","sub_path":"prodmodel/model/target/target.py","file_name":"target.py","file_ext":"py","file_size_in_byte":4483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"485379580","text":"#!/usr/bin/env python3\n\"\"\"importer.parser \"\"\"\n\n\nfrom lib.helpers import getlogger\nfrom pathlib import Path\nimport csv\nimport time\n\nimport pandas as pd\n\ndebug = True\n\nlogger = getlogger(__name__)\n\n\n# noinspection PyTypeChecker\ndef peek_into_file(fname: Path) -> csv.Dialect:\n \"\"\"\n Peek into a file in order to determine the dialect for pandas.read_csv() / csv functions.\n\n :param fname: a Path object for the filename\n :return: a csv.Dialect\n \"\"\"\n\n with fname.open(mode='r') as f:\n sniffer = csv.Sniffer()\n logger.debug(\"has apikeyheader: %s\", sniffer.has_header(f.readline()))\n f.seek(0)\n dialect = sniffer.sniff(f.readline(50))\n logger.debug(\"delim: '%s'\", dialect.delimiter)\n logger.debug(\"quotechar: '%s'\", dialect.quotechar)\n logger.debug(\"doublequote: %s\", dialect.doublequote)\n logger.debug(\"escapechar: '%s'\", dialect.escapechar)\n logger.debug(\"lineterminator: %r\", dialect.lineterminator)\n logger.debug(\"quoting: %s\", dialect.quoting)\n logger.debug(\"skipinitialspace: %s\", dialect.skipinitialspace)\n return dialect\n\n\nclass BaseParser:\n \"\"\"The abstract Parser class.\"\"\"\n def __init__(self):\n pass\n\n def parse_file(self, fname: Path, leak_id: int = None, csv_dialect=None) -> pd.DataFrame:\n \"\"\"Parse file (non-recursive) and returns a DataFrame with the contents.\n Overwrite this method in YOUR Parser subclass.\n\n # Parameters\n * fname: a Path object with the filename of the CSV file which should be parsed.\n * leak_id: the leak_id in the DB which is associated with that CSV dump file.\n # Returns\n a DataFrame\n number of errors while parsing\n \"\"\"\n logger.info(\"Parsing file %s...\" % fname)\n try:\n if csv_dialect:\n dialect = csv_dialect\n else:\n dialect = peek_into_file(fname) # try to guess\n df = pd.read_csv(fname, dialect=dialect, error_bad_lines=False, warn_bad_lines=True) # , usecols=range(2))\n logger.debug(df.head())\n logger.debug(df.info())\n logger.debug(\"Parsing file 2...\")\n df.insert(0, 'leak_id', leak_id)\n logger.debug(df.head())\n logger.debug(\"parsed %s\", fname)\n return df\n\n except Exception as ex:\n logger.error(\"could not pandas.read_csv(%s). Reason: %s. Skipping file.\" % (fname, str(ex)))\n raise ex # pass it on\n\n def normalize_data(self, df: pd.DataFrame, leak_id: int = None) -> pd.DataFrame:\n \"\"\"\n Normalize the given data / data frame\n\n :param df: a pandas df with the leak_data\n :param leak_id: foreign key to the leak table\n :return: a pandas df\n \"\"\"\n # replace NaN with None\n return df.where(pd.notnull(df), None)\n\n\nif __name__ == \"__main__\":\n\n\n p = BaseParser()\n t0 = time.time()\n # p.parse_recursively('test_leaks', '*.txt')\n t1 = time.time()\n logger.info(\"processed everything in %f [sec]\", (t1 - t0))\n","sub_path":"modules/collectors/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"468209535","text":"#!/usr/bin/env python\n\nfrom git_machete import __version__\nfrom os import path\nfrom setuptools import setup\n\nthis_directory = path.abspath(path.dirname(__file__))\nwith open(path.join(this_directory, 'README.md')) as f:\n long_description = f.read()\n\nsetup(\n name='git-machete',\n version=__version__,\n description='Probably the sharpest git repository organizer & rebase/merge workflow automation tool you\\'ve ever seen',\n long_description=long_description,\n long_description_content_type='text/markdown',\n author='Pawel Lipski',\n author_email='pawel.p.lipski@gmail.com',\n url='https://github.com/VirtusLab/git-machete',\n license='MIT',\n keywords='git',\n packages=['git_machete'],\n scripts=['git-machete'],\n python_requires='>=3.6, <4',\n classifiers=[\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Information Technology',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent'\n ],\n options={'bdist_wheel': {'universal': '1'}},\n include_package_data=True\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"595322512","text":"import random\nimport Jogos\nimport os\nimport time\n\n\ndef cls():\n os.system(\"cls\") or None\n\n\ndef sleep(x):\n time.sleep(x)\n\n\ndef bem_vindo():\n cls()\n print(\"*********************************\")\n print(\"Bem vindo ao jogo de adivinhação!\")\n print(\"*********************************\")\n\n\ndef seletor_de_dificuldade():\n while True:\n dificuldade = int(input(\"\\nDefina o nível de dificuldade desejada\\n(1)-Fácil (2)-Médio (3)-Difícil\\n\"))\n if(dificuldade == 1):\n dificuldade = 10\n break\n elif(dificuldade == 2):\n dificuldade = 5\n break\n elif(dificuldade == 3):\n dificuldade = 3\n break\n else:\n cls()\n print(\"Opção invalida!\\n\")\n sleep(1)\n cls()\n return dificuldade\n\n\ndef jogo(dificuldade, numero_secreto, pontos):\n for rodada in range(0, dificuldade):\n print(f\"\\n\\nRodada {rodada + 1} de {dificuldade}\")\n chute = int(input(\"Digite o seu chute: \"))\n\n if(chute < numero_secreto):\n cls()\n print(\"\\nSeu chute foi menor que o número secreto!\")\n sleep(1)\n pontos = abs(pontos - chute)\n continue\n elif (chute > numero_secreto):\n cls()\n print(\"\\nSeu chute foi maior que o número secreto!\")\n sleep(1)\n pontos = abs(pontos - chute)\n continue\n else:\n cls()\n print(\"\\nVocê acertou!\")\n sleep(1)\n break\n return pontos\n\n\ndef replay():\n while True:\n novamente = input(\"Deseja jogar novamente?\\n\").strip()\n cls()\n if novamente == \"sim\":\n novamente = True\n break\n elif novamente == \"não\":\n novamente = False\n break\n else:\n cls()\n print(\"Opção inválida!\")\n sleep(1)\n return novamente\n\n\ndef voltar_ao_seletor():\n while True:\n cls()\n voltar = input(\"Deseja voltar para o seletor de jogos?\\n\").strip()\n if voltar == \"sim\":\n cls()\n Jogos.jogos_por_chamada()\n break\n elif voltar == \"não\":\n voltar = False\n break\n else:\n cls()\n print(\"Opção inválida!\")\n sleep(1)\n\n\ndef adivinhação_por_chamada():\n cls()\n adivinhação()\n voltar_ao_seletor()\n\n\ndef adivinhação():\n bem_vindo()\n numero_secreto = random.randrange(1, 101)\n pontos = 1000\n novamente = True\n\n while novamente:\n dificuldade = seletor_de_dificuldade()\n pontos = jogo(dificuldade, numero_secreto, pontos)\n\n print(f\"\\n\\nFim de jogo!\\nO número secreto era: {numero_secreto}\\\n \\nSua pontuação foi de: {pontos} pontos\")\n sleep(1)\n novamente = replay()\n\n\nif(__name__ == \"__main__\"):\n adivinhação()\n","sub_path":"Adivinhação.py","file_name":"Adivinhação.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"183119715","text":"# Copyright 2020 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"export AIR file.\"\"\"\nimport argparse\nimport numpy as np\n\nfrom mindspore import Tensor, context, load_checkpoint, load_param_into_net, export\n\nfrom src.nets import net_factory\n\ncontext.set_context(mode=context.GRAPH_MODE, save_graphs=False)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='checkpoint export')\n parser.add_argument('--checkpoint', type=str.lower, default='', help='checkpoint of deeplabv3 (Default: None)')\n parser.add_argument('--model', type=str.lower, default='deeplab_v3_s8', choices=['deeplab_v3_s16', 'deeplab_v3_s8'],\n help='Select model structure (Default: deeplab_v3_s8)')\n parser.add_argument('--num_classes', type=int, default=21, help='the number of classes (Default: 21)')\n args = parser.parse_args()\n\n if args.model == 'deeplab_v3_s16':\n network = net_factory.nets_map['deeplab_v3_s16']('eval', args.num_classes, 16, True)\n else:\n network = net_factory.nets_map['deeplab_v3_s8']('eval', args.num_classes, 8, True)\n param_dict = load_checkpoint(args.checkpoint)\n\n # load the parameter into net\n load_param_into_net(network, param_dict)\n input_data = np.random.uniform(0.0, 1.0, size=[32, 3, 513, 513]).astype(np.float32)\n export(network, Tensor(input_data), file_name=args.model+'-300_11.air', file_format='AIR')\n","sub_path":"model_zoo/official/cv/deeplabv3/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"451321672","text":"import datetime as dt\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport mplfinance as mpf\nimport matplotlib.dates as mdates\nimport pandas as pd\nimport pandas_datareader.data as web\n\n# this is the code I used to manipulate the data into being useful for matplotlib finance.\n# There is most likely a more efficient way of doing this. I will be back once i have found it.\n\ndates = []\nopens = []\nhighs = []\nlows = []\ncloses = []\nvolumes = []\n\ndf = pd.read_csv('Bitcoin_datas.csv')\ndate = df['Date']\nopened = df['Open']\nhigh = df['High']\nlow = df['Low']\nclose = df['Close']\nvolume = df['Volume']\n\ndef reverse_date():\n for i in date:\n dates.append(i)\n dates.reverse()\n df['Date'] = dates\n\n for i in opened:\n opens.append(i)\n opens.reverse()\n df['Open'] = opens\n\n for i in high:\n highs.append(i)\n highs.reverse()\n df['High'] = highs\n\n for i in low:\n lows.append(i)\n lows.reverse()\n df['Low'] = lows\n\n for i in close:\n closes.append(i)\n closes.reverse()\n df['Close'] = closes\n\n for i in volume:\n volumes.append(i)\n volumes.reverse()\n df['Volume'] = volumes\n\n df.to_csv('____.csv')\n\nreverse_date()\n","sub_path":"manipulating_data.py","file_name":"manipulating_data.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"245783361","text":"import pika, os, logging, time\r\n\r\n# Parse CLODUAMQP_URL (fallback to localhost)\r\nurl = os.environ.get('CLOUDAMQP_URL', 'amqps://yvbeowen:VURyPmCU2CQh2LwQMq9gPlZ7eQcdq6e2@puffin.rmq2.cloudamqp.com/yvbeowen')\r\nparams = pika.URLParameters(url)\r\nconnection = pika.BlockingConnection(params) # Connect to CloudAMQP\r\nchannel = connection.channel() # start a channel\r\nchannel.exchange_declare(exchange='logs', exchange_type='fanout')\r\n\r\n# send a message\r\nchannel.basic_publish(exchange='logs', routing_key='', body='Integrated feature testing')\r\nprint(\"[x] Message sent to consumer\")\r\nconnection.close()\r\n\r\n\r\n\r\n\r\n","sub_path":"Web/Sending_message_through_RabbitMQ _extended.py","file_name":"Sending_message_through_RabbitMQ _extended.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"563782777","text":"b = int(input())\nn = int(input())\nv = []\nif not 2<=b<=9 or not 0<=n<=10000000:\n print('-1')\nelse:\n while n!=0:\n out,n = n%b,n//b\n v.append(out)\n v.reverse()\n out = ''.join(str(i) for i in v)\n if len(v) == 0:\n print(0)\n elif int(out) > 100000:\n print('-1')\n else:\n print(''.join(str(i) for i in v))\n\n\n","sub_path":"loop/bit.py","file_name":"bit.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"268011960","text":"from sklearn.model_selection import train_test_split, KFold, cross_val_score\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.utils.testing import all_estimators\nfrom sklearn.datasets import load_wine\nimport warnings\n\nwarnings.filterwarnings('ignore')\n\ndataset = load_wine()\nx = dataset.data\ny = dataset.target\nx_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.2, random_state=66)\n\nkfold = KFold(n_splits=5, shuffle=True)\nallAlgorithm = all_estimators(type_filter = 'classifier')\n\nfor (name, algorithm) in allAlgorithm:\n try:\n model = algorithm()\n scores = cross_val_score(model, x_train, y_train, cv=kfold)\n # model.fit(x_train, y_train)\n # y_pred = model.predict(x_test)\n print(name,'의 정답률 : \\n',scores)\n except:\n print(name, '없는 것')\n\n# import sklearn\n# print(sklearn.__version__) # 0.23.2","sub_path":"ml/m11_kfold_estimators3_wine.py","file_name":"m11_kfold_estimators3_wine.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"324024081","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom yaglm.linalg_utils import euclid_norm\n\n\ndef plot_successive_diffs(values, norm='MAD', log=True,\n marker='.', color='black', **kws):\n \"\"\"\n Gets the successive differences between values.\n\n Parameters\n ----------\n values: list of array-like\n The list of values.\n\n norm: str\n Which norm to use of the differences. See get_successive_diffs()\n\n log: bool\n Whether or not to log the differences.\n\n **kws:\n Keyword arguments to plt.plot()\n \"\"\"\n diffs = get_successive_diffs(values=values, norm=norm)\n if log:\n diffs = np.log10(diffs)\n plt.plot(diffs, marker=marker, color=color, **kws)\n\n ylab = '{} successive difference'.format(norm)\n if log:\n ylab = 'log10({})'.format(ylab)\n plt.ylabel(ylab)\n\n\ndef get_successive_diffs(values, norm='MAD'):\n \"\"\"\n Gets the successive differences between values.\n\n Parameters\n ----------\n values: list of array-like\n The list of values.\n\n norm: str\n Which norm to use of the differences. Must be one of ['L1', 'L2', 'RMSE', 'MAD', 'MAD'].\n\n Output\n ------\n diffs: list of floats\n The differences.\n \"\"\"\n\n norm = norm.lower()\n\n if norm == 'l2':\n norm = euclid_norm\n\n if norm == 'rmse':\n norm = lambda x: (np.array(x).reshape(-1) **2).mean()\n\n elif norm == 'l1':\n norm = lambda x: abs(np.array(x).reshape(-1)).sum()\n\n elif norm == 'mad':\n norm = lambda x: abs(np.array(x).reshape(-1)).mean()\n\n elif norm == 'max':\n norm = lambda x: abs(np.array(x)).max().mean()\n\n else:\n raise ValueError(\"Bad input for norm {}\".format(norm))\n\n n_values = len(values)\n return np.array([norm(values[i + 1] - values[i])\n for i in range(n_values - 1)])\n","sub_path":"yaglm/opt/viz/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"634280143","text":"n = int(input())\n\n\nl, r = 0, n\n\nprint(0, flush=True)\nre = input()\nif re==\"Vacant\": exit()\n\nfor i in range(19):\n mid = (l+r)//2\n print(mid, flush=True)\n tmp = input()\n if tmp==\"Vacant\": exit()\n\n p = abs(l-mid)%2\n\n if (re!=tmp and p) or (re==tmp and p-1):\n l = mid\n re = tmp\n else:\n if abs(l-mid) in [1, n-1]:\n l = mid\n re = tmp\n else: r = mid\n","sub_path":"Python_codes/p03439/s982873538.py","file_name":"s982873538.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"426358906","text":"from sunpy.visualization.imageanimator import ImageAnimatorWCS\nfrom collections import namedtuple\nfrom ndcube.visualization import animation as ani\nfrom ndcube import cube_utils as cu\nimport sunpy.map\nimport matplotlib.pyplot as plt\nimport sunpy.visualization.wcsaxes_compat as wcsaxes_compat\nimport astropy.units as u\nimport ndcube.cube_utils\nimport ndcube.wcs_util\nimport astropy.nddata\nimport numpy as np\nimport copy\nimport warnings\n\nDimensionPair = namedtuple('DimensionPair', 'shape axis_types')\nSequenceDimensionPair = namedtuple('SequenceDimensionPair', 'shape axis_types')\n\n__all__ = ['NDCube', 'NDCubeSequence']\n\n\nclass NDCube(astropy.nddata.NDData):\n \"\"\"\n Class representing N dimensional cubes.\n Extra arguments are passed on to NDData's init.\n\n Attributes\n ----------\n data: `numpy.ndarray`\n The array holding the actual data in this object.\n\n wcs: `ndcube.wcs.wcs.WCS`\n The WCS object containing the axes' information\n\n uncertainty : any type, optional\n Uncertainty in the dataset. Should have an attribute uncertainty_type\n that defines what kind of uncertainty is stored, for example \"std\"\n for standard deviation or \"var\" for variance. A metaclass defining\n such an interface is NDUncertainty - but isn’t mandatory. If the uncertainty\n has no such attribute the uncertainty is stored as UnknownUncertainty.\n Defaults to None.\n\n mask : any type, optional\n Mask for the dataset. Masks should follow the numpy convention\n that valid data points are marked by False and invalid ones with True.\n Defaults to None.\n\n meta : dict-like object, optional\n Additional meta information about the dataset. If no meta is provided\n an empty collections.OrderedDict is created. Default is None.\n\n unit : Unit-like or str, optional\n Unit for the dataset. Strings that can be converted to a Unit are allowed.\n Default is None.\n\n coords : `list` of `tuple`s, each with three entries (`str`, `int`, `astropy.units.quantity`)\n Gives the name, axis of data, and values of coordinates of a data axis not\n included in the WCS object.\n\n copy : bool, optional\n Indicates whether to save the arguments as copy. True copies every attribute\n before saving it while False tries to save every parameter as reference.\n Note however that it is not always possible to save the input as reference. Default is False.\n \"\"\"\n\n def __init__(self, data, uncertainty=None, mask=None, wcs=None, meta=None,\n unit=None, coords=None, copy=False, missing_axis=None, **kwargs):\n if missing_axis is None:\n self.missing_axis = [False]*wcs.naxis\n else:\n self.missing_axis = missing_axis\n if data.ndim is not wcs.naxis:\n count = 0\n for bool_ in self.missing_axis:\n if not bool_:\n count += 1\n if count is not data.ndim:\n raise ValueError(\n \"The number of data dimensions and number of wcs non-missing axes do not match.\")\n\n self.coords = {}\n coord_error = \"Coord must have three properties supplied, name (str), axis (int), values (Quantity): {0}\"\n\n if coords:\n for coord in coords:\n if len(coord) != 3:\n raise ValueError(coord_error.format(coord))\n elif not isinstance(coord[2], (str, int, astropy.units.quantity.Quantity)):\n raise ValueError(coord_error.format(coord))\n else:\n self.coords[coord[0]] = {\"axis\": coord[1], \"value\": coord[2]}\n\n super(NDCube, self).__init__(data, uncertainty=uncertainty, mask=mask,\n wcs=wcs, meta=meta, unit=unit, copy=copy, **kwargs)\n\n def pixel_to_world(self, quantity_axis_list, origin=0):\n \"\"\"\n Convert a pixel coordinate to a data (world) coordinate by using\n `~astropy.wcs.WCS.all_pix2world`.\n\n Parameters\n ----------\n quantity_axis_list : `list`\n A list of `~astropy.units.Quantity` with unit as pixel `pix`.\n\n origin : `int`.\n Origin of the top-left corner. i.e. count from 0 or 1.\n Normally, origin should be 0 when passing numpy indices, or 1 if\n passing values from FITS header or map attributes.\n See `~astropy.wcs.WCS.wcs_pix2world` for more information.\n Default is 0.\n\n Returns\n -------\n\n coord : `list`\n A list of arrays containing the output coordinates\n reverse of the wcs axis order.\n \"\"\"\n list_arg = []\n indexed_not_as_one = []\n result = []\n quantity_index = 0\n for i, _ in enumerate(self.missing_axis):\n # the cases where the wcs dimension was made 1 and the missing_axis is True\n if self.missing_axis[self.wcs.naxis-1-i]:\n list_arg.append(self.wcs.wcs.crpix[self.wcs.naxis-1-i]-1+origin)\n else:\n # else it is not the case where the dimension of wcs is 1.\n list_arg.append(quantity_axis_list[quantity_index])\n quantity_index += 1\n # appending all the indexes to be returned in the answer\n indexed_not_as_one.append(self.wcs.naxis-1-i)\n list_arguemnts = list_arg[::-1]\n pixel_to_world = self.wcs.all_pix2world(*list_arguemnts, origin)\n # collecting all the needed answer in this list.\n for index in indexed_not_as_one[::-1]:\n result.append(u.Quantity(pixel_to_world[index], unit=self.wcs.wcs.cunit[index]))\n return result[::-1]\n\n def world_to_pixel(self, quantity_axis_list, origin=0):\n \"\"\"\n Convert a world coordinate to a data (pixel) coordinate by using\n `~astropy.wcs.WCS.all_world2pix`.\n\n Parameters\n ----------\n quantity_axis_list : `list`\n A list of `~astropy.units.Quantity`.\n\n origin : `int`\n Origin of the top-left corner. i.e. count from 0 or 1.\n Normally, origin should be 0 when passing numpy indices, or 1 if\n passing values from FITS header or map attributes.\n See `~astropy.wcs.WCS.wcs_world2pix` for more information.\n Default is 0.\n\n Returns\n -------\n\n coord : `list`\n A list of arrays containing the output coordinates\n reverse of the wcs axis order.\n \"\"\"\n list_arg = []\n indexed_not_as_one = []\n result = []\n quantity_index = 0\n for i, _ in enumerate(self.missing_axis):\n # the cases where the wcs dimension was made 1 and the missing_axis is True\n if self.missing_axis[self.wcs.naxis-1-i]:\n list_arg.append(self.wcs.wcs.crval[self.wcs.naxis-1-i]+1-origin)\n else:\n # else it is not the case where the dimension of wcs is 1.\n list_arg.append(quantity_axis_list[quantity_index])\n quantity_index += 1\n # appending all the indexes to be returned in the answer\n indexed_not_as_one.append(self.wcs.naxis-1-i)\n list_arguemnts = list_arg[::-1]\n world_to_pixel = self.wcs.all_world2pix(*list_arguemnts, origin)\n # collecting all the needed answer in this list.\n for index in indexed_not_as_one[::-1]:\n result.append(u.Quantity(world_to_pixel[index], unit=u.pix))\n return result[::-1]\n\n def to_sunpy(self):\n wcs_axes = list(self.wcs.wcs.ctype)\n missing_axis = self.missing_axis\n index_not_one = []\n if 'TIME' in wcs_axes and len(self.dimensions.shape) is 1:\n result = self.pixel_to_world([u.Quantity(self.data, unit=u.pix)])\n elif 'HPLT-TAN' in wcs_axes and 'HPLN-TAN' in wcs_axes and len(self.dimensions.shape) is 2:\n if not missing_axis[wcs_axes.index(\"HPLT-TAN\")] and not missing_axis[wcs_axes.index(\"HPLN-TAN\")]:\n result = sunpy.map.Map(self.data, self.meta)\n else:\n warnings.warn(\"Object type not Implemented\")\n result = None\n return result\n\n @property\n def dimensions(self):\n \"\"\"\n Returns a named tuple with two attributes: 'shape' gives the shape\n of the data dimensions; 'axis_types' gives the WCS axis type of each dimension,\n e.g. WAVE or HPLT-TAN for wavelength of helioprojected latitude.\n \"\"\"\n ctype = list(self.wcs.wcs.ctype)\n axes_ctype = []\n for i, axis in enumerate(self.missing_axis):\n if not axis:\n axes_ctype.append(ctype[i])\n shape = u.Quantity(self.data.shape, unit=u.pix)\n return DimensionPair(shape=shape, axis_types=axes_ctype[::-1])\n\n def plot(self, axes=None, image_axes=[-1, -2], unit_x_axis=None, unit_y_axis=None,\n axis_ranges=None, unit=None, origin=0, **kwargs):\n \"\"\"\n Plots an interactive visualization of this cube with a slider\n controlling the wavelength axis for data having dimensions greater than 2.\n Plots an x-y graph onto the current axes for 2D or 1D data. Keyword arguments are passed\n on to matplotlib.\n Parameters other than data and wcs are passed to ImageAnimatorWCS, which in turn\n passes them to imshow for data greater than 2D.\n\n Parameters\n ----------\n image_axes: `list`\n The two axes that make the image.\n Like [-1,-2] this implies cube instance -1 dimension\n will be x-axis and -2 dimension will be y-axis.\n\n axes: `astropy.visualization.wcsaxes.core.WCSAxes` or None:\n The axes to plot onto. If None the current axes will be used.\n\n unit_x_axis: `astropy.units.Unit`\n The unit of x axis for 2D plots.\n\n unit_y_axis: `astropy.units.Unit`\n The unit of y axis for 2D plots.\n\n unit: `astropy.unit.Unit`\n The data is changed to the unit given or the cube.unit if not given, for 1D plots.\n\n axis_ranges: list of physical coordinates for array or None\n If None array indices will be used for all axes.\n If a list it should contain one element for each axis of the numpy array.\n For the image axes a [min, max] pair should be specified which will be\n passed to :func:`matplotlib.pyplot.imshow` as extent.\n For the slider axes a [min, max] pair can be specified or an array the\n same length as the axis which will provide all values for that slider.\n If None is specified for an axis then the array indices will be used\n for that axis.\n \"\"\"\n axis_data = ['x' for i in range(2)]\n axis_data[image_axes[1]] = 'y'\n if self.data.ndim >= 3:\n plot = _plot_3D_cube(self, image_axes=axis_data, unit_x_axis=unit_x_axis, unit_y_axis=unit_y_axis,\n axis_ranges=axis_ranges, *kwargs)\n elif self.data.ndim is 2:\n plot = _plot_2D_cube(self, axes=axes, image_axes=axis_data[::-1], **kwargs)\n elif self.data.ndim is 1:\n plot = _plot_1D_cube(self, unit=unit, origin=origin)\n return plot\n\n def __getitem__(self, item):\n if item is None or (isinstance(item, tuple) and None in item):\n raise IndexError(\"None indices not supported\")\n data = self.data[item]\n # here missing axis is reversed as the item comes already in the reverse order\n # of the input\n wcs, missing_axis = ndcube.wcs_util._wcs_slicer(\n self.wcs, copy.deepcopy(self.missing_axis[::-1]), item)\n if self.mask is not None:\n mask = self.mask[item]\n else:\n mask = None\n if self.uncertainty is not None:\n if isinstance(self.uncertainty.array, np.ndarray):\n if self.uncertainty.array.shape == self.data.shape:\n uncertainty = self.uncertainty[item]\n else:\n uncertainty = self.uncertainty\n else:\n uncertainty = self.uncertainty\n else:\n uncertainty = None\n coords_keys = list(self.coords.keys())\n result = NDCube(data, wcs=wcs, mask=mask, uncertainty=uncertainty, meta=self.meta,\n unit=self.unit, copy=False, missing_axis=missing_axis,\n coords=[(ck, self.coords[ck][\"axis\"],\n self.coords[ck][\"value\"][item[self.coords[ck][\"axis\"]]])\n for ck in coords_keys])\n return result\n\n def __repr__(self):\n return (\n \"\"\"Sunpy NDCube\n---------------------\n{wcs}\n---------------------\nLength of NDCube: {lengthNDCube}\nAxis Types of NDCube: {axis_type}\n\"\"\".format(wcs=self.wcs.__repr__(), lengthNDCube=self.dimensions[0], axis_type=self.dimensions[1]))\n\n\nclass NDCubeOrdered(NDCube):\n \"\"\"\n Class representing N dimensional cubes with oriented WCS.\n Extra arguments are passed on to NDData's init.\n The order is TIME, SPECTRAL, SOLAR-x, SOLAR-Y and any other dimension.\n For example, in an x, y, t cube the order would be (t,x,y) and in a\n lambda, t, y cube the order will be (t, lambda, y).\n Extra arguments are passed on to NDData's init.\n\n Attributes\n ----------\n data: `numpy.ndarray`\n The array holding the actual data in this object.\n\n wcs: `ndcube.wcs.wcs.WCS`\n The WCS object containing the axes' information. The axes'\n priorities are time, spectral, celestial. This means that if\n present, each of these axis will take precedence over the others.\n\n uncertainty : any type, optional\n Uncertainty in the dataset. Should have an attribute uncertainty_type\n that defines what kind of uncertainty is stored, for example \"std\"\n for standard deviation or \"var\" for variance. A metaclass defining\n such an interface is NDUncertainty - but isn’t mandatory. If the uncertainty\n has no such attribute the uncertainty is stored as UnknownUncertainty.\n Defaults to None.\n\n mask : any type, optional\n Mask for the dataset. Masks should follow the numpy convention\n that valid data points are marked by False and invalid ones with True.\n Defaults to None.\n\n meta : dict-like object, optional\n Additional meta information about the dataset. If no meta is provided\n an empty collections.OrderedDict is created. Default is None.\n\n unit : Unit-like or str, optional\n Unit for the dataset. Strings that can be converted to a Unit are allowed.\n Default is None.\n\n copy : bool, optional\n Indicates whether to save the arguments as copy. True copies every attribute\n before saving it while False tries to save every parameter as reference.\n Note however that it is not always possible to save the input as reference. Default is False.\n \"\"\"\n\n def __init__(self, data, uncertainty=None, mask=None, wcs=None, meta=None,\n unit=None, copy=False, missing_axis=None, **kwargs):\n axtypes = list(wcs.wcs.ctype)\n array_order = ndcube.cube_utils.select_order(axtypes)\n result_data = data.transpose(array_order)\n wcs_order = np.array(array_order)[::-1]\n result_wcs = ndcube.wcs_util.reindex_wcs(wcs, wcs_order)\n super(NDCubeOrdered, self).__init__(result_data, uncertainty=uncertainty, mask=mask,\n wcs=result_wcs, meta=meta, unit=unit, copy=copy,\n missing_axis=missing_axis, **kwargs)\n\n\ndef _plot_3D_cube(cube, image_axes=None, unit_x_axis=None, unit_y_axis=None,\n axis_ranges=None, **kwargs):\n \"\"\"\n Plots an interactive visualization of this cube using sliders to move through axes\n plot using in the image.\n Parameters other than data and wcs are passed to ImageAnimatorWCS, which in turn\n passes them to imshow.\n\n Parameters\n ----------\n image_axes: `list`\n The two axes that make the image.\n Like [-1,-2] this implies cube instance -1 dimension\n will be x-axis and -2 dimension will be y-axis.\n\n unit_x_axis: `astropy.units.Unit`\n The unit of x axis.\n\n unit_y_axis: `astropy.units.Unit`\n The unit of y axis.\n\n axis_ranges: `list` of physical coordinates for array or None\n If None array indices will be used for all axes.\n If a list it should contain one element for each axis of the numpy array.\n For the image axes a [min, max] pair should be specified which will be\n passed to :func:`matplotlib.pyplot.imshow` as extent.\n For the slider axes a [min, max] pair can be specified or an array the\n same length as the axis which will provide all values for that slider.\n If None is specified for an axis then the array indices will be used\n for that axis.\n \"\"\"\n i = ImageAnimatorWCS(cube.data, wcs=cube.wcs, unit_x_axis=unit_x_axis, unit_y_axis=unit_y_axis,\n axis_ranges=axis_ranges, **kwargs)\n return i\n\n\ndef _plot_2D_cube(cube, axes=None, image_axes=['x', 'y'], **kwargs):\n \"\"\"\n Plots a 2D image onto the current\n axes. Keyword arguments are passed on to matplotlib.\n\n Parameters\n ----------\n axes: `astropy.visualization.wcsaxes.core.WCSAxes` or `None`:\n The axes to plot onto. If None the current axes will be used.\n\n image_axes: `list`.\n The first axis in WCS object will become the first axis of image_axes and\n second axis in WCS object will become the seconf axis of image_axes.\n \"\"\"\n if axes is None:\n if cube.wcs.naxis is not 2:\n missing_axis = cube.missing_axis\n slice_list = []\n axis_index = []\n index = 0\n for i, bool_ in enumerate(missing_axis):\n if not bool_:\n slice_list.append(image_axes[index])\n index += 1\n else:\n slice_list.append(1)\n if index is not 2:\n raise ValueError(\"Dimensions of WCS and data don't match\")\n axes = wcsaxes_compat.gca_wcs(cube.wcs, slices=slice_list)\n plot = axes.imshow(cube.data, **kwargs)\n return plot\n\n\ndef _plot_1D_cube(cube, unit=None, origin=0):\n \"\"\"\n Plots a graph.\n Keyword arguments are passed on to matplotlib.\n\n Parameters\n ----------\n unit: `astropy.unit.Unit`\n The data is changed to the unit given or the cube.unit if not given.\n \"\"\"\n index_not_one = []\n for i, _bool in enumerate(cube.missing_axis):\n if not _bool:\n index_not_one.append(i)\n if unit is None:\n unit = cube.wcs.wcs.cunit[index_not_one[0]]\n plot = plt.plot(cube.pixel_to_world(\n [u.Quantity(np.arange(cube.data.shape[0]), unit=u.pix)], origin=origin)[0].to(unit), cube.data)\n return plot\n\n\nclass NDCubeSequence(object):\n \"\"\"\n Class representing list of cubes.\n\n Attributes\n ----------\n data_list : `list`\n List of cubes.\n\n meta : `dict` or None\n The header of the NDCubeSequence.\n\n common_axis: `int` or None\n The data axis which is common between the NDCubeSequence and the Cubes within.\n For example, if the Cubes are sequenced in chronological order and time is\n one of the zeroth axis of each Cube, then common_axis should be se to 0.\n This enables the option for the NDCubeSequence to be indexed as though it is\n one single Cube.\n \"\"\"\n\n def __init__(self, data_list, meta=None, common_axis=None, **kwargs):\n self.data = data_list\n self.meta = meta\n self.common_axis = common_axis\n\n def __getitem__(self, item):\n if item is None or (isinstance(item, tuple) and None in item):\n raise IndexError(\"None indices not supported\")\n return cu.get_cube_from_sequence(self, item)\n\n def plot(self, *args, **kwargs):\n i = ani.ImageAnimatorNDCubeSequence(self, *args, **kwargs)\n return i\n\n def explode_along_axis(self, axis):\n \"\"\"\n Separates slices of NDCubes in sequence along a given cube axis into (N-1)DCubes.\n\n Parameters\n ----------\n\n axis : `int`\n The axis along which the data is to be changed.\n \"\"\"\n # if axis is None then set axis as common axis.\n if self.common_axis is not None:\n if self.common_axis != axis:\n raise ValueError(\"axis and common_axis should be equal.\")\n # is axis is -ve then calculate the axis from the length of the dimensions of one cube\n if axis < 0:\n axis = len(self.dimensions.shape[1::]) + axis\n # To store the resultant cube\n result_cubes = []\n # All slices are initially initialised as slice(None, None, None)\n result_cubes_slice = [slice(None, None, None)] * len(self[0].data.shape)\n # the range of the axis that needs to be sliced\n range_of_axis = self[0].data.shape[axis]\n for ndcube in self.data:\n for index in range(range_of_axis):\n # setting the slice value to the index so that the slices are done correctly.\n result_cubes_slice[axis] = index\n # appending the sliced cubes in the result_cube list\n result_cubes.append(ndcube.__getitem__(tuple(result_cubes_slice)))\n # creating a new sequence with the result_cubes keeping the meta and common axis as axis\n return self._new_instance(result_cubes, meta=self.meta, common_axis=axis)\n\n def __repr__(self):\n return (\n \"\"\"Sunpy NDCubeSequence\n---------------------\nLength of NDCubeSequence: {length}\nLength of 1st NDCube: {lengthNDCube}\nAxis Types of 1st NDCube: {axis_type}\n\"\"\".format(length=self.dimensions.shape[0], lengthNDCube=self.dimensions.shape[1::],\n axis_type=self.dimensions.axis_types[1::]))\n\n @property\n def dimensions(self):\n return SequenceDimensionPair(shape=tuple([len(self.data)]+list(self.data[0].dimensions.shape)),\n axis_types=tuple([\"Sequence Axis\"]+self.data[0].dimensions.axis_types))\n\n @property\n def common_axis_coords(self):\n if self.common_axis:\n common_coords = {}\n common_coords_list = []\n coord_names = list(self[0].coords.keys())\n for coord_name in coord_names:\n if self[0].coords[coord_name][\"axis\"] == self.common_axis:\n coord_unit = self[0].coords[coord_name][\"value\"].unit\n qs = tuple([np.asarray(c.coords[\"time\"][\"value\"].to(coord_unit).value) for c in self])\n common_coords[coord_name] = u.Quantity(np.concatenate(qs), unit=coord_unit)\n else:\n common_coords = None\n return common_coords\n\n @classmethod\n def _new_instance(cls, data_list, meta=None, common_axis=None):\n \"\"\"\n Instantiate a new instance of this class using given data.\n \"\"\"\n return cls(data_list, meta=meta, common_axis=common_axis)\n\n @property\n def index_as_cube(self):\n \"\"\"\n Method to slice the NDcubesequence instance as a single cube\n\n Example\n -------\n >>> # Say we have three Cubes each cube has common_axis=0 is time and shape=(3,3,3)\n >>> data_list = [cubeA, cubeB, cubeC]\n >>> cs = NDCubeSequence(data_list, meta=None, common_axis=0)\n >>> # return zeroth time slice of cubeB in via normal NDCubeSequence indexing.\n >>> cs[1,:,0,:]\n >>> # Return same slice using this function\n >>> cs.index_sequence_as_cube[3:6, 0, :]\n \"\"\"\n if self.common_axis is None:\n raise ValueError(\"common_axis cannot be None\")\n return _IndexAsCubeSlicer(self)\n\n\nclass _IndexAsCubeSlicer(object):\n \"\"\"\n Helper class to make slicing in index_as_cube more pythonic.\n Helps to make operations like in numpy array.\n >>> data_list = numpy.array(range(10))\n >>> data_list[3:5]\n >>> [4, 5, 6]\n This makes slicing like this possible for index_as_cube.\n\n Attributes\n ----------\n seq : `ndcube.NDCubeSequence`\n Object of NDCubeSequence.\n \"\"\"\n\n def __init__(self, seq):\n self.seq = seq\n\n def __getitem__(self, item):\n return cu.index_sequence_as_cube(self.seq, item)\n","sub_path":"ndcube/ndcube.py","file_name":"ndcube.py","file_ext":"py","file_size_in_byte":24527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"619185015","text":"import codecs\nimport os\nimport re\n\nfrom setuptools import find_packages, setup\n\nNAME = \"project_name\"\nPACKAGES = find_packages(where=\"project_name\")\nMETA_PATH = os.path.join(\"project_name\", \"__init__.py\")\nINSTALL_REQUIRES = [\"numpy\", \"matplotlib\"]\nEXTRA_REQUIRE = {\"test\": [\"pytest>=3.6\"]}\nEXTRA_REQUIRE[\"dev\"] = EXTRA_REQUIRE[\"test\"] + [\n \"pre-commit\",\n \"flake8\",\n \"black<=21.9b0\",\n \"isort\",\n]\n\n# END PROJECT SPECIFIC\n\nCLASSIFIERS = [\n \"Development Status :: 5 - Production/Stable\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3\",\n]\n\nHERE = os.path.dirname(os.path.realpath(__file__))\n\n\ndef read(*parts):\n with codecs.open(os.path.join(HERE, *parts), \"rb\", \"utf-8\") as f:\n return f.read()\n\n\ndef find_meta(meta, meta_file=read(META_PATH)):\n meta_match = re.search(\n r\"^__{meta}__ = ['\\\"]([^'\\\"]*)['\\\"]\".format(meta=meta), meta_file, re.M\n )\n if meta_match:\n return meta_match.group(1)\n raise RuntimeError(\"Unable to find __{meta}__ string.\".format(meta=meta))\n\n\nsetup(\n name=NAME,\n use_scm_version={\n \"write_to\": os.path.join(NAME, \"{0}_version.py\".format(NAME)),\n \"write_to_template\": '__version__ = \"{version}\"\\n',\n },\n author=find_meta(\"author\"),\n author_email=find_meta(\"email\"),\n maintainer=find_meta(\"author\"),\n maintainer_email=find_meta(\"email\"),\n url=find_meta(\"uri\"),\n license=find_meta(\"license\"),\n description=find_meta(\"description\"),\n long_description=read(\"README.md\"),\n long_description_content_type=\"text/markdown\",\n packages=PACKAGES,\n keywords=[],\n install_requires=INSTALL_REQUIRES,\n extras_require=EXTRA_REQUIRE,\n classifiers=CLASSIFIERS,\n zip_safe=True,\n entry_points={\"console_scripts\": []},\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"570222479","text":"import io\nimport json\nimport keras\nimport keras.backend as K\nimport numpy as np\nimport pandas as pd\nimport urllib3\nfrom PIL import Image\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom collections import Counter\nfrom tensorflow.python.lib.io import file_io\n\nfrom networks.mobilenet import mobilenet_model\n\nimport os\n\nfrom utils import params\n\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\nhttp_client = urllib3.PoolManager(500)\n\nclass MultiLabelGenerator(ImageDataGenerator):\n def __init__(self, *args, **kwargs):\n super(MultiLabelGenerator, self).__init__(*args, **kwargs)\n\n def make_datagenerator(self, datafile, batch_size=32, dim=(224, 224), n_channels=3, n_classes=params.n_classes,\n seed=None, shuffle=True, test=False, data_path='./data/img/',\n save_images=False, train=False, label_occ_threshold=5000, GCP=True, thresholdsmaller=True):\n return DataGenerator(self, datafile, batch_size, dim, n_channels, n_classes,\n seed, shuffle, test, train, data_path, save_images, label_occ_threshold, GCP, thresholdsmaller)\n\n\nclass DataGenerator(keras.utils.Sequence):\n \"\"\" Generates data for Keras \"\"\"\n\n def __init__(self, image_data_generator, datafile, batch_size=32, dim=(224, 224), n_channels=3,\n n_classes=params.n_classes, seed=None, shuffle=True, test=False, train=False, data_path='./data/img/',\n save_images=True, label_occ_threshold=5000, GCP=True, thresholdsmaller=False):\n \"\"\" Initialization \"\"\"\n self.n = 0\n self.test = test\n self.seed = seed\n self.shuffle = shuffle\n self.image_data_generator = image_data_generator\n\n self.batch_size = batch_size\n self.dim = dim\n self.n_channels = n_channels\n self.n_classes = n_classes\n self.train = train\n self.thresholdsmaller = thresholdsmaller\n self.GCP = GCP\n\n # vars for saving and loading the image\n self.save_images = save_images\n self.path = data_path\n\n self.occurrences = np.zeros((n_classes,), dtype=int)\n if not os.path.exists(self.path):\n os.makedirs(self.path)\n\n if GCP:\n with file_io.FileIO(datafile, 'r') as f:\n train_data = json.load(f)\n else:\n with open(datafile, 'r') as f:\n train_data = json.load(f)\n\n df = pd.DataFrame.from_records(train_data[\"images\"])\n\n if not test:\n train_labels_df = pd.DataFrame.from_records(train_data[\"annotations\"])\n df = pd.merge(df, train_labels_df, on=\"imageId\", how=\"outer\")\n df[\"labelId\"] = df[\"labelId\"].apply(lambda x: [int(i) for i in x])\n\n df['imageId'] = df['imageId'].astype(int, copy=False)\n\n # Remove infrequent classes for training dataset and save class weights.\n if self.train:\n df[\"labelId\"] = self._find_freq_classes(df[\"labelId\"], label_occ_threshold)\n self.class_weights, self.binary_class_matrix = self._get_class_weights(df[\"labelId\"])\n\n # Normalize weights for sampling.\n self.class_weights_normalized, self.cw_choices, self.cw_probs = self._normalize_class_weights()\n\n # Shape of train_df ['imageId', 'url', 'labelId'], shape: (1014544, 3)\n self.df = df\n\n self.original_indices = self.df['imageId'].values\n self.epoch_indices = self.original_indices\n\n # Length Total Dataset\n self.n_samples = len(self.df)\n\n self.on_epoch_end()\n\n def _normalize_class_weights(self):\n factor = 1.0 / sum(self.class_weights.values())\n normalized = {k: (v * factor) for k, v in self.class_weights.items()}\n # No order in dict, so we have to iterate\n d_choices = []\n d_probs = []\n for k, v in normalized.items():\n d_choices.append(k)\n d_probs.append(v)\n return normalized, d_choices, d_probs\n\n def _find_freq_classes(self, series, label_occ_threshold):\n # Get labels to be ignored.\n total_list = []\n for i, item in series.iteritems():\n total_list.extend(item)\n count_items = Counter(total_list)\n\n if self.thresholdsmaller:\n labels_whitelist = [x for x in count_items if (count_items[x] <= label_occ_threshold) & (count_items[x] > 500)]\n else:\n labels_whitelist = [x for x in count_items if (count_items[x] > label_occ_threshold) & (count_items[x] > 500)]\n\n return series.apply(lambda x: [i for i in x if i in labels_whitelist])\n\n def _get_class_weights(self, series):\n # Create binary encoding for the labels\n y = np.empty((len(series), self.n_classes), dtype=np.int)\n\n for i, item in series.iteritems():\n labels = np.asarray(item)\n\n # Store label and class\n y[i,] = self._labels_to_array(labels)\n\n # Count per column\n counter = y.sum(axis=0)\n\n # Calculate and return weights\n majority = np.max(counter)\n class_weights = {i: 0 if counter[i] == 0 else float(majority / counter[i]) for i in range(len(counter))}\n\n return class_weights, y\n\n def on_epoch_end(self):\n \"\"\"\n Create new indices for the epoch\n \"\"\"\n if self.shuffle:\n np.random.shuffle(self.epoch_indices)\n\n def __len__(self):\n \"\"\" Denotes the number of batches per epoch \"\"\"\n return int(np.ceil(self.n_samples / self.batch_size))\n\n def _gen_balanced_sample(self):\n classes = np.random.choice(self.cw_choices, self.batch_size, p=self.cw_probs)\n\n # Generate binary matrix for classes\n samples = []\n for c in classes:\n # todo: sample one index per rows var and append to list, return list.\n idxs = np.where(self.binary_class_matrix[:,c] == 1)\n samples.append(np.random.choice(idxs[0]))\n\n return samples\n\n def __getitem__(self, index):\n \"\"\" Generate one batch of data \"\"\"\n # Generate indexes of the batch\n if self.train:\n batch_indices = self._gen_balanced_sample()\n else:\n batch_indices = self.epoch_indices[index * self.batch_size:(index + 1) * self.batch_size]\n return self._get_batches_of_transformed_samples(batch_indices)\n\n def get_image(self, url, ID):\n \"\"\"\n download image from url, reshapes it to dimension size e.g (128x128) and normalize it\n :returns np array of image dimension\n \"\"\"\n if self.GCP:\n file_path = '{}{}.jpg'.format(self.path, ID)\n with file_io.FileIO(file_path, mode='rb') as f:\n image = Image.open(io.BytesIO(f.read()))\n image = np.asarray(image, dtype=K.floatx())\n return image / 255\n else:\n # load the image from ./data/img/set/{ID} if it exists\n save_path = os.path.join(self.path, str(ID) + '.jpg')\n\n if os.path.isfile(save_path):\n image = Image.open(save_path)\n image = np.asarray(image, dtype=K.floatx())\n return image / 255\n\n response = http_client.request(\"GET\", url[0])\n image = Image.open(io.BytesIO(response.data))\n image = image.convert(\"RGB\")\n image = image.resize(self.dim, Image.ANTIALIAS)\n\n if self.save_images:\n image.save(save_path, optimize=True, quality=85)\n\n image = np.asarray(image, dtype=K.floatx())\n\n return image / 255\n\n def _labels_to_array(self, labels):\n \"\"\"\n Converts a list of labels to a one-hot encoded array\n \"\"\"\n labels_array = np.zeros((self.n_classes,), dtype=int)\n labels = np.array(labels)\n\n # Labels are 1-based, so do - 1\n if len(labels) > 0:\n labels_array[labels - 1] = 1\n\n # Bookkeeping\n self.occurrences += labels_array\n\n return labels_array\n\n # Input list_IDs_temp imageIDs list of size == self.batch_size\n def _get_batches_of_transformed_samples(self, list_IDs_temp):\n \"\"\"\n Generates data containing batch_size samples\n :param list_IDs_temp\n :return X: (n_samples, *dim, n_channels) y:(n_samples, n_classes)\n \"\"\"\n # Initialization\n #todo: GCP uses python 2, starred expressions don't work in Python2. Changed to python 3 in config.yaml :))\n X = np.empty((len(list_IDs_temp), *self.dim, self.n_channels), dtype=K.floatx())\n\n if not self.test:\n y = np.empty((len(list_IDs_temp), self.n_classes), dtype=np.int)\n\n # Generate data\n for i, ID in enumerate(list_IDs_temp):\n try:\n row = self.df.loc[self.df['imageId'] == int(ID)]\n url = row['url'].values\n image = self.get_image(url, ID)\n X[i, ] = image\n\n if not self.test:\n # The 0 indexing is because row is a mini dataframe, so it is two dimensional.\n labels = row['labelId'].values[0]\n labels = np.asarray(labels)\n # Store label and class\n y[i, ] = self._labels_to_array(labels)\n except Exception as e:\n print(\"Exception|\", e, \"|\", url)\n\n if not self.test:\n return X, y\n else:\n return X\n\nif __name__ == \"__main__\":\n generator = MultiLabelGenerator(horizontal_flip=True)\n generator = generator.make_datagenerator(\n datafile='../data/validation.json', data_path='../data/img/validation/', save_images=True, shuffle=True)\n\n # n_samples = 0\n # for i in tqdm(range(len(generator)), desc=\"Iterating Over Generator\", unit=\"batches\"):\n # batch_x, _ = generator[i]\n # n_samples += batch_x.shape[0]\n #\n # print(\"Total Samples:\", n_samples)\n\n # model, _ = mobilenet_model(generator.n_classes)\n # model.fit_generator(generator, steps_per_epoch=None, epochs=1, verbose=1)\n","sub_path":"batch_generator/batch_gen_weights.py","file_name":"batch_gen_weights.py","file_ext":"py","file_size_in_byte":10052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"378853338","text":"import ast\nimport json\n\nfrom django.http import JsonResponse\nfrom django.shortcuts import render, get_object_or_404\n\n# Create your views here.\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.decorators.http import require_POST\n\nfrom availability.models import POI, Availability, Features\n\n\ndef list_POIs(request):\n return JsonResponse({\n 'data': [t.to_dict() for t in POI.objects.all().order_by('-updated_at')],\n })\n\n\ndef get_availability(request, pk):\n return JsonResponse({\n 'data': [availability.to_dict() for availability in Availability.objects.filter(poi=pk)],\n })\n\n\ndef get_feature(request, pk):\n return JsonResponse({\n 'data': [feature.to_dict() for feature in Features.objects.get(poi=pk)],\n })\n\n\n@csrf_exempt\n@require_POST\ndef create_POI(request):\n\n data = json.loads(request.body)\n poi = data.get('poi')\n space = data.get('space')\n did = data.get('did')\n title = data.get('title')\n description = data.get('description')\n precision = data.get('precision')\n\n new_poi = POI(did=did, poi=poi, space=space, title=title, description=description,\n precision=precision)\n new_poi.save()\n\n return JsonResponse(new_poi.to_dict(), status=201)\n\n\n@csrf_exempt\ndef create_availability(request):\n if request.method == 'POST':\n data = json.loads(request.body)\n poi = data.get('poi')\n space = data.get('space')\n did = data.get('did')\n status = data.get('status')\n schedule = data.get('schedule')\n challenge = data.get('challenge')\n info = data.get('info')\n availability = Availability(did=did, poi_id=poi, space=space, schedule=schedule,\n challenge=challenge, info=info)\n availability.save()\n\n return JsonResponse(availability.to_dict(), status=201)\n\n return JsonResponse({}, status=200)\n\n\n@csrf_exempt\n@require_POST\ndef create_feature(request):\n data = json.loads(request.body)\n poi = data.get('poi')\n space = data.get('space')\n did = data.get('did')\n status = data.get('status')\n info = data.get('info')\n challenge = data.get('challenge')\n\n feature = Features(did=did, poi=poi, space=space, status=status, info=info,\n challenge=challenge)\n feature.save()\n\n return JsonResponse(feature.to_dict(), status=201)\n","sub_path":"server/availability/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"329835819","text":"#!/usr/bin/env python3\n\nimport json\n\ndef sum_of_item(item, skip_red=False):\n\n if isinstance(item, list):\n return sum([sum_of_item(i, skip_red) for i in item])\n\n if isinstance(item, dict):\n if skip_red and 'red' in item.values():\n return 0\n return sum([sum_of_item(i, skip_red) for i in item.values()])\n\n if isinstance(item, str):\n return 0\n\n if isinstance(item, int):\n return item\n\n\ndef main():\n in_values = \"\".join([x for x in open(\"inputs/day_12.txt\").read().strip().split(\"\\n\")])\n\n v = json.loads(in_values)\n\n print(\"Sum of all numbers: %s\", sum_of_item(v))\n print('Correct sum: %s', sum_of_item(v, True))\n\nif __name__ == '__main__':\n main()\n","sub_path":"2015/day_12.py","file_name":"day_12.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"391123647","text":"from google.cloud import speech\nfrom google.cloud.speech import enums\nfrom google.cloud.speech import types\nimport pickle\nimport io\nimport os\nimport argparse\nimport pandas as pd\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--id', default='1_1a', type=str, required=True)\nparser.add_argument('-n', '--task_num', type=int, required=True)\nargs = parser.parse_args()\n\naudio = 'gs://newbrowncorpus/{0}/{0}_task{1}.wav'.format(args.id, str(args.task_num))\noutput = '{0}/{0}_task{1}.p'.format(args.id, str(args.task_num))\nif not os.path.exists(args.id):\n os.makedirs(args.id)\n\nclient = speech.SpeechClient()\naudio = types.RecognitionAudio(uri=audio)\nconfig = types.RecognitionConfig(\n sample_rate_hertz=44100,\n language_code='en-US',\n enable_word_time_offsets=True)\noperation = client.long_running_recognize(config, audio)\n\nprint('Waiting for operation to complete...')\nresult = operation.result(timeout=300)\n\nwith open(output, 'wb+') as f:\n pickle.dump(result, f)\n\nfor result in result.results:\n alternative = result.alternatives[0]\n print(u'Transript: {}'.format(alternative.transcript))\n print('Confidence: {}'.format(alternative.confidence))\n\n for word_info in alternative.words:\n word = word_info.word\n start_time = word_info.start_time\n end_time = word_info.end_time\n print('Word: {}, start_time: {}, end_time: {}'.format(\n word,\n start_time.seconds + start_time.nanos * 1e-9,\n end_time.seconds + end_time.nanos * 1e-9))\n","sub_path":"backup/_prepass/audio2txt.py","file_name":"audio2txt.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"476066735","text":"import random\r\n\r\nLINE_BREAK = \"_________________________\\n\"\r\nTEXT_ORIGINAL_FILE = \"Original File\"\r\nTEXT_NEW_FILE = \"New File\"\r\n\r\n\r\n\r\nDISPLAY_LINE = \"{}: {}\"\r\n\r\n\r\n# Set the filename and access mode\r\nfileName = \"AManNamedJed.txt\"\r\naccessMode = \"r\"\r\n\r\nnewFileName = \"AnotherManNamedJed.txt\"\r\nnewAccessMode = \"w\"\r\n\r\n# Open the file\r\nwith open(fileName, accessMode) as storyFile:\r\n\r\n\t# Create a list to hold the story lines\r\n\tstory = []\r\n\r\n\t# Create a string to write to the file\r\n\ttoFile = \"\"\r\n\r\n\t# Create a string to display to the string\r\n\ttoConsole = \"\"\r\n\r\n\t# Add the lines of the story to the file\r\n\twhile True:\r\n\t\ttry:\r\n\t\t\tstory.append(storyFile.__next__())\r\n\t\texcept StopIteration:\r\n\t\t\tbreak\r\n\r\n\t# Choose a random line form the story to capitalize\r\n\trandomLine = random.randint(0, len(story)-1)\r\n\r\n\t# Print the original file title\r\n\tprint(LINE_BREAK+TEXT_ORIGINAL_FILE+\"\\n\"+LINE_BREAK)\r\n\r\n\t# Print every line in the original story\r\n\tfor line in story:\r\n\t\ttoConsole += line\r\n\tprint(toConsole)\r\n\r\n\r\n\t# Print the new file totle\r\n\tprint(LINE_BREAK + TEXT_NEW_FILE + \"\\n\" + LINE_BREAK)\r\n\r\n\t# Reset the console variable\r\n\ttoConsole = \"\"\r\n\r\n\t# Print every line in the new story\r\n\tfor i in range(len(story)):\r\n\r\n\t\t# Check if the line needs to be capitalized\r\n\t\tif i == randomLine:\r\n\t\t\tline = story[i].upper()\r\n\t\telse:\r\n\t\t\tline = story[i].lower()\r\n\r\n\t\t# Add the line to write to the file\r\n\r\n\t\ttoFile += line\r\n\r\n\t\ttoConsole += DISPLAY_LINE.format(i+1, line)\r\n\tprint(toConsole)\r\n\r\n# Write the new story to the new file\r\nwith open(newFileName, newAccessMode) as newFile:\r\n\tnewFile.seek(0)\r\n\tnewFile.write(toFile)\r\n","sub_path":"Assignment4/AManNamedJed.py","file_name":"AManNamedJed.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"2054023","text":"from utilityLibs.Texture2DArray import *\nfrom toolLibs import image\nimport os.path, zipfile, io\n\nclass ImageTexture2DArray(Texture2DArray):\n def __init__(self, *files):\n membuf = io.BytesIO()\n width = None\n height = None\n slices = 0\n\n #print(str(files))\n for fname in files:\n if fname.endswith(\".png\") or fname.endswith(\".jpg\"):\n tmp = open(os.path.join(\"assets\", fname), \"rb\").read()\n pw, ph, fmt, pix = image.decode(tmp)\n pix = image.flipY(pw, ph, pix)\n #print(fname,pw,ph)\n #print(fname + \" imageW: \" + str(pw) + \" imageH: \" + str(ph))\n if width == None:\n width = pw\n height = ph\n else:\n if width != pw or height != ph:\n raise RuntimeError(\"Size mismatch\"+\n str((width, height)) + \" \" + str((pw, ph)))\n slices += 1\n membuf.write(pix)\n\n elif fname.endswith(\".ora\") or fname.endswith(\".zip\"):\n z = zipfile.ZipFile(os.path.join(\"assets\"), fname)\n for n in sorted(z.namelist()):\n if \"thumbnail\" in n:\n continue\n if n.endswith(\".png\") or n.endswith(\".jpg\"):\n tmp = z.open(n).read()\n pw, ph, fmt, pix = image.decode(tmp)\n pix = image.flipY(pw, ph, pix)\n if width == None:\n width = pw;\n height = ph\n else:\n if width != pw or height != ph:\n raise RuntimeError(\"Size mismatch\"+\n str((width, height)) + \" \" + str((pw, ph)))\n slices += 1\n membuf.write(pix)\n else:\n raise RuntimeError(\"Cannot read file: \" + fname)\n\n #Push texture data to gpu\n Texture2DArray.__init__(self, width, height, slices)\n tmp = array.array(\"I\", [0])\n glGenTextures(1, tmp)\n self.tex = tmp[0]\n self.bind(0) #set superclass tex as the active tex object\n\n glTexImage3D(\n GL_TEXTURE_2D_ARRAY, #Type of Texture\n 0, #Mip Level\n GL_RGBA, #Internal Format\n width, height, slices, #Size\n 0, #Border\n GL_RGBA, #In Data Format\n GL_UNSIGNED_BYTE, #In Data type\n membuf.getbuffer()) #In Data\n\n self.unbind(0)","sub_path":"lab 6/utilityLibs/ImageTexture2DArray.py","file_name":"ImageTexture2DArray.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"111957558","text":"import os\nimport sys\nimport numpy as np\nnp.set_printoptions(threshold=sys.maxsize)\nimport math\n\nfrom _so_dir_maker_compare import dir_maker_compare\n\ndef save_data_compare(date_time, frame, opt_iter_robot, opt_iter_all, remove_ped, \\\n remove_ped_path_length, chandler, p2w_x, p2w_y, p2w, \\\n remove_ped_start, goal_dex, home_dir, save_dir, data_set, full_traj, \\\n random_sample, var_sample, num_random_samples, num_var_samples, \\\n ess_1, top_Z_indices_1, num_optima_1, \\\n optimal_ll_1, optima_dex_1, norm_likelihood_1, optima_1, \\\n robot_path_length_1, safety_remove_ped_1, \\\n safety_robot_1, robot_agent_path_diff_1, time_1, \\\n local_density_1, robot_history_x_1, robot_history_y_1, \\\n ess_2, top_Z_indices_2, num_optima_2, \\\n optimal_ll_2, optima_dex_2, norm_likelihood_2, optima_2, \\\n robot_path_length_2, safety_remove_ped_2, \\\n safety_robot_2, robot_agent_path_diff_2, time_2, \\\n local_density_2, robot_history_x_2, robot_history_y_2, \\\n agent_disrupt_fo, robot_agent_disrupt_fo, \\\n agent_disrupt_so, robot_agent_disrupt_so, \\\n label_1, label_2):\n def truncate(value):\n return math.trunc(value*1e4)/1e4\n\n if frame==0:\n ave_time = time_1[frame]\n std_time = time_1[frame]\n max_time = math.trunc(time_1[frame]*1e4)/1e4\n\n ave_agent_disrupt_fo = agent_disrupt_fo[frame]\n ave_agent_disrupt_so = agent_disrupt_so[frame]\n std_agent_disrupt_fo = agent_disrupt_fo[frame]\n std_agent_disrupt_so = agent_disrupt_so[frame]\n\n ave_robot_agent_disrupt_fo = robot_agent_disrupt_fo[frame]\n ave_robot_agent_disrupt_so = robot_agent_disrupt_so[frame]\n std_robot_agent_disrupt_fo = robot_agent_disrupt_fo[frame]\n std_robot_agent_disrupt_so = robot_agent_disrupt_so[frame]\n\n ave_density = local_density_1[frame]\n std_density = local_density_1[frame]\n max_density = math.trunc(local_density_1[frame]*1e4)/1e4\n else:\n ave_time = np.mean(time_1[:frame])\n std_time = np.std(time_1[:frame])\n max_time = math.trunc(np.max(time_1[:frame])*1e4)/1e4\n\n ave_agent_disrupt_fo = np.mean(agent_disrupt_fo[:frame])\n ave_agent_disrupt_so = np.mean(agent_disrupt_so[:frame])\n std_agent_disrupt_fo = np.std(agent_disrupt_fo[:frame])\n std_agent_disrupt_so = np.std(agent_disrupt_so[:frame])\n\n ave_robot_agent_disrupt_fo = np.mean(robot_agent_disrupt_fo[:frame])\n ave_robot_agent_disrupt_so = np.mean(robot_agent_disrupt_so[:frame])\n std_robot_agent_disrupt_fo = np.std(robot_agent_disrupt_fo[:frame])\n std_robot_agent_disrupt_so = np.std(robot_agent_disrupt_so[:frame])\n\n ave_density = np.mean(local_density_1[:frame])\n std_density = np.std(local_density_1[:frame])\n max_density = math.trunc(np.max(local_density_1[:frame])*1e4)/1e4\n\n time_now = math.trunc(time_1[frame]*1e4)/1e4\n ave_time = math.trunc(ave_time*1e4)/1e4\n std_time = math.trunc(std_time*1e4)/1e4\n\n density_now = math.trunc(local_density_1[frame]*1e4)/1e4\n ave_density = math.trunc(ave_density*1e4)/1e4\n std_density = math.trunc(std_density*1e4)/1e4\n\n robot_diff = [p2w_x*(robot_history_x_1-robot_history_x_2), \\\n p2w_y*(robot_history_y_1-robot_history_y_2)]\n\n plots_or_metrics = 'metrics'\n dir_maker_compare(remove_ped, remove_ped_start, goal_dex, home_dir, \\\n save_dir, data_set, full_traj, plots_or_metrics)\n\n filename = 'agent_' + str(remove_ped) + \\\n'_start_'+ str(remove_ped_start) + \\\n'_steps_'+ str(goal_dex) + '_compare_' + str(date_time) + '.txt'\n with open(filename, 'a') as text_file:\n print(f\"REMOVE PED: {remove_ped}\", file=text_file)\n print(f\"FRAME NUMBER: {frame}\", file=text_file)\n print(f\"ESS {label_1}: {ess_1}\", file=text_file)\n print(f\"TOP Z INDICES {label_1}: {top_Z_indices_1[:ess_1]}\", file=text_file)\n print(f\"ESS {label_2}: {ess_2}\", file=text_file)\n print(f\"TOP Z INDICES {label_2}: {top_Z_indices_2[:ess_2]}\", file=text_file)\n print(f\"NUM OPTIMA {label_1}: {num_optima_1}\", file=text_file)\n print(f\"NUM OPTIMA {label_2}: {num_optima_2}\", file=text_file)\n # for i in range(num_optima_1):\n # print(f\"LL {label_1} VALUES: {math.trunc(optimal_ll_1[i]*1e4)/1e4}\", file=text_file)\n # for i in range(num_optima_2):\n # print(f\"LL {label_2} VALUES: {math.trunc(optimal_ll_2[i]*1e4)/1e4}\", file=text_file)\n # for i in range(num_optima_1):\n # if opt_iter_robot or opt_iter_all:\n # zz = math.trunc(\\\n # np.linalg.norm((optima_1[0][0]-optima_1[i][0])*p2w)*1e4)/1e4\n # else:\n # zz = math.trunc(\\\n # np.linalg.norm((optima_1[0].x-optima_1[i].x)*p2w)*1e4)/1e4\n # print(f\"NORM DIFF BETWEEN {label_1} OPTIMA: {zz}\", file=text_file)\n print(f\"TIME NOW: {time_now}\", file=text_file)\n print(f\"TIME MEAN: {ave_time}+/-{std_time}\", file=text_file)\n print(f\"TIME MAX: {max_time}\", file=text_file)\n print(f\"SAFETY AGENT MIN: \\\n{math.trunc(np.min(safety_remove_ped_1)*1e4)/1e4}\", file=text_file)\n print(f\"SAFETY ROBOT {label_1} MIN: {math.trunc(np.min(safety_robot_1)*1e4)/1e4}\", file=text_file)\n print(f\"SAFETY ROBOT {label_2} MIN: {math.trunc(np.min(safety_robot_2)*1e4)/1e4}\", file=text_file)\n print(f\"SAFETY AGENT MEAN: \\\n{math.trunc(np.mean(safety_remove_ped_1)*1e4)/1e4}+/-\\\n{math.trunc(np.std(safety_remove_ped_1)*1e4)/1e4}\", file=text_file)\n print(f\"SAFETY ROBOT {label_1} MEAN: \\\n{math.trunc(np.mean(safety_robot_1)*1e4)/1e4}+/-\\\n{math.trunc(np.std(safety_robot_1)*1e4)/1e4}\", file=text_file)\n print(f\"SAFETY ROBOT {label_2} MEAN: \\\n{math.trunc(np.mean(safety_robot_2)*1e4)/1e4}+/-\\\n{math.trunc(np.std(safety_robot_2)*1e4)/1e4}\", file=text_file)\n if frame>0:\n print(f\"{label_1}-{label_1} PATH DIFF NORM \\\n{truncate(np.linalg.norm(robot_diff))}\", file=text_file)\n print(f\"{label_1}-{label_1} PATH DIFF MEAN \\\n{truncate(np.mean(robot_diff))}+/-{truncate(np.std(robot_diff))}\", file=text_file)\n print(f\"ROBOT {label_1}-AGENT PATH DIFF MEAN \\\n{math.trunc(1e4*np.mean(robot_agent_path_diff_1[:frame]))/1e4}+/-\\\n{math.trunc(1e4*np.std(robot_agent_path_diff_1[:frame]))/1e4}\", file=text_file)\n print(f\"ROBOT {label_1}-AGENT PATH DIFF MAX \\\n{math.trunc(np.max(robot_agent_path_diff_1)*1e4)/1e4}\", file=text_file)\n print(f\"ROBOT {label_2}-AGENT PATH DIFF MEAN \\\n{math.trunc(1e4*np.mean(robot_agent_path_diff_2[:frame]))/1e4}+/-\\\n{math.trunc(1e4*np.std(robot_agent_path_diff_2[:frame]))/1e4}\", file=text_file)\n print(f\"ROBOT {label_2}-AGENT PATH DIFF MAX \\\n{math.trunc(np.max(robot_agent_path_diff_2)*1e4)/1e4}\", file=text_file)\n print(f\"AGENT PATH LENGTH: \\\n{math.trunc(remove_ped_path_length*1e4)/1e4}\")\n print(f\"ROBOT {label_1} PATH LENGTH: {math.trunc(robot_path_length_1*1e4)/1e4}\", file=text_file)\n print(f\"ROBOT {label_2} PATH LENGTH: {math.trunc(robot_path_length_2*1e4)/1e4}\", file=text_file)\n print(f\"AGENT DISRUPT NOW {label_1}: {truncate(agent_disrupt_fo[frame])}\", file=text_file)\n print(f\"AGENT DISRUPT NOW {label_2}: {truncate(agent_disrupt_so[frame])}\", file=text_file)\n print(f\"ROBOT-AGENT DISRUPT NOW {label_1}: {truncate(robot_agent_disrupt_fo[frame])}\", file=text_file)\n print(f\"ROBOT-AGENT DISRUPT NOW {label_2}: {truncate(robot_agent_disrupt_so[frame])}\", file=text_file)\n print(f\"AGENT DISRUPT MEAN {label_1}: \\\n{truncate(ave_agent_disrupt_fo)}+/-\\\n{truncate(std_agent_disrupt_fo)}\", file=text_file)\n print(f\"AGENT DISRUPT MEAN {label_2}: \\\n{truncate(ave_agent_disrupt_so)}+/-\\\n{truncate(std_agent_disrupt_so)}\", file=text_file)\n print(f\"ROBOT-AGENT DISRUPT MEAN {label_1}: \\\n{truncate(ave_robot_agent_disrupt_fo)}+/-\\\n{truncate(std_robot_agent_disrupt_fo)}\", file=text_file)\n print(f\"ROBOT-AGENT DISRUPT MEAN {label_2}: \\\n{truncate(ave_robot_agent_disrupt_so)}+/-\\\n{truncate(std_robot_agent_disrupt_so)}\", file=text_file)\n print(f\"DENSITY NOW: {density_now}\", file=text_file)\n print(f\"DENSITY MEAN: {ave_density}+/-{std_density}\", file=text_file)\n print(f\"DENSITY MAX: {max_density}\", file=text_file)\n print('', file=text_file)\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"crowd_sim/envs/utils/_so_save_data_compare.py","file_name":"_so_save_data_compare.py","file_ext":"py","file_size_in_byte":8091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"165155418","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Dec 5 09:52:57 2017\r\n\r\n@author: ty-hongjy\r\n\"\"\"\r\n\r\nimport math\r\nfrom operator import mod\r\nimport time\r\ndef func(a,b,c,d):\r\n if mod(c,a)==0 and mod(d,b)==0:\r\n print( c+d,c/a,d/b)\r\n return 0\r\n elif(d-a)<0:\r\n print( \"*\",c+d,c/a,d/b)\r\n return -1\r\n else:\r\n func(a,b,c+a,d-a)\r\n \r\n \r\ndef main():\r\n# print(\"3,7\")\r\n # for n in range(11,101,1): \r\n # func(3,7,0,n)\r\n \r\n start=time.strftime('%H:%M:%S',time.localtime(time.time()))\r\n print(\"3,5\")\r\n #for n in range(1,1000001,1): \r\n for n in range(1,1000001,1): \r\n func(3,5,0,n)\r\n print(start)\r\n print(time.strftime('%H:%M:%S',time.localtime(time.time())))\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"noip/py2017-01.py","file_name":"py2017-01.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"224228102","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# This module uses OpenERP, Open Source Management Solution Framework.\n# Copyright (C) 2017-Today Sitaram\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see \n#\n##############################################################################\n\nfrom odoo import fields, models, api\n\n\nclass SrCreateQuotation(models.TransientModel):\n _name = \"sr.create.quotation\"\n\n partner_id = fields.Many2one('res.partner', string=\"Partner\")\n\n @api.multi\n def create_quotation(self):\n sale_id = self.env['sale.order'].create({'partner_id': self.partner_id.id})\n for product in self._context.get('active_ids'):\n self.env['sale.order.line'].create({'product_id': product,\n 'order_id': sale_id.id})\n\n action = self.env.ref('sale.action_quotations').read()[0]\n action['views'] = [(self.env.ref('sale.view_order_form').id, 'form')]\n action['res_id'] = sale_id.ids[0]\n return action\n","sub_path":"modules/sr_sale_multi_product_selection/models/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"582709035","text":"from newspaper import Article\nfrom konlpy.tag import Kkma\nfrom konlpy.tag import Okt\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.preprocessing import normalize\nimport numpy as np\n\nclass SentenceTokenizer(object):\n def __init__(self):\n self.kkma = Kkma()\n self.twitter = Okt()\n self.stopwords = ['중인' ,'만큼', '마찬가지', '꼬집었', \"연합뉴스\", \"데일리\", \"동아일보\", \"중앙일보\", \"조선일보\", \"기자\", \"뉴스\"\n,\"아\", \"휴\", \"아이구\", \"아이쿠\", \"아이고\", \"어\", \"나\", \"우리\", \"저희\", \"따라\", \"의해\", \"을\", \"를\", \"에\", \"의\", \"가\", \"사람\"]\n def url2sentences(self, url):\n article = Article(url, language='ko')\n article.download()\n article.parse()\n sentences = self.kkma.sentences(article.text)\n\n for idx in range(0, len(sentences)):\n if len(sentences[idx]) <= 10:\n sentences[idx-1] += (' ' + sentences[idx])\n sentences[idx] = ''\n\n return sentences\n \n def text2sentences(self, text):\n sentences = self.kkma.sentences(text)\n for idx in range(0, len(sentences)):\n if len(sentences[idx]) <= 10:\n sentences[idx-1] += (' ' + sentences[idx])\n sentences[idx] = ''\n \n return sentences\n\n def get_nouns(self, sentences):\n nouns = []\n for sentence in sentences:\n if sentence != '':\n nouns.append(' '.join([noun for noun in self.twitter.nouns(str(sentence)) if noun not in self.stopwords and len(noun) > 1]))\n\n return nouns","sub_path":"textrank/sentence_tokenizer.py","file_name":"sentence_tokenizer.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"95221757","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\n\n\"\"\" Super Class \"\"\"\nclass Optimizer(object):\n \"\"\"\n This is a template for implementing the classes of optimizers\n \"\"\"\n def __init__(self, net, lr=1e-4):\n self.net = net # the model\n self.lr = lr # learning rate\n\n \"\"\" Make a step and update all parameters \"\"\"\n def step(self):\n raise ValueError(\"Not Implemented Error\")\n\n\n\"\"\" Classes \"\"\"\nclass SGD(Optimizer):\n \"\"\" Some comments \"\"\"\n def __init__(self, net, lr=1e-4):\n self.net = net\n self.lr = lr\n\n def step(self):\n for layer in self.net.layers:\n for n, dv in layer.grads.items():\n layer.params[n] -= self.lr * dv\n\n\nclass SGDM(Optimizer):\n \"\"\" Some comments \"\"\"\n def __init__(self, net, lr=1e-4, momentum=0.0):\n self.net = net\n self.lr = lr\n self.momentum = momentum\n self.velocity = {} # last update of the velocity\n\n def step(self):\n #############################################################################\n # TODO: Implement the SGD + Momentum #\n #############################################################################\n # pass\n for layer in self.net.layers:\n for n, v in layer.params.items():\n dw = layer.grads[n]\n if n not in self.velocity:\n prev_velocity = np.zeros(dw.shape)\n else:\n prev_velocity = self.velocity.get(n)\n self.velocity[n] = self.momentum * prev_velocity - self.lr * dw\n layer.params[n] += self.velocity[n]\n #############################################################################\n # END OF YOUR CODE #\n #############################################################################\n\n\nclass RMSProp(Optimizer):\n \"\"\" Some comments \"\"\"\n def __init__(self, net, lr=1e-2, decay=0.99, eps=1e-8):\n self.net = net\n self.lr = lr\n self.decay = decay\n self.eps = eps\n self.cache = {} # decaying average of past squared gradients\n\n def step(self):\n #############################################################################\n # TODO: Implement the RMSProp #\n #############################################################################\n # pass\n for layer in self.net.layers:\n for n, v in layer.params.items():\n dw = layer.grads[n]\n w = layer.params[n]\n if n not in self.cache:\n cache = np.zeros(w.shape)\n else:\n cache = self.cache.get(n)\n self.cache[n] = self.decay * cache + (1 - self.decay) * (dw ** 2)\n layer.params[n] = w - self.lr * dw / (np.sqrt(self.cache[n] + self.eps))\n #############################################################################\n # END OF YOUR CODE #\n #############################################################################\n\n\nclass Adam(Optimizer):\n \"\"\" Some comments \"\"\"\n def __init__(self, net, lr=1e-3, beta1=0.9, beta2=0.999, t=0, eps=1e-8):\n self.net = net\n self.lr = lr\n self.beta1, self.beta2 = beta1, beta2\n self.eps = eps\n self.mt = {}\n self.vt = {}\n self.t = t\n\n def step(self):\n #############################################################################\n # TODO: Implement the Adam #\n #############################################################################\n # pass\n\n for layer in self.net.layers:\n for n, v in layer.params.items():\n self.t = self.t + 1\n dw = layer.grads[n]\n w = layer.params[n]\n if n not in self.mt:\n mt = np.zeros(dw.shape)\n else:\n mt = self.mt[n]\n\n if n not in self.vt:\n vt = np.zeros(dw.shape)\n else:\n vt = self.vt[n]\n\n self.mt[n] = self.beta1 * mt + (1 - self.beta1) * dw\n self.vt[n] = self.beta2 * vt + (1 - self.beta2) * (dw ** 2)\n\n _mt = self.mt[n] / (1 - self.beta1 ** self.t)\n _vt = self.vt[n] / (1 - self.beta2 ** self.t)\n\n\n layer.params[n] = w - self.lr * _mt / (np.sqrt(_vt) + self.eps)\n #############################################################################\n # END OF YOUR CODE #\n #############################################################################\n","sub_path":"csci566-assignment-1/lib/optim.py","file_name":"optim.py","file_ext":"py","file_size_in_byte":5003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"122127756","text":"from django.shortcuts import render\nfrom Book_Store.forms import RegistrationForm,StoreRegistrationForm\nfrom django.contrib.auth.models import auth\nfrom django.contrib import messages\nfrom Book_Store.models import StoreBook\nfrom django.contrib.auth import get_user_model\n# Create your views here.\ndef index(request):\n\treturn render(request,'index.html')\ndef SignUp(request):\n if request.method == 'POST':\n form = RegistrationForm(request.POST)\n if form.is_valid():\n form.save()\n return render(request, 'index.html' )\n else:\n form = RegistrationForm()\n return render(request,'SignUp.html',{'form': form})\ndef Store_User(request):\n if request.method == 'POST':\n form = StoreRegistrationForm(request.POST)\n if form.is_valid():\n form.save()\n return render(request, 'index.html' )\n else:\n form = StoreRegistrationForm()\n return render(request,'Store_USer.html',{'form': form})\ndef login(request):\n\tif request.method == 'POST':\n\t\tUsername=request.POST['Username']\n\t\tpassword=request.POST['Password']\n\t\tuser=auth.authenticate(username=Username,password=password)\n\t\tif user is not None:\n\t\t\tauth.login(request,user)\n\t\t\treturn render(request, 'index.html')\n\t\telse:\n\t\t\tmessages.info(request,'Invalid Credentials')\n\t\t\tmsg='Invalid Credentials'\n\t\t\treturn render(request,'login.html',{'msg':msg})\n\telse:\n\t\treturn render(request,'login.html')\ndef logout(request):\n\tauth.logout(request)\n\treturn render(request,'index.html')\ndef AddNewBook(request):\n\tStoreuser=request.user\n\tif request.method == 'POST':\n\t\tAuthor=request.POST['Author']\n\t\tBook=request.POST['Book']\n\t\tQuantity=request.POST['Quantity']\n\t\tif int(Quantity)<= 1:\n\t\t\tmessages.info(request,'invalid Credentials')\n\t\t\tmsg='Invalid Credentials'\n\t\t\treturn render(request,'AddNewBook.html',{'msg':msg,'Storeuser':Storeuser})\n\t\telse:\n\t\t\tfirst_name=request.user.first_name\n\t\t\tlast_name=request.user.last_name\n\t\t\ttemp = StoreBook(Storeuser=request.user,Book=Book,Author=Author,\n\t\t\tQuantity=Quantity,first_name= first_name,last_name=last_name)\n\t\t\ttemp.save()\n\t\t\treturn render(request, 'index.html')\n\telse:\n\t\treturn render(request,'AddNewBook.html',{'Storeuser':Storeuser})\ndef view_Stores(request):\n\tStorebook=get_user_model().objects.filter(is_staff=True)\n\treturn render(request, 'view_Stores.html',{'Storebook':Storebook})\ndef info(request,user_name):\n\tBookInStore=StoreBook.objects.filter(Storeuser=user_name)\n\tStore_record=get_user_model().objects.get(username=user_name)\n\tprint(BookInStore)\n\tStore=Store_record.first_name+' '+Store_record.last_name\n\tprint(Store)\n\tif BookInStore is None:\n\t\tmsg=\"The store have not Inserted any Book to database.\"\n\t\treturn render(request,'BookInStore.html',{'msg':msg,'Store':Store})\n\telse:\n\t\treturn render(request,'BookInStore.html',{'BookInStore':BookInStore,'Store':Store})\ndef get_book(request,id):\n\t#BookInStore=StoreBook.objects.get(id=id)\n\treturn render(request,'index.html')\ndef getbook(request,id):\n\tBookInStore=StoreBook.objects.get(id=id)\n\tStoreuser=BookInStore.Storeuser\n\tAuthor=BookInStore.Author\n\tBook=BookInStore.Book\n\tQuantity=BookInStore.Quantity\n\tif Quantity==0:\n\t\tmsg='Sorry Currently Book is out of stock'\n\t\treturn render(request,'msg.html',{'msg':msg})\n\tif request.method == 'POST' and Quantity != 0:\n\t\tStoreBook.objects.filter(id=id).update(Quantity=Quantity-1)\n\t\treturn render(request,'index.html')\n\treturn render(request,'get_book.html',{'Storeuser':Storeuser,\n'Author':Author,'Book':Book,'Quantity':Quantity})\ndef Update_list(request):\n\tBookInStore=StoreBook.objects.filter(Storeuser=request.user)\n\treturn render(request,'Update_list.html',{'BookInStore':BookInStore})\ndef Update_record(request,id):\n\tBookInStore=StoreBook.objects.get(id=id)\n\tStoreuser=BookInStore.Storeuser\n\tAuthor=BookInStore.Author\n\tBook=BookInStore.Book\n\tQuantity=BookInStore.Quantity\n\tif request.method == 'POST':\n\t\tQuantity=request.POST['Quantity']\n\t\tStoreBook.objects.filter(id=id).update(Quantity=Quantity)\n\t\tBookInStore=StoreBook.objects.filter(Storeuser=request.user)\n\t\treturn render(request,'Update_list.html',{'Storeuser':Storeuser,'BookInStore':BookInStore})\n\telse:\n\t\treturn render(request,'Update_record.html',{'Storeuser':Storeuser,\n\t'Author':Author,'Book':Book,'Quantity':Quantity})\ndef Delete_book(request):\n\tBookInStore=StoreBook.objects.filter(Storeuser=request.user)\n\treturn render(request,'Delete_book.html',{'BookInStore':BookInStore})\ndef Delete_record(request,id):\n\tBookInStore=StoreBook.objects.get(id=id)\n\tStoreuser=BookInStore.Storeuser\n\tAuthor=BookInStore.Author\n\tBook=BookInStore.Book\n\tQuantity=BookInStore.Quantity\n\tif request.method == 'POST':\n\t\tStoreBook.objects.filter(id=id).delete()\n\t\treturn render(request,'index.html')\n\treturn render(request,'Delete_Confirm.html',{'Storeuser':Storeuser,\n'Author':Author,'Book':Book,'Quantity':Quantity})\n","sub_path":"Book_Store/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"122631311","text":"from rest_framework import serializers\nfrom rest_framework.fields import Field, JSONField\n\nfrom main.models import Category\n\n\nclass SubCategoryDetail(serializers.ModelSerializer):\n class Meta:\n model = Category\n fields = (\n 'id',\n 'name',\n )\n\n\nclass CategoryDetailSerializer(serializers.ModelSerializer):\n siblings = SubCategoryDetail(many=True, source='get_siblings', read_only=True)\n children = SubCategoryDetail(many=True)\n parents = SubCategoryDetail(many=True, source='get_parents', read_only=True)\n\n # def create(self, validated_data):\n # print(validated_data)\n\n class Meta:\n model = Category\n fields = (\n 'id',\n 'name',\n 'parents',\n 'children',\n 'siblings',\n )\n\n\nclass ChildrenField(JSONField):\n\n def to_internal_value(self, data):\n data = super().to_internal_value(data)\n for child in data:\n category = CategoryCreateSerializer(data=child)\n category.is_valid(raise_exception=True)\n return data\n\n\nclass CategoryCreateSerializer(serializers.ModelSerializer):\n children = ChildrenField(required=False)\n\n def create(self, validated_data, parent=None):\n print(validated_data)\n children = validated_data.pop('children', [])\n category = Category.objects.create(**validated_data, parent=parent)\n for child in children:\n self.create(child, parent=category)\n\n return category\n\n class Meta:\n model = Category\n fields = (\n 'name',\n 'children',\n )\n","sub_path":"main/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"285110772","text":"# This Python file uses the following encoding: utf-8\nimport requests\nfrom bs4 import BeautifulSoup\nimport glob\nimport pandas as pd\nimport re\nimport os.path\nfrom utils import process_single_image\nimport cv2\nimport json\nimport demjson\n\n\nfilter_type = [\"skintype\", \"ingredients\", \"concerns\"]\nPROD_KEY = \"prod-id\"\ntags = [\"prod-title\", \"prod-desc\", PROD_KEY]\nurl_base = \"https://www.sallyhansen.com\"\nhttp_prefix = \"https:\"\n\nproduct_lines = [\"color-therapy\", \"complete-salon-manicure\", \"miracle-gel\", \"insta-dri\", \"hard-nails-xtreme-wear\", \"insta-dri-crayola\", \"salon-gel-polish-gel-nail-color-starter-kit\", \"salon-gel-polish-gel-nail-color\", \"i-heart-nail-art-pen\"]\n\n\nhtor = lambda h: tuple(int(h.replace('#', '')[i:i+2], 16) for i in (0, 2 ,4))\n\nrtoh = lambda rgb: '%s' % ''.join(('%02x' % p for p in rgb))\n\n\ndef get_color(url, dirname):\n path = os.path.join(dirname, 'temp_color.jpg')\n process_single_image(url, path)\n img = cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB)\n i, j, _ = img.shape\n color = img[i/2, j/2, :]\n return rtoh(color)\n\n\ndef process_product_line_page(page_, prod_line, dirname):\n soup = BeautifulSoup(page_.content, 'html.parser')\n\n r = soup.find('div', class_=\"product-radio__wrapper\")\n\n with open('{}/{}.html'.format(dirname, prod_line), 'w') as f:\n f.write(page_.content)\n\n results = []\n\n p = re.compile(r\"background-color:(#.+)\")\n pimage = re.compile(r\"background-image: url\\((.+)\\)\")\n p_images = re.compile(r\"\\s+window\\.product\\s+=\")\n images = None\n\n for x in soup.find_all('script'):\n if p_images.search(x.get_text()):\n s = p_images.sub('', x.get_text())\n s = s.replace('.trim()', '')\n with open('{}/{}.json'.format(dirname, prod_line), 'w') as f:\n f.write(s.encode('utf-8'))\n images = demjson.decode(s)\n\n if r is not None:\n for x in r.find_all(\"div\", class_=\"product-radio__input-wrapper\"):\n d = {\"prod_line\": prod_line}\n y = x.find('label')\n m = p.search(y[\"style\"])\n mimage = pimage.search(y[\"style\"])\n d[\"name\"] = y[\"for\"].strip().encode('utf-8')\n if mimage:\n d[\"hex\"] = get_color(mimage.group(1), dirname)\n d[\"colr_swatch_image\"] = mimage.group(1)\n elif m:\n d[\"hex\"] = m.group(1).replace(\"#\", \"\")\n else:\n d[\"hex\"] = None #images[\"skus\"][d[\"name\"]][\"colors\"][0][\"hex\"] or None\n d[\"slug\"] = url_base + y[\"data-slug\"]\n if images:\n d[\"image\"] = images[\"skus\"][d[\"name\"]][\"gallery\"][0][\"thumbnailImage\"]\n results.append(d)\n return results\n\n\ndef scrape(name):\n print(\"Scraping listing pages\")\n\n results = []\n for prod_line in product_lines:\n page = requests.get(url_base + '/us/nail-color/' + prod_line)\n page_results = process_product_line_page(page, prod_line, 'data_may')\n results += page_results\n print(\"Got {} products for {} line\".format(len(page_results), prod_line))\n\n df = pd.DataFrame(results)\n\n print(\"Donwloaded a total of {} products\".format(len(df)))\n df.to_csv(\"{}.csv\".format(name))\n return df\n\n\ndef join(filename1, filename2):\n\n df1 = pd.read_csv(filename1, dtype=str)\n df2 = pd.read_csv(filename2, dtype=str)\n df1['simplified_name'] = df1['name'].str.split('-', expand=True, n=1)[1].str.replace('-', '')\n df1['simplified_prod_line'] = df1['prod_line'].str.replace('-as-', '')\n\n df2['simplified_name'] = df2['Shade Name'].str.replace('[\\s+-]', '').str.replace('[.,?!\\']', '').str.lower().str.replace('é', 'e').str.replace('è', 'e').str.replace('ç', 'c')\n df2['simplified_prod_line'] = df2['Product name'].str.replace('\\s+', '-').str.lower().str.replace('-as', '').str.replace('®-\\+', '')\n\n df = pd.merge(df1, df2, how='outer', on=['simplified_name', 'simplified_prod_line'])\n print(df)\n df.to_csv('SH_spring_full.csv')\n\n\nscrape(\"sallyhansen_may\")\njoin(\"sallyhansen_may.csv\", \"SH-8.05.csv\")\n","sub_path":"sallyhensen/sallyhensen.py","file_name":"sallyhensen.py","file_ext":"py","file_size_in_byte":4043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"323070801","text":"#!/usr/bin/env python\n# encoding: utf-8\n# 描述class文件的格式\n#\n\nfrom lang.classfile.AttrSourceFile import SourceFileAttribute\nfrom lang.classfile.AttributeInfo import AttributeInfo\nfrom lang.classfile.ClassReader import ClassReader\nfrom lang.classfile.ConstantPool import ConstantPool\nfrom lang.classfile.MemberInfo import MemberInfo\n\n\nclass ClassFile:\n def __init__(self):\n # 小版本号\n self.minor_version = \"\"\n # 主版本号\n self.major_version = \"\"\n # 常量池\n self.constant_pool = None\n # 类访问标志,用于指出class文件定义的是类还是接口,访问级别是public还是private\n self.access_flags = \"\"\n # 类索引\n self.this_class = \"\"\n # 超类索引\n self.super_class = \"\"\n # 接口索引表\n self.interfaces = []\n # 变量\n self.fields = []\n # 方法\n self.methods = []\n # 属性\n self.attributes = []\n\n def parse(self, class_data):\n try:\n class_reader = ClassReader(class_data)\n self.read(class_reader)\n return self, None\n except Exception as err:\n return self, err\n\n def read(self, class_reader):\n self.read_and_check_magic(class_reader)\n self.read_and_check_version(class_reader)\n\n self.constant_pool = ConstantPool()\n self.constant_pool.read_constant_pool(class_reader)\n\n self.access_flags = int.from_bytes(class_reader.read_unit16(), byteorder=\"big\")\n self.this_class = int.from_bytes(class_reader.read_unit16(), byteorder=\"big\")\n self.super_class = int.from_bytes(class_reader.read_unit16(), byteorder=\"big\")\n self.interfaces = class_reader.read_unit16s()\n\n member_info = MemberInfo(self.constant_pool)\n self.fields = member_info.read_members(class_reader, self.constant_pool)\n self.methods = member_info.read_members(class_reader, self.constant_pool)\n self.attributes = AttributeInfo.read_attributes(class_reader, self.constant_pool)\n\n # 读取并检���Class文件的起始字节,必须以0xCAFEBABE固定字节开头\n @staticmethod\n def read_and_check_magic(class_reader):\n magic = class_reader.read_unit32()\n if magic != b'\\xca\\xfe\\xba\\xbe':\n raise RuntimeError(\"java.lang.ClassFormatError: magic!\")\n\n # 读取并检查版本号,由于采用java1.8的编译器,故支持版本号为45.0~52.0的class文件\n def read_and_check_version(self, class_reader):\n self.minor_version = int.from_bytes(class_reader.read_unit16(), byteorder='big')\n self.major_version = int.from_bytes(class_reader.read_unit16(), byteorder='big')\n\n if self.major_version == 45:\n return\n elif self.major_version in {46, 47, 48, 49, 50, 51, 52, 53, 54, 55}:\n if self.minor_version == 0:\n return\n raise RuntimeError(\"java.lang.UnsupportedClassVersionError!\")\n\n # 从常量池中查找类名\n @property\n def class_name(self):\n return self.constant_pool.get_class_name(self.this_class)\n\n # 从常量池中查找超类类名\n @property\n def super_class_name(self):\n if self.super_class > 0:\n return self.constant_pool.get_class_name(self.super_class)\n # 只有java.lang.Object没有超类\n return \"\"\n\n # 从常量池中查找接口名\n @property\n def interface_names(self):\n return [self.constant_pool.get_class_name(cpName) for cpName in self.interfaces]\n\n def fields(self):\n return self.fields\n\n def source_file_attribute(self):\n for _, attr_info in enumerate(self.attributes):\n if isinstance(attr_info, SourceFileAttribute):\n return attr_info\n\n return None\n","sub_path":"lang/classfile/ClassFile.py","file_name":"ClassFile.py","file_ext":"py","file_size_in_byte":3809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"402086715","text":"from PIL import Image, ImageFilter\n\n\ndef create_image_placeholder(img):\n placeholder = Image.open(img)\n (width, height) = placeholder.size\n new_size = (width // 30, height // 30)\n placeholder = placeholder.resize(new_size, Image.ANTIALIAS)\n placeholder = placeholder.filter(ImageFilter.BLUR)\n return placeholder\n","sub_path":"public/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"32677544","text":"#!/usr/bin/env python\n# -*- coding:utf8 -*-\n\nfrom django.conf.urls import url\nfrom blog import views\n\nurlpatterns = [\n\n url(r\"^backend/$\", views.backend),\n url(r'^add_article/$', views.add_article),\n url(r'^upload/$', views.upload),\n url(r'^del_article/(\\d+)$', views.del_article),\n url(r'^edit_article/(\\d+)$', views.edit_article),\n\n\n\n # 个人home页面\n url(r\"^(\\w+)/$\", views.home),\n\n # url(r\"^(\\w+)/category/(\\w+)$\", views.home),\n # url(r\"^(\\w+)/tag/(\\w+)$\", views.home),\n # url(r\"^(\\w+)/archive/(\\w+)$\", views.home),\n # 优化1,\n # url(r\"^(\\w+)/(category|tags|archive)/(\\w+)/$\", views.home),\n # 注意,上面如果是时间归类,且时间是按照2018-08的方式,则上面的url不可用,(\\w+)不能匹配 -,需要下面的url\n url(r'^(\\w+)/(category|tags|archive)/(.*)/$', views.home),\n\n # 文章详情页面\n url(r\"^(\\w+)/p/(\\d+)/$\", views.article),\n]\n\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"380164304","text":"import requests\nfrom django.conf import settings\n\nclass Flutterwave:\n FLUTTERWAVE_SECRET_KEY = settings.FLUTTERWAVE_SECRET_KEY\n verification_url = 'https://api.flutterwave.com/v3/'\n \n def verify_payment(self, reference, *args, **kwargs):\n \n path = (f'/transactions/{reference}/verify')\n \n headers = {\n \"Content-Type\": \"application/json\",\n \"Authorization\": \"Bearer \" + self.FLUTTERWAVE_SECRET_KEY\n }\n \n url = self.base_url + path\n response = requests.get(url, headers=headers)\n if response.status_code == 200:\n response_data = response.json()\n return response_data['status'], response_data['data']\n response_data = response.json()\n return response_data['status'], response_data['message']\n \n ","sub_path":"payment/flutterwave.py","file_name":"flutterwave.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"642567699","text":"from src_NBC.naive_bayes import *\n\ndf = pd.read_csv('/home/nam/ML_181/data/restaurant_wait.csv')\n\natt_target = 'Wait'\natt_name_list = df.columns.tolist()\natt_name_list.remove(att_target)\n\ndecisions_count, list_table_count = update_list_tables(data_frame=df, target_name=att_target)\n\nresult = {}\n\n# X = df.iloc[11:]\nX11 = df.iloc[11:].to_dict('records')[0]\nfor each_class in decisions_count.keys():\n s = 0\n for each_attribute_name in att_name_list:\n s += np.log(list_table_count[each_attribute_name].at[\\\n X11[each_attribute_name], each_class])\n\n s -= np.log(np.sum(list_table_count[each_attribute_name][each_class].tolist()))\n\n result[each_class] = np.log(decisions_count[each_class]) + s\n\nprint(max(result))\n","sub_path":"nbc.py","file_name":"nbc.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"177933453","text":"#! python3\r\n# dlTAL.py - Downloads a specific range of \"This American Life\" eps\r\n\r\nimport requests, os\r\nfrom bs4 import BeautifulSoup\r\n\r\n# Starting URL\r\nurl = 'http://audio.thisamericanlife.org/jomamashouse/ismymamashouse/'\r\nurl_title = 'http://www.thisamericanlife.org/radio-archives/episode/'\r\n\r\n# Range\r\ndl_start = 525\r\ndl_end = 525\r\nexten = '.mp3'\r\n\r\n# Place to store podcasts\r\nos.makedirs('TAL', exist_ok=True)\r\n\r\nfor ep in range(dl_start, (dl_end + 1)):\r\n\r\n\t# Create unique URL for each episode\r\n\turl_ep = url + str(ep) + exten\r\n\turl_name = url_title + str(ep)\r\n\t\r\n\t# Pull name of episode\r\n\tres = requests.get(url_name)\r\n\tres.raise_for_status()\r\n\tsoup = BeautifulSoup(res.text, 'html.parser')\r\n\t# Find title and extract w/ clean up of ':'\r\n\tsave_name = soup.find('h1', class_='node-title').string.replace(':','')\r\n\t\r\n\t# Download the episode\r\n\tprint('Downloading %s...' % url_ep)\r\n\tres = requests.get(url_ep)\r\n\tres.raise_for_status()\r\n\t\r\n\t# Save the file to ./TAL\r\n\taudio_file = open(os.path.join('TAL', '#' + save_name + exten), 'wb')\r\n\tfor chunk in res.iter_content(100000):\r\n\t\taudio_file.write(chunk)\r\n\taudio_file.close()\r\n\t\r\nprint('Done.')\r\n","sub_path":"tal/dlTALv0.5.py","file_name":"dlTALv0.5.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"287195469","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.constants as sp\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nfrom uncertainties import ufloat\nfrom uncertainties.unumpy import *\n#from uncertainties.umath import *\nplt.rcParams['text.usetex'] = True\n\n# Iteracions para el Nestle Sampling (con 1e5 es mas que suficiente)\nnpoints = int(1e3) # si se quiere disminuir el tiempo poner n = 1e2 por ejemplo\n#%% Datos del lab\n# mesures dels diametres en cm\ndiam2 = np.array([2.46,2.28,2.16,2.02,1.92,1.78,1.75,1.72,1.64,1.58,1.43,1.27,1.32,1.23])\ndiam1 = np.array([4.58,4.35,3.96,3.67,3.47,3.32,3.19,3.04,2.93,2.87,2.74,2.62,2.42,2.31])\nddiam = 0.05 #incertesa en les mesures de diametres en cm\n\nR = 6.5 #cm\n\nE = np.array([3.1,3.5,4.0,4.5,5.0,5.5,6.0,6.5,7.0,7.5,8.0,9.0,10.,11.]) #keV\n\n#%% Asignamos los errores a las magnitudes en arrays enteras\ndiam1err, diam2err = (np.array([]) for i in range(2))\n\nfor i in range(len(diam1)):\n diam1err = np.append(diam1err, ufloat(diam1[i],ddiam))\n diam2err = np.append(diam2err, ufloat(diam2[i],ddiam))\n\ntheta1 = (1/4)*arcsin(diam1err/(2*R))\ntheta2 = (1/4)*arcsin(diam2err/(2*R))\n\nhc = 1.24e-6 # ev*m\nx = (hc/np.sqrt(2*0.511*1e6*E*1e3))*1e12 # pm\ny1 = 2*sin(theta1)\ny2 = 2*sin(theta2)\n#%% split the nominal value and the error\ny1nom, y2nom, y1s, y2s = (np.array([]) for i in range(4))\nfor i in range(len(y1)):\n y1nom, y2nom = np.append(y1nom, y1[i].n), np.append(y2nom, y2[i].n)\n y1s, y2s = np.append(y1s, y1[i].s), np.append(y2s, y2[i].s)\n\n\n#%% Empleamos el package \"nestle\" para hacer las regresiones\nimport corner\nimport nestle\n\ndef nested_linear(x,y,yerr,b,title, npoints):\n \"\"\" Performs a linear regression with Nested Sampling and saves two plots\n 1. data+fit\n 2. corner plot\n Inputs: \n x,y = np.arrays: of data and uncertainties in \n yerr (np.array) = uncertainties on y\n b = np.array(b1,b2): boundaries of the parameters\n title = string: name for the plots' file .png\n Outputs:\n p: model parameter vector\n cov: covariance matrix (the diagonal elements are the errors of p)\n \"\"\"\n \n def model(theta, x):\n m, c = theta\n return m*x + c \n\n # The likelihood function:\n def loglike(theta):\n return -0.5*(np.sum((y-model(theta, x))**2/yerr**2))\n \n \n # Defines a flat prior in 0 < m < 1, 0 < c < 100:\n def prior_transform(theta):\n return np.array(b) * theta\n \n \n # Run nested sampling\n res = nestle.sample(loglike, prior_transform, 2, method='single',\n npoints= npoints)\n print(res.summary())\n \n # weighted average and covariance:\n p, cov = nestle.mean_and_cov(res.samples, res.weights)\n \n def rcoef(x,y,a,b): #x,y np.array ---- a,b model parameters\n ymod = a*x +b\n sse, ss = [], []\n for i in range(len(y)):\n sse.append((y[i] - ymod[i])**2)\n ss.append((y[i] - np.mean(y))**2)\n R2 = 1 - (sum(sse)/sum(ss))\n return R2\n r2 = rcoef(x,y,p[0],p[1])\n print(\"m = {0:5.5f} +/- {1:5.5f}\".format(p[0], np.sqrt(cov[0, 0])))\n print(\"b = {0:5.5f} +/- {1:5.5f}\".format(p[1], np.sqrt(cov[1, 1])))\n \n fig, ax = plt.subplots(1,1, figsize=(9,7))\n ax.errorbar(x, y, yerr=yerr, capsize=0, fmt='k.', ecolor='.7',label='Dades')\n ax.plot(x, model(p, x), c='k',label='Ajust lineal')\n ax.set_title(title,fontsize=18)\n ax.set_xlabel('$hc/\\sqrt{2m_e c^2 E(eV)}$',fontsize=18)\n ax.set_ylabel(r'$2 \\sin{\\theta}$',fontsize=18)\n ax.legend(fontsize=18)\n m = ufloat(p[0], np.sqrt(cov[0, 0]))\n b = ufloat(p[1], np.sqrt(cov[1, 1]))\n ax.text(x=0.045,y=0.75, s='a = {:3.4f} pm'.format(m), fontsize = 18, transform=ax.transAxes)\n ax.text(x=0.045,y=0.70, s='b = {:3.4f}'.format(b), fontsize = 18, transform=ax.transAxes)\n ax.text(x=0.040,y=0.65, s='$R^2$ = {:2.4f}'.format(r2), fontsize = 18, transform=ax.transAxes)\n ax.tick_params(axis='both', labelsize=20)\n plt.savefig(title+'_fit.png',dpi=300, bbox_inches='tight')\n plt.show()\n# figure = corner.corner(res.samples, weights=res.weights, labels=['a', 'b'],\n# range=[0.99999, 0.99999],show_titles=True,\n# quantiles=(0.16, 0.84), \n# levels=(1-np.exp(-0.5),),verbose=True,color='blue', \n# bins=50, smooth=2,truths=p,\n# truth_color='green')\n# plt.savefig(title+'_corner.png',dpi=300)\n# plt.show() \n return p, cov\n\n\n\n#%% Call the function to obtain the output\n \np1, cov1 = nested_linear(x,y1nom,y1s,np.array([10,-10]),'Anell gran (d$_1$)', npoints)\np2, cov2 = nested_linear(x,y2nom, y2s, np.array([10,-10]),'Anell petit (d$_2$)', npoints)\n#%%\nf = open('nestle_fit.txt', 'w')\nf.write('# \\t Nestle fit y = mx+b \\n')\nf.write('# m +/- dm \\t\\t b +/- db \\n')\nf.write('{0:5.5f}+/-{1:5.5f} \\t {2:5.5f}+/-{3:5.5f} \\n'.format(p1[0],np.sqrt(cov1[0][0]),p1[1],np.sqrt(cov1[1][1])))\nf.write('{0:5.5f}+/-{1:5.5f} \\t {2:5.5f}+/-{3:5.5f}'.format(p2[0],np.sqrt(cov2[0][0]),p2[1],np.sqrt(cov2[1][1])))\n\n#%% Calcula las magnitudes del problema con los parametros del ajuste\n# las pendientes de las rectas son 1/d1, 1/d2\nd1 = 1/ufloat(p1[0],np.sqrt(cov1[0,0])) # UNIDADES: pm = 1e-12 m\nd2 = 1/ufloat(p2[0],np.sqrt(cov2[0,0]))\n\na = 2*d1/np.sqrt(3) # a is the atomic separation of atoms, aresta del hexagono\nprint('a=', a)\na_real = 142 #pm, hace falta referenciar el valor \nprint('d1 = ', d1)\nprint('d2 = ', d2)\nprint('a/a_real= {:2.3f}'.format(a/a_real)) # debería ser 1...\n\n\n#%%\ndef nestle_linear2(x, y, yerr, b, title, npoints):\n def model(theta, x):\n m, c = theta\n return m*x + c \n \n # The likelihood function:\n def loglike(theta):\n return -0.5*(np.sum((y-model(theta, x))**2/yerr**2))\n \n \n # Defines a flat prior in 0 < m < 1, 0 < c < 100:\n def prior_transform(theta):\n return np.array(b) * theta\n \n \n # Run nested sampling\n res = nestle.sample(loglike, prior_transform, 2, method='single',\n npoints= npoints)\n print(res.summary())\n \n # weighted average and covariance:\n p, cov = nestle.mean_and_cov(res.samples, res.weights)\n\n def rcoef(x,y,a,b): #x,y np.array ---- a,b model parameters\n ymod = a*x +b\n sse, ss = [], []\n for i in range(len(y)):\n sse.append((y[i] - ymod[i])**2)\n ss.append((y[i] - np.mean(y))**2)\n R2 = 1 - (sum(sse)/sum(ss))\n return R2\n r2 = rcoef(x,y,p[0],p[1])\n print(\"m = {0:5.5f} +/- {1:5.5f}\".format(p[0], np.sqrt(cov[0, 0])))\n print(\"b = {0:5.5f} +/- {1:5.5f}\".format(p[1], np.sqrt(cov[1, 1])))\n # PLOT\n fig, ax = plt.subplots(1,1, figsize= (9,7))\n ax.errorbar(x, y, yerr=yerr, capsize=0, fmt='k.', ecolor='.7',label='Dades')\n ax.plot(x, model(p, x), c='k',label='y=mx+b')\n m = ufloat(p[0], np.sqrt(cov[0, 0]))\n b = ufloat(p[1], np.sqrt(cov[1, 1]))\n ax.text(x=0.045,y=0.75, s='a = {:3.1f}'.format(m), fontsize = 18, transform=ax.transAxes)\n ax.text(x=0.045,y=0.70, s='b = {:3.1f}'.format(b), fontsize = 18, transform=ax.transAxes)\n ax.text(x=0.040,y=0.65, s='$R^2$ = {:2.2f}'.format(r2), fontsize = 18, transform=ax.transAxes)\n \n ax.set_ylabel('$\\lambda$[pm] (Bragg)', fontsize = 18)\n ax.set_xlabel('$\\lambda$[pm] (DeBroglie)', fontsize = 18)\n ax.ticklabel_format(style='plain',axis='y', scilimits=(0,0))\n ax.legend(loc='upper left',fontsize=16)\n ax.set_title(title, fontsize=18)\n ax.tick_params(axis='both', labelsize=20)\n plt.savefig(title + 'lambda_nestle.png',dpi=300,bbox_inches='tight')\n plt.show()\n# figure = corner.corner(res.samples, weights=res.weights, labels=['a', 'b'],\n# range=[0.99999, 0.99999],show_titles=True,\n# quantiles=(0.16, 0.84), \n# levels=(1-np.exp(-0.5),),verbose=True,color='blue', \n# bins=50, smooth=2,truths=p,\n# truth_color='green')\n# plt.savefig(title + 'lambda_corner.png',dpi=300)\n# plt.show() \n return p, cov\n#%%\n# Plotea la longitud de onda de De Broglie vs de Bragg\n\n# E keV --> eV\ndeBroglie = 1e12*sp.h/np.sqrt(2*sp.m_e*sp.e*E*1e3) # en pm\nBragg1 = 2*d1*sin(theta1) # en pm\nBragg2 = 2*d2*sin(theta2) # en pm\n\n\n#split the nominal value and the error\nbraggnom1, braggs1, braggnom2, braggs2 = (np.array([]) for i in range(4))\nfor i in range(len(Bragg1)):\n braggnom1, braggs1 = np.append(braggnom1, Bragg1[i].n), np.append(braggs1, Bragg1[i].n)\n braggnom2, braggs2 = np.append(braggnom2, Bragg2[i].n), np.append(braggs2, Bragg2[i].n)\n \n \np1, cov1 = nestle_linear2(deBroglie, braggnom1, braggs1, np.array([10,-10]), 'Anell gran (d$_1$)', npoints )\np2, cov2 = nestle_linear2(deBroglie, braggnom2, braggs2, np.array([10,-10]), 'Anell petit (d$_2$)', npoints )","sub_path":"practica8/p8_nestle.py","file_name":"p8_nestle.py","file_ext":"py","file_size_in_byte":9008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"575412939","text":"#!/usr/bin/env python\n# coding:utf-8\n\ntry:\n import socketserver as SocketServer\nexcept:\n import SocketServer\n\nimport os\nimport json\nfrom modules import auth\nfrom conf import settings\n\n\n# 处理Ftp请求\nclass FtpServer(SocketServer.BaseRequestHandler):\n\n # serve_forever()启动时执行\n def handle(self):\n print(self.client_address, 'access.') # 输出接入客户端的ip和端口\n shutdown_flag = 0\n while shutdown_flag == 0: # 接收到退出信号前一直运行\n data = self.request.recv(1024)\n self.data_parser(data) # 从客户端接收到数据即解析\n\n # 解析客户端请求命令\n def data_parser(self, data):\n data = json.loads(data) # 客户端传来格式:{'username':'xxx', 'password':'xxx', 'action':'xxx'}\n if data.get('action'): # data字典中存在action键表示数据无误\n action_type = data.get('action') # 提取名为action_type的命令并执行,不存在该命令则报错\n res = getattr(self, action_type)(data) if hasattr(self, action_type) else 'Invalid client data.'\n else:\n print('Invalid client data.')\n\n # 用户认证,支持数据库和文件认证\n def user_auth(self, data):\n username, password = data.get('username'), data.get('password')\n auth_status, auth_msg = auth.authentication(username, password)\n if auth_status: # 通过文件或数据库检验用户登录\n response_data = {'status': '200', 'data': []}\n self.login_user = username # 记录客户端认证状态:传文件的时候这个变量存在表示已验证\n self.home_path = '{home}/{username}'.format(\n home=settings.USER_BASE_HOME_PATH,\n username=username\n )\n print('{} login.'.format(username))\n else:\n print('Authentication failed.', auth_msg)\n response_data = {'status': '201', 'data': []}\n response_data = json.dumps(response_data)\n self.request.send(response_data) # 向客户端返回认证结果(成功200,失败201)\n\n # 文件下载\n def cmd_get(self, data):\n print('----Client ask for downloading data')\n if hasattr(self, 'login_user'): # 用户已登录\n file_name = data.get('file_name')\n file_with_abs_path = '{}/{}'.format(self.home_path, file_name)\n print(file_with_abs_path)\n if os.path.isfile(file_with_abs_path): # 判断请求文件是否存在\n file_size = os.path.getsize(file_with_abs_path) # 获取文件总大小\n response_data = { # 告知客户端待接收文件总大小\n 'status': '300',\n 'data': [{\n 'file_name': file_name,\n 'size': file_size\n }]\n }\n self.request.send(json.dumps(response_data))\n client_response = json.loads(self.request.recv(1024))\n if client_response.get('status') == '301': # 客户端准备接收文件\n print('Start sending...')\n f = open(file_with_abs_path, 'rb')\n send_size = 0 # 已发送文件大小\n while file_size > send_size: # 文件总大小 > 已发送大小\n data = f.read(4096)\n self.request.send(data)\n send_size += len(data)\n else:\n print('\\n\\033[32;1m--- File download successfully ---\\033[0m')\n f.close()\n else:\n print('File does not exist.')\n else:\n print('User is not authorized.')\n\n def cmd_put(self, data):\n print('----Client ask for uploading data')\n if hasattr(self, 'login_user'): # 用户已登录\n file_name, file_size = data.get(\"file_name\"), data.get(\"file_size\")\n server_response = json.dumps({ # 服务端准备接收文件\n 'status': '301'\n })\n self.request.send(server_response)\n received_size = 0\n local_file_name = '{}/{}'.format(self.home_path, file_name) # 文件存放路径\n print(local_file_name)\n f = open(local_file_name, 'wb')\n while file_size > received_size:\n data = self.request.recv(4096)\n received_size += len(data)\n f.write(data)\n else:\n print('\\n\\033[32;1m--- File upload successfully ---\\033[0m')\n f.close()\n else:\n print('User is not authorized.')\n","sub_path":"FTP/Server/modules/socket_server.py","file_name":"socket_server.py","file_ext":"py","file_size_in_byte":5156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"133585630","text":"from datetime import datetime\n\nimport pytest\nfrom fastapi.testclient import TestClient\n\nfrom application import create_app\nfrom models import Market, Match, ProviderEvent, Selection, Sport\n\n\n@pytest.fixture\ndef test_client() -> TestClient:\n '''Fixture to creaete a FastAPI TestClient'''\n app = create_app()\n return TestClient(app)\n\n\n@pytest.fixture\ndef provider_event_new_event(valid_match) -> ProviderEvent:\n '''Fixture to create a ProviderEvent with type NewEvent'''\n return ProviderEvent(\n id=0,\n message_type='NewEvent',\n event=valid_match\n )\n\n\n@pytest.fixture\ndef provider_event_update_odds(valid_match) -> ProviderEvent:\n '''Fixture to create a ProviderEvent with type NewEvent'''\n return ProviderEvent(\n id=0,\n message_type='UpdateOdds',\n event=valid_match\n )\n\n\n@pytest.fixture\ndef valid_match(valid_sport, valid_market) -> Match:\n '''Fixture to create a valid Match'''\n return Match(\n id=0,\n url='/api/match/0',\n name='Test Match',\n startTime=datetime.utcnow(),\n sport=valid_sport,\n markets=[valid_market]\n )\n\n\n@pytest.fixture\ndef valid_sport() -> Sport:\n return Sport(\n id=0,\n name='Test Sport'\n )\n\n\n@pytest.fixture\ndef valid_market(valid_selection) -> Market:\n return Market(\n id=0,\n name='Winner',\n selections=[valid_selection]\n )\n\n\n@pytest.fixture\ndef valid_selection() -> Selection:\n return Selection(\n id=0,\n name='Test Team',\n odds=1.0\n )\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"268414500","text":"import random\nimport socket\nimport math\nimport traceback\nfrom threading import Thread\nfrom os import environ\n\nfrom parse_map import STARTING_POSES, MAP\n\nTCP_PORT = int(environ.get('PORT', '9000'))\nTCP_HOST = environ.get('HOST', '127.0.0.1')\nNMAP = [(1, 0), (0, 1), (-1, 0), (0, -1)]\nFLAG0 = b'#flag CTF{v3rY_F1r5T_ST3ps}\\n'\nFLAG1 = b'#flag CTF{K33p_601n6_fUr7h3r}\\n'\nFLAG2 = b'#flag CTF{1s_Th1S_th3_f1N4l_R00m?}\\n'\nMISFLAG = b'NOT THIS WAY!\\n'\nBUFFER_SIZE = 20\nMAX_CONNECTIONS = 1000\nTIMEOUT = 60\nSCAN_DENSITY = 16\nDELTA_STEP = 0.02\nCOLLISION_RANGE = 1\nDEBUG = False\n\n\nclass Destroyed(Exception):\n pass\n\n\ndef get_map_field(pos):\n return MAP[pos[1]][pos[0]]\n\n\ndef get_ray(pos, angle):\n pos = list(pos)\n\n delta = [math.cos(angle), math.sin(angle)]\n delta[0] *= DELTA_STEP\n delta[1] *= DELTA_STEP\n dist = 0\n\n while True:\n if get_map_field((math.floor(pos[0]), math.floor(pos[1]))).is_blocking():\n return dist\n else:\n pos[0] += delta[0]\n pos[1] += delta[1]\n dist += DELTA_STEP\n\n\nANGLE_DELTA = 2 * math.pi / SCAN_DENSITY\n\ndef get_all_rays(pos, direction):\n angle = {\n 0: 0,\n 1: math.pi / 2,\n 2: math.pi,\n 3: math.pi * 3 / 2,\n }[direction]\n\n# TODO: print flags\n\n rays = []\n\n for i in range(SCAN_DENSITY):\n rays.append(get_ray(pos, angle))\n angle += ANGLE_DELTA\n\n return rays\n\n\ndef move_pos(pos, direction, v):\n pos = list(pos)\n\n direction %= 4\n\n pos[0] += v * NMAP[direction][0]\n pos[1] += v * NMAP[direction][1]\n\n for y in range(-COLLISION_RANGE, COLLISION_RANGE+1):\n for x in range(-COLLISION_RANGE+abs(y), COLLISION_RANGE-abs(y)+1):\n if get_map_field((pos[0] + x, pos[1] + y)).is_blocking():\n raise Destroyed(\"Destroyed\")\n\n return pos\n\n\nclass ThreadedConnection(Thread):\n def __init__(self, client, address):\n Thread.__init__(self)\n self.client = client\n self.address = address\n self.started = False\n self.pos = list(random.choice(STARTING_POSES))\n self.direction = random.randrange(5)\n self.got_flag0 = False\n self.got_flag1 = False\n self.got_flag2 = False\n self.got_misflag1 = False\n self.got_misflag2 = False\n self.destroyed = False\n\n def run(self):\n if DEBUG:\n print(f\"New connection from address {self.address}.\")\n\n while True:\n try:\n if self.destroyed:\n try:\n self.client.recv(BUFFER_SIZE)\n self.client.close()\n except:\n pass\n return\n else:\n data = self.client.recv(1)\n if DEBUG:\n print(\"data received:\", data)\n if data:\n for c in data:\n self.handle(chr(c))\n else:\n self.client.close()\n raise Exception(\"Connection closed\")\n except:\n try:\n self.client.close()\n except:\n pass\n\n if DEBUG:\n print(\"Error, closing connection.\")\n traceback.print_exc()\n\n return\n\n def handle(self, c):\n if self.destroyed:\n return\n\n print(\"handle:\", c)\n {\n 'S': self.init_drone,\n 'L': self.left,\n 'R': self.right,\n 'F': self.forward,\n 'B': self.backward,\n '\\r': lambda: None,\n '\\n': lambda: None,\n ' ': lambda: None,\n '\\t': lambda: None,\n }.get(c, self.unrecognized)()\n\n def init_drone(self):\n if self.started:\n self.unrecognized()\n return\n\n if DEBUG:\n print(\"starting_pos:\", f\"({self.pos[0]}, {self.pos[1]})\")\n\n self.started = True\n self.print_pos()\n\n def left(self):\n self.rotate(-1)\n\n def right(self):\n self.rotate(1)\n\n def forward(self):\n self.move(1)\n\n def backward(self):\n self.move(-1)\n\n def unrecognized(self):\n self.client.sendall(b\"Unrecognized command!\\n\")\n\n try:\n self.client.shutdown();\n self.client.close()\n except:\n pass\n\n if DEBUG:\n print(\"Connection closed.\")\n\n def rotate(self, d):\n if not self.started:\n self.unrecognized()\n return\n\n self.direction += d\n self.direction %= 4\n self.print_pos()\n\n\n def move(self, v):\n if not self.started:\n self.unrecognized()\n return\n\n try:\n self.pos = move_pos(self.pos, self.direction, v)\n self.print_pos()\n except Destroyed:\n self.destroyed = True\n print(\"Destroyed.\")\n\n def print_pos(self):\n response = \"\"\n # response += f\"{self.pos[0]} {self.pos[1]}\\n\"\n\n field = get_map_field(self.pos)\n if not self.got_flag0 and field.is_flag0():\n self.got_flag0 = True\n self.print_flag0()\n if not self.got_flag1 and field.is_flag1():\n self.got_flag1 = True\n self.print_flag1()\n if not self.got_flag2 and field.is_flag2():\n self.got_flag2 = True\n self.print_flag2()\n if not self.got_misflag1 and field.is_misflag1():\n self.got_misflag1 = True\n self.print_misflag()\n if not self.got_misflag2 and field.is_misflag2():\n self.got_misflag2 = True\n self.print_misflag()\n\n if DEBUG:\n print(field)\n\n collisions = get_all_rays(self.pos, self.direction)\n for dist in collisions:\n response += f\"{dist}\\n\"\n\n self.client.sendall(response.encode())\n\n def print_flag0(self):\n self.client.sendall(FLAG0)\n\n def print_flag1(self):\n self.client.sendall(FLAG1)\n\n def print_flag2(self):\n self.client.sendall(FLAG2)\n\n def print_misflag(self):\n self.client.sendall(MISFLAG)\n\n\n\nclass ThreadedServer(object):\n def __init__(self, host, port):\n self.host = host\n self.port = port\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.sock.bind((self.host, self.port))\n\n def listen(self):\n self.sock.listen(MAX_CONNECTIONS)\n print(f\"Listening... host: {self.host}, port: {self.port}\")\n while True:\n client, address = self.sock.accept()\n client.settimeout(TIMEOUT)\n conn = ThreadedConnection(client, address)\n conn.start()\n\n\n\nThreadedServer(TCP_HOST, TCP_PORT).listen()\n","sub_path":"drone2/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"352525201","text":"import random\nfrom prettytable import PrettyTable\nfrom scipy.stats import f, t\nfrom functools import partial\n\nx1min = -6\nx1max = 10\nx2min = -10\nx2max = 5\nx3min = -9\nx3max = 3\n\nx_aver_min = (x1min + x2min + x3min) / 3\nx_aver_max = (x1max + x2max + x3max) / 3\n\nx1_aver = (x1max + x1min) / 2\nx2_aver = (x2max + x2min) / 2\nx3_aver = (x3max + x3min) / 2\n\nx1del = x1max - x1_aver\nx2del = x2max - x2_aver\nx3del = x3max - x3_aver\n\ny_min = 200 + int(x_aver_min)\ny_max = 200 + int(x_aver_max)\n\naver = []\naver_arr = []\ndef main (m=3):\n print(\"Рівняння регресії\")\n print(\"y=b0+b1*x1+b2*x2+b3*x3+b12*x1*x2+b13*x1*x3+b23*x2*x3+b123*x1*x2*x3+b11*x1^2+b22*x2^2+b33*x3^2\")\n\n Y_ALL = [[random.randint(y_min, y_max) for _ in range(15)] for _ in range(m)]\n\n x0_norm = [1] * 15\n x1_norm = [-1, -1, -1, -1, 1, 1, 1, 1, -1.215, 1.215, 0, 0, 0, 0, 0]\n x2_norm = [-1, -1, 1, 1, -1, -1, 1, 1, 0, 0, -1.215, 1.215, 0, 0, 0]\n x3_norm = [-1, 1, -1, 1, -1, 1, -1, 1, 0, 0, 0, 0, -1.215, 1.215, 0]\n x12_norm = [x * y for x, y in zip(x1_norm, x2_norm)]\n x13_norm = [x * y for x, y in zip(x1_norm, x3_norm)]\n x23_norm = [x * y for x, y in zip(x2_norm, x3_norm)]\n x123_norm = [x * y * z for x, y, z in zip(x1_norm, x2_norm, x3_norm)]\n x11_norm = [x * x for x in x1_norm]\n x22_norm = [x * x for x in x2_norm]\n x33_norm = [x * x for x in x3_norm]\n\n def x_filler (arr, xmin, xmax, xdel, x_aver):\n l = []\n for i in arr:\n if i == -1:\n l.append(xmin)\n elif abs(i) == 1.215:\n l.append(i * xdel + x_aver)\n else:\n l.append(xmax)\n return l\n\n x1 = x_filler(x1_norm, x1min, x1max, x1del, x1_aver)\n x2 = x_filler(x2_norm, x2min, x2max, x2del, x2_aver)\n x3 = x_filler(x3_norm, x3min, x3max, x3del, x3_aver)\n x12 = [x * y for x, y in zip(x1, x2)]\n x13 = [x * y for x, y in zip(x1, x3)]\n x23 = [x * y for x, y in zip(x2, x3)]\n x123 = [x * y * z for x, y, z in zip(x1, x2, x3)]\n x11 = [x * x for x in x1]\n x22 = [x * x for x in x2]\n x33 = [x * x for x in x3]\n\n def table (names, values):\n pretty = PrettyTable()\n for i in range(len(names)):\n pretty.add_column(names[i], values[i])\n print(pretty, \"\\n\")\n\n names = [\"X0\", \"X1\", \"X2\", \"X3\", \"X1X2\", \"X1X3\", \"X2X3\", \"X1X2X3\", \"X1^2\", \"X2^2\", \"X3^2\"]\n values = [x0_norm, x1_norm, x2_norm, x3_norm, x12_norm, x13_norm, x23_norm, x123_norm, x11_norm, x22_norm, x33_norm]\n table(names, values)\n\n print(f\"Матриця для m={m}\")\n\n def re_zip (allYValues):\n l = [[0 for _ in range(len(allYValues))] for _ in range(len(allYValues[0]))]\n for i in range(len(allYValues)):\n for j in range(len(allYValues[i])):\n l[j][i] = allYValues[i][j]\n return l\n\n Y_ALL = [[random.randint(y_min, y_max) for _ in range(15)] for _ in range(m)]\n Y_ROWS = re_zip(Y_ALL)\n Y_ROWS_AV = [sum(x) / len(x) for x in Y_ROWS]\n\n for i in range(len(Y_ALL)):\n names.append(f\"Y{i+1}\")\n values.append(Y_ALL[i])\n names.append(\"Y_AVERAGE\")\n values.append(Y_ROWS_AV)\n\n table(names, values)\n #################################################################################\n disp = [0] * 15\n\n for i in range(15):\n disp[i] = sum([(Y_ROWS_AV[i] - Y_ROWS[i][j]) ** 2 for j in range(m)]) / m\n\n Gp = max(disp) / sum(disp)\n\n f1 = m - 1\n f2 = N = 15\n\n def cohren_teoretical (f1, f2, q=0.05):\n q1 = q / f1\n fisher_value = f.ppf(q=1 - q1, dfn=f2, dfd=(f1 - 1) * f2)\n return fisher_value / (fisher_value + f1 - 1)\n\n Gt = cohren_teoretical(f1, f2)\n print(\"Дисперсія по рядкам\")\n for i, j in enumerate(disp):\n print(f\"{i+1}. {j:.2f}\")\n if Gp < Gt:\n print(\"Дисперсія однорідна\")\n else:\n print(\"Дисперсія неоднорідна\")\n\n print(\"Критерій Стьюдента\")\n sb = sum(disp) / N\n ssbs = sb / (m * N)\n sbs = ssbs ** 0.5\n\n bethas = [0] * 11\n x_norm = [x0_norm, x1_norm, x2_norm, x3_norm, x12_norm, x13_norm, x23_norm, x123_norm, x11_norm, x22_norm, x33_norm]\n for i in range(11):\n for j in range(len(x1_norm)):\n bethas[i] += Y_ROWS_AV[j]*x_norm[i][j]\n bethas[i] /= 15\n\n tethas = [abs(bethas[i]) / sbs for i in range(len(bethas))]\n\n f3 = f1 * f2\n student_teoretical = partial(t.ppf, q=1 - 0.025)\n T = student_teoretical(df=f3)\n d = 0\n\n\n for i in range(len(tethas)):\n if tethas[i] < T:\n bethas[i] = 0\n print(f\"Приймаємо betha{i} незначимим\")\n else:\n aver.append(bethas[i])\n print(f\"Betha{i} = {bethas[i]}\")\n d += 1\n aver_arr.append(sum(aver) / len(aver))\n\n yy1 = bethas[0] + bethas[1] * x1min + bethas[2] * x2min + bethas[3] * x3min + bethas[4] * x1min * x2min + bethas[\n 5] * x1min * x3min + bethas[\n 6] * x2min * x3min + bethas[7] * x1min * x2min * x3min + bethas[8] * x1min * x1min + bethas[\n 9] * x2min * x2min + bethas[\n 10] * x3min * x3min\n yy2 = bethas[0] + bethas[1] * x1min + bethas[2] * x2min + bethas[3] * x3max + bethas[4] * x1min * x2min + bethas[\n 5] * x1min * x3max + bethas[\n 6] * x2min * x3max + bethas[7] * x1min * x2min * x3max + bethas[8] * x1min * x1min + bethas[\n 9] * x2min * x2min + bethas[\n 10] * x3max * x3max\n yy3 = bethas[0] + bethas[1] * x1min + bethas[2] * x2max + bethas[3] * x3min + bethas[4] * x1min * x2max + bethas[\n 5] * x1min * x3min + bethas[\n 6] * x2max * x3min + bethas[7] * x1min * x2max * x3min + bethas[8] * x1min * x1min + bethas[\n 9] * x2max * x2max + bethas[\n 10] * x3min * x3min\n yy4 = bethas[0] + bethas[1] * x1min + bethas[2] * x2max + bethas[3] * x3max + bethas[4] * x1min * x2max + bethas[\n 5] * x1min * x3max + bethas[\n 6] * x2max * x3max + bethas[7] * x1min * x2max * x3max + bethas[8] * x1min * x1min + bethas[\n 9] * x2max * x2max + bethas[\n 10] * x3max * x3max\n yy5 = bethas[0] + bethas[1] * x1max + bethas[2] * x2min + bethas[3] * x3min + bethas[4] * x1max * x2min + bethas[\n 5] * x1max * x3min + bethas[\n 6] * x2min * x3min + bethas[7] * x1max * x2min * x3min + bethas[8] * x1max * x1max + bethas[\n 9] * x2min * x2min + bethas[\n 10] * x3min * x3min\n yy6 = bethas[0] + bethas[1] * x1max + bethas[2] * x2min + bethas[3] * x3max + bethas[4] * x1max * x2min + bethas[\n 5] * x1max * x3max + bethas[\n 6] * x2min * x3max + bethas[7] * x1max * x2min * x3max + bethas[8] * x1max * x1max + bethas[\n 9] * x2min * x2min + bethas[\n 10] * x3min * x3max\n yy7 = bethas[0] + bethas[1] * x1max + bethas[2] * x2max + bethas[3] * x3min + bethas[4] * x1max * x2max + bethas[\n 5] * x1max * x3min + bethas[\n 6] * x2max * x3min + bethas[7] * x1max * x2min * x3max + bethas[8] * x1max * x1max + bethas[\n 9] * x2max * x2max + bethas[\n 10] * x3min * x3min\n yy8 = bethas[0] + bethas[1] * x1max + bethas[2] * x2max + bethas[3] * x3max + bethas[4] * x1max * x2max + bethas[\n 5] * x1max * x3max + bethas[\n 6] * x2max * x3max + bethas[7] * x1max * x2max * x3max + bethas[8] * x1max * x1max + bethas[\n 9] * x2max * x2max + bethas[\n 10] * x3min * x3max\n yy9 = bethas[0] + bethas[1] * x1[8] + bethas[2] * x2[8] + bethas[3] * x3[8] + bethas[4] * x12[8] + bethas[5] * x13[\n 8] + bethas[6] * x23[8] + bethas[7] * \\\n x123[8] + bethas[8] * x11[8] + bethas[9] * x22[8] + bethas[10] * x33[8]\n yy10 = bethas[0] + bethas[1] * x1[9] + bethas[2] * x2[9] + bethas[3] * x3[9] + bethas[4] * x12[9] + bethas[5] * x13[\n 9] + bethas[6] * x23[9] + bethas[7] * \\\n x123[9] + bethas[8] * x11[9] + bethas[9] * x22[9] + bethas[10] * x33[9]\n yy11 = bethas[0] + bethas[1] * x1[10] + bethas[2] * x2[10] + bethas[3] * x3[10] + bethas[4] * x12[10] + bethas[5] * \\\n x13[10] + bethas[6] * x23[10] + bethas[\n 7] * x123[10] + bethas[8] * x11[10] + bethas[9] * x22[10] + bethas[10] * x33[10]\n yy12 = bethas[0] + bethas[1] * x1[11] + bethas[2] * x2[11] + bethas[3] * x3[11] + bethas[4] * x12[11] + bethas[5] * \\\n x13[11] + bethas[6] * x23[11] + bethas[\n 7] * x123[11] + bethas[8] * x11[11] + bethas[9] * x22[11] + bethas[10] * x33[11]\n yy13 = bethas[0] + bethas[1] * x1[12] + bethas[2] * x2[12] + bethas[3] * x3[12] + bethas[4] * x12[12] + bethas[5] * \\\n x13[12] + bethas[6] * x23[12] + bethas[\n 7] * x123[12] + bethas[8] * x11[12] + bethas[9] * x22[12] + bethas[10] * x33[12]\n yy14 = bethas[0] + bethas[1] * x1[13] + bethas[2] * x2[13] + bethas[3] * x3[13] + bethas[4] * x12[13] + bethas[5] * \\\n x13[13] + bethas[6] * x23[13] + bethas[\n 7] * x123[13] + bethas[8] * x11[13] + bethas[9] * x22[13] + bethas[10] * x33[13]\n yy15 = bethas[0] + bethas[1] * x1[14] + bethas[2] * x2[14] + bethas[3] * x3[14] + bethas[4] * x12[14] + bethas[5] * \\\n x13[14] + bethas[6] * x23[14] + bethas[\n 7] * x123[14] + bethas[8] * x11[14] + bethas[9] * x22[14] + bethas[10] * x33[14]\n\n print(\"Критерій Фішера\")\n f4 = N - d\n yy = [yy1, yy2, yy3, yy4, yy5, yy6, yy7, yy8, yy9, yy10, yy11, yy12, yy13, yy14, yy15]\n sad = sum([(yy[i] - Y_ROWS_AV[i]) ** 2 for i in range(len(yy))]) * m / (N - d)\n Fp = sad / sb\n fisher_teoretical = partial(f.ppf, q=1 - 0.05)\n Ft = fisher_teoretical(dfn=f4, dfd=f3)\n if Ft > Fp:\n print(\"Рівняння регресії адекватне оригіналу\")\n else:\n print(\"Рівняння регресії не є адекватне оригіналу\")\n m+=1\n if (m <= 100):\n main(m)\n\n\n\n\n\nif __name__ == '__main__':\n main()\n print(\"Середнє значення значимих коефіцієнтів = \", sum(aver_arr) / 100)\n","sub_path":"lab5.py","file_name":"lab5.py","file_ext":"py","file_size_in_byte":10142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"226253322","text":"import vkapi\nimport os\nfrom commands import *\nfrom commandSystem import command_list\n\ndef get_answer(key):\n message = \"Прости, не понимаю тебя. Напиши 'помощь', чтобы узнать мои команды\"\n attachment = ''\n for c in command_list:\n if key in c.keys:\n message, attachment = c.process()\n return message, attachment\n\ndef create_answer(data, token):\n user_id = data['user_id']\n message = get_answer(data['body'].lower())\n vkapi.send_message(user_id, token, message)\n\n","sub_path":"messageHandler.py","file_name":"messageHandler.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"580909679","text":"# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport shutil\nimport tempfile\nimport unittest\nfrom dataclasses import dataclass\n\nfrom data.an4 import download_an4\nfrom deepspeech_pytorch.configs.inference_config import EvalConfig, ModelConfig, TranscribeConfig, LMConfig\nfrom deepspeech_pytorch.configs.train_config import DeepSpeechConfig, AdamConfig, BiDirectionalConfig, \\\n FileCheckpointConfig, \\\n DataConfig, TrainingConfig\nfrom deepspeech_pytorch.enums import DecoderType\nfrom deepspeech_pytorch.inference import transcribe\nfrom deepspeech_pytorch.testing import evaluate\nfrom deepspeech_pytorch.training import train\n\n\n@dataclass\nclass DatasetConfig:\n target_dir: str = ''\n manifest_dir: str = ''\n min_duration: float = 0\n max_duration: float = 15\n val_fraction: float = 0.1\n sample_rate: int = 16000\n\n\nclass DeepSpeechSmokeTest(unittest.TestCase):\n def setUp(self):\n self.target_dir = tempfile.mkdtemp()\n self.manifest_dir = tempfile.mkdtemp()\n self.model_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n shutil.rmtree(self.target_dir)\n shutil.rmtree(self.manifest_dir)\n shutil.rmtree(self.model_dir)\n\n def build_train_evaluate_model(self,\n epoch: int,\n batch_size: int,\n model_config: BiDirectionalConfig,\n use_half: bool,\n cuda: bool):\n train_manifest, val_manifest, test_manifest = self.download_data(DatasetConfig(target_dir=self.target_dir,\n manifest_dir=self.manifest_dir))\n\n train_cfg = self.create_training_config(epoch=epoch,\n batch_size=batch_size,\n train_manifest=train_manifest,\n val_manifest=val_manifest,\n model_config=model_config,\n cuda=cuda)\n print(\"Running Training DeepSpeech Model Smoke Test\")\n train(train_cfg)\n\n # Expected final model path after training\n model_path = self.model_dir + '/deepspeech_final.pth'\n assert os.path.exists(model_path)\n\n lm_configs = [\n LMConfig(), # Test Greedy\n LMConfig(\n decoder_type=DecoderType.beam\n ) # Test Beam Decoder\n ]\n print(\"Running Inference Smoke Tests\")\n for lm_config in lm_configs:\n self.eval_model(\n model_path=model_path,\n test_manifest=test_manifest,\n cuda=cuda,\n use_half=use_half,\n lm_config=lm_config\n )\n\n self.inference(test_manifest=test_manifest,\n model_path=model_path,\n cuda=cuda,\n use_half=use_half,\n lm_config=lm_config)\n\n def eval_model(self,\n model_path: str,\n test_manifest: str,\n cuda: bool,\n use_half: bool,\n lm_config: LMConfig):\n # Due to using TravisCI with no GPU support we have to disable cuda\n eval_cfg = EvalConfig(\n model=ModelConfig(\n cuda=cuda,\n model_path=model_path,\n use_half=use_half\n ),\n lm=lm_config,\n test_manifest=test_manifest\n )\n evaluate(eval_cfg)\n\n def inference(self,\n test_manifest: str,\n model_path: str,\n cuda: bool,\n use_half: bool,\n lm_config: LMConfig):\n # Select one file from our test manifest to run inference\n with open(test_manifest) as f:\n file_path = next(f).strip().split(',')[0]\n\n transcribe_cfg = TranscribeConfig(\n model=ModelConfig(\n cuda=cuda,\n model_path=model_path,\n use_half=use_half\n ),\n lm=lm_config,\n audio_path=file_path\n )\n transcribe(transcribe_cfg)\n\n def download_data(self, cfg: DatasetConfig):\n download_an4(target_dir=cfg.target_dir,\n manifest_dir=cfg.manifest_dir,\n min_duration=cfg.min_duration,\n max_duration=cfg.max_duration,\n val_fraction=cfg.val_fraction,\n sample_rate=cfg.sample_rate)\n # Expected manifests paths\n train_manifest = os.path.join(self.manifest_dir, 'an4_train_manifest.csv')\n val_manifest = os.path.join(self.manifest_dir, 'an4_val_manifest.csv')\n test_manifest = os.path.join(self.manifest_dir, 'an4_test_manifest.csv')\n\n # Assert manifest paths exists\n assert os.path.exists(train_manifest)\n assert os.path.exists(val_manifest)\n assert os.path.exists(test_manifest)\n return train_manifest, val_manifest, test_manifest\n\n def create_training_config(self,\n epoch: int,\n batch_size: int,\n train_manifest: str,\n val_manifest: str,\n model_config: BiDirectionalConfig,\n cuda: bool):\n return DeepSpeechConfig(\n training=TrainingConfig(epochs=epoch,\n no_cuda=not cuda),\n data=DataConfig(train_manifest=train_manifest,\n val_manifest=val_manifest,\n batch_size=batch_size),\n optim=AdamConfig(),\n model=model_config,\n checkpointing=FileCheckpointConfig(save_folder=self.model_dir)\n )\n\n\nclass AN4SmokeTest(DeepSpeechSmokeTest):\n\n def test_train_eval_inference(self):\n # Hardcoded sizes to reduce memory/time, and disabled GPU due to using TravisCI\n model_cfg = BiDirectionalConfig(hidden_size=10,\n hidden_layers=1)\n self.build_train_evaluate_model(epoch=1,\n batch_size=10,\n model_config=model_cfg,\n cuda=False,\n use_half=False)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"PyTorch/contrib/audio/deepspeech/tests/smoke_test.py","file_name":"smoke_test.py","file_ext":"py","file_size_in_byte":7160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"80182464","text":"import logging\nfrom common import errfunctions\n\nfrom datetime import date\n\nfrom PyQt5 import QtWidgets, QtGui, QtCore\nfrom PyQt5.QtGui import QTextCursor, QTextLength\nfrom PyQt5.QtWidgets import QVBoxLayout\n\nfrom common.functions import desktopSizer, dateToSlash\nfrom incomequeries.textdocumenthelper import blockFormatCenter, blockFormatLeft, blockFormatLeftIndent, blockFormatRight, blockFormatPageBreak, charHeaderFormat, charLineFormat, \\\n insertCell, insertCells, charFooterFormat, charTotalFormat, defaultTextTableFormat\nfrom widgets.widgets import JTextEdit\n\n\nclass IncomeDetailedPage(QtWidgets.QWidget):\n def __init__(self, incomeData, parent=None):\n super().__init__(parent)\n\n incomeRows = incomeData.incomeRows\n\n errfunctions.uiLogger.info(\"Generating {}\".format(incomeData.blurb()))\n\n layout = QVBoxLayout(self)\n\n formatCenter = blockFormatCenter()\n formatLeft = blockFormatLeft()\n formatLeftIndent = blockFormatLeftIndent()\n formatRight = blockFormatRight()\n formatBreak = blockFormatPageBreak()\n\n # Title/description\n text = JTextEdit(self)\n cursor = QTextCursor(text.document())\n self.cursor = cursor\n cursor.setBlockFormat(formatLeftIndent)\n\n text.setFontWeight(50)\n text.setAlignment(QtCore.Qt.AlignLeft)\n text.setFontPointSize(20)\n text.append(\"Income Summary\")\n text.setFontPointSize(12)\n\n text.append(\"\\n\")\n\n cursor.setBlockFormat(formatRight)\n cursor.insertText(\"Date: {}\\n\\n\".format(dateToSlash(date.today())))\n cursor.movePosition(QtGui.QTextCursor.Down)\n\n cursor.setBlockFormat(formatLeftIndent)\n\n cursor.insertText(incomeData.blurb())\n cursor.insertText(\"\\n\\n\\n\")\n\n # Table\n tableWidth = 10\n tab1Format = defaultTextTableFormat()\n tab1Format.setAlignment(QtCore.Qt.AlignLeft)\n tab1Format.setLeftMargin(50)\n highRes = desktopSizer(0, 0)[0] > 1900\n addressWidth = 800 if highRes else 400\n payerWidth = 350 if highRes else 200\n widths = [QTextLength(QTextLength.FixedLength, width) for width in\n [90, 140, 120, payerWidth, 90, 50, 80, 90, 90, addressWidth]]\n tab1Format.setColumnWidthConstraints(widths)\n\n headerFormat = charHeaderFormat()\n lineFormat = charLineFormat()\n footerFormat = charFooterFormat()\n totalFormat = charTotalFormat()\n\n cursor.insertTable(1, tableWidth, tab1Format)\n\n insertCells(cursor, formatLeft, headerFormat, [\"Pay Date\", \"Charge Type\"])\n insertCell(cursor, formatRight, headerFormat, \"Allocation\")\n insertCells(cursor, formatLeft, headerFormat, [\"Payer\", \"RentCode\", \"Bank\", \"Payment\", \"Income ID\"])\n insertCell(cursor, formatRight, headerFormat, \"Rent\")\n insertCell(cursor, formatLeft, headerFormat, \"Property Address\")\n\n cursor.movePosition(QtGui.QTextCursor.Down)\n cursor.insertHtml(\"
    \")\n cursor.movePosition(QtGui.QTextCursor.Down)\n\n cursor.insertTable(incomeData.numRows(), tableWidth, tab1Format) #tab2\n cursor.setBlockFormat(formatCenter)\n\n for i, incomeRow in enumerate(incomeRows):\n # Pay date\n insertCell(cursor, formatLeft, lineFormat, \"{:%d/%m/%Y}\".format(incomeRow[0]))\n # Charge type\n insertCell(cursor, formatLeft, lineFormat, incomeRow[1])\n # Allocation (right aligned currency)\n insertCell(cursor, formatRight, lineFormat, \"£{:,} \".format(incomeRow[2]))\n # The rest\n insertCells(cursor, formatLeft, lineFormat, incomeRow[3:8])\n # Annual rent\n insertCell(cursor, formatRight, lineFormat, \"£{:,} \".format(incomeRow[8]))\n # Address\n insertCell(cursor, formatLeft, lineFormat, incomeRow[9])\n\n cursor.movePosition(QtGui.QTextCursor.Down)\n text.append('\\n')\n\n # Extra cell to ensure the totals line up\n cursor.insertTable(1, tableWidth + 1, tab1Format)\n\n insertCell(cursor, formatLeft, footerFormat, \"Total:\")\n cursor.movePosition(QtGui.QTextCursor.NextCell)\n insertCell(cursor, formatRight, totalFormat, \"£{:,}\".format(incomeData.totalIncome()))\n\n text.moveCursor(QTextCursor.Start)\n\n layout.addWidget(text)\n","sub_path":"incomequeries/incomedetailedpage.py","file_name":"incomedetailedpage.py","file_ext":"py","file_size_in_byte":4358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"445275083","text":"# -*- coding: utf-8 -*-\n\"\"\"\n @Time: 2018/3/19 17:49\n @Author: sunxiang\n\"\"\"\nimport os\nfrom gensim.models import Word2Vec\nsentences = [[\"cat\", \"say\", \"meow\"], [\"dog\", \"say\", \"woof\"]]\n\nmodel = Word2Vec(sentences, min_count=1)\nsay_vector = model['say']\nprint(say_vector)\n\n\nclass MySentences(object):\n def __init__(self, dirname):\n self.dirname = dirname\n\n def __iter__(self):\n for fname in os.listdir(self.dirname):\n for line in open(os.path.join(self.dirname, fname)):\n yield line.split()\n\n\nsentences = MySentences('/some/directory') # a memory-friendly iterator\nmodel = gensim.models.Word2Vec(sentences)","sub_path":"gensim_test/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"497381731","text":"from django.shortcuts import render\nfrom .forms import ContactForm\nfrom .models import Contact\nfrom django.core.mail import EmailMessage\nfrom django.conf import settings\n\n\ndef contact(request):\n form = ContactForm\n\n if request.method == \"POST\":\n form = ContactForm(request.POST)\n if form.is_valid():\n form.save()\n name = form.cleaned_data.get(\"name\")\n email_address = form.cleaned_data.get('email')\n phone = form.cleaned_data.get(\"phone\")\n msg = form.cleaned_data.get('message')\n body = f'Name: {name}\\nEmail: {email_address}\\nPhone: {phone}\\n\\nMessage: {msg}'\n\n email = EmailMessage(\n 'Comfur Beds - Contact Us',\n body,\n settings.EMAIL_HOST_USER,\n ['bilaluddin474@gmail.com'],\n )\n\n email.fail_silently = False\n email.send()\n\n context = {\n \"form\": form\n }\n return render(request, \"contact/contact.html\", context)\n","sub_path":"contact/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"389528303","text":"#-*- coding: UTF-8 -*-\nfrom five import grok\nimport json\nfrom zope.interface import Interface\nfrom plone.memoize.instance import memoize\n\nfrom emc.kb.contents.questionfolder import Iquestionfolder\nfrom emc.kb.contents.topicfolder import Itopicfolder\nfrom emc.kb.contents.question import Iquestion\nfrom emc.kb.contents.topic import Itopic\nfrom emc.kb.contents.answer import Ianswer\n\nfrom zope.interface import Interface\nfrom z3c.relationfield import RelationCatalog\nfrom zc.relation.interfaces import ICatalog\nfrom zope import component\nfrom Products.CMFCore.utils import getToolByName\nfrom zope.component import getUtility\nfrom zope.intid import IntIds\nfrom zope.intid.interfaces import IIntIds\nfrom zope.component import getMultiAdapter\n\nfrom plone.app.layout.navigation.interfaces import INavigationRoot\nfrom AccessControl.SecurityManagement import getSecurityManager\nfrom plone.app.layout.globals.context import ContextState\nfrom emc.kb.interfaces import IFollowing\nfrom emc.kb import _\n\nclass Iquestionfollowed(Interface):\n \"\"\"\n questionfollowed view interface\n\n \"\"\"\n def fetchquestionsIfollowed(start=0,size=20):\n \"\"\"当前用户关注的所有问题,返回问题brains\"\"\" \n \n\n def IFollowedTopicNum():\n \"\"\"当前用户关注话题数目\"\"\" \n def IFollowedAllTopic(start=0,size=20):\n \"\"\"当前用户关注所有话题,返回话题brains\"\"\" \n def fetchaffiliatedtopics(self,questionobject):\n \"\"\"取得问题的相关话题,最多返回三个相关话题,需要话题的标题,URL,返回dict型。\"\"\" \n\n def affiliatedtopicsNum(self,questionobject):\n \"\"\"需要返回一个相关话题数目\"\"\" \n \n def affiliatedtopics():\n \"\"\"需要返回一个问题的相关话题\"\"\" \n \nclass Itopicfollowed(Interface):\n \"\"\"\n topicfollowed view interface\n\n \"\"\"\n def IFollowedQuestionNum():\n \"\"\"当前用户关注话题数目\"\"\" \n def IFollowedAllQuestion(start=0,size=20):\n \"\"\"当前用户关注所有话题,返回话题brains\"\"\" \n \ngrok.templatedir('templates')\nclass questionfollowed(grok.View):\n grok.context(INavigationRoot)\n grok.template('questionfollowed_view') \n grok.require('zope2.View') \n grok.name('questionfollowed')\n \n def update(self):\n \n self.haveQuestions = bool(self.IFollowedQestionNum())>0\n self.questionsnum = self.IFollowedQestionNum()\n self.topicsnum = self.IFollowedTopicNum()\n \n def isFollowed(self,qbrain):\n \"\"\"给定问题qbrain,判断该该问题是否已被关注,返回boolean\"\"\"\n obj = qbrain.getObject()\n aobj = IFollowing(obj)\n pm = getToolByName(self.context, 'portal_membership')\n userobject = pm.getAuthenticatedMember()\n userid = userobject.getId() \n return aobj.available(userid)\n \n @memoize\n def IFollowedTopicNum(self):\n \"\"\"当前用户关注话题数目\"\"\" \n return len(self.IFollowedAllTopic(start=0, size=0))\n \n @memoize\n def IFollowedQestionNum(self):\n \"\"\"当前用户关注问题数目\"\"\" \n mp = getToolByName(self.context,'portal_membership')\n userobject = mp.getAuthenticatedMember()\n username = userobject.getId()\n \n questionlist = list(userobject.getProperty('myfollowquestion'))\n catalog = getToolByName(self.context, 'portal_catalog')\n \n return len(catalog({'object_provides': Iquestion.__identifier__,\n 'UID':questionlist}))\n \n def fetchquestionsIfollowed(self, start=0, size=10):\n mp = getToolByName(self.context,'portal_membership')\n userobject = mp.getAuthenticatedMember()\n username = userobject.getId()\n \n questionlist = list(userobject.getProperty('myfollowquestion'))\n catalog = getToolByName(self.context, 'portal_catalog')\n \n questionlist.reverse()\n startsize = start*size\n endsize = (start+1)*size\n questionGroup = questionlist[startsize:endsize]\n qbrain = [] \n for tpc in questionGroup:\n qbrain.append(catalog({'object_provides': Iquestion.__identifier__,\n 'UID':tpc})[0])\n return qbrain\n \n def IFollowedAllTopic(self, start=0, size=3):\n \"关注的话题\"\n \n mp = getToolByName(self.context,'portal_membership')\n userobject = mp.getAuthenticatedMember()\n username = userobject.getId()\n topiclist = userobject.getProperty('myfollowtopic')\n catalog = getToolByName(self.context, 'portal_catalog')\n if (start==0 and size==0):\n return catalog({'object_provides': Itopic.__identifier__,\n 'UID':topiclist,\n 'sort_on': 'modified',\n 'sort_order': 'reverse'}) \n return catalog({'object_provides': Itopic.__identifier__,\n 'UID':topiclist,\n 'b_start': start,\n 'b_size': size})\n \n def questionsIfollowedIndex(self, qbrain):\n catalog = getToolByName(self.context, 'portal_catalog')\n \n num = len(catalog({'object_provides': Ianswer.__identifier__,\n 'path': dict(query=qbrain.getPath(),depth=1)}))\n return num\n\n @memoize\n def affiliatedtopics(self,qbrain):\n \"\"\"需要返回一个问题的相关话题数目\"\"\" \n topic = qbrain.getObject() \n intids = getUtility(IIntIds) \n intid = intids.getId(topic)\n catalog = component.getUtility(ICatalog) \n qlist = sorted(catalog.findRelations({'from_id': intid}))\n qlists = []\n\n for q in qlist: \n qlists.append(q.to_object)\n re = sorted(qlists,key=lambda x:x.modified(),reverse=True) \n return re \n \n\n \n \nclass questionfollowedmore(grok.View):\n \"\"\"AJAX action for load more.\n \"\"\"\n \n grok.context(INavigationRoot)\n# grok.template('topicfollowed_view')\n grok.name('questionfollowedmore')\n grok.require('zope2.View')\n\n def render(self):\n \n# self.portal_state = getMultiAdapter((self.context, self.request), name=u\"plone_portal_state\")\n \n form = self.request.form\n formst = form['formstart']\n formstart = int(formst) \n nextstart = (formstart+1)*3\n \n questionfollowed_view = getMultiAdapter((self.context, self.request),name=u\"questionfollowed\")\n questionfollowednum = questionfollowed_view.IFollowedQestionNum()\n \n if nextstart>=questionfollowednum :\n ifmore = 1\n else :\n ifmore = 0\n \n # a batch \n braindata = questionfollowed_view.fetchquestionsIfollowed(formstart, 3) \n \n \n outhtml = \"\"\n brainnum = len(braindata)\n # question brains loop\n for i in range(brainnum):\n questionUrl = braindata[i].getURL()\n questionTitle = braindata[i].Title\n answerNum = questionfollowed_view.questionsIfollowedIndex(braindata[i])\n questionid = braindata[i].id.replace('.','_')\n topics = questionfollowed_view.affiliatedtopics(braindata[i])\n tnum = len(topics)\n # is followed ?\n follow = questionfollowed_view.isFollowed(braindata[i])\n if follow:\n followstyle = \"display:none;\"\n unfollowstyle = \"display:inline;\"\n else:\n followstyle = \"display:inline;\"\n unfollowstyle = \"display:none;\"\n \n out = \"\"\"
    \n \n
    \n %(answers)s答案\n  • \n \n \n 关注问题\n \n \n 取消关注 \n \"\"\" % dict (qurl=questionUrl,\n qtitle=questionTitle,\n answers=answerNum,\n followstyle=followstyle,\n unfollowstyle=unfollowstyle,\n targeturl=questionUrl)\n if tnum >3: \n topiclist = \"\"\n for j in range(3):\n topicUrl = topics[j].absolute_url()\n topicTitle = topics[j].title\n topiclist = topiclist +\"\"\"%s.\"\"\"%(topicUrl,topicTitle)\n topiclist = topiclist.encode('utf-8')\n topiclist = topiclist +\"\"\"等%s话题\"\"\"%(tnum) \n relatetopic = \"\"\"• 涉及到%s
    \"\"\"%(topiclist)\n \n elif tnum>0: \n topiclist = \"\"\n for j in range(tnum):\n topicUrl = topics[j].absolute_url()\n topicTitle = topics[j].title\n topiclist = topiclist+\"\"\"%s.\"\"\"%(topicUrl,topicTitle)\n topiclist = topiclist.encode('utf-8')\n relatetopic = \"\"\"• 涉及到%s话题
    \"\"\"%(topiclist)\n else:\n relatetopic = \"\"\"\"\"\"\n \n outhtml =outhtml+out+relatetopic\n \n data = { \n 'outhtml': outhtml,\n 'ifmore':ifmore,\n }\n \n self.request.response.setHeader('Content-Type', 'application/json')\n return json.dumps(data) \n \nclass topicfollowed(grok.View):\n grok.context(INavigationRoot)\n grok.template('topicfollowed_view')\n grok.require('zope2.View') \n grok.name('topicfollowed')\n \n def update(self):\n \n self.haveTopics = bool(self.fetchtopicsIfollowed())>0\n self.questionsnum = self.IFollowedQuestionNum() \n self.topicsnum = self.IFollowedTopicNum()\n \n def isFollowed(self,tbrain):\n \"\"\"给定话题tbrain,判断该话题是否已被关注,返回boolean\"\"\"\n obj = tbrain.getObject()\n aobj = IFollowing(obj)\n pm = getToolByName(self.context, 'portal_membership')\n userobject = pm.getAuthenticatedMember()\n userid = userobject.getId()\n \n return aobj.available(userid)\n \n def IFollowedTopicNum(self):\n \"\"\"当前用户关注话题数目\"\"\" \n \n return len(self.Followedtopiclist())\n \n @memoize\n def Followedtopiclist(self):\n mp = getToolByName(self.context,'portal_membership')\n userobject = mp.getAuthenticatedMember()\n username = userobject.getId()\n fwtlist = list(userobject.getProperty('myfollowtopic'))\n return fwtlist\n \n @memoize\n def Followedquestionlist(self):\n mp = getToolByName(self.context,'portal_membership')\n userobject = mp.getAuthenticatedMember()\n username = userobject.getId()\n fwqlist = list(userobject.getProperty('myfollowquestion'))\n return fwqlist \n \n \n def IFollowedQuestionNum(self):\n \"\"\"当前用户关注问题数目\"\"\" \n return len(self.Followedquestionlist())\n \n def IFollowedAllQuestion(self, start=0, size=10):\n \n\n fwqlist = self.Followedquestionlist()\n catalog = getToolByName(self.context, 'portal_catalog')\n if (start==0 and size==0):\n return catalog({'object_provides': Iquestion.__identifier__,\n 'UID':fwqlist,\n 'sort_on': 'modified',\n 'sort_order': 'reverse'}) \n return catalog({'object_provides': Iquestion.__identifier__,\n 'UID':fwqlist,\n 'sort_on': 'modified',\n 'sort_order': 'reverse',\n 'b_start': start,\n 'b_size': size}) \n def IFollowedAllTopic(self, start=0, size=2): \n\n topiclist = self.Followedtopiclist()\n\n catalog = getToolByName(self.context, 'portal_catalog')\n if (start==0 and size==0):\n return catalog({'object_provides': Itopic.__identifier__,\n 'UID':topiclist,\n 'sort_on': 'modified',\n 'sort_order': 'reverse'}) \n return catalog({'object_provides': Itopic.__identifier__,\n 'UID':topiclist,\n 'sort_on': 'modified',\n 'sort_order': 'reverse',\n 'b_start': start,\n 'b_size': size}) \n def fetchtopicsIfollowed(self, start=0, size=2):\n mp = getToolByName(self.context,'portal_membership')\n userobject = mp.getAuthenticatedMember()\n username = userobject.getId()\n topiclist = list(userobject.getProperty('myfollowtopic'))\n \n catalog = getToolByName(self.context, 'portal_catalog')\n topiclist.reverse()\n startsize = start*size\n endsize = (start+1)*size\n topicGroup = topiclist[startsize:endsize]\n qbrain = []\n for tpc in topicGroup:\n qbrain.append(catalog({'object_provides': Itopic.__identifier__,\n 'UID':tpc})[0])\n aa = qbrain\n return aa\n \n def isTopicpicAvalable(self,topic):\n \"\"\"判断图片字段是否有效\"\"\"\n try:\n image = topic.getObject().topicpic.size\n if image != 0:\n return True\n else:\n return False\n except:\n return False\n\nclass topicfollowedmore(grok.View):\n \"\"\"AJAX action for updating ratings.\n \"\"\"\n \n grok.context(INavigationRoot)\n grok.name('topicfollowedmore')\n grok.require('zope2.View') \n \n def render(self):\n form = self.request.form\n formst = form['formstart']\n formstart = int(formst) \n nextstart = (formstart+1)*2\n \n topicfollowed_view = getMultiAdapter((self.context, self.request),name=u\"topicfollowed\")\n topicfollowednum = topicfollowed_view.IFollowedTopicNum()\n \n if nextstart>=topicfollowednum :\n ifmore = 1\n else :\n ifmore = 0\n \n braindata = topicfollowed_view.fetchtopicsIfollowed(formstart, 2) \n \n outhtml = \"\"\n brainnum = len(braindata)\n for i in range(brainnum):\n havaTopicpic = topicfollowed_view.isTopicpicAvalable(braindata[i])\n topicobj = braindata[i].getObject()\n topicadapt = getMultiAdapter((topicobj, self.request),name=u\"images\") \n \n if havaTopicpic:\n thumb = topicadapt.scale('topicpic',width=64, height=64)\n imgtag = \"\"\"\"\"\" % \\\n (thumb.url,thummb.width,thumb.height) \n else:\n imgtag = \"\"\"\"\"\" \n topicUrl = braindata[i].getURL()\n topicDescription = braindata[i].Description\n topicTitle = braindata[i].Title\n follow = topicfollowed_view.isFollowed(braindata[i])\n if follow:\n followstyle = \"display:none;\"\n unfollowstyle = \"display:inline;\"\n else:\n followstyle = \"display:inline;\"\n unfollowstyle = \"display:none;\"\n \n out = \"\"\"
    \n
    \n \n
    \n
    \n %(ttitle)s \n \n 关注话题\n \n \n 取消关注 \n \n
    \n
    %(description)s
    \n
    \n
    \n
    \"\"\"% dict (turl = topicUrl,\n ttitle = topicTitle,\n imgtag = imgtag,\n followstyle = followstyle,\n unfollowstyle = unfollowstyle,\n targeturl = questionUrl,\n description = topicDescription)\n outhtml =outhtml+out\n \n data = { \n 'outhtml': outhtml,\n 'ifmore':ifmore,\n }\n \n self.request.response.setHeader('Content-Type', 'application/json')\n return json.dumps(data) ","sub_path":"emc/kb/browser/followed.py","file_name":"followed.py","file_ext":"py","file_size_in_byte":18129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"379074896","text":"import numpy as np\nimport tensorflow as tf\nimport param\n\n\ndef logistic_loss(x,t=0, coef=1):\n return coef * tf.log(1 + tf.exp(coef*(x-t)))\n \nclass tf_HSM():\n '''\n Model for fitting vision data to neural recordings.\n\n params:\n\n images: training input, \n neural_response: training recorded neural response\n\n Model:\n\n images-> LGN -> 2-layer MLP\n LGN: Any vision feature extractor. This model uae different of gaussian (DoG) here\n\n\n Output:\n train_op : Optimizer from Tensor Flow \n loss: loss value. This model use log_loss\n score : MSE\n pred_neural_response: prediction for neural response\n '''\n\n def __init__(self, **params): #def __init__(**params):\n self.num_lgn=[9]\n self.hlsr = [0.2] \n self.MLP_init = tf.truncated_normal_initializer(mean=0, stddev=0.01) \n self.activation = lambda x, y: logistic_loss(x, t=y, coef=1)\n self.images = None\n self.neural_response = None\n self.lgn_trainable = True\n self.UNIFORM_W_init = tf.random_uniform_initializer(-10/2.0,10.0/2.0)\n self.UNIFORM_ReLuThreshold_init = tf.random_uniform_initializer(0.0,10.0/2.0)\n\n #Load trained Ks\n self.lgn_x = None; self.lgn_y = None; \n self.lgn_sc = None; self.lgn_ss = None; \n self.lgn_rc = None; self.lgn_rs = None; \n\n\n def construct_free_params(self,TrainHPY_PRM = False):\n\n # LGN initialization\n \"\"\"\n self.lgn_x = tf.get_variable(name=\"x_pos\", shape=self.num_lgn, initializer=self.LGN_init, trainable=self.lgn_trainable) # 0-31\n self.lgn_y = tf.get_variable(name=\"y_pos\", shape=self.num_lgn, initializer=self.LGN_init, trainable=self.lgn_trainable) # 0-31\n self.lgn_sc = tf.get_variable(name=\"size_center\", shape=self.num_lgn, initializer=self.LGN_sc_init, trainable=self.lgn_trainable) #0.1 - 31\n self.lgn_ss = tf.get_variable(name=\"size_surround\", shape=self.num_lgn, initializer=self.LGN_init, trainable=self.lgn_trainable) #0.1 - 31\n self.lgn_rc = tf.get_variable(name=\"center_weight\", shape=self.num_lgn, initializer=self.LGN_init, trainable=self.lgn_trainable) #0-10\n self.lgn_rs = tf.get_variable(name=\"surround_weight\", shape=self.num_lgn, initializer=self.LGN_init, trainable=self.lgn_trainable) #0-10\n \"\"\"\n\n # MLP\n self.hidden_w = tf.get_variable(\n name=\"hidden_weights\",\n shape=(self.num_lgn[0], int(self.num_neurons[0]*self.hlsr[0])), # [9,20]\n initializer=self.UNIFORM_W_init) #init_bounds #-10, 10\n\n self.hl_tresh = tf.get_variable(\n name=\"hidden_layer_threshold\",\n shape=int(self.num_neurons[0]*self.hlsr[0]), #20\n initializer=self.UNIFORM_ReLuThreshold_init) #init_bounds # 0-10\n\n self.output_w = tf.get_variable(\n name=\"output_w\",\n shape=(int(self.num_neurons[0]*self.hlsr[0]), int(self.num_neurons[0])), #20, 103\n initializer=self.UNIFORM_W_init) # init_bound -10, 10\n\n self.ol_tresh = tf.get_variable(\n name=\"output_layer_threshold\", #output_layer_threshold\n shape=int(self.num_neurons[0]), #103\n initializer=self.UNIFORM_ReLuThreshold_init) # init_bound 0,10\n \n #Check bounds\n #checkbounds = lambda val, lower_bound, upper_bound : tf.minimum(tf.maximum(val,lower_bound), upper_bound)\n #self.hidden_w =checkbounds(self.hidden_w,-10,10); self.hl_tresh = checkbounds(self.hl_tresh,0,10);\n #self.output_w =checkbounds(self.output_w,-10,10); self.ol_tresh = checkbounds(self.ol_tresh,0,10);\n \n def DoG(self, x, y, sc, ss, rc, rs):\n # Passing the parameters for a LGN neuron\n #import ipdb; ipdb.set_trace()\n #x=14.62563043; y=19.43198948; sc=0.1; ss=1.85884457; rc= 0.45414222; rs=9.79140981;\n\n #Check bounds\n checkbounds = lambda val, lower_bound, upper_bound : tf.minimum(tf.maximum(val,lower_bound), upper_bound)\n \n\n x = checkbounds(x,0.0,self.img_size); y = checkbounds(y,0.0,self.img_size)\n sc =checkbounds(x,0.1,self.img_size); ss = checkbounds(y,0.0,self.img_size)\n rc=checkbounds(x,0.0,10.0); rs = checkbounds(y,0.0,10.0)\n\n pi = tf.constant(np.pi)\n pos = ((self.grid_xx - x)**2 + (self.grid_yy - y)**2)\n center = tf.exp(-pos/2/sc) / (2*(sc)*pi)\n surround = tf.exp(-pos/2/(sc + ss)) / (2*(sc + ss)*pi)\n weight_vec = tf.reshape((rc*(center)) - (rs*(surround)), [-1, 1])\n return tf.matmul(self.images, weight_vec)\n\n def LGN(self, i, x_pos, y_pos, lgn_sc, lgn_ss, lgn_rc, lgn_rs):\n output = self.DoG(\n x=x_pos[i],\n y=y_pos[i],\n sc=lgn_sc[i],\n ss=lgn_ss[i],\n rc=lgn_rc[i],\n rs=lgn_rs[i])\n i+=1 \n return i, output\n\n def LGN_loop(self,x_pos, y_pos, lgn_sc, lgn_ss, lgn_rc, lgn_rs):\n output = []\n \n for i in np.arange(self.num_lgn[0]):\n output += [self.DoG(\n x=x_pos[i],\n y=y_pos[i],\n sc=lgn_sc[i],\n ss=lgn_ss[i],\n rc=lgn_rc[i],\n rs=lgn_rs[i])]\n return tf.concat(1, output)\n \n def cond(self, i, x, y, sc, ss, rc, rs):\n return i < self.num_lgn[0] \n\n def build(self, data, label, x, y, sc, ss, rc, rs):\n #import ipdb; ipdb.set_trace()\n self.img_vec_size = int(data.get_shape()[-1])\n self.img_size = np.sqrt(self.img_vec_size)\n self.num_neurons = [int(label.get_shape()[-1])]\n\n grid_xx, grid_yy = tf.meshgrid(tf.range(self.img_size),tf.range(self.img_size))\n self.grid_xx = tf.cast(tf.reshape(grid_xx, [self.img_vec_size]), tf.float32)\n self.grid_yy = tf.cast(tf.reshape(grid_yy, [self.img_vec_size]), tf.float32)\n\n self.LGN_init = tf.random_uniform_initializer(0,self.img_size/2.0)\n self.LGN_sc_init = tf.random_uniform_initializer(0.1/2.0,self.img_size/2.0)\n\n self.construct_free_params()\n\n self.images = data\n self.neural_response = label\n assert self.images is not None\n assert self.neural_response is not None\n\n \n #Load trained LGN\n self.lgn_x = x; self.lgn_y = y; \n self.lgn_sc = sc; self.lgn_ss = ss; \n self.lgn_rc = rc; self.lgn_rs = rs; \n \n # DoG\n self.lgn_out = self.LGN_loop(\n x_pos=self.lgn_x,\n y_pos=self.lgn_y,\n lgn_sc=self.lgn_sc,\n lgn_ss=self.lgn_ss,\n lgn_rc=self.lgn_rc,\n lgn_rs=self.lgn_rs)\n \n # Run MLP\n checklowerbounds = lambda val, lower_bound : tf.maximum(val,lower_bound)\n self.hl_tresh = checklowerbounds(self.hl_tresh,0.0)\n self.ol_tresh= checklowerbounds(self.ol_tresh,0.0)\n\n self.l1 = self.activation(tf.matmul(self.lgn_out, self.hidden_w), self.hl_tresh) #RELU that shift\n self.output = self.activation(tf.matmul(self.l1, self.output_w), self.ol_tresh)\n \n #self.LGN_params={'x_pos':self.lgn_x, 'y_pos':self.lgn_y, 'lgn_sc':self.lgn_sc, 'lgn_ss':self.lgn_ss, 'lgn_rc':self.lgn_rc, 'lgn_rs':self.lgn_rs}\n \n \n return self.output, self.l1, self.lgn_out","sub_path":"old_code/tf_HSM_MLPonly.py","file_name":"tf_HSM_MLPonly.py","file_ext":"py","file_size_in_byte":7001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"625703948","text":"import torch\nimport torch.nn.functional as F\n\ndef aeq(*args):\n \"\"\"\n Assert all arguments have the same value\n \"\"\"\n arguments = (arg for arg in args)\n first = next(arguments)\n assert all(arg == first for arg in arguments), \\\n \"Not all arguments have the same value: \" + str(args)\n\n\ndef sequence_mask(lengths, max_len=None):\n \"\"\"\n Creates a boolean mask from sequence lengths.\n \"\"\"\n batch_size = lengths.numel()\n max_len = max_len or lengths.max()\n return (torch.arange(0, max_len)\n .type_as(lengths)\n .repeat(batch_size, 1)\n .lt(lengths.unsqueeze(1)))\n\n\ndef use_gpu(opt):\n return (hasattr(opt, 'gpuid') and len(opt.gpuid) > 0) or \\\n (hasattr(opt, 'gpu') and opt.gpu > -1)\n\n\ndef sample_attn(scores, dist_type):\n \"\"\" Fix later, I guess \"\"\"\n batch_size, tgt_length, src_length = scores[0].size()\n # scores : N x T x S\n nparam = len(scores)\n if dist_type != \"none\":\n # batch_size * tgt_length, src_length\n scores = [x.view(-1, x.size(-1)) for x in scores]\n if dist_type == \"dirichlet\":\n m = torch.distributions.Dirichlet(scores[0].cpu())\n elif dist_type == \"normal\":\n m = torch.distributions.normal.Normal(scores[0], scores[1])\n else:\n raise Exception(\"Unsupported dist_type\")\n if dist_type == 'normal':\n sample = F.softmax(m.rsample().cuda(), dim=-1).view(batch_size, tgt_length, -1).transpose(0,1)\n #sample = F.dropout(sample, p=0.1, training=training)\n else:\n sample = m.rsample().cuda().view(batch_size, tgt_length, -1).transpose(0,1)\n else:\n sample = F.softmax(scores[0], dim=-1).transpose(0, 1)\n # output is T x N x S, LOL\n return sample\n","sub_path":"onmt/Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"344980389","text":"from __future__ import print_function\nimport numpy as np\nfrom scipy import stats\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport statsmodels.api as sm\nfrom statsmodels.graphics.api import qqplot\n\nprint(sm.datasets.sunspots.NOTE)\n\ndta = sm.datasets.sunspots.load_pandas().data\ndta.index = pd.Index(sm.tsa.datetools.dates_from_range('1700', '2008'))\ndel dta[\"YEAR\"]\ndta.plot(figsize=(12,8));\n#plt.show()\n\nfig = plt.figure(figsize=(12,8))\nax1 = fig.add_subplot(211)\nfig = sm.graphics.tsa.plot_acf(dta.values.squeeze(), lags=40, ax=ax1)\nax2 = fig.add_subplot(212)\nfig = sm.graphics.tsa.plot_pacf(dta, lags=40, ax=ax2)\n#plt.show()\n\narma_mod20 = sm.tsa.ARMA(dta, (2,0)).fit()\nprint(arma_mod20.params)\narma_mod30 = sm.tsa.ARMA(dta, (3,0)).fit()\nprint(arma_mod20.aic, arma_mod20.bic, arma_mod20.hqic)\nprint(arma_mod30.params)\nprint(arma_mod30.aic, arma_mod30.bic, arma_mod30.hqic)\n\nsm.stats.durbin_watson(arma_mod30.resid.values)\n\nfig = plt.figure(figsize=(12,8))\nax = fig.add_subplot(111)\nax = arma_mod30.resid.plot(ax=ax);\n#plt.show()\n\nresid = arma_mod30.resid\nprint(stats.normaltest(resid))\n\nfig = plt.figure(figsize=(12,8))\nax = fig.add_subplot(111)\nfig = qqplot(resid, line='q', ax=ax, fit=True)\n#plt.show()\n\nfig = plt.figure(figsize=(12,8))\nax1 = fig.add_subplot(211)\nfig = sm.graphics.tsa.plot_acf(resid.values.squeeze(), lags=40, ax=ax1)\nax2 = fig.add_subplot(212)\nfig = sm.graphics.tsa.plot_pacf(resid, lags=40, ax=ax2)\nplt.show()","sub_path":"workspace/learnpythoninhsh/src/TimeSeries/SunpotsData.py","file_name":"SunpotsData.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"489824660","text":"from time import sleep\nimport cv2 as cv\nimport numpy as np\nimport threading\nfrom pyueye import ueye\nimport struct\nimport os\nimport copy\n\nimport wake2\nimport sys\n\nfrom find_edge import find_edge_v2 as fe\n\nimport find_points as fp\nimport binarizacia\nimport calibration\n\nimport function as f\n\n# Глобальные переменные\naddr = 0x20\nfrm = 0x20 # адрес от кого (адрес скрипта)\nto = 0x01 # адрес кому ( адрес сервера)\nline_cut_mass = []\n\nCamera = False #индикатор работы камеры\n\n\n# функция записывает данные в файл полученные при анализе контура\ndef writer_data(file_name, mas):\n file = open(file_name, 'w')\n for m in mas:\n for k in m:\n file.write(str(k) + ' ')\n file.write('\\n')\n file.close()\n\n\ndef writer_data_alfa(file_name, mas):\n file = open(file_name, 'w')\n for k in mas:\n file.write(str(k) + ' ')\n file.write('\\n')\n file.close()\n\n\ndef main():\n\n try:\n # init camera\n hcam = ueye.HIDS(0)\n ret = ueye.is_InitCamera(hcam, None)\n print(f\"initCamera returns {ret}\")\n\n # set color mode\n m_nColorMode = ueye.IS_CM_BGR8_PACKED\n ret = ueye.is_SetColorMode(hcam, ueye.IS_CM_BGR8_PACKED)\n print(f\"SetColorMode IS_CM_BGR8_PACKED returns {ret}\")\n\n # set region of interest\n width = 1280\n height = 1080\n rect_aoi = ueye.IS_RECT()\n rect_aoi.s32X = ueye.int(0)\n rect_aoi.s32Y = ueye.int(0)\n rect_aoi.s32Width = ueye.int(width)\n rect_aoi.s32Height = ueye.int(height)\n ueye.is_AOI(hcam, ueye.IS_AOI_IMAGE_SET_AOI, rect_aoi, ueye.sizeof(rect_aoi))\n print(f\"AOI IS_AOI_IMAGE_SET_AOI returns {ret}\")\n\n # allocate memory\n mem_ptr = ueye.c_mem_p()\n mem_id = ueye.int()\n bitspixel = 24 # for colormode = IS_CM_BGR8_PACKED\n ret = ueye.is_AllocImageMem(hcam, width, height, bitspixel,\n mem_ptr, mem_id)\n print(f\"AllocImageMem returns {ret}\")\n\n # set active memory region\n ret = ueye.is_SetImageMem(hcam, mem_ptr, mem_id)\n print(f\"SetImageMem returns {ret}\")\n\n # continuous capture to memory\n ret = ueye.is_CaptureVideo(hcam, ueye.IS_DONT_WAIT)\n print(f\"CaptureVideo returns {ret}\")\n\n # get data from camera and display\n lineinc = width * int((bitspixel + 7) / 8)\n\n # setting fps ( для замедления камеры )\n fps = ueye.c_double()\n ueye.is_SetFrameRate(hcam, 3, fps)\n print('fps = ', fps)\n\n # делаем автоматическую подстройку яркости для камеры\n x = ueye.c_double(1)\n y = ueye.c_double(0)\n ueye.is_SetAutoParameter(hcam, ueye.IS_SET_ENABLE_AUTO_GAIN, x, y)\n\n print('*******************************************')\n print('width = ', width)\n print('height = ', height)\n print('bitspixel = ', bitspixel)\n print('lineinc = ', lineinc)\n print('m_nColorMode = ', m_nColorMode)\n\n om = 1\n om_big = 1\n points = []\n sota = 60\n\n print('СТАРТ ПРОГРАММЫ')\n\n while True:\n global line_cut\n img = ueye.get_data(mem_ptr, width, height, bitspixel, lineinc, copy=True)\n img = np.reshape(img, (height, width, 3))\n\n # img = cv.resize(img, (0, 0), fx=0.5, fy=0.5)\n\n img_sniper = img.copy()\n\n h, w, _ = img.shape\n\n cv.line(img_sniper, (0, int(h / 2)), (w, int(h / 2)), (0, 0, 255), 1)\n cv.line(img_sniper, (int(w / 2), 0), (int(w / 2), h), (0, 0, 255), 1)\n\n cv.imshow('IP Camera stream', img_sniper)\n cv.waitKey(1)\n\n # Производим калибровку для общего снимка (поиск точек контура)\n if e_cal_big.wait(timeout=0):\n print('Калибровка большого снимка')\n file_name = './calibrovka_big.jpg'\n cv.imwrite(file_name, img)\n\n om_big, al_big = calibration.calibration(file_name) # проводим калибровку\n om_big = om_big * 1.04575 # вводим коэфициент для точности калибровки\n print('one_mm = ', om_big)\n print('angle = ', al_big)\n e_cal_big.clear()\n\n # Передаем количество пикселей в миллиметре и угол на сервер\n data = struct.pack(' int:\n if len(nums) == 0:\n return 0\n position = 0\n\n for i in range(1, len(nums)):\n if nums[position] != nums[i]:\n position += 1\n nums[position] = nums[i]\n \n return position + 1\n# @lc code=end\n\n","sub_path":"leetcode/python3/[26]_remove-duplicates-from-sorted-array.py","file_name":"[26]_remove-duplicates-from-sorted-array.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"75888667","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\nfile = open('hist_stock_data/AC_hist.csv')\nlinelist = file.readlines()\n\np_open = np.zeros(len(linelist)-2, dtype=float)\np_close = np.zeros(len(linelist)-2, dtype=float)\np_high = np.zeros(len(linelist)-2, dtype=float)\np_low = np.zeros(len(linelist)-2, dtype=float)\ni = 0\nk = 0\n\nfor x in linelist:\n y = x.split(',')\n try:\n p_close[i] = float(y[1])\n p_open[i] = float(y[2])\n p_high[i] = float(y[3])\n p_low[i] = float(y[4])\n except ValueError:\n continue\n i = i+1\n\np_close = p_close[::-1]\np_open = p_open[::-1]\np_high = p_high[::-1]\np_low = p_low[::-1]\n\n\n\n\nplt.plot(p_close)\nplt.plot(p_open)\nplt.plot(p_high, '-')\nplt.plot(p_low, '--')\nplt.ylim([min(p_low)-10, max(p_high)+10])\nplt.xlim([0, len(p_close)])\nplt.title('Historical Stock Prices for Ayala Corporation')\nplt.ylabel('Price (Php)')\nplt.show()","sub_path":"Thesis/numpy_basics/historical_data_processing.py","file_name":"historical_data_processing.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"620778354","text":"from graphviz import Digraph\nimport json\nimport os\n\n\ncwd = os.getcwd()\nfiles_path = os.path.join(cwd,\"..\")\nfiles_path = os.path.join(files_path,\"..\")\nonlyfiles = [f for f in os.listdir(files_path) if os.path.isfile(os.path.join(files_path, f))]\n\nfor output_file in onlyfiles:\n f = open(os.path.join(files_path, output_file),\"r\")\n contents = f.read()\n components = contents.split(\"\\n\")\n \n vertices = []\n edges = []\n for component in components:\n if( component[:6] == \"vertex\"):\n vertices.append(component[7:])\n elif( component[:4] == \"edge\"):\n edges.append(component[5:])\n\n dot = Digraph(comment=\"PDG\", format='png')\n\n for vertex in vertices:\n vertex_dict = json.loads(vertex)\n dot.node( str(vertex_dict[\"id\"]), str(vertex_dict[\"label\"]) )\n\n for edge in edges:\n edge_dict = json.loads(edge)\n if( str(edge_dict[\"label\"]) == \"\"):\n dot.edge( str(edge_dict[\"src\"]), str(edge_dict[\"targ\"]) ,label=str(edge_dict[\"label\"]), style = 'dashed')\n else:\n dot.edge( str(edge_dict[\"src\"]), str(edge_dict[\"targ\"]) ,label=str(edge_dict[\"label\"]))\n\n print(dot)\n dot.render(output_file+'.gv', view=True)\n","sub_path":"output/PDG/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"625990505","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nlabel = 'b=%.1f'\n\nx = np.arange(-10, 10, 0.1)\nw = 3\nfor b in [-10, -5, 0, 5, 10]:\n f = 1 / (1 + np.exp(-(x * w + b)))\n plt.plot(x, f, label=label % b)\nplt.legend(loc=2)\nplt.show()","sub_path":"demo19.py","file_name":"demo19.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"249134006","text":"# -*- coding: utf-8 -*-\nfrom pymysql import connect\nimport re\nimport urllib.parse\nfrom models import students\n\nURL_FUNC_DICT = dict()\n\n# WSGI接口\ndef application(env, start_response):\n\t\"\"\" \n\t在url字典中使用正则表达式找到对应函数并执行,如果没有对应函数就去找静态文件\n\tenv: 以字典形式传入参数\n\tstart_response: \n\t\t回调函数,回调函数需要有status和headers形参,status为字符串,headers为元组列表[()]\n\t\"\"\"\n\tbody_data = None\n\ttry:\n\t\turl = env['PATH_INFO']\n\t\t# 让函数支持正则表达式进行传参\n\t\tret = None\n\t\tfor key, value in URL_FUNC_DICT.items():\n\t\t\tret = re.match(key, url)\n\t\t\t# 匹配成功\n\t\t\tif ret:\n\t\t\t\tbody_data = value(ret)\n\t\t\t\tbreak\n\t\t# 匹配失败尝试获取静态文件\n\t\tif not ret:\n\t\t\tfile_src = \"./static\" + url\n\t\t\twith open(file_src, \"rb\") as f:\n\t\t\t\tbody_data = f.read()\n\t\tstart_response('200 OK', [('Content-Type', 'text/html;charset=utf-8'), (\"Content-Length\", str(len(body_data)))])\n\n\texcept Exception as e:\n\t\t# 失败404\n\t\tbody = \"{}\".format(e)\n\t\tbody_data = body.encode('utf-8')\n\t\tstart_response('404 NOT FOUND', [('Content-Type', 'text/html;charset=utf-8'), (\"Content-Length\", str(len(body_data)))])\n\t# 返回body二进制数据\n\treturn body_data\n\ndef readTemplatesFile(file_src):\n\t\"\"\" 读取模板文件,传入文件路径,返回字节数据 \"\"\"\n\tfile_src = \"./templates\" + file_src\n\twith open(file_src, \"rb\") as f:\n\t\tdata = f.read()\n\treturn data\n\ndef route(regular):\n\t\"\"\" 路由函数,将函数映射(指针)放入字典 \"\"\"\n\tdef set_url_func(func):\n\t\tURL_FUNC_DICT[regular] = func\n\t\tdef call_func(*args, **kwargs):\n\t\t\treturn func(*args, **kwargs)\n\t\treturn call_func\n\treturn set_url_func\n\n@route(r\"/index\")\ndef index(param):\n\treturn readTemplatesFile(\"/index.html\")\n\n@route(r\"/test\")\ndef test(param):\n\treturn readTemplatesFile(\"/test.txt\")\n\n@route(r\"/student\")\ndef student(param):\n\t# 读取html文件\n\thtml = readTemplatesFile(\"/student.html\").decode('utf-8')\n\t# 连接mysql数据库\n\tconn = connect(host=\"127.0.0.1\", port=3306, user=\"root\", password=\"123456\", database=\"student\", charset=\"utf8\")\n\t# 获取游标\n\tcs = conn.cursor()\n\t# 执行查询语句\n\tcs.execute(\"select * from students;\")\n\t# 获取查询结果元组\n\tcontent_info = cs.fetchall()\n\t# 使用正则表达式匹配模板填空\n\tcontent = ''\n\tfor student_info in content_info:\n\t\tcontent += ''\n\t\tfor temp in student_info:\n\t\t\tcontent += \"{}\".format(temp)\n\t\tcontent += ''\n\n\thtml = re.sub(r\"{\\%content\\%}\", content, html)\n\n\t# 关闭连接\n\tconn.close()\n\t\n\treturn html.encode('utf-8')\n\n@route(r\"/insert/name=(.*)\")\ndef insert_info(param):\n\t# # 读取html文件\n\t# html = readTemplatesFile(\"/student.html\").decode('utf-8')\n\t# # 连接mysql数据库\n\t# conn = connect(host=\"127.0.0.1\", port=3306, user=\"root\", password=\"123456\", database=\"student\", charset=\"utf8\")\n\t# # 获取游标\n\t# cs = conn.cursor()\n\t# # 解析url参数\n\t# student_name = urllib.parse.unquote(param.group(1))\n\t# # 执行查询语句\n\t# cs.execute(\"insert into students value(0, %s)\", student_name)\n\t# # 提交\n\t# conn.commit()\n\n\t# # 关闭连接\n\t# conn.close()\n\n\tstudent_name = urllib.parse.unquote(param.group(1))\n\ts = students(id=0, name=student_name)\n\ts.save()\n\n\treturn \"插入成功\".encode('utf-8')","sub_path":"WebServer/multiprocess_web_server/dynamic/mini_frame.py","file_name":"mini_frame.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"451371093","text":"# coding=utf-8\n\"\"\" Dhaval Patel. May 17, 2017\n parseheadline parses a text string of the repeated forms\n value.\n It returns a dictionary d, so that d['key']=value.\n Note that the order of the value pairs is not relevant.\n\"\"\"\nfrom __future__ import print_function\nimport sys\nimport re\n# Make code python2, python3 compatible.\nif sys.version_info[0] > 2:\n xrange = range\n\ndef parseheadline(headline):\n\t\"\"\"16850292-3visargavisarga12\"\"\"\n\theadline = headline.strip()\n\tsplits = re.split('[<]([^>]*)[>]([^<]*)',headline)\n #print(splits)\n\tresult = {}\n\tfor i in xrange(len(splits)):\n\t\tif i % 3 == 1:\n\t\t\tresult[splits[i]] = splits[i+1]\n\treturn result\ndef test():\n testlines=[\n \"16850292-3visargavisarga12\",\n \"16850292-3visargavisarga1\",\n \"292-3visargavisarga1\",\n \"nokeyval\",\n \"nokeyval\",\n ]\n for idx,line in enumerate(testlines):\n ntest = idx+1\n try:\n result = parseheadline(line)\n except:\n result = 'Error from parseheadline'\n # generate array of lines for output\n outarr =[]\n outarr.append(\"parseheadline test # %s\"% ntest)\n outarr.append(\"headline: %s\" % line)\n outarr.append(\" result: %s\" % result)\n outarr.append(\"\")\n # send outarr to stdout\n for out in outarr:\n print(out.encode('utf-8'))\nif __name__ == \"__main__\":\n test()\n","sub_path":"parseheadline.py","file_name":"parseheadline.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"370181757","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\nfrom datetime import datetime\n\nfrom finances.investment.assets_data import AssetsData\nfrom scipy.optimize import minimize\n\npd.core.common.is_list_like = pd.api.types.is_list_like\nimport pandas_datareader.data as web\nos.environ['TIINGO_API_KEY'] = 'ba62a0fba810f937382b5e772f8f152b58c4ebfc'\n\n# # # Load data from statsmodels datasets\nstart = datetime(2016, 4, 1)\nend = datetime(2019, 4, 1)\ndf = web.DataReader([\n'VXUS',\n'VTI',\n'MSFT',\n'AAPL',\n'AMZN',\n'VOO',\n# 'AMT',\n# 'GOOGL',\n# 'FB',\n# 'JNJ',\n# 'GOOG',\n# 'JPM',\n# 'XOM',\n# 'V',\n# 'BAC',\n# 'PG',\n# 'INTC',\n# 'PFE',\n# 'VZ',\n# 'CVX',\n# 'UNH',\n# 'CSCO',\n# 'T',\n# 'MRK',\n# 'WFC',\n# 'HD',\n# 'MA',\n# 'BA',\n# 'CMCSA',\n# 'KO',\n# 'DIS',\n# 'PEP',\n# 'NFLX',\n# 'C',\n# 'WMT',\n# 'MCD',\n# 'PM',\n# 'ABT',\n# 'ORCL',\n# 'ADBE',\n# 'DWDP',\n# 'IBM',\n# 'MDT',\n# 'UNP',\n# 'CRM',\n# 'MMM',\n# 'ABBV',\n# 'AMGN',\n# 'LLY',\n# 'PYPL',\n# 'HON',\n# 'AVGO',\n# 'NKE',\n# 'ACN',\n# 'MO',\n# 'TMO',\n# 'TXN',\n# 'COST',\n# 'UTX',\n# 'NVDA',\n# 'LIN',\n# 'NEE',\n# 'SBUX',\n# 'GE',\n# 'GILD',\n# 'BMY',\n# 'LOW',\n# 'BKNG',\n# 'DHR',\n# 'CAT',\n# 'USB',\n# 'AXP',\n# 'ANTM',\n# 'COP',\n# 'UPS',\n# 'LMT',\n# 'CVS',\n# 'MDLZ',\n ], 'tiingo', start, end)\ndf['logP'] = np.log(df['close'])\n\nstock_data = AssetsData(stock_data=df, N_horizon=126)\n\nlog_ret = stock_data.cumm_returns\n\nn_assets = len(log_ret.columns)\n\nnp.random.seed(42)\nnum_ports = 6000\nall_weights = np.zeros((num_ports, len(log_ret.columns)))\nret_arr = np.zeros(num_ports)\nvol_arr = np.zeros(num_ports)\nsharpe_arr = np.zeros(num_ports)\n\nfor x in range(num_ports):\n # Weights\n weights = np.array(np.random.random(len(log_ret.columns)))\n weights = weights/np.sum(weights)\n \n # Save weights\n all_weights[x,:] = weights\n \n # Expected return\n ret_arr[x] = np.sum( (log_ret.mean() * weights * 252))\n \n # Expected volatility\n vol_arr[x] = np.sqrt(np.dot(weights.T, np.dot(log_ret.cov()*252, weights)))\n \n # Sharpe Ratio\n sharpe_arr[x] = ret_arr[x]/vol_arr[x]\n\n\nplt.figure(figsize=(12,8))\nplt.scatter(vol_arr, ret_arr, c=sharpe_arr, cmap='viridis')\nplt.colorbar(label='Sharpe Ratio')\nplt.xlabel('Volatility')\nplt.ylabel('Return')\n# plt.scatter(max_sr_vol, max_sr_ret,c='red', s=50) # red dot\nplt.show()\n\n\ndef get_ret_vol_sr(weights):\n weights = np.array(weights)\n ret = np.sum(log_ret.mean() * weights) * 252\n vol = np.sqrt(np.dot(weights.T, np.dot(log_ret.cov()*252, weights)))\n sr = ret/vol\n return np.array([ret, vol, sr])\n\ndef neg_sharpe(weights):\n# the number 2 is the sharpe ratio index from the get_ret_vol_sr\n return get_ret_vol_sr(weights)[2] * -1\n\ndef check_sum(weights):\n #return 0 if sum of the weights is 1\n return np.sum(weights)-1\n\n\ncons = ({'type': 'eq', 'fun': check_sum})\nbounds = []\ninit_guess = []\nfor n in range(n_assets):\n bounds.append((0,1))\n init_guess.append(0.25)\n\nfrontier_y = np.linspace(0,0.3,200)\n\ndef minimize_volatility(weights):\n return get_ret_vol_sr(weights)[1]\n\nfrontier_x = []\n\nfor possible_return in frontier_y:\n print(possible_return)\n cons = ({'type':'eq', 'fun':check_sum},\n {'type':'eq', 'fun': lambda w: get_ret_vol_sr(w)[0] - possible_return})\n \n result = minimize(minimize_volatility,init_guess,method='SLSQP', bounds=bounds, constraints=cons)\n frontier_x.append(result['fun'])\n\n\n\nplt.figure(figsize=(12,8))\nplt.scatter(vol_arr, ret_arr, c=sharpe_arr, cmap='viridis')\nplt.colorbar(label='Sharpe Ratio')\nplt.xlabel('Volatility')\nplt.ylabel('Return')\nplt.plot(frontier_x,frontier_y, 'r--', linewidth=3)\nplt.show()","sub_path":"finances/investment/example_frontier.py","file_name":"example_frontier.py","file_ext":"py","file_size_in_byte":3582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"441029676","text":"#!/usr/bin/env python3\n#\n# Author:\n# Tamas Jos (@skelsec)\n#\n\nimport asyncio\nimport logging\nimport json\nimport traceback\nimport ipaddress\nimport multiprocessing\nimport threading\n\nfrom tqdm import tqdm\n\nimport aiosmb\nfrom aiosmb.commons.interfaces.machine import SMBMachine\nfrom aiosmb.commons.utils.extb import format_exc\n\nfrom jackdaw.common.apq import AsyncProcessQueue\nfrom jackdaw.dbmodel.netshare import NetShare\nfrom jackdaw.dbmodel.netsession import NetSession\nfrom jackdaw.dbmodel.localgroup import LocalGroup\nfrom jackdaw.dbmodel.smbfinger import SMBFinger\nfrom jackdaw import logger\nfrom jackdaw.dbmodel import get_session\n\nfrom jackdaw.dbmodel.adinfo import ADInfo\nfrom jackdaw.dbmodel.adcomp import Machine\n\nclass SMBGathererManager:\n\tdef __init__(self, smb_mgr, worker_cnt = 50, queue_size = 100000):\n\t\tself.queue_size = queue_size\n\t\tself.in_q = AsyncProcessQueue(queue_size)\n\t\tself.out_q = AsyncProcessQueue(queue_size)\n\t\tself.smb_mgr = smb_mgr\n\t\tself.gathering_type = ['all']\n\t\tself.localgroups = ['Administrators', 'Distributed COM Users','Remote Desktop Users']\n\t\tself.concurrent_connections = worker_cnt\n\t\tself.domain = None\n\t\tself.dc_ip = None\n\t\tself.timeout = 3\n\t\tself.db_conn = None\n\n\t\tself.total_targets = 0\n\t\tself.targets = []\n\t\tself.targets_file = None\n\t\tself.ldap_conn = None\n\t\tself.target_ad = None\n\t\tself.lookup_ad = None #if specified, it will look up the targets in the DB.\n\t\tself.out_file = None\n\n\t\tself.gatherer = None\n\t\t\n\t\tself.use_progress_bar = True\n\t\tself.prg_hosts = None\n\t\tself.prg_shares = None\n\t\tself.prg_sessions = None\n\t\tself.prg_groups = None\n\t\tself.prg_errors = None\n\n\t\tself.results_thread = None\n\n\tdef __target_generator(self):\n\t\tif self.db_conn is not None:\n\t\t\tsession = get_session(self.db_conn)\n\t\t\n\t\tfor target in self.targets:\n\t\t\ttid = -1\n\t\t\tyield (tid, target)\n\n\t\tif self.targets_file is not None:\n\t\t\ttid = -1\n\t\t\twith open(self.targets_file, 'r') as f:\n\t\t\t\tfor line in f:\n\t\t\t\t\tline = line.strip()\n\t\t\t\t\tyield (tid, line)\n\n\t\tif self.ldap_conn is not None:\n\t\t\tldap_filter = r'(&(sAMAccountType=805306369))'\n\t\t\tattributes = ['sAMAccountName']\n\t\t\tfor entry in self.ldap_conn.pagedsearch(ldap_filter, attributes):\n\t\t\t\ttid = -1\n\t\t\t\tif self.lookup_ad is not None:\n\t\t\t\t\tres = session.query(Machine)\\\n\t\t\t\t\t\t\t.filter_by(ad_id = self.lookup_ad)\\\n\t\t\t\t\t\t\t.with_entities(Machine.id)\\\n\t\t\t\t\t\t\t.filter(Machine.sAMAccountName == entry['attributes']['sAMAccountName'])\\\n\t\t\t\t\t\t\t.first()\n\t\t\t\t\tif res is not None:\n\t\t\t\t\t\ttid = res[0]\n\t\t\t\t\n\t\t\t\tyield (tid, entry['attributes']['sAMAccountName'][:-1])\n\n\t\tif self.target_ad is not None:\n\t\t\tfor target_id, target_name in session.query(Machine).filter_by(ad_id = self.target_ad).with_entities(Machine.id, Machine.sAMAccountName):\n\t\t\t\tyield (target_id, target_name[:-1])\n\n\t\tif self.db_conn is not None:\n\t\t\tsession.close()\n\n\tdef get_results(self):\n\t\tsession = None\n\t\tif self.db_conn is not None:\n\t\t\tsession = get_session(self.db_conn)\n\t\t\n\t\twhile True:\n\t\t\tx = self.out_q.get()\n\t\t\tif x is None:\n\t\t\t\tbreak\n\n\t\t\ttid, target, result, error = x\n\t\t\tif result is None and error is not None:\n\t\t\t\t#something went error\n\t\t\t\tlogger.debug('[AIOSMBScanner][TargetError][%s] %s' % (target.get_ip_or_hostname(), error))\n\t\t\t\tif self.use_progress_bar is True:\n\t\t\t\t\tself.prg_errors.update()\n\n\t\t\tif result is not None:\n\t\t\t\tif self.use_progress_bar is True:\n\t\t\t\t\tif isinstance(result, NetSession):\n\t\t\t\t\t\tself.prg_sessions.update()\n\t\t\t\t\telif isinstance(result, NetShare):\n\t\t\t\t\t\tself.prg_shares.update()\n\t\t\t\t\telif isinstance(result, LocalGroup):\n\t\t\t\t\t\tself.prg_groups.update()\n\n\t\t\t\tif session is None:\n\t\t\t\t\tlogger.debug(target, str(result), error)\n\t\t\t\telse:\n\t\t\t\t\tsession.add(result)\n\t\t\t\t\tsession.commit()\n\n\t\t\tif result is None and error is None:\n\t\t\t\tlogger.debug('Finished: %s' % target.ip)\n\t\t\t\tif self.use_progress_bar is True:\n\t\t\t\t\tself.prg_hosts.update()\n\t\n\tdef run(self):\n\t\tlogger.info('[+] Starting SMB information acqusition. This might take a while...')\n\t\tself.in_q = AsyncProcessQueue()\n\t\tself.out_q = AsyncProcessQueue()\n\t\tif self.use_progress_bar is True:\n\t\t\tself.prg_hosts = tqdm(desc='HOSTS', ascii = True)\n\t\t\tself.prg_shares = tqdm(desc='Shares', ascii = True)\n\t\t\tself.prg_sessions = tqdm(desc='Sessions', ascii = True)\n\t\t\tself.prg_groups = tqdm(desc='LocalGroup', ascii = True)\n\t\t\tself.prg_errors = tqdm(desc='Errors', ascii = True)\n\n\t\tself.results_thread = threading.Thread(target = self.get_results)\n\t\tself.results_thread.daemon = True\n\t\tself.results_thread.start()\n\n\t\tself.gatherer = AIOSMBGatherer(self.in_q, self.out_q, self.smb_mgr, gather = self.gathering_type, localgroups = self.localgroups, concurrent_connections = self.concurrent_connections)\n\t\tself.gatherer.start()\n\t\t\n\t\tfor target in self.__target_generator():\n\t\t\tself.total_targets += 1\n\t\t\tif self.use_progress_bar is True:\n\t\t\t\tself.prg_hosts.total = self.total_targets\n\t\t\tself.in_q.put(target)\n\t\t\n\t\tself.in_q.put(None)\n\t\t#if self.use_progress_bar is True:\n\t\t#\tself.prg_hosts.total = self.total_targets\n\n\t\tself.results_thread.join()\n\t\tlogger.info('[+] SMB information acqusition finished!')\n\n\nclass AIOSMBGatherer(multiprocessing.Process):\n\tdef __init__(self, in_q, out_q, smb_mgr, gather = ['all'], localgroups = [], concurrent_connections = 10):\n\t\tmultiprocessing.Process.__init__(self)\n\t\tself.in_q = in_q\n\t\tself.out_q = out_q\n\t\tself.smb_mgr = smb_mgr\n\t\tself.gather = gather\n\t\tself.localgroups = localgroups\n\t\tself.concurrent_connections = concurrent_connections\n\n\t\tself.targets = []\n\t\tself.worker_q = None\n\n\tdef setup(self):\n\t\tpass\n\n\tasync def scan_host(self, atarget):\n\t\ttry:\n\t\t\ttid, target = atarget\n\t\t\t#spneg = AuthenticatorBuilder.to_spnego_cred(self.credential, target)\n\t\t\tconnection = self.smb_mgr.create_connection_newtarget(target)\n\t\t\tasync with connection:\n\t\t\t\tawait connection.login()\n\t\t\t\t\n\t\t\t\textra_info = connection.get_extra_info()\n\t\t\t\tif extra_info is not None:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tf = SMBFinger.from_extra_info(tid, extra_info)\n\t\t\t\t\t\tawait self.out_q.coro_put((tid, connection.target, f, None))\n\t\t\t\t\texcept:\n\t\t\t\t\t\ttraceback.print_exc()\n\n\t\t\t\tmachine = SMBMachine(connection)\n\n\n\t\t\t\tif 'all' in self.gather or 'shares' in self.gather:\n\t\t\t\t\tasync for smbshare, err in machine.list_shares():\n\t\t\t\t\t\tif err is not None:\n\t\t\t\t\t\t\tawait self.out_q.coro_put((tid, connection.target, None, 'Failed to list shares. Reason: %s' % format_exc(err)))\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tshare = NetShare()\n\t\t\t\t\t\tshare.machine_id = tid\n\t\t\t\t\t\tshare.ip = connection.target.get_ip_or_hostname()\n\t\t\t\t\t\tshare.netname = smbshare.name\n\t\t\t\t\t\tshare.type = smbshare.type\n\t\t\t\t\t\tshare.remark = smbshare.remark\n\n\t\t\t\t\t\tawait self.out_q.coro_put((tid, connection.target, share, None))\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\tif 'all' in self.gather or 'sessions' in self.gather:\n\t\t\t\t\tasync for session, err in machine.list_sessions():\n\t\t\t\t\t\tif err is not None:\n\t\t\t\t\t\t\tawait self.out_q.coro_put((tid, connection.target, None, 'Failed to get sessions. Reason: %s' % format_exc(err)))\n\t\t\t\t\t\t\tcontinue\n\n\t\t\t\t\t\tsess = NetSession()\n\t\t\t\t\t\tsess.machine_id = tid\n\t\t\t\t\t\tsess.source = connection.target.get_ip_or_hostname()\n\t\t\t\t\t\tsess.ip = session.ip_addr.replace('\\\\','').strip()\n\t\t\t\t\t\tsess.username = session.username\n\n\t\t\t\t\t\tawait self.out_q.coro_put((tid, connection.target, sess, None))\n\n\t\t\t\tif 'all' in self.gather or 'localgroups' in self.gather:\n\t\t\t\t\tfor group_name in self.localgroups:\n\t\t\t\t\t\tasync for domain_name, user_name, sid, err in machine.list_group_members('Builtin', group_name):\n\t\t\t\t\t\t\tif err is not None:\n\t\t\t\t\t\t\t\tawait self.out_q.coro_put((tid, connection.target, None, 'Failed to connect to poll group memeberships. Reason: %s' % format_exc(err)))\n\t\t\t\t\t\t\t\tcontinue\n\n\t\t\t\t\t\t\tlg = LocalGroup()\n\t\t\t\t\t\t\tlg.machine_id = tid\n\t\t\t\t\t\t\tlg.ip = connection.target.get_ip_or_hostname()\n\t\t\t\t\t\t\tlg.hostname = connection.target.get_hostname()\n\t\t\t\t\t\t\tlg.sid = sid\n\t\t\t\t\t\t\tlg.groupname = group_name\n\t\t\t\t\t\t\tlg.domain = domain_name\n\t\t\t\t\t\t\tlg.username = user_name\n\t\t\t\t\t\t\tawait self.out_q.coro_put((tid, connection.target, lg, None))\n\t\t\n\t\texcept Exception as e:\n\t\t\tawait self.out_q.coro_put((tid, connection.target, None, 'Failed to connect to host. Reason: %s' % format_exc(e)))\n\t\t\treturn\n\n\t\tfinally:\n\t\t\tawait self.out_q.coro_put((tid, connection.target, None, None)) #target finished\n\n\tasync def worker(self):\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\ttarget = await self.worker_q.get()\n\t\t\t\tif target is None:\n\t\t\t\t\treturn\n\t\t\t\ttry:\n\t\t\t\t\tawait self.scan_host(target)\n\t\t\t\texcept:\n\t\t\t\t\t#exception should be handled in scan_host\n\t\t\t\t\tcontinue\n\t\t\texcept Exception as e:\n\t\t\t\tlogger.exception('WORKER ERROR')\n\t\t\t\traise\n\n\tasync def scan_queue(self):\n\t\t\"\"\"\n\t\tReads targets from queue and scans them\n\t\t\"\"\"\n\t\tself.worker_q = asyncio.Queue()\n\t\ttasks = []\n\t\tfor _ in range(self.concurrent_connections):\n\t\t\ttasks.append(asyncio.create_task(self.worker()))\n\n\t\twhile True:\n\t\t\ttarget = await self.in_q.coro_get()\n\t\t\tif target is None:\n\t\t\t\tfor _ in range(self.concurrent_connections):\n\t\t\t\t\tawait self.worker_q.put(None)\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tawait self.worker_q.put(target)\n\n\t\tresults = await asyncio.gather(*tasks, return_exceptions = True)\n\t\tfor res in results:\n\t\t\tif isinstance(res, Exception):\n\t\t\t\tlogger.error('Error! %s' % res)\n\t\tawait self.out_q.coro_put(None)\n\t\t\n\n\t\n\tdef run(self):\n\t\tself.setup()\n\t\ttry:\n\t\t\tloop = asyncio.get_event_loop()\n\t\texcept:\n\t\t\tloop = asyncio.new_event_loop()\n\t\t#loop.set_debug(True) # Enable debug\n\t\tloop.run_until_complete(self.scan_queue())\n\n\n","sub_path":"jackdaw/gatherer/smb/old_dontuse/smb_older_new.py","file_name":"smb_older_new.py","file_ext":"py","file_size_in_byte":9294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"104515954","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\n\nimport re\nfrom fuzzywuzzy import fuzz\n\n\ndef get_block(file_path, n): # 获取行号所在的函数体{ }号\n start = -1\n stop = -1\n stack = []\n label = True\n file = open(file_path, encoding='utf-8')\n file_list = file.readlines()\n # print('nn',n)\n file_list_num = list(enumerate(file_list))\n for h, sentence in file_list_num[n - 1::-1]:\n sentence = sentence.strip()\n if sentence == '':\n continue\n if sentence[0] == '/':\n continue\n if sentence[0] == '*':\n continue\n\n if 'function' in sentence:\n if '{' in sentence:\n start = h\n break\n else:\n for g, sentence in file_list_num[h:]:\n if '{' in sentence:\n start = g\n break\n else:\n continue\n break\n if 'contract' in sentence:\n if '{' in sentence:\n start = h\n break\n else:\n for g, sentence in file_list_num[h:]:\n if '{' in sentence:\n start = g\n break\n else:\n continue\n break\n for i, sentence in file_list_num[start:]:\n # if\n\n if '{' in sentence:\n stack.append((i, '{'))\n # print(sentence)\n if '}' in sentence and stack != []:\n stack.pop()\n # print(sentence)\n if stack == []:\n stop = i\n break\n else:\n continue\n return start, stop\n\n\n# 输入源文件路径名,替换的字符串,行号,新文件名\ndef copyfile(sourcepath, ss, ln, i, targetpath):\n # if not os.path.exists('./test/repair10/mutation2'):\n # os.makedirs('./test/repair10/mutation2/')\n if not os.path.exists(targetpath):\n os.makedirs(targetpath)\n f = open(sourcepath, 'r+')\n\n flist = f.readlines()\n line = flist[ln]\n cmindex = line.find(r'//')\n if cmindex != -1:\n line = line[0:cmindex]\n\n print(line.strip(), ss.strip(), fuzz.ratio(line.strip(), ss.strip()))\n if fuzz.ratio(line.strip(), ss.strip()) >= 94:\n return\n\n lnnum = ln + 1\n flist[ln] = ss + f'//Mutation Here for <{lnnum}>' + '\\n'\n (filepath, tempfilename) = os.path.split(sourcepath)\n (filename, extension) = os.path.splitext(tempfilename)\n ln += 1\n if 'int(' in ss or 'int8(' in ss or 'int16(' in ss or 'int32(' in ss or 'int64(' in ss or 'int128(' in ss or 'int256(' in ss:\n newp = targetpath + '/' + filename + '_mutation_for_inttruncate_' + str(ln) + '_' + str(\n i) + extension\n else:\n newp = targetpath + '/' + filename + '_mutation_for_uinttruncate_' + str(ln) + '_' + str(\n i) + extension\n # print(newp)\n f = open(newp, 'w+')\n f.writelines(flist)\n # print('ff', f.name)\n\n\ndef change(list, mg1, mg2):\n if ('uint', mg2) in list:\n s1 = 'uint128(' + mg2 + ')'\n return mg1 + s1\n if ('uint256', mg2) in list:\n s1 = 'uint128(' + mg2 + ')'\n return mg1 + s1\n if ('uint128', mg2) in list:\n s1 = 'uint64(' + mg2 + ')'\n return mg1 + s1\n if ('uint64', mg2) in list:\n s1 = 'uint32(' + mg2 + ')'\n return mg1 + s1\n if ('uint32', mg2) in list:\n s1 = 'uint16(' + mg2 + ')'\n return mg1 + s1\n if ('uint16', mg2) in list:\n s1 = 'uint8(' + mg2 + ')'\n return mg1 + s1\n\n if ('int16', mg2) in list:\n s1 = 'int8(' + mg2 + ')'\n return mg1 + s1\n if ('int32', mg2) in list:\n s1 = 'int16(' + mg2 + ')'\n return mg1 + s1\n if ('int64', mg2) in list:\n s1 = 'int32(' + mg2 + ')'\n return mg1 + s1\n if ('int128', mg2) in list:\n s1 = 'int64(' + mg2 + ')'\n return mg1 + s1\n if ('int256', mg2) in list:\n s1 = 'int128(' + mg2 + ')'\n return mg1 + s1\n if ('int', mg2) in list:\n s1 = 'int128(' + mg2 + ')'\n return mg1 + s1\n return mg1 + mg2\n\n\ndef up(ss, list):\n # 匹配运算符和变量\n pattern = re.compile(r'([+-/*%=])\\s*([a-zA-Z_][a-zA-Z\\d_]*)')\n pattern2 = re.compile(r'(\\+=|-=|/=|\\*=|%=)\\s*([a-zA-Z_][a-zA-Z\\d_]*)')\n if len(re.findall(pattern2, ss)) != 0:\n return True\n if len(re.findall(pattern, ss)) <= 1:\n return False\n return True\n\n # if len(re.findall(pattern, ss)) == 0:\n # return ss\n # newss = re.sub(pattern, lambda x: change(list, x.group(1), x.group(2)), ss)\n # # print('up', list, newss)\n # return newss\n\n\ndef pdmutation(fn, en, spath, list, tpath):\n file = open(spath)\n\n linenum = 0;\n pattern1 = re.compile(r'(^int256|^int64|^int32|^int8|^int) (\\w+)')\n pattern2 = re.compile(r'(^int256|^int64|^int32|^int8|^int) (public|internal|private) (\\w+)')\n pattern3 = re.compile(r'(uint256|uint64|uint32|uint16|uint8|uint) (\\w+)')\n pattern4 = re.compile(r'(uint256|uint64|uint32|uint16|uint8|uint) (public|internal|private) (\\w+)')\n # pattern3 = re.compile(r'([a-zA-Z\\$_][a-zA-Z\\d_]*)\\s*([+-/*=])\\s*([a-zA-Z\\$_][a-zA-Z\\d_]*)')\n\n listpa = list\n for line in file:\n cmindex = line.find(r'//')\n if cmindex != -1:\n line = line[0:cmindex]\n if linenum in range(fn, en + 1):\n # 匹配uint和int\n ret1 = re.findall(pattern1, line.strip())\n ret2 = re.findall(pattern2, line.strip())\n ret3 = re.findall(pattern3, line.strip())\n ret4 = re.findall(pattern4, line.strip())\n listpa += ret1\n listpa += fromthreegettwo(ret2)\n listpa += ret3\n listpa += fromthreegettwo(ret4)\n # 如果是在范围内行就进行判断截取\n\n if line.strip().find('function') != -1:\n fn1, en1 = get_block(spath, linenum + 1)\n # print(fn1, en1)\n pdmutation2(fn1, en1, spath, listpa, tpath)\n # 获取新的字符串如果不是赋值语句\n patternf = re.compile(r'(if\\s+)|(if\\()|(while\\s+)|(while\\()')\n if re.search(patternf, line) != None:\n linenum += 1\n continue\n stringbool = up(line, listpa)\n if stringbool:\n everymutation(spath, line.strip(), listpa, linenum, tpath)\n linenum += 1\n\n\ndef pdmutation2(fn, en, spath, list, tpath):\n file = open(spath)\n\n linenum = 0;\n pattern1 = re.compile(r'(^int256|^int64|^int32|^int8|^int) (\\w+)')\n pattern2 = re.compile(r'(^int256|^int64|^int32|^int8|^int) (public|internal|private) (\\w+)')\n pattern3 = re.compile(r'(uint256|uint64|uint32|uint16|uint8|uint) (\\w+)')\n pattern4 = re.compile(r'(uint256|uint64|uint32|uint16|uint8|uint) (public|internal|private) (\\w+)')\n listpa = list\n for line in file:\n cmindex = line.find(r'//')\n if cmindex != -1:\n line = line[0:cmindex]\n # 如果是在范围内行就进行判断截取\n if linenum in range(fn, en + 1):\n # 匹配uint和int\n ret1 = re.findall(pattern1, line.strip())\n ret2 = re.findall(pattern2, line.strip())\n ret3 = re.findall(pattern3, line.strip())\n ret4 = re.findall(pattern4, line.strip())\n listpa += ret1\n listpa += fromthreegettwo(ret2)\n listpa += ret3\n listpa += fromthreegettwo(ret4)\n # continue\n # 获取新的字符串\n # 获取新的字符串如果不是赋值语句\n patternf = re.compile(r'(if\\s+)|(if\\()|(while\\s+)|(while\\()')\n if re.search(patternf, line) != None:\n linenum += 1\n continue\n stringbool = up(line, listpa)\n if stringbool:\n everymutation(spath, line.strip(), listpa, linenum, tpath)\n linenum += 1\n\n\ndef everymutation(spath, old, list, linenum, tpath):\n pattern = re.compile(r'([+-/*=])\\s*([a-zA-Z_][a-zA-Z\\d_]*)')\n pattern2 = re.compile(r'(\\+=|-=|/=|\\*=|%=)\\s*([a-zA-Z_][a-zA-Z\\d_]*)')\n mm2 = re.search(pattern2, old)\n if mm2 != None:\n # print(f'change前的{list}')\n strr = change(list, mm2.group(1), mm2.group(2))\n s, e = mm2.span()\n strr2 = old.replace(old[s:e], strr, 1)\n copyfile(spath, strr2.strip(), linenum, 0, tpath)\n return\n match = re.search(pattern, old)\n i = 0\n for m in re.finditer(pattern, old):\n strr = change(list, m.group(1), m.group(2))\n s, e = m.span()\n strr2 = old.replace(old[s:e], strr, 1)\n copyfile(spath, strr2.strip(), linenum, i, tpath)\n i += 1\n\n\ndef fromthreegettwo(list):\n newlist = []\n for x, y, z in list:\n newlist.append((x, z))\n return newlist\n\n\ndef p(spath, tpath):\n file = open(spath)\n lnum = 0\n listpa = []\n pattern1 = re.compile(r'(^int256|^int64|^int32|^int8|^int) (\\w+)')\n pattern2 = re.compile(r'(^int256|^int64|^int32|^int8|^int) (public|internal|private) (\\w+)')\n pattern3 = re.compile(r'(uint256|uint64|uint32|uint16|uint8|uint) (\\w+)')\n pattern4 = re.compile(r'(uint256|uint64|uint32|uint16|uint8|uint) (public|internal|private) (\\w+)')\n for line in file:\n ret1 = re.findall(pattern1, line.strip())\n ret2 = re.findall(pattern2, line.strip())\n ret3 = re.findall(pattern3, line.strip())\n ret4 = re.findall(pattern4, line.strip())\n listpa += ret1\n listpa += fromthreegettwo(ret2)\n listpa += ret3\n listpa += fromthreegettwo(ret4)\n if line.strip().find(\"contract\") != -1:\n fn, en = get_block(spath, lnum + 1)\n pdmutation(fn, en, spath, listpa, tpath)\n # print(line.strip())\n lnum += 1\n\n# p('test/AI_repair.sol')\n","sub_path":"Mu.py","file_name":"Mu.py","file_ext":"py","file_size_in_byte":9874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"304335948","text":"from manage.connection import make_default_session\nfrom manage.config import UPDATE_DATE, RPT_DATE\nfrom manage.query.funds import funds_list\nfrom manage.util import funds_split\nfrom manage.wind.manager import manager, manager_info\n\n\ndef insert_manager():\n funds = funds_list()\n spited = funds_split(funds)\n managers = []\n for funds in spited:\n mgr = manager(funds, UPDATE_DATE)\n managers.extend(mgr)\n session = make_default_session()()\n session.add_all(managers)\n session.commit()\n session.close()\n\n\ndef insert_manager_info():\n funds = funds_list()\n spited = funds_split(funds)\n managers = []\n for funds in spited:\n for rank in range(1, 4):\n mgr = manager_info(funds, rank, UPDATE_DATE)\n managers.extend(mgr)\n session = make_default_session()()\n session.add_all(managers)\n session.commit()\n session.close()\n\n\nif __name__ == '__main__':\n insert_manager_info()\n","sub_path":"manage/insert/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"225536590","text":"# -*- coding:utf-8 -*-\n'''\n @Author: py.gooker\n @Email: zhangshch0131@126.com\n @DateTime: 2017-03-22 17:41:37\n @Description: Description\n'''\nimport urllib.parse as parse\n\nimport sys\nimport os\nimport json\n\n\ndef quote_str(data):\n print(data)\n encode = parse.quote(data, safe='/', encoding='utf-8', errors='replace')\n print(encode)\n\n\ndef quote_file(path):\n with open(path, mode='r') as f:\n lines = f.readlines()\n data = ''\n for line in lines:\n data += line\n # print(data)\n if data:\n quote_str(data)\n else:\n print(\"file data is empty\", path)\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n sys.exit(0)\n data = sys.argv[1]\n if os.path.isfile(data):\n quote_file(data)\n else:\n quote_str(data)\n","sub_path":"python/script/urlencode.py","file_name":"urlencode.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"175914147","text":"from tkinter import *\nimport math\n\n#global constants\nAPP_WIDTH = 290;\nAPP_HEIGHT = 240;\nBUTTONS = [\n ['*', '*'],\n ['+', '+'],\n ['-', '-'],\n ['^', '**'],\n ['/', '/'],\n ['0', '0'],\n ['1', '1'],\n ['2', '2'],\n ['3', '3'],\n ['4', '4'],\n ['5', '5'],\n ['6', '6'],\n ['7', '7'],\n ['8', '8'],\n ['9', '9'],\n ['.', '.'],\n ['Go', ''],\n ['C', ''],\n ['SV', ''],\n ['R', ''],\n ['C-F', ''],\n ['acos(', 'math.acos('],\n ['asin(', 'math.asin('],\n ['atan(', 'math.atan('],\n ['cos(', 'math.cos('],\n ['sin(', 'math.sin('],\n ['tan(', 'math.tan('],\n ['√', 'math.sqrt('],\n ['(', '('],\n [')', ')'],\n ['Deg', ''],\n ['Rad', '']\n];\n\n#global variables/booleans ect\nSphereVol = 0;\nResisters = 0;\nResistVal = 0;\ndegrees = 0;\nAngleMode = 1;\ndef validateInput( string ):\n value = 0;\n for i in range( 0, len( BUTTONS ) ):\n string = string.replace( BUTTONS[i][0], BUTTONS[i][1] );\n\n if( string.find( 'math.a' ) > -1 ):\n global AngleMode;\n if( AngleMode == 1 ):\n try: value = str( eval( 'math.degrees( ' + string + ' )' ) );\n except: value = 'ERROR: invalid input';\n return value;\n\n if( BUTTONS[i][0] == 'cos(' or BUTTONS[i][0] == 'tan(' or BUTTONS[i][0] == 'sin(' ):\n if( AngleMode == 1 ):\n degtorad = re.match( \"(^|)(math.cos\\((.*)\\))|(math.tan\\((.*)\\))|(math.sin\\((.*)\\))+$\", string );\n \n if( degtorad ):\n if( degtorad.group()[5:9] == BUTTONS[i][0] ):\n for index in range( 0, len( degtorad.group() ) ):\n try:\n if( len( degtorad.group( index ) ) > 0 ):\n angle = degtorad.group( index );\n value = float( degtorad.group( index ) );\n \n except: continue;\n \n if( value ):\n pos = string.find( degtorad.group()[5:9] );\n string = \"%s%f%s\" % ( string[:pos + 4], math.radians( value ), string[pos + 4 + len( str( angle ) ):pos + 4 + len( str( angle ) ) + 1] );\n \n if( re.match( \"math.sqrt\\((.*)\", string ) ):\n string += \")\";\n \n value = str( eval( string ) );\n #except: value = 'ERROR: invalid input';\n\n return value;\n\n#usage of b_Click: function has trigger: when a user clicks a button\n#to tidy this up could've seperated the individual functions,\n#and moved b_Click into class: application();\ndef b_Click( event ):\n global BUTTONS, app, Resisters, degrees, SphereVol, \\\n Resisters, ResistVal, AngleMode; #call the globals\n\n for i in range( 0, len( BUTTONS ) ): #loop through all buttons\n if( event.widget == BUTTONS[i][2] ): #if widgets match then...\n if( BUTTONS[i][0] == 'C' ):\n app.textVar.set( '' );\n return 1;\n \n if( BUTTONS[i][0] == 'Deg' ): AngleMode = 1; return 1;\n if( BUTTONS[i][0] == 'Rad' ): AngleMode = 0; return 1;\n \n if( BUTTONS[i][0] == 'Go' ): #calc function\n \n if( SphereVol > 0 ): #calc Sphere volumes func\n try:\n volume = ( 4 * math.pi )/3 * int( app.textVar.get() )**3;\n app.textVar.set( '= %f ' % volume );\n except:\n return app.textVar.set( 'ERROR: invalid input.' );\n \n SphereVol = 0;\n return 1;\n\n if( degrees > 0 ): #C to F calc \n try:\n fdeg = ( int( app.textVar.get() ) * ( 9 / 5 ) + 32 );\n app.textVar.set( 'F = %f' % fdeg );\n except:\n return app.textVar.set( 'ERROR: invalid input.' );\n \n degrees = 0;\n return 1;\n \n if( Resisters > 0 ): #calc resisters func\n if( Resisters < 5 ):\n try:\n ResistVal += 1/int( app.textVar.get() );\n except:\n return app.textVar.set( 'ERROR: invalid input.' );\n Resisters += 1;\n app.textVar.set( '' );\n if( Resisters != 5 ): return 1;\n\n if( ResistVal == 0 ):\n return app.textVar.set( 'Cannot divide by zero' );\n\n ResistVal = 1/ResistVal;\n app.textVar.set( '= %f' % ResistVal );\n Resistors = 0;\n ResistVal = 0;\n return 1;\n \n #get the input, and evaluate the string & execute/set to text\n app.textVar.set( '= %s' % validateInput( app.textVar.get() ) );\n #app.textVar.set( \"= %f\" % eval( str ) );\n #except:\n # app.textVar.set( 'ERROR: invalid input.' );\n \n return 1;\n\n if( BUTTONS[i][0] == 'C-F' ): #just custom buttons require invidiual\n app.textVar.set( 'Enter a degree in C: ' );\n degrees = 1;\n return 1;\n \n if( BUTTONS[i][0] == 'R' ):\n app.textVar.set( 'Enter 3 resistors: ' );\n Resisters = 1;\n return 1;\n\n if( Resisters == 1 ):\n app.textVar.set( '' );\n Resisters += 1;\n\n if( BUTTONS[i][0] == 'SV' ):\n app.textVar.set( 'Radius?: ' );\n SphereVol = 1;\n return 1;\n\n if( SphereVol == 1 ):\n app.textVar.set( '' );\n SphereVol += 1;\n\n if( degrees == 1 ):\n app.textVar.set( '' );\n degrees += 1;\n\n app.textVar.set( app.textVar.get() + BUTTONS[i][0] );\n \nclass application():\n def __init__( self ):\n global APP_WIDTH, APP_HEIGHT, BUTTONS;\n self.root = Tk();\n self.root.wm_title( \"Calculator\" );\n self.canvas = Canvas( self.root, width = APP_WIDTH, height = APP_HEIGHT );\n self.textVar = StringVar();\n self.display = Entry( self.root, textvariable = self.textVar, width = 42 );\n self.display.place( x = 20, y = 10 );\n self.canvas.pack();\n\n ypos = 40;\n xpos = 20;\n placedbuttons = 0;\n BUTTONS_count = len( BUTTONS );\n button_x = 0;\n for i in range( 0, BUTTONS_count ): #loop to the amount of buttons\n #add the button widget ID to BUTTONS array,\n #did this so it'll use less memory starting the application\n BUTTONS[i].append( Button( self.canvas, text = BUTTONS[i][0] ) );\n \n \n if( i > 1 ):\n if( i == 18 ):\n xpos = 150;\n self.line = self.canvas.create_line( placedbuttons - 1 * 28 + xpos + 12, 40, placedbuttons - 1 * 28 + xpos + 12, ypos + 10 );\n placedbuttons = 0;\n ypos = 40;\n\n if( i <= 19 ):\n if not( i % 4 ): #5 buttons per line\n ypos = ypos + 40; #adjust y when new line of buttons\n placedbuttons = 0;\n if( i >= 20 ):\n if not( i % 3 ):\n ypos = ypos + 40;\n placedbuttons = 0;\n \n\n if( i <= 20 or i >= 28 ): button_x = placedbuttons * 28 + xpos;\n else: button_x = ( placedbuttons * 45 ) + xpos;\n BUTTONS[i][len( BUTTONS[i] ) - 1].place( x = button_x, y = ypos ); \n\n placedbuttons += 1;\n\napp = application();\napp.root.bind( \"\", b_Click ); # trigger: mouse button 1/left\n","sub_path":"SciCalc.py","file_name":"SciCalc.py","file_ext":"py","file_size_in_byte":8149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"495587757","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sb\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score\nfrom sklearn import grid_search\nfrom sklearn.cross_validation import KFold\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.decomposition import PCA\n\ndata=pd.read_csv('newdata.csv')\ndata=data.drop('passed_no',1)\nfeatures=list(data.columns[:-1])\nlabels=data.columns[-1]\nfeatures = data.copy(features)\nlabels = data[labels]\n\n\nsvr = SVC()\nfor k in range(1000):\n\tfeatures_train,features_test,labels_train,labels_test=train_test_split(features,labels,test_size=0.1)\n\tpca = PCA(n_components=3)\n\tfeatures_train=pca.fit_transform(features_train)\n\tfeatures_test=pca.transform(features_test)\n\tsvr.fit(features_train,labels_train)\n\tpred=svr.predict(features_test)\n\tacc=accuracy_score(pred,labels_test)\n\tif acc > .8:\n\t\tbreak\n\n\ndef plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues):\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\n\n##Classifier ###\n\nsvr = SVC(kernel=\"rbf\")\nsvr.fit(features_train, labels_train)\npred=svr.predict(features_test)\nacc=accuracy_score(pred,labels_test)\n\n\n###generating confusion matrix \nfrom sklearn.metrics import confusion_matrix\nmat=confusion_matrix(pred,labels_test)\nplot_confusion_matrix(mat)\nplt.show()\n\n\n\n\n\n\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"293126325","text":"from datetime import datetime\nfrom django.http import Http404\nfrom django.utils import timezone\nfrom .base import CalAccessModelListMixin\nfrom django.core.urlresolvers import reverse\nfrom calaccess_raw.models.tracking import RawDataVersion\nfrom django.template.defaultfilters import date as dateformat\nfrom bakery.views import (\n BuildableArchiveIndexView,\n BuildableYearArchiveView,\n BuildableMonthArchiveView,\n BuildableDetailView\n)\n\n\nclass VersionArchiveIndex(BuildableArchiveIndexView):\n \"\"\"\n A list of the latest versions of CAL-ACCESS in our archive\n \"\"\"\n queryset = RawDataVersion.objects.complete().exclude(release_datetime__lte='2016-07-27')\n date_field = \"release_datetime\"\n template_name = \"calaccess_website/version_archive.html\"\n build_path = \"downloads/index.html\"\n\n\nclass VersionYearArchiveList(BuildableYearArchiveView):\n \"\"\"\n A list of all versions of CAL-ACCESS in a given year\n \"\"\"\n queryset = RawDataVersion.objects.complete().exclude(release_datetime__lte='2016-07-27')\n date_field = \"release_datetime\"\n make_object_list = False\n template_name = \"calaccess_website/version_archive_year.html\"\n\n def get_url(self):\n return reverse(\n 'version_archive_year',\n kwargs=dict(year=self.get_year())\n )\n\n\nclass VersionMonthArchiveList(BuildableMonthArchiveView):\n \"\"\"\n A list of all versions of CAL-ACCESS in a given year\n \"\"\"\n queryset = RawDataVersion.objects.complete().exclude(release_datetime__lte='2016-07-27')\n date_field = \"release_datetime\"\n month_format = \"%m\"\n make_object_list = True\n template_name = \"calaccess_website/version_archive_month.html\"\n\n def get_url(self):\n return reverse(\n 'version_archive_month',\n kwargs=dict(\n year=self.get_year(),\n month=self.get_month()\n )\n )\n\n\nclass VersionDetail(BuildableDetailView, CalAccessModelListMixin):\n \"\"\"\n A detail page with everything about an individual CAL-ACCESS version\n \"\"\"\n queryset = RawDataVersion.objects.complete().exclude(release_datetime__lte='2016-07-27')\n template_name = 'calaccess_website/version_detail_archived.html'\n\n def set_kwargs(self, obj):\n super(VersionDetail, self).set_kwargs(obj)\n self.kwargs.update({\n 'year': obj.release_datetime.year,\n 'month': dateformat(obj.release_datetime, 'm'),\n 'day': dateformat(obj.release_datetime, 'd'),\n 'time': dateformat(obj.release_datetime, 'His'),\n })\n\n def get_object(self, **kwargs):\n date_parts = map(int, [\n self.kwargs['year'],\n self.kwargs['month'],\n self.kwargs['day'],\n self.kwargs['time'][:2],\n self.kwargs['time'][2:4],\n self.kwargs['time'][-2:]\n ])\n dt = datetime(*date_parts)\n dt = timezone.utc.localize(dt)\n try:\n return self.get_queryset().get(release_datetime=dt)\n except self.get_queryset().model.DoesNotExist:\n raise Http404\n\n def get_context_data(self, **kwargs):\n \"\"\"\n Add some extra bits to the template's context\n \"\"\"\n context = super(VersionDetail, self).get_context_data(**kwargs)\n context['file_list'] = self.regroup_by_klass_group(self.object.files.all())\n if self.object.error_count:\n context['error_pct'] = 100 * self.object.error_count / float(self.object.download_record_count)\n else:\n context['error_pct'] = 0\n return context\n\n def get_url(self, obj):\n return reverse(\n 'version_detail',\n kwargs=dict(\n year=obj.release_datetime.year,\n month=dateformat(obj.release_datetime, 'm'),\n day=dateformat(obj.release_datetime, 'd'),\n time=dateformat(obj.release_datetime, 'His'),\n )\n )\n\n\nclass LatestVersion(VersionDetail):\n \"\"\"\n Detail page of the latest CAL-ACCESS version\n \"\"\"\n template_name = 'calaccess_website/version_detail_latest.html'\n\n def get_object(self, **kwargs):\n \"\"\"\n Return the latest object from the queryset every time.\n \"\"\"\n try:\n return self.get_queryset().latest(\"release_datetime\")\n except self.model.DoesNotExist:\n raise Http404\n\n def get_context_data(self, **kwargs):\n \"\"\"\n Add little extra bits that the standard detail page won't have.\n \"\"\"\n context = super(LatestVersion, self).get_context_data(**kwargs)\n # A hint we can use in the template as a switch\n context['is_latest'] = True\n return context\n\n def get_url(self, obj):\n \"\"\"\n The never-changing latest URL.\n \"\"\"\n return reverse('version_latest')\n\n def build_queryset(self):\n \"\"\"\n Only build this view for one object, the latest one.\n \"\"\"\n return self.build_object(self.get_object())\n","sub_path":"calaccess_website/views/versions.py","file_name":"versions.py","file_ext":"py","file_size_in_byte":5014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"169498663","text":"# OpenImages V4 dataset for Detectron\n\nimport os\n\n# Path to data dir\nassert 'DATA_DIR' in os.environ\n_DATA_DIR = os.environ['DATA_DIR']\n\n# Required dataset entry keys\nIM_DIR = 'image_directory'\nANN_FN = 'annotation_file'\n\n# Available datasets\nDATASETS = {\n 'open_images_v4_train_overfit': {\n IM_DIR:\n _DATA_DIR + '/train_overfit',\n ANN_FN:\n _DATA_DIR + '/annotations/train_overfit.json'\n },\n 'open_images_v4_train': {\n IM_DIR:\n _DATA_DIR + '/train',\n ANN_FN:\n _DATA_DIR + '/annotations/train.json'\n },\n 'open_images_v4_test': {\n IM_DIR:\n _DATA_DIR + '/test',\n ANN_FN:\n _DATA_DIR + '/annotations/test.json'\n },\n 'open_images_v4_val': {\n IM_DIR:\n _DATA_DIR + '/val',\n ANN_FN:\n _DATA_DIR + '/annotations/val.json'\n },\n 'open_images_v4_challenge': {\n IM_DIR:\n _DATA_DIR + '/test_challenge',\n ANN_FN:\n _DATA_DIR + '/annotations/test_challenge.json'\n },\n}\n","sub_path":"datasets/dataset_catalog.py","file_name":"dataset_catalog.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"174313870","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 22 10:04:22 2018\n\n@author: Han\n\"\"\"\n\nuser1 = input(\"Player 1: What is your name? \")\nuser2 = input(\"Player 2: What is your name? \")\nfor i in range(3): \n user1answer = input(str(user1) + \", please choose 'rock,' 'paper,' or 'scissors.' \")\n if user1answer == 'rock' or user1answer == 'paper' or user1answer == 'scissors': \n print('Valid Input')\n break\n if user1answer != 'rock' or user1answer != 'paper' or user1answer != 'scissors':\n print (\"You need to enter in 'rock,' 'paper,' or 'scissors.'\") \n \n \n # print (\"Restart game\")\n # user1answer = input(str(user1) + \", please choose 'rock,' 'paper,' or 'scissors.' \")\n\n \n\"\"\"\nfor user1answer in range (3):\n if user1answer == 'rock' or 'paper' or 'scissors':\n print(\"Player1: Guess again with the right entry\") \n input(str(user1) + \", please choose 'rock,' 'paper,' or 'scissors' again. \")\n break\n\"\"\"\n\n#user2answer = input(str(user2) + \", please choose 'rock,' 'paper,' or 'scissors.' \")\nfor i in range (3):\n user2answer = input(str(user2) + \", please choose 'rock,' 'paper,' or 'scissors.' \")\n if user2answer == 'rock' or user2answer == 'paper' or user2answer == 'scissors': \n print('Valid Input')\n break\n if user2answer != 'rock' or user2answer != 'paper' or user2answer != 'scissors':\n import sys\n sys.exit(\"You need to enter in 'rock,' 'paper,' or 'scissors'.\")\n#u1 = user1answer...\n#u2 = user2answer...\n\n \nif user1answer == user2answer:\n print(\"It's a tie.\")\nelif user1answer == 'rock':\n if user2answer == 'scissors':\n print(str(user1) + \" wins, rock beats scissors.\")\n #elif user2answer != 'rock' + 'paper' + 'scissors':\n # print(\"Invalid entry. Please choose 'rock,' 'paper,' or 'scissors' next time.\")\n else:\n print(str(user2) + \" wins, paper beats rock.\")\nelif user1answer == 'scissors':\n if user2answer == 'paper':\n print(str(user1) + \" wins, scissors beats paper.\")\n else:\n print(str(user2) + \" wins, rock beats scissors.\")\nelif user1answer == 'paper':\n if user2answer == 'rock':\n print(str(user1) + \" wins, paper beats rock.\")\n else:\n print(str(user2) + \" wins, scissors beats paper.\")\nelse: \n print(\"Invalid entry. Please choose 'rock,' 'paper,' or 'scissors' next time.\") \n \n","sub_path":"pythonprogramming/RockPaperScissors6.py","file_name":"RockPaperScissors6.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"263835167","text":"\n# coding: utf-8\n\n# In[1]:\n\n# SKRYPT PRZEDSTAWIA ODPORNOŚĆ NA ZASZUMIENIE WZORCA PREZENTOWANEGO\nimport numpy as np\nimport math\nimport matplotlib\nfrom matplotlib import pyplot as plt\nimport copy\nimport random\nimport chaotic_network as cn\nget_ipython().magic('matplotlib inline')\nfig_size = [12, 9]\nplt.rcParams[\"figure.figsize\"] = fig_size\n\n\n# In[2]:\n\nN = 100\np = 4\n\n\n# In[ ]:\n\nstep = 0.01\nratios = np.arange(0,1+step,step) #wektor z wartosciami okreslajacymi poziom szumu\nprob = np.zeros(np.size(ratios))\nit = 2500\ntrans = 2000\nit2 = 100\nq = 0.5\n\n\n# In[9]:\n\nfor z in range(it2):\n ii = 0\n for ratio in ratios:\n pat = np.ones((p,N))\n ###generowanie wzorcow losowych o zadanym q###\n for i in range(p):\n indices = random.sample(range(N),int(round(q*N)))\n pat[i,indices]=-1\n ###zaszumienie jednego z wybranych wzorcow zgodnie z poziomem szumu###\n indices2 = random.sample(range(N),int(round(ratio*N)))\n index = 0\n dist = pat[index,:].copy()\n for i in range(int(round(ratio*N))):\n dist[indices2[i]] = dist[indices2[i]]*random.choice([-1,1])\n w = cn.hebb(pat)\n x_0 = np.random.rand(1,N)\n eta_0 = np.zeros((1,N))\n zeta_0 = np.zeros((1,N))\n x = x_0\n eta = eta_0\n zeta = zeta_0\n a = 6.4+dist #stymulacja zaszumionym wzorcem\n mu = np.zeros((p,it))\n for i in range(it):\n out = cn.network_step(x, eta, zeta, w, a)\n x = out[0]\n eta = out[1]\n zeta = out[2]\n mu[:,i] = cn.overlap(x,pat,N)\n meanmu = np.mean(mu[:,trans:],1)\n if np.argmax(meanmu) == index:\n if np.size(np.unique(meanmu)) != np.size(np.unique(np.delete(meanmu,index))):\n prob[ii] = prob[ii]+1\n ii=ii+1\nprob=prob/it2\n\n\n# In[11]:\n\nplt.plot(ratios,prob)\nplt.ylim(ymax=1.02)\n\n\n# In[ ]:\n\n\n\n","sub_path":"noise.py","file_name":"noise.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"206784786","text":"import urllib.request\nimport requests\nfrom urllib.parse import urlparse\nfrom bs4 import BeautifulSoup\nfrom csv_writer import *\n\nURL = 'https://www.newsnow.co.uk/h/'\n\n\nclass NewsParser:\n\n def parse_html(self, url):\n response = requests.get(url)\n contents = response.text\n soup = BeautifulSoup(contents, 'lxml')\n news = soup.find_all('main', {'class': 'rs-grid__main js-maincontent'})\n news_data = []\n for one_news in news:\n news_attributes = one_news.select('div[class=hl]')\n for attribute in news_attributes:\n news_dict = {} \n title = attribute.find('a', {'class': 'hll'})\n news_maker = attribute.find('span', {'class': 'src-part'})\n news_url = attribute.select('a[href]')[0]\n news_dict['title'] = title.text\n news_dict['url'] = news_url.get('href')\n news_dict['news maker'] = news_maker.text\n if news_dict not in news_data:\n news_data.append(news_dict)\n return news_data\n\n\ndef main():\n parser = NewsParser()\n file = CSVFile('newsnow.csv')\n file.write(parser.parse_html(URL))\n\nif __name__ == '__main__':\n main()\n","sub_path":"news_parser.py","file_name":"news_parser.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"473239139","text":"import socket\nimport time\nimport threading\n\nsTimes = []\nr2Times = []\ndTimes = []\n\ndef sender(destinationIp,destPort):\n\ts = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\ti = 0\n\twhile i<100:\n\t\tstart = time.time()\n\t\ttime.clock()\n\t\ts.sendto(b\"helo\", (destinationIp, destPort))\n\t\twhile i<100:\n\t\t\tdata = s.recvfrom(1024)\n\t\t\tif data:\n\t\t\t\tend = time.time()\n\t\t\t\trtt = end-start\n\t\t\t\tif(destPort == 1043):\n\t\t\t\t\tsTimes.append(rtt)\n\t\t\t\tif(destPort == 3043):\n\t\t\t\t\tdTimes.append(rtt)\n\t\t\t\tif(destPort == 8080):\n\t\t\t\t\tr2Times.append(rtt)\n\t\t\t\ti+=1\n\t\t\t\tbreak\n\n\ts.close()\n\ndef findAverage(l):\n\ttotal = 0\n\tfor item in l:\n\t\ttotal += item\n\treturn total/len(l)\t\n\n\nif __name__ == '__main__':\n\tsSender = threading.Thread(target=sender, args=(\"10.10.3.1\", 1043)) #need to keep record\n\tdSender = threading.Thread(target=sender, args=(\"10.10.7.1\", 3043)) #need to keep record\n\tr2Sender = threading.Thread(target=sender, args=(\"10.10.6.1\", 8080)) #need to keep record\n\n\tsSender.start()\n\tdSender.start()\n\tr2Sender.start()\n\n\tsSender.join()\n\tdSender.join()\n\tr2Sender.join()\n\n\n\twith open('link_costs.txt', 'w') as f:\n\t\tf.write(\"router3-source\\n\")\n\t\tfor item in sTimes:\n\t\t\tf.write(\"%s\\n\" % item)\n\t\tf.write(\"avg = %s\\n\" % findAverage(sTimes))\n\n\t\tf.write(\"router3-destination\\n\")\n\t\tfor item in dTimes:\n\t\t\tf.write(\"%s\\n\" % item)\n\t\tf.write(\"avg = %s\\n\" % findAverage(dTimes))\n\n\t\tf.write(\"router3-router2\\n\")\n\t\tfor item in r2Times:\n\t\t\tf.write(\"%s\\n\" % item)\n\t\tf.write(\"avg = %s\\n\" % findAverage(r2Times))\n\n\texit(0)","sub_path":"Ceng435/TP1/linkCost/router3.py","file_name":"router3.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"557512322","text":"'''\nCreated on Sep 21, 2017\n@author: Roopali Vij\n'''\n\nimport pandas as pd\nfrom itertools import combinations, chain\n\n\nRULE = \"RULE\"\nBODY = \"BODY\"\nHEAD = \"HEAD\"\nANY = \"ANY\"\nNONE = \"NONE\"\nAND = \"and\"\nOR = \"or\"\n\ndef preprocess_data(file_path):\n\tdf = pd.read_table(file_path, delimiter='\\t', header = None)\n\tcolumns = []\n\tfor i in range(len(df.columns)-1):\n\t\tcolumns.append('G'+ str(i+1))\n\t\tdf[df.columns[i]] = 'G'+ str(i+1) + '_'+ df[df.columns[i]]\n\tcolumns.append('Diagnosis')\n\tdf.columns = columns\n\treturn df\n\ndef get_support_count(minimum_support, total_transactions):\n\tsupport_count = minimum_support * total_transactions\n\treturn support_count\n\ndef get_transactions(data_frame):\n transaction_list = list()\n for index, row in data_frame.iterrows():\n transaction = frozenset(row)\n transaction_list.append(transaction)\n return transaction_list\n\ndef get_len_one_item_set(data_frame):\n\tfirst_item_set = set()\n\tfor col in data_frame.columns:\n\t\tfor item in list(data_frame[col].unique()):\n\t\t\tfirst_item_set.add(frozenset([item]))\n\treturn first_item_set\n\ndef get_current_count(item_set, transaction_list, track_transactions):\n\tcurrent_track = {}\n\tfor item in item_set:\n\t\tfor transaction in transaction_list:\n\t\t\tif item.issubset(transaction):\n\t\t\t\ttrack_transactions[item] = track_transactions.get(item, 0) + 1\n\t\t\t\tcurrent_track[item] = current_track.get(item, 0) + 1\n\treturn current_track\n\ndef purge_items_less_than_min(current_track, support_count):\n\tnew_item_set = set()\n\tfor item, count in current_track.items():\n\t\tif count >= support_count:\n\t\t\tnew_item_set.add(item)\n\treturn new_item_set\n\ndef create_next_itemset(item_set, k):\n\tnew_set = set([i.union(j) for i in item_set for j in item_set if len(i.union(j)) == k])\n\treturn new_set\n\ndef get_all_item_sets(minimum_support, transaction_list,item_set):\n\tprint('Support is set to be '+ str(int(minimum_support*100))+'%')\n\tsupport_count = get_support_count(minimum_support, len(transaction_list))\n\ttrack_transactions = {}\n\tall_items = {}\n\t#keep track of total\n\ttotal_count = 0\n\n\t#prune for first item set -> length or k = 1 in nCk\n\tk = 1\n\tcurrent_track = get_current_count(item_set, transaction_list, track_transactions)\n\tpruned_set = purge_items_less_than_min(current_track, support_count)\n\ttotal_count += len(pruned_set)\n\tall_items[k] = pruned_set\n\tprint('number of length-' + str(k) + ' frequent itensets: ' + str(total_count))\n\n\tk += 1\n\n\twhile len(pruned_set):\n\t\tpruned_set = create_next_itemset(pruned_set, k)\n\t\tcurrent_track = get_current_count(pruned_set, transaction_list, track_transactions)\n\t\tpruned_set = purge_items_less_than_min(current_track, support_count)\n\t\ttotal_count += len(pruned_set)\n\t\tif len(pruned_set):\n\t\t\tall_items[k] = pruned_set\n\t\t\tprint('number of length-' + str(k) + ' frequent itemsets:' + str(len(pruned_set)))\n\t\tk += 1\n\tprint('number of all lengths frequent itemsets:' + str(total_count))\n\treturn all_items, track_transactions\n\ndef get_rules(support, confidence, total_transactions, track_transactions, all_items):\n\trules = []\n\tfor k, v in all_items.items():\n\t\tfor item in v:\n\t\t\tfor head in map(frozenset, [a for a in (chain(*[combinations(item, i + 1) for i, a in enumerate(item)]))]):\n\t\t\t\tbody = item.difference(head)\n\t\t\t\tif len(body):\n\t\t\t\t\tif (float(track_transactions[item]))/(float(track_transactions[head])) >= confidence:\n\t\t\t\t\t\trules.append((set(head), set(body)))\n\treturn rules\n\ndef get_queries():\n\ttemplate_1_queries = []\n\ttemplate_2_queries = []\n\ttemplate_3_queries = []\n\n\ttemplate_1_queries.append((\"RULE\", \"ANY\", ['G59_Up']))\n\ttemplate_1_queries.append((\"RULE\", \"NONE\", ['G59_Up']))\n\ttemplate_1_queries.append((\"RULE\", 1, ['G59_Up', 'G10_Down']))\n\ttemplate_1_queries.append((\"BODY\", \"ANY\", ['G59_Up']))\n\ttemplate_1_queries.append((\"BODY\", \"NONE\", ['G59_Up']))\n\ttemplate_1_queries.append((\"BODY\", 1, ['G59_Up', 'G10_Down']))\n\ttemplate_1_queries.append((\"HEAD\", \"ANY\", ['G59_Up']))\n\ttemplate_1_queries.append((\"HEAD\", \"NONE\", ['G59_Up']))\n\ttemplate_1_queries.append((\"HEAD\", 1, ['G59_Up', 'G10_Down']))\n\n\ttemplate_2_queries.append((\"RULE\", 3))\n\ttemplate_2_queries.append((\"BODY\", 2))\n\ttemplate_2_queries.append((\"HEAD\", 1))\n\n\ttemplate_3_queries.append((\"1or1\", (\"BODY\", \"ANY\", ['G10_Down']), (\"HEAD\", 1, ['G59_Up'])))\n\ttemplate_3_queries.append((\"1and1\", ( \"BODY\", \"ANY\",['G10_Down']), (\"HEAD\", 1, ['G59_Up'])))\n\ttemplate_3_queries.append((\"1or2\", (\"BODY\", \"ANY\", ['G10_Down']), (\"HEAD\", 2)))\n\ttemplate_3_queries.append((\"1and2\", (\"BODY\", \"ANY\",['G10_Down']), (\"HEAD\", 2)))\n\ttemplate_3_queries.append((\"2or2\", (\"BODY\", 1), ( \"HEAD\", 2)))\n\ttemplate_3_queries.append((\"2and2\", ( \"BODY\", 1), (\"HEAD\", 2)))\n\n\treturn template_1_queries ,template_2_queries, template_3_queries\n\ndef get_rule_size(item, check_head, check_body):\n\ttotal_rule_size = 0\n\tif check_head:\n\t\ttotal_rule_size += len(item[1])\n\tif check_body:\n\t\ttotal_rule_size += len(item[0])\n\treturn total_rule_size\n\ndef answer_template_1_query(query, rules):\n\tcheck_body = True\n\tcheck_head = True\n\tcheck = query[0]\n\tif check == BODY:\n\t\tcheck_head = False\n\telif check == HEAD:\n\t\tcheck_body = False\n\toperator = query[1]\n\titems_match_list = query[2]\n\tresults = []\n\tfor item in rules:\n\t\tremaining_set = set()\n\t\ttotal_item = set()\n\t\tif check_head:\n\t\t\ttotal_item = item[1] \n\t\tif check_body:\n\t\t\ttotal_item = total_item.union(item[0])\n\t\tremaining_set = total_item - set(items_match_list)\n\t\ttotal_rule_size = get_rule_size(item, check_head, check_body)\n\t\tlen_remainung_items = len(remaining_set)\n\t\tif operator == ANY and total_rule_size > len_remainung_items:\n\t\t\tresults.append(item)\n\t\telif operator == NONE and total_rule_size == len_remainung_items:\n\t\t\tresults.append(item)\n\t\telif operator == 1 and total_rule_size - len_remainung_items == 1:\n\t\t\tresults.append(item)\n\treturn results\n\n\ndef answer_template_1_queries(template_1_queries, rules):\n\tall_results = []\n\tfor query in template_1_queries:\n\t\tresults = answer_template_1_query(query, rules)\n\t\tall_results.append(results)\n\treturn all_results\n\ndef answer_template_2_query(query, rules):\n\tcheck_body = True\n\tcheck_head = True\n\tcheck = query[0]\n\tif check == BODY:\n\t\tcheck_head = False\n\telif check == HEAD:\n\t\tcheck_body = False\n\tsize = query[1]\n\tresults = []\n\tfor item in rules:\n\t\ttotal_rule_size = get_rule_size(item, check_head, check_body)\n\t\tif total_rule_size >= size:\n\t\t\tresults.append(item)\n\treturn results\n\ndef answer_template_2_queries(template_2_queries, rules):\n\tall_results = []\n\tfor query in template_2_queries:\n\t\tresults = answer_template_2_query(query, rules)\n\t\tall_results.append(results)\n\treturn all_results\n\ndef answer_template_3_query(query, rules):\n\tinfo = query[0]\n\tfirst_query_type = info[0]\n\toperation = info[1:-1]\n\tsecond_query_type = info[-1:]\n\tquery_1 = query[1]\n\tquery_2 = query[2]\n\tif first_query_type == '1':\n\t\tresults_1 = answer_template_1_query(query_1, rules)\n\telse:\n\t\tresults_1 = answer_template_2_query(query_1, rules)\n\n\tif second_query_type == '1':\n\t\tresults_2 = answer_template_1_query(query_2, rules)\n\telse:\n\t\tresults_2 = answer_template_2_query(query_2, rules)\n\tif operation == AND:\n\t\tresults = [e for e in results_2 if e in results_1]\n\telse: #union\n\t\tresults = results_1 + [e for e in results_2 if e not in results_1]\n\t \n\t\n\treturn results\n\ndef answer_template_3_queries(template_3_queries, rules):\n\tall_results = []\n\tfor query in template_3_queries:\n\t\tresults = answer_template_3_query(query, rules)\n\t\tall_results.append(results)\n\treturn all_results\n\nif __name__ == \"__main__\":\n\n\t#get data frame\n\tfile_path = 'associationruletestdata.txt'\n\tdata_frame = preprocess_data(file_path)\n\n\t#get transactions and first item set\n\ttransaction_list = get_transactions(data_frame)\n\titem_set = get_len_one_item_set(data_frame)\n\t\n\tprint('##############################')\n\tprint('###### PART 2 Begins #########')\n\tprint('##############################')\n\n\t#get rules for support = 50 and confidence = 70\n\tsupport = 0.5\n\tconfidence = 0.7\n\tall_items, track_transactions = get_all_item_sets(support, transaction_list, item_set)\n\trules = get_rules(support, confidence , len(transaction_list), track_transactions, all_items)\n\t\n\t'''print('###### All rules #########')\n\tfor item in rules:\n\t\tprint(str(item[0]) + \"==>\" + str(item[1]))'''\t\n\n\n\ttemplate_1_queries ,template_2_queries, template_3_queries = get_queries()\n\t\n\tprint('###### Template 1 queries #########')\n\tresults_template_1 = answer_template_1_queries(template_1_queries, rules)\n\ti = 0\n\tfor value in results_template_1:\n\t\tprint('Starting results for query: ' + str(template_1_queries[i]) + \" count:\" + str(len(value)))\n\t\t'''for item in value:\n\t\t\tprint(str(item[0]) + \"==>\" + str(item[1]))\n\t\tprint('Ending results for query: ' + str(template_1_queries[i]) + \" count:\" + str(len(value)))\n\t\t'''\n\t\ti+=1\n\n\tprint('###### Template 2 queries #########')\n\tresults_template_2 = answer_template_2_queries(template_2_queries, rules)\n\ti = 0\n\tfor value in results_template_2:\n\t\tprint('Starting results for query: ' + str(template_2_queries[i]) + \" count:\" + str(len(value)))\n\t\t'''for item in value:\n\t\t\tprint(str(item[0]) + \"==>\" + str(item[1]))\n\t\tprint('Ending results for query: ' + str(template_2_queries[i]) + \" count:\" + str(len(value)))\n\t\t'''\n\t\ti+=1\n\n\tprint('###### Template 3 queries #########')\n\tresults_template_3 = answer_template_3_queries(template_3_queries, rules)\n\ti = 0\n\tfor value in results_template_3:\n\t\tprint('Starting results for query: ' + str(template_3_queries[i]) + \" count:\" + str(len(value)))\n\t\t'''for item in value:\n\t\t\tprint(str(item[0]) + \"==>\" + str(item[1]))\n\t\tprint('Ending results for query: ' + str(template_3_queries[i]) + \" count:\" + str(len(value)))\n\t\t'''\n\t\ti+=1\n\n\t","sub_path":"Code/min_support_part2.py","file_name":"min_support_part2.py","file_ext":"py","file_size_in_byte":9561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"237471371","text":"#!/usr/bin/python3\nimport sys\nimport os\n\nif(len(sys.argv) != 5):\n print(\"請輸入參數:source problemid path_CONSOLE lxc_NAME\")\n exit()\n\nsource = sys.argv[1]\nproblemid = sys.argv[2]\npath_CONSOLE = sys.argv[3]\nlxc_NAME = sys.argv[4]\npath_Testdata = path_CONSOLE + \"/Testdata\"\npath_Special = path_CONSOLE + \"/Special\"\n\nlxc_path = \"/var/lib/lxc/\" + lxc_NAME + \"/rootfs/\"\n\nprint(\"IN LXC start\")\nprint(sys.argv[0] + \" | \" + sys.argv[1])\n\nrsync_Testdata = \"rsync -avR \" + path_Testdata + \"/\" + problemid + \" \" + lxc_path\nprint(rsync_Testdata)\nos.system(rsync_Testdata)\n\nrsync_Special = \"rsync -avR \" + path_Special + \"/\" + problemid + \" \" + lxc_path\nprint(rsync_Special)\nos.system(rsync_Special)\n\nrsync_CONSOLE = \"rsync -avR --exclude=\" + path_Testdata + \" \" + path_CONSOLE + \" \" + lxc_path\nprint(rsync_CONSOLE)\nos.system(rsync_CONSOLE)\n\nrsync_source = \"rsync -avR \" + source + \" \" + lxc_path \nprint(rsync_source)\nos.system(rsync_source)\n\nchown = \"chown -R nobody:nogroup \" + lxc_path + source\nprint(chown)\nos.system(chown)\nchown = \"chown -R nobody:nogroup \" + lxc_path + path_Special + \"/\" + problemid\nprint(chown)\nos.system(chown)\n\nprint(\"IN LXC end\")\n","sub_path":"JudgeServer_CONSOLE/Bin/rsync_DoSpecialCompile.py","file_name":"rsync_DoSpecialCompile.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"90231770","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\n\ndef split_data(df_ts, df_sum, dict_config):\n '''\n データ分割\n - 学習データと検証データに分割\n - 事故ラベルをサマリーファイルデータから取得\n\n Parameters\n ----------\n df_ts: pandas.DataFrame\n 加速度時系列データ\n df_sum: pandas.DataFrame\n サマリーデータ\n dict_config: dict\n configファイル設定値\n\n Returns\n -------\n df_ts_train : pandas.DataFrame\n 学習用時系列データ\n df_ts_test : pandas.DataFrame\n 検証用時系列データ\n df_sum_train : pandas.DataFrame\n 学習用サマリーデータ\n df_sum_test : pandas.DataFrame\n 検証用サマリーデータ\n '''\n\n # 時系列データをIDがサマリーデータにあるものに限定\n # (通常はすべてサマリーデータにあるはずなので、ここでレコード数は減らないはず)\n if len(df_sum)>0:\n df_ts_join = pd.merge(df_ts, df_sum, on=\"id\", how=\"inner\")\n print(\"時系列データをIDがサマリーデータにあるものに限定\")\n print(\"限定前レコード数:\", len(df_ts))\n print(\"限定後レコード数:\", len(df_ts_join))\n print()\n else:\n print(\"サマリーデータがないので、時系列データとサマリーデータの結合は行わない\\n\")\n df_ts_join=df_ts.copy()\n\n # もとの時系列データの削除\n del df_ts\n\n # 結合後のデータフレームに対応するサマリー情報のデータフレーム作成\n df_sum_join = df_ts_join[df_sum.columns].drop_duplicates()\n df_sum_join.reset_index(drop=True, inplace=True)\n \n # 学習、検証データ分割\n ## サマリーデータフレームの分割\n if dict_config[\"data_split\"][\"test_size\"]==0.0:\n df_sum_train = df_sum_join.copy()\n df_sum_test = pd.DataFrame({})\n elif dict_config[\"data_split\"][\"test_size\"]==1.0:\n df_sum_train = pd.DataFrame({})\n df_sum_test = df_sum_join.copy()\n elif \"claim_flag\" in df_sum_join.columns:\n df_sum_train, df_sum_test \\\n = train_test_split(df_sum_join, \n test_size=dict_config[\"data_split\"][\"test_size\"],\n random_state=dict_config[\"data_split\"][\"random_state\"],\n stratify=df_sum_join[\"claim_flag\"])\n else:\n df_sum_train, df_sum_test \\\n = train_test_split(df_sum_join, \n test_size=dict_config[\"data_split\"][\"test_size\"],\n random_state=dict_config[\"data_split\"][\"random_state\"])\n \n print(\"学習データ事故件数:\", len(df_sum_train))\n print(\"検証データ事故件数:\", len(df_sum_test), \"\\n\")\n\n if \"claim_flag\" in df_sum_train.columns:\n print(\"【学習データの事故ラベルの値ごとの件数】\\n\", \n df_sum_train[\"claim_flag\"].value_counts(), \"\\n\")\n\n if \"claim_flag\" in df_sum_test.columns:\n print(\"【検証データの事故ラベルの値ごとの件数】\\n\", \n df_sum_test[\"claim_flag\"].value_counts(), \"\\n\")\n\n ## 時系列データの分割\n if len(df_sum_train)==0:\n df_ts_train = pd.DataFrame({})\n else:\n df_ts_train = pd.merge(df_ts_join, df_sum_train[\"id\"], on=\"id\", how=\"inner\")\n\n if len(df_sum_test)==0:\n df_ts_test = pd.DataFrame({})\n else:\n df_ts_test = pd.merge(df_ts_join, df_sum_test[\"id\"], on=\"id\", how=\"inner\")\n \n print(\"学習用時系列データ総レコード数:\", len(df_ts_train))\n print(\"検証用時系列データ総レコード数:\", len(df_ts_test))\n\n # もとの時系列データの削除\n del df_ts_join\n\n return df_ts_train, df_ts_test","sub_path":"src_code/preprocess_20210216/python/split_data.py","file_name":"split_data.py","file_ext":"py","file_size_in_byte":3798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"547547451","text":"import os\nimport sys\nimport re\nfrom enum import EnumMeta\n\n\nclass System(EnumMeta):\n WINDOWS = 1\n MACOS = 2\n LINUX = 3\n\n\n_program_data = ''\n\nSYSTEM = None\n\nif sys.platform == 'win32':\n SYSTEM = System.WINDOWS\n _program_data = os.getenv('PROGRAMDATA')\n EPIC_WINREG_LOCATION = r\"com.epicgames.launcher\\shell\\open\\command\"\n LAUNCHER_WINREG_LOCATION = r\"Computer\\HKEY_CLASSES_ROOT\\com.epicgames.launcher\\shell\\open\\command\"\n LAUNCHER_PROCESS_IDENTIFIER = 'EpicGamesLauncher.exe'\n\nelif sys.platform == 'darwin':\n SYSTEM = System.MACOS\n _program_data = os.path.expanduser('~/Library/Application Support')\n EPIC_MAC_INSTALL_LOCATION = \"/Applications/Epic Games Launcher.app\"\n LAUNCHER_PROCESS_IDENTIFIER = 'Epic Games Launcher'\n\nLAUNCHER_INSTALLED_PATH = os.path.join(_program_data, 'Epic', 'UnrealEngineLauncher', 'LauncherInstalled.dat')\nGAME_MANIFESTS_PATH = os.path.join(_program_data, 'Epic', 'EpicGamesLauncher', 'Data', 'Manifests')\n\nAUTH_URL = r\"https://www.epicgames.com/id/login\"\nAUTH_REDIRECT_URL = r\"https://epicgames.com/account/personal\"\n\n\ndef regex_pattern(regex):\n return \".*\" + re.escape(regex) + \".*\"\n\n\nAUTH_PARAMS = {\n \"window_title\": \"Login to Epic\\u2122\",\n \"window_width\": 580,\n \"window_height\": 750,\n \"start_uri\": AUTH_URL,\n \"end_uri_regex\": regex_pattern(AUTH_REDIRECT_URL)\n}","sub_path":"src/consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"366065711","text":"# encoding: utf-8\nfrom django.db import models\n\nfrom core.managers import QuestionManager, ObjectManager\n\n\nclass Project(models.Model):\n title = models.CharField(max_length=255, verbose_name=u'Название')\n image = models.ImageField(upload_to='projects', verbose_name=u'Лого', blank=True, null=True)\n\n class Meta:\n verbose_name = u'проект'\n verbose_name_plural = u'проекты'\n\n def __unicode__(self):\n return self.title\n\n\nclass Question(models.Model):\n TYPE_ANSWERS = 'a'\n TYPE_INTEGER = 'i'\n\n TYPE_CHOICES = (\n (TYPE_ANSWERS, u'Варианты ответа'),\n (TYPE_INTEGER, u'Числовой ответ')\n )\n\n text = models.TextField(verbose_name=u'Текст вопроса')\n type = models.CharField(max_length=2, verbose_name=u'Тип', choices=TYPE_CHOICES)\n\n project = models.ForeignKey(Project, verbose_name=u'Проект', related_name='questions')\n\n next_question = models.ForeignKey('self', verbose_name=u'Следующий вопрос', related_name='prev_questions',\n blank=True, null=True)\n\n objects = QuestionManager()\n\n class Meta:\n verbose_name = u'вопрос'\n verbose_name_plural = u'вопросы'\n\n def to_dict(self):\n result = {\n 'id': self.pk,\n 'text': self.text,\n 'type': self.type\n }\n\n if self.type == self.TYPE_ANSWERS:\n result['answers'] = []\n for answer in self.answers.all():\n result['answers'].append({\n 'id': answer.pk,\n 'text': answer.text\n })\n\n return result\n\n def __unicode__(self):\n return self.text\n\n\nclass QuestionAnswer(models.Model):\n question = models.ForeignKey(Question, verbose_name=u'Вопрос', related_name='answers')\n text = models.CharField(verbose_name=u'Текст', max_length=255)\n\n class Meta:\n verbose_name = u'вариант ответа'\n verbose_name_plural = u'варианты ответа'\n\n def __unicode__(self):\n return self.text\n\n\nclass ProjectAttribute(models.Model):\n project = models.ForeignKey(Project, verbose_name=u'Проект', related_name='attributes')\n name = models.CharField(verbose_name=u'Имя аттрибута', max_length=255)\n weight = models.IntegerField(verbose_name=u'Вес атрибута', default=1)\n\n class Meta:\n verbose_name = u'аттрибуты'\n verbose_name_plural = u'аттрибуты'\n\n def __unicode__(self):\n return self.name\n\n\nclass QuestionRules(models.Model):\n CONDITION_LESS = '<'\n CONDITION_GREATER = '>'\n CONDITION_EQUALS = '='\n\n CONDITION_CHOICES = (\n (CONDITION_LESS, u'меньше'),\n (CONDITION_GREATER, u'больше'),\n (CONDITION_EQUALS, u'равно')\n )\n\n question = models.ForeignKey(Question, verbose_name=u'Вопрос', related_name='rules')\n\n condition = models.CharField(verbose_name=u'Условие', max_length=3, choices=CONDITION_CHOICES,\n default=CONDITION_EQUALS, blank=True, null=True)\n value = models.CharField(verbose_name=u'Значение', max_length=255, blank=True, null=True)\n\n answer = models.ForeignKey(QuestionAnswer, verbose_name=u'Вариант ответа', blank=True, null=True)\n\n next_question = models.ForeignKey(Question, verbose_name=u'Следующий вопрос', blank=True, null=True,\n related_name='prev_rules')\n miss_questions = models.ManyToManyField(Question, verbose_name=u'Вопросы, которые можно пропустить', blank=True,\n related_name='missed_rules')\n\n class Meta:\n verbose_name = u'правило перехода'\n verbose_name_plural = u'правила переходов'\n\n unique_together = ('question', 'answer')\n\n def __unicode__(self):\n return u'Правило перехода для вопроса \"{0}\"'.format(self.question)\n\n\nclass RulesAttribute(models.Model):\n rule = models.ForeignKey(QuestionRules, verbose_name=u'Правило', related_name='attributes')\n attribute = models.ForeignKey(ProjectAttribute, verbose_name=u'Аттрибут', related_name='rules_attribute')\n value = models.CharField(max_length=255, verbose_name=u'Значение')\n\n class Meta:\n verbose_name = u'аттрибут применяемый на правилах'\n verbose_name_plural = u'аттрибуты применяемые на правилах'\n\n\nclass Object(models.Model):\n project = models.ForeignKey(Project, verbose_name=u'Проект', related_name='objects')\n name = models.CharField(verbose_name=u'Имя', max_length=255)\n attributes = models.ManyToManyField(ProjectAttribute, verbose_name=u'Аттрибуты', through='ObjectAttribute')\n\n objects = ObjectManager()\n\n class Meta:\n verbose_name = u'объект'\n verbose_name_plural = u'объекты'\n\n def __unicode__(self):\n return self.name\n\n\nclass ObjectAttribute(models.Model):\n object = models.ForeignKey(Object, verbose_name=u'Объект', related_name='object_attributes')\n project_attribute = models.ForeignKey(ProjectAttribute, verbose_name=u'Аттрибут', related_name='object_attributes')\n value = models.CharField(verbose_name=u'Значение', max_length=255)\n\n class Meta:\n verbose_name = u'аттрибут объекты'\n verbose_name_plural = u'аттрибуты объектов'\n\n\nclass ProjectSession(models.Model):\n project = models.ForeignKey(Project, verbose_name=u'Проект')\n passed_questions = models.ManyToManyField(Question, verbose_name=u'Прошедние вопросы',\n related_name='sessions_passed')\n missed_questions = models.ManyToManyField(Question, verbose_name=u'Вопросы, которые нужно пропустить',\n related_name='sessions_missed')\n current_question = models.ForeignKey(Question, verbose_name=u'Текущий вопрос', blank=True, null=True)\n\n is_stopped = models.BooleanField(default=False)\n\n class Meta:\n verbose_name = u'сессия пользовательского опроса'\n verbose_name_plural = u'сессии пользовательского опроса'\n\n\nclass ProjectSessionAttributes(models.Model):\n session = models.ForeignKey(ProjectSession, verbose_name=u'Сессия', related_name='attributes')\n attribute = models.ForeignKey(ProjectAttribute, verbose_name=u'Аттрибут', related_name='session_attribute')\n condition = models.CharField(max_length=3, verbose_name=u'Условие', choices=QuestionRules.CONDITION_CHOICES,\n blank=True, null=True)\n value = models.CharField(max_length=255, verbose_name=u'Значения')\n\n","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"469013688","text":"\"\"\"\n@Author : sean cheng\n@Email : aya234@163.com\n@CreateTime : 2019/3/16\n@Program : 小野人快跑的小游戏\n\"\"\"\nimport pygame\nfrom pygame.locals import *\nfrom itertools import cycle\nimport random\n\nSCREENWIDTH = 800\nSCREENHEIGHT = 270\n\nFPS = 30\n\n\nclass GameMap():\n def __init__(self, x, y):\n self.bg = pygame.image.load('images/bg.jpg')\n self.x = x\n self.y = y\n\n def map_rolling(self):\n if self.x < - 790:\n self.x = 800\n else:\n self.x -= 5\n\n def map_update(self):\n SCREEN.blit(self.bg, (self.x, self.y))\n\n\nclass CaveMan():\n def __init__(self):\n self.rect = pygame.Rect(0, 0, 0, 0)\n self.jumpStatus = False\n self.jumpHeight = 140\n self.lowest_y = 140\n self.jumpValue = 0\n self.cavemanIndex = 0\n self.cavemanIndexGem = cycle([0, 1, 2])\n self.caveman_img = (pygame.image.load('images/caveman1.png').convert_alpha(),\n pygame.image.load('images/caveman2.png').convert_alpha(),\n pygame.image.load('images/caveman3.png').convert_alpha())\n self.jump_audio = pygame.mixer.Sound('audio/jump.wav')\n self.rect.size = self.caveman_img[0].get_size()\n self.x = 50\n self.y = self.lowest_y\n self.rect.topleft = (self.x, self.y)\n\n def jump(self):\n self.jumpStatus = True\n\n def move(self):\n if self.jumpStatus:\n if self.rect.y >= self.lowest_y:\n self.jumpValue = -5\n if self.rect.y <= self.lowest_y - self.jumpHeight:\n self.jumpValue = 5\n self.rect.y += self.jumpValue\n if self.rect.y >= self.lowest_y:\n self.jumpStatus = False\n\n def draw_caveman(self):\n cavemanIndex = next(self.cavemanIndexGem)\n SCREEN.blit(self.caveman_img[cavemanIndex], (self.x, self.rect.y))\n\n\nclass Obstacle():\n score = 1\n\n def __init__(self):\n self.rect = pygame.Rect(0, 0, 0, 0)\n self.stone = pygame.image.load('images/Rock.png').convert_alpha()\n self.treeTall = pygame.image.load('images/Tree_Tall.png').convert_alpha()\n self.numbers = (pygame.image.load('images/0.png').convert_alpha(),\n pygame.image.load('images/1.png').convert_alpha(),\n pygame.image.load('images/2.png').convert_alpha(),\n pygame.image.load('images/3.png').convert_alpha(),\n pygame.image.load('images/4.png').convert_alpha(),\n pygame.image.load('images/5.png').convert_alpha(),\n pygame.image.load('images/6.png').convert_alpha(),\n pygame.image.load('images/7.png').convert_alpha(),\n pygame.image.load('images/8.png').convert_alpha(),\n pygame.image.load('images/9.png').convert_alpha())\n self.score_audio = pygame.mixer.Sound('audio/score.wav')\n r = random.randint(0, 1)\n if r == 0:\n self.image = self.stone\n else:\n self.image = self.treeTall\n self.rect.size = self.image.get_size()\n self.width, self.height = self.rect.size\n self.x = 800\n self.y = 200 - (self.height / 2)\n self.rect.center = (self.x, self.y)\n\n def obstacle_move(self):\n self.rect.x -= 5\n\n def draw_obstacle(self):\n SCREEN.blit(self.image, (self.rect.x, self.rect.y))\n\n def getScore(self):\n tmp = self.score\n if tmp == 1:\n self.score_audio.play()\n self.score = 0\n return tmp\n\n def showScore(self, score):\n self.scoreDigits = [int(x) for x in list(str(score))]\n totalWidth = 0\n for digit in self.scoreDigits:\n totalWidth += self.numbers[digit].get_width()\n Xoffset = (SCREENWIDTH - totalWidth) / 2\n for digit in self.scoreDigits:\n SCREEN.blit(self.numbers[digit], (Xoffset, SCREENHEIGHT * 0.1))\n Xoffset += self.numbers[digit].get_width()\n\n\ndef game_over():\n bump_audio = pygame.mixer.Sound('audio/gameover.wav')\n bump_audio.play()\n\n screen_w = pygame.display.Info().current_w\n screen_h = pygame.display.Info().current_h\n over_img = pygame.image.load('images/gameover.png').convert_alpha()\n\n SCREEN.blit(over_img, ((screen_w - over_img.get_width()) / 2, (screen_h - over_img.get_height()) / 2))\n\n\ndef mainGame():\n score = 0\n over = False\n global SCREEN, FPSCLOCK\n pygame.init()\n FPSCLOCK = pygame.time.Clock()\n SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT))\n pygame.display.set_caption('小野人快跑')\n bg1 = GameMap(0, 0)\n bg2 = GameMap(800, 0)\n caveman = CaveMan()\n\n addObstacleTime = 0\n list = []\n\n while True:\n\n for event in pygame.event.get():\n if event.type == QUIT:\n over = True\n pygame.quit()\n exit(0)\n if event.type == KEYUP and event.key == K_SPACE:\n if caveman.rect.y >= caveman.lowest_y:\n caveman.jump()\n caveman.jump_audio.play()\n if over == True:\n mainGame()\n\n if over == False:\n bg1.map_update()\n bg1.map_rolling()\n bg2.map_update()\n bg2.map_rolling()\n\n caveman.move()\n caveman.draw_caveman()\n if addObstacleTime >= 1300:\n r = random.randint(0, 100)\n if r > 40:\n obstacle = Obstacle()\n list.append(obstacle)\n addObstacleTime = 0\n for i in range(len(list)):\n list[i].obstacle_move()\n list[i].draw_obstacle()\n if pygame.sprite.collide_rect(caveman, list[i]):\n over = True\n game_over()\n else:\n if (list[i].rect.x + list[i].rect.width) < caveman.rect.x:\n score += list[i].getScore()\n\n list[i].showScore(score)\n\n addObstacleTime += 20\n\n pygame.display.update()\n FPSCLOCK.tick(FPS)\n\n\nif __name__ == '__main__':\n mainGame()\n","sub_path":"caveman/caveman.py","file_name":"caveman.py","file_ext":"py","file_size_in_byte":6247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"328208496","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/hugo/.virtualenvs/gitinspector/lib/python2.7/site-packages/gitinspector/responsibilities.py\n# Compiled at: 2015-08-05 12:31:15\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom localization import N_\nfrom outputable import Outputable\nimport blame, changes, format, gravatar, terminal, textwrap\n\nclass ResponsibiltyEntry:\n blames = {}\n\n\nclass Responsibilities:\n\n @staticmethod\n def get(hard, useweeks, author_name):\n author_blames = {}\n for i in blame.get(hard, useweeks, changes.get(hard)).blames.items():\n if author_name == i[0][0]:\n total_rows = i[1].rows - i[1].comments\n if total_rows > 0:\n author_blames[i[0][1]] = total_rows\n\n return sorted(author_blames.items())\n\n\nRESPONSIBILITIES_INFO_TEXT = N_(b'The following repsonsibilties, by author, were found in the current revision of the repository (comments are exluded from the line count, if possible)')\nMOSTLY_RESPONSIBLE_FOR_TEXT = N_(b'is mostly responsible for')\n\nclass ResponsibilitiesOutput(Outputable):\n\n def __init__(self, hard, useweeks):\n self.hard = hard\n self.useweeks = useweeks\n Outputable.__init__(self)\n self.changes = changes.get(hard)\n\n def output_text(self):\n print(b'\\n' + textwrap.fill(_(RESPONSIBILITIES_INFO_TEXT) + b':', width=terminal.get_size()[0]))\n for i in sorted(set(i[0] for i in blame.get(self.hard, self.useweeks, self.changes).blames)):\n responsibilities = sorted(((i[1], i[0]) for i in Responsibilities.get(self.hard, self.useweeks, i)), reverse=True)\n if responsibilities:\n print(b'\\n' + i, _(MOSTLY_RESPONSIBLE_FOR_TEXT) + b':')\n for j, entry in enumerate(responsibilities):\n width, _unused = terminal.get_size()\n width -= 7\n print(str(entry[0]).rjust(6), end=b' ')\n print(b'...%s' % entry[1][-width + 3:] if len(entry[1]) > width else entry[1])\n if j >= 9:\n break\n\n def output_html(self):\n resp_xml = b'
    '\n resp_xml += b'

    ' + _(RESPONSIBILITIES_INFO_TEXT) + b'.

    '\n for i in sorted(set(i[0] for i in blame.get(self.hard, self.useweeks, self.changes).blames)):\n responsibilities = sorted(((i[1], i[0]) for i in Responsibilities.get(self.hard, self.useweeks, i)), reverse=True)\n if responsibilities:\n resp_xml += b'
    '\n if format.get_selected() == b'html':\n author_email = self.changes.get_latest_email_by_author(i)\n resp_xml += (b'

    {1} {2}

    ').format(gravatar.get_url(author_email, size=32), i, _(MOSTLY_RESPONSIBLE_FOR_TEXT))\n else:\n resp_xml += (b'

    {0} {1}

    ').format(i, _(MOSTLY_RESPONSIBLE_FOR_TEXT))\n for j, entry in enumerate(responsibilities):\n resp_xml += b'' if j % 2 == 1 else b'>') + entry[1] + b' (' + str(entry[0]) + b' eloc)
    '\n if j >= 9:\n break\n\n resp_xml += b'
    '\n\n resp_xml += b'
    '\n print(resp_xml)\n\n def output_xml(self):\n message_xml = b'\\t\\t' + _(RESPONSIBILITIES_INFO_TEXT) + b'\\n'\n resp_xml = b''\n for i in sorted(set(i[0] for i in blame.get(self.hard, self.useweeks, self.changes).blames)):\n responsibilities = sorted(((i[1], i[0]) for i in Responsibilities.get(self.hard, self.useweeks, i)), reverse=True)\n if responsibilities:\n author_email = self.changes.get_latest_email_by_author(i)\n resp_xml += b'\\t\\t\\t\\n'\n resp_xml += b'\\t\\t\\t\\t' + i + b'\\n'\n resp_xml += b'\\t\\t\\t\\t' + gravatar.get_url(author_email) + b'\\n'\n resp_xml += b'\\t\\t\\t\\t\\n'\n for j, entry in enumerate(responsibilities):\n resp_xml += b'\\t\\t\\t\\t\\t\\n'\n resp_xml += b'\\t\\t\\t\\t\\t\\t' + entry[1] + b'\\n'\n resp_xml += b'\\t\\t\\t\\t\\t\\t' + str(entry[0]) + b'\\n'\n resp_xml += b'\\t\\t\\t\\t\\t\\n'\n if j >= 9:\n break\n\n resp_xml += b'\\t\\t\\t\\t\\n'\n resp_xml += b'\\t\\t\\t\\n'\n\n print(b'\\t\\n' + message_xml + b'\\t\\t\\n' + resp_xml + b'\\t\\t\\n\\t')","sub_path":"pycfiles/gitinspector-0.3.2.macosx-10.10-x86_64.tar/responsibilities.py","file_name":"responsibilities.py","file_ext":"py","file_size_in_byte":4855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"563905618","text":"# -*- coding: utf-8 -*-\nimport sys\nimport os\nimport math\nimport numpy as np\nimport pandas as pd\nimport json\nimport umap\nimport joblib\nfrom collections import Counter\n# sys.path.insert(0, r'C:\\Users\\viska\\Documents\\AceCan')\n# os.chdir(r\"C:\\Users\\viska\\Documents\\AceCan\")\n# data_dir = r'.\\bki'\ndata_dir = './bki'\noutput_path= os.getcwd()\nfrom timeit import default_timer as timer\nfrom code.data.dataset import Dataset\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nfrom sklearn import preprocessing\nimport warnings\nwarnings.simplefilter(\"ignore\")\n# import matplotlib.pyplot as plt\n# from pylab import rcParams\n# rcParams['figure.figsize'] = 16, 10\n\n############## Process Data #################\ndef process_dataset_pc(data_dir, base, num, pca_comp, topk, test,smth=False): \n images = Dataset(data_dir, num)\n num = images.N_img #in case: num > N_images\n# pca_combined = np.zeros([images.layer, images.layer])\n print(f'Processing {num} [test :{test}] images with original size {images.size} ')\n with ThreadPoolExecutor() as executor: \n futures = []\n for idx in range(num):\n futures.append(executor.submit(lambda x: run_step_multiple(x, images, test, smth), idx))\n # print(f\" No.{idx} image is loaded\")\n mul_comb = np.zeros([images.layer,images.layer])\n for future in as_completed(futures):\n mul = future.result()\n mul_comb += mul\n pc = run_step_pc(mul_comb, pca_comp)\n return images.data1D, pc\n\ndef run_step_multiple(idx, images,smth, test = 'False'):\n if test:\n images.get_test_data(idx,smth)\n else:\n images.get_data(idx,smth)\n images.data1D[idx] = np.reshape(images.data[idx], [images.ver*images.hor, images.layer]).astype(float)\n return images.data1D[idx].T.dot(images.data1D[idx])\n\ndef run_step_pc(mul_comb, pca_comp):\n # use svd since its commputational faster\n print(\"=============== run step PCA ===============\")\n u,s,v = np.linalg.svd(mul_comb)\n assert np.allclose(u, v.T)\n print('Explained Variance Ratio', np.round(s/sum(s),3))\n pc = u[:,:pca_comp]\n return pc\n\ndef process_pca(data1Ds, pc, num, pca_comp, N_bins = 100, N_sigma = 3 ):\n pca_results = run_step_pc_transform(0, data1Ds, pc)\n # results = data1Ds[0]\n for i in range(1,num):\n pca_result = run_step_pc_transform(i, data1Ds, pc)\n pca_results = np.vstack((pca_results,pca_result))\n # results = np.vstack((results, data1Ds[i]))\n # pca_results = pca_results[1:,:]\n print('========= Intensity ==============')\n intensity = (np.sum(pca_results**2, axis = 1))**0.5\n # cutoffH = np.mean(intensity).round()\n return intensity, pca_results\n\ndef run_step_pc_transform(x, data1Ds, pc):\n return data1Ds[x].dot(pc)\n\n#===============================intensity=====================================\ndef process_intensity(pca_result, intensity, base, pca_comp,cutoff = None,r1=0.01,method='basic'):\n if cutoff == None:\n cutoff = run_step_cutoff(intensity)\n mask = intensity > cutoff\n print('norm length',np.sum(mask))\n norm_data = np.divide(pca_result[mask], intensity[mask][:,None])\n if method=='ratio':\n vmin,vmax=np.quantile(norm_data,r1), np.quantile(norm_data,1-r1)\n print('norm_data', vmin,vmax)\n norm_data=np.clip(norm_data,vmin,vmax)\n norm_data=(norm_data-vmin)/(vmax-vmin)\n pca_rebin=np.round(norm_data*(base-1))\n elif method=='basic':\n pca_rebin = np.trunc((norm_data + 1) * base/2)\n print('rebin, min/mac', np.min(pca_rebin), np.max(pca_rebin))\n stream_1D = 0\n for comp in range(pca_comp):\n stream_1D = stream_1D + pca_rebin.T[comp]*base**comp\n return stream_1D, norm_data, mask\n\ndef run_step_cutoff(intensity, N_bins = 100, N_sigma = 3 ):\n para = np.log(intensity[intensity > 0])\n (x,y) = np.histogram(para, bins = N_bins)\n y = (y[1]-y[0])/2 + y[:-1]\n assert len(x) == len(y)\n x_max = np.max(x)\n x_half = x_max//2\n mu = y[x == x_max]\n sigma = abs(y[abs(x - x_half).argmin()] -mu)\n cutoff_log = N_sigma* sigma + mu\n cutoff = int(np.exp(cutoff_log).round())\n return cutoff\n\ndef run_step_norm(pca_result, intensity, cutoffH, base, pca_comp):\n mask = intensity > cutoffH\n # print('norm length',np.sum(mask))\n norm_data = np.divide(pca_result[mask], intensity[mask][:,None])\n print('norm_data', np.min(norm_data), np.max(norm_data))\n pca_rebin = np.trunc((norm_data + 1) * base/2)\n print('rebin, min/mac', np.min(pca_rebin), np.max(pca_rebin))\n stream_1D = 0\n for comp in range(pca_comp):\n stream_1D = stream_1D + pca_rebin.T[comp]*base**comp\n return stream_1D, mask\n\n#################### Intensity ########################\n\ndef get_intensity_hist(intensity,N_bins = 100 ,N_sigma = 3):\n para = np.log(intensity[intensity > 0])\n histdata = plt.hist(para, bins = N_bins, color = 'gold')\n x, y = histdata[0], histdata[1][:-1]\n y = (y[1]-y[0])/2 + y\n assert len(x) == len(y)\n x_max = np.max(x)\n x_half = x_max//2\n mu = y[x == x_max]\n sigma = abs(y[abs(x - x_half).argmin()] -mu)\n cutoff_log = N_sigma* sigma + mu\n cutoff = int(np.exp(cutoff_log))\n peak_val = int(np.exp(mu))\n lower_sig = int(np.exp(mu - sigma))\n upper_sig = int(np.exp(mu + sigma))\n plt.axvline(mu, color = 'b', label = f'Peak = {peak_val}')\n plt.axvline(mu - sigma, color = 'cyan', ls = ':', label = f'-sigma = {lower_sig}')\n plt.axvline(mu+sigma, color = 'cyan', ls = ':', label = f'+sigma = {upper_sig}')\n plt.axvline(cutoff_log, color = 'r', label = f'3sigma = exp{np.round(cutoff_log,1)} = {cutoff}' )\n plt.axhline(x_half, color = 'cyan', ls = ':')\n plt.title('Histogram of Intensity Cutoff ')\n plt.xlabel('log(intensity)')\n plt.legend()\n return cutoff\n\n\n#################### 1D Stream #####################\ndef inverse_mapcode(stream_1D, base, pca_comp):\n stream_1D = np.array(stream_1D)\n inverted_pca = np.zeros((pca_comp,len(stream_1D)))\n for i in range(pca_comp):\n inverted_pca[i] = stream_1D % base\n stream_1D = stream_1D // base\n return inverted_pca\n\ndef process_stream_1D(stream_1D, base, pca_comp, topk ):\n c = Counter(stream_1D)\n HH = c.most_common(topk)\n exact_a = np.array(HH)\n exact_val, exact_freq = exact_a[:,0].astype('Int64'), exact_a[:,1].astype('Int64')\n exact_pca = inverse_mapcode(exact_val, base, pca_comp)\n exact_pd = pd.DataFrame(exact_pca.T, columns = range(pca_comp))\n exact_pd['freq'] = np.abs(exact_freq)\n exact_pd['val'] = exact_val\n if len(exact_pd) > 10000:\n print('exact_pd exceeding 10000, output top 10000 only')\n return exact_pd[:10000]\n # np.savetxt(f'{name}/exact_pdh', exact_pdh)\n return exact_pd\n\n# def process_stream_1D0(stream_1D, base, pca_comp, topk, percentage = 0.01 ):\n# c = Counter(stream_1D)\n# HH = c.most_common(topk)\n# exact_a = np.array(HH)\n# exact_val, exact_freq = exact_a[:,0].astype('Int64'), exact_a[:,1].astype('Int64')\n# exact_pca = inverse_mapcode(exact_val, base, pca_comp)\n# exact_pd = pd.DataFrame(exact_pca.T, columns = range(pca_comp))\n# exact_pd['freq'] = np.abs(exact_freq)\n# exact_pd['val'] = exact_val\n# high_cut = exact_pd['freq'][0]* percentage\n# print(high_cut)\n# exact_pdh = exact_pd[exact_pd['freq']> high_cut]\n# print('#exact_pdh', len(exact_pdh), high_cut)\n# print(exact_pd)\n# # np.savetxt(f'{name}/exact_pdh', exact_pdh)\n# return exact_pdh, exact_pd\n\n#################### UMAP ###########################\ndef process_umap(exact_pdh, pca_comp, scale = 500):\n umapH = uma.UMAP()\n umap_result = umapH.fit_transform(exact_pdh[list(range(pca_comp))])\n freqlist = exact_pdh['freq']\n lw = (freqlist/freqlist[0])**2\n u1 = umap_result[:,0]\n exact_pdh['u1'] = u1\n u2 = umap_result[:,1]\n exact_pdh['u2'] = u2\n plt.scatter(u1, u2, s = scale*lw)\n return None\n\n#################### Testing #######################\n\ndef test_mul_comb(mul_comb, pc, pca_comp):\n u,s,v = np.linalg.svd(mul_comb)\n assert np.allclose(u[:,:pca_comp], pc)\n plt.plot(np.log(s))\n plt.ylabel('log(eigenvalues)')\n plt.xlabel('layers')\n\n# def test_rebin(self, norm_data, mask, base, idx = 0, bg = -0.1):\n# masked_rebin = np.ones([pixel * num, pca_comp])* (bg)\n# pca_rebin = np.trunc((norm_data + 1) * base/2)\n# print('rebin, min/mac', np.min(pca_rebin), np.max(pca_rebin))\n# masked_rebin[mask] = pca_rebin\n# plot_rebin_data(self, masked_rebin, idx, bg, base)\n# return masked_rebin\n\n\n############################## Count Sketch #####################################\n\ndef process_countsketch(d, stream_1D, base, topk, col_range, row_range, device = 'cuda'):\n sketchs = {}\n for row in row_range: \n for col in col_range:\n val,freq = run_step_sketch(stream1D, d, col,row, topk, device)\n sketchs[f'{row}_{col}_val'] = val\n sketchs[f'{row}_{col}_freq'] = freq\n return val,freq\n# val,freq = process_countsketch(d, vec, base, topk, col_range, row_range)\n\ndef run_step_sketch(stream_1D, d, c,r,k, device = 'cuda'):\n csv = CSVec(d,c,r,k, device)\n stream_1D_tr = torch.tensor(stream_1D, dtype=torch.int64)\n cs.accumulateVec_heap(stream_1D_tr)\n cs_topk = csv.topk.cpu().numpy()\n cs_topk = cs_topk[cs_topk[:,0]>0]\n return cs_topk[:,0],cs_topk[:,1]\n\n \n\n# from __future__ import print_function\n# import time\n# import numpy as np\n# import pandas as pd\n# # from sklearn.datasets import fetch_mldata\n# from sklearn.decomposition import PCA\n# from sklearn.manifold import TSNE\n# %matplotlib inline\n# import matplotlib.pyplot as plt\n# from mpl_toolkits.mplot3d import Axes3D\n# import seaborn as sns\n# from matplotlib.colors import LogNorm\n# import umap.umap_ as uma\n# import math\n# from collections import Counter\n\n# ############################## Glueviz Functions #########################################\n# def get_cluster_idx(data0, sub_range, exact_pdh, col = 'col13'):\n# cluster = {}\n# i = 1\n# for subset in sub_range:\n# layer_data = data0.subsets[subset]\n# cluster[i] = layer_data[col].astype(int)\n# i+=1\n# exact_pdh['cluster'] = np.zeros(len(exact_pdh)).astype(int)\n# for key in range(1,max(sub_range)+2):\n# exact_pdh.loc[cluster[key],'cluster'] = int(key)\n# return None\n\n# def plot_umap_clusters(stream_1D, exact_pdhh, bg = -1 ):\n# HHvals = np.array(exact_pdhh['val'])\n# HHcluster = np.array(exact_pdhh['cluster'])\n# masked_streams = np.zeros(np.shape(stream_1D))\n# for idx, val in enumerate( HHvals): \n# label = HHcluster[idx]\n# masked_streams = np.where(stream_1D != val, masked_streams, label)\n# final_umap = np.ones(mask.shape) * bg\n# binary_umap = np.ones(mask.shape) * bg\n# masked_binary = (masked_streams > 0) * 1\n# final_umap[mask] = masked_streams\n# binary_umap[mask] = masked_binary\n# return final_umap, binary_umap, masked_streams \n\n\n# #################### Merger ###########################\n\n# def check_cluster(diff, base):\n# #TODO: check if we need to limit decode\n# if diff == 0:\n# return True\n# else:\n# decode = math.log(abs(diff), base)\n# same_cluster_query = np.floor(decode) == decode \n# return same_cluster_query\n\n# def get_merged_HHs(vals, base, limit):\n# merge_idx_dict = {}\n# val_l = len(vals)\n# clusters = np.zeros(val_l)\n# processed = [False] * val_l\n# cluster_dict= {}\n# color_idx = int(1 )\n# merged = False\n# for idx_1 in range(val_l):\n# if not processed[idx_1]:\n# val = vals[idx_1]\n# cluster_dict[f'{color_idx}'] = [val]\n# clusters[idx_1] = color_idx\n# for idx_2 in range(idx_1+1, val_l): \n# val_2 = vals[idx_2]\n# diff = abs(val - val_2)\n# if check_cluster(diff, base): \n# if not processed[idx_2]:\n# processed[idx_2] = True\n# else:\n# color_idx2 = int(clusters[idx_2])\n# if not merged: \n# if color_idx2 < color_idx:\n# # print(color_idx,color_idx2,val, val_2)\n# cluster_dict[f'{color_idx2}'] += cluster_dict[f'{color_idx}'] \n# cluster_dict[f'{color_idx}'] = []\n# clusters[clusters == color_idx] = color_idx2\n# color_idx0 = color_idx\n# color_idx = color_idx2\n# merged = True\n# else:\n# print('error')\n# else:\n# if color_idx2 != color_idx:\n# min_idx, max_idx = min( color_idx2, color_idx), max( color_idx2, color_idx)\n# if min_idx not in merge_idx_dict:\n# merge_idx_dict[min_idx] = set() \n# merge_idx_dict[min_idx].add(max_idx) \n# # color_idx, color_idx0 = min(color_idx2, color_idx), max(color_idx2, color_idx)\n# # # print(color_idx2, color_idx, color_idx0 )\n# # cluster_dict[f'{color_idx}'] += cluster_dict[f'{color_idx0}'] \n# # cluster_dict[f'{color_idx0}'] = [] \n# # clusters[clusters == color_idx0] = color_idx \n\n# ####################### assign values\n# cluster_dict[f'{color_idx}'] += [val_2] \n# clusters[idx_2] = color_idx\n# ############################## End idx_2 for loop ##############################\n# if merged:\n# color_idx = color_idx0\n# merged = False\n# else:\n# color_idx += 1 \n# # color_idx += 1\n# # print('color_idx',color_idx)\n# processed[idx_1] = True\n# if color_idx > limit:\n# print(f'Top {limit} color clusters found at {idx_1}, to continue increase limit' )\n# break\n# print(merge_idx_dict)\n# return clusters, cluster_dict, merge_idx_dict\n\n# def get_merged_pd(exact_pdh, base, limit = 10):\n# vals = exact_pdh['val']\n# val_l = len(vals)\n# clusters = np.zeros(val_l)\n# processed = [False] * val_l\n# color_idx = 1 \n# for idx_1 in range(val_l):\n# if not processed[idx_1]:\n# val = vals[idx_1]\n# clusters[idx_1] = color_idx\n# for idx_2 in range(idx_1+1, val_l): \n# val_2 = vals[idx_2]\n# diff = abs(val - val_2)\n# if check_cluster(diff, base):\n# clusters[idx_2] = color_idx\n# processed[idx_2] = True\n# color_idx += 1 \n# processed[idx_1] = True\n# if color_idx > limit:\n# print(f'Top {limit} color clusters after merger found, to continue increase limit' )\n# break\n# return exact_pdh\n\n\n#################### PCA ########################\n# def process_pca_DO0(data1Ds, pc, num, pca_comp):\n# with ThreadPoolExecutor() as executor: \n# futures = []\n# for idx in range(num):\n# futures.append(executor.submit(lambda x: run_step_pc_transform(x, data1Ds, pc), idx))\n# # print(f\" No.{idx} image is transformed\")\n# pca_results = np.zeros([1,pca_comp])\n# for future in as_completed(futures):\n# pca_result = future.result()\n# pca_results = np.vstack((pca_results,pca_result))\n# pca_results = pca_results[1:,:]\n# print('========= Intensity ==============')\n# intensity = (np.sum(pca_results**2, axis = 1))**0.5\n# return intensity, pca_results\n\n# def process_pca_DO(data1Ds, pc, num, base, pca_comp, N_bins = 100, N_sigma = 3 ):\n# pca_results = run_step_pc_transform(0, data1Ds, pc)\n# results = data1Ds[0]\n# for i in range(1,num):\n# pca_result = run_step_pc_transform(i, data1Ds, pc)\n# pca_results = np.vstack((pca_results,pca_result))\n# results = np.vstack((results, data1Ds[i]))\n# # pca_results = pca_results[1:,:]\n# print('========= Intensity ==============')\n# intensity = (np.sum(pca_results**2, axis = 1))**0.5\n# # cutoffH = np.mean(intensity).round()\n# cutoffH = run_step_cutoff(intensity, N_bins = 100, N_sigma = 3 )\n# print('cutoffH is set to be mean', cutoffH)\n# stream_1D, mask = run_step_norm(pca_results, intensity, cutoffH, base, pca_comp)\n# return stream_1D, mask\n","sub_path":"code/cancer/Execute116.py","file_name":"Execute116.py","file_ext":"py","file_size_in_byte":16890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"567950177","text":"import GoBackN.packet as packet\n# import socket\n# import sys\nimport _thread\nimport time\nimport GoBackN.filter as udt\n\nfrom GoBackN.timer import Timer\n\nPACKET_SIZE = 512\n# RECEIVER_ADDR = ('localhost', 8888)\n# SENDER_ADDR = ('localhost', 0)\nSLEEP_INTERVAL = 0.05\nTIMEOUT_INTERVAL = 0.5\nWINDOW_SIZE = 4\n\n# Shared resources across threads\nbase = 0\nmutex = _thread.allocate_lock()\nsend_timer = Timer(TIMEOUT_INTERVAL)\n\n\n# def set_send_addr(addr):\n# RECEIVER_ADDR = addr\n\n\n# Sets the window size\ndef set_window_size(num_packets):\n global base\n return min(WINDOW_SIZE, num_packets - base)\n\n\n# Send thread\ndef send(sock, filename, RECEIVER_ADDR):\n global mutex\n global base\n global send_timer\n\n # Open the file\n try:\n file = open(filename, 'rb')\n except IOError:\n print('Unable to open', filename)\n return\n\n # Add all the packets to the buffer\n packets = []\n seq_num = 0\n while True:\n data = file.read(PACKET_SIZE)\n if not data:\n break\n packets.append(packet.make(seq_num, data))\n seq_num += 1\n\n num_packets = len(packets)\n print('I Have:', num_packets)\n window_size = set_window_size(num_packets)\n next_to_send = 0\n base = 0\n\n # Start the receiver thread\n _thread.start_new_thread(receive, (sock,))\n\n while base < num_packets:\n mutex.acquire()\n # Send all the packets in the window\n while next_to_send < base + window_size:\n print('Sending packet', next_to_send)\n udt.send(packets[next_to_send], sock, RECEIVER_ADDR)\n next_to_send += 1\n\n # Start the timer\n if not send_timer.running():\n print('Starting timer')\n send_timer.start()\n\n # Wait until a timer goes off or we get an ACK\n while send_timer.running() and not send_timer.timeout():\n mutex.release()\n print('Sleeping')\n time.sleep(SLEEP_INTERVAL)\n mutex.acquire()\n\n if send_timer.timeout():\n # Looks like we timed out\n print('Timeout')\n send_timer.stop()\n next_to_send = base\n else:\n print('Shifting window')\n window_size = set_window_size(num_packets)\n mutex.release()\n\n # Send empty packet as sentinel\n udt.send(packet.make_empty(), sock, RECEIVER_ADDR)\n file.close()\n return \"Finish\"\n\n\n# Receive thread\ndef receive(sock):\n global mutex\n global base\n global send_timer\n\n while True:\n pkt, _ = udt.recv(sock)\n ack, _ = packet.extract(pkt)\n\n print('Got ACK', ack)\n if ack >= base:\n mutex.acquire()\n base = ack + 1\n print('Base updated', base)\n send_timer.stop()\n mutex.release()\n\n\n# # Main function\n# if __name__ == '__main__':\n# if len(sys.argv) != 2:\n# print('Expected filename as command line argument')\n# exit()\n#\n# sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n# sock.bind(SENDER_ADDR)\n# filename = sys.argv[1]\n#\n# send(sock, filename)\n# sock.close()\n","sub_path":"GoBackN/sender.py","file_name":"sender.py","file_ext":"py","file_size_in_byte":3121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"544030301","text":"#!python\nimport os\nimport numpy as np\nimport pandas as pd\nimport general_functions as gf\nimport argparse\nimport pdb\nparser = argparse.ArgumentParser()\nparser.add_argument('--trait', type=str, help='trait', default=None)\nargs = parser.parse_args()\n\nOUT_DIR = os.environ['OUT_DIR']\n## load trait condsigs\ncondsig = pd.read_csv(gf.out_dir+\"/condout/results/condsig_\"+args.trait+\"_gwas_normalised.tsv\", sep=\"\\t\")\ncondsig = gf.decompose_variantid(condsig['VARIANT'])\n\n\ndef get_partners(ld, var):\n partnersA = ld.loc[(ld['SNP_A'] == var) & (ld['R2'] > 0.8),\"SNP_B\"]\n partnersB = ld.loc[(ld['SNP_B'] == var) & (ld['R2'] > 0.8),\"SNP_A\"]\n partners = set(partnersB.tolist() + partnersA.tolist())\n return(list(partners))\n\ndef clump_function(partners, clumps, var):\n # if no clumps exist make the first one\n if clumps is None:\n clumps = pd.DataFrame({'VARIANT': partners+[var]})\n clumps['clump_id'] = 1\n return(clumps)\n\n # check if any partners already exist in a clump\n matching_clumps = []\n if len(partners) != 0:\n clumps_s = clumps.loc[clumps['VARIANT'].isin(partners),:]\n matching_clumps = clumps_s['clump_id'].unique().tolist()\n\n # if there are no matching clumps add this var and partners to new clump\n clumps_add = pd.DataFrame({'VARIANT': partners+[var]})\n if len(matching_clumps) == 0:\n clumps_add['clump_id'] = clumps['clump_id'].max()+1\n # if there is one matching clump merge into that one\n elif len(matching_clumps) == 1:\n clumps_add['clump_id'] = matching_clumps[0]\n # if there are more than one matching clumps, merge them all into a new clump\n elif len(matching_clumps) > 1:\n clumps_add['clump_id'] = clumps['clump_id'].max()+1 \n clumps.loc[clumps['clump_id'].isin(matching_clumps),\"clump_id\"] = clumps['clump_id'].max()+1\n \n # append clumps_add into the dataframe\n clumps = clumps.append(clumps_add, ignore_index=True)\n return(clumps)\n\ncondsig.loc[condsig['chromosome'].isin(['X', 'XY']),\"chromosome\"] = 23\nclumps = None\nfor chrom in condsig['chromosome'].unique():\n ld = pd.read_csv(gf.out_dir+\"/condout/ldclump_dosage/dosage_\"+str(chrom)+\".ld\")\n ld = ld.loc[ld['SNP_A'].isin(condsig['VARIANT']),:]\n ld = ld.loc[ld['SNP_B'].isin(condsig['VARIANT']),:]\n ld = ld.loc[ld['SNP_A'] != ld['SNP_B'],:]\n\n condsig_s = condsig.loc[condsig['chromosome'] == chrom,:]\n\n for index, row in condsig_s.iterrows():\n partners = get_partners(ld, row['VARIANT'])\n clumps = clump_function(partners, clumps, row['VARIANT'])\n\nclumps = clumps.drop_duplicates()\nclumps.to_csv(OUT_DIR+\"/tao_clump/in_trait_clumps_\"+args.trait+\".csv\", index=None)\n","sub_path":"code/exact_conditional_analysis/clumping_algorithm_trait.py","file_name":"clumping_algorithm_trait.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"513937544","text":"import pygame\nimport sys\nimport random\n\n\ndef ball_animation():\n global ball_speed_x, ball_speed_y, player_one_score, player_two_score, score_time\n\n ball.x += ball_speed_x\n ball.y += ball_speed_y\n\n if ball.top <= 0 or ball.bottom >= screen_height:\n ball_speed_y *= -1\n\n if ball.left <= 0:\n player_two_score += 1\n score_time = pygame.time.get_ticks()\n\n if ball.right >= screen_width:\n player_one_score += 1\n score_time = pygame.time.get_ticks()\n\n if ball.colliderect(player_one) or ball.colliderect(player_two):\n ball_speed_x *= -1\n\n\ndef player_one_animation():\n player_one.y += player_one_speed\n\n if player_one.top <= 0:\n player_one.top = 0\n\n if player_one.bottom >= screen_height:\n player_one.bottom = screen_height\n\n\ndef player_two_animation():\n if player_two.top < ball.y:\n player_two.top += player_two_speed\n\n if player_two.bottom > ball.y:\n player_two.bottom -= player_two_speed\n\n if player_two.top <= 0:\n player_two.top = 0\n\n if player_two.bottom >= screen_height:\n player_two.bottom = screen_height\n\n\ndef ball_start():\n global ball_speed_x, ball_speed_y, score_time\n\n current_time = pygame.time.get_ticks()\n ball.center = (screen_width/2, screen_height/2)\n\n if current_time - score_time < 700:\n number_three = game_font.render(\"3\", False, ball_color)\n screen.blit(number_three, (screen_width/2 - 10, screen_height/2 + 20))\n\n if 700 < current_time - score_time < 1400:\n number_two = game_font.render(\"2\", False, ball_color)\n screen.blit(number_two, (screen_width / 2 - 10, screen_height / 2 +20))\n\n if 1400 < current_time - score_time < 2100:\n number_one = game_font.render(\"1\", False, ball_color)\n screen.blit(number_one, (screen_width / 2 - 10, screen_height / 2 +20))\n\n if current_time - score_time < 2100:\n ball_speed_x, ball_speed_y = 0, 0\n else:\n ball_speed_y = 7 * random.choice((1, -1))\n ball_speed_x = 7 * random.choice((1, -1))\n score_time = None\n\n\n# General Setup\npygame.init()\nclock = pygame.time.Clock()\n\n# Main Window\nscreen_width = 1300\n\nscreen_height = 600\nscreen = pygame.display.set_mode((screen_width, screen_height))\npygame.display.set_caption('Ping Pong')\n\n# Game Rectangles\nball = pygame.Rect(screen_width/2 - 15, screen_height/2 - 15, 30, 30)\nplayer_one = pygame.Rect(screen_width - 20, screen_height/2 - 70, 10, 140)\nplayer_two = pygame.Rect(10, screen_height/2 - 70, 10, 140)\n\n# Game Colors\nbg_color = pygame.Color('purple')\nball_color = (255, 255, 255)\nplayer_one_color = (235, 85, 52)\nplayer_two_color = (110, 52, 235)\nvert_line_color = (0, 0, 0)\n\n# Game Variables\nball_speed_x = 7 * random.choice((1, -1))\nball_speed_y = 7 * random.choice((1, -1))\nplayer_one_speed = 0\nplayer_two_speed = 7\n\n# Text Variables\nplayer_one_score = 0\nplayer_two_score = 0\ngame_over = \"GAME OVER!\"\ngame_font = pygame.font.Font(\"freesansbold.ttf\", 42)\ngame_over_font = pygame.font.Font(\"freesansbold.ttf\", 100)\n\n# Score Timer\nscore_time = True\n\nwhile True:\n # handling output\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_DOWN:\n player_one_speed += 7\n if event.key == pygame.K_UP:\n player_one_speed -= 7\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_DOWN:\n player_one_speed -= 7\n if event.key == pygame.K_UP:\n player_one_speed += 7\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_DOWN:\n player_two_speed += 7\n if event.key == pygame.K_UP:\n player_two_speed -= 7\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_DOWN:\n player_two_speed -= 7\n if event.key == pygame.K_UP:\n player_two_speed += 7\n\n\n # Game Logic\n ball_animation()\n player_one_animation()\n player_two_animation()\n\n # Visuals\n screen.fill(bg_color)\n pygame.draw.rect(screen, player_one_color, player_one)\n pygame.draw.rect(screen, player_two_color, player_two)\n pygame.draw.ellipse(screen, ball_color, ball)\n pygame.draw.aaline(screen, vert_line_color, (screen_width/2, 0), (screen_width/2, screen_height))\n\n if score_time:\n ball_start()\n\n player_one_text = game_font.render(f\"{player_one_score}\", False, ball_color)\n screen.blit(player_one_text, (700, 450))\n\n player_two_text = game_font.render(f\"{player_two_score}\", False, ball_color)\n screen.blit(player_two_text, (560, 450))\n\n game_over_text = game_over_font.render(f\"{game_over}\", False, ball_color)\n screen.blit(player_two_text, (560, 450))\n\n # Updating the\n pygame.display.flip()\n clock.tick(60)\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"460487817","text":"from django.contrib.flatpages.models import FlatPage\nfrom django.db import models\nfrom django.utils import timezone\n\n\nclass Page(FlatPage):\n \"\"\"\n A static page that can be created/customized in admin.\n https://docs.djangoproject.com/en/3.2/ref/contrib/flatpages/\n \"\"\"\n\n meta_title = models.CharField(\n verbose_name=\"Titre (balise meta)\",\n max_length=100,\n blank=True,\n default=\"\",\n help_text=(\n \"Le titre qui sera affiché dans les SERPs. \"\n \"Il est recommandé de le garder < 60 caractères. \"\n \"Laissez vide pour réutiliser le titre de la page.\"\n ),\n )\n meta_description = models.TextField(\n verbose_name=\"Description (balise meta)\",\n max_length=255,\n blank=True,\n default=\"\",\n help_text=(\"La description qui sera affichée dans les SERPs. \" \"À garder < 150 caractères.\"),\n )\n\n created_at = models.DateTimeField(verbose_name=\"Date de création\", default=timezone.now)\n updated_at = models.DateTimeField(verbose_name=\"Date de modification\", auto_now=True)\n","sub_path":"lemarche/pages/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"552111329","text":"from itertools import combinations_with_replacement as cwr\n\ndef lazyGen (noRolls, maxDiceValue) :\n combinations = cwr([x for x in range(1, maxDiceValue+1)][::-1], noRolls)\n return combinations\n\ndef compareHands (player, dm, rollsPerHand) :\n rollWins = 0\n rollLoses = 0\n for roll in range(rollsPerHand) :\n if player[roll] > dm[roll] :\n rollWins += 1\n elif dm[roll] > player[roll]:\n rollLoses += 1\n else:\n if len(player) > len(dm):\n rollWins += 1\n elif len(dm) > len(player):\n rollLoses += 1\n if rollWins >= rollLoses :\n return 'win'\n else :\n return 'lose'\n\ndef legacyCompareHands(player, dm, rollsPerHand):\n rollWins = 0\n rollLoses = 0\n for roll in range(rollsPerHand) :\n if player[roll] >= dm[roll] :\n rollWins += 1\n else:\n rollLoses += 1\n if rollWins >= rollLoses :\n return 'win'\n else :\n return 'lose'\n\ndef calculateOutcomes(playerDiceNo, dmDiceNo, diceFace, legacy=False, verbose=False):\n '''\n Takes a number of dice for both player & DM as well as a dice type and returns win percentage\n '''\n wins = 0\n losses = 0\n rollCounter = 0\n leastRolls = min(playerDiceNo, dmDiceNo)\n playerArray = list(lazyGen(playerDiceNo, diceFace))\n dmArray = list(lazyGen(dmDiceNo, diceFace))\n\n comparitor = legacyCompareHands if legacy else compareHands\n\n for playerHand in playerArray :\n for dmHand in dmArray :\n rollCounter += 1\n outcome = comparitor(playerHand, dmHand, leastRolls)\n\n if verbose:\n print (playerHand, \"vs\", dmHand, \": player\", outcome)\n\n if outcome == 'win':\n wins += 1\n elif outcome == 'lose':\n losses += 1\n if verbose:\n print(\"Aggregate result:\", wins, \"successes,\", losses, \"failures of\", rollCounter, \"rolls. \\nScenario Win:Loss ratio:\", wins/losses, \"\\nProbability of success:\", 100*wins/rollCounter, \"%\")\n\n return wins / rollCounter","sub_path":"breakawayProbability.py","file_name":"breakawayProbability.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"18204555","text":"# -*- coding: utf-8 -*-\n\nimport mock\nimport time\nimport unittest\n\nfrom datetime import datetime\nfrom intercom import Intercom\nfrom intercom import Contact\nfrom mock import patch\nfrom nose.tools import istest\nfrom nose.tools import eq_\nfrom nose.tools import ok_\nfrom tests.unit import get_contact\n\n\nclass ContactTest(unittest.TestCase):\n \"\"\"\n Contacts are so similar to users that we only perform some basic coverage\n \"\"\"\n @istest\n def it_to_dict_itself(self):\n created_at = datetime.utcnow()\n contact = Contact(\n email=\"jim@example.com\", user_id=\"12345\",\n created_at=created_at, name=\"Jim Bob\")\n as_dict = contact.to_dict\n eq_(as_dict[\"email\"], \"jim@example.com\")\n ok_(as_dict[\"user_id\"])\n eq_(as_dict[\"created_at\"], time.mktime(created_at.timetuple()))\n eq_(as_dict[\"name\"], \"Jim Bob\")\n\n @istest\n def it_allows_update_last_request_at(self):\n payload = {\n 'user_id': '1224242',\n 'update_last_request_at': True,\n 'custom_attributes': {}\n }\n with patch.object(Intercom, 'post', return_value=payload) as mock_method:\n Contact.create(update_last_request_at=True)\n mock_method.assert_called_once_with(\n '/contacts/', update_last_request_at=True)\n\n @istest\n def it_fetches_a_contact(self):\n with patch.object(Intercom, 'get', return_value=get_contact()) as mock_method: # noqa\n contact = Contact.find(email='somebody@example.com')\n eq_(contact.email, 'bob@example.com')\n eq_(contact.name, 'Joe Schmoe')\n mock_method.assert_called_once_with('/contacts', email='somebody@example.com') # noqa\n\n @istest\n # @httpretty.activate\n def it_saves_a_contact_always_sends_custom_attributes(self):\n contact = Contact(email=\"jo@example.com\")\n\n body = {\n 'email': 'jo@example.com',\n 'user_id': 'i-1224242',\n 'custom_attributes': {}\n }\n\n with patch.object(Intercom, 'post', return_value=body) as mock_method:\n contact.save()\n eq_(contact.email, 'jo@example.com')\n eq_(contact.custom_attributes, {})\n mock_method.assert_called_once_with(\n '/contacts',\n email=\"jo@example.com\",\n custom_attributes={})\n\n @istest\n def it_can_save_a_contact_with_a_none_email(self):\n contact = Contact(\n email=None,\n companies=[{'company_id': 6, 'name': 'Intercom'}])\n body = {\n 'custom_attributes': {},\n 'email': None,\n 'user_id': 'i-1224242',\n 'companies': [{\n 'company_id': 6,\n 'name': 'Intercom'\n }]\n }\n with patch.object(Intercom, 'post', return_value=body) as mock_method:\n contact.save()\n ok_(contact.email is None)\n eq_(contact.user_id, 'i-1224242')\n mock_method.assert_called_once_with(\n '/contacts',\n email=None,\n companies=[{'company_id': 6, 'name': 'Intercom'}],\n custom_attributes={})\n\n @istest\n def it_deletes_a_contact(self):\n contact = Contact(id=\"1\")\n with patch.object(Intercom, 'delete', return_value={}) as mock_method:\n contact = contact.delete()\n eq_(contact.id, \"1\")\n mock_method.assert_called_once_with('/contacts/1/')\n\n @istest\n def it_returns_the_total_number_of_contacts(self):\n with mock.patch.object(Contact, 'count') as mock_count:\n mock_count.return_value = 100\n eq_(100, Contact.count())\n","sub_path":"tests/unit/test_contact.py","file_name":"test_contact.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"357838512","text":"from pyprocessing import *\nimport random\n\nSIZE = 600\n\ndef create_ball(radius, dx, dy):\n x = random.randint(0, SIZE)\n y = random.randint(0, SIZE)\n return (x, y, dx, dy, radius)\n\ndef create_random_ball():\n dx = random.randint(1, 20)\n dy = random.randint(1, 20)\n radius = random.randint(1, 50)\n return create_ball(radius, dx, dy)\n\n#balls = [create_ball(10, 10, 12), create_ball(15, -15, -10), create_ball(25, 3, 4), create_ball(8, 8, 8), create_ball(50, 8, 2)]\n#balls = [(20,20,10,12,10),(100,50,-15,-10,15)]\n\n\n\nballs = []\nfor e in range(8):\n balls.append(create_random_ball())\n\n\n\ndef setup():\n size(SIZE, SIZE)\n ellipseMode(CENTER)\n noStroke()\n\ndef draw():\n fill(200,50)\n rect(0,0, SIZE, SIZE)\n fill(0)\n for i in range(len(balls)):\n x,y,dx,dy,r = balls[i]\n x += dx\n if constrain(x,r,SIZE-r) != x: dx = -dx\n y += dy\n if constrain(y,r,SIZE-r) != y: dy = -dy\n balls[i] = x,y,dx,dy,r\n ellipse(x,y,r,r)\n\nrun()\n","sub_path":"balls.py","file_name":"balls.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"66990847","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 3 22:37:03 2019\n\n@author: fly\n\"\"\"\n\nimport tarfile\nimport os\n#import numpy as np\n#import cv2\nimport time\nimport subprocess as sp\nfrom datetime import datetime\nimport re\nimport threading as th\nimport imageLegTwitchBaseFunctions_tmp_20190717_flyPC as imLegTw\n\n\n\ndef present_time():\n now = datetime.now()\n return now.strftime('%Y%m%d_%H%M%S')\n\ndef natural_sort(l): \n convert = lambda text: int(text) if text.isdigit() else text.lower() \n alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] \n return sorted(l, key = alphanum_key)\n\ndef makeDirs(dirPath, printArg, printEnd='\\n'):\n try:\n os.makedirs(dirPath)\n except FileExistsError:\n print(printArg, end=printEnd)\n #print('Output directory already exists')\n\ndef getDirList(inDir, getAbsolutePath = True):\n if getAbsolutePath:\n return natural_sort([ os.path.join(inDir,name) for name in os.listdir(inDir) \\\n if os.path.isdir(os.path.join(inDir, name))])\n else:\n return natural_sort([name for name in os.listdir(inDir) \\\n if os.path.isdir(os.path.join(inDir, name))])\n\ndef getFileList(inDir, fileExt):\n return natural_sort([ os.path.join(inDir,name) for name in os.listdir(inDir) \\\n if os.path.isfile(os.path.join(inDir, name)) and fileExt in name])\n\n\ndef ffmpegCommand(fps, nThreads, codec, outfname):\n '''\n creates a ffmpeg command for subprocess\n '''\n command = [ 'ffmpeg',\n '-r', str(fps), # FPS of the output video file\n '-i', 'pipe:0', # The imput comes from a pipe\n '-an', # Tells FFMPEG not to expect any audio\n '-threads', str(nThreads), # define number of threads for parallel processing\n '-loglevel', 'error', # silence the output of ffmpeg to error only\n '-vcodec', codec, # specify the codec to be used for vidoe encoding\n '-y', # overwrite the existing file without asking\n outfname # name of the output file\n ] \n return command\n\ndef tarReadtoDict(tarName, nCurThrds):\n '''\n read contents of the imageData tar folder into a dict\n '''\n print('Reading tar file from %s # Current Threads: %d '%(tarName, nCurThrds))\n readTime = time.time()\n tar = tarfile.open(tarName,'r|') \n tarStack = {}\n for f in tar:\n if f.isfile():\n c = tar.extractfile(f).read()\n fname = f.get_info()['name']\n tarStack[fname] = c\n tar.close()\n print('Read %s at %s in: %.02f Seconds, # Current Threads: %d '%(\\\n tarName, present_time(), (time.time()-readTime), nCurThrds))\n return tarStack\n \ndef DictToMovFFMPEG(imDataDict, fps, nThreads, codec, outFname):\n '''\n Writes the image data in imDataDict to a movie using subprocess 'ffmpeg'\n '''\n writeTime = time.time()\n print('Writing AVI file %s by %s'%(outFname, th.currentThread().getName()))\n imNames = natural_sort(imDataDict.keys())\n ffmpegCmd = ffmpegCommand(fps, nThreads, codec=codec, outfname=outFname)\n pipe = sp.Popen(ffmpegCmd, stdin=sp.PIPE)\n for i,f in enumerate(imNames):\n im = imDataDict[f]\n pipe.stdin.write(im) # https://gist.github.com/waylan/2353749\n pipe.stdin.close()\n print('Wrote %s at %s in: %.02f Seconds by %s'%\n (outFname, present_time(), (time.time()-writeTime), th.currentThread().getName()))\n thread_available.set()\n\n#!/usr/bin/env python\nimport sys\nimport os\nimport re\n\n#t = os.popen('ffmpeg -v 5 -i \"%s\" -f null - 2>&1' % sys.argv[1]).read()\n#t = re.sub(r\"frame=.+?\\r\", \"\", t)\n#t = re.sub(r\"\\[(.+?) @ 0x.+?\\]\", \"[\\\\1]\", t)\n#print t\n#\n\n#baseDir ='/media/data_ssd/'\n\ninDir ='/media/fly/ncbsStorage/twitchData'\noutDir = '/media/data_ssd/rawMovies'\n\n#inDir ='/media/data_ssd/tmp'\n#outDir = '/media/data_ssd/rawMovies_'\n\nnThreads = 8\nnSubProcess = 4\n\n\nfps = 100\ncodec = 'libx264'\nimFolder = 'imageData'\ntarExt = '.tar'\nmovExt = '.avi'\n\nprint('----- Started at %s'%present_time())\n\nnCurThrds = th.active_count()\nthread_available = th.Event()\n\ni = 0\ngenotypeDirs = getDirList(inDir, getAbsolutePath = True)\nfor gtDir in genotypeDirs:\n for d in getDirList(gtDir, getAbsolutePath = True):\n if imFolder in getDirList(d, getAbsolutePath = False):\n baseDir = os.path.join(d, imFolder)\n tarList = getFileList(baseDir, tarExt)\n if len(tarList)>0:\n outMovDir = os.path.join(outDir, *(baseDir.split(os.sep)[-3:]))\n if os.path.isdir(outMovDir):\n print('--------- Processing directory: %s ---------'%d)\n # makeDirs(outMovDir, printArg = 'Output directory already exists')\n outFlist = imLegTw.getFiles(outMovDir, '*.avi')\n for tarFname in tarList:\n fname = tarFname.split(os.sep)[-1].split('.')[0]\n outFname = os.path.join(outMovDir, fname+movExt)\n if outFname in outFlist:\n i += 1\n print(i, tarFname)\n pipe = sp.Popen('ffmpeg -v 5 -i \"%s\" -f null - 2>&1' % outFname, stdout=sp.PIPE)\n out, err = pipe.communicate()\n errcode = pipe.returncode\n print(out)\n print(errcode)\n \n# print(tarFname, '\\n', outFname, '\\n', fname)\n# makeDirs(outMovDir, printArg='', printEnd='')\n# nCurThrds = th.active_count()\n# if nCurThrds>=nSubProcess:\n# print('\\n====> Waiting for a thread to finish, Total threads running: %d , --- at %s'\\\n# %(nCurThrds, present_time()))\n# thread_available.wait()\n# imStackDict = tarReadtoDict(tarFname, nCurThrds)\n# t = th.Thread(target = DictToMovFFMPEG, args = (imStackDict, fps, nThreads, codec, outFname, ))\n# t.start()\n# thread_available.clear()\n#t.join()\n\n\na = '/media/fly/ncbsStorage/twitchData/P0163_noTempShift/20170407_013754_P0163xTrpA1/imageData/20170408_123753.tar'\n\n\n#genotypeDirs = getDirList(inDir, getAbsolutePath = True)\n#for gtDir in genotypeDirs:\n# for d in getDirList(gtDir, getAbsolutePath = True):\n# if imFolder in getDirList(d, getAbsolutePath = False):\n# baseDir = os.path.join(d, imFolder)\n# tarList = getFileList(baseDir, tarExt)\n# if len(tarList)>0:\n# outMovDir = os.path.join(outDir, *(baseDir.split(os.sep)[-3:]))\n# print('--------- Processing directory: %s ---------'%d)\n# makeDirs(outMovDir, printArg = 'Output directory already exists')\n# for tarFname in tarList:\n# outFname = os.path.join(outMovDir, tarFname.split(os.sep)[-1].split('.')[0]+movExt)\n# makeDirs(outMovDir, printArg='', printEnd='')\n# nCurThrds = th.active_count()\n# if nCurThrds>=nSubProcess:\n# print('\\n====> Waiting for a thread to finish, Total threads running: %d , --- at %s'\\\n# %(nCurThrds, present_time()))\n# thread_available.wait()\n# imStackDict = tarReadtoDict(tarFname, nCurThrds)\n# t = th.Thread(target = DictToMovFFMPEG, args = (imStackDict, fps, nThreads, codec, outFname, ))\n# t.start()\n# thread_available.clear()\n#t.join()\n\n\n\n\n\n","sub_path":"movieFromTarCheckAvi_20190725.py","file_name":"movieFromTarCheckAvi_20190725.py","file_ext":"py","file_size_in_byte":7823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"12750681","text":"# From: https://pythonprogramming.net/python-port-scanner-sockets/\n\nimport socket\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver = 'google.com'\n\ndef pscan(port) :\n try:\n s.connet((server,port))\n return True\n except:\n return False\n\nfor x in range(1,26):\n if pscan(x):\n print('Port',x,'is open')\n else:\n print('Port',x,'is closed')\n\n","sub_path":"PythonPortScanner2.py","file_name":"PythonPortScanner2.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"222581341","text":"class Node:\n def __init__(self, value=None):\n self.value = value\n self.next_node = None\n\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n self.length = 0\n\n def append_node(self, value):\n self.length += 1\n new_node = Node(value)\n if self.tail:\n if self.head:\n self.head.next_node = new_node\n self.head = new_node\n else:\n self.tail.next_node = new_node\n self.head = new_node\n\n else:\n self.tail = new_node\n\n def get_node(self, index):\n node = self.tail\n if index == 0:\n return node.value\n elif index >= self.length:\n print('index out of range')\n return None\n else:\n for _ in range(index):\n node = node.next_node\n return node.value\n\n def pop_node(self, index):\n if index == 0:\n self.tail = self.tail.next_node\n elif index >= self.length:\n print('index out of range')\n return None\n else:\n node = self.tail\n for _ in range(index - 1):\n node = node.next_node\n node.next_node = node.next_node.next_node\n # node.next_node.next_node = None\n self.length -= 1\n\n def print_list(self):\n node = self.tail\n for _ in range(self.length):\n print(node.value)\n node = node.next_node\n\n\nfoo = LinkedList()\nfoo.append_node(1)\nfoo.append_node(2)\nfoo.append_node(\"a\")\nfoo.append_node(4)\nfoo.append_node(5)\n\n\nfoo.print_list()\nfoo.pop_node(5)\nprint('new list:')\nfoo.print_list()\n","sub_path":"draft/array.py","file_name":"array.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"626908047","text":"#!/usr/bin/python\nfrom datetime import datetime\nfrom datetime import timedelta\nimport datetime\nfrom stravalib.client import Client\nimport tweepy\n\nclass Consumer:\n @property\n def client_code(self):\n return 'xxx'\n\n @property\n def client_secret(self):\n return 'xxx'\n\nclass StravaUser:\n @property\n def StravaUserId(self):\n\t\t#julesjoseph\n return 999\n\n @property\n def StravaAccessToken(self):\n access_token = Client().exchange_code_for_token(client_id=1237, client_secret='xxx', code='xxx')\n return access_token\n\n @property\n def TwitterName(self):\n return 'xxx'\n @property\n def TwitterAccessCode(self):\n return 'xxxn'\n\n @property\n def TwitterAccessSecret(self):\n return 'xxx'\n\n#date helper methods\ndef GetCurrentDate():\n return datetime.now().date()\n\ndef GetLastWeekStart():\n day = datetime.now().date()\n lastWeekStart = day - timedelta(days=day.weekday()) + timedelta(days=0, weeks=-1)\n return datetime(lastWeekStart.year, lastWeekStart.month, lastWeekStart.day, 0, 0, 0)\n\ndef GetLastWeekEnd():\n day = datetime.now().date()\n lastWeekEnd = day - timedelta(days=day.weekday()) + timedelta(days=6, weeks=-1)\n return datetime(lastWeekEnd.year, lastWeekEnd.month, lastWeekEnd.day, 23, 59, 59)\n\ndef monday_test():\n today = datetime.date.today()\n weekday = today.weekday()\n if (weekday == 0):\n sendSummary()\n else:\n print(\"It's not Monday\")\n\n\ndef sendsummary():\n stravaUser = StravaUser()\n consumer = Consumer()\n\n print(\"StravaUserId %d\" % stravaUser.StravaUserId)\n print(\"StravaAccessToken %s\" % stravaUser.StravaAccessToken)\n print(\"TwitterName %s\" % stravaUser.TwitterName)\n print(\"TwitterAccessCode %s\" % stravaUser.TwitterAccessCode)\n print(\"GetLastWeekStart %s\" % GetLastWeekStart())\n print(\"GetLastWeekEnd %s\" % GetLastWeekEnd())\n\n stravaClient = Client()\n stravaClient.access_token = stravaUser.StravaAccessToken\n athlete = stravaClient.get_athlete()\n print(athlete.email)\n\n #this method does not allow you to pass both before and after dates?\n #can we safely assume that 100 activities will cover at least one week?\n activities = stravaClient.get_activities(after=GetLastWeekStart(), limit=100)\n\n totalDistance = []\n totalTime = []\n rideCount = 0\n for activity in activities:\n if activity.start_date_local < GetLastWeekEnd():\n rideCount=rideCount+1\n totalDistance.append(float(activity.distance))\n totalTime.append(activity.moving_time)\n\n sdistance = sum(totalDistance)/1000\n stime = sum(totalTime, timedelta())\n saverage = sdistance/(float(stime.seconds)/float(3600))\n\n distanceText = '{:.2f}'.format(sdistance)\n averageSpeedText = '{:.2f}'.format(saverage)\n\n status = 'Last Week\\'s #Strava: {rides} rides, {distance} km in {time} at {average} kmh'.format(rides=rideCount, distance=distanceText, time=stime, average=averageSpeedText)\n\n print(status)\n # create bot - veckostat twitter app\n #consumer key/consumer secret\n auth = tweepy.OAuthHandler(consumer.client_code, consumer.client_secret)\n\n #julesjoseph\n auth.set_access_token(stravaUser.TwitterAccessCode, stravaUser.TwitterAccessSecret)\n\n #api = tweepy.API(auth)\n #api.update_status(status)\n\nif __name__ == '__main__':\n monday_test()\n","sub_path":"weekly-strava-summary.py","file_name":"weekly-strava-summary.py","file_ext":"py","file_size_in_byte":3376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"356625976","text":"import argparse\nimport game\nimport player\n\n\nclass Parser():\n \"\"\"\n Handles the commands given by the user, including tracking the list\n of games running and creating/ending games when necessary.\n\n Limitations:\n - Options shouldn't be specified multiple times in the same command,\n that will result in weird behaviour. It generally doesn't make\n sense to do so, but even when it maybe does, it is not guaranteed\n to work as expected.\n - Players can only participate in one game at a time.\n \"\"\"\n\n def __init__(self):\n self.games = {}\n self.players = {}\n self.parser = argparse.ArgumentParser()\n self.parser.add_argument('-c', '--create', nargs='?', const='GAME_')\n self.parser.add_argument('-j', '--join')\n self.parser.add_argument('-t', '--tag')\n self.parser.add_argument('-s', '--shuffle', action='store_true')\n self.parser.add_argument('-d', '--deal', type=int)\n self.parser.add_argument('-f', '--flop', action='store_true')\n self.parser.add_argument('-o', '--overturn', nargs='?', const=1,\n type=int)\n self.parser.add_argument('-q', '--query', action='store_true')\n self.parser.add_argument('-p', '--players', action='store_true')\n self.parser.add_argument('-a', '--acquire', type=int)\n self.parser.add_argument('-b', '--bet', type=int)\n self.parser.add_argument('-w', '--win', type=int)\n self.parser.add_argument('-r', '--reveal', action='store_true')\n self.parser.add_argument('-m', '--msg', type=str, nargs='+')\n\n def create_game(self, bot, name='GAME_'):\n if name is 'GAME_':\n name += str(len(self.games))\n if name in self.games:\n return ('Game name \"%s\" collides with another game. '\n 'Please provide a different game name. ' % name)\n self.games[name] = game.Game(bot, name)\n return 'Created game %s ' % name\n\n def get_cur_game(self):\n if self.current_id in self.players:\n return self.players[self.current_id].game\n else:\n return None\n\n def join_game(self, game_id):\n if (self.current_id in self.players and\n self.players[self.current_id].game is not None):\n return ('You already appear to be in-game. Please quit game '\n 'before joining a new game. ')\n elif self.current_id not in self.players:\n self.players[self.current_id] = player.Player(self.current_id,\n self.current_id)\n if game_id not in self.games:\n return ('Game %s does not exist, please create new game or join '\n 'an existing game ' % game_id)\n self.games[game_id].add_player(self.players[self.current_id])\n self.players[self.current_id].game = self.games[game_id]\n return 'Successfully joined game %s ' % game_id\n\n def set_tag(self, player_tag):\n if self.current_id in self.players:\n self.players[self.current_id].tag = player_tag\n else:\n self.players[self.current_id] = player.Player(player_tag,\n self.current_id)\n return 'Successfully set tag to %s ' % player_tag\n\n def shuffle(self):\n game = self.get_cur_game()\n if game is not None:\n game.shuffle()\n return ''\n\n def deal(self, ncards):\n game = self.get_cur_game()\n if game is not None:\n game.deal(ncards)\n return ''\n\n def flip_flop(self):\n game = self.get_cur_game()\n if game is not None:\n game.flip_flop()\n return ''\n\n def overturn(self, ncards):\n game = self.get_cur_game()\n if game is not None:\n game.flip_cards(ncards)\n return ''\n\n def acquire(self, numpies):\n if self.current_id in self.players:\n return self.players[self.current_id].acquire(numpies)\n else:\n return 'Not a player'\n\n def bet(self, numpies):\n if self.current_id in self.players:\n return self.players[self.current_id].bet(numpies)\n else:\n return 'Not a player'\n\n def withdraw(self, numpies):\n if self.current_id in self.players:\n return self.players[self.current_id].withdraw(numpies)\n else:\n return 'Not a player'\n\n def reveal(self):\n if self.current_id in self.players:\n return self.players[self.current_id].reveal()\n else:\n return 'Not a player'\n\n def query_state(self):\n if self.current_id in self.players:\n return self.players[self.current_id].query_state()\n else:\n return 'Not a player, no info to query '\n\n def query_players(self):\n game = self.get_cur_game()\n if game is not None:\n return game.query_players()\n else:\n return 'Not participating in a valid game '\n\n def msg(self, msg):\n if self.current_id in self.players:\n return self.players[self.current_id].message_game(msg)\n else:\n return 'Not a player'\n\n def parse(self, command, player_id, bot):\n self.current_id = player_id\n try:\n known, unknown = self.parser.parse_known_args(command.split())\n except:\n return 'Internal error. Incorrect arguments? '\n ret = ''\n if known.create:\n ret += self.create_game(bot, known.create)\n if known.join:\n ret += self.join_game(known.join)\n if known.tag:\n ret += self.set_tag(known.tag)\n if known.shuffle:\n ret += self.shuffle()\n if known.deal is not None and known.deal > 0:\n ret += self.deal(known.deal)\n if known.flop:\n ret += self.flip_flop()\n if known.overturn is not None and known.overturn > 0:\n ret += self.overturn(known.overturn)\n if known.acquire is not None:\n ret += self.acquire(known.acquire)\n if known.bet is not None and known.bet > 0:\n ret += self.bet(known.bet)\n if known.win is not None and known.win > 0:\n ret += self.withdraw(known.win)\n if known.reveal:\n ret += self.reveal()\n if known.query:\n ret += self.query_state()\n if known.players:\n ret += self.query_players()\n if known.msg:\n ret += self.msg(' '.join(known.msg))\n prefix = ''\n if len(unknown) > 0:\n if len(ret) > 0:\n prefix = '\\n'\n ret += prefix + 'Unknown arguments:'\n for opt in unknown:\n ret += ' ' + opt\n return ret\n","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":6789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"194055371","text":"# Set creds and headers\nera_user = \"@@{era_creds.username}@@\"\nera_pass = \"@@{era_creds.secret}@@\"\nheaders = {\"Content-Type\": \"application/json\", \"Accept\": \"application/json\"}\n\n# Set the URL and payload\nurl = \"https://@@{era_ip}@@:8443/era/v0.8/databases/provision\"\npayload = {\n \"databaseName\": \"@@{DB_NAME}@@\",\n \"databaseType\": \"postgres_database\",\n \"databaseDescription\": \"Postgres database provisioned by Calm Application @@{calm_application_name}@@\",\n \"clusterId\": \"@@{CLUSTER_ID}@@\",\n \"softwareProfileId\": \"@@{SOFTWARE_PROF_ID}@@\",\n \"computeProfileId\": \"@@{COMPUTE_PROF_ID}@@\",\n \"networkProfileId\": \"@@{NETWORK_PROF_ID}@@\",\n \"dbParameterProfileId\": \"@@{DB_PARAM_ID}@@\",\n \"provisionInfo\": [\n {\"name\": \"application_type\", \"value\": \"postgres_database\"},\n {\"name\": \"listener_port\", \"value\": \"5432\"},\n {\"name\": \"database_size\", \"value\": \"200\"},\n {\"name\": \"working_dir\", \"value\": \"/tmp\"},\n {\"name\": \"auto_tune_staging_drive\", \"value\": True},\n {\"name\": \"db_password\", \"value\": \"@@{db_password}@@\"},\n {\"name\": \"dbserver_name\", \"value\": \"PostgreSQL-@@{calm_time}@@\"},\n {\n \"name\": \"dbserver_description\",\n \"value\": \"Postgres database server provisioned by Calm Application @@{calm_application_name}@@\",\n },\n {\"name\": \"ssh_public_key\", \"value\": \"@@{db_public_key}@@\"},\n ],\n \"timeMachineInfo\": {\n \"name\": \"PostgreSQL-@@{calm_time}@@_TM\",\n \"description\": \"PostgreSQL-@@{calm_time}@@ time machine\",\n \"slaId\": \"@@{SLA_ID}@@\",\n \"schedule\": {\n \"continuousSchedule\": {\n \"enabled\": True,\n \"logBackupInterval\": 30,\n \"snapshotsPerDay\": 30,\n },\n \"snapshotTimeOfDay\": {\"hours\": 1, \"minutes\": 0, \"seconds\": 0},\n \"weeklySchedule\": {\"enabled\": True, \"dayOfWeek\": \"SUNDAY\"},\n \"monthlySchedule\": {\"enabled\": True, \"dayOfMonth\": 1},\n \"quartelySchedule\": {\n \"enabled\": True,\n \"startMonth\": \"JANUARY\",\n \"dayOfMonth\": 1,\n },\n \"yearlySchedule\": {\"enabled\": False, \"month\": \"DECEMBER\", \"dayOfMonth\": 1},\n },\n },\n}\n\n# Make the call and set the response operation ID to the variable\nresp = urlreq(\n url,\n verb=\"POST\",\n auth=\"BASIC\",\n user=era_user,\n passwd=era_pass,\n params=json.dumps(payload),\n headers=headers,\n)\nif resp.ok:\n print(\"CREATE_OPERATION_ID={0}\".format(json.loads(resp.content)[\"operationId\"]))\nelse:\n print(\n \"Post Database create request failed\",\n json.dumps(json.loads(resp.content), indent=4),\n )\n exit(1)\n","sub_path":"examples/OscarApp/scripts/postgres/precreate/4ProvisionDB.py","file_name":"4ProvisionDB.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"111325460","text":"from airflow import DAG\nfrom datetime import datetime\nimport airflow\n\nfrom bigquery_get_data import BigQueryGetDataOperator\nfrom airflow.operators.slack_operator import SlackAPIPostOperator\n\ndag = DAG(\n dag_id='godatafest',\n default_args={\n 'owner': 'GoDataDriven',\n 'start_date': airflow.utils.dates.days_ago(2)\n }\n)\n\nimport ast\nbq_fetch_data = BigQueryGetDataOperator(\n task_id='bq_fetch_data',\n sql=\"\"\"select author.name,\n count(*) as commits\n from `bigquery-public-data.github_repos.commits` \n where \"apache/airflow\" in unnest(repo_name)\n and EXTRACT(DATE FROM committer.date) >= DATE_SUB(CURRENT_DATE(), INTERVAL 7 DAY)\n group by author.name\n \n order by count(*) DESC\n LIMIT 10\"\"\",\n dag=dag\n)\n\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.models import Variable\n\n\ndef send_to_slack_func(execution_date, **context):\n ti = context['ti']\n\n v1 = ti.xcom_pull(key=None, task_ids='bq_fetch_data')\n print(type(v1))\n\n res = []\n\n for x in v1:\n res.append(\"*\" + x[0].encode('utf-8') + \"*\")\n\n execution = execution_date.to_date_string()\n execution_start = execution_date.subtract(days=7).to_date_string()\n print(execution)\n op = SlackAPIPostOperator(\n task_id=\"slack_post\",\n text=\", \".join(res) + \" were _really_ active last week! \" + str(execution_start) + \" - \" + str(execution),\n username=\"daniels_most_amazing_github_analyzer\",\n icon_url=\"https://www.petmd.com/sites/default/files/Acute-Dog-Diarrhea-47066074.jpg\",\n token=Variable.get(\"token\"), dag=dag)\n op.execute(context=context)\n\n\nsend_to_slack = PythonOperator(\n task_id='send_to_slack',\n python_callable=send_to_slack_func,\n provide_context=True,\n dag=dag,\n)\n\nbq_fetch_data >> send_to_slack\n","sub_path":"dags/dag2.py","file_name":"dag2.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"399185746","text":"\"\"\" utils.py\n\nSome utility functions for visualizing downloaded Facebook data.\n\nAuthor: Brian Tuan\nLast Modified: April 10, 2017\n\n\"\"\"\n\nimport glob\nimport re\n\nfrom lxml import html\nfrom jinja2 import Template\n\nfrom pprint import PrettyPrinter\np = PrettyPrinter()\npprint = p.pprint\n\n\n\"\"\"\nBased on Facebook download output as of April 7, 2017. \n\nModify this dict first when Facebook data download output structure changes.\nAlso modify this dict to extend data-scraping scope, if desired.\nEventual updates may refactor this config into an external JSON file.\n\nAt the topmost level of the interestingXPaths dictionary, we have:\n key: Basename of a specific *.htm file,\n value: List of xpaths of interest.\n\nEach element of the value list is another dictionary, with the following keys:\n name: The name to which this xpath corresponds to in the returned parsed dictionary,\n xpath: The xpath expression corresponding to the location of the data of interest,\n lambda: A lambda function used to format the data as desired. Use lambda x: x for identity.\n\nA not insignificant amount of logic is buried in nuanced XPath expressions. \nFor future extensions, a useful XPath reference is here: \n https://www.w3schools.com/xml/xpath_intro.asp\n\"\"\"\ninterestingXPaths = {\n 'index': [\n {\n 'name': \"ConnectedApps\",\n 'xpath': \"//tr[th='Apps']/td/ul/li\", \n 'lambda': lambda x: x.text_content(),\n },\n ],\n 'security': [\n {\n 'name': \"InferredLoginLocations\",\n 'xpath': \"//li[text()[contains(., 'Estimated location inferred from IP')]]\",\n 'lambda': lambda x: _parseInferredLocation(x.text_content()),\n },\n {\n 'name': \"RecognizedMachines\",\n 'xpath': \"//h2[text()='Recognized Machines']/following-sibling::ul[1]/li\",\n 'lambda': lambda x: _parseRecognizedMachines(x.text_content()),\n },\n {\n 'name': \"SecurityActivity\",\n 'xpath': \"//h2[text()='Administrative Records']/following-sibling::ul[1]/\" +\n \"li[text()[not(contains(., 'Checkpoint')) and not(contains(., 'Profile'))]]\",\n 'lambda': lambda x: _parseAdminRecords(x.text_content()),\n },\n ],\n 'ads': [\n {\n 'name': \"Advertisers\",\n 'xpath': \"//h2[text()='Advertisers with your contact info']/following-sibling::ul[1]/li\",\n 'lambda': lambda x: x.text_content(),\n }\n ],\n 'contact_info': [\n {\n 'name': \"Contacts\",\n 'xpath': \"//h2[text()='Address Book']/following-sibling::table[1]/tr/td[1]/text()\",\n 'lambda': lambda x: x,\n }\n ]\n}\n\n\ndef _parseInferredLocation(text):\n location = tuple(map(float, re.search('IP:[0-9., -]*', text).group()[len('IP: '):].split(',')))\n created = re.search('Created: .*', text).group()[len('Created: '):]\n if 'Updated' in created:\n created = created[:created.index('Updated')]\n return 'Accessed: ' + created, location[0], location[1]\n\n\ndef _parseRecognizedMachines(text):\n name = text[:text.index('Created: ')]\n time = text[text.index('Updated: ') + len('Updated: ') : text.index('IP Address')]\n ipaddr = text[text.index('IP Address: ') + len('IP Address: '): text.index('Browser')]\n return {'name': name, 'time': time, 'ip': ipaddr}\n \n\ndef _parseAdminRecords(text):\n action = text[:text.index('Created: ')]\n time = text[text.index('Created: ') + len('Created: '): text.index('IP Address: ')]\n ipaddr = text[text.index('IP Address: ') + len('IP Address: '): text.index('Cookie: ')]\n return {'action': action, 'time': time, 'ip': ipaddr}\n\n\ndef parseDirectory(dirname, verbose=False):\n \"\"\"\n Main workhorse function that trawls through all *.htm files in a directory.\n Returns parsedDict, a dictionary of interesting information specified by interestingXPaths\n \"\"\"\n parsedDict = {}\n for fname in glob.iglob(dirname + '/**/*.htm', recursive=True):\n if 'photos/' not in fname and 'messages' not in fname:\n basename = re.search('/[a-z_]*.htm', fname).group()[len('/'): -len('.htm')]\n if verbose:\n print('Importing {}...'.format(fname))\n\n tree = html.parse(fname)\n xpaths = interestingXPaths.get(basename, [])\n if verbose:\n print('\\t' + str(list(map(lambda x: x['name'], xpaths))))\n for xpath in xpaths:\n parsedDict[xpath['name']] = list(map(\n xpath['lambda'], \n tree.xpath(xpath['xpath'])\n ))\n\n if verbose:\n print()\n if verbose:\n print(\"Ingested data: {}\\n\".format(list(parsedDict.keys())))\n return parsedDict\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"545806845","text":"# coding:utf8\nfrom __future__ import print_function\nimport torch.optim as optim\nfrom torch import nn, optim, autograd\nfrom utils import *\nfrom utils import get_dataset_2D_env as get_dataset_2D\nfrom torchvision import transforms\nfrom models import *\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport sys\n\ndef mean_nll(logits, y):\n return F.nll_loss(torch.log(logits), y)\n\ndef penalty(logits, y):\n scale = torch.tensor(1.).cuda().requires_grad_()\n loss = mean_nll(logits * scale, y)\n grad = autograd.grad(loss, [scale], create_graph=True)[0]\n return torch.sum(grad**2)\n\ndef VAE_loss(recon_x, x, mu, logvar, args):\n \"\"\"\n pred_y: predicted y\n recon_x: generating images\n x: origin images\n mu: latent mean\n logvar: latent log variance\n q_y_s: prior\n beta: tradeoff params\n \"\"\"\n x = x * 0.5 + 0.5\n BCE = F.binary_cross_entropy(recon_x.view(-1, 3 * args.image_size ** 2), x.view(-1, 3 * args.image_size ** 2),\n reduction='mean')\n \n KLD = -0.5 * torch.mean(1 + logvar - mu ** 2 - logvar.exp())\n \n return BCE, KLD\n\n\ndef train(epoch, model, optimizer, dataloader, args):\n all_zs = np.zeros((len(dataloader.dataset), args.zs_dim))\n RECON_loss = AverageMeter()\n KLD_loss = AverageMeter()\n classify_loss = AverageMeter()\n all_loss = AverageMeter()\n accuracy = AverageMeter()\n batch_begin = 0\n model.train()\n args.fix_mu = 1\n args.fix_var = 1\n for batch_idx, (x, target, env, u) in enumerate(dataloader):\n if args.cuda:\n x, target, env, u = x.cuda(), target.cuda().long(), env.cuda().long(), u.cuda()\n loss = torch.FloatTensor([0.0]).cuda()\n\n recon_loss = torch.FloatTensor([0.0]).cuda()\n kld_loss = torch.FloatTensor([0.0]).cuda()\n cls_loss = torch.FloatTensor([0.0]).cuda()\n irm_loss = torch.FloatTensor([0.0]).cuda()\n for ss in range(args.env_num):\n if torch.sum(env == ss) <= 1:\n continue\n _, recon_x, mu, logvar, z, s, zs = model(x[env == ss,:,:,:], ss, feature=1, is_train = 1)\n pred_y = model.get_y_by_zs(mu, logvar, ss)\n recon_loss_t, kld_loss_t = VAE_loss(recon_x, x[env == ss,:,:,:], mu, logvar, args)\n cls_loss_t = F.nll_loss(torch.log(pred_y), target[env == ss])\n \n accuracy.update(compute_acc(pred_y.detach().cpu().numpy(), target[env == ss].detach().cpu().numpy()),\n pred_y.size(0))\n recon_loss = torch.add(recon_loss, torch.sum(env == ss) * recon_loss_t)\n kld_loss = torch.add(kld_loss, torch.sum(env == ss) * kld_loss_t)\n cls_loss = torch.add(cls_loss, torch.sum(env == ss) * cls_loss_t)\n recon_loss = recon_loss / x.size(0)\n kld_loss = kld_loss / x.size(0)\n cls_loss = cls_loss / x.size(0)\n\n RECON_loss.update(recon_loss.item(), x.size(0))\n KLD_loss.update(kld_loss.item(), x.size(0))\n classify_loss.update(cls_loss.item(), x.size(0))\n loss = torch.add(loss, args.alpha * recon_loss + args.beta * kld_loss + args.gamma * cls_loss)\n \n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n all_loss.update(loss.item(), x.size(0))\n \n \n if batch_idx % 10 == 0:\n args.logger.info(\n 'epoch [{}/{}], batch: {}, rec_loss:{:.4f}, kld_loss:{:.4f} cls_loss:{:.4f}, overall_loss:{:.4f},acc:{:.4f}'\n .format(epoch,\n args.epochs,\n batch_idx,\n RECON_loss.avg,\n KLD_loss.avg * args.beta,\n classify_loss.avg,\n all_loss.avg,\n accuracy.avg * 100))\n \n if args.model == 'VAE' or args.model == 'VAE_old' or args.model == 'sVAE' or \\\n args.model == 'VAE_f' or args.model == 'sVAE_f':\n all_zs = all_zs[:batch_begin]\n args.logger.info('epoch [{}/{}], loss:{:.4f}'.format(epoch, args.epochs, all_loss.avg))\n \n return all_zs, accuracy.avg\n\ndef evaluate(epoch, model, dataloader, args):\n model.eval()\n model.zero_grad()\n accuracy = AverageMeter()\n accuracy_init = AverageMeter()\n pred = np.zeros((dataloader.dataset.__len__(), args.num_classes))\n best_loss = 10000 * np.ones((dataloader.dataset.__len__(), 1))\n batch_begin = 0\n pred_pos_num = 0\n for batch_idx, (x, target, env, u) in enumerate(dataloader):\n if args.cuda:\n x, target, env, u = x.cuda(), target.cuda().long(), env.cuda().long(), u.cuda()\n pred_y_init, pred_y = model(x, is_train = 0, is_debug=1)\n pred_pos_num = pred_pos_num + np.where(np.argmax(np.array(pred_y.detach().cpu().numpy()). \\\n reshape((x.size(0), args.num_classes)), axis=1) == 1)[0].shape[0]\n accuracy_init.update(compute_acc(np.array(pred_y_init.detach().cpu().numpy()).\n reshape((x.size(0), args.num_classes)), target.detach().cpu().numpy()), x.size(0))\n accuracy.update(compute_acc(np.array(pred_y.detach().cpu().numpy()).\n reshape((x.size(0), args.num_classes)), target.detach().cpu().numpy()), x.size(0))\n\n batch_begin = batch_begin + x.size(0)\n args.logger.info('init_acc: %0.4f, after acc: %0.4f' % (accuracy_init.avg, accuracy.avg))\n return pred, accuracy.avg\n\ndef main():\n args = get_opt()\n \n args = make_dirs(args)\n logger = get_logger(args)\n logger.info(str(args))\n args.logger = logger\n other_info = {}\n\n if args.seed != -1:\n torch.manual_seed(args.seed)\n if args.cuda:\n torch.cuda.manual_seed(args.seed)\n train_loader = DataLoader(get_dataset_2D(root = args.root, args=args, fold='train',\n transform=transforms.Compose([\n transforms.RandomHorizontalFlip(p=0.5),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n\n ])),\n batch_size=args.batch_size,\n shuffle=True,\n num_workers=0,\n pin_memory=True,\n drop_last = True)\n test_loader = DataLoader(get_dataset_2D(root = args.root, args=args, fold='test',\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n\n ])),\n batch_size=args.test_batch_size,\n shuffle=False,\n num_workers=0,\n pin_memory=True)\n val_loader = None\n \n model = LaCIM_rho(in_channel=args.in_channel,\n zs_dim=args.zs_dim,\n num_classes=args.num_classes,\n decoder_type=1,\n total_env=args.env_num,\n args=args,\n ).cuda()\n\n if args.optimizer == 'sgd':\n optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.reg)\n else:\n optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.reg)\n\n pytorch_total_params = sum(p.numel() for p in model.parameters())\n print('model params: ', pytorch_total_params, '%0.4f M' % (pytorch_total_params / 1e6))\n\n\n best_acc = -1\n for epoch in range(1, args.epochs + 1):\n adjust_learning_rate(optimizer, epoch, args.lr, args.lr_decay, args.lr_controler)\n _, _ = train(epoch, model, optimizer, train_loader, args)\n\n is_best = 0\n pred_test, test_acc = evaluate(epoch, model, test_loader, args)\n if test_acc >= best_acc:\n best_acc = copy.deepcopy(test_acc)\n best_acc_ep = copy.deepcopy(epoch)\n is_best = 1\n logger.info('test acc: %0.4f, test_ep: %d, lr2: %0.5f, wd2: %0.5f, sample %d'\n % (test_acc, args.test_ep, args.lr2, args.reg2, args.sample_num))\n\n checkpoint(epoch, args.model_save_dir, model, is_best, other_info, logger)\n logger.info('epoch %d:, current test_acc: %0.4f, best_acc: %0.4f, at ep %d'\n %(epoch, test_acc, best_acc, best_acc_ep))\n logger.info('model save path: %s'%args.model_save_dir)\n logger.info('*' * 50)\n logger.info('*' * 50)\n \nif __name__ =='__main__':\n main()","sub_path":"real_world/LaCIM_rho.py","file_name":"LaCIM_rho.py","file_ext":"py","file_size_in_byte":8841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"429018214","text":"#!/usr/bin/env python3\n\nimport sys\n\ndef help():\n\tprint('''\n\t\tUsage:\n\t\t------------\n\t\tblast2gff.py -blast > \n\n\t\tDescription:\n\t\t------------\n\t\tConverts command-line blast tabular output (format 6 or 7) to GFF3 format.\n\t\tIf there are multiple HSPs in the blast file, only the first (assumed to have\n\t\tthe highest bit score) will be included in the output. The default blast\n\t\tformats 6 and 7 can be customized so as to include subject strand. This script\n\t\tassumes subject strand is the 13th field in the blast file.\n\n\t\tPrints GFF3 to stdout.\n\t\t\n\t\t''')\n\tsys.exit(0)\n\nargs = sys.argv\n\nif not '-blast' in args or len(args) != 3:\n\thelp()\n\nblast_fl_pth = args[args.index('-blast') + 1]\n\nprint('##gff-version 3\\n')\n\nsource = \"blastn\"\ntype = \"gene_part\"\nphase = \".\"\nlast_feat = \"\"\n\nwith open(blast_fl_pth) as blast_fl:\n\tfor line in blast_fl:\n\t\tif line.startswith(\"#\"):\n\t\t\tcontinue\n\t\telse:\n\t\t\tblast_line = line.strip().split()\n\t\t\tif last_feat == blast_line[0]:\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tlast_feat = blast_line[0] # so as to not use more that one HSP for each feature\n\t\t\t\n\n\t\t\tattr = \"ID={0}\".format(blast_line[0])\n\t\t\tseq_id = blast_line[1]\n\t\t\tstart = blast_line[8]\n\t\t\tend = blast_line[9]\n\t\t\tscore = blast_line[10]\n\t\t\tif blast_line[12] == \"plus\":\n\t\t\t\tstrand = \"+\"\n\t\t\telif blast_line[12] == \"minus\":\n\t\t\t\tstrand = \"-\"\n\t\t\t\tEND = end\n\t\t\t\tend = start\n\t\t\t\tstart = END\n\n\t\t\tprint(\"{0}\\t{1}\\t{2}\\t{3}\\t{4}\\t{5}\\t{6}\\t{7}\\t{8}\".format(seq_id, source, type, start, end, score, strand, phase, attr))\n","sub_path":"various/blast2gff.py","file_name":"blast2gff.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"194838146","text":"from __future__ import print_function\n\ndef remove_double(word):\n last = False\n nw = \"\"\n for c in word:\n if c != last:\n nw += c\n last = c\n return nw\n\ndef min_count(l):\n mini = 9999999\n temp = max(l)\n for i in xrange(temp):\n v = 0\n for j in l:\n v += abs(j - (temp - i))\n if v < mini:\n mini = v\n if v > mini:\n break\n return mini\n\ndef count_letter(word):\n i = 1\n l = word[0]\n while(len(word) > i and word[i] == l):\n i+=1\n word = word[i:]\n return i, word\n\nif __name__ == '__main__':\n T = int(raw_input())\n for pb_i in xrange(T):\n N = int(raw_input())\n words = []\n for i in xrange(N):\n words.append(raw_input())\n\n # is possible ?\n a = remove_double(words[0])\n c = False\n for word in words:\n if remove_double(word) != a:\n result = \"Fegla Won\"\n print(\"Case #{}: {}\".format(pb_i+1, result))\n c = True\n break\n if c:\n continue\n\n # diff\n result = 0\n for letter in a:\n occ = []\n for i in xrange(len(words)):\n count, words[i] = count_letter(words[i])\n occ.append(count)\n res = min_count(occ)\n result += res\n\n print(\"Case #{}: {}\".format(pb_i+1, result))","sub_path":"solutions_5751500831719424_1/Python/Mattgu74/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"574403874","text":"def userinputvalidations_searchword(): \n # Search Word - User Input, With Validation\n while True:\n searchword = input(\"Enter the search term: \")\n if searchword == \"\":\n print(\"Oops! That was not a valid search term. Try again...\")\n continue\n else:\n break \n return searchword\n\n\n\n","sub_path":"input_searchword.py","file_name":"input_searchword.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"260567012","text":"# An example of receiving signals in curio and threads\n# all at once using Curio's SignalSet functionality.\n\nfrom stario import *\nimport os\nimport signal\nimport threading\n\nasync def signal_task(label):\n async with SignalQueue(signal.SIGUSR1, signal.SIGUSR2, signal.SIGINT) as s:\n while True:\n signo = await s.get()\n print(label, 'got:', signo)\n if signo == signal.SIGINT:\n print(label, 'Goodbye!')\n break\n\ndef signal_thread(label):\n with SignalQueue(signal.SIGUSR1, signal.SIGUSR2, signal.SIGINT) as s:\n while True:\n signo = s.get()\n print(label, 'got:', signo)\n if signo == signal.SIGINT:\n print(label, 'Goodbye!')\n break\n\nasync def main():\n # Launch the async function in curio\n t1 = await spawn(signal_task, 'curio')\n\n # Launch an independent thread\n t2 = threading.Thread(target=signal_thread, args=('thread',))\n t2.start()\n \n print('Send me signals on PID', os.getpid())\n\n await t1.join()\n await run_in_thread(t2.join)\n\nif __name__ == '__main__':\n with enable_signals([signal.SIGUSR1, signal.SIGUSR2, signal.SIGINT]):\n run(main())\n\n \n \n","sub_path":"examples/multisignal.py","file_name":"multisignal.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"433631994","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n#\n# Copyright © 2017 crane \n#\n# Distributed under terms of the MIT license.\n\n\"\"\"\n\n\"\"\"\n\n# 还不能使用\n\nimport sys\n\n\ndef main():\n\targv = sys.argv\n\tassert( len(argv) == 2 and \"need a linkaddr for address\" )\n\n\thttp = arv[1]\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bin/add-plugins.py","file_name":"add-plugins.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"313256032","text":"a = 900\nb = 1000\n\nprint(\"\\tFollowing are the Prime numbers between\", a, \"and\", b,\"\\n\")\n\nfor num in range(a, b + 1):\n if num > 1:\n for i in range(2, num):\n if (num % i) == 0:\n break\n \n else:\n print(num, end =\" \")","sub_path":"Pfundamental Lab/Lab 6/Task 2.py","file_name":"Task 2.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"288764495","text":"from flask import Flask, Blueprint, request, jsonify,render_template\nfrom flask_cors import CORS\nfrom flask_mongoengine import MongoEngine\nfrom flask_jwt_extended import JWTManager\nfrom cryptography.fernet import Fernet\n\napp = Flask(__name__)\nCORS(app)\n\napp.config.from_object('config')\n\n#Initializing celery - Used to run long background tasks\nfrom app.celery_creater import make_celery\ncelery = make_celery(app)\n\nfernet = Fernet(str(app.config['FERNET_DASHBOARD_KEY']).encode())\n\njwt = JWTManager(app=app)\n\ndb = MongoEngine(app)\n\napi = Blueprint('api',__name__,url_prefix='/api')\n\nfrom app.user.controllers import user\napi.register_blueprint(user)\n\napp.register_blueprint(api)\n\n\n@app.errorhandler(404)\n@app.errorhandler(405)\ndef _handle_error(ex):\n if request.path.startswith('/api/'):\n return jsonify(error=str(ex)), ex.code\n else:\n return ex","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"84220910","text":"\"\"\"Nedelec elements on simplices.\n\nThese elements' definitions appear in https://doi.org/10.1007/BF01396415\n(Nedelec, 1980) and https://doi.org/10.1007/BF01389668 (Nedelec, 1986)\n\"\"\"\n\nfrom ..finite_element import CiarletElement\nfrom ..moments import make_integral_moment_dofs\nfrom ..polynomials import polynomial_set, Hcurl_polynomials\nfrom ..functionals import TangentIntegralMoment, IntegralMoment\nfrom .lagrange import Lagrange, VectorLagrange\nfrom .rt import RaviartThomas\n\n\nclass NedelecFirstKind(CiarletElement):\n \"\"\"Nedelec first kind Hcurl finite element.\"\"\"\n\n def __init__(self, reference, order, variant=\"equispaced\"):\n poly = polynomial_set(reference.tdim, reference.tdim, order - 1)\n poly += Hcurl_polynomials(reference.tdim, reference.tdim, order)\n dofs = make_integral_moment_dofs(\n reference,\n edges=(TangentIntegralMoment, Lagrange, order - 1,\n {\"variant\": variant}),\n faces=(IntegralMoment, VectorLagrange, order - 2, \"covariant\",\n {\"variant\": variant}),\n volumes=(IntegralMoment, VectorLagrange, order - 3, \"covariant\",\n {\"variant\": variant}),\n )\n\n super().__init__(reference, order, poly, dofs, reference.tdim, reference.tdim)\n self.variant = variant\n\n def init_kwargs(self):\n \"\"\"Return the kwargs used to create this element.\"\"\"\n return {\"variant\": self.variant}\n\n names = [\"Nedelec\", \"Nedelec1\", \"N1curl\"]\n references = [\"triangle\", \"tetrahedron\"]\n min_order = 1\n continuity = \"H(curl)\"\n\n\nclass NedelecSecondKind(CiarletElement):\n \"\"\"Nedelec second kind Hcurl finite element.\"\"\"\n\n def __init__(self, reference, order, variant=\"equispaced\"):\n poly = polynomial_set(reference.tdim, reference.tdim, order)\n\n dofs = make_integral_moment_dofs(\n reference,\n edges=(TangentIntegralMoment, Lagrange, order, {\"variant\": variant}),\n faces=(IntegralMoment, RaviartThomas, order - 1, \"covariant\", {\"variant\": variant}),\n volumes=(IntegralMoment, RaviartThomas, order - 2, \"covariant\", {\"variant\": variant}),\n )\n\n super().__init__(reference, order, poly, dofs, reference.tdim, reference.tdim)\n self.variant = variant\n\n def init_kwargs(self):\n \"\"\"Return the kwargs used to create this element.\"\"\"\n return {\"variant\": self.variant}\n\n names = [\"Nedelec2\", \"N2curl\"]\n references = [\"triangle\", \"tetrahedron\"]\n min_order = 1\n continuity = \"H(curl)\"\n","sub_path":"symfem/elements/nedelec.py","file_name":"nedelec.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"474728643","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('inventario', '0003_auto_20150622_1432'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Proveedor',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('creado', models.DateTimeField(auto_now_add=True)),\n ('modificado', models.DateTimeField(auto_now=True)),\n ('nombre', models.CharField(max_length=100)),\n ('encargado', models.CharField(max_length=100)),\n ('telefono', models.PositiveIntegerField(null=True, blank=True)),\n ('email', models.EmailField(max_length=254, null=True, blank=True)),\n ],\n options={\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='Sucursal',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('creado', models.DateTimeField(auto_now_add=True)),\n ('modificado', models.DateTimeField(auto_now=True)),\n ('nombre', models.CharField(max_length=100)),\n ('direccion', models.CharField(max_length=100)),\n ('telefono', models.PositiveIntegerField(null=True, blank=True)),\n ('email', models.EmailField(max_length=254, null=True, blank=True)),\n ('encargado', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'abstract': False,\n },\n ),\n migrations.RenameField(\n model_name='producto',\n old_name='actualizado',\n new_name='modificado',\n ),\n migrations.AddField(\n model_name='categoria',\n name='slug',\n field=models.SlugField(null=True, editable=False, blank=True),\n ),\n migrations.AddField(\n model_name='marca',\n name='slug',\n field=models.SlugField(null=True, editable=False, blank=True),\n ),\n migrations.AddField(\n model_name='producto',\n name='barcode',\n field=models.PositiveIntegerField(null=True, blank=True),\n ),\n migrations.AddField(\n model_name='producto',\n name='imagen',\n field=models.ImageField(null=True, upload_to=b'producto', blank=True),\n ),\n migrations.AddField(\n model_name='producto',\n name='slug',\n field=models.SlugField(null=True, editable=False, blank=True),\n ),\n migrations.AddField(\n model_name='producto',\n name='user',\n field=models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True),\n ),\n migrations.AlterField(\n model_name='producto',\n name='existencia',\n field=models.PositiveIntegerField(null=True, blank=True),\n ),\n migrations.AlterField(\n model_name='producto',\n name='nombre',\n field=models.CharField(unique=True, max_length=100),\n ),\n migrations.AddField(\n model_name='producto',\n name='proveedor',\n field=models.ManyToManyField(to='inventario.Proveedor', blank=True),\n ),\n migrations.AddField(\n model_name='producto',\n name='sucursal',\n field=models.ManyToManyField(to='inventario.Sucursal', blank=True),\n ),\n ]\n","sub_path":"company/apps/inventario/migrations/0004_auto_20150626_1002.py","file_name":"0004_auto_20150626_1002.py","file_ext":"py","file_size_in_byte":3822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"324478647","text":"from personal_assistant_cli.core.address_book.address_book import AddressBook\nfrom personal_assistant_cli.core.note_book.note_book import NoteBook\nfrom personal_assistant_cli.core.sort_manager.sort_manager import SortManager\nfrom personal_assistant_cli.core.context_analyzer.fuzz import check_command\n\nimport types\n\n\nclass ContextAnalyzer:\n\n def analyze(self, request: str) -> (type, types.FunctionType, str):\n \"\"\"\n Get string-request from user and return from this the following:\n - responsible_module - what module should do a command (AddressBook, NoteBook or SortManager);\n - command - a command for responsible_module;\n - user_data - everything else left in the string-request\n \"\"\"\n\n if request == \"\":\n return None, None, None\n\n responsible_module, command, user_data = None, None, None\n words = request.split()\n\n check_answer, check_text = check_command(\" \".join(words[0:2]))\n if check_answer:\n if check_text in [\"off\", \"help\", \"sort\"]:\n if check_text == \"sort\":\n words[0] = check_text\n else:\n request = check_text\n else:\n new_command_text = check_text.split()\n words[0], words[1] = new_command_text[0], new_command_text[1]\n request = \" \".join(words)\n\n if request == \"off\":\n responsible_module = \"main\"\n command = \"off\"\n elif request == \"help\":\n responsible_module = \"main\"\n command = \"help\"\n elif \"show birthday\" in request:\n responsible_module = AddressBook\n command = AddressBook.show_users_birthday\n user_data = \" \".join(words[2:])\n elif \"show record\" in request:\n responsible_module = AddressBook\n command = AddressBook.get_records\n user_data = \" \".join(words[2:])\n elif \"show note\" in request:\n responsible_module = NoteBook\n command = NoteBook.get_table\n user_data = \" \".join(words[2:])\n elif \"add tag\" in request:\n responsible_module = NoteBook\n command = NoteBook.add_tag_to_note\n user_data = \" \".join(words[2:])\n elif \"sort\" == words[0]:\n responsible_module = SortManager\n command = SortManager.sort\n user_data = \" \".join(words[1:])\n elif len(words) > 1:\n if \"record\" == words[1]:\n responsible_module = AddressBook\n if \"add\" == words[0]:\n command = AddressBook.add\n elif \"change\" == words[0]:\n command = AddressBook.change\n elif \"delete\" == words[0]:\n command = AddressBook.delete\n elif \"search\" == words[0]:\n command = AddressBook.filter\n\n user_data = \" \".join(words[2:])\n elif \"note\" == words[1]:\n responsible_module = NoteBook\n if \"add\" == words[0]:\n command = NoteBook.add\n elif \"change\" == words[0]:\n command = NoteBook.change\n elif \"delete\" == words[0]:\n command = NoteBook.delete\n elif \"filter\" == words[0]:\n command = NoteBook.filter_for_tags\n elif \"tag\" == words[0]:\n command = NoteBook.add_tag_to_note\n elif \"search\" == words[0]:\n command = NoteBook.search\n\n user_data = \" \".join(words[2:])\n\n return responsible_module, command, user_data\n","sub_path":"personal_assistant_cli/core/context_analyzer/context_analyzer.py","file_name":"context_analyzer.py","file_ext":"py","file_size_in_byte":3697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"569319241","text":"''' A Series of Tubes '''\n\ndef move_packet(direction, x_axis, y_axis):\n ''' Move the Packet in the Diagram '''\n\n return {\n 'up': [x_axis, y_axis - 1],\n 'down': [x_axis, y_axis + 1],\n 'left': [x_axis - 1, y_axis],\n 'right': [x_axis + 1, y_axis]\n }[direction]\n\ndef continue_direction(direction, diagram, x_axis, y_axis):\n ''' Checks to see if a change of direction is needed '''\n\n if direction == 'up':\n if y_axis > 0:\n if (diagram[y_axis - 1][x_axis] == '|') or (diagram[y_axis - 1][x_axis].isalpha()):\n return True\n elif direction == 'down':\n if y_axis < len(diagram) - 1:\n if (diagram[y_axis + 1][x_axis] == '|') or (diagram[y_axis + 1][x_axis].isalpha()):\n return True\n elif direction == 'left':\n if x_axis > 0:\n if (diagram[y_axis][x_axis - 1] == '-') or (diagram[y_axis][x_axis - 1].isalpha()):\n return True\n elif direction == 'right':\n if x_axis < len(diagram[0]) - 1:\n if (diagram[y_axis][x_axis + 1] == '-') or (diagram[y_axis][x_axis + 1].isalpha()):\n return True\n\n return False\n\ndef change_direction(direction, diagram, x_axis, y_axis):\n ''' Determine the next direction to take. '''\n\n new_direction = 'none'\n if direction == 'up' or direction == 'down':\n if x_axis > 0:\n if (diagram[y_axis][x_axis - 1] == '-') or (diagram[y_axis][x_axis - 1].isalpha()):\n new_direction = 'left'\n\n if x_axis < len(diagram[0]) - 1:\n if (diagram[y_axis][x_axis + 1] == '-') or (diagram[y_axis][x_axis + 1].isalpha()):\n new_direction = 'right'\n\n elif direction == 'right' or direction == 'left':\n if y_axis > 0:\n if (diagram[y_axis - 1][x_axis] == '|') or (diagram[y_axis - 1][x_axis].isalpha()):\n new_direction = 'up'\n\n if y_axis < len(diagram) - 1:\n if (diagram[y_axis + 1][x_axis] == '|') or (diagram[y_axis + 1][x_axis].isalpha()):\n new_direction = 'down'\n return new_direction\n\ndef main():\n ''' A Series of Tubes '''\n\n diagram = open('../puzzle_input.txt').read().split('\\n')\n\n x_axis = diagram[0].index('|')\n y_axis = 0\n direction = 'down'\n diagram_end = False\n steps = 0\n\n while not diagram_end:\n while True:\n if diagram[y_axis][x_axis] not in ['|', '-', '+']:\n if not diagram[y_axis][x_axis].isalpha():\n diagram_end = True\n break\n\n x_axis, y_axis = move_packet(direction, x_axis, y_axis)\n steps += 1\n\n if x_axis < 0 or x_axis >= len(diagram[0]) or y_axis < 0 or y_axis >= len(diagram):\n diagram_end = True\n break\n if diagram[y_axis][x_axis] == \"+\":\n if continue_direction(direction, diagram, x_axis, y_axis):\n continue\n else:\n break\n\n direction = change_direction(direction, diagram, x_axis, y_axis)\n if direction == 'none':\n diagram_end = True\n\n print(steps)\n\nif __name__ == '__main__':\n main()\n ","sub_path":"day19/python/solve_puzzle_day19_2.py","file_name":"solve_puzzle_day19_2.py","file_ext":"py","file_size_in_byte":3200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"83346960","text":"#encoding=utf-8\nimport pandas as pd\nimport time\nimport numpy as num\nimport ccxt\nimport talib as ta\nfrom email_util import *\n\na = 0\n\ndef strategy(name,zhouqi):\n global a\n if (a == 1):\n return\n gateio = ccxt.gateio()\n limit = 500\n current_time = int(time.time()//60*60*1000)\n\n if (zhouqi == '15m'):\n since_time = current_time - limit * 15 * 60 * 1000\n data = gateio.fetch_ohlcv(symbol=name,timeframe='15m', limit=500,since=since_time)\n zhouqi_ch = \"15分钟\"\n if (zhouqi == '1h'):\n since_time = current_time - limit * 1* 60 * 60 * 1000\n data = gateio.fetch_ohlcv(symbol=name, timeframe='1h', limit=500, since=since_time)\n zhouqi_ch = \"1小时\"\n if (zhouqi == '2h'):\n since_time = current_time - limit * 2 * 60 * 60 * 1000\n data = gateio.fetch_ohlcv(symbol=name, timeframe='2h', limit=500, since=since_time)\n zhouqi_ch = \"2小时\"\n if (zhouqi == '4h'):\n since_time = current_time - limit * 4* 60 * 60 * 1000\n data = gateio.fetch_ohlcv(symbol=name, timeframe='4h', limit=500, since=since_time)\n zhouqi_ch = \"4小时\"\n\n df = pd.DataFrame(data)\n df = df.rename(columns={0: 'open_time', 1: 'open', 2: 'high', 3: 'low', 4: 'close', 5: 'volume'})\n df['open_time'] = pd.to_datetime(df['open_time'], unit='ms') + pd.Timedelta(hours=8)\n\n # 02、 数据格式处理、并计算布林线值\n closeArray = num.array(df['close'])\n highArray = num.array(df['high'])\n lowArray = num.array(df['low'])\n\n doubleCloseArray = num.asarray(closeArray, dtype='double')\n doubleHighArray = num.asarray(highArray, dtype='double')\n doubleLowArray = num.asarray(lowArray, dtype='double')\n\n upperband, middleband, lowerband = ta.BBANDS(doubleCloseArray, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)\n\n print(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n print(zhouqi_ch + \"CLOSE===============\" + str(closeArray[-1]))\n print(zhouqi_ch + \"LOWER===============\" + str(lowArray[-1]))\n print(zhouqi_ch + \"HIGHER==============\" + str(highArray[-1]))\n print(zhouqi_ch + \"BULL upperband======\" + str(upperband[-1]))\n print(zhouqi_ch + \"BULL middleband=====\" + str(middleband[-1]))\n print(zhouqi_ch + \"BULL lowerband======\" + str(lowerband[-1]))\n\n if (lowArray[-1] <= lowerband[-1]):\n a = 1\n sendMail(name + \"触\"+ zhouqi_ch +\"BL下沿:\" + str(closeArray[-1]), name + \"触\"+ zhouqi_ch +\"BL下沿:\" + str(closeArray[-1]))\n if (highArray[-1] >= upperband[-1]):\n a = 1\n sendMail(name + \"触\"+ zhouqi_ch +\"BL上沿:\" + str(closeArray[-1]), name + \"触\"+ zhouqi_ch +\"BL上沿:\" + str(closeArray[-1]))\n\nstrategy(\"BCH/USDT\",\"15m\")\nstrategy(\"BCH/USDT\",\"1h\")\nstrategy(\"BCH/USDT\",\"2h\")\nstrategy(\"BCH/USDT\",\"4h\")\n\n\n\n\n\n","sub_path":"QKL_BCHUSDT.py","file_name":"QKL_BCHUSDT.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"400437570","text":"\"\"\"DbMigrations global settings.\n\nModifying this file will alter all DbMigrations applied or created on this system.\n\"\"\"\n\n# DbMigrations version.\n# This is used by the installer to determine the version number,\n# and printed by `dbmigrations version`\nVERSION = '1.0.0-4'\n\n# The prefix for environment variables.\nENVIRONMENT_PREFIX = 'MIG_'\n\n# Allows printing the configuration options on the command line.\n# Disabled by default for security reasons.\n# Do not enable in production environments.\nPRINT_CONFIG_ENABLED = False\n\n# Used to control the logging level for all of DbMigrations\nDEFAULT_LOG_LEVEL = 'INFO'\n\n# Used to set which database adapter is the default.\nDEFAULT_ADAPTER = 'postgresql'\n","sub_path":"dbmigrations/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"407109337","text":"def func_outer():\n x = 2\n print('x равно', x)\n\n def func_inner():\n nonlocal x\n x = 5\n\n\n func_inner()\n print('Локальное x сменилось на', x)\n\n\ndef total(initial=5, *numbers, **keywords):\n count = initial\n print(count)\n print(numbers)\n print(keywords)\n for number in numbers:\n count += number\n print(count)\n for key in keywords:\n count += keywords[key]\n print(count)\n return count\n\n\nfunc_outer()\nprint(total(10, 1, 2, 3, vegetables=50, fruits=100))\n\n\n","sub_path":"a_byte_of_python/def.py","file_name":"def.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"636429686","text":"from functools import wraps\r\nfrom typing import List\r\n\r\nfrom flask import request, abort\r\nfrom jwt import DecodeError\r\nfrom sqlalchemy.orm.exc import NoResultFound\r\n\r\nfrom backend.blockstack_auth import BlockstackAuth\r\nfrom backend.database.db import DB_SESSION\r\nfrom backend.database.model import User\r\n\r\n\r\ndef check_params_int(params: List):\r\n \"\"\"\r\n Checks a List of params if they are really castable to int.\r\n\r\n :except: ValueError if one of the Parameters isn't an int\r\n :return: -\r\n \"\"\"\r\n for param in params:\r\n if param:\r\n int(param)\r\n\r\n\r\ndef auth_user(func):\r\n \"\"\"\r\n Decorator for resources that need authentication.\r\n\r\n Verifys the given authToken belongs to a specific user, saves it to the DB (for \"caching\"),\r\n returns the User-instance it verifys\r\n\r\n :param func: function to decorate\r\n :return:\r\n \"\"\"\r\n\r\n @wraps(func)\r\n def decorated_function(*args, **kws):\r\n if 'authToken' not in request.headers:\r\n abort(401)\r\n\r\n try:\r\n shortened_token = BlockstackAuth.short_jwt(request.headers['authToken']) # implicitly checks if its a token\r\n username = BlockstackAuth.get_username_from_token(shortened_token)\r\n\r\n session = DB_SESSION()\r\n user_inst: User = session.query(User).filter(User.usernameUser == username).one()\r\n\r\n # check if token matches \"cached\" token, if thats the case, we are done here... else:\r\n if shortened_token != user_inst.authToken:\r\n # verify token:\r\n if BlockstackAuth.verify_auth_response(shortened_token):\r\n # token is valid, save it to DB\r\n user_inst.authToken = shortened_token\r\n session.commit()\r\n else:\r\n # token invalid, abort\r\n abort(401)\r\n\r\n else: # token is valid\r\n pass\r\n except NoResultFound:\r\n # User needs to register\r\n abort(404)\r\n except (KeyError, ValueError, DecodeError): # jwt decode errors\r\n abort(401)\r\n else:\r\n tmp = func(user_inst, *args, **kws)\r\n session.commit()\r\n return tmp\r\n\r\n return decorated_function\r\n","sub_path":"backend/resources/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"39313884","text":"#!/usr/bin/env python3\n'''\nTake raw .bits files and decode them to FASM.\n'''\n\nimport os\nimport fasm\nfrom prjxray import db\nfrom prjxray import fasm_disassembler\nfrom prjxray import bitstream\n\n\ndef run(db_root, bits_file, verbose, canonical):\n disassembler = fasm_disassembler.FasmDisassembler(db.Database(db_root))\n\n with open(bits_file) as f:\n bitdata = bitstream.load_bitdata(f)\n\n print(\n fasm.fasm_tuple_to_string(\n disassembler.find_features_in_bitstream(bitdata, verbose=verbose),\n canonical=canonical))\n\n\ndef main():\n import argparse\n\n parser = argparse.ArgumentParser(\n description='Convert 7-series bits file to FASM.')\n\n database_dir = os.getenv(\"XRAY_DATABASE_DIR\")\n database = os.getenv(\"XRAY_DATABASE\")\n db_root_kwargs = {}\n if database_dir is None or database is None:\n db_root_kwargs['required'] = True\n else:\n db_root_kwargs['required'] = False\n db_root_kwargs['default'] = os.path.join(database_dir, database)\n\n parser.add_argument('--db-root', help=\"Database root.\", **db_root_kwargs)\n parser.add_argument('bits_file', help='')\n parser.add_argument(\n '--verbose',\n help='Print lines for unknown tiles and bits',\n action='store_true')\n parser.add_argument(\n '--canonical', help='Output canonical bitstream.', action='store_true')\n args = parser.parse_args()\n\n run(args.db_root, args.bits_file, args.verbose, args.canonical)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"utils/bits2fasm.py","file_name":"bits2fasm.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"249668603","text":"from __future__ import division\nfrom __future__ import print_function\nimport numpy as np\nfrom numba import jit\nimport matplotlib.pyplot as plt\n\n\n@jit(nopython=True)\ndef _seed_numba(seed):\n np.random.seed(seed)\n\ndef seed(seed):\n np.random.seed(seed)\n _seed_numba(seed)\n\n@jit(nopython=True)\ndef log_mean_prob(log_Prob):\n max_log_prob = np.max(log_Prob)\n return np.log(np.mean(np.exp(log_Prob - max_log_prob))) + max_log_prob\n\n@jit(nopython=True)\ndef normalize_prob(log_Prob):\n Prob = np.exp(log_Prob - np.max(log_Prob))\n Prob /= np.sum(Prob)\n return Prob\n\n@jit(nopython=True)\ndef residual_resample(Prob):\n M = Prob.size\n res_M = M\n res_Prob = Prob * M\n count = np.zeros(M, dtype=np.int64)\n for i in range(M):\n count[i] = int(res_Prob[i])\n res_Prob[i] -= count[i]\n res_M -= count[i]\n if res_M > 0:\n j = 0\n cum_prob = 0.0\n res_Prob /= res_M\n sampled_float = np.sort(np.random.rand(res_M))\n for i in range(M):\n cum_prob += res_Prob[i]\n while j < res_M and sampled_float[j] <= cum_prob:\n count[i] += 1\n j += 1\n j = 0\n sampled_int = np.arange(M)\n for i in range(M):\n if count[i] == 0:\n while count[j] <= 1: j += 1\n sampled_int[i] = j\n count[j] -= 1\n return sampled_int\n\n\n@jit(nopython=True)\ndef generate_data(theta, T):\n \"\"\"\n model:\n s_0 = N(0,5)\n s_{t+1} = s_t/2 + 25s_t/(1+s_t**2) + 8cos(1.2t) + N(0,theta[0]**2)\n o_{t+1} = s_{t+1}^2/2 + N(0,theta[1]**2)\n \"\"\"\n s = np.zeros((T))\n o = np.zeros((T))\n s[0] = 0.0\n o[0] = s[0]**2/2 + np.random.normal()*theta[1]\n for t in range(1,T):\n s[t] = s[t-1]/2 + 25*s[t-1]/(1+s[t-1]**2) + 8*np.cos(1.2*t) + np.random.normal()*theta[0]\n o[t] = s[t]**2/2 + np.random.normal()*theta[1]\n return s, o\n\n\n@jit(nopython=True)\ndef particlefilter(theta, o, M, lag):\n \"\"\"\n input:\n o[0~T]\n M: number of particles\n lag: for pre-fit residual lag\n\n output: s_pre, s_post, y,\n where, \n s_pre[t] = E[s_t|o_{1:t-1}]\n s_post[t] = E[s_t|o_{1~t}]\n y[t,k] = o_t - E[O_t|o_{1~t-k}], k=0,1,...,lag-1,lag\n \"\"\"\n T = o.shape[0]\n s_pre = np.zeros((T,M))\n s_post = np.zeros((T,M))\n y = np.zeros((T,lag))\n W = np.zeros((T,M))\n\n # initilazation\n for i in range(M):\n s_pre[0,i] = 0.0\n W[0,i] = -np.log(theta[1])-((s_pre[0,i]**2/2-o[0])/theta[1])**2/2\n\n for t in range(1,T):\n \n # resample according to last step's weight\n probability = normalize_prob(W[t-1,:])\n sampled_index = residual_resample(probability)\n for j in range(M):\n s_post[t-1,j] = s_pre[t-1,sampled_index[j]]\n\n # transition & reweight\n for i in range(M):\n s_pre[t,i] = s_post[t-1,i]/2 + 25*s_post[t-1,i]/(1+s_post[t-1,i]**2) + \\\n 8*np.cos(1.2*t) + np.random.normal() * theta[0]\n W[t,i] = -np.log(theta[1])-((s_pre[t,i]**2/2-o[t])/theta[1])**2/2\n\n y = np.zeros((T,lag+1)) #y[t,lag] = o_t - E[O_t|o_{1:t-lag}]\n for t in range(T-lag):\n tmp = s_post[t].copy()\n for i in range(1,lag+1):\n o_hat = 0.0\n for j in range(M):\n tmp[j] = tmp[j]/2 + 25*tmp[j]/(1+tmp[j]**2) + \\\n 8*np.cos(1.2*(t+i)) + np.random.normal() * theta[0]\n o_hat += tmp[j]**2/2/M\n y[t+i,i] = o[t+i] - o_hat\n y[t,0] = o[t] - np.mean(s_post[t,:]**2/2)\n\n return s_pre, s_post, y\n\nif __name__ == '__main__':\n \n seed(123)\n \n theta = np.array([1,1])\n T = 500\n M = 1000\n K = 10\n\n s, o = generate_data(theta,T)\n s_pre, s_post, y = particlefilter(theta, o, M, K)\n \n for i in range(0,10):\n print('average of (o_t-E[O_t|o_0:t-{}])^2'.format(i),np.mean(y[:,i]**2))\n\n plt.plot(y[:,0])\n plt.plot(y[:,1])\n plt.show()\n\n\n\n ","sub_path":"dataGenerator2.py","file_name":"dataGenerator2.py","file_ext":"py","file_size_in_byte":3954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"527876447","text":"\"\"\"\nreddit.py\n\ncontains functions related to reddit\n\n\"\"\"\nimport praw\nfrom modules.reddit_config import reddit_obj\n\ndef get_post_info(sub_name: str, number_of_posts: int, start_point: int, category: str) -> str:\n\t\"\"\"\n\t\tRetrieves desired post info from reddit.\n\t\tsub_name is a string representing the name of the subreddit to be searched in.\n\t\tnumnber_of_posts is the number of posts wanted.\n\t\tstart_point is the point in the list of posts to start at.\n\t\tcategory is the category to search in (such as hot or new)\n\t\tReturns a str with the info from the reddit posts desired\n\t\"\"\"\n\t# get a list of posts from a desired subreddit and category:\n\tsub_list = eval(\"reddit_obj.subreddit('{}').{}()\".format(sub_name,category))\n\t\n\t# sets the sub_list to the position desired\n\tfor _ in range(start_point - 1):\n\t\tsub_list.next()\n\n\t\"\"\"\n\t\titerates through the sub_list starting\n\t\tfrom the desired position and ends at \n\t\tthe number of posts desired.\n\t\tadds the post info to a str to be returned\n\t\tat the end\n\t\"\"\"\n\tpost_counter = start_point\n\tstr_to_return = \"\"\n\tfor sub in sub_list:\n\t\tstr_to_return += \"Here is post #{} in the {} category on the {} subreddit\".format(post_counter,category,sub_name)\n\t\tstr_to_return += \"\\n\\nURL:\\n{}\\n\\nTITLE:\\n{}\\n\\nBODY:\\n{}\\n\\n\".format(sub.url, sub.title, sub.selftext)\n\t\tif number_of_posts == 1:\n\t\t\tbreak\n\t\telse:\n\t\t\tpost_counter += 1\n\t\t\tnumber_of_posts -= 1\n\n\treturn str_to_return\n\n\n","sub_path":"modules/reddit.py","file_name":"reddit.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"506740876","text":"#!/usr/bin/python\n#\n# Copyright 2018-2022 Polyaxon, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom typing import Dict\n\nfrom polyaxon.polyaxonfile import CompiledOperationSpecification, OperationSpecification\nfrom polyaxon.polypod.compiler import converter, make\nfrom polyaxon.polypod.compiler.config import PolypodConfig\nfrom polyaxon.polypod.compiler.converters import PLATFORM_CONVERTERS\nfrom polyaxon.schemas.cli.agent_config import AgentConfig\n\n\ndef convert(\n owner_name: str,\n project_name: str,\n run_name: str,\n run_uuid: str,\n content: str,\n default_auth: bool,\n agent_content: str = None,\n) -> Dict:\n polypod_config = PolypodConfig()\n compiled_operation = CompiledOperationSpecification.read(content)\n\n polypod_config.resolve(\n compiled_operation=compiled_operation,\n agent_config=AgentConfig.read(agent_content) if agent_content else None,\n )\n return converter.convert(\n compiled_operation=compiled_operation,\n owner_name=owner_name,\n project_name=project_name,\n run_name=run_name,\n run_uuid=run_uuid,\n namespace=polypod_config.namespace,\n polyaxon_init=polypod_config.polyaxon_init,\n polyaxon_sidecar=polypod_config.polyaxon_sidecar,\n run_path=run_uuid,\n artifacts_store=polypod_config.artifacts_store,\n connection_by_names=polypod_config.connection_by_names,\n secrets=polypod_config.secrets,\n config_maps=polypod_config.config_maps,\n default_sa=polypod_config.default_sa,\n converters=PLATFORM_CONVERTERS,\n default_auth=default_auth,\n )\n\n\ndef make_and_convert(\n owner_name: str,\n project_name: str,\n run_uuid: str,\n run_name: str,\n content: str,\n default_auth: bool = False,\n):\n operation = OperationSpecification.read(content)\n compiled_operation = OperationSpecification.compile_operation(operation)\n return make(\n owner_name=owner_name,\n project_name=project_name,\n project_uuid=project_name,\n run_uuid=run_uuid,\n run_name=run_name,\n run_path=run_uuid,\n compiled_operation=compiled_operation,\n params=operation.params,\n converters=PLATFORM_CONVERTERS,\n default_auth=default_auth,\n )\n","sub_path":"core/polyaxon/agents/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"513861449","text":"import re\nimport pickle\n\nimport pandas as pd\nimport tensorflow as tf\n\nimport jieba as jb\n\n\ndef remove_punctuation(line): # 删除除字母,数字,汉字以外的所有符号\n line = str(line)\n if line.strip() == '':\n return ''\n rule = re.compile(u\"[^a-zA-Z0-9\\u4E00-\\u9FA5]\")\n line = rule.sub('', line)\n return line\n\n\ndef get_stopwords_list(filepath): # 获取停用词\n stopwords = [line.strip() for line in open(\n filepath, 'r', encoding='utf-8').readlines()]\n return stopwords\n\n\ndef load_preprocessed_data_from_csv(dataset, with_Y=True, onehot=True):\n dataset_df = pd.read_csv(dataset)\n X = dataset_df['cutted_content'].values\n if with_Y:\n if onehot:\n Y = pd.get_dummies(dataset_df['label']).values\n else:\n Y = dataset_df['label'].values\n return X, Y\n return X\n\n\ndef tokenize(lang, mode='load', path=None, max_num_words=None, max_sequence_len=256): # mode: create or load\n if mode == 'load':\n with open(path, 'rb') as handle:\n lang_tokenizer = pickle.load(handle)\n print('** Load tokenzier from: ', path)\n else:\n lang_tokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=max_num_words,\n filters='!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~', lower=True)\n lang_tokenizer.fit_on_texts(lang)\n # saving\n with open(path, 'wb') as handle:\n pickle.dump(lang_tokenizer, handle,\n protocol=pickle.HIGHEST_PROTOCOL)\n print('** Save tokenizer at: ', path)\n\n tensor = lang_tokenizer.texts_to_sequences(lang)\n\n tensor = tf.keras.preprocessing.sequence.pad_sequences(tensor, maxlen=max_sequence_len,\n padding='post', truncating='post') # NOTE\n print('** Total different words: %s.' % len(lang_tokenizer.word_index))\n\n return tensor, lang_tokenizer\n\n\ndef preprocess_text_series(text_series, stopwords_path=None):\n cleaned_texts = text_series.apply(remove_punctuation)\n stopwords = []\n if stopwords_path != None:\n stopwords = get_stopwords_list(stopwords_path)\n cutted_texts = cleaned_texts.apply(lambda x: \" \".join(\n [w for w in list(jb.cut(x)) if w not in stopwords]))\n return cutted_texts\n","sub_path":"utils/data_helper.py","file_name":"data_helper.py","file_ext":"py","file_size_in_byte":2331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"633263070","text":"\n\nif __name__ == '__main__':\n # x = open(\"outR.css\", 'r')\n # out = open(\"outF.css\", 'w')\n\n x = open(\"outR.css\", 'r')\n out = open(\"outI.css\", 'w')\n\n l = x.readline()\n\n while(l!=\"\"):\n print(l)\n l=x.readline()\n l1=l.replace(\"rogue\", \"infiltrator\")\n l2=l1.replace(\"Rogue\", \"Infiltrator\")\n\n out.write(l2)\n\n\n\n","sub_path":"pycharm/dnd/remove spell.py","file_name":"remove spell.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"8146820","text":"def is_isogram(word): \r\n \r\n c_word = word.lower() \r\n \r\n l_list = [] \r\n \r\n for l in c_word: \r\n \r\n # If letter is an alphabet then only check \r\n if l.isalpha(): \r\n if l in l_list: \r\n return False\r\n l_list.append(l) \r\n \r\n return True\r\nword=input(\"Enter\")\r\nprint(is_isogram(word)) ","sub_path":"shru4.py","file_name":"shru4.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"370302541","text":"#!/usr/bin/env python\n\nfrom ansible.module_utils.basic import * \nfrom nsxramlclient.client import NsxClient\n\n\"\"\"nsx_logical_switch.py: create logical switch \"\"\"\n\n__copyright__ = \"(c) 2019 Dell Inc. or its subsidiaries. All rights reserved. Dell, EMC, and other trademarks are trademarks of Dell Inc. or its subsidiaries. Other trademarks may be trademarks of their respective owners.\"\n\ndef retrieve_scope(module, session, tz_name):\n vdn_scopes = session.read('vdnScopes', 'read')['body']\n vdn_scope_dict_list = vdn_scopes['vdnScopes']['vdnScope']\n vdn_scope_id = None\n if isinstance(vdn_scope_dict_list, dict):\n if vdn_scope_dict_list['name'] == tz_name:\n vdn_scope_id = vdn_scope_dict_list['objectId']\n elif isinstance(vdn_scope_dict_list, list):\n try:\n vdn_scope_id = [scope['objectId'] for scope in vdn_scope_dict_list if scope['name'] == tz_name][0]\n except IndexError:\n vdn_scope_id = None\n\n if vdn_scope_id:\n return vdn_scope_id\n else:\n module.fail_json(msg='The transport zone with the name {} could not be found in NSX'.format(tz_name))\n\ndef get_lswitch_id(session, lswitchname, scope):\n lswitches_api = session.read_all_pages('logicalSwitches', uri_parameters={'scopeId': scope})\n all_lswitches = session.normalize_list_return(lswitches_api)\n\n for lswitch_dict in all_lswitches:\n if lswitchname == lswitch_dict.get('name'):\n return [lswitch_dict.get('objectId')]\n\n return []\n\n\n\ndef get_lswitch_details(session, lswitch_id):\n return session.read('logicalSwitch', uri_parameters={'virtualWireID': lswitch_id})['body']\n\n\ndef create_lswitch(session, lswitchname, lswitchdesc, lswitchcpmode, scope):\n lswitch_create_dict = session.extract_resource_body_example('logicalSwitches', 'create')\n lswitch_create_dict['virtualWireCreateSpec']['controlPlaneMode'] = lswitchcpmode\n lswitch_create_dict['virtualWireCreateSpec']['name'] = lswitchname\n lswitch_create_dict['virtualWireCreateSpec']['description'] = lswitchdesc\n lswitch_create_dict['virtualWireCreateSpec']['tenantId'] = 'Unused'\n return session.create('logicalSwitches', uri_parameters={'scopeId': scope}, request_body_dict=lswitch_create_dict)\n\n\ndef change_lswitch_details(session, lswitchid, body_dict):\n return session.update('logicalSwitch', uri_parameters={'virtualWireID': lswitchid}, request_body_dict=body_dict)\n\n\ndef delete_lswitch(session, lswitchid):\n return session.delete('logicalSwitch', uri_parameters={'virtualWireID': lswitchid})\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=dict(\n state=dict(default='present', choices=['present', 'absent']),\n nsxmanager_spec=dict(required=True, no_log=True, type='dict'),\n name=dict(required=True),\n description=dict(),\n transportzone=dict(required=True),\n controlplanemode=dict(default='UNICAST_MODE', choices=['UNICAST_MODE', 'MULTICAST_MODE', 'HYBRID_MODE'])\n ),\n supports_check_mode=False\n )\n\n# from nsxramlclient.client import NsxClient\n client_session=NsxClient(module.params['nsxmanager_spec']['raml_file'], module.params['nsxmanager_spec']['host'],\n module.params['nsxmanager_spec']['user'], module.params['nsxmanager_spec']['password'])\n\n vdn_scope=retrieve_scope(module, client_session, module.params['transportzone'])\n lswitch_id=get_lswitch_id(client_session, module.params['name'], vdn_scope)\n\n if len(lswitch_id) is 0 and 'present' in module.params['state']:\n ls_ops_response=create_lswitch(client_session, module.params['name'], module.params['description'],\n module.params['controlplanemode'], vdn_scope)\n module.exit_json(changed=True, argument_spec=module.params, ls_ops_response=ls_ops_response)\n elif len(lswitch_id) is not 0 and 'present' in module.params['state']:\n lswitch_details=get_lswitch_details(client_session,lswitch_id[0])\n change_required=False\n for lswitch_detail_key, lswitch_detail_value in lswitch_details['virtualWire'].iteritems():\n if lswitch_detail_key == 'name' and lswitch_detail_value != module.params['name']:\n #TODO: Check the bellow line\n lswitch_details['virtualWire']['name']=module.params['nsxmanager_spec']['name']\n change_required=True\n elif lswitch_detail_key == 'description' and lswitch_detail_value != module.params['description']:\n lswitch_details['virtualWire']['description']=module.params['description']\n change_required=True\n elif lswitch_detail_key == 'controlPlaneMode' and lswitch_detail_value != module.params['controlplanemode']:\n lswitch_details['virtualWire']['controlPlaneMode']=module.params['controlplanemode']\n change_required=True\n if change_required:\n ls_ops_response=change_lswitch_details(client_session,lswitch_id[0],lswitch_details)\n module.exit_json(changed=True, argument_spec=module.params, ls_ops_response=ls_ops_response)\n else:\n module.exit_json(changed=False, argument_spec=module.params)\n elif len(lswitch_id) is not 0 and 'absent' in module.params['state']:\n ls_ops_response=delete_lswitch(client_session, lswitch_id[0])\n module.exit_json(changed=True, argument_spec=module.params, ls_ops_response=ls_ops_response)\n else:\n module.exit_json(changed=False, argument_spec=module.params)\n\n\n\n#from ansible.module_utils.basic import *\nif __name__ == '__main__':\n main()\n","sub_path":"library/nsx_logical_switch.py","file_name":"nsx_logical_switch.py","file_ext":"py","file_size_in_byte":5645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"567904755","text":"## the version of analysis_old.py from when I first got it. What it looked like when we got access to Case's data\n\nfrom sklearn.svm import SVC\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.gaussian_process import GaussianProcessClassifier\nfrom sklearn.gaussian_process.kernels import RBF\nfrom sklearn import model_selection as ms\nfrom mpl_toolkits import mplot3d\nimport matplotlib.pyplot as plt\nimport scipy.stats as sp\n\n\n\ntarget = []\nnot_target = []\nunclassified = []\n\n\ndef import_seqdata(seqname, seqlen, gc, cov, hasBlast, isTarget, kdist_list):\n seqdata = (seqname, seqlen, kdist_list, isTarget, gc, cov)\n if hasBlast == 1:\n if isTarget == 1:\n target.append(seqdata)\n else:\n not_target.append(seqdata)\n else:\n unclassified.append(seqdata)\n return 0\n\n\ndef plot_mixtures(kmer_list):\n all_gc_t = []\n all_rcov_t = []\n all_kcov_t = []\n all_gc_n = []\n all_rcov_n = []\n all_kcov_n = []\n all_gc_u = []\n all_rcov_u = []\n all_kcov_u = []\n for i in range(len(kmer_list)):\n gc_t = []\n rcov_t = []\n kcov_t = []\n gc_n = []\n rcov_n = []\n kcov_n = []\n gc_u = []\n rcov_u = []\n kcov_u = []\n for seqdata in target:\n for j in range(len(seqdata[2][i])):\n if seqdata[2][i][j] == 0:\n continue\n gc_t.append(seqdata[4])\n rcov_t.append(seqdata[5])\n kcov_t.append(j)\n all_gc_t.append(seqdata[4])\n all_rcov_t.append(seqdata[5])\n all_kcov_t.append(j)\n for seqdata in not_target:\n for j in range(len(seqdata[2][i])):\n if seqdata[2][i][j] == 0:\n continue\n gc_n.append(seqdata[4])\n rcov_n.append(seqdata[5])\n kcov_n.append(j)\n all_gc_n.append(seqdata[4])\n all_rcov_n.append(seqdata[5])\n all_kcov_n.append(j)\n for seqdata in unclassified:\n for j in range(len(seqdata[2][i])):\n if seqdata[2][i][j] == 0:\n continue\n gc_u.append(seqdata[4])\n rcov_u.append(seqdata[5])\n kcov_u.append(j)\n all_gc_u.append(seqdata[4])\n all_rcov_u.append(seqdata[5])\n all_kcov_u.append(j)\n plt.figure(i)\n ax = plt.axes(projection=\"3d\")\n ax.scatter(gc_t, rcov_t, kcov_t, c='r', marker='o', alpha=0.1)\n ax.scatter(gc_u, rcov_u, kcov_u, c='g', marker='o', alpha=0.1)\n ax.scatter(gc_n, rcov_n, kcov_n, c='b', marker='o', alpha=0.1)\n plt.savefig(F\"figures/mixture{kmer_list[i]}.png\");\n plt.figure(len(kmer_list))\n ax = plt.axes(projection=\"3d\")\n ax.scatter(all_gc_t, all_rcov_t, all_kcov_t, c='r', marker='o', alpha=0.1)\n ax.scatter(all_gc_u, all_rcov_u, all_kcov_u, c='g', marker='o', alpha=0.1)\n ax.scatter(all_gc_n, all_rcov_n, all_kcov_n, c='b', marker='o', alpha=0.1)\n plt.savefig(\"figures/mixtureALL.png\");\n\n\n\ndef GM_model(kmer_list):\n totalHistData = []\n gm_models = {}\n aic_scores = {}\n bic_scores = {}\n for k in range(len(kmer_list)):\n kmerHistData = []\n for i in range(len(seq_list)):\n regionKmerHistData = readHistData(histFile_list[i][k])\n if blast_list[i] == 1 and tax_list[i] == 1:\n for dataPoint in regionKmerHistData:\n kmerHistData.append(dataPoint)\n totalHistData.append((seq_list[i], kmer_list[k], regionKmerHistData))\n gm_models[kmer_list[k]] = [GaussianMixture(n, covariance_type='full').fit(kmerHistData) for n in range(1,6)]\n #aic_scores[kmer_list[k]] = [gm_models[kmer_list[k]][n].aic(kmerHistData) for n in range(0,5)]\n #bic_scores[kmer_list[k]] = [gm_models[kmer_list[k]][n].bic(kmerHistData) for n in range(0,5)]\n kmer_scores = {seq : {} for seq in seq_list}\n for seqTuple in totalHistData:\n kmer_scores[seqTuple[0]][seqTuple[1]] = [gm_models[seqTuple[1]][n].score(seqTuple[2]) for n in range(0,5)]\n return kmer_scores\n\n\n\ndef DT_classify(classifier):\n regionIDs = []\n X = []\n for item in unclassified:\n regionIDs.append(item[0]) # region name\n X.append(item[4:])\n Y = []\n for i in classifier.predict(X):\n Y.append(i)\n return list(zip(regionIDs, Y))\n\n\n\ndef DT_model():\n X = []\n Y = []\n features = [\"GC\", \"Coverage\"]\n for item in target + not_target:\n X.append(item[4:])\n Y.append(item[3]) # isTarget\n X_train, X_test, Y_train, Y_test = ms.train_test_split(X, Y, test_size=0.33, random_state=0)\n classifier = tree.DecisionTreeClassifier()\n classifier = classifier.fit(X_train, Y_train)\n print(\"Classifier built, score is %s out of 1.00\" % classifier.score(X_test, Y_test))\n #with open(\"model.dot\", 'w') as dotfile:\n # tree.export_graphviz(classifier, out_file=dotfile, feature_names=features,\n # class_names=Y, filled=True, rounded=True, special_characters=True)\n return DT_classify(classifier)\n\n\n\ndef run_analysis(kmer_list):\n print(\"Seqdata imported, %d target sequences, %d contaminant sequences, and %d unclassified sequences\\n\" % (len(target), len(not_target), len(unclassified)))\n plot_mixtures(kmer_list)\n #classifiers = [\n # SVC(gamma=2, C=1, nu=(len(target)/len(not_target))),\n # GaussianNB(),\n # DecisionTreeClassifier(),\n # MLPClassifier(alpha=1, max_iter=1000),\n # RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1),\n # GaussianProcessClassifier(1.0 * RBF(1.0))]\n\n #if len(testdata) != 0:\n # classifier = constructDTclassifier(corpus, kmer_list)\n # result = classifyData(classifier, testdata)\n #else:\n # result = []\n #with open(\"tokeep.txt\", \"w+\") as k, open(\"toremove.txt\", \"w+\") as r:\n # for item in result:\n # if item[1] == 1:\n # k.write(\"%s x\\n\" % item[0])\n # else:\n # r.write(\"%s x\\n\" % item[0])\n # for i in range(len(corpus)):\n # if corpus[i][0] == 1:\n # k.write(\"%s\\n\" % corpus_map[i])\n # else:\n # r.write(\"%s\\n\" % corpus_map[i])\n return 1\n\n","sub_path":"src/analysis_old_caseversion.py","file_name":"analysis_old_caseversion.py","file_ext":"py","file_size_in_byte":6481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"339029709","text":"from __future__ import print_function\nimport numpy as np\nimport czigzag as czz\nimport zigzag as pzz\nimport time\n\ndef mytimeit(mod, a):\n t0 = time.time()\n pivots = mod.peak_valley_pivots(a, 0.03, -0.03)\n t1 = time.time() \n modes = mod.pivots_to_modes(pivots)\n t2 = time.time()\n returns = mod.compute_segment_returns(a, pivots)\n t3 = time.time()\n drawdown = mod.max_drawdown(a)\n t4 = time.time()\n t = []\n t.append((t1-t0)*1000)\n t.append((t2-t1)*1000)\n t.append((t3-t2)*1000)\n t.append((t4-t3)*1000)\n return t, pivots, modes, returns, drawdown\n\n\ndef diff(name, a1, a2):\n print(\"{}: the two modules produce the same thing = {}\".format(name, np.array_equal(a1, a2)))\n\n\ndef run():\n size = 1000000\n a = np.cumprod(1. + np.random.randn(size) * 0.01)\n t_pzz, pivots_pzz, modes_pzz, returns_pzz, drawdown_pzz = mytimeit(pzz, a)\n t_czz, pivots_czz, modes_czz, returns_czz, drawdown_czz = mytimeit(czz, a)\n\n print(\"CZigZag: execution time of peak_valley_pivots, pivots_to_modes, returns, max_drawdown = %7.1f, %7.1f, %7.1f, %7.1f ms\" % (t_czz[0], t_czz[1], t_czz[2], t_czz[3]))\n print(\"ZigZag: execution time of peak_valley_pivots, pivots_to_modes, returns, max_drawdown = %7.1f, %7.1f, %7.1f, %7.1f ms\" % (t_pzz[0], t_pzz[1], t_pzz[2], t_pzz[3]))\n print(\"Speedup: peak_valley_pivots, pivots_to_modes, returns, max_drawdown = %7.1f, %7.1f, %7.1f, %7.1f\" % (t_pzz[0]/t_czz[0], t_pzz[1]/t_czz[1], t_pzz[2]/t_czz[2], t_pzz[3]/t_czz[3]))\n\n diff('pivots', pivots_czz, pivots_pzz)\n diff('modes', modes_czz, modes_pzz)\n diff('returns', returns_czz, returns_pzz)\n diff('drawdown', drawdown_czz, drawdown_pzz)\n\n\ndef main():\n print(\"First run\")\n run()\n print(\"Second run\")\n run()\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"czigzag/tests/test_czigzag.py","file_name":"test_czigzag.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"488886785","text":"## 1. Introduction ##\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nwomen_degrees = pd.read_csv('percent-bachelors-degrees-women-usa.csv')\nmajor_cats = ['Biology', 'Computer Science', 'Engineering', 'Math and Statistics']\n\nfig = plt.figure(figsize=(12, 12))\n\nfor sp in range(0,4):\n ax = fig.add_subplot(2,2,sp+1)\n ax.plot(women_degrees['Year'], women_degrees[major_cats[sp]], c='blue', label='Women')\n ax.plot(women_degrees['Year'], 100-women_degrees[major_cats[sp]], c='green', label='Men')\n for key,spine in ax.spines.items():\n spine.set_visible(False)\n ax.set_xlim(1968, 2011)\n ax.set_ylim(0,100)\n ax.set_title(major_cats[sp])\n ax.tick_params(bottom=\"off\", top=\"off\", left=\"off\", right=\"off\")\n\nplt.legend(loc='upper right')\nplt.show()","sub_path":"5-storytelling-data--visualization/Color, Layout, and Annotations-148.py","file_name":"Color, Layout, and Annotations-148.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"585375645","text":"import time\nfrom datetime import datetime, timedelta\n\nimport requests\n\n\nclass Client:\n def __init__(self, auth_data: dict, user_agent: str):\n self.auth_data = auth_data\n self.user_agent = user_agent\n self._endpoint = \"https://oauth.reddit.com\"\n\n self._expire_in = 0\n self._last_auth = datetime.min\n\n self._wait = 0\n self._last_request = datetime.min\n\n @property\n def auth_key(self) -> str:\n if (datetime.now() - self._last_auth).seconds > self._expire_in - 1:\n r = requests.post(\n \"https://www.reddit.com/api/v1/access_token\",\n headers={\"User-Agent\": \"OPED User Agent 0.1\"},\n data=self.auth_data,\n auth=(\"bdJpF9eA5Vz4Dw\", \"B2SIAD6-nketU9gHusKx-y9cRWo\"),\n )\n r.raise_for_status()\n\n data = r.json()\n self._auth_key = data[\"access_token\"]\n self._expire_in = data[\"expires_in\"]\n self._last_auth = datetime.now()\n\n return self._auth_key\n\n def request(self, method: str, url: str, data: dict = {}) -> dict:\n if self._wait and (datetime.now() - self._last_request).seconds < self._wait:\n time.sleep()\n\n headers = {\n \"Authorization\": f\"bearer {self.auth_key}\",\n \"User-Agent\": self.user_agent,\n }\n r = requests.request(method, self._endpoint + url, headers=headers, data=data)\n r.raise_for_status()\n\n self._last_request = datetime.now()\n if float(r.headers[\"X-Ratelimit-Remaining\"]) == 0:\n self._wait = r.headers[\"X-Ratelimit-Reset\"]\n\n return r.json()\n\n def wiki_pages(self, subreddit: str) -> list:\n return self.request(\"GET\", f\"/r/{subreddit}/wiki/pages\")[\"data\"]\n\n def wiki_page(self, subreddit: str, page: str) -> dict:\n return self.request(\"GET\", f\"/r/{subreddit}/wiki/{page}\")[\"data\"]\n","sub_path":"parser/reddit.py","file_name":"reddit.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"622855350","text":"import random\nimport mysql.connector\nimport mysqllogin\nimport subprocess\nimport logging\nimport time\nfrom socket import *\nfrom datetime import timedelta\n\n######################################\nIRCHOST = 'xs4all.nl.quakenet.org' \nIRCPORT = 6667\nIRCUSER = 'BierBot * * : bestaboteva'\nIRCNICK = 'BierBot'\nIRCchannel = '#dasimperium'\nsqlhost = mysqllogin.sqlhost\nsqluser = mysqllogin.sqluser\nsqlpw = mysqllogin.sqlpw\nsqldb = mysqllogin.sqldb\n######################################\n\n# Liste der im Channel anwesenden leute\nuser_online = []\n# Liste in der die Witze gespeichert werden\nwitze = []\n\n# konfiguation des loggers\nlogging.basicConfig(filename='bot.log', level=logging.DEBUG, format=\"%(asctime)s %(message)s\")\n\ndef timestamp(ausgabe = \"\"):\n zeit = time.localtime()\n if ausgabe == \"\":\n timestmp = \"{0:02d}:{1:02d}:{2:02d} - {3:02d}.{4:02d}.{5:04d}\".format(zeit[3], zeit[4], zeit[5], zeit[2], zeit[1], zeit[0])\n return timestmp\n elif ausgabe == \"zeit\":\n timestmp = \"{0:02d}:{1:02d}:{2:02d}\".format(zeit[3], zeit[4], zeit[5])\n return timestmp\n elif ausgabe == \"datum\":\n timestmp = \"{0:02d}.{1:02d}.{2:02d}\".format(zeit[2], zeit[1], zeit[0])\n return timestmp\n \ndef shell_exec(nick, cmd):\n if cmd == \"ls\":\n p = subprocess.Popen(\"ls\", stdout=subprocess.PIPE, shell=True)\n output = p.stdout.read().decode().replace(\"\\r\", \" \").replace(\"\\n\", \" \")\n con.send(\"PRIVMSG {} : {}\".format(nick, output))\n elif cmd == \"df\":\n p = subprocess.Popen(\"df -h\", stdout=subprocess.PIPE, shell=True)\n output = p.stdout.read().decode().replace(\"\\r\", \" \").replace(\"\\n\", \" \")\n con.send(\"PRIVMSG {} : {}\".format(nick, output)) \n else:\n con.send(\"PRIVMSG {} : wat?\".format(nick))\n \ndef system_uptime(nick, privat = False):\n try:\n with open('/proc/uptime', 'r') as f:\n uptime_seconds = float(f.readline().split()[0])\n uptime_string = str(timedelta(seconds = uptime_seconds))\n if privat == True:\n con.send(\"PRIVMSG {} :Uptime: {}\".format(nick, uptime_string))\n else:\n con.send(\"PRIVMSG {} :Uptime: {}\".format(IRCchannel, uptime_string))\n except BaseException as e:\n logging.exception(\"FEHLER '{}'\".format(e))\n\ndef witzeupdate(nick):\n global witze\n startzeit = time.time()\n try:\n f = open(\"witze.txt\", \"r\")\n witze = f.readlines()\n f.close()\n except BaseExcpetion as e:\n logging.error(\"witzedatei konnte nicht geladen werden '{}'\".format(e))\n logging.info(\"Es wurden {} Witze eingelesen\".format(len(witze)))\n endzeit = time.time()\n con.send(\"PRIVMSG {} :Es wurden {} witze in {}s geladen\".format(nick, len(witze), round(endzeit - startzeit, 4)))\n \ndef gibwitz():\n global witze\n rseed = random.random()\n random.seed(rseed)\n if len(witze) != 0:\n witz = witze[random.randint(0,len(witze)-1)]\n return witz\n else:\n return \"keine Witze geladen\"\n \ndef bot_commands(nick):\n befehle = (\n \"commands - Listet alle Befehle auf\",\n \"uhr - Gibt die Uhrzeit aus\",\n \"datum - Gibt das Datum aus\",\n \"bier - Gibt dir ein köstliches vBier\",\n \"energy - Gibt einen Köstlichen Monster Energy\",\n \"monster - macht das gleiche wie energy\",\n \"witz - lässt den Bot einen unglaublich guten Witz erzählen\",\n \"shit - gibt einen Joint rum\",\n \"kaffee - gibt kaffee\",\n \"uptime - gibt die server uptime aus\"\n )\n for element in befehle:\n con.send(\"PRIVMSG {} :{}\".format(nick, element))\n time.sleep(0.2)\n \n##def bot_say(nachricht):\n## nachricht = nachricht.split(\"say\", 1)[1]\n## con.send(\"PRIVMSG {} :{}\".format(IRCchannel, nachricht))\n \ndef bot_weed(nick, privat = False):\n if privat == False:\n con.send(\"PRIVMSG {} :BierBot steckt einen Joint an und reicht ihn herum\".format(IRCchannel))\n else:\n con.send(\"PRIVMSG {} :BierBot steckt dir Joint an und reicht ihn dir\".format(nick))\n \ndef bot_witz(nick, privat = False):\n if privat == False:\n con.send(\"PRIVMSG {} :{}\".format(IRCchannel, gibwitz()))\n else:\n con.send(\"PRIVMSG {} :{}\".format(nick, gibwitz()))\n \ndef bot_uhrzeit(nick, privat):\n if privat == False:\n con.send(\"PRIVMSG {} :Es ist gerade {}\".format(IRCchannel, timestamp(\"zeit\")))\n else:\n con.send(\"PRIVMSG {} :Es ist gerade {}\".format(nick, timestamp(\"zeit\")))\n\ndef bot_datum(nick, privat):\n if privat == False:\n con.send(\"PRIVMSG {} :Wir haben den {}\".format(IRCchannel, timestamp(\"datum\")))\n else:\n con.send(\"PRIVMSG {} :Wir haben den {}\".format(nick, timestamp(\"datum\"))) \n\ndef bot_bier(nick, privat):\n if privat == False:\n con.send(\"PRIVMSG {} :Öffnet ein Bier für {} und reicht es feierlich rüber\".format(IRCchannel, nick))\n else:\n con.send(\"PRIVMSG {} :Öffnet dir ein Bier und reicht es feierlich rüber\".format(nick))\n userstats(nick, \"bier_erhalten\")\n \ndef bot_kaffee(nick, privat):\n if privat == False:\n con.send(\"PRIVMSG {} :Reicht {} einen leckeren Kaffee rüber\".format(IRCchannel, nick))\n else:\n con.send(\"PRIVMSG {} :Reicht dir einen mega leckeren Kaffee rüber\".format(nick))\n userstats(nick, \"energy_erhalten\") \n\ndef bot_monster(nick, privat):\n if privat == False:\n con.send(\"PRIVMSG {} :Reicht {} ein mega kaltes Monster Energy rüber\".format(IRCchannel, nick))\n else:\n con.send(\"PRIVMSG {} :Reicht dir ein mega kaltes Monster Energy rüber\".format(nick))\n userstats(nick, \"energy_erhalten\")\n \ndef bot_willkommen(nick):\n global user_online\n if nick != IRCNICK:\n con.send(\"PRIVMSG {} :Hallo {}!\".format(IRCchannel, nick))\n userstats(nick, \"joined_channel\")\n user_online.append(nick)\n \ndef bot_wiedersehen(nick):\n global user_online\n userstats(nick, \"leaved_channel\")\n user_online.remove(nick)\n \ndef nick_changed(nick_alt, nick_neu):\n global user_online\n user_online.remove(nick_alt)\n user_online.append(nick_neu)\n userstats(nick_alt, \"nick_changed\", nick_neu)\n\ndef konsolen_ausgabe(nachricht):\n zeit = timestamp()\n print(\"\\n\" + zeit + nachricht + \"\\n\\n\")\n\ndef bot_adjektiv(nick, privat, adjektiv):\n global user_online\n if adjektiv.find(\".\") != -1:\n adjektiv = adjektiv.replace(\".\",\"\")\n if adjektiv.find(\"!\") != -1:\n adjektiv = adjektiv.replace(\"!\",\"\")\n if adjektiv.find(\"?\") != -1:\n adjektiv = adjektiv.replace(\"?\",\"\")\n if adjektiv == \"cool\":\n if privat == True:\n con.send(\"PRIVMSG {} :Du nicht!\".format(nick))\n return\n else:\n con.send(\"PRIVMSG {} :Du nicht!\".format(IRCchannel))\n return\n rseed = random.random()\n random.seed(rseed)\n if privat == True:\n con.send(\"PRIVMSG {} :{} {}\".format(nick, user_online[random.randint(0, len(user_online) -1)], adjektiv))\n else:\n con.send(\"PRIVMSG {} :{} {}\".format(IRCchannel, user_online[random.randint(0, len(user_online) -1)], adjektiv))\n \ndef pingpong(message):\n# Antwortet auf den Ping\n pong = message.split(\":\")\n con.send(\"PONG :\" + pong[1])\n\n# Überprüft die eingegangenen nachrichten und verarbeitet diese weiter\ndef controller(message):\n # Globale Variable Importieren\n global user_online\n # Überprüft auf PING\n if message.startswith(\"PING :\"):\n pingpong(message)\n # Überprüft auf authentifizierung und joined dem channel\n if message.split(\" \")[1].startswith(\"221\"):\n con.send(\"JOIN \" + IRCchannel)\n # Speicher die User die im channel sind in eine Liste\n if message.split(\" \")[1].startswith(\"353\"):\n for nick in message.split(\" \")[5:]:\n if nick.startswith(\":\") or nick.startswith(\"@\"):\n user_online.append(nick[1:])\n else:\n user_online.append(nick)\n \n # Checkt ob jemand joined oder leaved oder umbenennt\n if message.split(\" \")[1].startswith(\"QUIT\") or message.split(\" \")[1].startswith(\"PART\"):\n nick = message.split(\"!\")[0][1:]\n bot_wiedersehen(nick)\n \n if message.split(\" \")[1].startswith(\"JOIN\"):\n nick = message.split(\"!\")[0][1:]\n bot_willkommen(nick)\n \n if message.split(\" \")[1].startswith(\"NICK\"):\n nick_alt = message.split(\"!\")[0][1:]\n nick_neu = message.split(\"NICK\")[1][2:]\n nick_changed(nick_alt, nick_neu)\n \n # Checkt ob ein User etwas geschrieben hat\n if message.split(\" \")[1].startswith(\"PRIVMSG\"):\n #prüft ob es query oder öffentlich ist\n if message.split(\" \")[2].startswith(IRCNICK):\n privat = True\n else:\n privat = False\n \n #Extrahiert den Nick aus der servermessage\n nick = message.split(\"!\")[0][1:]\n #Extrahiert die Nachricht aus der servermessage\n nachricht = message.split(\" \", 3)[3][1:]\n #Schickt die nachricht an die Verlaufmethode\n chatlog(nick, nachricht)\n #Überprüft ob der Bot angesprochen wurde\n if nachricht.lower().find(IRCNICK.lower()) != -1 and message.split(\" \")[1].startswith(\"PRIVMSG\"):\n if nachricht.lower().startswith(IRCNICK.lower()):\n ###################################################\n # AB HIER WERDEN DIE BEFEHL AN DEN BOT ÜBERPRÜFT #\n ###################################################\n # Überprüft ob nach dem namen ein doppeltpunkt kommt\n if nachricht.lower().split(IRCNICK.lower())[1].startswith(\":\"):\n bot_befehl = nachricht.lower().split(IRCNICK.lower())[1][2:].lower()\n else:\n bot_befehl = nachricht.lower().split(IRCNICK.lower())[1][1:].lower()\n logging.info(\"Botbefehl: \" + bot_befehl)\n if bot_befehl == \"uhr\":\n bot_uhrzeit(nick, privat)\n if bot_befehl == \"datum\":\n bot_datum(nick, privat)\n if bot_befehl == \"bier\":\n bot_bier(nick, privat)\n if bot_befehl == \"energy\" or bot_befehl == \"monster\":\n bot_monster(nick, privat)\n if bot_befehl == \"witz\":\n bot_witz(nick, privat)\n if bot_befehl == \"witzupdate\":\n witzeupdate(nick) \n if bot_befehl == \"shit\":\n bot_weed(nick, privat)\n if bot_befehl == \"commands\":\n bot_commands(nick)\n if bot_befehl == \"kaffee\":\n bot_kaffee(nick, privat)\n if bot_befehl.startswith(\"say0815\"):\n bot_say(nachricht)\n if bot_befehl.startswith(\"wer\"):\n adjektiv = bot_befehl.split(\" \", 1)[1]\n bot_adjektiv(nick, privat, adjektiv)\n if bot_befehl == \"uptime\":\n system_uptime(nick, privat)\n if bot_befehl.startswith(\"exec\"):\n cmd = bot_befehl.split(\" \", 1)[1]\n shell_exec(nick, cmd)\n if bot_befehl.startswith(\"stats\"):\n return_stats(bot_befehl.split(\" \", 1)[1])\n \nclass connection:\n # Konstruktor\n def __init__(self, ho, po, us, ni):\n self.HOST = str(ho)\n self.PORT = int(po)\n self.USER = str(us)\n self.NICK = str(ni)\n # Socket Objekt erstellen\n self.s = socket(AF_INET, SOCK_STREAM)\n # Dateireferenz vom Socket erstellen\n self.fs = self.s.makefile(\"rw\")\n # Verbindung Herstellen\n def connect(self):\n # Socket verbinden\n self.s.connect((self.HOST, self.PORT))\n # Beim Server anmelden\n self.fs.write(\"PASS \" + str(random.random()) + \"\\n\")\n self.fs.write(\"USER \" + self.USER + \"\\n\")\n self.fs.write(\"NICK \" + self.NICK + \"\\n\")\n self.fs.flush()\n def receive(self):\n while True:\n # sendet die empfangenen daten an die controller methode\n # ohne escape sequenz\n try:\n message = self.fs.readline()[:-1]\n controller(message)\n except BaseException as e:\n logging.exception(\"Fehler beim einlesen der nachricht '{}'\".format(e))\n\n def send(self, nachricht):\n global startzeit\n global endzeit\n try:\n self.fs.write(nachricht + \"\\n\")\n self.fs.flush()\n chatlog(\"BOT\", nachricht)\n except BaseException as e:\n logging.exception(\"Fehler beim senden der Nachricht '{}'\".format(e))\n\n## SQL LOGGING ##\ndef userExists(nick):\n #Prüft ob der Nutzer angelegt ist, und legt dieses gegebenenfalls an\n conn = mysql.connector.connect(user=sqluser, password=sqlpw, host=sqlhost, database=sqldb, buffered=True)\n cur = conn.cursor()\n cur.execute(\"SELECT nick FROM userstats WHERE nick = '{}'\".format(nick))\n if cur.rowcount < 1:\n cur.execute(\"INSERT INTO userstats (nick) VALUES '{}'\".format(nick))\n return True\n else:\n return True\n conn.close()\n \ndef chatlog(nick, nachricht):\n if not nachricht.startswith(\"PONG :xs4all.nl.quakenet.org\"):\n # Verbindungm mit der Datenbank herstellen\n conn = mysql.connector.connect(user=sqluser, password=sqlpw, host=sqlhost, database=sqldb, buffered=True)\n cur = conn.cursor()\n # Query ausführen\n cur.execute(\"INSERT INTO irclog (nick, nachricht) VALUES ('{}', '{}')\".format(nick, nachricht))\n if userExists(nick):\n cur.execute(\"UPDATE userstats SET zeichen_gesendet=zeichen_gesendet+{} where nick='{}'\".format(len(nachricht), nick))\n conn.close()\n \ndef userstats(nick, action, value=\"\"):\n# Verbindungm mit der Datenbank herstellen\n conn = mysql.connector.connect(user=sqluser, password=sqlpw, host=sqlhost, database=sqldb, buffered=True)\n cur = conn.cursor()\n if action == \"joined_channel\":\n if userExists(nick):\n cur.execute(\"UPDATE userstats SET gejoined=gejoined+1 where nick='{}'\".format(nick))\n cur.execute(\"UPDATE userstats SET online=1 where nick='{}'\".format(nick))\n logging.info(\"{} CHANNEL BETRETEN\".format(nick))\n \n if action == \"bier_erhalten\":\n if userExists(nick):\n cur.execute(\"UPDATE userstats SET bier=bier+1 where nick='{}'\".format(nick))\n logging.info(\"{} BIER ERHALTEN\".format(nick))\n \n if action == \"energy_erhalten\":\n if userExists(nick):\n cur.execute(\"UPDATE userstats SET energy=energy+1 where nick='{}'\".format(nick))\n logging.info(\"{} ENERGY ERHALTEN\".format(nick))\n \n if action == \"leaved_channel\":\n if userExists(nick):\n cur.execute(\"UPDATE userstats SET online=0 where nick='{}'\".format(nick))\n logging.info(\"{} CHANNEL VERLASSEN\".format(nick))\n\n if action == \"nick_changed\":\n if userExists(nick):\n cur.execute(\"UPDATE userstats SET nick='{}' where nick='{}'\".format(value, nick))\n logging.info(\"{} HEISST JETZT {}\".format(nick, value))\n conn.close() \n## SQL Statistik ##\n\ndef return_stats(nick, privat=False, value=\"\"):\n conn = mysql.connector.connect(user=sqluser, password=sqlpw, host=sqlhost, database=sqldb)\n cur = conn.cursor()\n cur.execute(\"SELECT * from userstats WHERE nick = '{}'\".format(nick))\n id, nick, online, bier, energy, gejoined, zeichen_gesendet = cur.fetchone()\n con.send(\"PRIVMSG {} : {} hat schon {} Bier getrunken, {} Energy, ist schon {} mal gejoined und hat schon {} zeichen gesendet\".format(IRCchannel, nick, bier, energy, gejoined, zeichen_gesendet))\n conn.close()\n \nif __name__ == \"__main__\":\n con = connection(IRCHOST, IRCPORT, IRCUSER, IRCNICK)\n con.connect()\n con.receive()","sub_path":"ircbot.py","file_name":"ircbot.py","file_ext":"py","file_size_in_byte":15935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"141688121","text":"from items.models import Item\n\nfrom rest_framework import serializers\n\n\nclass ItemSerializer(serializers.ModelSerializer):\n class Meta:\n model = Item\n fields = ('id', 'name', 'code', 'active')\n\n def validate_name(self, value):\n \"\"\"Overide Validate to check if unique on API POST.\"\"\"\n value = value.lower()\n if Item.objects.filter(name=value).exists():\n raise serializers.ValidationError(\"This name already exist.\")\n return value\n\n def validate_code(self, value):\n \"\"\"Overide Validate to check if unique on API POST.\"\"\"\n value = value.upper()\n if Item.objects.filter(code=value).exists():\n raise serializers.ValidationError(\"This code already exist.\")\n return value\n","sub_path":"django-bookmark/items/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"473647860","text":"# (C) Datadog, Inc. 2010-2016\n# All rights reserved\n# Licensed under Simplified BSD License (see LICENSE)\n\n# stdlib\nimport mock\nfrom nose.plugins.attrib import attr\nimport re\n\n# 3p\n\n# project\nfrom tests.checks.common import AgentCheckTest\nimport check\n\ninstance = {\n 'host': 'localhost',\n 'port': 26379,\n 'password': 'datadog-is-devops-best-friend'\n}\n\n\n@attr(requires='upsc')\nclass TestUpsc(AgentCheckTest):\n \"\"\"Test for UPSC integration.\"\"\"\n CHECK_NAME = 'upsc'\n TEST_CHECK_CONFIG = {'instances': [\n {\n 'tags': ['foo:bar'],\n 'string_tags': ['ups.testStringTag'],\n 'excluded': ['ups.ignoreme'],\n 'excluded_re': ['ups\\.ignore\\..*'],\n 'excluded_devices': ['ignoreme'],\n 'excluded_devices_re': ['ignore\\..*']\n }\n ]}\n\n class MockUpscCheck(check.UpscCheck):\n \"\"\" Some overrides to work in CI\"\"\"\n\n def list_ups_devices(self):\n return ['ignoreme', 'ignore.me.too', 'testUps']\n\n @mock.patch('subprocess.check_output')\n def query_ups_device(self, name):\n return {\n 'ups.status': 'OL',\n\n }\n\n\n @attr('config')\n def test_load_from_config(self):\n self.load_check(self.TEST_CHECK_CONFIG, {})\n self.check.update_from_config(self.TEST_CHECK_CONFIG['instances'][0])\n\n self.assertListEqual(['foo:bar'], self.check.additional_tags)\n self.assertListEqual(sorted(['ups.testStringTag'] + self.check.DEFAULT_STRING_TAGS),\n sorted(self.check.string_tags))\n self.assertListEqual(sorted(['ups.ignoreme'] + self.check.DEFAULT_EXCLUDED_TAGS),\n sorted(self.check.excluded))\n self.assertListEqual([re.compile('ups\\.ignore\\..*')], self.check.excluded_re)\n self.assertListEqual(['ignoreme'], self.check.excluded_devices)\n self.assertListEqual([re.compile('ignore\\..*')], self.check.excluded_devices_re)\n\n @mock.patch('subprocess.check_output')\n def test_list_ups_devices(self, mock_iocall):\n self.load_check(self.TEST_CHECK_CONFIG, {})\n self.check.update_from_config(self.TEST_CHECK_CONFIG['instances'][0])\n\n mock_iocall.return_value = '\\n'.join(['ignoreme', 'ignore.me.too', 'testUps'])\n self.assertListEqual(sorted(['ignoreme', 'ignore.me.too', 'testUps']),\n sorted(self.check.list_ups_devices()))\n\n @mock.patch('subprocess.check_output')\n def test_query_ups_device(self, mock_iocall):\n self.load_check(self.TEST_CHECK_CONFIG, {})\n self.check.update_from_config(self.TEST_CHECK_CONFIG['instances'][0])\n\n mock_iocall.return_value = '\\n'.join(['ups.status: OL', 'battery.charge: 100'])\n self.assertDictEqual({'ups.status': 'OL', 'battery.charge': '100'}, self.check.query_ups_device('testUps'))\n\n def test_convert_and_filter_stats(self):\n self.load_check(self.TEST_CHECK_CONFIG, {})\n self.check.update_from_config(self.TEST_CHECK_CONFIG['instances'][0])\n\n test_stats = {'ups.status': 'OL', 'battery.charge': '100', 'ups.testStringTag': 'foo Bar-*/baz',\n 'device.mfr': 'CPS', 'device.model': 'OR700VAU1'}\n result_stats, tags = self.check.convert_and_filter_stats(test_stats)\n self.assertDictEqual({'ups.status': 1.0, 'battery.charge': 100.0}, result_stats)\n self.assertListEqual(\n sorted(['ups.testStringTag:foo__bar_baz', 'foo:bar', 'device.mfr:cps', 'device.model:or700_vau1']),\n sorted(tags)\n )\n\n @mock.patch('subprocess.check_output')\n def test_check(self, mock_iocall):\n \"\"\"\n Testing Upsc check.\n \"\"\"\n self.load_check(self.TEST_CHECK_CONFIG, {})\n\n # run your actual tests...\n mock_list_results = '\\n'.join(['ignoreme', 'ignore.me.too', 'testUps'])\n mock_query_results = '\\n'.join(['ups.status: OL', 'battery.charge: 100', 'ups.testStringTag: foo Bar-*/baz',\n 'ups.ignoreme: 1', 'ups.ignore.me.too: 3', 'device.mfr: CPS',\n 'device.model: OR700VAU1'])\n\n results = [\n mock_list_results, mock_query_results, mock_query_results, mock_query_results, mock_query_results\n ]\n\n def sequence_calls(*args, **kwargs):\n return results.pop(0)\n\n mock_iocall.side_effect = sequence_calls\n\n self.run_check(self.TEST_CHECK_CONFIG['instances'][0])\n\n test_tags = ['foo:bar', 'ups.testStringTag:foo__bar_baz', 'device.mfr:cps', 'device.model:or700_vau1']\n\n test_cases = (\n ('battery.charge', 1, 100.0),\n ('ups.status', 1, 1.0),\n )\n\n for name, count, value in test_cases:\n self.assertMetric(\n 'upsc.{}'.format(name),\n count=count,\n value=value,\n tags=test_tags\n )\n\n # Raises when COVERAGE=true and coverage < 100%\n self.coverage_report()\n","sub_path":"upsc/test_upsc.py","file_name":"test_upsc.py","file_ext":"py","file_size_in_byte":5012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"488066389","text":"from __future__ import division\nfrom buy import Buy\n#from quote_buy import QuoteBuy\nfrom sell import Sell\nfrom give import Give # tests give and messaging\nfrom logger import LoggerTest\nfrom endowment import Endowment\nfrom abce import *\n\n\nfor parameters in read_parameters('simulation_parameters.csv'):\n s = Simulation(parameters)\n action_list = [\n repeat([\n ('all', 'one'),\n ('all', 'two'),\n ('all', 'three'),\n ('all', 'clean_up')\n ], 1000),\n ('endowment', 'Iconsume'),\n ('all', 'all_tests_completed')\n\n ]\n s.add_action_list(action_list)\n\n s.build_agents(Buy, 2)\n #s.build_agents(QuoteBuy, 2)\n s.build_agents(Sell, 2)\n s.build_agents(Give, 2) # tests give and messaging\n s.build_agents(Endowment, 2) # tests declare_round_endowment and declare_perishable\n s.build_agents(LoggerTest, 1)\n\n s.declare_round_endowment(resource='labor_endowment', productivity=5, product='labor')\n s.declare_round_endowment(resource='cow', productivity=10, product='milk')\n s.declare_perishable(good='labor')\n\n # s.panel_data('Firm', command='buy_log')\n\n s.run()\n\n","sub_path":"unittest/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"55013492","text":"class Movie():\r\n\r\n # Enables movie related information to be stored\r\n def __init__(self,\r\n movie_title,\r\n friendly_name,\r\n movie_trailer,\r\n movie_parental_rating):\r\n self.title=movie_title\r\n self.trailer_youtube_url=movie_trailer\r\n self.parental_rating=movie_parental_rating\r\n # set poster image URL based on movie name\r\n self.poster_image_url= \"i/movie_poster/\" + friendly_name + \".jpg\"\r\n","sub_path":"media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"582086899","text":"from slacky.config import load_config as lc\nfrom slacky.api.auth import authenticate\nfrom colorama import init\nfrom colorama import Fore, Back, Style\nfrom time import time\nimport httpx, json, logging, getpass\n\nwith open('version.txt', 'r') as file:\n version = file.read()\n\nres = httpx.get('https://raw.githubusercontent.com/M4cs/Slacky/blob/master/version.txt').content\n\nclass Prefixes:\n info = str('[' + Fore.GREEN + Style.BRIGHT + 'INFO' + Style.RESET_ALL + '] ')\n warning = str('[' + Fore.YELLOW + Style.BRIGHT + 'WARNING' + Style.RESET_ALL + '] ')\n event = str('[' + Fore.BLUE + Style.BRIGHT + 'EVENT' + Style.RESET_ALL + '] ')\n error = str('[' + Fore.RED + Style.BRIGHT + 'ERROR' + Style.RESET_ALL + '] ')\n start = str('[' + Fore.LIGHTBLUE_EX + Style.BRIGHT + 'SLACKY' + Style.RESET_ALL + '] ')\n\nclass Listeners:\n def __init__(self, config):\n self.listeners = config['listeners']\n\n def add(self, phrase):\n self.listeners.append(phrase)\n with open('config.json', 'r+') as file:\n obj = json.load(file)\n obj['listeners'] = self.listeners\n file.seek(0)\n json.dump(obj, file, indent=4)\n file.truncate()\n \n def delete(self, phrase):\n num = self.listeners.index(phrase)\n del self.listeners[num]\n with open('config.json', 'r+') as file:\n obj = json.load(file)\n obj['listeners'] = self.listeners\n file.seek(0)\n json.dump(obj, file, indent=4)\n file.truncate()\n\nprint(Prefixes.start + 'Welcome to Slacky v1 | The First Python Self-Bot for Slack!')\nconfig = lc()\nif not config:\n print(Prefixes.warning + 'No Config File Found. Starting Wizard.')\n print(Prefixes.start + 'Enter Legacy Workspace Token (Starts w/ xoxp)')\n token = input('> ')\n print(Prefixes.start + 'Enter User ID. Google How To Get This.')\n user_id = input('> ')\n print(Prefixes.start + 'Enter Desired Prefix')\n prefix = input('> ')\n print(Prefixes.info + 'Entered Token:', token)\n print(Prefixes.info + 'Entered User ID:', user_id)\n print(Prefixes.info + 'Entered Prefix:', prefix)\n print(Prefixes.start + 'Press ENTER to Confirm Information or Ctrl+C to Quit.')\n getpass.getpass('')\n with open('config.json', 'w+') as file:\n config = {\n 'token': token,\n 'user': user_id,\n 'prefix': prefix,\n 'listeners': []\n }\n json.dump(config, file, indent=4)\n print(Prefixes.event + 'Config Saved! Please Restart To Use Slacky')\n exit(0)\n\nprint(Prefixes.info + 'Config Loaded')\nprint(Prefixes.event + 'Attempting to Authenticate with Slack', end='\\r')\nlistener = Listeners(config)\nclient = authenticate(config)\nif not client:\n print(Prefixes.error + 'Could Not Authenticate with Slack! Please check your config and token!')\nprint(' ' * 65, end='\\r')\nprint(Prefixes.info + 'Authentication Successful!')\n","sub_path":"slacky/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"126583158","text":"import pathlib\n\nfrom setuptools import setup\n\npkg_name = 'pura'\nbase_dir = pathlib.Path(__file__).parent\nwith open(base_dir / 'src' / pkg_name / '_version.py') as f:\n version_globals = {}\n exec(f.read(), version_globals)\n version = version_globals['__version__']\n\nsetup(\n name=pkg_name,\n description='The little async embedded visualization framework that could',\n long_description='''\nPura is a simple embedded visualization framework inspired by the\nProcessing API and based on the python-trio async/await event loop.\n''',\n long_description_content_type='text/markdown',\n version=version,\n author='GROOVE X, Inc.',\n author_email='gx-sw@groove-x.com',\n url='https://github.com/groove-x/pura',\n license='MIT',\n packages=[pkg_name],\n package_dir={'': 'src'},\n install_requires=[\n 'attrs >= 19.2.0', # for \"eq\"\n 'h11 >= 0.9.0',\n 'trio >= 0.11.0',\n 'trio-util >= 0.1.0',\n 'trio-websocket >= 0.8.0'\n ],\n python_requires='>=3.7',\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3 :: Only',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Framework :: Trio',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"152027105","text":"from random import choice\r\n\r\n# Grab a word for guessing from a pre-made list\r\nrandom_word_list = choice([\"horse\", \"apple\", \"chair\"])\r\n\r\n# user input\r\ninput_char = input(\"What is your guess? \")\r\n\r\n# User-defined function\r\n\r\n\r\ndef word_check(input_char):\r\n \"\"\"\r\n 1. Make sure guess is a single letter\r\n 2. if that letter is in words_list\r\n 3. how many times it appears in\r\n 4. print the letters out\r\n 5. counter to limit guesses\r\n \"\"\"\r\n\r\n\r\nletter_appears = 0 # 3\r\nguess_limit = 5 # 5\r\nwhile True:\r\n guess_limit += 1 # 5\r\n letter_appears += 1 # 1\r\n for letter in random_word_list:\r\n if letter in random_word_list: # 2\r\n print(letter) # 4\r\n else:\r\n print(\"Try again: \") # 4\r\n break\r\n\r\n\r\n# single_letter = 1 # 1\r\nif len(input_char) > 1:\r\n print(\"Only 1 character allowed!\")\r\n","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"562053641","text":"from django.core.exceptions import ObjectDoesNotExist\nfrom django.core.management.base import BaseCommand, CommandError\nfrom django.db import IntegrityError\nfrom workshops.util import \\\n upload_person_task_csv, \\\n verify_upload_person_task, \\\n create_uploaded_persons_tasks\n\nclass Command(BaseCommand):\n args = 'filename'\n help = 'Upload users and roles from the given CSV files.'\n\n def handle(self, *args, **options):\n if len(args) != 1:\n raise CommandError('No CSV filename specified')\n filename = args[0]\n\n try:\n with open(filename, 'r') as reader:\n persons_tasks, empty_fields = upload_person_task_csv(reader)\n except Exception as e:\n raise CommandError('Failed to read CSV file: {0}'.format(str(e)))\n\n if empty_fields:\n missing = ', '.join(empty_fields)\n raise CommandError('Missing field(s) in {0}: {1}'.format(filename, missing))\n\n errors = verify_upload_person_task(persons_tasks)\n if errors:\n raise CommandError('Errors in upload:\\n{0}'.format('\\n'.join(errors)))\n\n try:\n persons, tasks = create_uploaded_persons_tasks(persons_tasks)\n except (IntegrityError, ObjectDoesNotExist) as e:\n raise CommandError('Failed to create persons/tasks: {0}'.format(str(e)))\n\n for p in persons:\n print(p)\n for t in tasks:\n print(t)\n","sub_path":"workshops/management/commands/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"377335491","text":"import numpy as np\nimport dirichlet\nimport plotter\n\ndef writeToFile(U, sfile):\n n = len(U)\n\n for i in range(0, n):\n for j in range(0 , n):\n sfile.write('%4f' % U[i][j] + '\\t')\n sfile.write('\\n')\n\nn = 100\nh = 1 / n\n\nX = np.arange(0, 1+h, h)\nY = np.arange(0, 1+h, h)\n\nU = np.array(dirichlet.solDirichlet(len(X)))\nG = np.array(dirichlet.getDirichlet(X, Y))\n\nprint('error = ', dirichlet.error(U,G))\n\nplotter.plotSurface(X, Y, U, 'Numerical Solution')\nplotter.plotSurface(X, Y, G, 'Analitical Sulution')\nplotter.plotContour(X, Y, U, n = 15, title = 'Numerical Solution')\nplotter.plotContour(X, Y, G, n = 15, title = 'Analitical Sulution')","sub_path":"equation/DirichletPy/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"464695229","text":"\"\"\"\nSC101 Baby Names Project\nAdapted from Nick Parlante's Baby Names assignment by\nJerry Liao.\nread and add the data to the dictionary\nName: Charlie Liu\n\"\"\"\n\nimport sys\n\n\ndef add_data_for_name(name_data, year, rank, name):\n \"\"\"\n Adds the given year and rank to the associated name in the name_data dict.\n Input:\n name_data (dict): dict holding baby name data\n year (str): the year of the data entry to add\n rank (str): the rank of the data entry to add\n name (str): the name of the data entry to add\n Output:\n This function modifies the name_data dict to store the provided\n name, year, and rank. This function does not return any values.\n \"\"\"\n year_rank_d = {} # a dictionary, key is year and value is rank\n year_rank_d[year] = rank # put to key value pair\n if name in name_data: # if name exist in dictionary\n if year in name_data[name]: # if year exist in year_rank_dictionary\n rank_temp = name_data[name][year] # set a variable - rank_temp, use it to compare rank\n if int(rank_temp) > int(rank): # if rank is smaller\n name_data[name][year] = rank # assign rank to value\n else: # if rank_temp is smaller\n name_data[name][year] = rank_temp # assign rank_temp to value\n else: # if year do not exist\n name_data[name][year] = rank # add year rank to dictionary\n else:\n name_data[name] = year_rank_d # if name do not exist, add name and year_rank_dictionary pair\n\n\ndef add_file(name_data, filename):\n \"\"\"\n Reads the information from the specified file and populates the name_data\n dict with the data found in the file.\n\n Input:\n name_data (dict): dict holding baby name data\n filename (str): name of the file holding baby name data\n\n Output:\n This function modifies the name_data dict to store information from\n the provided file name. This function does not return any value.\n\n \"\"\"\n\n with open(filename, 'r') as f:\n year = '' # a string to storage year\n for line in f: # for every line in the file\n data_list = line.split(',') # separate line using \",\"\n if len(data_list) == 1: # if the length og the line is 1\n year = data_list[0] # get the value\n year = year.strip() # erase all the spacing\n else:\n rank = data_list[0] # get the rank value\n rank = rank.strip() # erase all the spacing\n name1 = data_list[1] # get the name value\n name1 = name1.strip() # erase all the spacing\n name2 = data_list[2] # get the name value\n name2 = name2.strip() # erase all the spacing\n add_data_for_name(name_data, year, rank, name1) # add the name, rank, year to name_data dictionary\n add_data_for_name(name_data, year, rank, name2) # add the name, rank, year to name_data dictionary\n\n\ndef read_files(filenames):\n \"\"\"\n Reads the data from all files specified in the provided list\n into a single name_data dict and then returns that dict.\n\n Input:\n filenames (List[str]): a list of filenames containing baby name data\n\n Returns:\n name_data (dict): the dict storing all baby name data in a structured manner\n \"\"\"\n name_data = {} # create a dictionary for storage name year rank data\n for ele in filenames: # for every element in filenames\n add_file(name_data, ele) # add the text in the element (filename in filenames) to dictionary\n return name_data # return name_data dictionary\n\n\ndef search_names(name_data, target):\n \"\"\"\n Given a name_data dict that stores baby name information and a target string,\n returns a list of all names in the dict that contain the target string. This\n function should be case-insensitive with respect to the target string.\n\n Input:\n name_data (dict): a dict containing baby name data organized by name\n target (str): a string to look for in the names contained within name_data\n\n Returns:\n matching_names (List[str]): a list of all names from name_data that contain\n the target string\n\n \"\"\"\n names = [] # a list storage name fit target\n target = target.lower() # convert target into lower alphabet\n for ele in name_data: # for every element in name_data dictionary\n ele_lower = ele.lower() # convert element into lower alphabet\n if target in ele_lower: # if target in element\n names.append(ele) # add the element to the names list\n return names # return the list\n\n\ndef print_names(name_data):\n \"\"\"\n (provided, DO NOT MODIFY)\n Given a name_data dict, print out all its data, one name per line.\n The names are printed in alphabetical order,\n with the corresponding years data displayed in increasing order.\n\n Input:\n name_data (dict): a dict containing baby name data organized by name\n Returns:\n This function does not return anything\n \"\"\"\n for key, value in sorted(name_data.items()):\n print(key, sorted(value.items()))\n\n\ndef main():\n # (provided, DO NOT MODIFY)\n args = sys.argv[1:]\n # Two command line forms\n # 1. file1 file2 file3 ..\n # 2. -search target file1 file2 file3 ..\n\n # Assume no search, so list of filenames to read\n # is the args list\n filenames = args\n\n # Check if we are doing search, set target variable\n target = ''\n if len(args) >= 2 and args[0] == '-search':\n target = args[1]\n filenames = args[2:] # Update filenames to skip first 2\n\n # Read in all the filenames: baby-1990.txt, baby-2000.txt, ...\n names = read_files(filenames)\n\n # Either we do a search or just print everything.\n if len(target) > 0:\n search_results = search_names(names, target)\n for name in search_results:\n print(name)\n else:\n print_names(names)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"stanCode Projects/baby_name_searching_system/babynames.py","file_name":"babynames.py","file_ext":"py","file_size_in_byte":6754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"277889651","text":"from airflow.contrib.hooks.datadog_hook import DatadogHook\n\nhook = DatadogHook()\n\ntitle=\"Test airflow event\"\ntext=\"This is a test event from the airflow hook\"\nalert_type=\"error\"\ntags=[\"airflow_test\"]\n\n#test event to the org event stream\n#hook.post_event(title, text, aggregation_key=None, alert_type=alert_type, date_happened=None, \\\n# handle=None, priority=None, related_event_id=None, tags=tags, device_name=None)\n\nmetric_name=\"airflow_hook_test_metric\"\ndatapoint=1\ntags=[\"airflow_test\"]\nmetric_type=\"count\"\n\n#send a metric from the hook\n#hook.send_metric(metric_name, datapoint, tags=tags, type_=metric_type, interval=None)\n\nquery=\"avg:airflow_hook_test_metric{*}.as_count()\"\nfrom_seconds_ago=3600\nto_seconds_ago=0\nresponse={}\n\n#query a metric sent via the airflow datadog hook\n#response = hook.query_metric(query, from_seconds_ago, to_seconds_ago)\n#print(response)\n","sub_path":"datadog_hook_example.py","file_name":"datadog_hook_example.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"156407864","text":"#!/usr/bin/env python3\n\"\"\"This is an example to resume training programmatically.\"\"\"\n# pylint: disable=no-value-for-parameter\nimport click\n\nfrom garage import wrap_experiment\nfrom garage.trainer import Trainer\n\n\n@click.command()\n@click.option('--saved_dir',\n required=True,\n help='Path where snapshots are saved.')\n@wrap_experiment\ndef resume_experiment(ctxt, saved_dir):\n \"\"\"Resume a PyTorch experiment.\n\n Args:\n ctxt (garage.experiment.ExperimentContext): The experiment\n configuration used by Trainer to create the snapshotter.\n saved_dir (str): Path where snapshots are saved.\n\n \"\"\"\n trainer = Trainer(snapshot_config=ctxt)\n trainer.restore(from_dir=saved_dir)\n trainer.resume()\n\n\nresume_experiment()\n","sub_path":"src/garage/examples/torch/resume_training.py","file_name":"resume_training.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"133482009","text":"from django import forms\n'''\nAuthor Kamil Zajac\n'''\n\nfrom homework.models import Article\nfrom homework import fields\n\n#Class which provides and engine for\n#parsing custom fields as a form and \n#validates them as well\nclass DynamicForm(forms.Form):\n \n class Meta:\n model = Article\n exclude = ('title','created','modified','title_url',)\n \n def __init__(self, *args, **kwargs):\n from django.forms.widgets import DateInput\n extra = kwargs.pop('extra')\n super(DynamicForm, self).__init__(*args, **kwargs)\n counter = 1\n for tuple in extra:\n field_name = 'custom_field_' + str(counter)\n name = tuple[0]\n type = tuple[1].replace('.','')\n self.fields[field_name] = fields.createField(type)\n if len(tuple) > 2:\n self.fields[field_name].initial = tuple[2]\n self.fields[field_name].widget = fields.TypeWidget(attrs={}, type=type)\n self.fields[field_name].help_text = name.replace('_',' ')\n counter += 1\n","sub_path":"homework/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"243348164","text":"\"\"\"\n 1st: array interation\n\n Time O(N)\n Space O(1)\n 44 ms, faster than 25.00%\n\"\"\"\n\n\nclass Solution:\n def maxPower(self, s: str) -> int:\n maxCount = 0\n curCount = 0\n lastChar = ''\n for c in s:\n if c == lastChar:\n curCount += 1\n else:\n lastChar = c\n curCount = 1\n maxCount = max(maxCount, curCount)\n return maxCount\n\n\n\"\"\"\n 2nd: array interation\n - same logic as 1st approach\n\n Time O(N)\n Space O(1)\n 44 ms, faster than 25.00%\n\"\"\"\n\n\nclass Solution:\n def maxPower(self, s: str) -> int:\n maxCount = 1\n curCount = 1\n for i in range(1, len(s)):\n if s[i] == s[i-1]:\n curCount += 1\n else:\n curCount = 1\n maxCount = max(maxCount, curCount)\n return maxCount\n","sub_path":"leetcode/1446-consecutive-characters/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"190038353","text":"import pyaudio\nimport os\nimport listening\n# import simpleaudio as sa\nimport speech_recognition as sr\n\n# searchsound = sa.WaveObject.from_wave_file('sound/search.wav')\nindex = pyaudio.PyAudio().get_device_count() - 1\n\nprint (index)\n\nr = sr.Recognizer()\n\nif os.uname()[1] == 'raspberrypi':\n mic = sr.Microphone(1)\nelse:\n mic = sr.Microphone()\n\n\ndef recognize_search():\n # playsound = searchsound.play()\n # playsound.wait_done()\n print ('listening for phrase')\n with mic as source:\n audio = r.listen(source)\n response = {\n \"success\": True,\n \"error\": None,\n \"text\": None\n }\n try:\n response[\"text\"] = r.recognize_google(audio)\n except sr.RequestError:\n response[\"success\"] = False\n response[\"error\"] = \"unavailable\"\n except sr.UnknownValueError:\n response[\"error\"] = \"unknown\"\n\n if response['text']:\n\n phrase = response['text'].replace(\" \", \"_\")\n print ('phrase: ' + phrase)\n\nif __name__ == \"__main__\":\n while (1):\n print ('listening for keyword projector')\n listening.recognition(recognize_search, 'projector')","sub_path":"labvibes.py","file_name":"labvibes.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"39330305","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 29 03:03:45 2018\n\n@author: sun\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nimport pandas as pd\nimport matplotlib\n\nsns.set() \nmatplotlib.rcParams['figure.figsize'] = [12, 8]\n\npath = './rssi.csv'\ndata = pd.read_csv(path)\n\n\"\"\"\nRSSI신호 세기는 0에 가까울 수록(적을수록) 더 세다.\n차트의 크기를 8,20으로 지정\n차트를 그리기위한 subplot을 4행 2열로 지정\n\"\"\"\n\nfig = plt.figure(figsize=(8, 20))\nfrom itertools import product\n\naxs = fig.subplots(4,2)\nfor pair, ax in zip(product((1,2), (\"A\",\"B\",\"C\",\"D\")), axs.flatten()):\n (floor, ap) = pair\n mask = (data.z == floor) & (data.ap == ap)\n signal = data[mask][[\"signal\", \"x\", \"y\"]]\n ax.scatter(signal.x, signal.y, c=signal.signal)\n ax.set_title(\"Floor: %s AP: %s\" %(floor, ap))\n \nplt.savefig('rssi1.png')\nplt.show()\n \n# 각 샘플링 위치와 AP의 유클리드 거리를 구한다.\nap_coordinates = {\"A\": (23, 17, 2), \"B\": (23, 41, 2), \"C\" : (1, 15, 2), \"D\": (1, 41, 2)}\ng = data.groupby([\"x\", \"y\", \"z\", \"ap\"])\ndef dist(df):\n ap_coords = ap_coordinates[df.iloc[0].ap]\n x, y, z = ap_coords\n df[\"distance\"] = np.sqrt((df.x - x) ** 2 + (df.y - y) ** 2 + (df.z - z) ** 2)\n return df\nprint(data.head(5))\ndata = g.apply(dist)\nprint(data.head(5))\n\n\"\"\"\n수치가 적을 수록 신호가 강한 것임.\n구해지는 수치에 산란, 반산, 방해, 간섭 등의 오차가 있을 수 있음\nRSSI신호 세기는 0에 가까울 수록(적을수록) 더 세다.\n차트의 크기를 18,60으로 지정\n\"\"\"\n\nfig, axes = plt.subplots(4,2, figsize=(18, 16))\nfor pair, ax in zip(product((1,2), (\"A\",\"B\",\"C\",\"D\")), axes.flatten()):\n (floor, ap) = pair\n mask = (data.z == floor) & (data.ap == ap)\n signal = data[mask][[\"signal\", \"distance\"]]\n ax.plot(signal.distance, signal.signal, '.')\n ax.set_ylabel(\"RSSI\")\n ax.set_title(\"Floor %s, AP: %s\" %(floor, ap))\n \nplt.savefig('rssi2.png')\nplt.show()\n \nprint(data.head(5))\n\"\"\"\n최소, 최대, 평균, 중앙값을 기준으로 data값을 교차해 그림\n\"\"\"\n\nfig, axes = plt.subplots(2,2, figsize=(18, 16))\nestimators = [np.min, np.max, np.mean, np.median]\nfor ax, estimator in zip(axes.flatten(), estimators):\n mask = (data.z == 2) & (data.ap == \"A\")\n signal = data[mask][[\"signal\", \"distance\"]]\n sns.regplot(\"distance\", \"signal\", data=data, \n x_estimator=estimator, x_bins=100, ax=ax)\n ax.set_title(estimator.__name__)\n\nplt.savefig('rssi3.png')\nplt.show()\n","sub_path":"Python/Lab38/Beacon/rssi_detailnote.py","file_name":"rssi_detailnote.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"505416582","text":"import sys\nimport csv\n\n\nfilename = sys.argv[1]\nfrow = True\ntitle = []\ndata = []\nwith open(filename, 'r') as file:\n reader = csv.reader(file)\n for row in reader:\n if frow:\n title = row\n frow = False\n else:\n modrow = [row[0]]\n tot = 0\n for i in range(1, len(row)):\n modrow.append(int(row[i]))\n tot += int(row[i])\n modrow.append(tot)\n data.append(modrow)\n\nmaxMath = [0, 0]\nmaxBio = [0, 0]\nmaxEng = [0, 0]\nmaxPhy = [0, 0]\nmaxChem = [0, 0]\nmaxHindi = [0, 0]\nfor i in range(len(data)):\n if data[i][1] > maxMath[0]:\n maxMath[0] = data[i][1]\n maxMath[1] = data[i][0]\n if data[i][2] > maxBio[0]:\n maxBio[0] = data[i][2]\n maxBio[1] = data[i][0]\n if data[i][3] > maxEng[0]:\n maxEng[0] = data[i][3]\n maxEng[1] = data[i][0]\n if data[i][4] > maxPhy[0]:\n maxPhy[0] = data[i][4]\n maxPhy[1] = data[i][0]\n if data[i][5] > maxChem[0]:\n maxChem[0] = data[i][5]\n maxChem[1] = data[i][0]\n if data[i][6] > maxHindi[0]:\n maxHindi[0] = data[i][6]\n maxHindi[1] = data[i][0]\n\nprint(\"Topper in Maths is {}\".format(maxMath[1]))\nprint(\"Topper in Biology is {}\".format(maxBio[1]))\nprint(\"Topper in English is {}\".format(maxEng[1]))\nprint(\"Topper in Physics is {}\".format(maxPhy[1]))\nprint(\"Topper in Chemistry is {}\".format(maxChem[1]))\nprint(\"Topper in Hindi is {}\".format(maxHindi[1]))\n\nfirst = [0, 0]\nsecond = [0, 0]\nthird = [0, 0]\n\nfor i in range(len(data)):\n if data[i][7] > third[0]:\n if data[i][7] > second[0]:\n if data[i][7]>first[0]:\n second[0] = first[0]\n second[1] = first[1]\n first[0] = data[i][7]\n first[1] = data[i][0]\n else:\n third[0] = second[0]\n third[1] = second[1]\n second[0] = data[i][7]\n second[1] = data[i][0]\n else:\n third[0] = data[i][7]\n third[1] = data[i][0]\n\nprint(\"\\nBest students in the class are {}, {}, {} \".format(first[1], second[1], third[1]))\n","sub_path":"part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":2157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"546457856","text":"# encoding: utf-8\n\n\"\"\"\n# @Time : 2019-08-20 13:41\n# @Author : Function\n# @FileName : WriteYaml.py\n# @Software: PyCharm\n\n操作Yaml文件 存储appium启动命令\n\"\"\"\nimport yaml\nfrom AutoUI.Config.setting import yam_file\n\n\nclass WriteYamlCommand:\n @staticmethod\n def read_data():\n \"\"\"\n 加载yaml数据\n \"\"\"\n with open(yam_file) as fr:\n data = yaml.load(fr, Loader=yaml.FullLoader)\n return data\n\n def get_value(self, key, port):\n '''\n 获取value\n '''\n data = self.read_data()\n value = data[key][port]\n return value\n\n def write_data(self,i,device,bp,port,systemPort):\n \"\"\"\n 写入数据\n \"\"\"\n data = self.join_data(i,device,bp,port,systemPort)\n with open(\"../Config/AppiumPort.yaml\", \"a\") as fr:\n yaml.dump(data, fr)\n\n def join_data(self,i,device,bp,port,systemPort):\n \"\"\"\n 拼接启动命令\n :param port: 端口号\n :return: 返回拼接命令行\n \"\"\"\n data = {\n \"user_info_\" + str(i): {\n \"deviceName\": device,\n \"bp\": bp,\n \"port\": port,\n \"systemPort\":systemPort\n }\n }\n return data\n\n def clear_data(self):\n \"\"\"\n 清空Yaml文件清除内存(为kill appium做好准备)\n :return:\n \"\"\"\n with open(\"../Config/AppiumPort.yaml\", \"w\") as fr:\n fr.truncate()\n fr.close()\n\n def get_file_lines(self):\n \"\"\"\n 获取Yaml文件中的行数 给appium Server启动端启动appium服务\n :return:\n \"\"\"\n data = self.read_data()\n return len(data)\n\n\nif __name__ == \"__main__\":\n w = WriteYamlCommand()\n a = w.get_value('user_info_' + str(1), 'port')\n print(a)\n\n\n\n\n\n\n\n\n\n","sub_path":"AutoUI/Util/WriteYaml.py","file_name":"WriteYaml.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"35489797","text":"import urllib.request\n\n\ndef red_text():\n quotes = open(\"Movie.txt\");\n contents_of_files = quotes.read()\n quotes.close()\n chech_profanity(contents_of_files)\n\n \ndef chech_profanity(text_to_check):\n print(text_to_check)\n connection = urllib.request.urlopen(\"http://www.wdyl.com/profanity?q=\"+ urllib.parse.quote(text_to_check))\n output = connection.read()\n print(output)\n connection.close()\n \nred_text()\n","sub_path":"exercise-5/ScanForCurseWords.py","file_name":"ScanForCurseWords.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"130798357","text":"import sys\n\nfrom scanner import Scanner\nfrom selenium import webdriver\n\nfrom validator import is_valid_url\n\n\ndef handle_terminal_args(args, driver):\n if len(args) == 2:\n https_address = sys.argv.pop()\n if is_valid_url(https_address):\n driver.get(https_address)\n driver.maximize_window()\n else:\n driver.quit()\n print(\"please run again with valid url: for example :: 'https://www.google.com'\")\n exit()\n else:\n driver.minimize_window()\n valid_address = input(\"Please input valid url:\\n\")\n match = is_valid_url(valid_address)\n while not match:\n valid_address = input(\"Please input valid url: for example 'https://www.google.com'\\n\")\n match = is_valid_url(valid_address)\n if match:\n driver.maximize_window()\n driver.get(valid_address)\n\n\nscan = Scanner(webdriver.Chrome(\"drivers/chromedriver\"))\nhandle_terminal_args(sys.argv, scan.get_driver())\n\nscan.number_of_html_form_elements()\nscan.number_of_html_image_tags()\n\nscan.quit_driver()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"227216598","text":"from frame.extensions.templates import Jinja2Driver, TemplateDriver\nfrom frame.dotdict import DotDict\nfrom jinja2 import Environment, ChoiceLoader, PackageLoader, FileSystemLoader\n\n\njade_config = DotDict({\n 'environment': None\n})\n\n\nclass JadeDriver(Jinja2Driver):\n def __init__(self, **options):\n TemplateDriver.__init__(self, **options)\n\n loaders = list(options['loaders'])\n loaders.insert(0, FileSystemLoader(options['directory']))\n\n if jade_config.environment:\n self.environment = jade_config.environment\n else:\n self.environment = Environment(\n loader=ChoiceLoader(loaders),\n extensions=options['extensions'] + ['pyjade.ext.jinja.PyJadeExtension'])\n\n\ndef register_config(config):\n config.templates.jade = jade_config\n\n\ndef register_driver(drivers):\n drivers.register('template', 'jade', JadeDriver)","sub_path":"venv/Lib/site-packages/frame/extensions/jade.py","file_name":"jade.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"289409790","text":"import matplotlib.pylab as plt\nimport argparse\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-x\", \"--xVector\", nargs='+', type=float, required=True, help=\"Vector with x coordinates\")\nap.add_argument(\"-y\", \"--yVector\", nargs='+', type=float, required=True, help=\"Vector with y coordinates\")\nap.add_argument(\"-t\", \"--plotTrue\", type=int, required=True, help=\"Flag for true points plot\")\nap.add_argument(\"-xT\", \"--xTrueVector\", nargs='+', type=float, help=\"Vector with x coordinates\")\nap.add_argument(\"-yT\", \"--yTrueVector\", nargs='+', type=float, help=\"Vector with y coordinates\")\nargs = vars(ap.parse_args())\n\n#plt.axhline(0, color='k')\n#plt.axvline(0, color='k')\nif (args[\"plotTrue\"]):\n\tplt.plot(args[\"xTrueVector\"], args[\"yTrueVector\"], 'o')\nplt.plot(args[\"xVector\"], args[\"yVector\"])\nplt.show() ","sub_path":"Tarea6/Ejercicio1/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"8090693","text":"def before_all(context):\n import os\n import django\n\n os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tests.settings')\n django.setup()\n\n from django.test import utils\n utils.setup_test_environment()\n\n\ndef before_scenario(context, scenario):\n from django.db import connection\n connection.creation.create_test_db(verbosity=0, autoclobber=True)\n\n # Set-up webtest app\n\n # Ensure settings are patched just like in django_webtest\n from django.conf import settings\n\n # Copied from django_webtest\n context._cached_middleware = settings.MIDDLEWARE_CLASSES\n context._cached_auth_backends = settings.AUTHENTICATION_BACKENDS\n\n webtest_auth_middleware = 'django_webtest.middleware.WebtestUserMiddleware'\n django_auth_middleware = 'django.contrib.auth.middleware.AuthenticationMiddleware'\n\n settings.MIDDLEWARE_CLASSES = list(settings.MIDDLEWARE_CLASSES)\n if django_auth_middleware not in settings.MIDDLEWARE_CLASSES:\n # There can be a custom AuthenticationMiddleware subclass or\n # replacement, we can't compute its index so just put our auth\n # middleware to the end. If appending causes problems\n # _setup_auth_middleware method can be overriden by a subclass.\n settings.MIDDLEWARE_CLASSES.append(webtest_auth_middleware)\n else:\n index = settings.MIDDLEWARE_CLASSES.index(django_auth_middleware)\n settings.MIDDLEWARE_CLASSES.insert(index + 1, webtest_auth_middleware)\n\n settings.AUTHENTICATION_BACKENDS = list(settings.AUTHENTICATION_BACKENDS)\n backend_name = 'django_webtest.backends.WebtestUserBackend'\n settings.AUTHENTICATION_BACKENDS.insert(0, backend_name)\n\n from django_webtest import DjangoTestApp\n context.browser = DjangoTestApp()\n\n\ndef after_scenario(context, scenario):\n from django.db import connection\n connection.creation.destroy_test_db('', verbosity=0)\n\n from django.conf import settings\n settings.MIDDLEWARE_CLASSES = context._cached_middleware\n settings.AUTHENTICATION_BACKENDS = context._cached_auth_backends\n\n\ndef after_all(context):\n from django.test import utils\n utils.teardown_test_environment()\n","sub_path":"tests/features/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"389246202","text":"import json, string\nimport random\nfrom os import path\n\nif not path.exists(\".flaskenv\"):\n\tf = open(\".flaskenv\", \"w+\")\n\tf.write(\"set FLASK_APP = main.py\")\n\tf.close()\n\nwith open(\"config.json\", \"r\") as f:\n\tconfig = json.load(f)\n\tf.close()\n\tchars = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\\\"#$%&'()*+,-./:;<=>?@[]^_`{|}~\"\n\tconfig[\"SECRET\"] = \"\".join(random.choice(chars) for i in range(32))\n\twith open(\"config.json\", \"w\") as f:\n\t\tjson.dump(config, f, indent = 4)\n\t\tf.close()\n","sub_path":"install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"147509902","text":"#!/usr/bin/python\nimport sys\nimport numpy as np\nimport pandas as pd\ndf = pd.read_csv(str(sys.argv[1]), header=1) # TOF\ndf[df.columns[0]] = pd.to_datetime(df[df.columns[0]])\ndf.drop(df.columns[2], axis=1, inplace=True)\ndf = df.rename(\n columns={df.columns[0]: 'time', df.columns[1]: 'pressure'})\n#df = df.convert_dtypes()\ndf['pressure'].replace('', np.nan, inplace=True)\ndf.dropna(subset=['pressure'], inplace=True)\n\ndf['fSec'] = df[df.columns[0]].map(\n (lambda x: (x - pd.Timestamp(\"1970-01-01 00:00:00.000\")) // pd.Timedelta('1s')))\ndf['fNanoSec'] = df[df.columns[0]].map((lambda x: int(\n str((x - pd.Timestamp(\"1970-01-01 00:00:00.000\")) // pd.Timedelta('1ns'))[10:])))\n\ndf.drop(df.columns[0], axis=1, inplace=True)\n\ndf = df.reindex(columns=['fSec', 'fNanoSec', 'pressure'])\n\ndf.fSec = pd.to_numeric(df.fSec, errors='ignore')\ndf = df[df.fSec >= 1535894231]\ndf = df[df.fSec <= 1535994231]\n\nprint(df)\n","sub_path":"pres.py","file_name":"pres.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"517859491","text":"# -*- coding: utf-8 -*-\n\nimport pygame\nfrom threading import Lock\n\nmutex = Lock()\n\nclass cachorro:\n pos_x=0\n pos_y=0\n imagem = None\n power_level = 0\n buracos = [3]\n listaBuracos = []\n tamanho_y = 60\n tamanho_x = 60\n \n \n \n \n def __init__(self, pos_x,pos_y,power_level):\n self.pos_x = pos_x\n self.pos_y = pos_y\n self.power_level = power_level\n self.quantidadeBuracos = 0\n self.listaBuracos = [power_level]\n self.tamanho_y = 40\n self.tamanho_x = 40\n \n\n def spawn_dog(x, y, p_level):\n c = cachorro(x,y,p_level)\n c.imagem = pygame.image.load('Cachorro/caoBaixo.png')\n return c\n \n def dog_up(vel, c):\n mutex.acquire(1)\n try:\n c.pos_y -= vel\n c.imagem = pygame.image.load('Cachorro/caoCima.png')\n finally:\n mutex.release()\n return c\n \n def dog_down(vel, c):\n mutex.acquire(1)\n try:\n c.pos_y += vel\n c.imagem = pygame.image.load('Cachorro/caoBaixo.png')\n finally:\n mutex.release()\n return c\n \n def dog_left(vel, c):\n mutex.acquire(1)\n try:\n c.pos_x -= vel\n c.imagem = pygame.image.load('Cachorro/caoEsquerda.png')\n finally:\n mutex.release()\n return c\n \n def dog_right(vel, c):\n mutex.acquire(1)\n try:\n c.pos_x += vel\n c.imagem = pygame.image.load('Cachorro/caoDireita.png')\n finally:\n mutex.release()\n return c\n \n def dog_buraco(c):\n c.quantidadeBuracos +=1\n c.buracos.append(c.pos_x)\n c.buracos.append(c.pos_y)\n c.listaBuracos.append(c.buracos) \n return c\n","sub_path":"Sistemas Operacionais/Jogo Python/cachorro.py","file_name":"cachorro.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"486522862","text":"# there is a cycle\ndirected_graph_loop = {\n 'A':{'B'}, \n 'B':{'D'}, \n 'C':{'B','E'}, \n 'D':{'G','H'},\n 'I':{'J'},\n 'F':{'C'},\n 'G':{'F'} \n }\n\n# no cycle\ndirected_graph_loop2 = {\n 'A':{'B'}, \n 'B':{'D','C'}, \n 'C':{'E'}, \n 'D':{'G','H'},\n 'I':{'J'},\n 'F':{'C'},\n }\n\n\n# bfs way\n# check if there is no cycle\n# using iterative bfs\n# it ignores vertice that leads to cycle\n# and count the number of non-cycle vertex\n\ndef has_cycle(graph):\n # calc indegrees\n indegrees = dict()\n for e in graph:\n val = indegrees.get(e, 0)\n indegrees[e] = val\n for v in graph[e]:\n val = indegrees.get(v, 0)\n indegrees[v] = val + 1\n\n q = [x for x in indegrees if indegrees[x] == 0]\n cnt = 0\n while len(q) > 0:\n t = q.pop(0)\n cnt += 1\n if t in graph:\n for x in graph[t]:\n indegrees[x] -= 1\n if indegrees[x] == 0:\n q.append(x)\n return cnt != len(indegrees)\n \n\n# dfs way\n# the graph can be a forest, so we need to mark nodes with different colors\n# 0, not visited, 1, being visited now, 2, visited before\ndef has_cycle2(graph):\n seen = dict()\n def _dfs(graph, seen, vertex):\n if seen.get(vertex, 0) == 1: \n return True\n seen[vertex] = 1\n res = False\n if vertex in graph:\n for x in graph[vertex]:\n if _dfs(graph, seen, x):\n res = True\n break\n seen[vertex] = 2\n return res\n\n for e in graph:\n if len(e) > 0 and seen.get(e[0], 0) == 0 and _dfs(graph, seen, e[0]):\n return True\n return False\n\n# union find\n# for directed graph, union find may not work, as there may be more than one\n# edges come out or go into a node.\n# it is ok to use union find to detect weak cycles (ignore directions), but not\n# strong cycles\n# another big advantage is, union find can dynamically detect cycle in undirected graph\n# without creating a full graph beforehand\nclass UF:\n def __init__(self, path_compress=True):\n self.root = dict()\n self.rank = dict()\n self.path_comp = path_compress\n\n def findRoot(self, vertex):\n v = vertex\n while v != None:\n vertex = v \n v = self.root.get(vertex, None) \n return vertex\n\n def connect(self, a, b):\n ra, rb = self.findRoot(a), self.findRoot(b)\n if ra == rb:\n return False\n else:\n if self.path_comp:\n rk1, rk2 = self.rank.get(ra, 0), self.rank.get(rb, 0)\n if rk1 < rk2:\n self.root[ra] = rb\n elif rk1 > rk2:\n self.root[rb] = ra\n else:\n self.root[rb] = ra\n self.rank[ra] = rk1 + 1\n else:\n self.root[b] = a\n return True\n\ndef has_cycle3(graph):\n uf = UF()\n for e in graph:\n if len(graph[e]) > 0:\n for x in graph[e]:\n if not uf.connect(e, x):\n return True\n return False\n\n\nif __name__ == '__main__':\n ret = has_cycle(directed_graph_loop)\n print(\"bfs: directed_graph_loop has loop: \", ret)\n\n ret = has_cycle(directed_graph_loop2)\n print(\"bfs: directed_graph_loop2 has loop: \", ret)\n\n\n ret = has_cycle2(directed_graph_loop)\n print(\"dfs: directed_graph_loop has loop: \", ret)\n\n ret = has_cycle2(directed_graph_loop2)\n print(\"dfs: directed_graph_loop2 has loop: \", ret)\n\n ret = has_cycle3(directed_graph_loop)\n print(\"union find: directed_graph_loop has loop: \", ret)\n\n ret = has_cycle3(directed_graph_loop2)\n print(\"union find: directed_graph_loop2 has loop: \", ret)\n\n\n","sub_path":"loop.py","file_name":"loop.py","file_ext":"py","file_size_in_byte":3827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"296224613","text":"from time import sleep\r\nimport threading\r\nimport datetime\r\n\r\nfrom Interlocutor import *\r\nfrom ConsoleChatEmulator import ConsoleChatEmulator\r\nfrom Logger import *\r\n\r\nlogger = Logger()\r\nchatEnv = ConsoleChatEmulator(logger)\r\n\r\ndef mainLoop():\r\n\tglobal chatEnv\r\n\tglobal logger\r\n\twhile True:\r\n\t\tchatEnv.is_conversation_going = True\r\n\t\tinterlocutor = Interlocutor(datetime.datetime.now(), logger)\r\n\t\twhile chatEnv.IsConversationGoing() and interlocutor.ContinueConversation():\r\n\t\t\tinterlocutor.OnMessagesReceived(chatEnv.NewMessages())\r\n\t\t\tmsg = interlocutor.Speak()\r\n\t\t\tif msg:\r\n\t\t\t\tchatEnv.Say(msg)\r\n\t\t\tsleep(0.05)\r\n\r\nthread = threading.Thread(target=mainLoop)\r\nthread.daemon = True\r\nthread.start()\r\nwhile True:\r\n\tmsgText = input('Вы: ')\r\n\tchatEnv.OnNewMessage(msgText)\r\n\tsleep(0.1)\r\n","sub_path":"local_sample.py","file_name":"local_sample.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"390225496","text":"from typing import TypeVar, Generic\n\nfrom fp.list import List\nfrom fp.option import Option\nfrom fp.validation import Validation\n\nA = TypeVar('A')\nB = TypeVar('B')\nErr = TypeVar('Err')\n\n\nclass OptionSequence(Generic[A]):\n\n @classmethod\n def sequence(cls, xs: List[Option[A]]) -> Option[List[A]]:\n \"\"\"\n Evaluate each action in the sequence from left to right, and collect the results\n effectively converting F[G[A]] into an G[F[A]].\n \"\"\"\n _, xs = xs.partition(lambda x: x.is_empty())\n if xs.is_empty():\n return Option.empty()\n else:\n return Option(xs.map(lambda x: x.get()))\n\n\nclass ValidationSequence(Generic[A]):\n\n @classmethod\n def sequence(cls, xs: List[Validation]) -> Validation[List[Err], List[A]]:\n \"\"\"\n Evaluate each action in the sequence from left to right, and collect the results\n effectively converting F[G[A]] into an G[F[A]].\n \"\"\"\n err, succ = xs.partition(lambda x: x.is_failure())\n if err.is_empty():\n xs = succ.map(lambda x: x.get())\n return Validation.success(xs)\n else:\n xs = err.map(lambda x: x.get())\n return Validation.failure(xs)\n","sub_path":"fp/sequence.py","file_name":"sequence.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"519614767","text":"import GetOldTweets3 as got\nimport timeit\nimport time\nimport csv\n\ncountries = ['Australia', 'China', 'Spain', 'Italy', 'United States', 'Venezuela']\n#The approx mileage for each country radius to collect tweets from\ncountry_radius = [\"2500mi\", \"3250mi\", \"675mi\", \"250mi\", \"2500mi\", \"500mi\"]\ncountry_code = ['AU', 'CN', 'ES', 'IT', 'US', 'VE']\n\nmonth = 4\ndate = 1\nwithin = 0\ncode = 0\n\nfor country in countries:\n print(country)\n\n while date <= 12:\n\n print('2020-'+ str(month) + '-' + str(date))\n\n #GetOldTweets setup\n tweetCriteria = got.manager.TweetCriteria().setQuerySearch('Coronavirus')\\\n .setLang('en')\\\n .setNear(country)\\\n .setSince(\"2020-\"+ str(month) + \"-\" + str(date))\\\n .setUntil(\"2020-\"+ str(month) + \"-\" + str(date+1))\\\n .setMaxTweets(10000)\\\n .setWithin(country_radius[within])\n \n tweet = got.manager.TweetManager.getTweets(tweetCriteria, bufferLength = 10000)\n print(\"Collecting Tweets:\", len(tweet))\n\n date2 = \"04-0\" + str(date) + \"-2020\"\n\n date += 1\n\n #Places the tweets into a csv file for sentiment analysis\n if len(tweet) != 0:\n with open(f\"{country}/{country_code[code]}_{date2}.csv\", 'w', encoding='utf-8') as fd:\n writer = csv.writer(fd)\n writer.writerow([\"tweet\"])\n for tweets in tweet:\n text = tweets.text.replace('\\n', ' ').replace('\\r', '')\n writer.writerow([text])\n \n print(\"Sleeping\")\n time.sleep(600)\n\n date = 1\n within += 1\n code += 1\n","sub_path":"GetOldTweets/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"383481822","text":"# author : Sabyasachee Baruah\n\nimport numpy as np\nimport torch\nfrom torchcrf import CRF\nfrom torch import nn\nfrom transformers import BertModel\n\nclass TargetLabeler(nn.Module):\n '''\n Model to find target (entity and event) spans given the opinion expression and MPQA2 target span\n Hparams:\n Bert pretrained model name\n Max seq len\n Position Embedding Size\n BiLSTM hidden size\n BiLSTM num layers\n '''\n\n def __init__(self, hparams):\n super().__init__()\n self.hparams = hparams\n self.encoder = BertModel.from_pretrained(hparams.pretrained_model_name)\n self.expression_position_embedding = nn.Embedding(2 * hparams.max_seq_len, hparams.position_embedding_size)\n self.target_position_embedding = nn.Embedding(2 * hparams.max_seq_len, hparams.position_embedding_size)\n self.bilstm = nn.LSTM(self.encoder.config.hidden_size + 2 * hparams.position_embedding_size, hparams.hidden_size, num_layers=hparams.bilistm_n_layers, bidirectional=True, batch_first=True)\n self.output = nn.Linear(2 * hparams.hidden_size, 3)\n self.crf = CRF(3, batch_first=True)\n\n def forward(self, X_wordid, X_mask, pos, Y=None):\n # X_wordid is the batch-size x max-seq-len matrix of WordPiece token indices\n # X_mask is the batch-size x max-seq-len matrix of 0s and 1s.\n # X_mask = 0 for padded tokens, otherwise 1\n # \n # pos is the batch-size x 4 matrix\n # (pos[i, 0], pos[i, 1]) is the opinion expression span\n # (pos[i, 2], pos[i, 3]) is the target span\n # \n # Y is the batch-size x max-seq-len matrix of the token labels\n # O = 0, B = 1, I = 2\n # Padded tokens also have label O (= 0)\n # \n # If Y is not None, return loss\n # otherwise return Y_pred\n \n X_word = self.encoder(X_wordid, X_mask).last_hidden_state\n\n batch_size, max_seq_len = X_wordid.shape\n X_eposid = torch.tile(torch.LongTensor(np.arange(max_seq_len)), (batch_size, 1))\n X_tposid = torch.tile(torch.LongTensor(np.arange(max_seq_len)), (batch_size, 1))\n\n for i in range(batch_size):\n estart, eend, tstart, tend = pos[i]\n length = X_mask[i].sum()\n \n X_eposid[:estart] = estart - X_eposid[:estart]\n X_eposid[estart: eend] = 0\n X_eposid[eend:] = X_eposid[eend:] - eend + max_seq_len\n X_eposid[length:] = 2*max_seq_len - 1\n\n X_tposid[:tstart] = tstart - X_tposid[:tstart]\n X_tposid[tstart: tend] = 0\n X_tposid[tend:] = X_tposid[tend:] - tend + max_seq_len\n X_tposid[length:] = 2*max_seq_len - 1\n \n X_epos = self.expression_position_embedding(X_eposid)\n X_tpos = self.target_position_embedding(X_tposid)\n\n X = torch.cat((X_word, X_epos, X_tpos), dim=2)\n # X is of shape batch-size x max-seq-len x (Hw + 2 * Hpos)\n # Hw is the encoder hidden size, Hpos is the position embedding size\n\n A, _ = self.bilstm(X)\n A = A.contiguous()\n # A is of shape batch-size x max-seq-len x 2H\n # H is the hidden size\n\n B = self.output(A)\n # B is of shape batch-size x max-seq-len x 3\n\n crf_mask = X_mask.byte()\n Y_pred = self.crf.decode(B, crf_mask)\n # Y_pred is a list of list of integers\n\n if Y is not None:\n loss = -self.crf(B, Y, crf_mask)\n return loss, Y_pred\n else:\n return Y_pred\n","sub_path":"05-opinion-mining/target-labeler/models/TargetLabeler.py","file_name":"TargetLabeler.py","file_ext":"py","file_size_in_byte":3518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"172173804","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 10 14:31:12 2018\n\n@author: raja\n\"\"\"\n\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 8 15:59:48 2018\n\n@author: raja\n\"\"\"\n\n\nfrom skimage import io \nfrom skimage import color\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\nfrom scipy import ndimage\n\ndef find_feature(box):\n box=np.floor(box)\n box_list=box.ravel()\n hist,bins = np.histogram(box_list.ravel(),360,[0,360])\n \n b_bins=np.zeros(360)\n b_hist=np.zeros(360)\n for i in range(0,360):\n count=0\n for j in range(0,np.size(box_list)):\n if i==box_list[j]:\n count=count+1\n b_bins[i]=i\n b_hist[i]=count\n \n N_pix= np.size(box)\n N_g= b_hist\n P_g= N_g/N_pix\n g_g= b_bins\n \n his_mean=np.sum(g_g * P_g)+1\n his_SD = np.sqrt((np.sum(np.square(g_g-his_mean)*P_g)))\n his_skew = ((np.sum(((g_g-his_mean)**3)*P_g)))/(his_SD**3)\n his_energy = np.sum(P_g**2)\n his_entropy = -np.sum(P_g*np.log2(P_g+1))\n \n return his_mean, his_SD, his_skew, his_energy, his_entropy\n \n \n \n \n \n \n \n \n \n \nraja1= io.imread('/home/raja/Mod 7/test pics/potter.jpg')\nraja1=color.rgb2gray(raja1)*255\npic=np.copy(raja1)\n\npic=pic.astype(float)\n\nmask1=np.array([[1,0,-1]])\nmask2=np.array([[1],[0],[-1]])\n\nmask1=mask1.astype(float)\nmask2=mask2.astype(float)\n\nc1=ndimage.convolve(pic,mask1)\nc2=ndimage.convolve(pic,mask2)\n\n#io.imshow(c1)\n#io.imshow(c2)\nI1=c1.astype(float)\nI2=c2.astype(float)\n\nG=np.sqrt(np.square(I1)+np.square(I2))\n\n#acc= I2/(I1+0.0000000001)\n#theta= np.arctan(acc)\ntheta= np.arctan2(I2,I1)\nmod_G=G.astype(np.uint16)\n\ntheta_deg= np.rad2deg(theta)\nr,c = np.shape(theta_deg)\n\n\nfor i in range(0,r):\n for j in range(0,c):\n if theta_deg[i,j]<0:\n theta_deg[i,j]=theta_deg[i,j]+360\n \n \npic=np.copy(theta_deg)\nresult_pic=np.zeros(np.shape(theta_deg))\nfeatures_full=np.zeros((np.int(np.floor(r*c/6)),6))\nk1=8;k2=8;k=0\ntest_feature=np.zeros((1,5))\nfor i in range(0,r,8):\n for j in range(0,c,8):\n pic2= pic[i:i+k1,j:j+k2]\n #features_full[k,0:5]=find_feature(pic2)\n test_feature[0,0:5]=find_feature(pic2)\n result_pic[i:i+k1,j:j+k2]=svm1.predict(test_feature)\n #features_full[k,5]=1\n k=k+1\n \n \n \n \n \n \n\n","sub_path":"Pattern_Recognition/HOG_potter_test.py","file_name":"HOG_potter_test.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"406184228","text":"from scipy.io.wavfile import read\nfrom scipy.signal import stft\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams\nrcParams.update({'figure.autolayout': True})\n\n\ndef audiosignal(audiofile, info=None):\n \"\"\"\n This function is designed to:\n >>> Shorten an audiofile to amount of samples whithin 10 seconds if length of\n audiofile in seconds is greater than 10 seconds\n This is done by evaluating if amount of samples in total is greater than\n 10*samplingrate.\n >>> Only consider the first sound channel if the audio file consist \n of more than one sound channel.\n\n Parameters\n ----------\n audiofile : TYPE wav.file\n DESCRIPTION: Chosen audiofile\n \n info : TYPE, optional, bool\n DESCRIPTION: If True, info such as length of audiofile in seconds, in \n samples, amount of samples within 10 seconds is calculated \n and printed, and number of sound channnels is printed.\n Default: None\n \n Returns\n -------\n samplingrate : samples per second\n \n audio : TYPE, array of int16\n DESCRIPTION: Amplitude content in audiofile\n\n \"\"\"\n samplingrate,audio=read(audiofile)\n \n if info==True:\n print(f'''\n Input info:\n Length of input signal: {len(audio)/samplingrate:.0f} seconds\n Amount of samples in total: {len(audio):.0f} samples\n Amount of samples within 10 sec: {10*samplingrate} samples\n Number of sound channels: {np.size(audio[0])}\n_____________________________________________________________________________\n ''')\n \n amount_samples_total = len(audio)\n amount_samples_10s = 10*samplingrate\n nr_channels = np.size(audio[0])\n \n if amount_samples_total > amount_samples_10s and nr_channels == 1:\n audio= audio[0:10*samplingrate]\n print('Inputsignal is shortened to samples within 10 s')\n elif amount_samples_total > amount_samples_10s and nr_channels != 1:\n audio= audio[0:10*samplingrate:,0]\n print('Inputsignal is shortened to samples within 10 s and sound channel 1 is chosen')\n else:\n audio\n \n return samplingrate, audio\n\ndef FourierAndtimePLOTS(inputsignal, samplingrate):\n \"\"\"\n Plots of inputsignal in time domain and frequency domain.\n Note: The plot of inputsignal in frequency domain is onesided\n\n Parameters\n ----------\n inputsignal : TYPE array\n DESCRIPTION: the signal to be plotted in time domain and frequency domain\n samplingrate : TYPE int\n DESCRIPTION: The samplingrate of inout signal\n\n \"\"\"\n \n endpoint_of_fftplot = int(len(inputsignal)/2)\n \n fourier = np.fft.fft(inputsignal)\n fourier = np.abs(fourier)\n\n freq = np.fft.fftfreq(len(fourier), d=1/samplingrate)\n \n plt.figure()\n plt.plot(freq[0:endpoint_of_fftplot], fourier[0:endpoint_of_fftplot])\n plt.xlabel(\"Frequency [Hz]\")\n plt.ylabel(\"Magnitude\")\n #plt.savefig(f\"C4freq.pdf\")\n\n time = np.linspace(0, len(inputsignal)/samplingrate, len(inputsignal))\n plt.figure()\n plt.plot(time, inputsignal, 'r')\n plt.xlabel(\"Time [s]\")\n #plt.savefig(\"C4audio.pdf\")\n\n\ndef stft_of_signal(window,windowlength,overlap,inputsignal,samplerate, plot=None):\n \"\"\"\n GENERAL\n ----------\n This function takes an input signal and plots a spectrogram of windowed signal.\n The function uses the function stft from scipy.signal.\n \n \n Parameters\n ----------\n window : TYPE str\n DESCRIPTION: Specifies the applied window function. \n If window function is not specified, default: Hanning window\n \n windowlength : TYPE int\n DESCRIPTION: Length of each frame\n Defaults to: 256\n \n overlap : TYPE: float, int\n DESCRIPTION: Percentwise overlap from frame to frame\n Default: 0.5\n \n inputsignal : TYPE list, tuple, array\n DESCRIPTION: The signal which is analysed\n \n samplerate : TYPE float, int\n DESCRIPTION: samples per second\n \n plot : bool, Optional\n DESCRIPTION: When True, spectrogram of windowed input signal is plotted\n Default: None\n\n Returns\n -------\n f : TYPE Array of float 64\n DESCRIPTION: Array of sample frequencies.\n \n t : TYPE Array of float 64\n DESCRIPTION: Array of segment times.\n \n Zxx : TYPE Array of complex64\n DESCRIPTION: STFT of windowed signal \n \"\"\"\n f,t,Zxx = stft(inputsignal, fs=samplerate, window=window, nfft=windowlength ,nperseg=windowlength) \n \n \n if plot==True:\n plt.figure()\n plt.pcolormesh(t, f, np.abs(Zxx), vmin=0)\n plt.colorbar()\n plt.title(f'Spectrogram of input signal windowed with {window:} winow')\n plt.ylabel('Frequency [Hz]')\n plt.xlabel('Time [sec]')\n return f, t, Zxx\n \n#Liste der indeholder lydfilerne\naudiofile =(\"piano-C4.wav\", \"trumpet-C4.wav\", \"BandofHorses.wav\", \"KingsOfMetal.wav\")\n\nrate, audio = audiosignal(audiofile[0], info=True)\n\nFourierAndtimePLOTS(audio, rate)\nf, t, Zxx = stft_of_signal('hanning',2**13,0.5,audio,rate,plot=True)","sub_path":"lyd/STFTsignal.py","file_name":"STFTsignal.py","file_ext":"py","file_size_in_byte":5305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"119328763","text":"import sys\nfrom PyQt5 import QtWidgets\n \nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt5 import NavigationToolbar2QT as NavigationToolbar\nimport matplotlib.pyplot as plt\n \nimport random\n \nclass Window(QtWidgets.QDialog):\n def __init__(self, parent=None):\n super().__init__(parent)\n \n self.figure = plt.figure()\n self.axes = self.figure.add_subplot(111)\n # We want the axes cleared every time plot() is called\n self.axes.hold(False)\n self.canvas = FigureCanvas(self.figure)\n \n \n self.toolbar = NavigationToolbar(self.canvas, self)\n self.toolbar.hide()\n \n # Just some button \n self.button1 = QtWidgets.QPushButton('Plot')\n self.button1.clicked.connect(self.plot)\n \n self.button2 = QtWidgets.QPushButton('Zoom')\n self.button2.clicked.connect(self.zoom)\n \n self.button3 = QtWidgets.QPushButton('Pan')\n self.button3.clicked.connect(self.pan)\n \n self.button4 = QtWidgets.QPushButton('Home')\n self.button4.clicked.connect(self.home)\n \n \n # set the layout\n layout = QtWidgets.QVBoxLayout()\n layout.addWidget(self.toolbar)\n layout.addWidget(self.canvas)\n \n btnlayout = QtWidgets.QHBoxLayout()\n btnlayout.addWidget(self.button1)\n btnlayout.addWidget(self.button2)\n btnlayout.addWidget(self.button3)\n btnlayout.addWidget(self.button4)\n qw = QtWidgets.QWidget(self)\n qw.setLayout(btnlayout)\n layout.addWidget(qw)\n \n self.setLayout(layout)\n \n def home(self):\n self.toolbar.home()\n def zoom(self):\n self.toolbar.zoom()\n def pan(self):\n self.toolbar.pan()\n \n def plot(self):\n ''' plot some random stuff '''\n data = [random.random() for i in range(25)]\n self.axes.plot(data, '*-')\n self.canvas.draw()\n \nif __name__ == '__main__':\n app = QtWidgets.QApplication(sys.argv)\n \n main = Window()\n main.setWindowTitle('Simple QTpy and MatplotLib example with Zoom/Pan')\n main.show()\n \n sys.exit(app.exec_())","sub_path":"example(show graph of iMatplotlib in GUI_Qt5)/hide NavigationToolbar.py","file_name":"hide NavigationToolbar.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"266029131","text":"from selenium import webdriver\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nimport pandas as pd\nimport itertools as it\n\ndriver = webdriver.Chrome()\ndriver.get(\"https://www.climatechangecommunication.org/climate-change-opinion-map/\")\n\n# switch to iframe\nWebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, \"//iframe[@src = 'https://environment.yale.edu/ycom/factsheets/MapPage/2017Rev/?est=happening&type=value&geo=county']\")))\n\ndef alt_apend(old_list):\n list_1=old_list[2:len(old_list):5]\n list_2=old_list[4:len(old_list):5]\n new_list=[None]*(len(list_1)+len(list_2))\n new_list[::2]=list_1\n new_list[1::2]=list_2\n return(new_list)\n\n# select options and download data\n\ncongressional_dist=WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, \"//*[@id='cd']\")))\ncongressional_dist.click()\n\nnames=WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, \"//*[@id='document']/div[*]//*[@class='name']\")))\nlabels=WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, \"//*[@id='document']/div[*]//*[@class='label']\")))\n\ncolumns=[]\n\nfor n in range(1,len(names)):\n no=(names[n].text+\"_\"+labels[(n*2)].text)\n yes=(names[n].text+\"_\"+labels[(n*2)+1].text)\n columns.append(no)\n columns.append(yes)\n\nloc=['State']+['CD']+columns\ndata=pd.DataFrame()\n\nstate_string=WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, \"//*[@id='stateSelect']\")))\nstate=state_string.text.split(\"\\n\")\n\n#select states\n\n\nfor s in range(1,len(state)):\n select_state = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, \"//*[@id='stateSelect']/option[text()='\"+state[s]+\"']\")))\n select_state.click()\n cd_string=WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, \"//*[@id='cdSelect']\")))\n cd=cd_string.text.split(\"\\n\")\n\n #select counties\n for c in range (1,len(cd)):\n select_cd=WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, \"//*[@id='cdSelect']/option[text()='\"+cd[c]+\"']\")))\n select_cd.click()\n\n #scrape data\n raw_data = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, \"//*[@id='document']/div[*]//*[name()='svg']\")))\n\n list_data_beliefs=raw_data[2].text.split(\"\\n\")\n list_data_risk=raw_data[3].text.split(\"\\n\")\n list_data_policy=raw_data[4].text.split(\"\\n\")\n list_data_behavior=raw_data[5].text.split(\"\\n\")\n\n beliefs=alt_apend(list_data_beliefs)\n risk=alt_apend(list_data_risk)\n policy=alt_apend(list_data_policy)\n behavior=alt_apend(list_data_behavior)\n\n region=[state[s],cd[c]]\n temp=list(it.chain(region, beliefs,risk,policy,behavior))\n temp=pd.DataFrame(temp)\n temp=pd.DataFrame.transpose(temp)\n data=pd.concat([data,temp])\n\n print(list_data_behavior)\n\ndata.columns=loc[0:len(loc)-1]\ndata.to_csv(\"map_data.csv\")\n\n\n# switch back to default content\ndriver.switch_to.default_content()","sub_path":"Cities_map_data.py","file_name":"Cities_map_data.py","file_ext":"py","file_size_in_byte":3170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"524426835","text":"import os,time,sys\nif __name__ == '__main__':\n ISOTIMEFORMAT='%Y-%m-%d %X'\n time=time.strftime(ISOTIMEFORMAT, time.localtime(time.time()))\n cmd = \"vmstat\"\n cmd = \"top -n 1 | grep '^Cpu'\"\n r = os.popen(cmd) \n result = r.read() \n r.close()\n f = open('/result.txt', 'a')\n f.write(time+':'+'\\n'+result)\n f.close()","sub_path":"sysutil_zl.py","file_name":"sysutil_zl.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"480607924","text":"from django.conf.urls import url\nfrom . import views \n\nurlpatterns=[\n\turl(r'^lista/$', views.lista_post, name='lista_post'),\n\turl(r'^(?P\\d{4})/(?P\\d{2})/(?P\\d{2})/'r'(?P[-\\w]+)/$', views.detalle_post, name='detalle_post'),\n\turl(r'^$', views.inicio, name='inicio'),\n\turl(r'^proyectos/$', views.proyectos, name='proyectos'),\n\turl(r'^contacto/$', views.contacto, name='contacto'),\n]","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"52473833","text":"import requests\n\nfrom api.config.readconfig import ReadConfig\nimport unittest\nimport sys\n\nprint(\"https://pre.svocloud.com\".encode(\"utf-8\"))\nclass test_1stloginAndbingidng(unittest.TestCase):\n\n def test_1stloginAndbingidng(self):\n #获取wechat access_token 私人账户\n r = requests.get(\n \"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxcc7aee2c5d1e2699&secret=fb1d4ecfdbc26bbf80cfa29d2447ba82\")\n access_token = r.json()[\"access_token\"]\n print(access_token)\n print(r.text)\n\n\n\n\n#验证码错误\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"app_api/get_wechat_access_token.py","file_name":"get_wechat_access_token.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"505008931","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport matplotlib\nmatplotlib.rcParams['mathtext.fontset'] = 'stix'\nmatplotlib.rcParams['font.family'] = 'STIXGeneral'\n\ndef sig(x):\n return 1/(1 + np.exp(-x))\n\ndef kappa(x):\n return (1 + np.pi*x/8)**-0.5\n\n\nnp.random.seed(0)\n\nx = np.load('x.npy')[:20, :]\ny = np.load('y.npy')[:20]\nos.chdir(os.getcwd() + '/rich_images/lin_reg_ascent_1d')\n\nSw = np.array([[10, 0],\n [0, 10]], dtype = 'float64')\nMw = np.array([[0, 0]], dtype = 'float64').T\n\nw = np.array([[-1, 10]], dtype = 'float64').T\n\nrate = 0.001\nfor i in range(10000):\n grad = -(np.linalg.inv(Sw)).dot(w - Mw)\n term_1 = np.sum(y*(1 - sig((x).dot(w)))*x, axis = 0)\n grad += np.reshape(term_1, (2, 1))\n term_2 = np.sum((1 - y)*(sig((x).dot(w)))*x, axis = 0)\n grad -= np.reshape(term_2, (2, 1))\n\n w += rate*grad\n\n\nS_lap = np.linalg.inv(Sw)\nsigs = sig((x).dot(w))\nsigs = np.append(sigs, sigs, axis = 1).T\nS_lap += np.sum((sigs*(1 - sigs)*x.T).dot(x))\nS_lap = np.linalg.inv(S_lap)\n\nxs = np.linspace(-2, 4.5, 100)\nxs = np.stack([np.ones_like(xs), xs], axis = 1)\nmeans = (xs.dot(w)).reshape((-1))\nstdevs = (xs.dot(S_lap)).dot(xs.T).diagonal()\n\nplt.title('Bayesian fit', fontsize = 20)\nplt.plot(xs[:, 1], sig(kappa(stdevs)*means), color = 'black')\nx_1 = x[np.where(y == 1)[0]]\nx_2 = x[np.where(y == 0)[0]]\nplt.scatter(x_1, np.zeros_like(x_1), marker = 'x', color = 'black')\nplt.scatter(x_2, np.zeros_like(x_2), marker = 'o', color = 'white',\n edgecolor = 'black')\nplt.xlabel(r'$x$', fontsize = 18)\nplt.ylabel(r'$p(C_r)$', fontsize = 18)\nplt.xticks(fontsize = 13)\nplt.yticks([0, 0.5, 1], fontsize = 13)\nplt.show()\n","sub_path":"classification/bayesian_fit.py","file_name":"bayesian_fit.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"9173861","text":"# Author: Christian Brodbeck \nfrom numpy.testing import assert_array_equal\n\nfrom eelbrain import datasets, concatenate\n\n\ndef test_concatenate():\n \"Test concatenate()\"\n ds = datasets.get_uts(True)\n\n v0 = ds[0, 'utsnd']\n v1 = ds[1, 'utsnd']\n vc = concatenate((v1, v0))\n assert_array_equal(vc.sub(time=(0, 1)).x, v1.x)\n assert_array_equal(vc.sub(time=(1, 2)).x, v0.x)\n","sub_path":"eelbrain/tests/test_ndvar.py","file_name":"test_ndvar.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"437785514","text":"'''\nUtilities related to interfacing with Canvas\n\n(C) Mustafa Quraish, 2020\n'''\nimport requests\nimport os\n\n\nclass Canvas():\n\n # -------------------------------------------------------------------------\n\n def __init__(self, config):\n self.base_url = config['base_url']\n self.course_id = config['course']\n self.assgn_id = config['assignment']\n self.cfg = config\n self.mapping = None\n self._get_token()\n self.header = {\"Authorization\": \"Bearer \" + self.token}\n\n # -------------------------------------------------------------------------\n # Internal Utils\n # -------------------------------------------------------------------------\n\n def _get_token(self):\n '''\n Try to load Canvas token from file. If it doesn't exist, prompt\n the user and give them an option to save it locally.\n '''\n from pathlib import Path\n\n token_path = f\"{Path.home()}/.canvas.tokens\"\n if os.path.exists(token_path):\n lst = [line.split(\",\") for line in open(token_path).readlines()]\n tokens_dict = { url.strip(): token.strip() for url, token in lst }\n if self.base_url in tokens_dict:\n self.token = tokens_dict[self.base_url]\n return\n\n token = input(\"Enter Canvas Token: \").strip()\n prompt = input(f\"Save token in {token_path} ?: [Y]/n\")\n if 'n' not in prompt.lower():\n with open(token_path, 'a') as token_file:\n token_file.write(f'{self.base_url},{token}\\n')\n \n self.token = token\n\n # -------------------------------------------------------------------------\n\n def _get_mapping(self):\n if self.mapping is not None:\n return\n\n print(\"- Fetching course users...\", end=\"\", flush=True)\n\n url = f'{self.base_url}/api/v1/courses/{self.course_id}/users'\n page, res = 1, None\n\n self.mapping = {}\n\n while (res != []):\n data = {\n 'enrollment_type': 'student',\n 'per_page': 100,\n 'page': page,\n }\n res = requests.get(url, data=data, headers=self.header).json()\n\n # Pick the field as the identifier. For archived courses, login_id\n # is not always available. This makes it easier to test\n for user in res:\n if 'login_id' in user:\n self.mapping[user['login_id']] = user['id']\n elif 'sis_user_id' in user:\n self.mapping[user['sis_user_id']] = user['id']\n elif 'email' in user:\n userid = user['email'].split('@')[0]\n self.mapping[userid] = user['id']\n else:\n raise Exception(\"No suitable column found in canvas data\")\n page += 1\n print(\".\", end=\"\", flush=True)\n\n print()\n return\n\n # -------------------------------------------------------------------------\n\n def _get_file_url(self, submission):\n file_url = None\n\n if not submission[\"late\"] or self.cfg[\"allow_late\"]:\n if \"attachments\" in submission:\n # Assuming only one attachment for now\n file_url = submission[\"attachments\"][0][\"url\"]\n\n if file_url is not None:\n return file_url\n\n # If we're here need to look at submission history\n if \"submission_history\" not in submission:\n return None\n\n # Initial default that is earlier than all dates\n latest_date = \"0000-00-00T00:00:00Z\"\n\n for sub in submission['submission_history']:\n # Want newest submission that is either not late or allowed to be\n if (not sub[\"late\"]) or self.cfg[\"allow_late\"]:\n if sub[\"submitted_at\"] > latest_date:\n if \"attachments\" in sub:\n file_url = sub[\"attachments\"][0][\"url\"]\n latest_date = sub[\"submitted_at\"]\n\n return file_url\n\n # -------------------------------------------------------------------------\n # Functions meant to be exposed\n # -------------------------------------------------------------------------\n\n def students(self):\n self._get_mapping()\n return self.mapping.keys()\n\n # -------------------------------------------------------------------------\n\n def get_mapping(self):\n self._get_mapping()\n return self.mapping\n\n # -------------------------------------------------------------------------\n\n def student_exists(self, student):\n self._get_mapping()\n return student in self.mapping\n\n # -------------------------------------------------------------------------\n\n def upload_report(self, student_id, report_path):\n '''\n Upload a file to the comments section of a given assignment for the \n given student_id\n '''\n self._get_mapping()\n if student_id not in self.mapping:\n raise ValueError(f\"{student_id} not in the course.\")\n\n canvas_id = self.mapping[student_id]\n\n url = (f\"{self.base_url}/api/v1/courses/{self.course_id}\"\n f\"/assignments/{self.assgn_id}/submissions/{canvas_id}\"\n f\"/comments/files\")\n\n file_size = os.path.getsize(report_path)\n data = {\n \"name\": report_path,\n \"size\": file_size,\n \"content_type\": \"text/html\",\n \"parent_folder_path\": \"My Files/reports\"\n }\n\n res = requests.post(url, data=data, headers=self.header).json()\n\n if res.get('error') or res.get('errors'):\n return False\n\n url = res.get('upload_url')\n data = {\"file\": open(report_path, 'rb')}\n\n res = requests.post(url, files=data, headers=self.header).json()\n if (res.get('error')):\n return False\n\n url = res.get('location')\n res = requests.get(url, headers=self.header).json()\n if (res.get('upload_status') != \"success\"):\n return False\n\n file_id = res.get('id')\n url = (f\"{self.base_url}/api/v1/courses/{self.course_id}/\"\n f\"assignments/{self.assgn_id}/submissions/{canvas_id}\")\n\n data = {\"comment[file_ids][]\": file_id}\n res = requests.put(url, data=data, headers=self.header).json()\n\n return True\n\n # -------------------------------------------------------------------------\n\n def download_submission(self, student_id, student_dir):\n self._get_mapping()\n if student_id not in self.mapping:\n raise ValueError(f\"{student_id} not in the course.\")\n canvas_id = self.mapping[student_id]\n\n url = (f\"{self.base_url}/api/v1/courses/{self.course_id}/\"\n f\"assignments/{self.assgn_id}/submissions/{canvas_id}\")\n data = {\"include[]\": \"submission_history\"}\n res = requests.get(url, data=data, headers=self.header).json()\n\n if res.get('error') or res.get('errors'):\n return False\n\n file_url = self._get_file_url(res)\n\n # Found no submissions.\n if file_url is None:\n return False\n\n res = requests.get(file_url, data={}, headers=self.header)\n # Assuming no errors returned for now...\n file_name = self.cfg[\"file_name\"]\n open(f'{student_dir}/{file_name}', 'wb').write(res.content)\n\n return True\n\n # -------------------------------------------------------------------------\n\n def upload_mark(self, student_id, mark_list):\n self._get_mapping()\n if student_id not in self.mapping:\n raise ValueError(f\"{student_id} not in the course.\")\n canvas_id = self.mapping[student_id]\n\n url = (f\"{self.base_url}/api/v1/courses/{self.course_id}/\"\n f\"assignments/{self.assgn_id}/submissions/{canvas_id}\")\n\n # For Canvas, we can only submit one numerical mark. Take the sum:\n mark = sum(mark_list)\n\n data = {\"submission[posted_grade]\": f\"{mark}\"}\n res = requests.put(url, data=data, headers=self.header).json()\n\n if res.get('error') or res.get('errors'):\n return False\n\n return True\n\n# -----------------------------------------------------------------------------\n","sub_path":"marker/lms/canvas.py","file_name":"canvas.py","file_ext":"py","file_size_in_byte":8294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"586166602","text":"#!/usr/bin/env python\n\"\"\"\nThis file is part of the package FUNtoFEM for coupled aeroelastic simulation\nand design optimization.\n\nCopyright (C) 2015 Georgia Tech Research Corporation.\nAdditional copyright (C) 2015 Kevin Jacobson, Jan Kiviaho and Graeme Kennedy.\nAll rights reserved.\n\nFUNtoFEM is licensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this software except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\n\n# FUN3D one-way coupled drivers that use fixed fun3d aero loads\n__all__ = [\"Fun3dOnewayDriver\", \"Fun3dRemote\"]\n\nimport numpy as np\n\n\"\"\"\nUnfortunately, FUN3D has to be completely re-initialized for new aerodynamic meshes, so we have\nto split our Fun3dOnewayDriver scripts in implementation into two files, a my_fun3d_driver.py and a my_fun3d_analyzer.py.\nThe file my_fun3d_driver.py is called from a run.pbs script and manages the optimization and AIMs; this file\nalso uses system calls to the file my_fun3d_analyzer.py which runs the FUN3D analysis for each mesh. There are two \nclass methods Fun3dOnewayDriver.remote and Fun3dOnewayDriver.analysis which build the drivers for each of the two files.\n\nNOTE : only aerodynamic functions can be evaluated from this driver. If you only need aerodynamic DVs, you should build\nthe driver with class method Fun3dOnewayDriver.analysis(). If you need shape derivatives through ESP/CAPS, you shoud\nbuild the driver class using the class method Fun3dOnewayDriver.remote() and setup a separate script with a driver running the analysis.\nMore details on these two files are provided below. Do not construct a driver with analysis() class method and shape DVs,\nit will error in FUN3D upon the 2nd analysis iteration.\n\nmy_fun3d_driver.py : main driver script which called from the run.pbs\n NOTE : similar to tests/fun3d_tests/test_fun3d_oneway_shape.py\n - Construct the FUNtoFEMmodel\n - Build the Fun3dModel and link with Fun3dAim + AflrAIM and mesh settings, then store in funtofem_model.flow = this\n - Construct bodies and scenarios\n - Register aerodynamic and shape DVs to the scenarios/bodies\n - Construct the SolverManager with comm, but leave flow and structural attributes empty\n - Construct the fun3d oneway driver with class method Fun3dOnewayDriver.remote to manage system calls to the other script.\n - Build the optimization manager / run the driver\n\nmy_fun3d_analyzer.py : fun3d analysis script, which is called indirectly from my_fun3d_driver.py\n NOTE : similar to tests/fun3d_tests/run_fun3d_analysis.py\n - Construct the FUNtoFEMmodel\n - Construct the bodies and scenarios\n - Register aerodynamic DVs to the scenarios/bodies (no shape variables added and no AIMs here)\n - Construct the Fun3dInterface\n - Construct the solvers (SolverManager), and set solvers.flow = my_fun3d_interface\n - Construct the a fun3d oneway driver with class method Fun3dOnewayDriver.analysis\n - Run solve_forward() and solve_adjoint() on the Fun3dOnewayAnalyzer\n\nFor an example implementation see tests/fun3d_tests/ folder with test_fun3d_oneway_aero.py for just aero DVs\nand (test_fun3d_oneway_driver.py => run_fun3d_analysis.py) pair of files for the shape DVs using the Fun3dRemote and system calls.\n\"\"\"\n\nimport os\nfrom funtofem.driver import TransferSettings\nfrom funtofem.optimization.optimization_manager import OptimizationManager\n\nimport importlib.util\n\nfun3d_loader = importlib.util.find_spec(\"fun3d\")\nif fun3d_loader is not None: # check whether we can import FUN3D\n from funtofem.interface import Fun3dInterface\n\n\nclass Fun3dRemote:\n def __init__(\n self,\n analysis_file,\n fun3d_dir,\n output_name=\"f2f_analysis\",\n nprocs=1,\n aero_name=\"fun3d\",\n struct_name=\"tacs\",\n ):\n \"\"\"\n Manages remote analysis calls for a FUN3D / FUNtoFEM driver call\n\n Parameters\n ----------\n nprocs: int\n number of procs for the system call to the Fun3dOnewayAnalyzer\n analyzer_file: os filepath\n the location of the subprocess file for the Fun3dOnewayAnalyzer (my_fun3d_analyzer.py)\n fun3d_dir: filepath\n location of the fun3d directory for meshes, one level above the scenario folders\n output_file: filepath\n optional location to write an output file for the forward and adjoint analysis\n \"\"\"\n self.analysis_file = analysis_file\n self.fun3d_dir = fun3d_dir\n self.nprocs = nprocs\n self.output_name = output_name\n self.aero_name = aero_name\n self.struct_name = struct_name\n\n @classmethod\n def paths(cls, fun3d_dir, aero_name=\"fun3d\", struct_name=\"struct\"):\n return cls(\n analysis_file=None,\n fun3d_dir=fun3d_dir,\n aero_name=aero_name,\n struct_name=struct_name,\n )\n\n @classmethod\n def fun3d_path(cls, fun3d_dir, filename):\n return os.path.join(fun3d_dir, filename)\n\n @property\n def struct_sens_file(self):\n return os.path.join(self.fun3d_dir, f\"{self.struct_name}.sens\")\n\n @property\n def aero_sens_file(self):\n return os.path.join(self.fun3d_dir, f\"{self.aero_name}.sens\")\n\n @property\n def output_file(self):\n return os.path.join(self.fun3d_dir, f\"{self.output_name}.txt\")\n\n @property\n def bdf_file(self):\n return os.path.join(self.fun3d_dir, f\"{self.struct_name}.bdf\")\n\n @property\n def dat_file(self):\n return os.path.join(self.fun3d_dir, f\"{self.struct_name}.dat\")\n\n @property\n def design_file(self):\n return os.path.join(self.fun3d_dir, \"funtofem.in\")\n\n\nclass Fun3dOnewayDriver:\n @classmethod\n def nominal(cls, solvers, model, transfer_settings=None):\n \"\"\"\n Build a Fun3dOnewayDriver with fun3dAim shape variables and FUN3D analysis\n all in one, using the FUN3D mesh morphing.\n \"\"\"\n return cls(solvers, model, transfer_settings=transfer_settings, is_paired=False)\n\n @classmethod\n def remote(cls, solvers, model, fun3d_remote):\n \"\"\"\n Build a Fun3dOnewayDriver object for the my_fun3d_driver.py script:\n this object would be responsible for the fun3d, aflr AIMs and\n\n \"\"\"\n return cls(solvers, model, fun3d_remote=fun3d_remote, is_paired=True)\n\n @classmethod\n def analysis(cls, solvers, model, transfer_settings=None):\n \"\"\"\n Build an Fun3dOnewayDriver object for the my_fun3d_analyzer.py script:\n this object would be responsible for running the FUN3D\n analysis and writing an aero.sens file to the FUN3D directory.\n If you are using the analysis driver by itself (e.g. for FUN3D mesh morphing) then turn \"is_paired\" off.\n \"\"\"\n return cls(solvers, model, transfer_settings=transfer_settings, is_paired=True)\n\n def __init__(\n self,\n solvers,\n model,\n transfer_settings=None,\n fun3d_remote=None,\n is_paired=False,\n ):\n \"\"\"\n Build the FUN3D analysis driver for shape/no shape change. Able to run another FUN3D analysis remotely or\n do it internally depending on how the object is constructed. The user is recommended to use the class methods\n to build the driver most of the time not the main constructor.\n\n Parameters\n ----------\n solvers: :class:`~funtofem.interface.SolverManager'\n no need to add solvers.flow here just give it the comm so we can setup empty body class\n model: :class:`~funtofem_model.FUNtoFEMmodel`\n The model containing the design data.\n is_paired: bool\n Whether you need a pair of drivers to one remote and one analysis or just one analysis driver\n \"\"\"\n self.solvers = solvers\n self.comm = solvers.comm\n self.model = model\n self.transfer_settings = transfer_settings\n self.fun3d_remote = fun3d_remote\n self.is_paired = is_paired\n\n # store the shape variables list\n self.shape_variables = [\n var for var in self.model.get_variables() if var.analysis_type == \"shape\"\n ]\n\n # make sure there is shape change otherwise they should just use Fun3dOnewayAnalyzer\n if not (self.change_shape) and self.is_remote:\n raise AssertionError(\n \"Need shape variables to use the Fun3dOnewayDriver otherwise use the Fun3dOnewayAnalyzer which duals as the driver for no shape DVs.\"\n )\n\n if self.is_remote and self.model.flow is not None:\n if self.model.flow.mesh_morph:\n raise AssertionError(\n \"The mesh morphing does not require a remote driver! Make this driver regularly!\"\n )\n\n if not self.is_remote:\n if self.model.flow is not None:\n if not self.is_paired and not self.model.flow.mesh_morph:\n raise AssertionError(\n \"The nominal version of the driver only works for Fun3d mesh morphing not remeshing.\"\n )\n\n assert isinstance(self.solvers.flow, Fun3dInterface)\n if self.change_shape and self.root_proc:\n print(\n f\"Warning!! You are trying to remesh without using remote system calls of FUN3D, this will likely cause a FUN3D bug.\"\n )\n\n # check for unsteady problems\n self._unsteady = False\n for scenario in model.scenarios:\n if not scenario.steady:\n self._unsteady = True\n break\n\n # get the fun3d aim for changing shape\n if model.flow is None:\n fun3d_aim = None\n else:\n fun3d_aim = model.flow.fun3d_aim\n self.fun3d_aim = fun3d_aim\n\n comm = solvers.comm\n comm_manager = solvers.comm_manager\n\n if transfer_settings is not None:\n transfer_settings = TransferSettings() # default\n\n # initialize variables\n for body in self.model.bodies:\n # transfer to fixed structural loads in case the user got only aero loads from the Fun3dOnewayDriver\n body.initialize_transfer(\n comm=comm,\n struct_comm=comm_manager.struct_comm,\n struct_root=comm_manager.struct_root,\n aero_comm=comm_manager.aero_comm,\n aero_root=comm_manager.aero_root,\n transfer_settings=transfer_settings, # using minimal settings since we don't use the state variables here (almost a dummy obj)\n )\n for scenario in model.scenarios:\n body.initialize_variables(scenario)\n\n # shape optimization\n if self.change_shape:\n assert fun3d_aim is not None\n assert self.fun3d_model.is_setup\n self._setup_grid_filepaths()\n else:\n # TODO :\n for body in self.model.bodies:\n body.update_transfer()\n # local_ns = body.struct_nnodes\n # global_ns = self.comm.Reduce(local_ns,root=0)\n # if body.struct_nnodes > 0:\n # for scenario in self.model.scenarios:\n # # perform disps transfer from fixed struct to aero disps\n # body.transfer_disps(scenario)\n # body.transfer_temps(scenario)\n # end of __init__ method\n\n def solve_forward(self):\n \"\"\"\n Forward analysis for the given shape and functionals.\n Assumes shape variables have already been changed.\n \"\"\"\n\n if self.change_shape:\n # run the pre analysis to generate a new mesh\n self.fun3d_aim.pre_analysis()\n\n # doing the mesh morph inside of Fortran now but have to move the surf.dat file into the Flow directory for each scenario\n # other way of mesh morph\n # if self.model.flow.mesh_morph:\n # self.model.write_fun3d_surface_file(self.comm, os.path.join(self.fun3d_interface.fun3d_dir, \"nominal_surf.dat\"), root=0)\n # self.model.read_fun3d_surface_file(self.comm, root=0)\n\n # system call FUN3D forward analysis\n if self.is_remote:\n # write the funtofem design input file\n self.model.write_design_variables_file(\n self.comm,\n filename=Fun3dRemote.paths(self.fun3d_remote.fun3d_dir).design_file,\n root=0,\n )\n\n # clear the output file\n if self.root_proc and os.path.exists(self.fun3d_remote.output_file):\n os.remove(self.fun3d_remote.output_file)\n\n # system call the analysis driver\n os.system(\n f\"mpiexec_mpt -n {self.fun3d_remote.nprocs} python {self.fun3d_remote.analysis_file} 2>&1 > {self.fun3d_remote.output_file}\"\n )\n\n else: # non-remote call of FUN3D forward analysis\n # read in the funtofem design input file\n self.model.read_design_variables_file(\n self.comm,\n filename=Fun3dRemote.paths(self.fun3d_interface.fun3d_dir).design_file,\n root=0,\n )\n\n # run the FUN3D forward analysis with no shape change\n if self.steady:\n for scenario in self.model.scenarios:\n self._solve_steady_forward(scenario, self.model.bodies)\n\n if self.unsteady:\n for scenario in self.model.scenarios:\n self._solve_unsteady_forward(scenario, self.model.bodies)\n\n if self.change_shape and self.fun3d_aim.mesh_morph:\n self.fun3d_aim.unlink()\n return\n\n def solve_adjoint(self):\n \"\"\"\n Solve the adjoint analysis for the given shape and functionals.\n Assumes the forward analysis for this shape has already been performed.\n \"\"\"\n\n # run the adjoint aerodynamic analysis\n functions = self.model.get_functions()\n\n # Zero the derivative values stored in the function\n for func in functions:\n func.zero_derivatives()\n\n if not (self.is_remote):\n if self.steady:\n for scenario in self.model.scenarios:\n self._solve_steady_adjoint(scenario, self.model.bodies)\n\n if self.unsteady:\n for scenario in self.model.scenarios:\n self._solve_unsteady_adjoint(scenario, self.model.bodies)\n\n # write sens file for remote to read or if shape change all in one\n if not self.is_paired:\n filepath = self.model.flow.fun3d_aim.sens_file_path\n else:\n filepath = Fun3dRemote.paths(\n self.fun3d_interface.fun3d_dir\n ).aero_sens_file\n\n # write the sensitivity file for the FUN3D AIM\n self.model.write_sensitivity_file(\n comm=self.comm,\n filename=filepath,\n discipline=\"aerodynamic\",\n )\n\n # shape derivative section\n if self.change_shape: # either remote or regular\n # src for movement of sens file or None if not moving it\n sens_file_src = self.fun3d_remote.aero_sens_file if self.is_paired else None\n\n # run the tacs aim postAnalysis to compute the chain rule product\n self.fun3d_aim.post_analysis(sens_file_src)\n\n # update function values, NOTE : function values are not available in the remote version of the driver\n # after solve_forward (if you just need one grid and solve_forward, you don't need a remote driver, build the analysis one)\n self._get_functions()\n\n # store the shape variables in the function gradients\n for scenario in self.model.scenarios:\n self._get_shape_derivatives(scenario)\n return\n\n @property\n def steady(self) -> bool:\n return not (self._unsteady)\n\n @property\n def unsteady(self) -> bool:\n return self._unsteady\n\n @property\n def manager(self, hot_start: bool = False):\n return OptimizationManager(self, hot_start=hot_start)\n\n @property\n def root_proc(self) -> bool:\n return self.comm.rank == 0\n\n def _transfer_fixed_struct_disps(self):\n \"\"\"\n Transfer fixed structural displacements over to the new aero mesh for shape change.\n \"\"\"\n # TODO : set this up for shape change from struct to aero disps\n return\n\n def _solve_steady_forward(self, scenario, bodies):\n # set functions and variables\n self.fun3d_interface.set_variables(scenario, bodies)\n self.fun3d_interface.set_functions(scenario, bodies)\n\n # run the forward analysis via iterate\n self.fun3d_interface.initialize(scenario, bodies)\n for step in range(1, scenario.steps + 1):\n self.fun3d_interface.iterate(scenario, bodies, step=0)\n self.fun3d_interface.post(scenario, bodies)\n\n # get functions to store the function values into the model\n self.fun3d_interface.get_functions(scenario, bodies)\n return\n\n def _solve_unsteady_forward(self, scenario, bodies):\n # set functions and variables\n self.fun3d_interface.set_variables(scenario, bodies)\n self.fun3d_interface.set_functions(scenario, bodies)\n\n # run the forward analysis via iterate\n self.fun3d_interface.initialize(scenario, bodies)\n for step in range(1, scenario.steps + 1):\n self.fun3d_interface.iterate(scenario, bodies, step=step)\n self.fun3d_interface.post(scenario, bodies)\n\n # get functions to store the function values into the model\n self.fun3d_interface.get_functions(scenario, bodies)\n return\n\n def _solve_steady_adjoint(self, scenario, bodies):\n if scenario.adjoint_steps is None:\n steps = scenario.steps\n else:\n steps = scenario.adjoint_steps\n\n # set functions and variables\n self.fun3d_interface.set_variables(scenario, bodies)\n self.fun3d_interface.set_functions(scenario, bodies)\n\n # zero all coupled adjoint variables in the body\n for body in bodies:\n body.initialize_adjoint_variables(scenario)\n\n # initialize, run, and do post adjoint\n self.fun3d_interface.initialize_adjoint(scenario, bodies)\n for step in range(1, steps + 1):\n self.fun3d_interface.iterate_adjoint(scenario, bodies, step=step)\n self._extract_coordinate_derivatives(scenario, bodies, step=0)\n self.fun3d_interface.post_adjoint(scenario, bodies)\n\n # transfer disps adjoint since fa -> fs has shape dependency\n # if self.change_shape:\n # for body in bodies:\n # body.transfer_disps_adjoint(scenario)\n\n # call get function gradients to store the gradients w.r.t. aero DVs from FUN3D\n self.fun3d_interface.get_function_gradients(scenario, bodies)\n return\n\n def _solve_unsteady_adjoint(self, scenario, bodies):\n # set functions and variables\n self.fun3d_interface.set_variables(scenario, bodies)\n self.fun3d_interface.set_functions(scenario, bodies)\n\n # zero all coupled adjoint variables in the body\n for body in bodies:\n body.initialize_adjoint_variables(scenario)\n\n # initialize, run, and do post adjoint\n self.fun3d_interface.initialize_adjoint(scenario, bodies)\n for rstep in range(scenario.steps + 1):\n step = scenario.steps + 1 - rstep\n self.fun3d_interface.iterate_adjoint(scenario, bodies, step=step)\n self._extract_coordinate_derivatives(scenario, bodies, step=step)\n self.fun3d_interface.post_adjoint(scenario, bodies)\n self._extract_coordinate_derivatives(scenario, bodies, step=0)\n\n # transfer disps adjoint since fa -> fs has shape dependency\n # if self.change_shape:\n # for body in bodies:\n # body.transfer_disps_adjoint(scenario)\n\n # call get function gradients to store the gradients w.r.t. aero DVs from FUN3D\n self.fun3d_interface.get_function_gradients(scenario, bodies)\n return\n\n @property\n def fun3d_interface(self):\n return self.solvers.flow\n\n @property\n def is_remote(self) -> bool:\n \"\"\"whether we are calling FUN3D in a remote manner\"\"\"\n return self.fun3d_remote is not None\n\n @property\n def fun3d_model(self):\n return self.model.flow\n\n @property\n def change_shape(self) -> bool:\n return len(self.shape_variables) > 0\n\n def _setup_grid_filepaths(self):\n \"\"\"setup the filepaths for each fun3d grid file in scenarios\"\"\"\n if self.fun3d_interface is not None:\n fun3d_dir = self.fun3d_interface.fun3d_dir\n else:\n fun3d_dir = self.fun3d_remote.fun3d_dir\n grid_filepaths = []\n for scenario in self.model.scenarios:\n filepath = os.path.join(\n fun3d_dir,\n scenario.name,\n \"Flow\",\n f\"{scenario.fun3d_project_name}.lb8.ugrid\",\n )\n grid_filepaths.append(filepath)\n # set the grid filepaths into the fun3d aim\n self.fun3d_aim.grid_filepaths = grid_filepaths\n return\n\n @property\n def manager(self, hot_start: bool = False):\n return OptimizationManager(self, hot_start=hot_start)\n\n @property\n def root_proc(self) -> bool:\n return self.comm.rank == 0\n\n def _extract_coordinate_derivatives(self, scenario, bodies, step):\n \"\"\"extract the coordinate derivatives at a given time step\"\"\"\n self.fun3d_interface.get_coordinate_derivatives(\n scenario, self.model.bodies, step=step\n )\n\n # add transfer scheme contributions\n if step > 0:\n for body in bodies:\n body.add_coordinate_derivative(scenario, step=0)\n\n return\n\n def _get_functions(self):\n \"\"\"\n read function values from fun3dAIM when operating in the remote version of the driver\n \"\"\"\n print(f\"Entering get remote functions...\", flush=True)\n functions = self.model.get_functions()\n nfunc = len(functions)\n remote_functions = None\n if self.fun3d_aim.root_proc:\n remote_functions = np.zeros((nfunc))\n direct_fun3d_aim = self.fun3d_aim.aim\n for ifunc, func in enumerate(functions):\n remote_functions[ifunc] = direct_fun3d_aim.dynout[func.full_name].value\n\n # broadcast the function values to other processors\n fun3d_aim_root = self.fun3d_aim.root\n remote_functions = self.comm.bcast(remote_functions, root=fun3d_aim_root)\n\n # update model function values in the remote version of the driver\n for ifunc, func in enumerate(functions):\n func.value = remote_functions[ifunc]\n if (\n self.comm.rank == 0\n ): # debug print out for func values to check if read in properly\n print(f\"function {func.name} = {func.value}\")\n return\n\n def _get_shape_derivatives(self, scenario):\n \"\"\"\n Gather shape derivatives together from the FUN3D AIM and store the data in the FUNtoFEM model.\n \"\"\"\n gradients = None\n\n # read shape gradients from tacs aim on root proc\n fun3d_aim_root = self.fun3d_aim.root\n if self.fun3d_aim.root_proc:\n gradients = []\n direct_fun3d_aim = self.fun3d_aim.aim\n\n for ifunc, func in enumerate(scenario.functions):\n gradients.append([])\n for ivar, var in enumerate(self.shape_variables):\n derivative = direct_fun3d_aim.dynout[func.full_name].deriv(var.name)\n gradients[ifunc].append(derivative)\n\n # broadcast shape gradients to all other processors\n gradients = self.comm.bcast(gradients, root=fun3d_aim_root)\n\n # store shape derivatives in funtofem model on all processors\n for ifunc, func in enumerate(scenario.functions):\n for ivar, var in enumerate(self.shape_variables):\n derivative = gradients[ifunc][ivar]\n func.add_gradient_component(var, derivative)\n\n return\n\n # @classmethod\n # def prime_disps(cls, funtofem_driver):\n # \"\"\"\n # Used to prime aero disps for optimization over FUN3D analysis with no shape variables\n\n # Parameters\n # ----------\n # funtofem_driver: :class:`~funtofem_nlbgs_driver.FUNtoFEMnlbgs`\n # the coupled funtofem NLBGS driver\n # \"\"\"\n # # TODO : this is currently not very usable since we use system calls to separate analyses\n # # unless we made a disps read in file (but not high priority)\n # funtofem_driver.solve_forward()\n # return cls(funtofem_driver.solvers, funtofem_driver.model, nominal=False)\n","sub_path":"funtofem/driver/fun3d_oneway_driver.py","file_name":"fun3d_oneway_driver.py","file_ext":"py","file_size_in_byte":25360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"77960448","text":"import cv2\r\n\r\nwidth = 500\r\nheight = 300\r\ncap = cv2.VideoCapture(\"resources/10 Sec Road Trip.mp4\")\r\n\r\n\r\nwhile True:\r\n ret,frame = cap.read()\r\n frame = cv2.resize(frame,(width,height))\r\n gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\r\n cv2.imshow(\"original\",frame)\r\n cv2.imshow(\"Gray\", gray)\r\n\r\n k = cv2.waitKey(15)\r\n if k == ord(\"q\"):\r\n break\r\n\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n","sub_path":"opencvbasic/2. Read,write and save video using opencv.py","file_name":"2. Read,write and save video using opencv.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"228719145","text":"outFp=None\noutStr=\"\"\n\noutFp=open(\"C:/Users/400T6B/Desktop/dfdfd.txt\",\"w\",encoding='utf-8')\n\nwhile True:\n outStr=input(\"내용 입력 :\")\n if outStr !=\"\":\n outFp.writelines(outStr+\"\\n\")\n else:\n break\n\noutFp.close()\nprint(\"---정상적으로 파일에 써졌음---\")\n","sub_path":"컴퓨팅 사고력 향상을 위한 SW코딩/쓰기.py","file_name":"쓰기.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"363143715","text":"# coding: utf-8\nfrom django.shortcuts import render\nfrom django.views.generic import View\nfrom django.http import JsonResponse\nfrom django.db.models import Count\nfrom pure_pagination import Paginator, PageNotAnInteger\n\nfrom operations.forms import UserAskForm\nfrom operations.models import UserFav\nfrom .models import Organization, CityDict\nfrom courses.models import Course, Video, Chapter\n# Create your views here.\n\n\nclass OrgListView(View):\n \"\"\"\n 机构列表页\n \"\"\"\n def get(self, request):\n all_cities = CityDict.objects.all()\n all_orgs = Organization.objects.all()\n\n # test\n # any_org = Organization()\n # any_org.course_nums = any_org.get_course_nums()\n # any_org.save()\n\n hot_orgs = Organization.objects.all().order_by('-click_nums')[:3]\n\n # 筛选功能\n city_id = request.GET.get('city', \"\")\n if city_id:\n all_orgs = all_orgs.filter(city_id=city_id)\n city_id = int(city_id)\n\n org_type = request.GET.get('ct', '')\n if org_type:\n all_orgs = all_orgs.filter(org_type=org_type)\n\n # 排序功能\n sort_keyword = request.GET.get('sort', '')\n if sort_keyword == 'students':\n all_orgs = all_orgs.order_by('-student_nums')\n\n if sort_keyword == 'courses':\n # all_orgs = all_orgs.order_by('course_nums')\n all_orgs = all_orgs.annotate(nums=Count('course')).order_by('-nums')\n\n all_orgs_nums = all_orgs\n\n # 分页功能\n try:\n page = request.GET.get('page', 1)\n except PageNotAnInteger:\n page = 1\n p = Paginator(all_orgs, 3, request=request)\n all_orgs = p.page(page)\n\n return render(request, 'org-list.html', {\n 'all_cities': all_cities,\n 'all_orgs': all_orgs,\n 'all_orgs_nums': all_orgs_nums,\n 'city_id': city_id,\n 'org_type': org_type,\n 'sort_keyword': sort_keyword,\n 'hot_orgs': hot_orgs,\n })\n\n def post(self, request):\n pass\n\n\nclass UserAskView(View):\n def post(self, request):\n user_ask_form = UserAskForm(request.POST)\n\n if user_ask_form.is_valid():\n user_ask = user_ask_form.save(commit=True)\n return JsonResponse({'status': 'success', 'msg': u'信息发送成功'})\n \n else:\n return JsonResponse({'status': 'fail', 'msg': u'您填写的信息不合法'})\n\n\nclass OrgHomeView(View):\n \"\"\"\n 机构首页\n \"\"\"\n def get(self, request, org_id):\n current_page = 'org_home'\n course_org = Organization.objects.get(id=int(org_id))\n all_courses = course_org.course_set.all()[:3]\n all_teachers = course_org.teacher_set.all()[:3]\n\n if request.user.is_authenticated():\n if UserFav.objects.filter(user=request.user, fav_id=int(org_id), fav_type=2):\n is_fav = True\n else:\n is_fav = False\n else:\n is_fav =False\n\n return render(request, 'org-detail-homepage.html', {\n 'all_courses': all_courses,\n 'all_teachers': all_teachers,\n 'course_org': course_org,\n 'current_page': current_page,\n 'is_fav': is_fav\n })\n\n def post(self, request):\n pass\n\n\nclass OrgHomeCourseView(View):\n \"\"\"\n 机构首页 - 机构课程\n \"\"\"\n def get(self, request, org_id):\n current_page = 'org_course'\n course_org = Organization.objects.get(id=int(org_id))\n all_courses = course_org.course_set.all()[:3]\n\n if request.user.is_authenticated():\n if UserFav.objects.filter(user=request.user, fav_id=int(org_id), fav_type=2):\n is_fav = True\n else:\n is_fav = False\n else:\n is_fav =False\n\n return render(request, 'org-detail-course.html', {\n 'all_courses': all_courses,\n 'course_org': course_org,\n 'current_page': current_page,\n 'is_fav': is_fav\n })\n\n def post(self, request):\n pass\n\n\nclass OrgHomeDescView(View):\n \"\"\"\n 机构首页 - 机构介绍\n \"\"\"\n def get(self, request, org_id):\n current_page = 'org_desc'\n course_org = Organization.objects.get(id=int(org_id))\n\n if request.user.is_authenticated():\n if UserFav.objects.filter(user=request.user, fav_id=int(org_id), fav_type=2):\n is_fav = True\n else:\n is_fav = False\n else:\n is_fav =False\n return render(request, 'org-detail-desc.html', {\n 'course_org': course_org,\n 'current_page': current_page,\n 'is_fav': is_fav\n })\n\n def post(self, request):\n pass\n\n\nclass OrgHomeTeacherView(View):\n \"\"\"\n 机构首页 - 机构讲师\n \"\"\"\n def get(self, request, org_id):\n current_page = 'org_teacher'\n course_org = Organization.objects.get(id=int(org_id))\n all_teachers = course_org.teacher_set.all()[:3]\n if request.user.is_authenticated():\n if UserFav.objects.filter(user=request.user, fav_id=int(org_id), fav_type=2):\n is_fav = True\n else:\n is_fav = False\n else:\n is_fav =False\n\n return render(request, 'org-detail-teachers.html', {\n 'course_org': course_org,\n 'all_teachers': all_teachers,\n 'current_page': current_page,\n 'is_fav': is_fav\n })\n","sub_path":"apps/organizations/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"498655533","text":"import urllib2, threading\n\n_thread = None\n\nqueue = []\n\ndef urlopen( request, callback ):\n\tglobal _thread\n\n\tqueue.append( ( request, callback ) )\n\n\tif not _thread:\n\t\t_thread = threading.Thread( target=_requestThread )\n\t\t_thread.start()\n\ndef _requestThread():\n\tglobal _thread\n\n\twhile len( queue ):\n\t\trequest, callback = queue.pop()\n\t\tresponse = urllib2.urlopen( request ).read()\n\t\tcallback( response )\n\n\t_thread = None\n","sub_path":"payment_processor/utils/async_urllib2.py","file_name":"async_urllib2.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"62923613","text":"import numpy as np, matplotlib.pyplot as plt\nimport du, du.stats\nimport IPython as ip, sys\nimport mixtures\nfrom scipy.stats import multivariate_normal as mvn\n\ndef bg_test():\n dataPath = 'data/sample001'\n SigmaBA = 20*np.ones(3)\n SigmaBL = 5*np.ones(2)\n\n bg = du.imread('%s/bgRgb4x.png' % dataPath)\n bg = bg[:, 100:361]\n # bg = bg[:, 100:255]\n\n bgLab = du.rgb2labImg(bg)\n\n imgs = du.GetImgPaths('%s/rgb4x' % dataPath)\n img = du.imread(imgs[0])\n img = img[:, 100:361]\n # img = img[:, 100:255]\n imgLab = du.rgb2labImg(img)\n\n nY, nX, D = img.shape\n N = nY*nX\n \n xy = np.array(list(np.ndindex(nY, nX)))[:,::-1] \n bL = xy.astype(np.float)\n bA = du.asShape(bgLab, (N, D)).astype(np.float)\n b = np.concatenate((bL, bA), axis=1)\n\n yL = xy.astype(np.float)\n yA = du.asShape(imgLab, (N, D)).astype(np.float)\n\n bgLL_A = du.stats.logmvnpdfdiag(yA, bA, SigmaBA)\n bgLL_L = du.stats.logmvnpdfdiag(xy, xy, SigmaBL)\n bgLL = bgLL_A + bgLL_L\n\n K = 2\n altLL = bgLL\n sideLL = -30 * np.ones((K, N))\n nSamples = 500\n maxBreaks = 5\n # maxBreaks = 1\n alpha = 0.1\n beta = np.array([99, 1, 1])\n\n v = 2000\n # v = 5\n S = 20*(v - D - 1) * np.eye(2)\n\n Gamma = np.tile(1.0*np.eye(2), (K, 1, 1))\n # Gamma = np.tile(0.01*np.eye(2), (K, 1, 1))\n # Gamma = np.tile(50*np.eye(2), (K, 1, 1))\n\n # xPrior = np.stack([mvn.rvs(np.mean(yL, axis=0), Lambda[k]) for k in range(K)])\n # xPrior = mvn.rvs(np.mean(yL, axis=0), Lambda, size=2)\n # xPrior = np.stack( [np.ran\n\n # xPrior = np.zeros((K, 2))\n # xPrior[0] = [130, 75]\n # xPrior[1] = [100, 185]\n # # xPrior[1] = np.mean(yL, axis=0)\n #\n # Lambda = np.zeros((K, 2, 2))\n # Lambda[0] = 10*np.eye(2)\n # Lambda[1] = 1e4*np.eye(2)\n\n # Lambda = np.tile(1e6*np.eye(2), (K, 1, 1))\n # # Lambda = np.tile(1e4*np.eye(2), (K, 1, 1))\n\n zInitStrategy = 'zeros'\n\n\n def run(idx):\n import mixtures\n return mixtures.fit_extents_model_semi_conjugate( \\\n yL, K, nSamples=nSamples, altLL=altLL, sideLL=sideLL,\n maxBreaks=maxBreaks, alpha=alpha, v=v, S=S,\n Gamma=Gamma, zInitStrategy=zInitStrategy,\n showProgress=False)\n # return mixtures.fit_extents_model_semi_conjugate( \\\n # yL, K, nSamples=nSamples, altLL=altLL, sideLL=sideLL,\n # maxBreaks=maxBreaks, alpha=alpha, v=v, S=S, Lambda=Lambda,\n # Gamma=Gamma, xPrior=xPrior, zInitStrategy=zInitStrategy,\n # showProgress=True)\n\n # z, delta, pi, Pi, mu, Sigma, x, ll = run(0)\n res = du.ParforD(run, range(12))\n z, delta, pi, Pi, mu, Sigma, x, ll = \\\n res[np.argmax( [ r[-1][-1] for r in res ] ) ]\n\n # z, delta, pi, Pi, mu, Sigma, x, ll = mixtures.fit_extents_model( \\\n # yL, K, nSamples=nSamples, altLL=altLL, sideLL=sideLL,\n # maxBreaks=maxBreaks, alpha=alpha, v=v, S=S)\n\n # kappa = .01\n # v = 1000\n # S = 20*np.eye(2) * (v - D + 1)\n # z, delta, pi, Pi, mu, Sigma, x, ll = mixtures.fit_extents_model( \\\n # yL, K, nSamples=nSamples, altLL=altLL, sideLL=sideLL,\n # kappa=kappa, maxBreaks=maxBreaks, alpha=alpha, v=v, S=S)\n\n colors = du.diffcolors(K)\n colors = np.concatenate(([[0, 0, 0]], colors))\n\n def show(idx, **kwargs):\n import matplotlib.pyplot as plt, numpy as np, du, du.stats\n if kwargs.get('figure') is not None:\n plt.figure(kwargs.get('figure').number)\n\n drawImg = img\n drawImgSolid = np.zeros((nY, nX, 3), dtype=np.uint8)\n deltaImg = du.asShape(delta[idx], (nY, nX))\n for k in range(K):\n dk = np.nonzero(deltaImg == k+1)\n drawImg = du.DrawOnImage(drawImg, dk,\n np.concatenate((colors[k+1], [0.25])))\n drawImgSolid = du.DrawOnImage(drawImgSolid, dk, colors[k+1])\n\n plt.subplot(121)\n plt.imshow(drawImg)\n for k in range(K):\n for p in range(maxBreaks):\n # don't draw components with no associations\n if np.sum(np.logical_and(z[idx] == p, delta[idx] == k+1)) < 1:\n continue\n\n if pi[idx, k, p] < 0.05:\n transparency = 0.1\n linestyle = '--'\n else:\n transparency = 0.3\n linestyle = '-'\n\n pts = du.stats.Gauss2DPoints(mu[idx,k,p], Sigma[idx,k,p])\n\n col = np.concatenate(( colors[k+1], [transparency,] ))\n plt.plot(*pts, c=col, linestyle=linestyle)\n\n plt.scatter(x[idx, k, 0], x[idx, k, 1], s=100, c=colors[k+1], marker='H')\n plt.xlim(0, nX)\n plt.ylim(0, nY)\n plt.gca().invert_yaxis()\n plt.title('Sample %05d' % idx)\n\n plt.subplot(122)\n plt.imshow(drawImgSolid)\n # plt.show()\n\n # save figures\n import os\n folder_name = '001'\n try: os.mkdir('extents/%s' % folder_name)\n except: None\n\n try: os.mkdir('extents/%s/samples' % folder_name)\n except: None\n\n def save(idx):\n import matplotlib.pyplot as plt\n f = plt.figure()\n show(idx, figure=f)\n plt.savefig('extents/%s/samples/%05d.png' % (folder_name, idx),\n bbox_inches='tight', dpi=270)\n plt.close(f.number)\n du.ParforD(save, range(nSamples))\n\n plt.plot(ll)\n plt.title('Sample Log-Likelihood')\n plt.savefig('extents/%s/ll.pdf' % folder_name, bbox_inches='tight')\n\n imgs = du.GetImgPaths('extents/%s/samples' % folder_name)\n du.rgbs2mp4(imgs, 'extents/%s/samples.mp4' % folder_name, crf=18, fps=10)\n\n# dill.dump_session('extents/%s/session.pkl' % folder_name)\n\n\n\n # du.ViewPlots(range(nSamples), show)\n\n # fig, _ = du.ViewPlots(range(nSamples), show)\n # du.figure(num=fig.number, w=1600, h=1200)\n # plt.show()\n\n\ndef simple_test():\n N = 100\n D = 2\n y = np.random.rand(N, D)\n\n nSamples = 10\n K = 2\n altLL = -10*np.ones(N)\n sideLL = np.zeros((K, N))\n sideLL[0] = -10\n sideLL[1] = -20\n\n z, delta, pi, Pi, mu, Sigma, x, ll = \\\n mixtures.fit_extents_model(y, K, nSamples=nSamples, altLL=altLL)\n\n cols = du.diffcolors(K+1)\n print(cols)\n\n plt.scatter(y[:,0], y[:,1], s=1, c=cols[delta[-1]])\n plt.show()\n\nif __name__ == \"__main__\":\n bg_test()\n # simple_test()\n","sub_path":"test_extents.py","file_name":"test_extents.py","file_ext":"py","file_size_in_byte":5778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"229560456","text":"\"\"\"\nDjango settings for irmaonerd project.\n\nDeveloped by Murilo Viana\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\nURL = 'http://irmaonerd.com.br/'\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '&*37+625qy)l(t4ywr+q19sap^6ogq6w%=ks!i0sn5=f*ypr*6'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = False\nLOCAL = False\n\nTEMPLATE_DEBUG = True\n\nALLOWED_HOSTS = ['*']\n\n# Templates\nTEMPLATE_DIRS = (\n os.path.join(BASE_DIR, '../templates'),\n)\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.sites',\n 'django.contrib.sitemaps',\n\n 'south',\n 'sorl.thumbnail',\n 'pagination',\n 'tinymce',\n 'robots',\n\n 'autores',\n 'posts',\n 'destaques',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n\n 'pagination.middleware.PaginationMiddleware',\n)\n\nimport django.conf.global_settings as DEFAULT_SETTINGS\n\nTEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (\n 'django.core.context_processors.request',\n 'irmaonerd.context.base',\n)\n\nROOT_URLCONF = 'irmaonerd.urls'\n\nWSGI_APPLICATION = 'irmaonerd.wsgi.application'\n\n# Internationalization\n\nLANGUAGE_CODE = 'pt-br'\n\nTIME_ZONE = 'America/Sao_Paulo'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\nSITE_ID = 1\n\n# Static files (CSS, JavaScript, Images)\n\nSTATIC_ROOT = 'staticfiles'\nSTATIC_URL = '/static/'\n\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, '../static'),\n)\n\nMEDIA_ROOT = 'media'\nMEDIA_URL = '/media/'\n\nADMIN_MEDIA_PREFIX = '/staticfiles/admin/'\n\nTINYMCE_DEFAULT_CONFIG = {\n 'plugins': \"table,spellchecker,paste,searchreplace\",\n 'theme': \"advanced\",\n 'cleanup_on_startup': True,\n 'custom_undo_redo_levels': 10,\n 'width': 721,\n 'height': 600,\n 'content_css': '%scss/my_editor.css' % STATIC_URL,\n}\n\n# Database\n# Local settings\ntry:\n from local_settings import *\nexcept ImportError:\n pass","sub_path":"irmaonerd/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"356167494","text":"##\n# Project: gespeaker - A GTK frontend for espeak \n# Author: Fabio Castelli \n# Copyright: 2009-2010 Fabio Castelli\n# License: GPL-2+\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the Free\n# Software Foundation; either version 2 of the License, or (at your option)\n# any later version.\n# \n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\n# more details.\n# \n# On Debian GNU/Linux systems, the full text of the GNU General Public License\n# can be found in the file /usr/share/common-licenses/GPL-2.\n##\n\nPLUGIN_NAME = 'Welcome message'\nPLUGIN_VERSION = '0.1'\nPLUGIN_DESCRIPTION = 'Play welcome message on startup'\nPLUGIN_AUTHOR = 'Fabio Castelli'\nPLUGIN_ICON = ''\nPLUGIN_WEBSITE = ''\n\nimport Settings\nfrom plugins import GespeakerPlugin, register_plugin\n\nclass GespeakerPlugin_Welcome(GespeakerPlugin):\n def on_uiready(self, ui):\n # Play welcome message if PlayWelcomeText is set\n if Settings.get('PlayWelcomeText'):\n if Settings.get('UseCustomWelcome'):\n # Play customized welcome message\n message = Settings.get('WelcomeText')\n else:\n # Play default welcome message\n message = Settings.default('WelcomeText')\n self.logger('Play welcome message: %s' % message)\n ui.proxy['text.set'](message, 0)\n ui.proxy['espeak.play'](None, None)\n\nplugin = GespeakerPlugin_Welcome(\n PLUGIN_NAME, PLUGIN_VERSION, PLUGIN_DESCRIPTION, \n PLUGIN_AUTHOR, PLUGIN_ICON, PLUGIN_WEBSITE)\nregister_plugin(PLUGIN_NAME, plugin)\n","sub_path":"plugins/plugin_welcome/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"174190572","text":"import numpy as np\nfrom torch.utils.data.dataset import Dataset\nimport torch\nimport os\nimport random\nimport logging\nfrom scipy.ndimage.filters import convolve\nimport imageio\n\n# Define DB information\nBASE_PATH = '/Users/mayzha/datasets/IQA/databaserelease2'\nLIST_FILE_NAME = '/Users/mayzha/PycharmProjects/fr_repro/LIVE_IQA.txt'\nTRAIN_RATIO=0.9\nALL_SCENES = list(range(24))\nALL_DIST_TYPES = list(range(24))\n\n\nlogger=logging.getLogger('IQA')\n\n\n\ndef get_dataset():\n \"\"\"\n Make train and test image list from TID2013 database\n TID2013: 25 reference images x 24 distortions x 5 levels\n \"\"\"\n logger.info(\"start to load dataset info\")\n\n scenes, dist_types, d_img_list, r_img_list, score_list = [], [], [], [], []\n list_file_name = LIST_FILE_NAME\n with open(list_file_name, 'r') as listFile:\n for line in listFile:\n (scn_idx, dis_idx, ref, dis, score,width,height) = line.split()\n scn_idx = int(scn_idx)\n dis_idx = int(dis_idx)\n\n scenes.append(scn_idx)\n dist_types.append(dis_idx)\n r_img_list.append(ref)\n d_img_list.append(dis)\n score_list.append(float(score))\n\n n_images = len(d_img_list)\n\n # divide scene randomly get train and test dataset\n random.shuffle(ALL_SCENES)\n train_scenes_indexs = ALL_SCENES[:int(TRAIN_RATIO * len(ALL_SCENES))]\n test_scenes_indexs = ALL_SCENES[int(TRAIN_RATIO * len(ALL_SCENES)):len(ALL_SCENES)]\n\n train_scenes, train_dist_types, train_d_img_list, train_r_img_list, train_score_list = [], [], [], [], []\n test_scenes, test_dist_types, test_d_img_list, test_r_img_list, test_score_list = [], [], [], [], []\n for index in range(n_images):\n if scenes[index] in train_scenes_indexs: # train\n train_scenes.append(scenes[index])\n train_dist_types.append(dist_types[index])\n train_d_img_list.append(d_img_list[index])\n train_r_img_list.append(r_img_list[index])\n train_score_list.append(score_list[index])\n else:\n test_scenes.append(scenes[index]) # test\n test_dist_types.append(dist_types[index])\n test_d_img_list.append(d_img_list[index])\n test_r_img_list.append(r_img_list[index])\n test_score_list.append(score_list[index])\n\n train_score_list = np.array(train_score_list, dtype='float32')\n test_score_list = np.array(test_score_list, dtype='float32')\n\n dataSetInfo = {\n 'train': {\n 'scenes': train_scenes, # int list\n 'dist_types': train_dist_types, # int list\n 'r_img_path_list': train_r_img_list, # string list\n 'd_img_path_list': train_d_img_list, # string list\n 'score_list': train_score_list, # numpy array\n 'n_images': len(train_r_img_list), # int\n 'dataset_dir': BASE_PATH, # string\n },\n 'test': {\n 'scenes': test_scenes, # int list\n 'dist_types': test_dist_types, # int list\n 'r_img_path_list': test_r_img_list, # string list\n 'd_img_path_list': test_d_img_list, # string list\n 'score_list': test_score_list, # numpy array\n 'n_images': len(test_r_img_list), # int\n 'dataset_dir': BASE_PATH, # string\n },\n\n }\n\n\n return dataSetInfo\n\ndataSetInfo=get_dataset()\n\n\nclass Tid2013Dataset(Dataset):\n\n def __init__(self,dataset_dir,transform,type='train'):\n\n self.dataSetInfo=dataSetInfo[type]\n\n self.dataset_dir=dataset_dir\n self.transform=transform #@todo\n self.color='gray'\n\n self.patch_step=[80,80]\n self.patch_size=[112,112]\n\n self.patch_mode = 'shift_center'\n self.local_norm= False\n\n\n self.std_filt_r=1.0\n self.fr_met=None\n self.fr_met_avg=False\n self.num_ch=1\n self.fr_met_scale=1.0\n self.random_crops=0\n\n \n\n\n def __len__(self):\n return self.dataSetInfo['n_images']\n\n\n\n\n def load_reference_img(self,img_relative_path):\n \"\"\"\n load single reference_img to patches\n \"\"\"\n\n patch_size=self.patch_size\n patch_step=self.patch_step\n\n\n ref_top_left_set = []\n r_pat_set = []\n pass_list = []\n\n # img path\n img_path=os.path.join(self.dataset_dir,img_relative_path)\n # open with scipy misc\n img = imageio.imread( img_path)\n current_h=img.shape[0]\n current_w=img.shape[1]\n\n # Gray\n img = convert_color2(img, self.color)\n\n # Local normalization\n if self.local_norm:\n if self.color == 'gray':\n # faster\n r_img_norm = local_normalize_1ch(img)\n else:\n r_img_norm = local_normalize(img, self.num_ch)\n else:\n r_img_norm = img.astype('float32') / 255.\n\n if self.color == 'gray':\n r_img_norm = r_img_norm[:, :, None]\n\n\n # numbers of patches along y and x axes\n ny = (current_h - patch_size[0]) // patch_step[0] + 1\n nx = (current_w - patch_size[1]) // patch_step[1] + 1\n patch_info=(int(ny*nx),ny,nx)\n\n\n\n # get non-covered length along y and x axes\n cov_height = patch_step[0] * (ny - 1) + patch_size[0]\n cov_width = patch_step[1] * (nx - 1) + patch_size[1]\n nc_height = current_h - cov_height\n nc_width = current_w - cov_width\n\n # Shift center\n if self.patch_mode == 'shift_center':\n shift = [(nc_height + 1) // 2, (nc_width + 1) // 2]\n if shift[0] % 2 == 1:\n shift[0] -= 1\n if shift[1] % 2 == 1:\n shift[1] -= 1\n shift = tuple(shift)\n else:\n shift = (0, 0)\n\n # generate top_left_set of patches\n top_left_set = np.zeros((nx * ny, 2), dtype=np.int)\n for yidx in range(ny):\n for xidx in range(nx):\n top = (yidx * patch_step[0] + shift[0])\n left = (xidx * patch_step[1] + shift[1])\n top_left_set[yidx * nx + xidx] = [top, left]\n ref_top_left_set.append(top_left_set)\n\n # Crop the images to patches\n for idx in range(ny * nx):\n [top, left] = top_left_set[idx]\n\n # if top + patch_size[0] > current_h:\n #\n # print(' (%d > %d)' % (top + patch_size[0], current_h))\n #\n # if left + patch_size[1] > current_w:\n #\n # print(' (%d > %d)' % (left + patch_size[1], current_w))\n\n r_crop_norm = r_img_norm[top:top + patch_size[0],\n left:left + patch_size[1]]\n\n r_pat_set.append(r_crop_norm)\n\n # if len(pass_list) > 0:\n # self.n_images -= len(pass_list)\n # print(' - Ignored ref. images due to small size: %s' %\n # ', '.join(str(i) for i in pass_list))\n\n\n return patch_info,ref_top_left_set, r_pat_set\n\n\n\n\n\n\n\n\n\n\n\n def load_distored_img(self,patch_info,ref_top_left_set,img_relative_path):\n img_path=os.path.join(self.dataset_dir,img_relative_path)\n\n\n\n\n patch_size = self.patch_size\n\n n_patches = 0\n npat_img_list = []\n d_pat_set = []\n loc_met_set = []\n filt_idx_list = []\n dis2ref_idx = []\n\n\n pat_idx = 0\n\n\n # Read ref. and dist. images\n d_img_raw = imageio.imread( img_path)\n\n cur_h = d_img_raw.shape[0]\n cur_w = d_img_raw.shape[1]\n\n # Gray or RGB\n d_img = convert_color2(d_img_raw, self.color)\n\n # Read local metric scores\n if self.fr_met:\n ext = int(1. / self.fr_met_scale) - 1\n met_size = (int((cur_h + ext) * self.fr_met_scale),\n int((cur_w + ext) * self.fr_met_scale))\n met_pat_size = (int((patch_size[0] + ext) * self.fr_met_scale),\n int((patch_size[1] + ext) * self.fr_met_scale))\n if self.fr_met == 'SSIM_now':\n # d_img_ds = misc.imresize(d_img, met_size, interp='bicubic')\n # r_img_ds = misc.imresize(r_img, met_size, interp='bicubic')\n # loc_q_map = ssim(d_img_ds, r_img_ds)\n raise NotImplementedError()\n else:\n met_s_fname = (img_relative_path +\n self.fr_met_suffix + self.fr_met_ext)\n loc_q_map = np.fromfile(\n os.path.join(self.fr_met_path, self.fr_met_subpath,\n met_s_fname),\n dtype='float32')\n loc_q_map = loc_q_map.reshape(\n (met_size[1], met_size[0])).transpose()\n\n # Local normalization\n if self.local_norm:\n if self.color == 'gray':\n # faster\n d_img_norm = local_normalize_1ch(d_img)\n else:\n d_img_norm = local_normalize(d_img, self.num_ch)\n else:\n d_img_norm = d_img.astype('float32') / 255.\n\n if self.color == 'gray':\n d_img_norm = d_img_norm[:, :, None]\n\n top_left_set = ref_top_left_set\n\n if np.array(top_left_set).shape[0]==1:\n top_left_set=ref_top_left_set[0]\n\n cur_n_patches=np.array(top_left_set).shape[0]\n\n\n\n\n\n if self.random_crops > 0:\n if self.random_crops < cur_n_patches:\n n_crops = self.random_crops\n rand_perm = np.random.permutation(cur_n_patches)\n sel_patch_idx = sorted(rand_perm[:n_crops])\n top_left_set = top_left_set[sel_patch_idx].copy()\n else:\n n_crops = cur_n_patches\n sel_patch_idx = np.arange(cur_n_patches)\n\n npat_filt = n_crops\n npat_img_list.append((npat_filt, 1, npat_filt))\n n_patches += npat_filt\n\n idx_set = list(range(npat_filt))\n filt_idx_list.append(idx_set)\n\n else:\n # numbers of patches along y and x axes\n npat, ny, nx = patch_info\n npat_filt = int(npat * self.std_filt_r)\n\n npat_img_list.append((npat_filt, ny, nx))\n n_patches += npat_filt\n\n if self.std_filt_r < 1.0:\n std_set = np.zeros((nx * ny))\n for idx, top_left in enumerate(top_left_set):\n top, left = top_left\n std_set[idx] = np.std(\n d_img[top:top + patch_size[0],\n left:left + patch_size[1]])\n\n # Filter the patches with low std\n if self.std_filt_r < 1.0:\n idx_set = sorted(list(range(len(std_set))),\n key=lambda x: std_set[x], reverse=True)\n idx_set = sorted(idx_set[:npat_filt])\n else:\n idx_set = list(range(npat_filt))\n filt_idx_list.append(idx_set)\n\n # Crop the images to patches\n for idx in idx_set:\n [top, left] = top_left_set[idx]\n\n\n # if top + patch_size[0] > cur_h:\n # print('\\n@Error: imidx=%d, pat=%d' % (im_idx, idx), end='')\n # print(' (%d > %d)' % (top + patch_size[0], cur_h))\n #\n # if left + patch_size[1] > cur_w:\n # print('\\n@Error: imidx=%d, pat=%d' % (im_idx, idx), end='')\n # print(' (%d > %d)' % (left + patch_size[1], cur_w))\n\n d_crop_norm = d_img_norm[top:top + patch_size[0],\n left:left + patch_size[1]]\n\n d_pat_set.append(d_crop_norm)\n\n # if self.random_crops > 0:\n # dis2ref_idx.append(\n # ref_img2pat_idx[ref_idx][sel_patch_idx[idx]])\n # else:\n # dis2ref_idx.append(ref_img2pat_idx[ref_idx][idx])\n\n # Crop the local metric scores\n if self.fr_met:\n ext = int(1. / self.fr_met_scale) - 1\n top_r = int((top + ext) * self.fr_met_scale)\n left_r = int((left + ext) * self.fr_met_scale)\n\n # if top_r + met_pat_size[0] > met_size[0]:\n # print('\\n@Error (FR metric size):', end='')\n # print(' imidx=%d, pat=%d' % (im_idx, idx), end='')\n # print(' (%d > %d)' % (\n # top_r + met_pat_size[0], met_size[0]))\n #\n # if left_r + met_pat_size[1] > met_size[1]:\n # print('\\n@Error (FR metric size):', end='')\n # print(' imidx=%d, pat=%d' % (im_idx, idx), end='')\n # print(' (%d > %d)' % (\n # left_r + met_pat_size[1], met_size[1]))\n\n loc_met_crop = loc_q_map[top_r:top_r + met_pat_size[0],\n left_r:left_r + met_pat_size[1]]\n # if loc_met_crop.shape != met_pat_size:\n # print('\\n@Error (oc_met_crop.shape != met_pat_size)')\n # print(\"@ image (%d-%d):\" % (im_idx, idx),\n # d_img_list[im_idx])\n # print(\"@ loc_met_crop.shape:\", loc_met_crop.shape)\n # print(\"@ met_size:\", met_size)\n # print(\"@ top_r:\", top_r)\n # print(\"@ left_r:\", left_r)\n # os.system(\"pause\")\n\n if self.fr_met_avg:\n loc_met_set.append(\n np.mean(loc_met_crop, keepdims=True))\n else:\n loc_met_set.append(loc_met_crop)\n\n pat_idx += 1\n\n\n\n # if len(pass_list) > 0:\n # self.n_images -= len(pass_list)\n # print(' - Ignored image list due to small size: %s' %\n # ', '.join(str(i) for i in pass_list))\n\n self.n_patches = n_patches\n self.npat_img_list = npat_img_list\n self.d_pat_set = d_pat_set\n if self.fr_met:\n self.loc_met_set = loc_met_set\n self.filt_idx_list = filt_idx_list\n self.dis2ref_idx = dis2ref_idx\n\n\n return d_pat_set\n\n\n\n\n\n def __getitem__(self, index):\n patch_info,ref_top_left_set, r_pat_set=self.load_reference_img(self.dataSetInfo['r_img_path_list'][index])\n d_pat_set=self.load_distored_img(patch_info,ref_top_left_set,self.dataSetInfo['d_img_path_list'][index])\n mos= self.dataSetInfo['score_list'][index]\n\n r_pat_set = np.array(r_pat_set).transpose(0, 3,1,2)\n d_pat_set = np.array(d_pat_set).transpose(0, 3,1,2)\n mos = np.array(mos)\n\n\n r_pat_set=torch.from_numpy(r_pat_set)\n d_pat_set=torch.from_numpy(d_pat_set)\n mos=torch.from_numpy(mos)\n\n\n\n return r_pat_set,d_pat_set,mos\n\n\n\n\n\n\ndef gray2rgb(im):\n w, h = im.shape\n ret = np.empty((w, h, 3), dtype=np.uint8)\n ret[:, :, :] = im[:, :, np.newaxis]\n return ret\n\n\ndef rgb2gray(rgb):\n assert rgb.shape[2] == 3\n return np.dot(rgb[..., :3], [0.299, 0.587, 0.114])\n\n\ndef rgb2ycbcr(rgb):\n xform = np.array([[.299, .587, .114],\n [-.1687, -.3313, .5],\n [.5, -.4187, -.0813]])\n ycbcr = np.dot(rgb[..., :3], xform.T)\n ycbcr[:, :, [1, 2]] += 128\n return ycbcr\n\n\ndef ycbcr2rgb(ycbcr):\n xform = np.array([[1, 0, 1.402],\n [1, -0.34414, -.71414],\n [1, 1.772, 0]])\n rgb = ycbcr.astype('float32')\n rgb[:, :, [1, 2]] -= 128\n return rgb.dot(xform.T)\n\n\nk = np.float32([1, 4, 6, 4, 1])\nk = np.outer(k, k)\nkern = k / k.sum()\n\n\ndef local_normalize_1ch(img, const=127.0):\n mu = convolve(img, kern, mode='nearest')\n mu_sq = mu * mu\n im_sq = img * img\n tmp = convolve(im_sq, kern, mode='nearest') - mu_sq\n sigma = np.sqrt(np.abs(tmp))\n structdis = (img - mu) / (sigma + const)\n\n # Rescale within 0 and 1\n # structdis = (structdis + 3) / 6\n structdis = 2. * structdis / 3.\n return structdis\n\n\ndef local_normalize(img, num_ch=1, const=127.0):\n if num_ch == 1:\n mu = convolve(img[:, :, 0], kern, mode='nearest')\n mu_sq = mu * mu\n im_sq = img[:, :, 0] * img[:, :, 0]\n tmp = convolve(im_sq, kern, mode='nearest') - mu_sq\n sigma = np.sqrt(np.abs(tmp))\n structdis = (img[:, :, 0] - mu) / (sigma + const)\n\n # Rescale within 0 and 1\n # structdis = (structdis + 3) / 6\n structdis = 2. * structdis / 3.\n norm = structdis[:, :, None]\n elif num_ch > 1:\n norm = np.zeros(img.shape, dtype='float32')\n for ch in range(num_ch):\n mu = convolve(img[:, :, ch], kern, mode='nearest')\n mu_sq = mu * mu\n im_sq = img[:, :, ch] * img[:, :, ch]\n tmp = convolve(im_sq, kern, mode='nearest') - mu_sq\n sigma = np.sqrt(np.abs(tmp))\n structdis = (img[:, :, ch] - mu) / (sigma + const)\n\n # Rescale within 0 and 1\n # structdis = (structdis + 3) / 6\n structdis = 2. * structdis / 3.\n norm[:, :, ch] = structdis\n\n return norm\n\n\n\ndef convert_color2(img, color):\n \"\"\" Convert image into gray or RGB or YCbCr.\n (In case of gray, dimension is not increased for\n the faster local normalization.)\n \"\"\"\n assert len(img.shape) in [2, 3]\n if color == 'gray':\n # if d_img_raw.shape[2] == 1:\n if len(img.shape) == 3: # if RGB\n if img.shape[2] > 3:\n img = img[:, :, :3]\n img_ = rgb2gray(img)\n elif color == 'rgb':\n if len(img.shape) == 2: # if gray\n img_ = gray2rgb(img)\n elif len(img.shape) == 3: # if RGB\n if img.shape[2] > 3:\n img = img[:, :, :3]\n img_ = img\n elif color == 'ycbcr':\n if len(img.shape) == 2: # if gray\n img_ = rgb2ycbcr(gray2rgb(img))\n elif len(img.shape) == 3: # if RGB\n if img.shape[2] > 3:\n img = img[:, :, :3]\n img_ = rgb2ycbcr(img)\n else:\n raise ValueError(\"Improper color selection: %s\" % color)\n\n return img_\n\n\nif __name__ == '__main__':\n dataset=Tid2013Dataset(\"/Users/mayzha//datasets/IQA/tid2013\",None)\n\n r_pat_set,d_pat_set,loc_met_crop=dataset[1]","sub_path":"dataset/live.py","file_name":"live.py","file_ext":"py","file_size_in_byte":18268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"652543767","text":"# -*- coding: utf-8 -*-\n# ---------------------------------------\n# 堆排序,采用二叉堆的数据结构来实现的,实质上还是一维数组。二叉堆是一个近似完全二叉树 。\n#\n# 时间 Ο(nlogn) 空间 O(1) 不稳定\n#\n# 二叉堆具有以下性质:\n# 1. 父节点的键值总是大于或等于(小于或等于)任何一个子节点的键值。\n# 2. 每个节点的左右子树都是一个二叉堆(都是最大堆或最小堆)。\n#\n# 步骤\n# 1. 构造最大堆(Build_Max_Heap):若数组下标范围为0~n,考虑到单独一个元素是大根堆,则从下标n/2开始的元素均为大根堆。于是只要从n/2-1开始,向前依次构造大根堆,这样就能保证,构造到某个节点时,它的左右子树都已经是大根堆\n# 2. 排序(HeapSort):由于堆是用数组模拟的。得到一个大根堆后,数组内部并不是有序的。因此需要将堆化数组有序化。思想是移除根节点,并做最大堆调整的递归运算。第一次将heap[0]与heap[n-1]交换,再对heap[0...n-2]做最大堆调整。第二次将heap[0]与heap[n-2]交换,再对heap[0...n-3]做最大堆调整。重复该操作直至heap[0]和heap[1]交换。由于每次都是将最大的数并入到后面的有序区间,故操作完后整个数组就是有序的了\n# 3. 最大堆调整(Max_Heapify):该方法是提供给上述两个过程调用的。目的是将堆的末端子节点作调整,使得子节点永远小于父节点\n# ---------------------------------------\n\n\ndef heap_sort(array):\n n = len(array)\n first = int(n / 2 - 1)\n for start in range(first, -1, -1):\n max_heapify(array, start, n - 1)\n for end in range(n - 1, 0, -1):\n array[end], array[0] = array[0], array[end]\n max_heapify(array, 0, end - 1)\n return array\n\n\ndef max_heapify(array, start, end):\n root = start\n while True:\n child = root * 2 + 1\n if child > end:\n break\n if child + 1 <= end and array[child] < array[child + 1]:\n child += 1\n if array[root] < array[child]:\n array[root], array[child] = array[child], array[root]\n root = child\n else:\n break\n","sub_path":"practise/sort/heap_sort.py","file_name":"heap_sort.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"286149592","text":"#FilesPerJob=30\n#FilesPerJobMainBKG=2\n#FilesPerJobDATA=100\n\nTESTRUN=False\n\nimport math\nimport os\nimport sys\nsys.path.append(os.getcwd())\n\n#-----Variable Deinition-----#\nfrom WPandCut2016 import *\n\n#------End of Variable Definition-----#\n\n\n\nimport glob\nimport copy\nimport subprocess\nimport string\nfrom LatinoAnalysis.Tools.commonTools import *\n\n\n\nsamples={}\n\n\n\n\n\nMETFilter_MC = 'METFilter_MC'\n\nMETFilter_DATA = 'METFilter_DATA'\n\nmcCommonWeight='XSWeight*SFweight*METFilter_MC'\n\nMETFilter_DATA = 'METFilter_DATA'\n\n\nsamples['DY'] = { 'name' : getSampleFiles(directory,'DYJetsToLL_M-50-LO_ext2',False,'nanoLatino_')\n + getSampleFiles(directory,'DYJetsToLL_M-10to50-LO',False,'nanoLatino_'),\n 'weight' : mcCommonWeight,\n 'FilesPerJob' : FilesPerJobMainBKG,\n 'suppressNegative' :['all'],\n 'suppressNegativeNuisances' :['all'],\n\n}\n\n\n################################################\n############ DATA DECLARATION ##################\n################################################\nDataRun = [\n ['B','Run2016B-Nano1June2019_ver2-v1'],\n ['C','Run2016C-Nano1June2019-v1'],\n ['D','Run2016D-Nano1June2019-v1'],\n ['E','Run2016E-Nano1June2019-v1'],\n ['F','Run2016F-Nano1June2019-v1'],\n ['G','Run2016G-Nano1June2019-v1'],\n ['H','Run2016H-Nano1June2019-v1'],\n]\n\n\nDataSets = ['SingleElectron'\n]\n\nDataTrig = {\n 'SingleElectron' : 'Trigger_sngEl' ,\n }\n\n\n\nfor Run in DataRun :\n\n samples['DATA'+Run[1]] = { 'name': [ ] ,\n 'weight' : 'METFilter_DATA*LepWPCut' ,\n 'weights' : [ ],\n 'isData': ['all'],\n 'FilesPerJob' : FilesPerJobDATA,\n }\n\n directoryDATA = treeBaseDir+CAMPAIGN_DATA+'/'+STEP_DATA\n for DataSet in DataSets :\n FileTarget = getSampleFiles(directoryDATA,DataSet+'_'+Run[1],True,'nanoLatino_')\n for iFile in FileTarget:\n\n samples['DATA'+Run[1]]['name'].append(iFile)\n samples['DATA'+Run[1]]['weights'].append(DataTrig[DataSet])\n","sub_path":"Configurations/HWWSemiLepHighMass/Full_v6Production/ForAN/TriggerEff/2016/samples_2016data.py","file_name":"samples_2016data.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"204461230","text":"_base_ = [\n '../../_base_/models/swin/swin_base.py', '../../_base_/default_runtime.py'\n]\nmodel=dict(backbone=dict(patch_size=(2,4,4), drop_path_rate=0.3), test_cfg=dict(max_testing_views=4))\n\n# dataset settings\ndataset_type = 'VideoDataset'\ndata_root = 'data/kinetics400/train'\ndata_root_val = 'data/kinetics400/val'\nann_file_train = 'data/kinetics400/kinetics400_train_list.txt'\nann_file_val = 'data/kinetics400/kinetics400_val_list.txt'\nann_file_test = 'data/kinetics400/kinetics400_val_list.txt'\nimg_norm_cfg = dict(\n mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_bgr=False)\ntrain_pipeline = [\n dict(type='DecordInit'),\n dict(type='SampleFrames', clip_len=32, frame_interval=2, num_clips=1),\n dict(type='DecordDecode'),\n dict(type='Resize', scale=(-1, 256)),\n dict(type='RandomResizedCrop'),\n dict(type='Resize', scale=(224, 224), keep_ratio=False),\n dict(type='Flip', flip_ratio=0.5),\n dict(type='Normalize', **img_norm_cfg),\n dict(type='FormatShape', input_format='NCTHW'),\n dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),\n dict(type='ToTensor', keys=['imgs', 'label'])\n]\nval_pipeline = [\n dict(type='DecordInit'),\n dict(\n type='SampleFrames',\n clip_len=32,\n frame_interval=2,\n num_clips=1,\n test_mode=True),\n dict(type='DecordDecode'),\n dict(type='Resize', scale=(-1, 256)),\n dict(type='CenterCrop', crop_size=224),\n dict(type='Flip', flip_ratio=0),\n dict(type='Normalize', **img_norm_cfg),\n dict(type='FormatShape', input_format='NCTHW'),\n dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),\n dict(type='ToTensor', keys=['imgs'])\n]\ntest_pipeline = [\n dict(type='DecordInit'),\n dict(\n type='SampleFrames',\n clip_len=32,\n frame_interval=2,\n num_clips=4,\n test_mode=True),\n dict(type='DecordDecode'),\n dict(type='Resize', scale=(-1, 224)),\n dict(type='ThreeCrop', crop_size=224),\n dict(type='Flip', flip_ratio=0),\n dict(type='Normalize', **img_norm_cfg),\n dict(type='FormatShape', input_format='NCTHW'),\n dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),\n dict(type='ToTensor', keys=['imgs'])\n]\ndata = dict(\n videos_per_gpu=8,\n workers_per_gpu=4,\n val_dataloader=dict(\n videos_per_gpu=1,\n workers_per_gpu=1\n ),\n test_dataloader=dict(\n videos_per_gpu=1,\n workers_per_gpu=1\n ),\n train=dict(\n type=dataset_type,\n ann_file=ann_file_train,\n data_prefix=data_root,\n pipeline=train_pipeline),\n val=dict(\n type=dataset_type,\n ann_file=ann_file_val,\n data_prefix=data_root_val,\n pipeline=val_pipeline),\n test=dict(\n type=dataset_type,\n ann_file=ann_file_test,\n data_prefix=data_root_val,\n pipeline=test_pipeline))\nevaluation = dict(\n interval=5, metrics=['top_k_accuracy', 'mean_class_accuracy'])\n\n# optimizer\noptimizer = dict(type='AdamW', lr=1e-3, betas=(0.9, 0.999), weight_decay=0.05,\n paramwise_cfg=dict(custom_keys={'absolute_pos_embed': dict(decay_mult=0.),\n 'relative_position_bias_table': dict(decay_mult=0.),\n 'norm': dict(decay_mult=0.),\n 'backbone': dict(lr_mult=0.1)}))\n# learning policy\nlr_config = dict(\n policy='CosineAnnealing',\n min_lr=0,\n warmup='linear',\n warmup_by_epoch=True,\n warmup_iters=2.5\n)\ntotal_epochs = 30\n\n# runtime settings\ncheckpoint_config = dict(interval=1)\nwork_dir = work_dir = './work_dirs/k400_swin_base_patch244_window877.py'\nfind_unused_parameters = False\n\n\n# do not use mmdet version fp16\nfp16 = None\noptimizer_config = dict(\n type=\"DistOptimizerHook\",\n update_interval=8,\n grad_clip=None,\n coalesce=True,\n bucket_size_mb=-1,\n use_fp16=True,\n)\n","sub_path":"configs/recognition/swin/swin_base_patch244_window877_kinetics400_1k.py","file_name":"swin_base_patch244_window877_kinetics400_1k.py","file_ext":"py","file_size_in_byte":3933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"430454250","text":"import os\nfrom time import time, strftime, localtime\nimport pickle\n\nimport torch\n\n\nclass Cache:\n def __init__(self, d=None):\n pass\n\n def append(self, d):\n for k in d.keys():\n if not hasattr(self, k):\n self.__dict__[k] = list()\n self.__dict__[k].append(d[k])\n\n def append_l(self, d):\n for k in d.keys():\n if not hasattr(self, k):\n self.__dict__[k] = list()\n self.__dict__[k] += d[k]\n\n\nclass Recorder():\n def __init__(self, data=None, output_dir='./output/', file='log.rec'):\n self.data = data if data else dict()\n assert isinstance(self.data, dict)\n self.train = Cache()\n self.val = Cache()\n self.test = Cache()\n self.model = Cache()\n\n self.output_dir = output_dir\n self.file = file\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n def open(self):\n self.data['start_time'] = strftime(\"%Y-%m-%d %H:%M:%S\", localtime())\n self.start_time = time()\n\n def close(self):\n assert self.start_time is not None\n self.data['duration'] = time() - self.start_time\n\n\n\n def save(self):\n torch.save(self, self.output_dir+self.file)\n\n @staticmethod\n def load(file='./output/log.rec', device='cuda' if torch.cuda.is_available() else 'cpu'):\n # with open(file, 'rb') as f:\n return torch.load(file, map_location=device)\n\n # def save(self):\n # with open(self.output_dir+self.file, 'wb') as f:\n # pickle.dump(self, f)\n\n # @staticmethod\n # def load(file='./output/log.rec'):\n # with open(file, 'rb') as f:\n # return pickle.load(f)\n\n\n\n\n\n\n\n\n# col = Recorder()\n# col.train.append({\n# 'acc_class': 0.1,\n# 'acc_r': 0.2,\n# 'loss_class': 3.5,\n# 'loss_r': 3.6,\n# 'epoch': 2,\n# 'mini_batch': 3})\n#\n# col.save()\n#\n# col2 = Recorder.load()\n# print()\n\n\n # def __init__(self, **kwargs):\n # super().__init__()\n # self.__dict__.update(kwargs)\n #\n # def __getitem__(self, index):\n # b = Batch()\n # for k in self.__dict__.keys():\n # if self.__dict__[k] is not None:\n # b.update(**{k: self.__dict__[k][index]})\n # return b\n #\n # def update(self, **kwargs):\n # self.__dict__.update(kwargs)\n #\n # def append(self, batch):\n # assert isinstance(batch, Batch), 'Only append Batch is allowed!'\n # for k in batch.__dict__.keys():\n # if batch.__dict__[k] is None:\n # continue\n # if not hasattr(self, k) or self.__dict__[k] is None:\n # self.__dict__[k] = batch.__dict__[k]\n # elif isinstance(batch.__dict__[k], np.ndarray):\n # self.__dict__[k] = np.concatenate([\n # self.__dict__[k], batch.__dict__[k]])\n # elif isinstance(batch.__dict__[k], torch.Tensor):\n # self.__dict__[k] = torch.cat([\n # self.__dict__[k], batch.__dict__[k]])\n # elif isinstance(batch.__dict__[k], list):\n # self.__dict__[k] += batch.__dict__[k]\n # else:\n # s = 'No support for append with type' \\\n # + str(type(batch.__dict__[k])) \\\n # + 'in class Batch.'\n # raise TypeError(s)\n #\n #\n\n","sub_path":"dl/utils/recorder.py","file_name":"recorder.py","file_ext":"py","file_size_in_byte":3533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"163584270","text":"import json\nimport cv2\nimport os\nimport random\nimport numpy as np\n\nappstatic = '/app/static'\nsrc = 'source'\nuploads = 'uploads'\n\ndef scalingWdith(img, width):\n ratio = width / img.shape[1]\n return cv2.resize(img, None, fx=ratio, fy=ratio)\n\ndef coords2contour(coords):\n return np.array([ [[ point['x'], point['y'] ]] for point in coords])\n\ndef contour2coords(contour):\n return [ { 'x': int(point[0,0]), 'y': int(point[0,1])} for point in contour]\n\ndef contour2list(contours):\n return [ [ [ [point[0], point[1] ] for point in poly ] for poly in contour] for contour in contours]\n\ndef STATIC_PATH(dir, name = None):\n return appstatic + '/' + dir + ('/' + name if name != None else '')\n\ndef jsonparse (data):\n return json.loads(data, encoding='utf-8')\n\ndef loadjson (name):\n jdata = None\n try:\n with open(name + '.txt', 'r') as f:\n jdata = json.load(f)\n except:\n pass\n\n return jdata if jdata != None else {}\n\ndef savejson (name, data):\n with open(name + '.txt', 'w') as f:\n f.write(json.dump(data))\n\ndef loadimg(dir, name):\n return cv2.imread(STATIC_PATH(dir, name))\n\ndef saveimg(dir, name, img):\n if (not os.path.isdir(STATIC_PATH(dir))):\n os.mkdir(STATIC_PATH(dir))\n cv2.imwrite(STATIC_PATH(dir,name), img)\n\ndef savetemp(dir, name, img):\n prev, extn = name.split('.')\n tmp = prev + '-' + hex(random.getrandbits(128)) + '.' + extn\n saveimg(dir, tmp, img)\n return tmp\n\ndef wipetemp(dir, name):\n prev, extn = name.split('.')\n if (os.path.isdir(STATIC_PATH(dir))):\n for l in os.listdir(STATIC_PATH(dir)):\n if prev in l and extn in l:\n os.remove(STATIC_PATH(dir, l))\n\ndef listing (dir):\n return os.listdir(STATIC_PATH(dir))\n\ndef coords_split(coords):\n lines = {'ver':[], 'hor': []}\n prevcoord = coords[0]\n prevstate = 'ver'\n line = [prevcoord]\n\n for coord in coords:\n x1, y1 = prevcoord.values()\n x2, y2 = coord.values()\n\n angle = np.arctan2(y2 - y1, x2 - x1) * 180.0 / np.pi\n\n state = 'ver' if 60 <= angle <= 120 or -120 <= angle <= -60 else 'hor'\n\n if state == prevstate:\n line.append(coord)\n else:\n lines[prevstate].append(line)\n line = [prevcoord, coord]\n\n prevstate = state\n prevcoord = coord\n\n lines[prevstate].append(line)\n if len(lines['ver']) == 1: lines['ver'].pop(0)\n\n return lines","sub_path":"app/mdata.py","file_name":"mdata.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"100537290","text":"\"\"\"\nSelenium Test to login to Qxf2 Tutorial Page and assert the title\n\"\"\"\nfrom selenium import webdriver\n\n# Create an instance of Firefox WebDriver\ndriver = webdriver.Firefox()\n# The driver.get method will navigate to a page given by the URL\ndriver.get(\"http://localhost/selenium-tutorial-main.html\")\n# Assert the Page Title\nassert \"Qxf2 Services: Selenium training main\" in driver.title\n# Close the browser window\ndriver.close()\n","sub_path":"Navigate_Qxf2_Tutorial_Test.py","file_name":"Navigate_Qxf2_Tutorial_Test.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"87106213","text":"from galaxy.jobs import JobDestination\nfrom galaxy.jobs.mapper import JobMappingException\nimport os\nimport logging\nimport datetime\n\nlog = logging.getLogger(__name__)\n\nDESTINATION_DEFAULT = 'qsmall'\nDESTINATIONS = ('qsmall', 'qbig', 'qmid')\n\ndef dynamic_queue_pub (tool,tool_id, job, app):\n WALLTIME = 0\n param_dict = dict( [ ( p.name, p.value ) for p in job.parameters ] )\n param_dict = tool.params_from_strings( param_dict, app )\n\n if '__job_resource' in param_dict:\n if param_dict['__job_resource']['__job_resource__select'] == 'yes':\n # If time is set assing the value to WALLTIME\n if param_dict['__job_resource']['time']:\n WALLTIME = param_dict['__job_resource']['time']\n resource_key = None\n for resource_key in param_dict['__job_resource'].keys():\n if param_dict['__job_resource'][resource_key] in DESTINATIONS:\n destination_id = param_dict['__job_resource'][resource_key]\n break\n\n else:\n log.warning('(%s) Destination/walltime dynamic plugin got an invalid value for selector: %s \\nSending job to %s (default) queue', job.id, param_dict['__job_resource']['__job_resource__select'], DESTINATION_DEFAULT)\n destination_id = 'qsmall'\n elif param_dict['__job_resource']['__job_resource__select'] == 'no':\n destination_id = DESTINATION_DEFAULT\n\n else:\n destination_id = DESTINATION_DEFAULT\n else:\n log.warning('(%s) Destination/walltime dynamic plugin did not receive the __job_resource param, keys were: %s \\nSending job to %s (default) queue', job.id, param_dict.keys(), DESTINATION_DEFAULT)\n destination_id = DESTINATION_DEFAULT\n # IF WALLTIME was set replace default walltime by the new set value\n if WALLTIME > 0 :\n destination = app.job_config.get_destination( destination_id )\n # If the user tries to set a walltime > 48 hour on qsmall, reset to 24 hours\n #if destination_id == 'qsmall':\n # return destination_id\n # If a user tries to set more than 24 hours on qbig reset to 48 hours\n if destination_id == 'qfat512' and WALLTIME > 24 :\n return destination_id\n # set walltime to the chosen destination\n else:\n destination.params['Resource_List'] = 'walltime=%s:00:00' % str(WALLTIME)\n return destination\n\n else:\n return destination_id\n","sub_path":"galaxy-install-playbook/templates/galaxy-config/server/Pub_destination.py","file_name":"Pub_destination.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"366516346","text":"\"\"\"\npython3 add_gallery.py ../../_posts/2018-02-01-electric-kalimba.md ../img/projects/electric_kalimba\n\"\"\"\nimport os\nimport sys\n\n\npost_file = os.path.abspath(sys.argv[1])\nimg_dir = os.path.abspath(sys.argv[2])\nimg_dir_relative = \"/assets%s\" % img_dir.split(\"assets\")[1]\n\nimages = [i for i in os.listdir(img_dir) if not i.startswith(\".\")]\ngallery_name = \"gallery\"\n\ngallery = f\"{gallery_name}:\\n\"\nfor img in images:\n image_path = f\"{img_dir_relative}/{img}\"\n url = image_path\n gallery += f\" - url: {url}\\n\"\n gallery += f\" image_path: {image_path}\\n\"\nprint(gallery)\n\ngallery_md = '### Gallery\\n\\n{% include gallery id=\"gallery\" %}'\nprint(gallery_md)\n","sub_path":"assets/scripts/add_gallery.py","file_name":"add_gallery.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"352819543","text":"#!/Library/Frameworks/Python.framework/Versions/Current/bin/python\n# -*- coding: UTF-8 -*-\nimport requests\nimport time,datetime\nimport random\nimport MySQLdb\nimport logging\nfrom bs4 import BeautifulSoup\nimport re\nimport os\n\ndef getHtml(url):\n try:\n user_agent = 'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36'\n headers = {\n 'User-Agent' : user_agent,\n 'Referer':'http://www.google.com/'\n }\n html = requests.get(url,headers=headers)\n return html\n except:\n logging.info(\"Meliuz Say No!~\")\n return \"\"\ndef getSoup(html):\n soup = BeautifulSoup(str(html.content), \"html.parser\")\n return soup\ndef getOffers(soup):\n try:\n offers = soup.find_all(\"li\",attrs={\"class\": \"d-b bg--white box--round box--shadow mb- coupon-container\"})\n return offers\n except:\n logging.info(\"No Offers!\")\n return \"\"\n\ndef getName(offer):\n pattern = r'target=\"_blank\"> (.*) '\n name = re.findall(pattern,str(offer))\n if name == []:\n return \"\"\n else:\n return name\ndef getDescription(offer):\n pattern = r'

    (.*)

    '\n desc = re.findall(pattern,str(offer))\n if desc == []:\n desc = \"\"\n else:\n desc = desc[0]\n re_h = re.compile(r'<[^>]+>')\n description = re_h.sub(' ',desc)\n return description\ndef getCode(offer):\n pattern = r'data-code=\"(.*)\" data-coupon='\n code = re.findall(pattern,str(offer))\n return code\ndef getImg(soup,store_id):\n try:\n imagename = \"/Users/liuzhiguo/Sites/Colpon/public/images/Store-\"+str(store_id)+\".png\"\n imgurl = \"http:\"+str(soup.find(\"img\",attrs={\"class\": \"d-b box--shadow img--round img--responsive\"}).get(\"src\"))\n data=requests.get(imgurl,timeout=30).content\n with open(imagename,'wb') as f:\n f.write(data)\n except:\n logging.info(\"Store_id : %s Not OK!\" % str(store_id))\ndef ifImg(store_id):\n filename = r'/Users/liuzhiguo/Sites/Colpon/public/images/Store-'+str(store_id)+'.png'\n return os.path.exists(filename)\ndef main():\n #SQLs\n sqlselectstores = \"SELECT * FROM stores\"\n sqlselectoffers = \"SELECT %s FROM offers WHERE store_id = %s\"\n sqlinsertoffers = \"INSERT INTO offers (store_id,type,name,description,link,code,status,confirm_date,ends,created_at,updated_at) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\"\n sqlupdateoffers = \"UPDATE offers set status = %s, link = %s, confirm_date = %s, ends = %s, updated_at = %s where id = %s\"\n sqlupdate = \"UPDATE offers set status = %s where store_id = %s\"\n #Open SQL\n conn = MySQLdb.connect(\n host = 'localhost',\n port = 3306,\n user = 'root',\n passwd = 'root',\n db = 'colpon',\n charset = 'utf8',\n )\n cursor = conn.cursor()\n #Select Stores\n cursor.execute(sqlselectstores)\n stores = cursor.fetchall()\n for store in stores:\n store_id = store[0]\n link = store[4]\n url = store[5]\n logging.info(\"url = %s\" % url)\n html = getHtml(url)\n if html == \"\":\n #Today End!\n t1 = (datetime.datetime.strptime((str(datetime.date.today()+datetime.timedelta(1))+\" 00:00:00\"),'%Y-%m-%d %H:%M:%S')-datetime.datetime.now()).seconds+int(random.uniform(600, 6000))\n logging.info(\"Html None Today End! Start Sleep %ss (Sleep Till Tomorrow)\" % t1)\n time.sleep(t1)\n html = getHtml(url)\n soup = getSoup(html)\n offers = getOffers(soup)\n if ifImg(store_id):\n logging.info(\"Img it's OK!~\")\n else:\n getImg(soup,store_id)\n now = time.strftime(\"%Y-%m-%d %H:%M:%S\")\n #Select Offers\n cursor.execute(sqlselectoffers,('*',store_id))\n select_offers = cursor.fetchall()\n #Update Offers Status = 0\n cursor.execute(sqlupdate,(0,store_id))\n logging.info(\"Update Offers Status = 0\")\n for offer in offers:\n name = getName(offer)\n description = getDescription(offer)\n code = getCode(offer)\n if code == []:\n codetype = \"D\"\n logging.info(\"codetype = D\")\n code = \"\"\n else:\n codetype = \"C\"\n code = code[0]\n logging.info(\"codetype = C\")\n confirm_date = datetime.datetime.now() - datetime.timedelta(days = int(random.uniform(0, 3)), hours = int(random.uniform(1, 23)), minutes = int(random.uniform(1, 59)), seconds = int(random.uniform(1, 59)))\n ends = datetime.datetime.now() + datetime.timedelta(days = int(random.uniform(5, 30)), hours = int(random.uniform(1, 23)), minutes = int(random.uniform(1, 59)), seconds = int(random.uniform(1, 59)))\n n = 0\n offer_id = 0\n for select_offer in select_offers:\n try:\n if select_offers[3] == name and select_offers[4] == description:\n n = 1\n offer_id = select_offers[0]\n except:\n logging.info(\"Select Offer Error\")\n if n == 0 and name != \"\" and description != \"\":\n #Insert Offers\n cursor.execute(sqlinsertoffers,(store_id,codetype,name,description,link,code,1,confirm_date,ends,now,now))\n logging.info(\"Insert Offers\")\n else:\n #Update Offers Status = 1\n cursor.execute(sqlupdateoffers,(1,link,confirm_date,ends,now,offer_id))\n logging.info(\"Update Offers Status = 1\")\n if description == \"\" and code == \"\" and n == 0:\n description = 'As melhores ofertas e promoções'\n #Insert Offers\n cursor.execute(sqlinsertoffers,(store_id,\"D\",name,description,link,\"\",1,confirm_date,ends,now,now))\n logging.info(\"No Offer But Insert Offers\")\n #Commit\n conn.commit()\n #Sleep 60s-600s\n t = int(random.uniform(30, 200))\n logging.info(\"Sleep Start : %s\" % time.strftime(\"%Y-%m-%d %H:%M:%S\"))\n logging.info(\"Sleep : %ss\" % t)\n time.sleep(t)\n #Colse SQL\n cursor.close()\n conn.close()\n\nif __name__ == '__main__':\n while True:\n #Log\n logging.basicConfig(level=logging.DEBUG,\n format='%(process)d %(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\n datefmt='%a, %d %b %Y %H:%M:%S',\n filename='Colpon-Offers.log',\n filemode='w')\n #Today Start\n logging.info(\"Today Start %s\" % time.strftime(\"%Y-%m-%d %H:%M:%S\"))\n main()\n #Today End!\n t1 = (datetime.datetime.strptime((str(datetime.date.today()+datetime.timedelta(1))+\" 00:00:00\"),'%Y-%m-%d %H:%M:%S')-datetime.datetime.now()).seconds+int(random.uniform(600, 6000))\n logging.info(\"Today End! Start Sleep %ss (Sleep Till Tomorrow)\" % t1)\n time.sleep(t1)\n","sub_path":"Python/Colpon-Offers.py","file_name":"Colpon-Offers.py","file_ext":"py","file_size_in_byte":7030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"447980498","text":"from IPython.parallel import Client\nfrom IPython.parallel import interactive\nimport subprocess as sp\nrc = Client()\nengines = rc[:]\n\nvoice1 = 'Fred'\n\ndef load_lyrics(song):\n with open(song) as f:\n lyrics = f.readlines()\n lyrics = [l.strip('\\n') for l in lyrics]\n lyrics = [l for l in lyrics if l]\n \n return lyrics\n\ndef do_song(song):\n lyrics = load_lyrics(song)\n for line in lyrics:\n say(line + '.')\n\ndef say(t):\n sp.call(['say', '-v', voice1, t])\n\n\n# parallel part for choruses\n@interactive\ndef isay(t, voice=voice1):\n import subprocess as sp\n sp.call(['say', '-v', voice, t])\n\ndef say_parallel(lines, voices=voice1):\n assert isinstance(lines, list)\n\n if len(voices) == 1:\n engines['voice1'] = voice1\n elif len(voices) == len(lines):\n engines.map_sync(isay, lines, voices)\n","sub_path":"sing.py","file_name":"sing.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"165699323","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis file is a Fgp spider created on top of the ATSSpider\nscrapy crawl fgp -a mining_job_id=999 -a iteration=1 -a extract=1 -a url=\"http://www.fgp.com/jobs\"\n\nsample url:\n http://www.fgp.com/jobs\n\"\"\"\n\nfrom re import compile\nfrom urlparse import urljoin\n\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, HtmlFormatter, ConvertDateString\n\n\nclass Fgp(ATSSpider):\n\n name = 'fgp'\n ref_re = compile(\"/job/(\\d+)\")\n\n def start_requests(self):\n yield Request(url=self.start_urls[0], callback=self.parse_job_callback())\n\n def parse_job(self, response):\n sel = Selector(response)\n\n jobs = sel.xpath(\"//div[@class='item-list jobs']/ul/li\")\n for job in jobs:\n loader = BrightcorpItemLoader(selector=job)\n loader.add_xpath('url', \".//a[contains(text(),'Open a New Window to Bookmark')]/@href\")\n loader.add_xpath('title', \"h3/a/text()\")\n loader.add_xpath('date', \"p[@class='posted-job']/text()\", ConvertDateString(\"%b %d, %Y\"))\n loader.add_xpath('jobcategory', \".//div[strong[contains(text(),'Division:')]]/text()\")\n loader.add_xpath('jobtype', \".//div[strong[contains(text(),'Type:')]]/text()\")\n loader.add_xpath('referencenumber', \"h3/a/@name\", Prefix(\"%s-\" % self.name))\n loader.add_xpath('baseSalary', \".//div[strong[contains(text(),'Compensation:')]]/text()\")\n loader.add_xpath('description', \".//p[strong[contains(text(),'Job Description:')]]\", HtmlFormatter())\n loader.add_xpath('qualifications', \".//p[strong[contains(text(),'Qualifications:')]]\", HtmlFormatter())\n loader.add_xpath('location', \".//div[strong[contains(text(),'City/State:')]]/text()\")\n if not loader.get_output_value('location'):\n loader.add_xpath('location', \".//div[strong[contains(text(),'Location:')]]/text()\")\n\n yield loader.load_item()\n\n next_page = sel.xpath(\"//a[contains(text(),'Next')]/@href\").extract()\n if next_page:\n next_url = urljoin(response.url, next_page[0])\n yield Request(url=next_url, callback=self.parse_job_callback())\n","sub_path":"brightcorp/brightcorp/spiders/fgp.py","file_name":"fgp.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"74967334","text":"import copy\n\nfrom tensorflow.python.client import device_lib\n\nfrom submodule.tfoptflow.model_pwcnet import _DEFAULT_PWCNET_TEST_OPTIONS\nfrom submodule.tfoptflow.model_pwcnet import ModelPWCNet as pwc_net\n\nfrom odometry.preprocessing.estimators.network_estimator import NetworkEstimator\nfrom odometry.utils import resize_image\n\n\nclass PWCNetEstimator(NetworkEstimator):\n\n def __init__(self, *args, **kwargs):\n super(PWCNetEstimator, self).__init__(*args, **kwargs)\n self.name = 'PWCNet'\n\n def get_nn_opts(self):\n nn_opts = copy.deepcopy(_DEFAULT_PWCNET_TEST_OPTIONS)\n nn_opts['verbose'] = True\n nn_opts['ckpt_path'] = self.checkpoint\n nn_opts['batch_size'] = 1\n\n devices = device_lib.list_local_devices()\n gpus = [device for device in devices if device.device_type=='GPU']\n device = (gpus if len(gpus) else devices)[0].name\n\n nn_opts['gpu_devices'] = [device]\n nn_opts['controller'] = device\n nn_opts['use_dense_cx'] = True\n nn_opts['use_res_cx'] = True\n nn_opts['pyr_lvls'] = 6\n nn_opts['flow_pred_lvl'] = 2\n return nn_opts \n\n def _load_model(self):\n nn_opts = self.get_nn_opts()\n self.model = pwc_net(mode='test', options=nn_opts)\n\n def _convert_model_output_to_prediction(self, optical_flow):\n size = optical_flow.shape\n optical_flow_small = resize_image(optical_flow, (int(size[1] / 4), int(size[0] / 4)))\n optical_flow_small[..., 0] /= size[1]\n optical_flow_small[..., 1] /= size[0]\n return optical_flow_small\n\n def _run_model_inference(self, model_input):\n return self.model.predict_from_img_pairs(model_input, batch_size=1, verbose=False)\n","sub_path":"odometry/preprocessing/estimators/pwcnet_estimator.py","file_name":"pwcnet_estimator.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"291046435","text":"from collections import deque, namedtuple\nimport numpy as np\nimport torch\nimport random\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n\nclass replayMemory():\n\n def __init__(self, action_size, memory_size, batch_size, seed):\n '''\n :param action_size:\n :param memory_size:\n :param batch_size:\n :param seed:\n '''\n\n self.action_size = action_size\n self.memory = deque(maxlen=int(memory_size))\n self.priority = deque()\n self.batch_size = batch_size\n self.experience = namedtuple(\"Experience\", field_names=[\"state\", \"action\", \"reward\", \"next_state\", \"done\"])\n self.seed = random.seed(seed)\n\n def __len__(self):\n return len(self.memory)\n\n def sample(self):\n '''\n :return:\n '''\n\n experience = random.sample(self.memory, k=self.batch_size)\n\n state = torch.from_numpy(np.vstack([exp.state for exp in experience if exp is not None])).float().to(device)\n action = torch.from_numpy(np.vstack([exp.action for exp in experience if exp is not None])).long().to(device)\n reward = torch.from_numpy(np.vstack([exp.reward for exp in experience if exp is not None])).float().to(device)\n next_state = torch.from_numpy(np.vstack([exp.next_state for exp in experience if exp is not None])).float().to(\n device)\n done = torch.from_numpy(\n np.vstack([exp.done for exp in experience if exp is not None]).astype(np.uint8)).float().to(device)\n\n return (state, action, reward, next_state, done)\n\n def add(self, state, action, reward, next_state, done):\n experience = self.experience(state, action, reward, next_state, done)\n self.memory.append(experience)\n\n '''\n call a function that gives back an index of size batch_size and se that to sample from emory buffer using np.random.choice\n\n need a vector pw ith priorty weight\n\n '''","sub_path":"memory.py","file_name":"memory.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"473841217","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport pandas as pd\nimport math\n\n#% matplotlib inline\n\n'''\n# 选择图像\nimage_file = 'Image_Fusion/2054.png'\nimage = cv2.imread(image_file, 1)\n'''\n## 问题:合并颜色少的区域到临近区域,计算区域像素的中点\n'''\n- 获取图像中所有像素点的颜色三通道值\n- 计算颜色出现频次和各颜色坐标中心点\n- 当出现次数少于阈值时,将其颜色转化为坐标中心点距离临近的颜色\n- 重新计算颜色区域中心点\n- 赋予标签并存储:{坐标,label}\n'''\n\n# 获取图像中所有像素点的颜色三通道值和索引位置\nimage_file = 'Image_Fusion/7169.png'\nimage = cv2.imread(image_file, 1)\n\n# 计算颜色出现频次\ndef compute_counts(image):\n dict_rgb = {}\n image = list(image)\n\n for i in image:\n for j in i:\n if tuple(j) not in dict_rgb:\n dict_rgb[tuple(j)] = 1\n else:\n dict_rgb[tuple(j)] += 1\n return dict_rgb\n\n# 计算各颜色坐标中心点\ndef compute_point(image):\n dict_point = {}\n dict_rgb = compute_counts(image)\n image = list(image)\n\n for x in range(len(image)):\n for y in range(len(image[0])):\n if tuple(image[x][y]) not in dict_point:\n dict_point[tuple(image[x][y])] = [x + 1, y + 1]\n else:\n dict_point[tuple(image[x][y])][0] += (x + 1)\n dict_point[tuple(image[x][y])][1] += (y + 1)\n\n for index in dict_point:\n for i in range(len(dict_point[index])):\n dict_point[index][i] = dict_point[index][i] // dict_rgb[index]\n\n return dict_point\n\n# 计算中心点花费时间\nimport time\n\nstart_time = time.time()\ndict_point = compute_point(image)\ncost_time = time.time() - start_time\nprint(cost_time)\n\n# 计算距离\ndef distance(x, y):\n dist = math.sqrt((x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2)\n return dist\n\n# 计算中心点距离最小颜色\ndef compute_distance(dict_point):\n # 设置最大距离\n min_distance = math.sqrt(480 ** 2 + 640 ** 2)\n\n # 循环遍历,计算一个中点和其他各点的距离\n for i in dict_point:\n for j in dict_point:\n if i != j:\n dist = distance(dict_point[i], dict_point[j])\n if dist < min_distance:\n min_distance = dist\n min_index = j\n # print(min_distance)\n # print(min_index)\n dict_point[i].append(min_index)\n return dict_point\n\n # 求取每个点和其他点的最小值,将距离最小对应的元组颜色加入字典\n\n# 当出现次数少于阈值时,将其颜色转化为坐标中心点距离临近的颜色\ndef modify_rgb(image, pix, to_pix):\n for i in image:\n for j in i:\n if j[0] == pix[0] and j[1] == pix[1] and j[2] == pix[2]:\n j[0] = to_pix[0]\n j[1] = to_pix[1]\n j[2] = to_pix[2]\n\n# 根据阈值选择要处理区域\ndef threshold(image, dict_rgb, threshold_value, dict_point):\n threshold_value = threshold_value\n for i in dict_rgb:\n if dict_rgb[i] < threshold_value:\n modify_rgb(image, i, dict_point[i][2])\n\nimport time\n\nstart_time = time.time()\n# 获取图片颜色出现次数\ndict_rgb = compute_counts(image)\n\n# 获取图像区域中心点坐标\ndict_point = compute_point(image)\n\n# 计算距离,更新图像区域最近中心点\ndict_point = compute_distance(dict_point)\n\n# 根据阈值修改rgb值\nthreshold(image, dict_rgb, 15000, dict_point)\n\ncost_time = time.time() - start_time\nprint(cost_time)\n\ncompute_counts(image)\n\ncv2.namedWindow('rose', cv2.WINDOW_NORMAL)\ncv2.imshow('rose', image)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n# 赋予标签并存储:{坐标,label}\ncompute_point(image)\n\n# 建立PSPnet标签索引列表\n\n'''\n# 建立MaskRCNN标签索引列表\nclass_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',\n 'bus', 'train', 'truck', 'boat', 'traffic light',\n 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',\n 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',\n 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',\n 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',\n 'kite', 'baseball bat', 'baseball glove', 'skateboard',\n 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',\n 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',\n 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',\n 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',\n 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',\n 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',\n 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',\n 'teddy bear', 'hair drier', 'toothbrush']\n'''\n\n","sub_path":"6_Image_zone_fusion.py","file_name":"6_Image_zone_fusion.py","file_ext":"py","file_size_in_byte":5007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"209481672","text":"def registerCode(registerName):\r\n name = registerName.lower()\r\n if name == \"printreg\" or name == \"reg0\" or name == \"printregister\":\r\n return \"000\"\r\n elif name == \"reg1\":\r\n return \"001\"\r\n elif name == \"reg2\":\r\n return \"010\"\r\n elif name == \"reg3\":\r\n return \"011\"\r\n elif name == \"reg4\":\r\n return \"100\"\r\n elif name == \"reg5\":\r\n return \"101\"\r\n elif name == \"reg6\":\r\n return \"110\"\r\n elif name == \"reg7\":\r\n return \"111\"\r\n else:\r\n return \"--1\"\r\nregistre = [\"000\", \"001\", \"010\", \"011\", \"100\", \"101\", \"110\", \"111\"]\r\nwith open(\"main.tud\", \"r\") as f:\r\n ROM = \"\"\r\n count = 0\r\n for codeLine in f:\r\n instruction = codeLine.lower().split()\r\n if instruction[0] == \"block\" or instruction[0] == \"bloc\" or instruction[0] == \"blk\":\r\n ROM = ROM + \"0\"*15\r\n break\r\n elif instruction[0] == \"mov\":\r\n if len(instruction) != 3:\r\n exit(-1)\r\n reg1 = registerCode(instruction[1])\r\n reg2 = registerCode(instruction[2])\r\n if reg2 == \"--1\" and instruction[2].isnumeric() and reg1 in registre:\r\n number = \"{0:b}\".format(int(instruction[2])%256)\r\n while len(number) < 8:\r\n number = \"0\" + number\r\n ROM += \"0010\" + reg1 + number\r\n elif reg2 in registre and reg1 in registre:\r\n ROM += \"0001\" + reg1 + reg2 + \"0\"*5\r\n else:\r\n exit(-1)\r\n elif instruction[0] == \"sub\" or instruction[0] == \"subb\":\r\n if len(instruction) != 3:\r\n exit(-2)\r\n reg1 = registerCode(instruction[1])\r\n reg2 = registerCode(instruction[2])\r\n if reg1 in registre and reg2 in registre:\r\n ROM += \"0011\" + reg1 + reg2 + 5*\"0\"\r\n else:\r\n exit(-2)\r\n elif instruction[0] == \"add\" or instruction[0] == \"ad\":\r\n if len(instruction) != 3:\r\n exit(-3)\r\n reg1 = registerCode(instruction[1])\r\n reg2 = registerCode(instruction[2])\r\n if reg1 in registre and reg2 in registre:\r\n ROM += \"0100\" + reg1 + reg2 + 5*\"0\"\r\n else:\r\n exit(-3)\r\n elif instruction[0] == \"mul\" or instruction[0] == \"mull\":\r\n if len(instruction) != 3:\r\n exit(-4)\r\n reg1 = registerCode(instruction[1])\r\n reg2 = registerCode(instruction[2])\r\n if reg1 in registre and reg2 in registre:\r\n ROM += \"0101\" + reg1 + reg2 + 5*\"0\"\r\n else:\r\n exit(-4)\r\n elif instruction[0] == \"sll\" or instruction[0] == \"sl\":\r\n if len(instruction) != 2:\r\n exit(-5)\r\n reg1 = registerCode(instruction[1])\r\n if reg1 in registre:\r\n ROM += \"0110\" + reg1 + 8*\"0\"\r\n else:\r\n exit(-5)\r\n elif instruction[0] == \"slr\" or instruction[0] == \"sr\":\r\n if len(instruction) != 2:\r\n exit(-6)\r\n reg1 = registerCode(instruction[1])\r\n if reg1 in registre:\r\n ROM += \"0111\" + reg1 + 8*\"0\"\r\n else:\r\n exit(-6)\r\n elif instruction[0] == \"inv\" or instruction[0] == \"not\" or instruction[0] == \"no\" or instruction[0] == \"!\":\r\n if len(instruction) != 2:\r\n exit(-7)\r\n reg1 = registerCode(instruction[1])\r\n if reg1 in registre and reg2 in registre:\r\n ROM += \"1000\" + reg1 + 8*\"0\"\r\n else:\r\n exit(-7)\r\n elif instruction[0] == \"and\" or instruction[0] == \"&\":\r\n if len(instruction) != 3:\r\n exit(-8)\r\n reg1 = registerCode(instruction[1])\r\n reg2 = registerCode(instruction[2])\r\n if reg1 in registre and reg2 in registre:\r\n ROM += \"1001\" + reg1 + reg2 + 5*\"0\"\r\n else:\r\n exit(-8)\r\n elif instruction[0] == \"or\" or instruction[0] == \"|\":\r\n if len(instruction) != 3:\r\n exit(-9)\r\n reg1 = registerCode(instruction[1])\r\n reg2 = registerCode(instruction[2])\r\n if reg1 in registre and reg2 in registre:\r\n ROM += \"1010\" + reg1 + reg2 + 5*\"0\"\r\n else:\r\n exit(-9)\r\n elif instruction[0] == \"xor\" or instruction[0] == \"^\":\r\n if len(instruction) != 3:\r\n exit(-10)\r\n reg1 = registerCode(instruction[1])\r\n reg2 = registerCode(instruction[2])\r\n if reg1 in registre and reg2 in registre:\r\n ROM += \"1011\" + reg1 + reg2 + 5*\"0\"\r\n else:\r\n exit(-10)\r\n elif instruction[0] == \"xnor\":\r\n if len(instruction) != 3:\r\n exit(-11)\r\n reg1 = registerCode(instruction[1])\r\n reg2 = registerCode(instruction[2])\r\n if reg1 in registre and reg2 in registre:\r\n ROM += \"1100\" + reg1 + reg2 + 5*\"0\"\r\n else:\r\n exit(-11)\r\n elif instruction[0] == \"jmp\" or instruction[0] == \"jump\":\r\n if len(instruction) != 2 and not instruction[1].isnumeric():\r\n exit(-12)\r\n adresa = int(instruction[1]) % 32\r\n adresa = \"{0:b}\".format(adresa)\r\n while len(adresa) < 5:\r\n adresa = \"0\" + adresa\r\n ROM += \"1101\" + adresa + 6*\"0\"\r\n elif instruction[0] == \"jz\" or instruction[0] == \"jumpz\" or instruction[0] == \"jumpzero\" or instruction[0] == \"jzero\":\r\n if len(instruction) != 2 and not instruction[1].isnumeric():\r\n exit(-12)\r\n adresa = int(instruction[1]) % 32\r\n adresa = \"{0:b}\".format(adresa)\r\n while len(adresa) < 5:\r\n adresa = \"0\" + adresa\r\n ROM += \"1110\" + adresa + 6*\"0\"\r\n else:\r\n exit(-16)\r\n count += 1\r\n if count == 31:\r\n break\r\n nr_zero = 480 - len(ROM)\r\n ROM += nr_zero*\"0\"\r\n outt = open(\"codmasina.txt\", \"w\")\r\n\r\n outt.write(ROM)\r\n\r\n outt.close()","sub_path":"Compilator.py","file_name":"Compilator.py","file_ext":"py","file_size_in_byte":6202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"452412743","text":"import datetime\nfrom django.db import models\nfrom django.utils import formats\nfrom django.contrib.auth import get_user_model\nfrom django.core.validators import RegexValidator, MinValueValidator, MaxValueValidator\nfrom rosreestr.models import ApiRosreestrRequests\n\n\n# Create your models here.\n# ======================= ********************************************** ==========================\nclass Room(models.Model):\n ROOM_TYPE = (('FL', 'Квартира'),\n ('UN', 'Нежилое помещение'),)\n\n number = models.CharField(max_length=5,\n primary_key=True,\n verbose_name='Номер')\n type = models.CharField(max_length=2,\n choices=ROOM_TYPE,\n verbose_name='Тип помещения')\n square = models.DecimalField(max_digits=12,\n decimal_places=3,\n verbose_name='Площадь')\n cadastre_regex = RegexValidator(regex=r'^\\d{2}:\\d{2}:\\d{6,7}:\\d{1,35}$',\n message=\"Должен соответствовать формату АА:ВВ:CCCCСCC:КККККК\")\n cadastre = models.CharField(validators=[cadastre_regex], max_length=50,\n unique=True,\n verbose_name='Кадастровый номер',\n help_text='Должен соответствовать формату АА:ВВ:CCCCСCC:ККККК')\n\n def __str__(self):\n return '%s %s' % (self.get_type_display(), self.number)\n\n class Meta:\n verbose_name = 'Помещение'\n verbose_name_plural = 'Помещения'\n\n\n# ======================= ********************************************** ==========================\nclass Owner(models.Model):\n room = models.ForeignKey(Room, on_delete=models.CASCADE,\n verbose_name='Номер помещения')\n user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,\n verbose_name='Владелец')\n portion = models.DecimalField(max_digits=5,\n decimal_places=2,\n default=100,\n validators=[MinValueValidator(0.01), MaxValueValidator(100)],\n verbose_name='Доля собственности (от 0 до 100%)')\n rosreestr = models.ForeignKey(ApiRosreestrRequests, on_delete=models.SET_NULL,\n null=True, blank=True,\n verbose_name='Проверочный запрос в росреестр')\n date_request = models.DateField(auto_now_add=True,\n verbose_name='Дата запроса')\n date_confirmation = models.DateField(null=True, blank=True,\n verbose_name='Дата подтверждения')\n date_cancellation = models.DateField(null=True, blank=True,\n verbose_name='Дата аннулирования')\n cancelid = models.ForeignKey('self', on_delete=models.SET_NULL,\n null=True, blank=True,\n verbose_name='Аннулирующая запись')\n\n def __str__(self):\n return '{date},{owner},{area},{portion}'.format(date=formats.date_format(self.date_request),\n owner=self.user.fullname,\n area=self.room, portion=self.portion)\n\n def confirm(self):\n self.date_confirmation = datetime.datetime.today()\n self.save()\n\n def cancel(self, new_owner):\n self.date_cancellation = datetime.datetime.today()\n self.cancelid = new_owner\n self.save()\n\n class Meta:\n unique_together = (('room', 'user', 'date_request'),)\n index_together = [\n ['date_confirmation', \"date_cancellation\"],\n ]\n verbose_name = 'Владелец'\n verbose_name_plural = 'Владельцы'\n","sub_path":"area/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"293386410","text":"import setuptools\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name = \"tpapi\",\n version = \"0.1\",\n author = \"Luke Knowles\",\n author_email = \"luke.knowles@tierpoint.com\",\n description = \"A Python wrapper for the TierPoint API.\",\n install_requires = [\"requests\"],\n long_description= long_description,\n long_description_content_type= \"text/markdown\",\n url = \"https://github.com/lukeknowles/tpapi-wrappers/\",\n package_dir = {\"\": \"src\"},\n packages = setuptools.find_packages(where=\"src\"),\n python_requires = \">=3.6\",\n)","sub_path":"tpapi/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"89211001","text":"from django.db import models\nfrom rest_framework import status, test\n\nfrom nodeconductor.structure.models import ProjectRole\nfrom nodeconductor.structure.tests import factories, fixtures, models as test_models\n\n\nclass ServiceCreateTest(test.APITransactionTestCase):\n def setUp(self):\n self.fixture = fixtures.ProjectFixture()\n self.customer_url = factories.CustomerFactory.get_url(self.fixture.customer)\n self.client.force_authenticate(self.fixture.owner)\n\n def test_if_required_fields_is_not_specified_error_raised(self):\n response = self.client.post(factories.TestServiceFactory.get_list_url(), {\n 'name': 'Test service',\n 'customer': self.customer_url,\n 'backend_url': 'http://example.com/',\n })\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n self.assertIn('username', response.data)\n\n def test_validate_required_fields(self):\n response = self.client.post(factories.TestServiceFactory.get_list_url(), {\n 'name': 'Test service',\n 'customer': self.customer_url,\n 'backend_url': 'http://example.com/',\n 'username': 'admin',\n 'password': 'secret',\n })\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n\nclass ServiceResourcesCounterTest(test.APITransactionTestCase):\n \"\"\"\n There's one shared service. Also there are 2 users each of which has one project.\n There's one VM in each project. Service counters for each user should equal 1.\n For staff user resource counter should equal 2.\n \"\"\"\n def setUp(self):\n self.customer = factories.CustomerFactory()\n self.settings = factories.ServiceSettingsFactory(shared=True)\n self.service = factories.TestServiceFactory(customer=self.customer, settings=self.settings)\n\n self.user1 = factories.UserFactory()\n self.project1 = factories.ProjectFactory(customer=self.customer)\n self.project1.add_user(self.user1, ProjectRole.ADMINISTRATOR)\n self.spl1 = factories.TestServiceProjectLinkFactory(service=self.service, project=self.project1)\n self.vm1 = factories.TestNewInstanceFactory(service_project_link=self.spl1)\n\n self.user2 = factories.UserFactory()\n self.project2 = factories.ProjectFactory(customer=self.customer)\n self.project2.add_user(self.user2, ProjectRole.ADMINISTRATOR)\n self.spl2 = factories.TestServiceProjectLinkFactory(service=self.service, project=self.project2)\n self.vm2 = factories.TestNewInstanceFactory(service_project_link=self.spl2)\n\n self.service_url = factories.TestServiceFactory.get_url(self.service)\n\n def test_counters_for_shared_providers_should_be_filtered_by_user(self):\n self.client.force_authenticate(self.user1)\n response = self.client.get(self.service_url)\n self.assertEqual(1, response.data['resources_count'])\n\n self.client.force_authenticate(self.user2)\n response = self.client.get(self.service_url)\n self.assertEqual(1, response.data['resources_count'])\n\n def test_counters_are_not_filtered_for_staff(self):\n self.client.force_authenticate(factories.UserFactory(is_staff=True))\n response = self.client.get(self.service_url)\n self.assertEqual(2, response.data['resources_count'])\n\n def test_subresources_are_skipped(self):\n subresource = factories.TestSubResourceFactory(service_project_link=self.spl1)\n self.client.force_authenticate(self.user1)\n response = self.client.get(self.service_url)\n self.assertEqual(1, response.data['resources_count'])\n\n\nclass UnlinkServiceTest(test.APITransactionTestCase):\n def test_when_service_is_unlinked_all_related_resources_are_unlinked_too(self):\n resource = factories.TestNewInstanceFactory()\n service = resource.service_project_link.service\n unlink_url = factories.TestServiceFactory.get_url(service, 'unlink')\n\n self.client.force_authenticate(factories.UserFactory(is_staff=True))\n response = self.client.post(unlink_url)\n\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)\n self.assertRaises(models.ObjectDoesNotExist, service.refresh_from_db)\n\n def test_owner_cannot_unlink_service_with_shared_settings(self):\n fixture = fixtures.ServiceFixture()\n service_settings = factories.ServiceSettingsFactory(shared=True)\n service = test_models.TestService.objects.get(customer=fixture.customer, settings=service_settings)\n unlink_url = factories.TestServiceFactory.get_url(service, 'unlink')\n self.client.force_authenticate(fixture.owner)\n\n response = self.client.post(unlink_url)\n\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n self.assertTrue(test_models.TestService.objects.filter(pk=service.pk).exists())\n","sub_path":"nodeconductor/structure/tests/test_service.py","file_name":"test_service.py","file_ext":"py","file_size_in_byte":4891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"90266952","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nProblem 6:\nCreated on Fri Jun 5 08:04:11 2020\n\n@author: krishnendu\n\"\"\"\n\nimport numpy as np\nfrom scipy.integrate import *\nimport matplotlib.pyplot as plt\ndef fun1(x,y): ##defining the function for derivative \n return [32*y[0]+66*y[1]+(2/3)*x+(2/3),-66*y[0]-133*y[1]-(1/3)*x-1/3]\nx=np.linspace(0,0.5,1000) #creating mesh points\ns=solve_ivp(fun1,[0,0.5],[1/3,1/3],dense_output=\"True\") #solving the probelm using solve_ivp \nplt.plot(x,s.sol(x).T[:,0],label='y1') \nplt.plot(x,s.sol(x).T[:,1],label='y2') \nplt.legend()\nplt.xlabel(\"x\",size=18)\nplt.ylabel(\"y\",size=18)\nplt.title(\"Problem 6\",size=18)\nplt.grid()\nplt.show()\n\n\n","sub_path":"Problem_6.py","file_name":"Problem_6.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"44207187","text":"#!/usr/bin/python3\n\"\"\" This script contains function that queries the Reddit API,\n parses the title of all hot articles, and prints a sorted count\n of given keywords.\n\n Globals:\n @posts: the list of a hot posts from a given subreddit\n @after: the link that keeps track of a pagination\n\"\"\"\nfrom requests import get\nfrom sys import argv\n\nposts = []\nafter = None\n\n\ndef print_counts(posts, word_list):\n \"\"\" Prints a sorted count of given keywords (case-insensitive)\n\n Args:\n @posts: list of a hottest posts\n @word_list: a list of keywords to print\n\n Globals:\n @posts: the list of a hot posts from a given subreddit\n @after: the link that keeps track of a pagination\n \"\"\"\n results = {}\n for word in word_list:\n results[word.lower()] = 0\n\n for title in posts:\n words = title.split(\" \")\n for word in words:\n if results.get(word) is not None:\n results[word] += 1\n\n keywords = sorted(results, key=results.get, reverse=True)\n for kword in keywords:\n if results.get(kword):\n for word in word_list:\n if kword == word.lower():\n print(\"{}: {}\".format(word, results[kword]))\n\n\ndef count_words(subreddit, word_list):\n \"\"\" Queries the Reddit API, parses the title of all hot articles,\n prints a sorted count of given keywords (case-insensitive,\n delimited by spaces. E.g., JavaScript should count as javascript,\n but java should not).\n\n Args:\n @subreddit: a subreddit to retrieve\n @word_list: a list of keywords to search\n \"\"\"\n global posts\n global after\n\n headers = {\"User-Agent\": \"0x16. API advanced by Cu7ious\"}\n url = \"https://www.reddit.com/r/{}/hot.json\".format(subreddit)\n\n if after:\n url = url + \"?after={}\".format(after)\n\n count = get(url, headers=headers).json().get(\"data\")\n\n for post in count.get(\"children\"):\n posts.append(post.get(\"data\").get(\"title\").lower())\n\n after = count.get(\"after\")\n if after is not None:\n return count_words(subreddit, word_list)\n\n return print_counts(posts, word_list)\n\n\nif __name__ == \"__main__\":\n count_words(argv[1], argv[2].split(\" \"))\n","sub_path":"0x16-api_advanced/100-count.py","file_name":"100-count.py","file_ext":"py","file_size_in_byte":2274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"373762894","text":"\"\"\"\nCopyright (C) 2016 Julien Durand\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport itertools\nimport json\nimport os\n\nimport numpy as np\nfrom unidecode import unidecode\n\nimport src.db as db\nimport src.utils as utils\n\nSEPARATOR = ','\n\ndata_path = './data/ban'\nindex_path = './index/'\nfilename_template = 'BAN_licence_gratuite_repartage_%s.csv'\n\ncity_csv_path = 'index/cities.csv'\nstreet_csv_path = 'index/streets.csv'\nlocality_csv_path = 'index/locality.csv'\nnumber_csv_path = 'index/numbers.csv'\n\nrepetition_ref_path = 'index/repetitions.json'\n\ndepartements = (\n '01', '02', '03', '04', '05', '06', '07', '08', '09', '10',\n '11', '12', '13', '14', '15', '16', '17', '18', '19', '21',\n '22', '23', '24', '25', '26', '27', '28', '29', '2A', '2B',\n '30', '31', '32', '33', '34', '35', '36', '37', '38', '39',\n '40', '41', '42', '43', '44', '45', '46', '47', '48', '49',\n '50', '51', '52', '53', '54', '55', '56', '57', '58', '59',\n '60', '61', '62', '63', '64', '65', '66', '67', '68', '69',\n '70', '71', '72', '73', '74', '75', '76', '77', '78', '79',\n '80', '81', '82', '83', '84', '85', '86', '87', '88', '89',\n '90', '91', '92', '93', '94', '95',\n '971', '972', '973', '974', '975', '976',\n)\n\nAddress = (\n 'id',\n 'nom_voie',\n 'id_fantoir',\n 'numero',\n 'rep',\n 'code_insee',\n 'code_post',\n 'alias',\n 'nom_ld',\n 'nom_afnor',\n 'libelle_acheminement',\n 'x',\n 'y',\n 'lon',\n 'lat',\n 'nom_commune',\n)\n\n#\n# Index\n#\n\n\ndef index_departement(departement, city_file, street_file, locality_file,\n number_file, street_id_generator, locality_id_generator,\n repetition_id_generator, repetitions):\n file = os.path.join(data_path, filename_template % departement)\n if not os.path.exists(file):\n print('ERROR for departement %s : file not found' % departement)\n return 1 # FIXME considered as skipping a line only\n\n print('Indexing : %s' % file)\n\n cities = {}\n streets = {}\n localities = {}\n numbers = set()\n\n with open(file, 'r', encoding='UTF-8') as in_file:\n next(in_file, None) # skip header (first line)\n duplicates = 0\n nb_exceptions = 0\n for line in in_file:\n values = line[:-1].replace('\"\"', '').split(';')\n try:\n numero = values[3]\n if int(numero) < 0:\n raise Exception('Invalid numero : \"%s\"' % numero)\n\n rep = values[4]\n\n code_insee = values[5]\n if len(code_insee) != 5:\n raise Exception('Invalid code_insee : \"%s\"' % code_insee)\n\n code_post = values[6]\n if len(code_post) != 5:\n raise Exception('Invalid code_post : \"%s\"' % code_post)\n\n nom_ld = unidecode(values[8])\n if len(nom_ld) > 80:\n raise Exception('Invalid nom_ld : \"%s\"' % nom_ld)\n\n nom_afnor = values[9]\n if len(nom_afnor) > 32:\n raise Exception('Invalid nom_afnor : \"%s\"' % nom_afnor)\n\n nom_commune = values[10]\n if len(nom_commune) > 45:\n raise Exception('Invalid nom_commune : \"%s\"' % nom_commune)\n\n # x = float(values[11])\n\n # y = float(values[12])\n\n lon = values[13]\n if not -180 <= float(lon) <= 180:\n raise Exception('Invalid lon : \"%s\"' % lon)\n\n lat = values[14]\n if not -90 <= float(lat) <= 90:\n raise Exception('Invalid lat : \"%s\"' % lat)\n\n city_key = hash(code_insee + ':' + code_post)\n if city_key not in cities:\n cities[city_key] = {\n 'code_insee': code_insee,\n 'code_post': code_post,\n 'nom_commune': nom_commune,\n 'lon': [],\n 'lat': [],\n }\n cities[city_key]['lon'].append(float(lon))\n cities[city_key]['lat'].append(float(lat))\n\n street_key = hash(code_insee + ':' + code_post + ':' +\n nom_afnor)\n if street_key not in streets:\n street_id = str(next(street_id_generator))\n streets[street_key] = street_id\n street_line = ','.join((street_id, code_insee, code_post,\n nom_afnor,))\n street_file.write(street_line + '\\n')\n street_id = streets[street_key]\n\n locality_key = hash(code_insee + ':' + code_post + ':' +\n nom_ld)\n if locality_key not in localities:\n locality_id = str(next(locality_id_generator))\n localities[locality_key] = locality_id\n locality_line = ','.join((locality_id, code_insee,\n code_post, nom_ld,))\n locality_file.write(locality_line + '\\n')\n locality_id = localities[locality_key]\n\n if rep not in repetitions:\n repetition_key = str(next(repetition_id_generator))\n repetitions[rep] = repetition_key\n rep = repetitions[rep]\n\n number_key = hash(street_id + ':' + locality_id + ':' +\n numero + ':' + rep)\n if number_key not in numbers:\n numbers.add(number_key)\n number_line = ','.join((street_id, locality_id, numero,\n rep, lon, lat))\n number_file.write(number_line + '\\n')\n else:\n duplicates += 1\n except Exception as e:\n nb_exceptions += 1\n print(e)\n\n for city_key, city in cities.items():\n code_insee = city['code_insee']\n code_post = city['code_post']\n nom_commune = city['nom_commune']\n lon = np.mean(city['lon'])\n lat = np.mean(city['lat'])\n city_line = ','.join((code_insee, code_post, nom_commune, str(lon),\n str(lat)))\n city_file.write(city_line + '\\n')\n if duplicates:\n print(\"duplicates: \", duplicates)\n if nb_exceptions:\n print(\"exceptions: \", nb_exceptions)\n return nb_exceptions\n\n\ndef process_csv_files():\n repetitions = {}\n nb_exceptions = 0\n street_id_generator = itertools.count()\n locality_id_generator = itertools.count()\n repetition_id_generator = itertools.count()\n\n with open(city_csv_path, 'w', encoding='UTF-8') as city_file, \\\n open(street_csv_path, 'w', encoding='UTF-8') as street_file, \\\n open(locality_csv_path, 'w', encoding='UTF-8') as locality_file, \\\n open(number_csv_path, 'w', encoding='UTF-8') as number_file, \\\n open(repetition_ref_path, 'w', encoding='UTF-8') as \\\n repetition_file:\n\n for departement in departements:\n nb_exceptions += index_departement(departement, city_file,\n street_file, locality_file,\n number_file,\n street_id_generator,\n locality_id_generator,\n repetition_id_generator,\n repetitions)\n\n print('TOTAL number of skipped lines : ', nb_exceptions)\n\n indexed_repetition = {int(v): k for k, v in repetitions.items()}\n indexed_repetition = sorted(indexed_repetition)\n repetition_file.write(json.dumps(indexed_repetition))\n print('saved repetition.json reference file')\n\n\ndef city_factory(line):\n code_insee, code_post, nom_commune, lon, lat = line[:-1].split(SEPARATOR)\n lon = utils.degree_to_int(float(lon))\n lat = utils.degree_to_int(float(lat))\n return (code_insee, code_post, nom_commune, lon, lat)\n\n\ndef street_factory(line):\n street_id, code_insee, code_post, nom_voie = line[:-1].split(SEPARATOR)\n street_id = int(street_id)\n return (street_id, code_insee, code_post, nom_voie,)\n\n\ndef locality_factory(line):\n locality_id, code_insee, code_post, nom_ld = line[:-1].split(SEPARATOR)\n locality_id = int(locality_id)\n return (locality_id, code_insee, code_post, nom_ld,)\n\n\ndef number_factory(line):\n street_id, locality_id, numero, rep, lon, lat = \\\n line[:-1].split(SEPARATOR)\n street_id = int(street_id)\n locality_id = int(locality_id)\n numero = utils.safe_cast(numero, int, -1) # fixme\n if numero > 2**16 - 1:\n raise Exception('Error : numero overflows 16bits')\n return (street_id, locality_id, numero, rep,\n utils.geohash(float(lon), float(lat)))\n\n\ndef create_np_table(in_filename, dtype, factory, out_filename, sort=None):\n nb_lines = utils.count_file_lines(in_filename)\n with open(in_filename, 'r+') as f, open(out_filename, 'wb+') as out_file:\n table = np.memmap(out_file, dtype=dtype, shape=(nb_lines,))\n for i, line in enumerate(f):\n table[i] = factory(line)\n if sort:\n table.sort(order=sort)\n print('sorted %s on %s' % (out_filename, sort))\n table.flush()\n print('written ', out_filename, ' : %.3f' % utils.b_to_mb(table.nbytes),\n 'MB')\n os.remove(in_filename)\n return table\n\n\ndef create_np_index(table, column, out_filename):\n index_column = np.argsort(table, order=column).astype('int32')\n with open(out_filename, 'wb') as out_file:\n np.save(out_file, index_column)\n print('written ', out_filename, ' : %.3f' %\n utils.b_to_mb(index_column.nbytes),\n 'MB')\n\n\ndef create_db():\n cities = create_np_table(city_csv_path, db.city_dtype, city_factory,\n db.city_db_path, sort='code_insee')\n\n streets = create_np_table(street_csv_path, db.street_dtype, street_factory,\n db.street_db_path)\n\n localities = create_np_table(locality_csv_path, db.locality_dtype,\n locality_factory, db.locality_db_path)\n\n numbers = create_np_table(number_csv_path, db.number_dtype, number_factory,\n db.number_db_path, sort='street_id')\n\n create_np_index(cities, 'code_post', db.cities_post_index_path)\n create_np_index(streets, 'code_insee', db.streets_insee_index_path)\n create_np_index(localities, 'code_insee', db.localities_insee_index_path)\n create_np_index(numbers, 'locality_id', db.numbers_locality_index_path)\n create_np_index(numbers, 'geohash', db.numbers_geohash_index_path)\n\n\ndef index():\n print('Indexing')\n if not os.path.exists(index_path):\n os.mkdir(index_path)\n\n process_csv_files()\n create_db()\n\n\nif __name__ == '__main__':\n index()\n","sub_path":"src/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":11645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"3536205","text":"import boto3\nimport os\nimport sys\nimport collections\n\n\ns3 = boto3.client('s3')\nrds = boto3.client('rds')\n\n# Backup the newest snapshot each day, check to make sure we're not backing it\n# up twice.\n\n\ndef list_backups():\n s3_objects = s3.list_objects_v2(Bucket='dosomething-quasar-archive', Delimiter=\"/\")\n folders = []\n for folder in s3_objects['CommonPrefixes']:\n folders.append(folder['Prefix'][:-1])\n return folders\n\n\ndef list_snapshots():\n response = rds.describe_db_snapshots(DBInstanceIdentifier='quasar-prod')\n snapshots = {}\n for res in response['DBSnapshots']:\n snapshots[res['DBSnapshotIdentifier'][4:]] = res['DBSnapshotArn']\n return snapshots\n\n\ndef check_backup_status():\n # Report back metrics for RDS backup progress.\n task_progress = rds.describe_export_tasks(\n Filters=[\n {\n 'Name': 's3-bucket',\n 'Values': [os.environ.get('EXPORT_S3_BUCKET_NAME')]\n }\n ]\n )\n task_status = collections.OrderedDict()\n task_status['running'] = 0\n\n for task in task_progress['ExportTasks']:\n task_status[task['ExportTaskIdentifier']] = {\"status\":task['Status']}\n if (task['Status'] in ('IN_PROGRESS', 'STARTING')):\n task_status['running'] += 1\n if ('WarningMessage' in task):\n task_status[task['ExportTaskIdentifier']].update({\"msg\":task['WarningMessage']})\n\n return task_status\n\n\ndef start_export_task():\n rds_snapshots = list_snapshots()\n s3_backups = list_backups()\n task_status = check_backup_status()\n # Check which of these snapshots is not saved in the s3 bucket\n # Export RDS snapshots to S3.\n to_backup = list(set(rds_snapshots) - set(s3_backups) - set(task_status.keys()))\n\n backup_slots = 5 - task_status['running'] # StartExportTask only allows for 5 concurrent backups\n if backup_slots <= 5:\n try:\n i = 0\n if i <= backup_slots:\n for snapshot in to_backup:\n rds.start_export_task(ExportTaskIdentifier=snapshot, # S3 folder name\n SourceArn=rds_snapshots[snapshot], # RDS Snapshot ARN\n S3BucketName=os.environ.get('EXPORT_S3_BUCKET_NAME'),\n IamRoleArn=os.environ.get('EXPORT_ROLE_ARN'),\n KmsKeyId=os.environ.get('EXPORT_KMS_ID'))\n i += 1\n except Exception as e:\n print(e)\n sys.exit(-1) # Fail the Jenkins job if there's an exception\n","sub_path":"quasar/aws_s3.py","file_name":"aws_s3.py","file_ext":"py","file_size_in_byte":2609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"605820500","text":"import time, vk\nimport datetime\nfrom datetime import datetime as dd\n\napi = vk.API(vk.Session(access_token=((input('TOKEN LINK:').rsplit('access_token='))[1].rsplit('&'))[0]), v='5.92',lang='ru')\n\nstartDate = dd(2021, 2, 13)\n\nwhile True:\n\tminuteEnding = \" минут\"\n\t\n\tdatetimeDelta = dd.now() - startDate;\n\t\n\tminutes = int(datetimeDelta.days * 24 * 60 + datetimeDelta.seconds / 60)\n\n\tunitMinutes = int(minutes % 10)\n\tdecMinutes = int(minutes % 100)\n\n\tif decMinutes <= 10 or decMinutes >= 20:\n\t\tif unitMinutes >= 2 and unitMinutes <= 4: \n\t\t\tminuteEnding = minuteEnding + \"ы\"\n\t\telif unitMinutes == 1: \n\t\t\tminuteEnding = minuteEnding + \"у\"\n\t\n\tsendString = \"Уже \" + str(minutes) + minuteEnding + \" люблю её..\"\n\t\n\tapi.status.set(text = sendString)\n\t\n\tprint(sendString)\n\t\n\ttime.sleep(60)","sub_path":"vk_status_changer.py","file_name":"vk_status_changer.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"235560565","text":"\"\"\"Plotting methods for radar data.\"\"\"\n\nimport numpy\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as pyplot\nimport matplotlib.colors\nfrom gewittergefahr.gg_utils import grids\nfrom gewittergefahr.gg_utils import radar_utils\nfrom gewittergefahr.gg_utils import error_checking\nfrom gewittergefahr.deep_learning import input_examples\nfrom gewittergefahr.plotting import plotting_utils\n\nSHEAR_VORT_DIV_NAMES = [\n radar_utils.VORTICITY_NAME, radar_utils.DIVERGENCE_NAME,\n radar_utils.LOW_LEVEL_SHEAR_NAME, radar_utils.MID_LEVEL_SHEAR_NAME\n]\n\nKM_TO_KILOFEET = 3.2808\nMETRES_TO_KM = 1e-3\nPER_SECOND_TO_PER_KILOSECOND = 1e3\n\nDEFAULT_FONT_SIZE = 20\n\nFIELD_NAME_TO_VERBOSE_DICT = {\n radar_utils.ECHO_TOP_15DBZ_NAME: '15-dBZ echo top (kft ASL)',\n radar_utils.ECHO_TOP_18DBZ_NAME: '18-dBZ echo top (kft ASL)',\n radar_utils.ECHO_TOP_20DBZ_NAME: '20-dBZ echo top (kft ASL)',\n radar_utils.ECHO_TOP_25DBZ_NAME: '25-dBZ echo top (kft ASL)',\n radar_utils.ECHO_TOP_40DBZ_NAME: '40-dBZ echo top (kft ASL)',\n radar_utils.ECHO_TOP_50DBZ_NAME: '50-dBZ echo top (kft ASL)',\n radar_utils.LOW_LEVEL_SHEAR_NAME: r'Low-level shear (ks$^{-1}$)',\n radar_utils.MID_LEVEL_SHEAR_NAME: r'Mid-level shear (ks$^{-1}$)',\n radar_utils.MESH_NAME: 'Max estimated hail size (mm)',\n radar_utils.REFL_NAME: 'Reflectivity (dBZ)',\n radar_utils.REFL_COLUMN_MAX_NAME: 'Column-max reflectivity (dBZ)',\n radar_utils.REFL_0CELSIUS_NAME: r'0 $^{\\circ}C$ reflectivity (dBZ)',\n radar_utils.REFL_M10CELSIUS_NAME: r'-10 $^{\\circ}C$ reflectivity (dBZ)',\n radar_utils.REFL_M20CELSIUS_NAME: r'-20 $^{\\circ}C$ reflectivity (dBZ)',\n radar_utils.REFL_LOWEST_ALTITUDE_NAME: 'Lowest-altitude refl (dBZ)',\n radar_utils.SHI_NAME: 'Severe-hail index',\n radar_utils.VIL_NAME: 'Vertically integ liquid (mm)',\n radar_utils.DIFFERENTIAL_REFL_NAME: 'Diff reflectivity (dB)',\n radar_utils.SPEC_DIFF_PHASE_NAME: r'Spec diff phase ($^{\\circ}$ km$^{-1}$)',\n radar_utils.CORRELATION_COEFF_NAME: 'Correlation coefficient',\n radar_utils.SPECTRUM_WIDTH_NAME: r'Spectrum width (m s$^{-1}$)',\n radar_utils.VORTICITY_NAME: r'Vorticity (ks$^{-1}$)',\n radar_utils.DIVERGENCE_NAME: r'Divergence (ks$^{-1}$)'\n}\n\n\ndef _get_friendly_colours():\n \"\"\"Returns colours in colourblind-friendly scheme used by GridRad viewer.\n\n :return: colour_list: 1-D list, where each element is a numpy array with the\n [R, G, B] values in that order.\n \"\"\"\n\n colour_list = [\n [242, 247, 233], [220, 240, 212], [193, 233, 196], [174, 225, 196],\n [156, 218, 205], [138, 200, 211], [122, 163, 204], [106, 119, 196],\n [112, 92, 189], [137, 78, 182], [167, 64, 174], [167, 52, 134],\n [160, 41, 83], [153, 30, 30]\n ]\n\n for i in range(len(colour_list)):\n colour_list[i] = numpy.array(colour_list[i], dtype=float) / 255\n\n return colour_list\n\n\ndef _get_modern_colours():\n \"\"\"Returns colours in \"modern\" scheme used by GridRad viewer.\n\n :return: colour_list: See doc for `_get_friendly_colours`.\n \"\"\"\n\n colour_list = [\n [0, 0, 0], [64, 64, 64], [131, 131, 131], [0, 24, 255],\n [0, 132, 255], [0, 255, 255], [5, 192, 127], [5, 125, 0],\n [105, 192, 0], [255, 255, 0], [255, 147, 8], [255, 36, 15],\n [255, 0, 255], [255, 171, 255]\n ]\n\n for i in range(len(colour_list)):\n colour_list[i] = numpy.array(colour_list[i], dtype=float) / 255\n\n return colour_list\n\n\ndef _get_reflectivity_colour_scheme():\n \"\"\"Returns colour scheme for reflectivity.\n\n :return: colour_map_object: Instance of `matplotlib.colors.ListedColormap`.\n :return: colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`.\n \"\"\"\n\n colour_list = [\n [4, 233, 231], [1, 159, 244], [3, 0, 244], [2, 253, 2],\n [1, 197, 1], [0, 142, 0], [253, 248, 2], [229, 188, 0],\n [253, 149, 0], [253, 0, 0], [212, 0, 0], [188, 0, 0],\n [248, 0, 253], [152, 84, 198]\n ]\n\n for i in range(len(colour_list)):\n colour_list[i] = numpy.array(colour_list[i], dtype=float) / 255\n\n colour_map_object = matplotlib.colors.ListedColormap(colour_list)\n colour_map_object.set_under(numpy.full(3, 1))\n\n colour_bounds_dbz = numpy.array(\n [0.1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70])\n colour_norm_object = matplotlib.colors.BoundaryNorm(\n colour_bounds_dbz, colour_map_object.N)\n\n return colour_map_object, colour_norm_object\n\n\ndef _get_zdr_colour_scheme():\n \"\"\"Returns colour scheme for Z_DR (differential reflectivity).\n\n :return: colour_map_object: Instance of `matplotlib.colors.ListedColormap`.\n :return: colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`.\n \"\"\"\n\n colour_list = _get_modern_colours()\n colour_map_object = matplotlib.colors.ListedColormap(colour_list)\n\n colour_bounds_db = numpy.array(\n [-1, -0.5, 0, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 2.5, 3, 3.5, 4])\n colour_norm_object = matplotlib.colors.BoundaryNorm(\n colour_bounds_db, colour_map_object.N)\n\n return colour_map_object, colour_norm_object\n\n\ndef _get_kdp_colour_scheme():\n \"\"\"Returns colour scheme for K_DP (specific differential phase).\n\n :return: colour_map_object: Instance of `matplotlib.colors.ListedColormap`.\n :return: colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`.\n \"\"\"\n\n colour_list = _get_modern_colours()\n colour_map_object = matplotlib.colors.ListedColormap(colour_list)\n\n colour_bounds_deg_km01 = numpy.array(\n [-1, -0.5, 0, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 2.5, 3, 3.5, 4])\n colour_norm_object = matplotlib.colors.BoundaryNorm(\n colour_bounds_deg_km01, colour_map_object.N)\n\n return colour_map_object, colour_norm_object\n\n\ndef _get_rho_hv_colour_scheme():\n \"\"\"Returns colour scheme for rho_hv (cross-polar correlation coefficient).\n\n :return: colour_map_object: Instance of `matplotlib.colors.ListedColormap`.\n :return: colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`.\n \"\"\"\n\n colour_list = _get_modern_colours()\n colour_map_object = matplotlib.colors.ListedColormap(colour_list)\n colour_map_object.set_under(numpy.full(3, 1))\n\n colour_bounds_unitless = numpy.array(\n [0.7, 0.75, 0.8, 0.85, 0.9, 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97,\n 0.98, 0.99, 1]\n )\n\n colour_norm_object = matplotlib.colors.BoundaryNorm(\n colour_bounds_unitless, colour_map_object.N)\n\n return colour_map_object, colour_norm_object\n\n\ndef _get_spectrum_width_colour_scheme():\n \"\"\"Returns colour scheme for velocity-spectrum width.\n\n :return: colour_map_object: Instance of `matplotlib.colors.ListedColormap`.\n :return: colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`.\n \"\"\"\n\n colour_list = _get_friendly_colours()\n colour_map_object = matplotlib.colors.ListedColormap(colour_list)\n colour_map_object.set_under(numpy.full(3, 1))\n\n colour_bounds_m_s01 = numpy.array(\n [0.1, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 5, 6, 7, 8, 9, 10])\n colour_norm_object = matplotlib.colors.BoundaryNorm(\n colour_bounds_m_s01, colour_map_object.N)\n\n return colour_map_object, colour_norm_object\n\n\ndef _get_vorticity_colour_scheme():\n \"\"\"Returns colour scheme for vorticity.\n\n :return: colour_map_object: Instance of `matplotlib.colors.ListedColormap`.\n :return: colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`.\n \"\"\"\n\n colour_list = [\n [0, 0, 76.5], [0, 0, 118.5], [0, 0, 163.3], [0, 0, 208.1],\n [0, 0, 252.9], [61, 61, 255], [125, 125, 255], [189, 189, 255],\n [253, 253, 255], [255, 193, 193], [255, 129, 129], [255, 65, 65],\n [255, 1, 1], [223.5, 0, 0], [191.5, 0, 0], [159.5, 0, 0],\n [127.5, 0, 0], [95.5, 0, 0]\n ]\n\n for i in range(len(colour_list)):\n colour_list[i] = numpy.array(colour_list[i], dtype=float) / 255\n\n colour_map_object = matplotlib.colors.ListedColormap(colour_list)\n colour_bounds_ks01 = numpy.array(\n [-7, -6, -5, -4, -3, -2, -1.5, -1, -0.5, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 7])\n colour_norm_object = matplotlib.colors.BoundaryNorm(\n colour_bounds_ks01, colour_map_object.N)\n\n return colour_map_object, colour_norm_object\n\n\ndef _get_az_shear_colour_scheme():\n \"\"\"Returns colour scheme for azimuthal shear.\n\n :return: colour_map_object: Instance of `matplotlib.colors.ListedColormap`.\n :return: colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`.\n \"\"\"\n\n colour_list = [\n [0, 0, 76.5], [0, 0, 118.5], [0, 0, 163.3], [0, 0, 208.1],\n [0, 0, 252.9], [61, 61, 255], [125, 125, 255], [189, 189, 255],\n [253, 253, 255], [255, 193, 193], [255, 129, 129], [255, 65, 65],\n [255, 1, 1], [223.5, 0, 0], [191.5, 0, 0], [159.5, 0, 0],\n [127.5, 0, 0], [95.5, 0, 0]\n ]\n\n for i in range(len(colour_list)):\n colour_list[i] = numpy.array(colour_list[i], dtype=float) / 255\n\n colour_map_object = matplotlib.colors.ListedColormap(colour_list)\n colour_bounds_ks01 = 2 * numpy.array(\n [-7, -6, -5, -4, -3, -2, -1.5, -1, -0.5, 0.5, 1, 1.5, 2, 3, 4, 5, 6, 7])\n colour_norm_object = matplotlib.colors.BoundaryNorm(\n colour_bounds_ks01, colour_map_object.N)\n\n return colour_map_object, colour_norm_object\n\n\ndef _get_divergence_colour_scheme():\n \"\"\"Returns colour scheme for divergence.\n\n :return: colour_map_object: Instance of `matplotlib.colors.ListedColormap`.\n :return: colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`.\n \"\"\"\n\n return _get_az_shear_colour_scheme()\n\n\ndef _get_echo_top_colour_scheme():\n \"\"\"Returns colour scheme for echo top.\n\n :return: colour_map_object: Instance of `matplotlib.colors.ListedColormap`.\n :return: colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`.\n \"\"\"\n\n colour_list = [\n [120, 120, 120], [16, 220, 244], [11, 171, 247], [9, 144, 202],\n [48, 6, 134], [4, 248, 137], [10, 185, 6], [1, 241, 8],\n [255, 186, 1], [255, 251, 0], [132, 17, 22], [233, 16, 1]\n ]\n\n for i in range(len(colour_list)):\n colour_list[i] = numpy.array(colour_list[i], dtype=float) / 255\n\n colour_map_object = matplotlib.colors.ListedColormap(colour_list)\n colour_map_object.set_under(numpy.full(3, 1))\n\n colour_bounds_kft = numpy.array(\n [0.1, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65])\n colour_norm_object = matplotlib.colors.BoundaryNorm(\n colour_bounds_kft, colour_map_object.N)\n\n return colour_map_object, colour_norm_object\n\n\ndef _get_mesh_colour_scheme():\n \"\"\"Returns colour scheme for MESH (maximum estimated size of hail).\n\n :return: colour_map_object: Instance of `matplotlib.colors.ListedColormap`.\n :return: colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`.\n \"\"\"\n\n colour_list = [\n [152, 152, 152], [152, 203, 254], [0, 152, 254], [0, 45, 254],\n [0, 101, 0], [0, 152, 0], [0, 203, 0], [254, 254, 50],\n [254, 203, 0], [254, 152, 0], [254, 0, 0], [254, 0, 152],\n [152, 50, 203]\n ]\n\n for i in range(len(colour_list)):\n colour_list[i] = numpy.array(colour_list[i], dtype=float) / 255\n\n colour_map_object = matplotlib.colors.ListedColormap(colour_list)\n colour_map_object.set_under(numpy.full(3, 1))\n\n colour_bounds_mm = numpy.array(\n [0.1, 15.9, 22.2, 28.6, 34.9, 41.3, 47.6, 54, 60.3, 65, 70, 75, 80, 85])\n colour_norm_object = matplotlib.colors.BoundaryNorm(\n colour_bounds_mm, colour_map_object.N)\n\n return colour_map_object, colour_norm_object\n\n\ndef _get_shi_colour_scheme():\n \"\"\"Returns colour scheme for SHI (severe-hail index).\n\n :return: colour_map_object: Instance of `matplotlib.colors.ListedColormap`.\n :return: colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`.\n \"\"\"\n\n colour_list = [\n [152, 152, 152], [152, 203, 254], [0, 152, 254], [0, 45, 254],\n [0, 101, 0], [0, 152, 0], [0, 203, 0], [254, 254, 50],\n [254, 203, 0], [254, 152, 0], [254, 0, 0], [254, 0, 152],\n [152, 50, 203], [101, 0, 152]\n ]\n\n for i in range(len(colour_list)):\n colour_list[i] = numpy.array(colour_list[i], dtype=float) / 255\n\n colour_map_object = matplotlib.colors.ListedColormap(colour_list)\n colour_map_object.set_under(numpy.full(3, 1))\n\n colour_bounds_unitless = numpy.array(\n [1, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 360, 390, 420])\n colour_norm_object = matplotlib.colors.BoundaryNorm(\n colour_bounds_unitless, colour_map_object.N)\n\n return colour_map_object, colour_norm_object\n\n\ndef _get_vil_colour_scheme():\n \"\"\"Returns colour scheme for VIL (vertically integrated liquid).\n\n :return: colour_map_object: Instance of `matplotlib.colors.ListedColormap`.\n :return: colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`.\n \"\"\"\n\n colour_list = [\n [16, 71, 101], [0, 99, 132], [46, 132, 181], [74, 166, 218],\n [122, 207, 255], [179, 0, 179], [222, 83, 222], [255, 136, 255],\n [253, 191, 253], [255, 96, 0], [255, 128, 32], [255, 208, 0],\n [180, 0, 0], [224, 0, 0]\n ]\n\n for i in range(len(colour_list)):\n colour_list[i] = numpy.array(colour_list[i], dtype=float) / 255\n\n colour_map_object = matplotlib.colors.ListedColormap(colour_list)\n colour_map_object.set_under(numpy.full(3, 1))\n\n colour_bounds_mm = numpy.array(\n [0.1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70])\n colour_norm_object = matplotlib.colors.BoundaryNorm(\n colour_bounds_mm, colour_map_object.N)\n\n return colour_map_object, colour_norm_object\n\n\ndef _field_to_plotting_units(field_matrix, field_name):\n \"\"\"Converts radar field from default units to plotting units.\n\n :param field_matrix: numpy array in default units.\n :param field_name: Name of radar field (must be accepted by\n `radar_utils.check_field_name`).\n :return: new_field_matrix: Same as input, except in plotting units.\n \"\"\"\n\n radar_utils.check_field_name(field_name)\n\n if field_name in radar_utils.ECHO_TOP_NAMES:\n return field_matrix * KM_TO_KILOFEET\n\n if field_name in SHEAR_VORT_DIV_NAMES:\n return field_matrix * PER_SECOND_TO_PER_KILOSECOND\n\n return field_matrix\n\n\ndef _field_name_to_plotting_units(field_name):\n \"\"\"Converts field *name* from default units to plotting units.\n\n :param field_name: Name of radar field (must be accepted by\n `radar_utils.check_field_name`).\n :return: new_field_name: Same as input, except in plotting units.\n \"\"\"\n\n radar_utils.check_field_name(field_name)\n\n if field_name in radar_utils.ECHO_TOP_NAMES:\n return field_name.replace('_km', '_kft')\n\n if field_name in SHEAR_VORT_DIV_NAMES:\n return field_name.replace('_s01', '_ks01')\n\n return field_name\n\n\ndef layer_ops_to_field_and_panel_names(\n list_of_layer_operation_dicts, include_units=True):\n \"\"\"Converts list of layer operations to list of field and panel names.\n\n P = number of layer operations = number of panels\n\n :param list_of_layer_operation_dicts: See doc for\n `input_examples.reduce_examples_3d_to_2d`.\n :param include_units: Boolean flag. If True, panel names will include\n units.\n :return: field_name_by_panel: length-P list with names of radar fields.\n :return: panel_names: length-P list of panel names (to be printed at bottoms\n of panels).\n \"\"\"\n\n error_checking.assert_is_boolean(include_units)\n\n num_panels = len(list_of_layer_operation_dicts)\n field_name_by_panel = [''] * num_panels\n panel_names = [''] * num_panels\n\n for i in range(num_panels):\n this_operation_dict = list_of_layer_operation_dicts[i]\n field_name_by_panel[i] = this_operation_dict[\n input_examples.RADAR_FIELD_KEY]\n\n this_min_height_m_agl = int(numpy.round(\n this_operation_dict[input_examples.MIN_HEIGHT_KEY] * METRES_TO_KM\n ))\n this_max_height_m_agl = int(numpy.round(\n this_operation_dict[input_examples.MAX_HEIGHT_KEY] * METRES_TO_KM\n ))\n\n this_field_name_verbose = FIELD_NAME_TO_VERBOSE_DICT[\n field_name_by_panel[i]\n ]\n\n if not include_units:\n this_field_name_verbose = this_field_name_verbose[\n :this_field_name_verbose.find(' (')\n ]\n\n panel_names[i] = '{0:s}\\n{1:s} from {2:d}-{3:d} km AGL'.format(\n this_field_name_verbose,\n this_operation_dict[input_examples.OPERATION_NAME_KEY].upper(),\n this_min_height_m_agl, this_max_height_m_agl\n )\n\n return field_name_by_panel, panel_names\n\n\ndef radar_fields_and_heights_to_panel_names(\n field_names, heights_m_agl, include_units=True):\n \"\"\"Converts list of radar field/height pairs to panel names.\n\n P = number of panels\n\n :param field_names: length-P list with names of radar fields. Each must be\n accepted by `radar_utils.check_field_name`.\n :param heights_m_agl: length-P numpy array of heights (metres above ground\n level).\n :param include_units: Boolean flag. If True, panel names will include\n units.\n :return: panel_names: length-P list of panel names (to be printed at bottoms\n of panels).\n \"\"\"\n\n error_checking.assert_is_boolean(include_units)\n\n error_checking.assert_is_string_list(field_names)\n error_checking.assert_is_numpy_array(\n numpy.array(field_names), num_dimensions=1)\n num_panels = len(field_names)\n\n error_checking.assert_is_numpy_array(\n heights_m_agl, exact_dimensions=numpy.array([num_panels])\n )\n error_checking.assert_is_geq_numpy_array(heights_m_agl, 0.)\n heights_m_agl = numpy.round(heights_m_agl).astype(int)\n\n panel_names = [''] * num_panels\n\n for i in range(num_panels):\n this_field_name_verbose = FIELD_NAME_TO_VERBOSE_DICT[field_names[i]]\n\n if not include_units:\n this_field_name_verbose = this_field_name_verbose[\n :this_field_name_verbose.find(' (')\n ]\n\n panel_names[i] = '{0:s}\\nat {1:.2f} km AGL'.format(\n this_field_name_verbose, heights_m_agl[i] * METRES_TO_KM)\n\n return panel_names\n\n\ndef get_default_colour_scheme(field_name):\n \"\"\"Returns default colour scheme for radar field.\n\n :param field_name: Field name (must be accepted by\n `radar_utils.check_field_name`).\n :return: colour_map_object: Instance of `matplotlib.colors.ListedColormap`.\n :return: colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`.\n \"\"\"\n\n radar_utils.check_field_name(field_name)\n\n if field_name in radar_utils.REFLECTIVITY_NAMES:\n return _get_reflectivity_colour_scheme()\n\n if field_name in radar_utils.SHEAR_NAMES:\n return _get_az_shear_colour_scheme()\n\n if field_name in radar_utils.ECHO_TOP_NAMES:\n return _get_echo_top_colour_scheme()\n\n if field_name == radar_utils.MESH_NAME:\n return _get_mesh_colour_scheme()\n\n if field_name == radar_utils.SHI_NAME:\n return _get_shi_colour_scheme()\n\n if field_name == radar_utils.VIL_NAME:\n return _get_vil_colour_scheme()\n\n if field_name == radar_utils.DIFFERENTIAL_REFL_NAME:\n return _get_zdr_colour_scheme()\n\n if field_name == radar_utils.SPEC_DIFF_PHASE_NAME:\n return _get_kdp_colour_scheme()\n\n if field_name == radar_utils.CORRELATION_COEFF_NAME:\n return _get_rho_hv_colour_scheme()\n\n if field_name == radar_utils.SPECTRUM_WIDTH_NAME:\n return _get_spectrum_width_colour_scheme()\n\n if field_name == radar_utils.VORTICITY_NAME:\n return _get_vorticity_colour_scheme()\n\n if field_name == radar_utils.DIVERGENCE_NAME:\n return _get_divergence_colour_scheme()\n\n return None\n\n\ndef plot_latlng_grid(\n field_matrix, field_name, axes_object, min_grid_point_latitude_deg,\n min_grid_point_longitude_deg, latitude_spacing_deg,\n longitude_spacing_deg, colour_map_object=None, colour_norm_object=None):\n \"\"\"Plots lat-long grid as colour map.\n\n M = number of rows (unique grid-point latitudes)\n N = number of columns (unique grid-point longitudes)\n\n Because this method plots a lat-long grid (rather than an x-y grid), if you\n have used Basemap to plot borders or anything else, the only acceptable\n projection is cylindrical equidistant (in which x = longitude and\n y = latitude, so no coordinate conversion is necessary).\n\n To use the default colour scheme for the given radar field, leave\n `colour_map_object` and `colour_norm_object` empty.\n\n :param field_matrix: M-by-N numpy array with values of radar field.\n :param field_name: Name of radar field (must be accepted by\n `radar_utils.check_field_name`).\n :param axes_object: Instance of `matplotlib.axes._subplots.AxesSubplot`.\n :param min_grid_point_latitude_deg: Minimum latitude (deg N) over all grid\n points. This should be the latitude in the first row of `field_matrix`\n -- i.e., at `field_matrix[0, :]`.\n :param min_grid_point_longitude_deg: Minimum longitude (deg E) over all grid\n points. This should be the longitude in the first column of\n `field_matrix` -- i.e., at `field_matrix[:, 0]`.\n :param latitude_spacing_deg: Spacing (deg N) between grid points in adjacent\n rows.\n :param longitude_spacing_deg: Spacing (deg E) between grid points in\n adjacent columns.\n :param colour_map_object: Instance of `matplotlib.pyplot.cm`. If this is\n None, the default colour scheme for `field_name` will be used.\n :param colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`. If\n this is None, the default colour scheme for `field_name` will be used.\n \"\"\"\n\n field_matrix = _field_to_plotting_units(\n field_matrix=field_matrix, field_name=field_name)\n\n (field_matrix_at_edges, grid_cell_edge_latitudes_deg,\n grid_cell_edge_longitudes_deg\n ) = grids.latlng_field_grid_points_to_edges(\n field_matrix=field_matrix, min_latitude_deg=min_grid_point_latitude_deg,\n min_longitude_deg=min_grid_point_longitude_deg,\n lat_spacing_deg=latitude_spacing_deg,\n lng_spacing_deg=longitude_spacing_deg)\n\n field_matrix_at_edges = numpy.ma.masked_where(\n numpy.isnan(field_matrix_at_edges), field_matrix_at_edges)\n\n use_default_colour_scheme = (\n colour_map_object is None or colour_norm_object is None\n )\n\n if use_default_colour_scheme:\n colour_map_object, colour_norm_object = get_default_colour_scheme(\n field_name)\n else:\n if hasattr(colour_norm_object, 'boundaries'):\n colour_norm_object.boundaries = _field_to_plotting_units(\n field_matrix=colour_norm_object.boundaries,\n field_name=field_name)\n else:\n colour_norm_object.vmin = _field_to_plotting_units(\n field_matrix=colour_norm_object.vmin, field_name=field_name)\n colour_norm_object.vmax = _field_to_plotting_units(\n field_matrix=colour_norm_object.vmax, field_name=field_name)\n\n if hasattr(colour_norm_object, 'boundaries'):\n min_colour_value = colour_norm_object.boundaries[0]\n max_colour_value = colour_norm_object.boundaries[-1]\n else:\n min_colour_value = colour_norm_object.vmin\n max_colour_value = colour_norm_object.vmax\n\n if not use_default_colour_scheme:\n min_colour_value = _field_to_plotting_units(\n field_matrix=min_colour_value, field_name=field_name)\n max_colour_value = _field_to_plotting_units(\n field_matrix=max_colour_value, field_name=field_name)\n\n pyplot.pcolormesh(\n grid_cell_edge_longitudes_deg, grid_cell_edge_latitudes_deg,\n field_matrix_at_edges, cmap=colour_map_object, norm=colour_norm_object,\n vmin=min_colour_value, vmax=max_colour_value, shading='flat',\n edgecolors='None', axes=axes_object, zorder=-1e9)\n\n\ndef plot_2d_grid_without_coords(\n field_matrix, field_name, axes_object, font_size=DEFAULT_FONT_SIZE,\n annotation_string=None, colour_map_object=None,\n colour_norm_object=None):\n \"\"\"Plots 2-D grid as colour map.\n\n M = number of rows in grid\n N = number of columns in grid\n\n In this case the grid is not georeferenced (convenient for storm-centered\n radar images).\n\n To use the default colour scheme for the given radar field, leave\n `colour_map_object` and `colour_norm_object` empty.\n\n :param field_matrix: M-by-N numpy array of radar values.\n :param field_name: Same.\n :param axes_object: Same.\n :param font_size: Font size for annotation.\n :param annotation_string: Annotation (will be printed in the bottom-center).\n If you want no annotation, leave this alone.\n :param colour_map_object: See doc for `plot_latlng_grid`.\n :param colour_norm_object: Same.\n :return: colour_map_object: Same as input, except default might have been\n set.\n :return: colour_norm_object: Same as input, except default might have been\n set.\n \"\"\"\n\n error_checking.assert_is_numpy_array_without_nan(field_matrix)\n error_checking.assert_is_numpy_array(field_matrix, num_dimensions=2)\n\n field_matrix = _field_to_plotting_units(\n field_matrix=field_matrix, field_name=field_name)\n field_matrix = numpy.ma.masked_where(\n numpy.isnan(field_matrix), field_matrix)\n\n use_default_colour_scheme = (\n colour_map_object is None or colour_norm_object is None\n )\n\n if use_default_colour_scheme:\n colour_map_object, colour_norm_object = get_default_colour_scheme(\n field_name)\n else:\n if hasattr(colour_norm_object, 'boundaries'):\n colour_norm_object.boundaries = _field_to_plotting_units(\n field_matrix=colour_norm_object.boundaries,\n field_name=field_name)\n else:\n colour_norm_object.vmin = _field_to_plotting_units(\n field_matrix=colour_norm_object.vmin, field_name=field_name)\n colour_norm_object.vmax = _field_to_plotting_units(\n field_matrix=colour_norm_object.vmax, field_name=field_name)\n\n if hasattr(colour_norm_object, 'boundaries'):\n min_colour_value = colour_norm_object.boundaries[0]\n max_colour_value = colour_norm_object.boundaries[-1]\n else:\n min_colour_value = colour_norm_object.vmin\n max_colour_value = colour_norm_object.vmax\n\n axes_object.pcolormesh(\n field_matrix, cmap=colour_map_object, norm=colour_norm_object,\n vmin=min_colour_value, vmax=max_colour_value, shading='flat',\n edgecolors='None', zorder=-1e9)\n\n x_coord_limits = axes_object.get_xlim()\n x_grid_coords = numpy.linspace(\n x_coord_limits[0], x_coord_limits[1], num=5, dtype=float\n )[1:-1]\n\n y_coord_limits = axes_object.get_ylim()\n y_grid_coords = numpy.linspace(\n y_coord_limits[0], y_coord_limits[1], num=5, dtype=float\n )[1:-1]\n\n axes_object.set_xticks(x_grid_coords)\n axes_object.set_yticks(y_grid_coords)\n axes_object.grid(\n b=True, which='major', axis='both', linestyle='--', linewidth=2)\n\n axes_object.xaxis.set_ticklabels([])\n axes_object.yaxis.set_ticklabels([])\n axes_object.xaxis.set_ticks_position('none')\n axes_object.yaxis.set_ticks_position('none')\n\n if annotation_string is not None:\n error_checking.assert_is_string(annotation_string)\n\n bounding_box_dict = {\n 'facecolor': 'white',\n 'alpha': 0.5,\n 'edgecolor': 'black',\n 'linewidth': 2\n }\n\n axes_object.text(\n 0.5, 0.01, annotation_string, fontsize=font_size, fontweight='bold',\n bbox=bounding_box_dict, color='k', horizontalalignment='center',\n verticalalignment='bottom', transform=axes_object.transAxes,\n zorder=1e10)\n\n return colour_map_object, colour_norm_object\n\n\ndef plot_many_2d_grids_without_coords(\n field_matrix, field_name_by_panel, num_panel_rows=None,\n figure_object=None, axes_object_matrix=None, panel_names=None,\n colour_map_object_by_panel=None, colour_norm_object_by_panel=None,\n plot_colour_bar_by_panel=None, font_size=DEFAULT_FONT_SIZE,\n row_major=True):\n \"\"\"Plots 2-D colour map in each panel (one per field/height pair).\n\n M = number of rows in spatial grid\n N = number of columns in spatial grid\n P = number of panels (field/height pairs)\n\n This method uses the default colour scheme for each radar field.\n\n If `num_panel_rows is None`, this method needs arguments `figure_object` and\n `axes_object_matrix` -- and vice-versa.\n\n :param field_matrix: M-by-N-by-P numpy array of radar values.\n :param field_name_by_panel: length-P list of field names.\n :param num_panel_rows: Number of rows in paneled figure (different than M,\n which is number of rows in spatial grid).\n :param figure_object: See doc for `plotting_utils.create_paneled_figure`.\n :param axes_object_matrix: See above.\n :param panel_names: length-P list of panel names (will be printed at bottoms\n of panels). If you do not want panel names, make this None.\n :param colour_map_object_by_panel: length-P list of `matplotlib.pyplot.cm`\n objects. If this is None, the default will be used for each field.\n :param colour_norm_object_by_panel: length-P list of\n `matplotlib.colors.BoundaryNorm` objects. If this is None, the default\n will be used for each field.\n :param plot_colour_bar_by_panel: length-P numpy array of Boolean flags. If\n plot_colour_bar_by_panel[k] = True, horizontal colour bar will be\n plotted under [k]th panel. If you want to plot colour bar for every\n panel, leave this as None.\n :param font_size: Font size.\n :param row_major: Boolean flag. If True, panels will be filled along rows\n first, then down columns. If False, down columns first, then along\n rows.\n :return: figure_object: See doc for `plotting_utils.create_paneled_figure`.\n :return: axes_object_matrix: Same.\n :raises: ValueError: if `colour_map_object_by_panel` or\n `colour_norm_object_by_panel` has different length than number of\n panels.\n \"\"\"\n\n error_checking.assert_is_boolean(row_major)\n error_checking.assert_is_numpy_array(field_matrix, num_dimensions=3)\n num_panels = field_matrix.shape[2]\n\n if panel_names is None:\n panel_names = [None] * num_panels\n if plot_colour_bar_by_panel is None:\n plot_colour_bar_by_panel = numpy.full(num_panels, True, dtype=bool)\n\n these_expected_dim = numpy.array([num_panels], dtype=int)\n error_checking.assert_is_numpy_array(\n numpy.array(panel_names), exact_dimensions=these_expected_dim\n )\n error_checking.assert_is_numpy_array(\n numpy.array(field_name_by_panel), exact_dimensions=these_expected_dim\n )\n\n error_checking.assert_is_boolean_numpy_array(plot_colour_bar_by_panel)\n error_checking.assert_is_numpy_array(\n plot_colour_bar_by_panel, exact_dimensions=these_expected_dim)\n\n if (colour_map_object_by_panel is None\n or colour_norm_object_by_panel is None):\n colour_map_object_by_panel = [None] * num_panels\n colour_norm_object_by_panel = [None] * num_panels\n\n error_checking.assert_is_list(colour_map_object_by_panel)\n error_checking.assert_is_list(colour_norm_object_by_panel)\n\n if len(colour_map_object_by_panel) != num_panels:\n error_string = (\n 'Number of colour maps ({0:d}) should equal number of panels '\n '({1:d}).'\n ).format(len(colour_map_object_by_panel), num_panels)\n\n raise ValueError(error_string)\n\n if len(colour_norm_object_by_panel) != num_panels:\n error_string = (\n 'Number of colour-normalizers ({0:d}) should equal number of panels'\n ' ({1:d}).'\n ).format(len(colour_norm_object_by_panel), num_panels)\n\n raise ValueError(error_string)\n\n if figure_object is None:\n error_checking.assert_is_integer(num_panel_rows)\n error_checking.assert_is_geq(num_panel_rows, 1)\n error_checking.assert_is_leq(num_panel_rows, num_panels)\n\n num_panel_columns = int(numpy.ceil(\n float(num_panels) / num_panel_rows\n ))\n\n figure_object, axes_object_matrix = (\n plotting_utils.create_paneled_figure(\n num_rows=num_panel_rows, num_columns=num_panel_columns,\n shared_x_axis=False, shared_y_axis=False,\n keep_aspect_ratio=True)\n )\n else:\n error_checking.assert_is_numpy_array(\n axes_object_matrix, num_dimensions=2)\n\n num_panel_rows = axes_object_matrix.shape[0]\n num_panel_columns = axes_object_matrix.shape[1]\n\n if row_major:\n order_string = 'C'\n else:\n order_string = 'F'\n\n for k in range(num_panels):\n this_panel_row, this_panel_column = numpy.unravel_index(\n k, (num_panel_rows, num_panel_columns), order=order_string\n )\n\n # this_colour_map_object, this_colour_norm_object = (\n # plot_2d_grid_without_coords(\n # field_matrix=field_matrix[..., k],\n # field_name=field_name_by_panel[k],\n # axes_object=axes_object_matrix[\n # this_panel_row, this_panel_column],\n # annotation_string=panel_names[k], font_size=font_size,\n # colour_map_object=colour_map_object_by_panel[k],\n # colour_norm_object=colour_norm_object_by_panel[k]\n # )\n # )\n\n this_colour_map_object, this_colour_norm_object = (\n plot_2d_grid_without_coords(\n field_matrix=field_matrix[..., k],\n field_name=field_name_by_panel[k],\n axes_object=axes_object_matrix[\n this_panel_row, this_panel_column],\n annotation_string=None, font_size=font_size,\n colour_map_object=colour_map_object_by_panel[k],\n colour_norm_object=colour_norm_object_by_panel[k]\n )\n )\n\n if not plot_colour_bar_by_panel[k]:\n continue\n\n this_extend_min_flag = field_name_by_panel[k] in SHEAR_VORT_DIV_NAMES\n\n this_colour_bar_object = plotting_utils.plot_colour_bar(\n axes_object_or_matrix=axes_object_matrix[\n this_panel_row, this_panel_column],\n data_matrix=field_matrix[..., k],\n colour_map_object=this_colour_map_object,\n colour_norm_object=this_colour_norm_object,\n orientation_string='horizontal',\n extend_min=this_extend_min_flag, extend_max=True,\n fraction_of_axis_length=0.75, font_size=font_size)\n\n this_colour_bar_object.set_label(\n panel_names[k].replace('\\n', '; '), fontsize=font_size,\n fontweight='bold')\n\n for k in range(num_panel_rows * num_panel_columns):\n if k < num_panels:\n continue\n\n this_panel_row, this_panel_column = numpy.unravel_index(\n k, (num_panel_rows, num_panel_columns), order=order_string\n )\n\n axes_object_matrix[this_panel_row, this_panel_column].axis('off')\n\n return figure_object, axes_object_matrix\n\n\ndef plot_3d_grid_without_coords(\n field_matrix, field_name, grid_point_heights_metres, ground_relative,\n num_panel_rows=None, figure_object=None, axes_object_matrix=None,\n font_size=DEFAULT_FONT_SIZE, colour_map_object=None,\n colour_norm_object=None):\n \"\"\"Plots 3-D grid as many colour maps (one per height).\n\n M = number of grid rows\n N = number of grid columns\n H = number of grid heights\n\n To use the default colour scheme for the given radar field, leave\n `colour_map_object` and `colour_norm_object` empty.\n\n If `num_panel_rows is None`, this method needs arguments `figure_object` and\n `axes_object_matrix` -- and vice-versa.\n\n :param field_matrix: M-by-N-by-H numpy array with values of radar field.\n :param field_name: Name of radar field (must be accepted by\n `radar_utils.check_field_name`).\n :param grid_point_heights_metres: length-H integer numpy array of heights.\n :param ground_relative: Boolean flag. If True, heights in\n `height_by_pair_metres` are ground-relative. If False,\n sea-level-relative.\n :param num_panel_rows: Number of rows in paneled figure (different than M,\n the number of grid rows).\n :param figure_object: See doc for `plotting_utils.create_paneled_figure`.\n :param axes_object_matrix: See above.\n :param font_size: Font size for colour-bar ticks and panel labels.\n :param colour_map_object: See doc for `plot_latlng_grid`.\n :param colour_norm_object: Same.\n :return: figure_object: See doc for `plotting_utils.init_panels`.\n :return: axes_object_matrix: Same.\n \"\"\"\n\n error_checking.assert_is_numpy_array(field_matrix, num_dimensions=3)\n error_checking.assert_is_geq_numpy_array(grid_point_heights_metres, 0)\n grid_point_heights_metres = numpy.round(\n grid_point_heights_metres\n ).astype(int)\n\n num_heights = field_matrix.shape[2]\n these_expected_dim = numpy.array([num_heights], dtype=int)\n error_checking.assert_is_numpy_array(\n grid_point_heights_metres, exact_dimensions=these_expected_dim)\n\n error_checking.assert_is_boolean(ground_relative)\n\n if figure_object is None:\n error_checking.assert_is_integer(num_panel_rows)\n error_checking.assert_is_geq(num_panel_rows, 1)\n error_checking.assert_is_leq(num_panel_rows, num_heights)\n\n num_panel_columns = int(numpy.ceil(\n float(num_heights) / num_panel_rows\n ))\n\n figure_object, axes_object_matrix = (\n plotting_utils.create_paneled_figure(\n num_rows=num_panel_rows, num_columns=num_panel_columns,\n shared_x_axis=False, shared_y_axis=False,\n keep_aspect_ratio=True)\n )\n else:\n error_checking.assert_is_numpy_array(\n axes_object_matrix, num_dimensions=2)\n\n num_panel_rows = axes_object_matrix.shape[0]\n num_panel_columns = axes_object_matrix.shape[1]\n\n for i in range(num_panel_rows):\n for j in range(num_panel_columns):\n this_height_index = i * num_panel_columns + j\n\n if this_height_index >= num_heights:\n axes_object_matrix[i, j].axis('off')\n continue\n\n this_annotation_string = '{0:.1f} km'.format(\n grid_point_heights_metres[this_height_index] * METRES_TO_KM\n )\n\n if ground_relative:\n this_annotation_string += ' AGL'\n else:\n this_annotation_string += ' ASL'\n\n plot_2d_grid_without_coords(\n field_matrix=field_matrix[..., this_height_index],\n field_name=field_name, axes_object=axes_object_matrix[i, j],\n annotation_string=this_annotation_string,\n colour_map_object=colour_map_object,\n colour_norm_object=colour_norm_object, font_size=font_size)\n\n return figure_object, axes_object_matrix\n","sub_path":"gewittergefahr/plotting/radar_plotting.py","file_name":"radar_plotting.py","file_ext":"py","file_size_in_byte":39363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"238443297","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: /Users/ryan/DH/prosodic/lib/Rime.py\n# Compiled at: 2012-12-06 15:11:04\nfrom entity import entity\n\nclass Rime(entity):\n\n def __init__(self, nucleuscoda, lang):\n self.feats = {}\n self.nucleus = nucleuscoda[0]\n self.coda = nucleuscoda[1]\n self.featpaths = {}\n self.lang = lang\n self.children = []\n if self.nucleus:\n self.children.append(self.nucleus)\n else:\n self.broken = True\n if self.coda:\n self.children.append(self.coda)\n\n def isBranching(self):\n return self.hasCoda()\n\n def hasCoda(self):\n if self.coda.children:\n return True\n else:\n return False","sub_path":"pycfiles/prosody-0.0.5-py3-none-any/Rime.py","file_name":"Rime.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"269736888","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import jit\n\ndef createBasicConv(in_chs, out_chs, **kwargs):\n return nn.Sequential(\n nn.Conv1d(in_chs, out_chs, bias=False, **kwargs),\n nn.ReLU(inplace=True)\n )\n\ndef createNormConv(in_chs, out_chs, **kwargs):\n return nn.Sequential(\n nn.Conv1d(in_chs, out_chs, bias=False, **kwargs),\n nn.BatchNorm1d(out_chs),\n nn.ReLU(inplace=True)\n )\n\n\ndef createBasicConvT(in_chs, out_chs, **kwargs):\n return nn.Sequential(\n nn.ConvTranspose1d(in_chs, out_chs, **kwargs),\n nn.ReLU(inplace=True)\n )\n\ndef createNormConvT(in_chs, out_chs, **kwargs):\n return nn.Sequential(\n nn.ConvTranspose1d(in_chs, out_chs, **kwargs),\n nn.BatchNorm1d(out_chs),\n nn.ReLU(inplace=True)\n )\n\n\ndef createBasicLastConvT(in_chs, out_chs, **kwargs):\n return nn.Sequential(\n nn.ConvTranspose1d(in_chs, out_chs, **kwargs),\n nn.Sigmoid()\n )\n\ndef createNormLastConvT(in_chs, out_chs, **kwargs):\n return nn.Sequential(\n nn.ConvTranspose1d(in_chs, out_chs, **kwargs),\n nn.BatchNorm1d(out_chs),\n nn.Sigmoid()\n )\n\n\nclass EncoderInceptionBasic(nn.Module):\n\n def __init__(self, in_channels, batchNorm=False):\n super().__init__()\n\n if batchNorm:\n createConv = createNormConv\n else:\n createConv = createBasicConv\n\n self.conv1 = createConv(in_channels, in_channels, kernel_size=1)\n\n self.conv3 = createConv(in_channels, in_channels, kernel_size=3, padding=1)\n\n self.conv3_1 = createConv(in_channels, in_channels, kernel_size=3, padding=1)\n self.conv3_2 = createConv(in_channels, in_channels, kernel_size=3, padding=1)\n\n self.pool3 = nn.MaxPool1d(kernel_size=3, stride=1, padding=1)\n\n def forward(self, x):\n \n y_c1 = self.conv1(x)\n\n y_c3 = self.conv3(x)\n\n y_c5 = self.conv3_1(x)\n y_c5 = self.conv3_2(y_c5)\n \n y_p3 = self.pool3(x)\n\n # print(y_c1.size())\n # print(y_c3.size())\n # print(y_c5.size())\n # print(y_p3.size())\n\n out = y_c1 + y_c3 + y_c5 + y_p3\n\n return out\n\nclass DecoderInceptionBasic(nn.Module):\n\n def __init__(self, in_channels, batchNorm=False):\n super().__init__()\n\n if batchNorm:\n createConv = createNormConvT\n else:\n createConv = createBasicConvT\n\n self.conv1 = createConv(in_channels, in_channels, kernel_size=1)\n\n self.conv3 = createConv(in_channels, in_channels, kernel_size=3, padding=1)\n\n self.conv3_1 = createConv(in_channels, in_channels, kernel_size=3, padding=1)\n self.conv3_2 = createConv(in_channels, in_channels, kernel_size=3, padding=1)\n\n self.pool3 = nn.MaxPool1d(kernel_size=3, stride=1, padding=1)\n\n def forward(self, x):\n \n y_c1 = self.conv1(x)\n\n y_c3 = self.conv3(x)\n\n y_c5 = self.conv3_1(x)\n y_c5 = self.conv3_2(y_c5)\n \n y_p3 = self.pool3(x)\n\n # print(y_c1.size())\n # print(y_c3.size())\n # print(y_c5.size())\n # print(y_p3.size())\n\n out = y_c1 + y_c3 + y_c5 + y_p3\n\n return out\n\n\n# class Encoder(nn.Module):\nclass Encoder(jit.ScriptModule):\n\n def __init__(self, first_channel, latent_size, repeat=0, batchNorm=False):\n super().__init__()\n\n if batchNorm:\n createConv = createNormConv\n else:\n createConv = createBasicConv\n\n k = first_channel\n\n self.repeat = repeat\n\n self.conv1 = createConv( 1, k, kernel_size=3, stride=3, padding=1)\n self.conv2 = createConv( k, 2*k, kernel_size=3, stride=3, padding=1)\n self.conv3 = createConv( 2*k, 4*k, kernel_size=3, stride=3, padding=1)\n self.conv4 = createConv( 4*k, 8*k, kernel_size=3, stride=2, padding=1)\n self.conv5 = createConv( 8*k, 16*k, kernel_size=3, stride=2, padding=1)\n self.conv6 = createConv(16*k, 32*k, kernel_size=3, stride=2, padding=1)\n \n # self.module1 = nn.Sequential(*[EncoderInceptionBasic( k, batchNorm) for _ in range(self.repeat)])\n # self.module2 = nn.Sequential(*[EncoderInceptionBasic( 2*k, batchNorm) for _ in range(self.repeat)])\n # self.module3 = nn.Sequential(*[EncoderInceptionBasic( 4*k, batchNorm) for _ in range(self.repeat)])\n # self.module4 = nn.Sequential(*[EncoderInceptionBasic( 8*k, batchNorm) for _ in range(self.repeat)])\n # self.module5 = nn.Sequential(*[EncoderInceptionBasic(16*k, batchNorm) for _ in range(self.repeat)])\n # self.module6 = nn.Sequential(*[EncoderInceptionBasic(32*k, batchNorm) for _ in range(self.repeat)])\n\n # self.module0 = nn.Sequential(*[EncoderInceptionBasic( 1) for _ in range(self.repeat)])\n\n self.module1 = nn.Sequential(*[EncoderInceptionBasic( k) for _ in range(self.repeat)])\n self.module2 = nn.Sequential(*[EncoderInceptionBasic( 2*k) for _ in range(self.repeat)])\n self.module3 = nn.Sequential(*[EncoderInceptionBasic( 4*k) for _ in range(self.repeat)])\n self.module4 = nn.Sequential(*[EncoderInceptionBasic( 8*k) for _ in range(self.repeat)])\n self.module5 = nn.Sequential(*[EncoderInceptionBasic(16*k) for _ in range(self.repeat)])\n self.module6 = nn.Sequential(*[EncoderInceptionBasic(32*k) for _ in range(self.repeat)])\n\n self.embedding_size = 5*32*k\n\n self.fc1 = nn.Linear(self.embedding_size, latent_size)\n self.fc2 = nn.Linear(self.embedding_size, latent_size)\n\n def forward(self, x):\n\n if self.repeat > 0:\n # h = self.module0(x)\n\n # h = self.conv1(h)\n h = self.conv1(x)\n h = self.module1(h)\n h = self.conv2(h)\n h = self.module2(h)\n h = self.conv3(h)\n h = self.module3(h)\n h = self.conv4(h)\n h = self.module4(h)\n h = self.conv5(h)\n h = self.module5(h)\n h = self.conv6(h)\n h = self.module6(h)\n else:\n h = self.conv1(x)\n h = self.conv2(h)\n h = self.conv3(h)\n h = self.conv4(h)\n h = self.conv5(h)\n h = self.conv6(h)\n\n h = h.view(-1, self.embedding_size)\n\n mu = self.fc1(h)\n logvar = self.fc2(h)\n\n return mu, logvar\n\n# class Decoder(nn.Module):\nclass Decoder(jit.ScriptModule):\n\n def __init__(self, last_channel, latent_size, repeat=0, batchNorm=False):\n super().__init__()\n\n if batchNorm:\n createConvT = createNormConvT\n createLastConvT = createBasicLastConvT\n else:\n createConvT = createBasicConvT\n createLastConvT = createBasicLastConvT\n\n self.repeat = repeat\n\n k = last_channel\n\n self.embedding_size = 5*32*k\n\n self.fc = nn.Linear(latent_size, self.embedding_size)\n\n self.convT1 = createConvT(32*k, 16*k, kernel_size=2, stride=2, padding=0)\n self.convT2 = createConvT(16*k, 8*k, kernel_size=2, stride=2, padding=0)\n self.convT3 = createConvT( 8*k, 4*k, kernel_size=2, stride=2, padding=0)\n self.convT4 = createConvT( 4*k, 2*k, kernel_size=3, stride=3, padding=0)\n self.convT5 = createConvT( 2*k, k, kernel_size=3, stride=3, padding=0)\n # self.convT6 = createConvT( k, 1, kernel_size=3, stride=3, padding=0)\n self.convT6 = createLastConvT( k, 1, kernel_size=3, stride=3, padding=0)\n\n # self.module1 = nn.Sequential(*[DecoderInceptionBasic(32*k, batchNorm) for _ in range(self.repeat)])\n # self.module2 = nn.Sequential(*[DecoderInceptionBasic(16*k, batchNorm) for _ in range(self.repeat)])\n # self.module3 = nn.Sequential(*[DecoderInceptionBasic( 8*k, batchNorm) for _ in range(self.repeat)])\n # self.module4 = nn.Sequential(*[DecoderInceptionBasic( 4*k, batchNorm) for _ in range(self.repeat)])\n # self.module5 = nn.Sequential(*[DecoderInceptionBasic( 2*k, batchNorm) for _ in range(self.repeat)])\n # self.module6 = nn.Sequential(*[DecoderInceptionBasic( k, batchNorm) for _ in range(self.repeat)])\n\n self.module1 = nn.Sequential(*[DecoderInceptionBasic(32*k) for _ in range(self.repeat)])\n self.module2 = nn.Sequential(*[DecoderInceptionBasic(16*k) for _ in range(self.repeat)])\n self.module3 = nn.Sequential(*[DecoderInceptionBasic( 8*k) for _ in range(self.repeat)])\n self.module4 = nn.Sequential(*[DecoderInceptionBasic( 4*k) for _ in range(self.repeat)])\n self.module5 = nn.Sequential(*[DecoderInceptionBasic( 2*k) for _ in range(self.repeat)])\n self.module6 = nn.Sequential(*[DecoderInceptionBasic( k) for _ in range(self.repeat)])\n\n # self.module7 = nn.Sequential(*[DecoderInceptionBasic( 1) for _ in range(self.repeat)])\n\n\n def forward(self, z):\n\n x = self.fc(z)\n\n x = x.view(-1, self.embedding_size//5, 5)\n\n if self.repeat > 0:\n x = self.module1(x)\n x = self.convT1(x)\n x = self.module2(x)\n x = self.convT2(x)\n x = self.module3(x)\n x = self.convT3(x)\n x = self.module4(x)\n x = self.convT4(x)\n x = self.module5(x)\n x = self.convT5(x)\n x = self.module6(x)\n x = self.convT6(x)\n\n # x = self.module7(x)\n # x = F.sigmoid(x)\n\n else:\n x = self.convT1(x)\n x = self.convT2(x)\n x = self.convT3(x)\n x = self.convT4(x)\n x = self.convT5(x)\n x = self.convT6(x)\n\n return x\n\n# class InceptionVAE(nn.Module):\nclass InceptionVAE(jit.ScriptModule):\n\n def __init__(self, first_channel, latent_size, repeat=0, batchNorm=False):\n super().__init__()\n self.encoder = Encoder(first_channel, latent_size, repeat, batchNorm)\n self.decoder = Decoder(first_channel, latent_size, repeat, batchNorm)\n\n def forward(self, x):\n mu, logvar = self.encoder(x)\n sigma = logvar.mul(0.5).exp()\n eps = torch.randn_like(sigma)\n\n if self.training:\n z = eps.mul(sigma).add_(mu) # mu + sigma^(1/2) * eps\n else:\n z = mu\n\n recon_x = self.decoder(z)\n return recon_x, mu, logvar\n\n def loss_function(self, recon_x, x, mu, logvar):\n\n assert (torch.min(recon_x) >= 0. and torch.max(recon_x) <= 1.)\n\n x2 = torch.clamp(x.view(recon_x.size()), 1e-24, 1.0-1e-24)\n assert (torch.min(x2) >= 0. and torch.max(x2) <= 1.)\n\n BCE = F.binary_cross_entropy(recon_x, x2, reduction='sum')\n # BCE = F.binary_cross_entropy(recon_x, x.view(-1, self.x_size), reduction='sum')\n # BCE = F.mse_loss(recon_x, x)\n \n # 0.5*(1 + log(sigma^2) - mu^2 - sigma^2) \n # 実装ではsigmaがマイナスになるとlogsigmaを求められないためか、2*logsigmaをlogvarと置いて\n # KL距離を0.5*(mu^2 + exp(logvar) −logvar − 1) とする記述が主流?\n # https://qiita.com/nishiha/items/2264da933504fbe3fc68\n\n KLD = 0.5 * torch.sum(mu.pow(2) + logvar.exp() - logvar - 1)\n # KLD = 0\n\n return BCE, KLD\n\nif __name__ == '__main__':\n\n x = torch.randn(10,1,1080)\n\n model = EncoderInceptionBasic(in_channels=1)\n\n out = model(x)\n\n print(out.size())\n\n model = DecoderInceptionBasic(in_channels=1)\n\n out = model(x)\n\n print(out.size())\n\n encoder = Encoder(first_channel=8, latent_size=18, repeat=1, batchNorm=False)\n\n mu, sigma = encoder(x)\n\n print(mu.size())\n\n decoder = Decoder(last_channel=8, latent_size=18, repeat=1, batchNorm=False)\n\n recon = decoder(mu)\n\n print(recon.size())","sub_path":"model/InceptionVAE.py","file_name":"InceptionVAE.py","file_ext":"py","file_size_in_byte":11786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"475564438","text":"##[3liz - Raster]=group\n##Define 1 raster layer properties=name\n##Raster_layer=raster\n##QML_file=file\n##Coordinate_Reference_System=crs None\n##Refresh_contrast_enhancement=boolean True\n##Save_layer_style_as_default=boolean False\n\nfrom qgis.core import *\nfrom qgis.utils import iface\nimport os\n\n# rename inputs\ncrs = Coordinate_Reference_System\nqml = QML_file\nrce = Refresh_contrast_enhancement\nss = Save_layer_style_as_default\n\n# Get layer object\nlayer = processing.getObject(Raster_layer)\n\n# Set style from QML\nif os.path.exists(qml):\n layer.loadNamedStyle(qml)\n iface.legendInterface().refreshLayerSymbology(layer)\n\n# Set CRS\nif crs:\n qcrs = QgsCoordinateReferenceSystem()\n qcrs.createFromOgcWmsCrs(crs)\n layer.setCrs(qcrs)\n\n\n# Refresh default contrast enhancement\nif rce:\n layer.setDefaultContrastEnhancement()\n\n# Save style as default\nif ss:\n layer.saveDefaultStyle()","sub_path":"scripts/Define_1_raster_layer_properties.py","file_name":"Define_1_raster_layer_properties.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"493836524","text":"#!/usr/bin/python3\n\"\"\"\nlist states from database or filestorage in a route with flask\n\"\"\"\nfrom flask import Flask, render_template, g\nfrom models import storage\n\n\nif __name__ == \"__main__\":\n app = Flask(__name__)\n\n @app.route('/states', strict_slashes=False)\n @app.route('/states/', strict_slashes=False)\n def get_states(id=\"\"):\n states = storage.all('State')\n statel = []\n for key, state in states.items():\n statel.append(state)\n sortstatel = sorted(statel, key=lambda i: i.name)\n if id:\n for state in sortstatel:\n if state.id == id:\n objfound = state\n return render_template('9-states.html', **locals())\n\n @app.teardown_appcontext\n def teardown_states(e):\n storage.close()\n\n app.run()\n","sub_path":"web_flask/9-states.py","file_name":"9-states.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"349158051","text":"import arcpy, Frame\r\n\r\narcpy.env.workspace = arcpy.GetParameterAsText(0) #this is where the files are to go\r\ninput1= arcpy.GetParameterAsText(1) # this is where the feature class is put\r\noutput= arcpy.GetParameterAsText(2) # for right now this is where the text file is saved just for testing\r\nUser_Field = arcpy.GetParameterAsText(3) # this is the string into which the user put the Field name\r\nUser_Class = arcpy.GetParameterAsText(4) # this is the string into which the user put the Class name\r\nCell_Size= arcpy.GetParameterAsText(5) # input of the cells size of the new feature class\r\nRatio= arcpy.GetParameterAsText(6) # input of the Ratio of the new feature class\r\nUser_Field_Count= arcpy.GetParameterAsText(7)\t # column name for the frequency of each Field\r\n\r\n#list for the class in the shape file\r\nClass_List=[]\r\n#nothing in this list yet, code not done\r\nFields_List=[]\r\n#this is a text file that is for testing to see if it is outputting the right thing\r\nValidation = True\r\n\r\nFields=arcpy.ListFields(input1)\r\ntry: # makeing sure the user put in the right Field name\r\n\tfor i in Fields:\r\n\t\tFields_List.append(i.name) # putting all of the Field in the feature class into the Fields_List\r\n\tif User_Field in Fields_List: # makes sure user put in the right field that have the class in them\r\n\t\tarcpy.AddMessage(\"Field Verified\")\r\n\t\twith arcpy.da.SearchCursor(input1,[User_Field]) as Classes: # this goes through the field of User_Field to find all of the class and then put them in the CLass list\r\n\t\t\tfor i in Classes:\r\n\t\t\t\tif i[0] not in Class_List:\r\n\t\t\t\t\tClass_List.append(i[0])\t\t\t\t\t # running through all of the Class and putting them in the Class_List\r\n\t\r\n\t\tdel Classes\t\t\t\r\n\telse:\r\n\t\traise ValueError\r\n\t\t\r\nexcept ValueError:\r\n\tarcpy.AddMessage(\"Error with Field name(check spelling)\")\r\n\tValidation = False\r\n\t\r\nClass_List.sort() # just to make the output to look nice\r\n\r\nif Validation: # makeing sure that the User put in the right Class\r\n\ttry:\r\n\t\tif int(User_Class) in Class_List:\r\n\t\t\tarcpy.AddMessage(\"Class Verified\")\r\n\t\telse:\r\n\t\t\traise ValueError\r\n\t\t\r\n\texcept ValueError:\r\n\t\tarcpy.AddMessage(\"Error with Value/Class (check spelling)\")\r\n\t\tValidation = False\r\n\r\nif Validation: # making sure the user put in the right field for the pixle count\r\n\ttry:\r\n\t\tif User_Field_Count in Fields_List:\r\n\t\t\tarcpy.AddMessage(\"Field 2 Verified\")\r\n\t\telse:\r\n\t\t\traise ValueError\r\n\t\t\t\r\n\texcept ValueError:\r\n\t\tarcpy.AddMessage(\"Error with Field / Column Name for pixel count (check spelling)\")\r\n\t\tValidation = False\r\n\t\t\r\n\t\t\r\n\t\t\r\n#spliting the user x & y inputs into its own variable \r\nxy=Cell_Size.split(\" \") \r\nX=xy[0]\r\nY=xy[1]\r\n\r\n# checking to see if the user put in the right class and field name to do the rest of the code\r\nif Validation:\r\n\tParameters = Frame.classifiedRaster(input1,X,Y,Ratio,User_Class)\r\n\t#arcpy.AddMessage(str(input1) + \" \" + str(X) + \" \" + str(Y) + \" \" + str(Ratio) + \" \" + str(User_Class))\r\n\tParameters.processRaster(output, User_Field_Count , Class_List,User_Field,Fields_List)\r\n","sub_path":"Inputs_Code.py","file_name":"Inputs_Code.py","file_ext":"py","file_size_in_byte":3403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"264057167","text":"from os.path import join\n\nfrom rivr import template\n\nclass TemplateLoadError(Exception):\n def __init__(self, template, tried):\n self.template = template\n self.tried = tried\n \n def __str__(self):\n return 'Unable to load %s' % self.template\n\nclass Loader(object):\n def __init__(self):\n self.template_dirs = []\n \n def load_template(self, template_names):\n tried = []\n \n if isinstance(template_names, str):\n template_names = [template_names]\n \n for template_name in template_names:\n for template_dir in self.template_dirs:\n filepath = join(template_dir, template_name)\n try:\n f = open(filepath)\n try:\n return f.read()\n finally:\n f.close()\n except IOError:\n tried.append(filepath)\n \n return tried\n \n def get_template(self, template_name):\n template_content = self.load_template(template_name)\n \n if isinstance(template_content, list):\n raise TemplateLoadError(template_name, template_content)\n \n return template.Template(template_content)\n","sub_path":"rivr/template/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"148668519","text":"#!/usr/bin/env python\n\nimport os\nfrom setuptools import find_packages, setup\n\nENCODING = 'utf-8'\nPACKAGE_NAME = 'foil'\n\nlocal_directory = os.path.abspath(os.path.dirname(__file__))\nversion_path = os.path.join(local_directory, PACKAGE_NAME, '_version.py')\n\nversion_ns = {}\nwith open(version_path, 'r', encoding=ENCODING) as f:\n exec(f.read(), {}, version_ns)\n\n\ndef get_requirements(requirement_file):\n requirements = list(\n open(requirement_file, 'r',\n encoding=ENCODING).read().strip().split('\\r\\n'))\n return requirements\n\n\nsetup(name=PACKAGE_NAME,\n packages=find_packages(exclude=('tests',)),\n include_package_data=True,\n version=version_ns['__version__'],\n license='MIT',\n description='Data cleaning and ETL utilities.',\n url='https://github.com/portfoliome/foil',\n author='Philip Martin',\n author_email='philip.martin@censible.co',\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Developers',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Topic :: Utilities',\n ],\n keywords='ETL finance generators processing',\n install_requires=get_requirements('requirements.txt'),\n extras_require={\n 'develop': get_requirements('requirements-dev.txt'),\n 'test': get_requirements('requirements-test.txt')\n },\n zip_safe=False)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"637654522","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport gettext\nimport os\nimport sys\n\nimport werkzeug\nimport werkzeug.routing\nimport jinja2\n\nimport hatta.error\nimport hatta.page\nimport hatta.search\nimport hatta.storage\nimport hatta.views\nimport hatta.request\nimport hatta.response\n\n\nclass WikiTitleConverter(werkzeug.routing.PathConverter):\n \"\"\"Behaves like the path converter, but doesn't match the \"+ pages\".\"\"\"\n\n def to_url(self, value):\n return werkzeug.url_quote(value.strip(), self.map.charset, safe=\"/\")\n\n regex = '([^+%]|%[^2]|%2[^Bb]).*'\n\n\nclass WikiAllConverter(werkzeug.routing.BaseConverter):\n \"\"\"Matches everything.\"\"\"\n\n regex = '.*'\n\n\ndef init_gettext(language):\n if language is not None:\n try:\n translation = gettext.translation(\n 'hatta',\n 'locale',\n languages=[language],\n )\n except IOError:\n translation = gettext.translation(\n 'hatta',\n fallback=True,\n languages=[language],\n )\n else:\n translation = gettext.translation('hatta', fallback=True)\n return translation\n\n\ndef init_template(translation):\n template_env = jinja2.Environment(\n extensions=['jinja2.ext.i18n'],\n loader=jinja2.PackageLoader('hatta', 'templates'),\n )\n template_env.autoescape = True\n template_env.install_gettext_translations(translation, True)\n return template_env\n\n\nclass Wiki(object):\n \"\"\"\n The main class of the wiki, handling initialization of the whole\n application and most of the logic.\n \"\"\"\n storage_class = hatta.storage.WikiStorage\n index_class = hatta.search.WikiSearch\n filename_map = hatta.page.filename_map\n mime_map = hatta.page.mime_map\n\n def __init__(self, config):\n if config.get_bool('show_version', False):\n sys.stdout.write(\"Hatta %s\\n\" % hatta.__version__)\n sys.exit()\n self.dead = False\n self.config = config\n\n self.language = config.get('language')\n translation = init_gettext(self.language)\n self.gettext = translation.ugettext\n self.template_env = init_template(translation)\n self.path = os.path.abspath(config.get('pages_path', 'docs'))\n self.repo_path = config.get('repo_path')\n self.page_charset = config.get('page_charset', 'utf-8')\n self.menu_page = self.config.get('menu_page', u'Menu')\n self.front_page = self.config.get('front_page', u'Home')\n self.logo_page = self.config.get('logo_page', u'logo.png')\n self.locked_page = self.config.get('locked_page', u'Locked')\n self.site_name = self.config.get('site_name', u'Hatta Wiki')\n self.read_only = self.config.get_bool('read_only', False)\n self.fallback_url = self.config.get('fallback_url')\n self.icon_page = self.config.get('icon_page')\n self.alias_page = self.config.get('alias_page', 'Alias')\n self.help_page = self.config.get('help_page', 'Help')\n self.math_url = self.config.get(\n 'math_url',\n 'http://www.mathtran.org/cgi-bin/mathtran?tex=',\n )\n self.pygments_style = self.config.get('pygments_style', 'tango')\n self.extension = self.config.get('extension')\n self.unix_eol = self.config.get_bool('unix_eol', False)\n self.recaptcha_public_key = self.config.get('recaptcha_public_key')\n self.recaptcha_private_key = self.config.get('recaptcha_private_key')\n self.subdirectories = self.config.get_bool('subdirectories', False)\n if self.subdirectories:\n self.storage_class = hatta.storage.WikiSubdirectoryStorage\n self.storage = self.storage_class(\n self.path,\n self.page_charset,\n self.gettext,\n self.unix_eol,\n self.extension,\n self.repo_path,\n )\n self.repo_path = self.storage.repo_path\n self.cache = os.path.abspath(\n config.get(\n 'cache_path',\n os.path.join(self.repo_path, '.hg', 'hatta', 'cache'),\n )\n )\n self.index = self.index_class(self.cache, self.language, self.storage)\n self.index.update(self)\n self.url_rules = hatta.views.URL.get_rules()\n self.views = hatta.views.URL.get_views()\n self.url_converters = {\n 'title': WikiTitleConverter,\n 'all': WikiAllConverter,\n }\n self.url_map = werkzeug.routing.Map(\n self.url_rules,\n converters=self.url_converters,\n )\n\n def add_url_rule(self, rule, name, func):\n \"\"\"Let plugins add additional url rules.\"\"\"\n\n self.url_rules.append(rule)\n self.views[name] = func\n self.url_map = werkzeug.routing.Map(\n self.url_rules,\n converters=self.url_converters,\n )\n\n @werkzeug.responder\n def application(self, environ, start):\n \"\"\"The main application loop.\"\"\"\n\n adapter = self.url_map.bind_to_environ(environ)\n request = hatta.request.WikiRequest(self, adapter, environ)\n try:\n endpoint, values = adapter.match()\n view = self.views[endpoint]\n return view(request, **values)\n except werkzeug.exceptions.HTTPException as err:\n return err\n\n","sub_path":"support/hatta/wiki.py","file_name":"wiki.py","file_ext":"py","file_size_in_byte":5346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"10376684","text":"import core.decorators\nfrom core.sql.db_connect import Connection\nfrom core.sql.commands_sql import SQL_List\n\n@core.decorators.admin.init\ndef init(update, context):\n connector = Connection()\n query = SQL_List.SQL\n connector.cur.execute(query)\n rows = connector.cur.fetchall()\n string = \"\"\n for link in rows:\n string += f\"ID {link[0]}: {link[2]}\\n\"\n message = \"GIVEAWAY LIST:\"\n update.effective_message.reply_html(message + \"\\n\\nParticipants List:\\n\" + string)","sub_path":"core/commands/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"302662133","text":"import ScanModule\nimport AccessModule\nimport sqlite3 as sqlite\nimport re\n\nModule = { \n \"name\": \"Filecontent Scanner\",\n \"version\": \"0.1\",\n \"class\": \"FilecontentModule\"\n}\n\nclass FilecontentModule(ScanModule.ScanModule):\n def runScan(self, accessModule):\n assert(isinstance(accessModule, AccessModule.AccessModule))\n \n results = []\n cursor = self.conn.cursor()\n \n cursor.execute(\"\"\"SELECT filepattern, contentpattern, description, severity, paths FROM filecontent\"\"\")\n data = cursor.fetchall()\n \n for d in data:\n if (d[4] == None) or (d[4] == \"\"): \n paths = [\"/\"]\n else:\n paths = d[4].split(\";\")\n \n for p in paths:\n result = accessModule.findFile(d[0], p)\n if len(result) > 0:\n compiledpattern = re.compile(d[1])\n for r in result:\n rfile = accessModule.openFile(r, \"r\")\n if (rfile == None):\n continue\n \n with rfile as f: \n line = f.readline()\n while (line != \"\"):\n if re.match(compiledpattern, line):\n results.append(ScanModule.ScanResult(r, d[2], d[3]))\n break\n line = f.readline()\n \n return results\n \n def __init__(self):\n self.conn = sqlite.connect(\"filecontent.db\")\n pass","sub_path":"modules/ScanFilecontent.py","file_name":"ScanFilecontent.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"559618983","text":"from __future__ import unicode_literals\nfrom django.core.validators import MinValueValidator, MaxValueValidator\nfrom django.db import models\nfrom datetime import date\nfrom extras.models import Partner, Contact\nfrom generic.models import Platform\nfrom asset.models import Title\nfrom extras.models import FExchange\nfrom generic.models import Contract_Type\nfrom djmoney.models.fields import MoneyField\nfrom django.dispatch import receiver\nfrom django.db.models.signals import post_save\n# Create your models here.\n\nclass IPRight( models.Model ):\n def get_autogenerated_code():\n last_id = IPRight.objects.values('id').order_by('id').last()\n if not last_id:\n return \"RIGHT-\"+str(1)\n return \"RIGHT-\"+str(last_id['id'])\n\n right_type_option = (\n ('Both','Exclusive & Non Exclusive'),\n ('Excl','Exclusive'),\n ('NExc','Non Exclusive')\n )\n code = models.CharField( max_length = 20, default=get_autogenerated_code, editable=False)\n entity = models.CharField( max_length = 100, blank=False )\n right_type = models.CharField( max_length = 30, choices=right_type_option, default='Both', null=False, blank=False)\n exclusivity = models.CharField( max_length=100, blank=False, default=\"None\" )\n inclusivity = models.CharField( max_length=100, blank=False, default=\"All\" )\n\n def __str__(self):\n return \"%s\" % (self.code)\n\n class Meta:\n verbose_name = \"IP Right\"\n\n\nclass IPRightGroup (models.Model):\n def get_autogenerated_code():\n last_id = IPRightGroup.objects.values('id').order_by('id').last()\n if not last_id:\n return \"RGRP-\"+str(1)\n return \"RGRP-\"+str(last_id['id'])\n code = models.CharField( max_length = 20, default=get_autogenerated_code, editable=False)\n ip_right = models.ManyToManyField( IPRight, blank=False, null=False )\n\n def __str__(self):\n return \"%s\" % (self.code)\n\n class Meta:\n verbose_name = \"IP Rights Group\"\n\n\nclass Contract(models.Model):\n def get_autogenerated_code():\n last_id = Contract.objects.values('id').order_by('id').last()\n if not last_id:\n return \"CT/\" + str(1)\n return \"CT/\" + str(last_id['id'])\n code = models.CharField(max_length=10, default=get_autogenerated_code, editable=False, blank=False)\n nature = models.ForeignKey(Contract_Type, null=True, blank=False, verbose_name=\"Contract Nature\", on_delete=models.CASCADE)\n sign_date = models.DateField(blank = False, default = date.today, verbose_name=\"Sign Date\")\n start_date = models.DateField(blank = False, default = date.today, verbose_name=\"Start Date\")\n end_date = models.DateField(blank = False, default = date.today, verbose_name=\"End Date\")\n perpetual = models.BooleanField( default = False, blank = False )\n rights_group = models.ForeignKey( IPRightGroup, null=True, on_delete=models.CASCADE, related_name = \"contract_associated_ip_rights_group\")\n notes = models.TextField(blank=True, max_length=250, default=None)\n attach = models.FileField(blank=True)\n contract_status_option = (\n ('Active', 'Active'),\n ('Inactive', 'Inactive'),\n ('Draft', 'Draft'),\n )\n contract_status = models.CharField(max_length=15, choices=contract_status_option, default='Draft', null=False, blank=False )\n\n def __str__(self):\n return self.code\n\n class Meta:\n verbose_name = \"Contract\"\n verbose_name_plural = \"Contract\"\n\nclass Contract_Signatories(models.Model):\n def get_autogenerated_code():\n last_id = Contract_Signatories.objects.values('id').order_by('id').last()\n if not last_id:\n return \"CT/SG/\" + str(1)\n return \"CT/SG/\" + str(last_id['id'])\n code = models.CharField(max_length=8, default=get_autogenerated_code, editable=False, blank=False)\n partner = models.ForeignKey(Partner, on_delete=models.CASCADE)\n contract = models.ForeignKey(Contract, on_delete=models.CASCADE)\n rev_percentage = models.IntegerField(default=0, verbose_name='Revenue Percentage', validators = [MinValueValidator(0), MaxValueValidator(100)] )\n contact = models.ForeignKey(Contact, on_delete=models.CASCADE)\n signer = models.TextField(default='', verbose_name=\"Signer Information\", max_length=50, blank=True)\n\n def __str__(self):\n return self.code\n\n class Meta:\n verbose_name = \"Contract Signatory\"\n verbose_name_plural = \"Contract Signatories\"\n\n\n\n# Create your models here.\nclass Earning(models.Model):\n def get_autogenerated_code():\n last_fxchange_id = Earning.objects.values('id').order_by('id').last()\n if not last_fxchange_id:\n return \"GR/ERN-\"+str(1)\n return \"GR/ERN-\"+str(last_fxchange_id['id'])\n code = models.CharField( max_length = 20, default=get_autogenerated_code, editable=False)\n title_id = models.ForeignKey(Title, null=False, on_delete =models.CASCADE, related_name=\"earning_for_title\")\n platform_id = models.ForeignKey(Platform, null=False, on_delete =models.CASCADE, related_name=\"earning_from_platform_for_title\")\n contract = models.ForeignKey( Contract, null=False, on_delete=models.CASCADE, related_name=\"earning_for_contract\")\n month = models.DateField( blank = False, default= date.today, verbose_name=\"Earning For Month\")\n revenue = MoneyField(max_digits=10, decimal_places=2,verbose_name=\"Gross Revenue\", default_currency= \"USD\")\n currency = models.ForeignKey(FExchange, null=False, on_delete =models.CASCADE, related_name=\"earning_in_currency\" )\n\n def __str__ (self):\n return \"%s\" % (self.code)\n\n class Meta:\n verbose_name=\"Earning\"\n verbose_name_plural = \"Earnings\"\n unique_together = ('title_id', 'platform_id', 'month','contract')\n\n\nclass EarningSplit( models.Model ):\n def get_autogenerated_code():\n last_id = EarningSplit.objects.values('id').order_by('id').last()\n if not last_id:\n return \"ERN/SPLIT-\"+str(1)\n return \"ERN/SPLIT-\"+str(last_id['id'])\n code = models.CharField( max_length = 20, default=get_autogenerated_code, editable=False)\n earning_ref = models.ForeignKey( Earning, null=False, on_delete=models.CASCADE, related_name=\"earning_correspondence\" )\n partner = models.ForeignKey( Partner, null=False, on_delete=models.CASCADE, related_name=\"earning_split_for_partner\" )\n calculated_revenue_usd = models.FloatField( null=False, blank=False, default=0.0 )\n\n def __str__ (self):\n return \"%s\" % (self.code)\n\n class Meta:\n verbose_name=\"Earning Split\"\n verbose_name_plural = \"Earning Splits\"\n unique_together = ('earning_ref', 'partner')\n\n\n\n\nclass Distribution(models.Model):\n def get_autogenerated_code():\n last_id = Distribution.objects.values('id').order_by('id').last()\n if not last_id:\n return \"DSTR-\"+str(1)\n return \"DSTR-\"+str(last_id['id'])\n code = models.CharField( max_length = 20, default=get_autogenerated_code, editable=False)\n contract = models.ForeignKey( Contract, null=False, blank=False, related_name=\"distributed_under_contract\", on_delete=models.CASCADE)\n platform = models.ForeignKey(Platform, null=False, related_name=\"distributed_on_platform\", on_delete= models.CASCADE)\n title = models.ForeignKey(Title, null=False, related_name=\"this_title_distributed\", on_delete=models.CASCADE)\n remark = models.TextField(max_length = 50, blank= True)\n distributed_on = models.DateField(default=date.today, blank=False)\n\n def __str__ (self):\n return \"%s\" % (self.code)\n\n class Meta:\n verbose_name = \"Distribution\"\n verbose_name_plural = \"Distributions\"\n\n\n\n@receiver(post_save, sender = Earning)\ndef SplitEarningsSignal(sender, instance, created, **kwargs):\n cso = Contract_Signatories.objects.filter(contract=instance.contract)\n for j in cso:\n grossRevenue, partnr = (instance.revenue*j.rev_percentage)/100, j.partner\n if created:\n EarningSplit.objects.create(calculated_revenue_usd=grossRevenue, partner = partnr, earning_ref=instance)\n\n","sub_path":"cfms/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"84603320","text":"class Solution(object):\n def containsNearbyDuplicate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n if nums is None or len(nums) == 0:\n return False\n\n import collections\n hashmap = collections.defaultdict(int)\n\n for i, v in enumerate(nums):\n if v in hashmap and i - hashmap[v] <= k:\n return True\n hashmap[v] = i\n\n return False\n\nclass Solution(object):\n def containsNearbyDuplicate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n if nums is None or len(nums) == 0:\n return False\n\n hash = {}\n for i in xrange(len(nums)):\n if nums[i] not in hash:\n hash[nums[i]] = [i]\n else:\n hash[nums[i]].append(i)\n\n for key, item in hash.iteritems():\n if len(item) > 1:\n for i in xrange(1, len(item)):\n if abs(item[i] - item[i-1]) <= k:\n return True\n\n return False\n","sub_path":"python/219. Contains Duplicate II.py","file_name":"219. Contains Duplicate II.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"555131192","text":"from flask import render_template, Flask\nfrom config import config\nfrom app.models import db\nfrom app.cache import cache\nfrom app.mod_home.views import mod_home as home_module\nfrom app.mod_detail.views import mod_detail as detail_module\n\n\ndef create_app(config_name):\n # Define the WSGI application object\n app = Flask(__name__, template_folder='templates', static_folder='static', instance_relative_config=True)\n\n # flask cache\n cache.init_app(app, config={'CACHE_TYPE': 'simple'})\n\n # configurations\n try:\n app.config.from_object(config[config_name])\n app.config.from_pyfile('config.py')\n except IOError:\n app.config.from_object(config[config_name])\n\n config[config_name].init_app(app)\n\n # initialize tha db\n db.init_app(app)\n\n # setup the error handlers and register blueprints\n error_handlers(app)\n register_blueprints(app)\n\n return app\n\n\ndef error_handlers(app):\n \"\"\"\n Sets up the error handlers for the application\n :param app: the flask app instance\n :return:\n \"\"\"\n # Error handler for page not found\n @app.errorhandler(404)\n def not_found(error):\n return render_template('404.html'), 404\n\n @app.errorhandler(403)\n def error_403(error):\n return render_template(\"403.html\"), 403\n\n @app.errorhandler(500)\n def error_500(error):\n return render_template(\"500.html\"), 500\n\n\ndef register_blueprints(app):\n \"\"\"\n Registers the application blueprints\n Register blueprint(s) ALL blueprints will be registered here\n :param app:\n :return:\n \"\"\"\n app.register_blueprint(home_module)\n app.register_blueprint(detail_module)","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"344708193","text":"from django.dispatch import Signal\n\ntransaction_started = Signal()\ntransaction_started.__doc__ = \"\"\"\nSent after order was started (awaiting payment)\n\"\"\"\n\ntransaction_was_successful = Signal(providing_args=['invoice'])\ntransaction_was_successful.__doc__ = \"\"\"\nSent after order was completed (product, account,order)\n\"\"\"\n\n\ntransaction_was_unsuccessful = Signal(providing_args=['invoice'])\ntransaction_was_unsuccessful.__doc__ = \"\"\"\nSent after order was returned (product, account,order)\n\"\"\"\n\norder_canceled = Signal(providing_args=['invoice'])\norder_canceled.__doc__ = \"\"\"\nSent after order was canceled (product, account,order)\n\"\"\"\n\n\norder_novalid = Signal(providing_args=['product','user','instance'])\norder_novalid.__doc__ = \"\"\"\nSent after order was canceled (product, account,order)\n\"\"\"\n\n\n\n","sub_path":"billing/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"47714739","text":"#!/usr/bin/env python3\n\n#Copyright 2011-16 Newcastle University\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport datetime\nimport os\nimport io\nimport sys\nimport traceback\nimport shutil\nfrom optparse import OptionParser\nimport examparser\nfrom exam import Exam,ExamError\nimport xml2js\nfrom zipfile import ZipFile, ZipInfo\nimport xml.etree.ElementTree as etree\nfrom itertools import count\nimport subprocess\nimport json\nimport jinja2\n\n\nnamespaces = {\n '': 'http://www.imsglobal.org/xsd/imscp_v1p1',\n 'xsi': 'http://www.w3.org/2001/XMLSchema-instance',\n 'adlcp': 'http://www.adlnet.org/xsd/adlcp_v1p3',\n 'adlseq': 'http://www.adlnet.org/xsd/adlseq_v1p3',\n 'adlnav': 'http://www.adlnet.org/xsd/adlnav_v1p3',\n 'imsss': 'http://www.imsglobal.org/xsd/imsss',\n}\n\n# because pre-py3.2 versions of etree always put a colon in front of tag names\n# from http://stackoverflow.com/questions/8113296/supressing-namespace-prefixes-in-elementtree-1-2\nif etree.VERSION[0:3] == '1.2':\n #in etree < 1.3, this is a workaround for supressing prefixes\n\n def fixtag(tag, namespaces):\n import string\n # given a decorated tag (of the form {uri}tag), return prefixed\n # tag and namespace declaration, if any\n if isinstance(tag, etree.QName):\n tag = tag.text\n namespace_uri, tag = tag[1:].split(\"}\", 1)\n prefix = namespaces.get(namespace_uri)\n if namespace_uri not in namespaces:\n prefix = etree._namespace_map.get(namespace_uri)\n if namespace_uri not in etree._namespace_map:\n prefix = \"ns%d\" % len(namespaces)\n namespaces[namespace_uri] = prefix\n if prefix == \"xml\":\n xmlns = None\n else:\n if prefix is not None:\n nsprefix = ':' + prefix\n else:\n nsprefix = ''\n xmlns = (\"xmlns%s\" % nsprefix, namespace_uri)\n else:\n xmlns = None\n if prefix is not None:\n prefix += \":\"\n else:\n prefix = ''\n\n return \"%s%s\" % (prefix, tag), xmlns\n\n etree.fixtag = fixtag\n for ns,url in namespaces.items():\n etree._namespace_map[url] = ns if len(ns) else None\nelse:\n #For etree > 1.3, use register_namespace function\n for ns,url in namespaces.items():\n try:\n etree.register_namespace(ns,url) \n except AttributeError:\n etree._namespace_map[url]=ns\n\n\ntry:\n basestring\nexcept NameError:\n basestring = str\n\ndef realFile(file):\n \"\"\"\n Filter out temporary files created by vim\n \"\"\"\n return not (file[-1]=='~' or file[-4:]=='.swp')\n\n\n\nclass NumbasCompiler(object):\n def __init__(self,options):\n self.options = options\n self.get_themepaths()\n\n def get_themepaths(self):\n self.themepaths = [self.options.theme]\n for theme,i in zip(self.themepaths,count()):\n theme = self.themepaths[i] = self.get_theme_path(theme)\n inherit_file = os.path.join(theme,'inherit.txt')\n if os.path.exists(inherit_file):\n self.themepaths += open(inherit_file).read().splitlines()\n\n self.themepaths.reverse()\n\n def get_theme_path(self,theme):\n if os.path.exists(theme):\n return theme\n else:\n ntheme = os.path.join(self.options.path,'themes',theme)\n if os.path.exists(ntheme):\n return ntheme\n else:\n raise Exception(\"Couldn't find theme %s\" % theme)\n\n def compile(self):\n self.parse_exam()\n\n files = self.files = self.collect_files()\n\n self.render_templates()\n\n self.make_xml()\n files[os.path.join('.','settings.js')] = io.StringIO(self.xmls)\n\n self.make_locale_file()\n\n if self.options.scorm:\n self.add_scorm()\n\n self.collect_stylesheets()\n self.collect_scripts()\n\n if self.options.minify:\n self.minify()\n \n if self.options.zip:\n self.compileToZip()\n else:\n self.compileToDir()\n\n def parse_exam(self):\n \"\"\"\n Parse an exam definition from the given source\n \"\"\"\n try:\n self.exam = Exam.fromstring(self.options.source)\n self.examXML = self.exam.tostring()\n self.resources = self.exam.resources\n self.extensions = self.exam.extensions\n except ExamError as err:\n raise Exception('Error constructing exam:\\n%s' % err)\n except examparser.ParseError as err:\n raise Exception(\"Failed to compile exam due to parsing error.\\n%s\" % err)\n except:\n raise Exception('Failed to compile exam.')\n\n def collect_files(self,dirs=[('runtime','.')]):\n \"\"\"\n Collect files from the given directories to be included in the compiled package\n \"\"\"\n resources = [x if isinstance(x,list) else [x,x] for x in self.resources]\n\n for name,path in resources:\n if os.path.isdir(path):\n dirs.append((os.path.join(self.options.path,path),os.path.join('resources',name)))\n\n extensions = [os.path.join(self.options.path,'extensions',x) for x in self.extensions]\n extfiles = []\n for x in extensions:\n if os.path.isdir(x):\n extfiles.append((os.path.join(os.getcwd(),x),os.path.join('extensions',os.path.split(x)[1])))\n else:\n raise Exception(\"Extension {} not found\".format(x))\n dirs += extfiles\n\n for themepath in self.themepaths:\n dirs.append((os.path.join(themepath,'files'),'.'))\n\n files = {}\n for (src,dst) in dirs:\n src = os.path.join(self.options.path,src)\n for x in os.walk(src, followlinks=self.options.followlinks):\n xsrc = x[0]\n xdst = x[0].replace(src,dst,1)\n for y in filter(realFile,x[2]):\n files[os.path.join(xdst,y)] = os.path.join(xsrc,y) \n\n for name,path in resources:\n if not os.path.isdir(path):\n files[os.path.join('resources',name)] = os.path.join(self.options.path,path)\n \n return files\n\n def make_xml(self):\n \"\"\"\n Write the javascript representation of the XML files (theme XSLT and exam XML)\n \"\"\"\n xslts = {}\n for themedir in self.themepaths:\n xsltdir = os.path.join(themedir,'xslt')\n\n if os.path.exists(xsltdir):\n files = filter(lambda x: x[-5:]=='.xslt', os.listdir(xsltdir))\n for file in files:\n name, ext = os.path.splitext(file)\n xslts[name] = xml2js.encode(open(os.path.join(xsltdir,file),encoding='utf-8').read())\n\n if 'question' not in xslts and self.question_xslt is not None:\n xslts['question'] = xml2js.encode(self.question_xslt)\n\n xslts_js = ',\\n\\t\\t'.join('{}: \"{}\"'.format(name,body) for name,body in xslts.items())\n\n extensionfiles = []\n for extension in self.extensions:\n name = os.path.split(extension)[1]\n if os.path.exists(os.path.join(extension,name+'.js')):\n extensionfiles.append('extensions/'+name+'/'+name+'.js')\n\n self.xmls = xml2js.rawxml_js_template.format(**{\n 'extensionfiles': str(extensionfiles),\n 'templates': xslts_js,\n 'examXML': xml2js.encode(self.examXML),\n })\n\n def render_templates(self):\n \"\"\"\n Render index.html using the theme templates\n \"\"\"\n template_paths = [os.path.join(path,'templates') for path in self.themepaths]\n template_paths.reverse()\n\n self.template_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(template_paths))\n index_dest = os.path.join('.','index.html')\n if index_dest not in self.files:\n index_html = self.render_template('index.html')\n if index_html:\n self.files[index_dest] = io.StringIO(index_html)\n self.question_xslt = self.render_template('question.xslt')\n\n def render_template(self,name):\n try:\n template = self.template_environment.get_template(name)\n output = template.render({'exam': self.exam,'options': self.options})\n return output\n except jinja2.exceptions.TemplateNotFound:\n return None\n\n def make_locale_file(self):\n \"\"\"\n Make locale.js using the selected locale file\n \"\"\"\n localePath = os.path.join(self.options.path,'locales')\n locales = {}\n for fname in os.listdir(localePath):\n name,ext = os.path.splitext(fname)\n if ext.lower()=='.json':\n with open(os.path.join(localePath,fname),encoding='utf-8') as f:\n locales[name.lower()] = {'translation': json.loads(f.read())}\n\n locale_js_template = \"\"\"\n Numbas.queueScript('localisation-resources',['i18next'],function() {{\n Numbas.locale = {{\n preferred_locale: {},\n resources: {}\n }}\n }});\n \"\"\"\n locale_js = locale_js_template.format(json.dumps(self.options.locale),json.dumps(locales))\n\n self.files[os.path.join('.','locale.js')] = io.StringIO(locale_js)\n\n def add_scorm(self):\n \"\"\"\n Add the necessary files for the SCORM protocol to the package\n \"\"\"\n\n self.files.update(self.collect_files([('scormfiles','.')]))\n\n IMSprefix = '{http://www.imsglobal.org/xsd/imscp_v1p1}'\n manifest = etree.fromstring(open(os.path.join(self.options.path,'scormfiles','imsmanifest.xml')).read())\n manifest.attrib['identifier'] = 'Numbas: %s' % self.exam.name\n manifest.find('%sorganizations/%sorganization/%stitle' % (IMSprefix,IMSprefix,IMSprefix)).text = self.exam.name\n def to_relative_url(path):\n path = os.path.normpath(path)\n bits = []\n head,tail=os.path.split(path)\n while head!='':\n bits.insert(0,tail)\n head,tail=os.path.split(head)\n bits.insert(0,tail)\n return '/'.join(bits)\n\n resource_files = [to_relative_url(x) for x in self.files.keys()]\n\n resource_element = manifest.find('%sresources/%sresource' % (IMSprefix,IMSprefix))\n for filename in resource_files:\n file_element = etree.Element('file')\n file_element.attrib = {'href': filename}\n resource_element.append(file_element)\n\n manifest_string = etree.tostring(manifest)\n try:\n manifest_string = manifest_string.decode('utf-8')\n except AttributeError:\n pass\n\n self.files[os.path.join('.','imsmanifest.xml')] = io.StringIO(manifest_string)\n\n def collect_stylesheets(self):\n \"\"\"\n Collect together all CSS files and compile them into a single file, styles.css\n \"\"\"\n stylesheets = [(dst,src) for dst,src in self.files.items() if os.path.splitext(dst)[1]=='.css']\n stylesheets.sort(key=lambda x:x[0])\n for dst,src in stylesheets:\n del self.files[dst]\n stylesheets = [src for dst,src in stylesheets]\n stylesheets = '\\n'.join(open(src,encoding='utf-8').read() if isinstance(src,basestring) else src.read() for src in stylesheets)\n self.files[os.path.join('.','styles.css')] = io.StringIO(stylesheets)\n\n def collect_scripts(self):\n \"\"\"\n Collect together all Javascript files and compile them into a single file, scripts.js\n \"\"\"\n javascripts = [(dst,src) for dst,src in self.files.items() if os.path.splitext(dst)[1]=='.js']\n for dst,src in javascripts:\n del self.files[dst]\n\n javascripts.sort(key=lambda x:x[0])\n\n javascripts = [src for dst,src in javascripts]\n numbas_loader_path = os.path.join(self.options.path,'runtime','scripts','numbas.js')\n javascripts.remove(numbas_loader_path)\n\n javascripts.insert(0,numbas_loader_path)\n javascripts = '\\n'.join(open(src,encoding='utf-8').read() if isinstance(src,basestring) else src.read() for src in javascripts)\n self.files[os.path.join('.','scripts.js')] = io.StringIO(javascripts)\n\n\n def minify(self):\n \"\"\"\n Minify all javascript files in the package\n \"\"\"\n for dst,src in self.files.items():\n if isinstance(src,basestring) and os.path.splitext(dst)[1] == '.js':\n p = subprocess.Popen([self.options.minify,src],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)\n out,err = p.communicate()\n code = p.poll()\n if code != 0:\n raise Exception('Failed to minify %s with minifier %s' % (src,self.options.minify))\n else:\n self.files[dst] = io.StringIO(out.decode('utf-8'))\n\n def compileToZip(self):\n \"\"\" \n Compile the exam as a .zip file\n \"\"\"\n def cleanpath(path):\n if path=='': \n return ''\n dirname, basename = os.path.split(path)\n dirname=cleanpath(dirname)\n if basename!='.':\n dirname = os.path.join(dirname,basename)\n return dirname\n\n f = ZipFile(self.options.output,'w')\n\n for (dst,src) in self.files.items():\n dst = ZipInfo(cleanpath(dst))\n dst.external_attr = 0o644<<16\n dst.date_time = datetime.datetime.today().timetuple()\n if isinstance(src,basestring):\n f.writestr(dst,open(src,'rb').read())\n else:\n f.writestr(dst,src.read())\n\n print(\"Exam created in %s\" % os.path.relpath(self.options.output))\n\n f.close()\n\n def compileToDir(self):\n \"\"\"\n Compile the exam as a directory on the filesystem\n \"\"\"\n if self.options.action == 'clean':\n try:\n shutil.rmtree(self.options.output)\n except OSError:\n pass\n try:\n os.mkdir(self.options.output)\n except OSError:\n pass\n \n def makepath(path): #make sure directory hierarchy of path exists by recursively creating directories\n dir = os.path.dirname(path)\n if not os.path.exists(dir):\n makepath(dir)\n try:\n os.mkdir(dir)\n except OSError:\n pass\n\n for (dst,src) in self.files.items():\n dst = os.path.join(self.options.output,dst)\n makepath(dst)\n if isinstance(src,basestring):\n if self.options.action=='clean' or not os.path.exists(dst) or os.path.getmtime(src)>os.path.getmtime(dst):\n shutil.copyfile(src,dst)\n else:\n shutil.copyfileobj(src,open(dst,'w',encoding='utf-8'))\n \n print(\"Exam created in %s\" % os.path.relpath(self.options.output))\n\ndef run():\n parser = OptionParser(usage=\"usage: %prog [options] source\")\n parser.add_option('-t','--theme',\n dest='theme',\n action='store',\n type='string',\n default='default',\n help='Path to the theme to use'\n )\n parser.add_option('-f','--followlinks',\n dest='followlinks',\n action='store_true',\n default=False,\n help='Whether to follow symbolic links in the theme directories'\n )\n parser.add_option('-u','--update',\n dest='action',\n action='store_const',\n const='update',\n default='update',\n help='Update an existing exam.'\n )\n parser.add_option('-c','--clean',\n dest='action',\n action='store_const',\n const='clean',\n help='Start afresh, deleting any existing exam in the target path'\n )\n parser.add_option('-z','--zip',\n dest = 'zip',\n action='store_true',\n default=False,\n help='Create a zip file instead of a directory'\n )\n parser.add_option('-s','--scorm',\n dest='scorm',\n action='store_true',\n default=False,\n help='Include the files necessary to make a SCORM package'\n )\n parser.add_option('-p','--path',\n dest='path',\n default=os.getcwd(),\n help='The path to the Numbas files'\n )\n parser.add_option('-o','--output',\n dest='output',\n help='The target path'\n )\n parser.add_option('--pipein',\n dest='pipein',\n action='store_true',\n default=False,\n help=\"Read .exam from stdin\")\n parser.add_option('-l','--language',\n dest='locale',\n default='en-GB',\n help='Language (ISO language code) to use when displaying text')\n parser.add_option('--minify',\n dest='minify',\n default='',\n help='Path to Javascript minifier. If not given, no minification is performed.')\n\n (options,args) = parser.parse_args()\n\n if options.pipein:\n options.source = sys.stdin.detach().read().decode('utf-8')\n if not options.output:\n options.output = os.path.join(path,'output','exam')\n else:\n try:\n source_path = args[0]\n except IndexError:\n parser.print_help()\n return\n\n if not os.path.exists(source_path):\n osource = source_path\n source_path = os.path.join(path,source_path)\n if not os.path.exists(source_path):\n print(\"Couldn't find source file %s\" % osource)\n exit(1)\n options.source=open(source_path,encoding='utf-8').read()\n\n if not options.output:\n output = os.path.basename(os.path.splitext(source_path)[0])\n if options.zip:\n output += '.zip'\n options.output=os.path.join(path,'output',output)\n \n\n try:\n compiler = NumbasCompiler(options)\n compiler.compile()\n except Exception as err:\n sys.stderr.write(str(err)+'\\n')\n _,_,exc_traceback = sys.exc_info()\n traceback.print_exc()\n exit(1)\n\nif __name__ == '__main__':\n run()\n\n","sub_path":"bin/numbas.py","file_name":"numbas.py","file_ext":"py","file_size_in_byte":19426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"5911818","text":"#!/usr/bin/env\n# -*- coding: utf-8 -*-\n# Copyright (C) Victor M. Mendiola Lau - All Rights Reserved\n# Unauthorized copying of this file, via any medium is strictly prohibited\n# Proprietary and confidential\n# Written by Victor M. Mendiola Lau , February 2017\n\nimport pylab\nfrom datasets.nir_tablets import load_nir_tablets\n\n# ---------------------------------------------------------------\n\n\ndef plot_nir_tablets_data_set():\n # loading the nir tablets data set\n ds = load_nir_tablets()\n\n # removing columns associated with classes and properties\n ds = ds.iloc[:, :-3]\n\n # plotting the data set\n ds.T.plot(legend=None)\n pylab.show()\n\n\ndef plot_nir_tablets_class1_subset():\n # loading the nir tablets data set\n ds = load_nir_tablets()\n\n # getting samples of class1\n ds_class1 = ds.loc[ds['Type'] == 1]\n\n # removing columns associated with classes and properties\n ds_class1 = ds_class1.iloc[:, :-3]\n\n # getting the subset (getting the 1/4 of the data set)\n ub_rows = int(ds_class1.shape[0] / 7)\n ds_class1 = ds_class1.iloc[:ub_rows, :]\n\n # plotting the data set\n ds_class1.T.plot()\n pylab.show()\n","sub_path":"datasets/nir_tablets/demos.py","file_name":"demos.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"8861755","text":"#!/usr/bin/python3.6/p4_23.py\n\n\"\"\"Exercise P4.23 Play the game Nim against the computer. Computer plays in\none of two modes: basic (preferred word over pejorative 'stupid') or advanced\n(also preferred word), chosen at random. The loser of the game is the player\nwho picks the last marble from the current pile.\n\"\"\"\n\nfrom random import randint\n\n\nprint(\"Welcome to the Nim game.\")\nresponse = input(\"Welcome to the Nim game. Press \\\"s\\\" to start (or \\\"q\\\" to quit): \").upper()\n\nif response == 'Q':\n exit(\"Goodbye. Come back soon.\")\nelif response == 'S':\n pile = randint(10, 100)\n print(\"Let the game begin. The starting pile size is \", pile)\n\n\n MIN_PULL = 1\n max_pull = ( pile // 2 )\n\n player_pull = 0\n computer_pull = 0\n turn_ctr = 0\n\n # Sets the computer mode to basic(0) or advanced(1)\n mode = randint(0, 1)\n print(mode)\n\n if mode == 0:\n print(\"Computer will be playing in basic mode.\")\n elif mode ==1:\n print(\"Computer will be playing in advanced mode.\")\n\n # Determines whether computer goes first (0) or player (1)\n first_turn = randint(0, 1)\n print(\"first turn is..\", first_turn)\n\n if first_turn == 0:\n print(\"Computer gets first turn to pull from the starting pile of\", pile, \"marbles.\")\n if mode == 0:\n computer_pull = randint(1, pile // 2)\n pile = pile - computer_pull\n turn_ctr += turn_ctr + 1\n elif mode == 1:\n print(\"To do\")\n # computer_pull = pile -\n else:\n print(\"You get first turn to pull from the starting pile of\", pile, \"marbles.\")\n print(\"You can pick from\", MIN_PULL, \"up to\", max_pull, \"marbles.\")\n player_pull = input(\"How many marbles would you like to take?: \")\n player_pull = int(player_pull)\n pile = pile - player_pull\n print(\"new pile size for next turn is...\", pile)\n","sub_path":"4_assign/p4_23.py","file_name":"p4_23.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"228355454","text":"# ---------------------------------------------------------------------------------------------\n# Copyright (c) Akash Nag. All rights reserved.\n# Licensed under the MIT License. See LICENSE.md in the project root for license information.\n# ---------------------------------------------------------------------------------------------\n\n# This module handles all file related functions\n\nimport ash\nfrom ash.utils import *\nfrom ash.utils.utils import *\n\ndef normalized_path(path):\n\tif(path == None): return None\n\treturn os.path.abspath(os.path.expanduser(path))\n\n# returns the name of the file without its directory\ndef get_file_title(filename):\n\tpos = filename.rfind(\"/\")\n\treturn filename[pos+1:]\n\n# returns a list of directories in dir_list which are under parent_dir\ndef filter_child_directories(parent_dir, dir_list):\n\tfiltered = list()\n\tn = len(parent_dir)\n\tfor d in dir_list:\n\t\tif(d.startswith(parent_dir + \"/\")):\n\t\t\tsd = d[n+1:]\n\t\t\tif(sd.find(\"/\") == -1): filtered.append(d)\n\treturn filtered\n\n# get the file name of a file with respect to project_dir (keeps the project_dir name)\ndef get_relative_file_title(project_dir, filename):\n\tif(filename == None): return \"\"\n\tif(not filename.startswith(project_dir)): return filename\n\tpos = project_dir.rfind(\"/\")\n\tif(pos == 0):\n\t\treturn filename[pos:]\n\telse:\n\t\treturn filename[pos+1:]\n\n# get the file name of a file with respect to project_dir (removes the project_dir name)\ndef get_relative_file_title2(project_dir, filename):\n\tif(filename == None): return \"\"\n\tif(not filename.startswith(project_dir)): return filename\n\tif(project_dir == \"/\"):\n\t\treturn filename[1:]\n\telse:\n\t\treturn filename[len(project_dir)+1:]\n\n# get all sub-directories w.r.t. filename and project_dir\ndef get_relative_subdirectories(project_dir, filename):\t\t# filename must be a file, not a directory\n\trelpath = filename[len(project_dir):]\n\tpos = relpath.rfind(\"/\")\n\tcore = relpath[1:pos+1]\n\tn = len(core)\n\tsubdir_list = list()\n\tfor i in range(n):\n\t\tif(core[i] == \"/\"): subdir_list.append(project_dir + \"/\" + core[0:i])\n\treturn subdir_list\n\ndef is_file_under_directory(dirname, filename):\n\treturn(True if filename.startswith(dirname + \"/\") else False)\n\n# returns a new filename from an existing filename to serve as a copy during Save As...\ndef get_copy_filename(filename):\n\tpos1 = filename.rfind(\"/\")\n\tdir = filename[0:pos1+1]\n\tft = filename[pos1+1:]\n\tpos2 = ft.rfind(\".\")\n\tif(pos2 < 0):\n\t\treturn filename + \"-copy\"\n\telse:\n\t\treturn dir + ft[0:pos2] + \"-copy\" + ft[pos2:]\n\n# predict the encoding of a file\ndef predict_file_encoding(filename, n = 20):\n\tif(not os.path.isfile(filename)): return None\n\tfs = int(os.stat(filename).st_size)\n\tn = min([fs, n])\n\twith open(filename, \"rb\") as f:\n\t\trawdata = b\"\".join([f.readline() for _ in range(n)])\n\tenc = chardet.detect(rawdata)[\"encoding\"]\n\treturn (\"utf-8\" if enc == \"ascii\" else enc)\t\t# assume UTF-8\n\n# returns the size of a filename formatted in units\ndef get_file_size(filename):\n\tif(filename == None): \n\t\treturn None\n\telse:\n\t\tbytes = os.stat(filename).st_size\n\t\tif(bytes < 1000): return str(bytes) + \" bytes\"\n\t\tkb = bytes / 1024\n\t\tif(kb >= 1000):\n\t\t\tmb = kb / 1024\n\t\t\tif(mb >= 1000):\n\t\t\t\tgb = mb / 1024\n\t\t\t\tif(gb >= 1000):\n\t\t\t\t\ttb = gb / 1024\n\t\t\t\t\tif(tb >= 1000):\n\t\t\t\t\t\tpb = tb / 1024\n\t\t\t\t\t\treturn str(round(pb,2)) + \" PB\"\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn str(round(tb,2)) + \" KB\"\n\t\t\t\telse:\n\t\t\t\t\treturn str(round(gb,2)) + \" GB\"\n\t\t\telse:\n\t\t\t\treturn str(round(mb,2)) + \" MB\"\n\t\telse:\n\t\t\treturn str(round(kb,2)) + \" KB\"\n\n# get the mime-type of a file\ndef get_textfile_mimetype(filename):\n\tmt = str(mimetypes.guess_type(filename, strict=False)[0]).lower()\n\tpos = mt.find(\"/\")\n\tif(pos < 0):\n\t\treturn \"unknown\"\n\telse:\n\t\treturn mt[pos+1:]\n\n# checks if a file rests in any of the IGNORED DIRECTORIES or has an extension in IGNORED_FILE_EXTENSIONS\ndef should_ignore_file(filename):\n\tIGNORED_FILE_EXTENSIONS = ash.SETTINGS.get(\"IGNORED_FILE_EXTENSIONS\")\n\tIGNORED_DIRECTORIES = ash.SETTINGS.get(\"IGNORED_DIRECTORIES\")\n\n\tpos = filename.rfind(\".\")\n\tif(os.path.isfile(filename) and pos > -1):\t\t\n\t\text = filename[pos:]\n\t\tif(ext in IGNORED_FILE_EXTENSIONS): return True\n\n\tpositions = get_delim_positions(filename[1:], \"/\")\n\tlast_pos = -1\n\tfor pos in positions:\n\t\tdir = filename[last_pos+1:pos]\n\t\tlast_pos = pos\n\t\tif(dir in IGNORED_DIRECTORIES): return True\n\treturn False\n\n# check if a directory is in any of the IGNORED DIRECTORIES\ndef should_ignore_directory(dirname):\n\tif(get_file_title(dirname) not in ash.SETTINGS.get(\"IGNORED_DIRECTORIES\")):\n\t\treturn False\n\telse:\n\t\treturn True","sub_path":"src/ash/utils/fileUtils.py","file_name":"fileUtils.py","file_ext":"py","file_size_in_byte":4522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"216496995","text":"#\n# MIT License\n#\n# Copyright (c) 2020 Airbyte\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n\n\nimport copy\nfrom typing import Any, List, MutableMapping, Set, Tuple\n\nimport pytest\nfrom airbyte_cdk import AirbyteLogger\nfrom airbyte_cdk.models import AirbyteMessage, ConfiguredAirbyteCatalog, Type\nfrom source_facebook_marketing.source import SourceFacebookMarketing\n\n\n@pytest.fixture(scope=\"session\", name=\"state\")\ndef state_fixture() -> MutableMapping[str, MutableMapping[str, Any]]:\n return {\n \"ads\": {\"updated_time\": \"2021-02-19T10:42:40-0800\"},\n \"ad_sets\": {\"updated_time\": \"2021-02-19T10:42:40-0800\"},\n \"campaigns\": {\"updated_time\": \"2021-02-19T10:42:40-0800\"},\n }\n\n\n@pytest.fixture(scope=\"session\", name=\"state_with_include_deleted\")\ndef state_with_include_deleted_fixture(state):\n result_state = copy.deepcopy(state)\n for state in result_state.values():\n state[\"include_deleted\"] = True\n\n return result_state\n\n\n@pytest.fixture(scope=\"session\", name=\"configured_catalog\")\ndef configured_catalog_fixture():\n return ConfiguredAirbyteCatalog.parse_file(\"integration_tests/configured_catalog.json\")\n\n\nclass TestFacebookMarketingSource:\n @pytest.mark.parametrize(\n \"stream_name, deleted_id\", [(\"ads\", \"23846756820320398\"), (\"campaigns\", \"23846541919710398\"), (\"ad_sets\", \"23846541706990398\")]\n )\n def test_streams_with_include_deleted(self, stream_name, deleted_id, config_with_include_deleted, configured_catalog):\n catalog = self.slice_catalog(configured_catalog, {stream_name})\n records, states = self._read_records(config_with_include_deleted, catalog)\n deleted_records = list(filter(self._deleted_record, records))\n is_specific_deleted_pulled = deleted_id in list(map(self._object_id, records))\n\n assert states, \"incremental read should produce states\"\n for name, state in states[-1].state.data.items():\n assert \"include_deleted\" in state, f\"State for {name} should include `include_deleted` flag\"\n\n assert deleted_records, f\"{stream_name} stream should have deleted records returned\"\n assert is_specific_deleted_pulled, f\"{stream_name} stream should have a deleted record with id={deleted_id}\"\n\n @pytest.mark.parametrize(\"stream_name, deleted_num\", [(\"ads\", 2), (\"campaigns\", 3), (\"ad_sets\", 1)])\n def test_streams_with_include_deleted_and_state(self, stream_name, deleted_num, config_with_include_deleted, configured_catalog, state):\n \"\"\"Should ignore state because of include_deleted enabled\"\"\"\n catalog = self.slice_catalog(configured_catalog, {stream_name})\n records, states = self._read_records(config_with_include_deleted, catalog, state=state)\n deleted_records = list(filter(self._deleted_record, records))\n\n assert len(deleted_records) == deleted_num, f\"{stream_name} should have {deleted_num} deleted records returned\"\n\n @pytest.mark.parametrize(\"stream_name, deleted_num\", [(\"ads\", 0), (\"campaigns\", 0), (\"ad_sets\", 0)])\n def test_streams_with_include_deleted_and_state_with_included_deleted(\n self, stream_name, deleted_num, config_with_include_deleted, configured_catalog, state_with_include_deleted\n ):\n \"\"\"Should keep state because of include_deleted enabled previously\"\"\"\n catalog = self.slice_catalog(configured_catalog, {stream_name})\n records, states = self._read_records(config_with_include_deleted, catalog, state=state_with_include_deleted)\n deleted_records = list(filter(self._deleted_record, records))\n\n assert len(deleted_records) == deleted_num, f\"{stream_name} should have {deleted_num} deleted records returned\"\n\n @staticmethod\n def _deleted_record(record: AirbyteMessage) -> bool:\n return record.record.data[\"effective_status\"] == \"ARCHIVED\"\n\n @staticmethod\n def _object_id(record: AirbyteMessage) -> str:\n return str(record.record.data[\"id\"])\n\n @staticmethod\n def slice_catalog(catalog: ConfiguredAirbyteCatalog, streams: Set[str]) -> ConfiguredAirbyteCatalog:\n sliced_catalog = ConfiguredAirbyteCatalog(streams=[])\n for stream in catalog.streams:\n if stream.stream.name in streams:\n sliced_catalog.streams.append(stream)\n return sliced_catalog\n\n @staticmethod\n def _read_records(conf, catalog, state=None) -> Tuple[List[AirbyteMessage], List[AirbyteMessage]]:\n records = []\n states = []\n for message in SourceFacebookMarketing().read(AirbyteLogger(), conf, catalog, state=state):\n if message.type == Type.RECORD:\n records.append(message)\n elif message.type == Type.STATE:\n states.append(message)\n\n return records, states\n","sub_path":"airbyte-integrations/connectors/source-facebook-marketing/integration_tests/test_streams.py","file_name":"test_streams.py","file_ext":"py","file_size_in_byte":5755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"294356298","text":"'''\nEste script lee los datos del archivo datos_n.txt que corresponden al valor\nasociado a los bins en cada repeticion del algoritmo de metropolis.\nObtiene el promedio de cada valor y su respectivo error.\n'''\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nn = np.loadtxt('datos_10_millones_puntos.txt')\nbins_escogido = np.linspace(-10, 10, 51)\n\nsuma_ns = np.zeros(50)\nfor i in range(0, 5050, 50):\n suma_ns += n[i:i+50]\n\nns_promedio = np.copy(suma_ns)/101.\n\n# queremos formar la parte suma sobre i de (x_i - )^2\nsuma_diferencia_al_cuadrado = np.zeros(50)\nfor i in range(0, 5050, 50):\n diferencia = (n[i:i+50]-ns_promedio)\n for i in range(50):\n suma_diferencia_al_cuadrado[i] += diferencia[i]*diferencia[i]\n\n# calculando la desviacion estandar\n\ndesviacion_estandar = np.zeros(50)\nfor i in range(50):\n desviacion_estandar[i] = np.sqrt(suma_diferencia_al_cuadrado[i])/7.\n\nfig = plt.figure(1)\nfig.clf()\nplt.bar(bins_escogido[:50], ns_promedio,\n width=bins_escogido[1] - bins_escogido[0], color='g', alpha=0.5,\n yerr=desviacion_estandar, error_kw=dict(ecolor='red'))\nplt.xlabel('x')\nplt.show()\nplt.draw()\nplt.savefig('bonus.png')\nnp.savetxt('desviacion_estandar_10_millones.txt', desviacion_estandar)\n","sub_path":"bonus.py","file_name":"bonus.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"200078553","text":"from gwf import Workflow, AnonymousTarget\nfrom gwf.workflow import collect\nimport os\nimport glob\nfrom groups import Group\n\ngwf = Workflow()\n\n# Associated variables and setup which can be added to environment variable instead.\npath_to_relate = \"/faststorage/home/eriks/relate-clues/relate_v1.1.2_x86_64_dynamic/\"\npath_to_vcfs = \"/faststorage/project/simons/data/1000Genomes/\"\npath_to_ancestor = \"/faststorage/project/simons/data/1000Genomes/ancestral_alignmens/human_ancestor_GRCh37_e59/human_ancestor_{}.fa\"\npath_to_poplabels = \"data/pops/1000GP_Phase3.sample\"\npath_to_mask = \"data/depth_chr_masks/20140520.chr{}.strict_mask.fasta\"\nmaskx = \"data/depth_chr_masks/20141020.chrX.strict_mask.fasta\"\ngenetic_map = \"/faststorage/home/eriks/relate-clues/data/recombination_maps/genetic_map_chr{}_combined_b37.txt\"\ngenetic_map_x = \"/faststorage/home/eriks/relate-clues/data/recombination_maps/genetic_map_chrX_nonPAR_combined_b37.txt\"\nhaps_sample_dir = \"/faststorage/home/eriks/relate-clues/steps/haps_sample\"\n\npop_files = \"data/pops/\"\nuse_all = True\npop_list = glob.glob(pop_files + \"*.txt\")\n\nif use_all is True:\n pop_list.append(\"all_individuals\")\n\nvcfs = []\nchromosomes = list(range(1, 23))+[\"X\"]\n\nfor chrom in chromosomes:\n if chrom == 'X':\n vcf_path_and_name = os.path.join(\n path_to_vcfs, 'ALL.chrX.phase3_shapeit2_mvncall_integrated_v1b.20130502.genotypes'\n ) # dont use file extension\n else:\n vcf_path_and_name = os.path.join(\n path_to_vcfs, 'ALL.chr{}.phase3_shapeit2_mvncall_integrated_v5a.20130502.genotypes'.format(chrom)\n )\n ancestor_name = os.path.join(path_to_ancestor, \"human_ancestor_{}.fa\".format(chrom))\n vcfs.append({\"vcf_path\": vcf_path_and_name, \"chrom\": chrom})\n\n\ndef vcf_to_haps(vcf_path, chrom, relate_path, output_dir):\n \"\"\"Converts vcf files to haps/sample using the script from Relate \"\"\"\n inputs = [vcf_path+\".vcf.gz\"]\n haps_out = os.path.join(output_dir, \"chrom{}.haps\".format(chrom))\n sample_out = os.path.join(output_dir, \"chrom{}.sample\".format(chrom))\n RelateFileFormats = os.path.join(relate_path, \"bin/RelateFileFormats\")\n outputs = {\"haps\": haps_out, \"sample\": sample_out}\n options = {\n \"cores\": 2,\n \"memory\": \"4g\",\n \"walltime\": \"1:00:00\"\n }\n spec = \"\"\"\n {} --mode ConvertFromVcf --haps {} --sample {} -i {}\n \"\"\".format(RelateFileFormats, haps_out, sample_out, vcf_path)\n return AnonymousTarget(inputs=inputs, outputs=outputs, options=options, spec=spec)\n\n\ndef prepare_input(haps, sample, mask, ancestor, pop, output_dir, poplabels, relate_path):\n inputs = {\"haps\": haps, \"sample\": sample}\n s = os.path.basename(haps)\n number = s[5:s.find(\".\")]\n PrepareInputFiles = os.path.join(relate_path, \"scripts/PrepareInputFiles/PrepareInputFiles.sh\")\n destination_name = output_dir + \"chrom{}\".format(number)\n if number == \"X\":\n n_mask = maskx\n else:\n n_mask = mask.format(number)\n ancestor_in = ancestor.format(number)\n outputs = {\"haps\": destination_name+\".haps.gz\", \"sample\": destination_name+\".sample.gz\"}\n if pop != \"all_individuals\":\n remove_ids = \" --remove_ids \" + pop\n else:\n remove_ids = \"\"\n options = {\n \"cores\": 8,\n \"memory\": \"4g\",\n \"walltime\": \"4:00:00\"\n }\n spec = \"\"\"\n {} --haps {} --sample {} --mask {} --ancestor {}{} --poplabels {} -o {}\n \"\"\".format(PrepareInputFiles, haps, sample, n_mask, ancestor_in, remove_ids, poplabels, destination_name)\n return AnonymousTarget(inputs=inputs, outputs=outputs, options=options, spec=spec)\n\n\ndef make_chunks(haps, sample, pop, output_dir, relate_path):\n inputs = {\"haps\": haps, \"sample\": sample}\n s = os.path.basename(haps)\n number = s[5:s.find(\".\")]\n make_chunks = os.path.join(relate_path, \"bin/Relate\")\n dist = output_dir+\"chrom{}.dist.gz\".format(number)\n if number == \"X\":\n gene_map = genetic_map_x\n else:\n gene_map = genetic_map.format(number)\n outputs = [output_dir+\"temp/chrom{}/chunk_0.hap\".format(number)]\n options = {\n \"cores\": 4,\n \"memory\": \"16g\",\n \"walltime\": \"4:00:00\"\n }\n spec = \"\"\"\n cd {}\n {} --mode \"MakeChunks\" --haps {} --sample {} --map {} --dist {} -o {} --memory 14\n \"\"\".format(output_dir+\"temp/\",\n make_chunks, haps, sample, gene_map, dist, \"chrom{}\".format(number))\n print(spec)\n return AnonymousTarget(inputs=inputs, outputs=outputs, options=options, spec=spec)\n\n\nos.makedirs(haps_sample_dir, exist_ok=True)\nhaps_sample = gwf.map(vcf_to_haps, vcfs, extra={\"relate_path\": path_to_relate, \"output_dir\": haps_sample_dir})\nprep_list = []\n\n\nfor pop in pop_list:\n if os.path.basename(pop).endswith(\"txt\"):\n popname = os.path.basename(pop)[:-4]\n else:\n popname = pop\n path_to_dir = os.getcwd()+\"/steps/{}_prepared/\".format(popname)\n os.makedirs(path_to_dir, exist_ok=True)\n os.makedirs(path_to_dir+\"temp/\", exist_ok=True)\n with Group(gwf, suffix=popname) as g:\n preps = g.map(prepare_input, haps_sample.outputs, name=\"prepare_input\", extra={\n \"mask\": path_to_mask, \"ancestor\": path_to_ancestor, \"pop\": pop,\n \"output_dir\": path_to_dir, \"poplabels\": path_to_poplabels,\n \"relate_path\": path_to_relate})\n chunks = g.map(make_chunks, preps.outputs, name=\"make_chunks\", extra={\n \"pop\": pop,\n \"output_dir\": path_to_dir,\n \"relate_path\": path_to_relate})\n\n# Try at cleaning up the haps_sample dir, does not work currently\n# gwf.target_from_template(\n# name=\"remove_intermediate_files\",\n# template=cleanup(haps=prep_list, directory=haps_sample_dir)\n# )\n","sub_path":"workflow_preparation.py","file_name":"workflow_preparation.py","file_ext":"py","file_size_in_byte":5758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"281688296","text":"from drf_yasg import openapi\n\nfrom ..serializers import AuthorSerializer, PictureAuthorSerializer\n\nbad_request = openapi.Response(\n description=\"Bad request\",\n schema=openapi.Schema(\n type=openapi.TYPE_OBJECT,\n title=\"Errors\",\n properties={\n \"field\": openapi.Schema(\n type=openapi.TYPE_ARRAY,\n items=openapi.Schema(type=openapi.TYPE_STRING),\n )\n },\n ),\n)\n\nnot_found = openapi.Response(\n description=\"Not found\",\n schema=openapi.Schema(\n type=openapi.TYPE_OBJECT,\n title=\"Message\",\n properties={\n \"detail\": openapi.Schema(\n type=openapi.TYPE_STRING,\n )\n },\n ),\n)\n\nunauthorized = openapi.Response(\n description=\"Unauthorized\",\n schema=openapi.Schema(\n type=openapi.TYPE_OBJECT,\n title=\"Message\",\n properties={\n \"detail\": openapi.Schema(\n type=openapi.TYPE_STRING,\n )\n },\n ),\n)\n\n\nforbidden = openapi.Response(\n description=\"Forbidden\",\n schema=openapi.Schema(\n type=openapi.TYPE_OBJECT,\n title=\"Message\",\n properties={\n \"detail\": openapi.Schema(\n type=openapi.TYPE_STRING,\n )\n },\n ),\n)\n\ncreate = dict(\n tags=[\"authors\"],\n request_body=AuthorSerializer,\n responses={\n 201: openapi.Response(description=\"Created\", schema=AuthorSerializer),\n 400: bad_request,\n 401: unauthorized,\n 403: forbidden,\n },\n)\n\nretrive = dict(\n tags=[\"authors\"],\n responses={\n 200: openapi.Response(description=\"Ok\", schema=AuthorSerializer),\n 400: bad_request,\n 401: unauthorized,\n 403: forbidden,\n 404: not_found,\n },\n)\n\nupdate = dict(\n tags=[\"authors\"],\n request_body=AuthorSerializer,\n responses={\n 200: openapi.Response(description=\"Ok\", schema=AuthorSerializer),\n 400: bad_request,\n 401: unauthorized,\n 403: forbidden,\n 404: not_found,\n },\n)\n\ndelete = dict(\n tags=[\"authors\"],\n responses={\n 204: openapi.Response(description=\"No Content\"),\n 400: bad_request,\n 401: unauthorized,\n 403: forbidden,\n 404: not_found,\n },\n)\n\npicture = dict(\n tags=[\"authors\"],\n request_body=PictureAuthorSerializer,\n responses={\n 200: openapi.Response(description=\"Ok\", schema=AuthorSerializer),\n 400: bad_request,\n 401: unauthorized,\n 403: forbidden,\n 404: not_found,\n },\n)\n","sub_path":"app/author/docs/schemas.py","file_name":"schemas.py","file_ext":"py","file_size_in_byte":2562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"222931652","text":"from __future__ import division\n\nimport numpy as np\nfrom sklearn import svm\nfrom sklearn.metrics import classification_report\n\nfrom keras.models import Model\nfrom keras.layers import GlobalAveragePooling2D\nfrom vggish import VGGish\n\nfrom dataset.dataset_utils import read_dataset_filenames, TRAIN_SET, TEST_SET, VAL_SET\nfrom vggish_inputs import wavfile_to_examples\n\n\ndef loading_data(files, labels, sound_extractor):\n \"\"\"\n Given a list of filenames and its laabels, extract a feature vector with the sound_extractor given\n :param files: List of path to .wav files\n :param labels: List of class names, correlative to the files list\n :param sound_extractor: Keras model used to compute the embeddings/features\n :return: List of features and list of labels\n \"\"\"\n\n ret_data = []\n ret_labels = []\n batch_size = 32\n batch = []\n\n for file_name, label in zip(files, labels):\n # compute log mel spectogram from audio files\n log_mel = wavfile_to_examples(file_name)\n\n # TODO: not sure why for some files the output is empty, should look closer at this\n if len(log_mel) != 1:\n continue\n # add the label to the return list and the spectogram to the batch\n ret_labels.append(label)\n batch.append(log_mel)\n if len(batch) == batch_size:\n # when batch is full, run it through the net to get the embeddings/features\n batch = np.concatenate(batch, axis=0)\n features = sound_extractor.predict(np.expand_dims(batch,-1))\n ret_data.append(features)\n # reset the batch\n batch = []\n\n if len(batch) > 0:\n # check if there is data in the batch waiting to be run through the net\n batch = np.concatenate(batch, axis=0)\n features = sound_extractor.predict(np.expand_dims(batch, -1))\n ret_data.append(features)\n\n ret_data = np.concatenate(ret_data, axis=0)\n ret_labels = np.array(ret_labels)\n\n # check everything is as expected\n assert len(ret_labels) == len(ret_data)\n\n return ret_data, ret_labels\n\n\nif __name__ == '__main__':\n\n # define the feature extractor\n sound_model = VGGish(include_top=False, load_weights=True)\n\n x = sound_model.get_layer(name=\"conv4/conv4_2\").output\n output_layer = GlobalAveragePooling2D()(x)\n sound_extractor = Model(input=sound_model.input, output=output_layer)\n\n # load dataset\n dataset = read_dataset_filenames()\n\n # load the training data and compute its features/embeddings\n print(\"loading training data...\")\n X_train, y_train = loading_data(*dataset[TRAIN_SET], sound_extractor)\n\n # load the testing data and compute its features/embeddings\n print(\"loading test data...\")\n X_test, y_test = loading_data(*dataset[TEST_SET], sound_extractor)\n\n # load the validation data and compute its features/embeddings\n print(\"loading validation data...\")\n X_val, y_val = loading_data(*dataset[VAL_SET], sound_extractor)\n\n print('Training...')\n # Train simple SVM classifier from sckit, using its default parameters\n clf = svm.LinearSVC()\n clf.fit(X_train, y_train)\n\n # Evaluate the model in all sets\n print('Report for training')\n y_pred = clf.predict(X_train)\n print(classification_report(y_train, y_pred))\n\n print('Report for validation')\n y_pred = clf.predict(X_val)\n print(classification_report(y_val, y_pred))\n\n print('Report for testing')\n y_pred = clf.predict(X_test)\n print(classification_report(y_test, y_pred))\n\n\n\n","sub_path":"evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":3523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"20524030","text":"# Owner(s): [\"module: dynamo\"]\nimport copy\nimport functools\nimport os\nimport unittest\n\nimport torch\n\nhas_torch_xla = True\ntry:\n import torch._dynamo.optimizations.torchxla_integration as integration\nexcept ImportError:\n has_torch_xla = False\n\nimport torch.utils._pytree as pytree\nfrom torch import fx, nn\n\n\nclass BasicModule(nn.Module):\n def __init__(self):\n super(BasicModule, self).__init__()\n\n def forward(self, x, y):\n return x + y\n\n def get_random_inputs(self):\n return (torch.randn(10), torch.randn(10))\n\n\nclass MatmulModule(nn.Module):\n def __init__(self):\n super(MatmulModule, self).__init__()\n\n def forward(self, x, y):\n return x @ y\n\n def get_random_inputs(self):\n return (torch.randn(5, 100), torch.randn(100, 5))\n\n\nclass LinearModule(nn.Module):\n def __init__(self):\n super().__init__()\n self.linear = nn.Linear(10, 5)\n\n def forward(self, x):\n return self.linear(x)\n\n def get_random_inputs(self):\n return (torch.randn(10),)\n\n\nclass ModuleInplaceUpdate(nn.Module):\n def __init__(self):\n super(ModuleInplaceUpdate, self).__init__()\n\n def forward(self, a, b):\n a.sub_(b)\n return b - 1, b + 1\n\n def get_random_inputs(self):\n return (torch.randn(10), torch.randn(10))\n\n\ndef allclose(expected, actual):\n def unwrap(cont):\n if isinstance(cont, (list, tuple)) and len(cont) == 1:\n return cont[0]\n return cont\n\n expected = unwrap(expected)\n actual = unwrap(actual)\n\n if isinstance(expected, torch.Tensor) and isinstance(actual, torch.Tensor):\n return torch.allclose(expected, actual)\n elif isinstance(expected, (tuple, list)) and isinstance(actual, (tuple, list)):\n return len(expected) == len(actual) and all(\n torch.allclose(a, b) for a, b in zip(expected, actual)\n )\n else:\n raise RuntimeError(\"Unexpected types\")\n\n\n@functools.lru_cache(None)\ndef should_run_torchxla_tests():\n \"\"\"\n Run the tests if torch_xla is available and number of gpu devices is specified.\n \"\"\"\n gpu_device_specified = int(os.environ.get(\"GPU_NUM_DEVICES\", \"0\")) > 0\n return has_torch_xla and gpu_device_specified\n\n\ndef make_reuse_graph_test(module_class, niter=100):\n @unittest.skipIf(\n not should_run_torchxla_tests(),\n \"Skip the tests since torch_xla is not available or XLA devices are not specified\",\n )\n def test_wrapper(self):\n import torch_xla.core.xla_model as xm\n\n xla_dev = xm.xla_device()\n mod = module_class()\n xla_module = copy.deepcopy(mod).to(device=xla_dev)\n inputs = mod.get_random_inputs()\n optimized_mod = integration.extract_compiled_graph(\n fx.symbolic_trace(mod), inputs\n )\n\n for i in range(niter):\n rand_args = mod.get_random_inputs()\n orig_dev = rand_args[0].device\n rand_args_copy = copy.deepcopy(rand_args)\n\n # Can not simply call\n # expected = mod(*rand_args)\n # Since we need use xla to calculate expected results\n xla_inputs = tuple(\n copy.deepcopy(inp).to(device=xla_dev) for inp in rand_args\n )\n xla_out = xla_module(*xla_inputs)\n # copy xla_inputs back to rand_args since the model may inplace update\n # the arguments\n rand_args = tuple(inp.to(device=orig_dev) for inp in xla_inputs)\n expected = pytree.tree_map(lambda o: o.to(device=orig_dev), xla_out)\n\n actual = optimized_mod(*rand_args_copy)\n\n if not allclose(expected, actual):\n print(\n f\"Incorrect results at iter {i}. expected\\n{expected}, actual\\n{actual}\"\n )\n self.assertTrue(False)\n\n # make sure arguments match after calling the model forward method\n # to handle inplace updates.\n if not allclose(rand_args, rand_args_copy):\n print(\n f\"Incorrect updated arguments at iter {i}. expected\\n{rand_args}, actual\\n{rand_args_copy}\"\n )\n self.assertTrue(False)\n\n return test_wrapper\n\n\nclass TorchXLAReuseGraphTest(unittest.TestCase):\n test_basic = make_reuse_graph_test(BasicModule)\n test_matmul = make_reuse_graph_test(MatmulModule)\n test_linear = make_reuse_graph_test(LinearModule)\n test_inplace_update = make_reuse_graph_test(ModuleInplaceUpdate)\n","sub_path":"test/dynamo/test_torchxla_integration.py","file_name":"test_torchxla_integration.py","file_ext":"py","file_size_in_byte":4500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"186209955","text":"#!/usr/bin/env python\nimport rospy\nfrom opencv_object_tracking.msg import position_publish\nfrom opencv_object_tracking.srv import *\nfrom geometry_msgs.msg import Point\nimport numpy as np\nimport threading\n\n# define the transfer function from quaternion to rotate matrix\ndef quaternion_to_rotation_matrix(quat):\n q = quat.copy()\n n = np.dot(q, q)\n if n < np.finfo(q.dtype).eps:\n return np.identity(4)\n q = q * np.sqrt(2.0 / n)\n q = np.outer(q, q)\n rot_matrix = np.array(\n [[1.0 - q[2, 2] - q[3, 3], q[1, 2] + q[3, 0], q[1, 3] - q[2, 0], 0.0],\n [q[1, 2] - q[3, 0], 1.0 - q[1, 1] - q[3, 3], q[2, 3] + q[1, 0], 0.0],\n [q[1, 3] + q[2, 0], q[2, 3] - q[1, 0], 1.0 - q[1, 1] - q[2, 2], 0.0],\n [0.0, 0.0, 0.0, 1.0]],\n dtype=q.dtype)\n return rot_matrix\n\n# handle the loop problem caused by rospy.spin()\ndef thread_job():\n rospy.spin()\n # spin() simply keeps python from exiting until this node is stopped\n\ndef Handle_Transfer_Object(req):\n # the server to answer the client resquest to send the actual object position in robot base\n global actual_1_position, actual_2_position, actual_1_position_temp, actual_2_position_temp\n actual_1_position.x = actual_1_position_temp[0]\n actual_1_position.y = actual_1_position_temp[1]\n actual_1_position.z = actual_1_position_temp[2]\n actual_2_position.x = actual_2_position_temp[0]\n actual_2_position.y = actual_2_position_temp[1]\n actual_2_position.z = actual_2_position_temp[2]\n actual_position = [actual_1_position, actual_2_position]\n return TransferObjectResponse(actual_position)\n\ndef callback(data):\n global object_1_position, object_2_position, counter_1, counter_2\n # store the sample data until it is up to 5 and compute the average position to filter the noise ; I have divided the Position_XYZ into two seperated array, not in an array, by judging the counter\n if data.counter == 1:\n object_1_position_temp[counter_1,:] = np.array([data.Position_XYZ[0].x, data.Position_XYZ[0].y, data.Position_XYZ[0].z])\n counter_1 = counter_1 + 1\n elif data.counter == 2:\n object_2_position_temp[counter_2,:] = np.array([data.Position_XYZ[0].x, data.Position_XYZ[0].y, data.Position_XYZ[0].z])\n counter_2 = counter_2 + 1\n else: \n rospy.loginfo(\"data gap %s\", data.counter)\n if counter_1 == 5:\n object_1_position = np.mean(object_1_position_temp, axis=0)\n counter_1 = 0\n if counter_2 == 5:\n object_2_position = np.mean(object_2_position_temp, axis=0)\n counter_2 = 0\n #rospy.loginfo(rospy.get_caller_id() + \"I heard %s\", data.Position_XYZ)\n \ndef listener():\n global rotate_matrix, object_1_position, object_2_position, actual_1_position_temp, actual_2_position_temp\n\n rospy.init_node('listener', anonymous=True)\n\n # handle the loop problem caused by rospy.spin()\n add_thread = threading.Thread(target = thread_job)\n add_thread.start()\n\n rospy.Subscriber(\"position_object\", position_publish, callback)\n rospy.Service('transfer_acutal_position', TransferObject, Handle_Transfer_Object)\n while not rospy.is_shutdown(): \n # judge the oject_position whether is empty if not compute the object position in robot base\n if np.where(object_1_position!=0)[0].shape[0]==0 or np.where(object_2_position!=0)[0].shape[0]==0:\n pass\n else:\n actual_1_position_temp = np.dot(rotate_matrix, np.concatenate((object_1_position, [1])))\n actual_2_position_temp = np.dot(rotate_matrix, np.concatenate((object_2_position, [1])))\n\n \nif __name__ == '__main__':\n # get the eye_on_base calibration matrix parameters from master\n translation_x = rospy.get_param('/translation/x')\n translation_y = rospy.get_param('/translation/y')\n translation_z = rospy.get_param('/translation/z')\n rotation_x = rospy.get_param('/rotation/x')\n rotation_y = rospy.get_param('/rotation/y')\n rotation_z = rospy.get_param('/rotation/z')\n rotation_w = rospy.get_param('/rotation/w')\n # get the rotation and translation of the matrix\n quaternion = np.array([rotation_w, rotation_x, rotation_y, rotation_z])\n rotate_matrix = quaternion_to_rotation_matrix(quaternion)\n rotate_matrix[0,3] = translation_x\n rotate_matrix[1,3] = translation_y\n rotate_matrix[2,3] = translation_z\n # count the sample number for average the data\n counter_1 = 0\n counter_2 = 0\n\n #store the sample data and the final data\n object_1_position_temp = np.zeros((5,3))\n object_2_position_temp = np.zeros((5,3))\n object_1_position = np.zeros(3)\n object_2_position = np.zeros(3)\n #store the sample data and the final data\n actual_1_position_temp = np.zeros(3)\n actual_2_position_temp = np.zeros(3)\n actual_1_position = Point()\n actual_2_position = Point()\n try:\n listener()\n except rospy.ROSInterruptException:\n pass\n\n","sub_path":"scripts/calibration.py","file_name":"calibration.py","file_ext":"py","file_size_in_byte":4893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"16998373","text":"##############################################\n# PDFDatabase.py #\n##############################################\n\n#============================================\n# import\n#============================================\n\nimport prettytable\nimport string\nimport re\nimport argparse\nfrom ROOT import *\n\nimport sys\nsys.argv.append( '-b-' )\n\n#-------------------------------------------\n# rescale\n#-------------------------------------------\ndef rescale(x):\n f = RooFormulaVar(\"rescalex\", \"40.0*@0+150.0\", RooArgList(x))\n return f\n\n#----------------------------------------\n# linear\n#----------------------------------------\ndef linear(x):\n m = RooRealVar(\"slope\", \"slope\", -0.33, -10, 0) \n b = RooRealVar(\"offset\", \"offset\", 15, 2, 1000) \n \n linear_model = RooGenericPdf(\"linear_model\", \"@1*(@0-140)+@2\", RooArgList(x, m, b))\n return linear_model, [m, b]\n\n \n#----------------------------------------\n# Tripple Gaussian\n#----------------------------------------\ndef TripleGauss(x):\n meanG1 = RooRealVar(\"MeanG1\", \"MeanG1\", 0.1, -1., 1.)\n meanG2 = RooRealVar(\"MeanG2\", \"MeanG2\", 0.1, -1., 1.)\n meanG3 = RooRealVar(\"MeanG3\", \"MeanG3\", 0.1, -1., 1.)\n widthG1 = RooRealVar(\"WidthG1\", \"WidthG1\", 0.1, 0., 1.)\n widthG2 = RooRealVar(\"WidthG2\", \"WidthG2\", 0.1, 0., 1.)\n widthG3 = RooRealVar(\"WidthG3\", \"WidthG3\", 0.1, 0., 1.)\n coefG1 = RooRealVar(\"coefG1\", \"coefG1\", 0.5,0.,1.)\n coefG2 = RooRealVar(\"coefG2\", \"coefG2\", 0.5,0.,1.)\n gaus1 = RooGaussian(\"gaus1\", \"gaus1\", x, meanG1, widthG1)\n gaus2 = RooGaussian(\"gaus2\", \"gaus2\", x, meanG2, widthG2)\n gaus3 = RooGaussian(\"gaus3\", \"gaus3\", x, meanG3, widthG3)\n triplegauss = RooAddPdf('triplegauss', 'triplegauss', RooArgList(gaus1, gaus2, gaus3), RooArgList(coefG1,coefG2))\n return triplegauss, [meanG1, meanG2, meanG3, widthG1, widthG2, widthG3, coefG1, coefG2], [gaus1,gaus2,gaus3]\n\n#----------------------------------------------------------------\n# Legendre Polynomial\n#----------------------------------------------------------------\ndef MKLegendre(x):\n eps = 0.0000001 #epsilon\n arglist = RooArgList() \n # constant off set to handle negative pdf values\n #uni = r.RooUniform(\"uni\",\"uni\",r.RooArgSet(x))\n #data_uni = uni.generate(r.RooArgSet(x),500000)\n #data\n #data = r.RooDataHist('data_obs', 'data_obs', r.RooArgList(x), hist_data)\n #data.add(data_uni)\n # defining Legendre polynomial\n le0 = RooLegendre(\"le0\",\"le0\",x,0) \n co0 = RooRealVar(\"co0\",\"co0\",eps,-1,1)\n le1 = RooLegendre(\"le1\",\"le1\",x,1) \n co1 = RooRealVar(\"co1\",\"co1\",eps,-1,1)\n le2 = RooLegendre(\"le2\",\"le2\",x,2) \n co2 = RooRealVar(\"co2\",\"co2\",eps,-1,1)\n le3 = RooLegendre(\"le3\",\"le3\",x,3) \n co3 = RooRealVar(\"co3\",\"co3\",eps,-1,1)\n le4 = RooLegendre(\"le4\",\"le4\",x,4) \n co4 = RooRealVar(\"co4\",\"co4\",eps,-1,1)\n le5 = RooLegendre(\"le5\",\"le5\",x,5)\n co5 = RooRealVar(\"co5\",\"co5\",eps,-1,1)\n le6 = RooLegendre(\"le6\",\"le6\",x,6) \n co6 = RooRealVar(\"co6\",\"co6\",eps,-1,1)\n le7 = RooLegendre(\"le7\",\"le7\",x,7) \n co7 = RooRealVar(\"co7\",\"co7\",eps,-1,1)\n le8 = RooLegendre(\"le8\",\"le8\",x,8) \n co8 = RooRealVar(\"co8\",\"co8\",eps,-1,1)\n le9 = RooLegendre(\"le9\",\"le9\",x,9) \n co9 = RooRealVar(\"co9\",\"co9\",eps,-1,1)\n le10 = RooLegendre(\"le10\",\"le10\",x,10) \n co10 = RooRealVar(\"co10\",\"co10\",eps,-1,1)\n arglist.add(co0) #0\n arglist.add(le0)\n arglist.add(co1)\n arglist.add(le1)\n arglist.add(co2)\n arglist.add(le2)\n arglist.add(co3)\n arglist.add(le3)\n arglist.add(co4)\n arglist.add(le4)\n arglist.add(co5)\n arglist.add(le5) #11\n arglist.add(co6)\n arglist.add(le6)\n arglist.add(co7)\n arglist.add(le7) #15\n #arglist.add(co8)\n #arglist.add(le8) # 17\n arglist.add(co9)\n arglist.add(le9) # 19\n arglist.add(co10)\n arglist.add(le10) # 21\n leg = RooGenericPdf(\"leg\",\"leg\",\"@0*@1+@2*@3+@4*@5+@6*@7+@8*@9+@10*@11+@12*@13+@14*@15+@16*@17+@18*@19\",arglist)\n return leg, [le0,co0,le1,co1,le2,co2,le3,co3,le4,co4,le5,co5,le6,co6,le7,co7,le9,co9,le10,co10]\n # @0*@1+@2*@3+@4*@5+@6*@7+@8*@9+@10*@11+@12*@13+@14*@15+@16*@17+@18*@19+@20*@21\n","sub_path":"python_files/backup/SignalPDFDatabase.py","file_name":"SignalPDFDatabase.py","file_ext":"py","file_size_in_byte":4160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"599688023","text":"'''\nWSGI Kerberos Authentication Middleware\n\nAdd Kerberos/GSSAPI Negotiate Authentication support to any WSGI Application\n'''\nimport kerberos\nimport logging\nimport os\nimport socket\n\nLOG = logging.getLogger(__name__)\nLOG.addHandler(logging.NullHandler())\n\n\ndef _consume_request(environ):\n '''\n Consume and discard all of the data on the request.\n\n This avoids problems that some clients have when they get an unexpected\n and premature close from the server.\n\n RFC2616: If an origin server receives a request that does not include an\n Expect request-header field with the \"100-continue\" expectation, the\n request includes a request body, and the server responds with a final\n status code before reading the entire request body from the transport\n connection, then the server SHOULD NOT CLOSE the transport connection until\n it has read the entire request, or until the client closes the connection.\n Otherwise, the client might not reliably receive the response message.\n However, this requirement is not be construed as preventing a server from\n defending itself against denial-of-service attacks, or from badly broken\n client implementations.\n '''\n try:\n sock = environ.get('wsgi.input')\n if hasattr(sock, 'closed') and sock.closed:\n return\n # Figure out how much content is available for us to consume.\n expected = int(environ.get('CONTENT_LENGTH', '0'))\n\n # Try to receive all of the data. Keep retrying until we get an error\n # which indicates that we can't retry. Eat errors. The client will just\n # have to deal with a possible Broken Pipe -- we tried.\n received = 0\n while received < expected:\n try:\n received += len(sock.read(expected - received))\n except socket.error as err:\n if err.errno != errno.EAGAIN:\n break\n except (KeyError, ValueError):\n pass\n\n\nclass KerberosAuthMiddleware(object):\n '''\n WSGI Middleware providing Kerberos Authentication\n\n If no hostname is provided, the name returned by socket.gethostname() will\n be used.\n\n :param app: WSGI Application\n :param hostname: Hostname for kerberos name canonicalization\n :type hostname: str\n :param unauthorized: 401 Response text or text/content-type tuple\n :type unauthorized: str or tuple\n :param forbidden: 403 Response text or text/content-type tuple\n :type forbidden: str or tuple\n '''\n\n def __init__(self, app, hostname=None, unauthorized=None, forbidden=None,\n auth_required_callback=None):\n if hostname is None:\n hostname = socket.gethostname()\n\n if unauthorized is None:\n unauthorized = ('Unauthorized', 'text/plain')\n elif isinstance(unauthorized, basestring):\n unauthorized = (unauthorized, 'text/plain')\n\n if forbidden is None:\n forbidden = ('Forbidden', 'text/plain')\n elif isinstance(forbidden, basestring):\n forbidden = (forbidden, 'text/plain')\n\n if auth_required_callback is None:\n auth_required_callback = lambda x: True\n\n self.application = app # WSGI Application\n self.service = 'HTTP@%s' % hostname # GSS Service\n self.unauthorized = unauthorized # 401 response text/content-type\n self.forbidden = forbidden # 403 response text/content-type\n self.auth_required_callback = auth_required_callback\n\n if 'KRB5_KTNAME' in os.environ:\n try:\n principal = kerberos.getServerPrincipalDetails('HTTP',\n hostname)\n except kerberos.KrbError as exc:\n LOG.warn('KerberosAuthMiddleware: %s' % exc.message[0])\n else:\n LOG.debug('KerberosAuthMiddleware is identifying as %s' %\n principal)\n else:\n LOG.warn('KerberosAuthMiddleware: set KRB5_KTNAME to your keytab '\n 'file')\n\n def _unauthorized(self, environ, start_response, token=None):\n '''\n Send a 401 Unauthorized response\n '''\n headers = [('content-type', self.unauthorized[1])]\n if token:\n headers.append(('WWW-Authenticate', token))\n else:\n headers.append( ('WWW-Authenticate', 'Negotiate'))\n _consume_request(environ)\n start_response('401 Unauthorized', headers)\n return [self.unauthorized[0]]\n\n def _forbidden(self, environ, start_response):\n '''\n Send a 403 Forbidden response\n '''\n headers = [('content-type', self.forbidden[1])]\n _consume_request(environ)\n start_response('403 Forbidden', headers)\n return [self.forbidden[0]]\n\n def _authenticate(self, client_token):\n '''\n Validate the client token\n\n Return the authenticated users principal and a token suitable to\n provide mutual authentication to the client.\n '''\n state = None\n server_token = None\n user = None\n try:\n rc, state = kerberos.authGSSServerInit(self.service)\n if rc == kerberos.AUTH_GSS_COMPLETE:\n rc = kerberos.authGSSServerStep(state, client_token)\n if rc == kerberos.AUTH_GSS_COMPLETE:\n server_token = kerberos.authGSSServerResponse(state)\n user = kerberos.authGSSServerUserName(state)\n elif rc == kerberos.AUTH_GSS_CONTINUE:\n server_token = kerberos.authGSSServerResponse(state)\n except kerberos.GSSError:\n pass\n finally:\n if state:\n kerberos.authGSSServerClean(state)\n return server_token, user\n\n\n def __call__(self, environ, start_response):\n '''\n Authenticate the client, and on success invoke the WSGI application.\n Include a token in the response headers that can be used to\n authenticate the server to the client.\n '''\n # If we don't need to authenticate the request, shortcut the whole\n # process.\n if not self.auth_required_callback(environ):\n return self.application(environ, start_response)\n\n authorization = environ.get('HTTP_AUTHORIZATION')\n # If we have no 'Authorization' header, return a 401.\n if authorization is None:\n return self._unauthorized(environ, start_response)\n\n # If we have an 'Authorization' header, extract the client's token and\n # attempt to authenticate with it.\n client_token = ''.join(authorization.split()[1:])\n server_token, user = self._authenticate(client_token)\n\n # If we get a server_token and a user, call the application, add our\n # token, and return the response for mutual authentication\n if server_token and user:\n # Add the user to the environment for the application to use it,\n # call the application, add the token to the response, and return\n # it\n environ['REMOTE_USER'] = user\n def custom_start_response(status, headers, exc_info=None):\n headers.append(('WWW-Authenticate', ' '.join(['negotiate',\n server_token])))\n return start_response(status, headers, exc_info)\n return self.application(environ, custom_start_response)\n elif server_token:\n # If we got a token, but no user, return a 401 with the token\n return self._unauthorized(start_response, server_token)\n else:\n # Otherwise, return a 403.\n return self._forbidden(environ, start_response)\n","sub_path":"wsgi_kerberos.py","file_name":"wsgi_kerberos.py","file_ext":"py","file_size_in_byte":7794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"296752651","text":"import json\nimport boto3\nimport base64\nfrom botocore.errorfactory import ClientError\nimport os\n\n\n# Constants\nBUCKET_NAME = 'nya-portfolio-updates-public'\nFILE_PATH = 'images/avatars'\n\n\"https://.s3.amazonaws.com/images/avatars/389a7198-c5a9-413d-adc2-09221b8c478d.jpg\"\n\ndef exception(e):\n # Response for errors\n status_code = 400\n return {\n 'statusCode': status_code,\n 'body': json.dumps({'errorMessage' : str(e)})\n }\n\ndef response(data): \n # Response for success\n return {\n 'statusCode': 200,\n 'body': json.dumps(data)\n }\n\ndef fileExists(key):\n try:\n s3.head_object(Bucket=BUCKET_NAME, Key=key)\n print(\"File already exists: \" + key) \n return True\n except ClientError:\n # Not found\n return False\n\n\ns3 = boto3.client('s3')\ndynamodb = boto3.resource('dynamodb')\n\n\ndef lambda_handler(event, context):\n # Instance variables\n responseData = {}\n fileName = None\n\n # Extract Query parameters & Validate\n if 'queryStringParameters' not in event:\n return exception('No query parameters in event - check API Gateway configuration')\n try:\n fileName = event['queryStringParameters']['fileName']\n personID = event['queryStringParameters']['personID']\n except Exception as e:\n return exception(f'Invalid patameters {str(e)}')\n \n # Check for existing Photo - If file exists increment suffix\n while fileExists(FILE_PATH+'/'+fileName):\n name, extension = os.path.splitext(fileName)\n nameArray = name.rsplit(\"_\", 1)\n if len(nameArray) > 1:\n versionNumber = nameArray[len(nameArray)-1]\n newVersion = int(versionNumber) + 1\n fileName = nameArray[0] + \"_\" + str(newVersion) + extension\n else:\n fileName = name + \"_1\" + extension\n \n # Now save (with updated filename if needed) \n try:\n bodyData = event['body']\n decodedFile = base64.b64decode(bodyData)\n s3.put_object(Bucket=BUCKET_NAME, Key=FILE_PATH+'/'+fileName, Body=decodedFile)\n s3Location = f\"https://{BUCKET_NAME}.s3.amazonaws.com/{FILE_PATH}/{fileName}\"\n except Exception as e:\n # Other exception\n return exception(f'File Upload failed: {str(e)}')\n\n # Return success message\n responseData['success'] = True\n responseData['data'] = {}\n responseData['data']['photoURL'] = s3Location\n return response(responseData) ","sub_path":"functions/cta/uploadMemberPhoto.py","file_name":"uploadMemberPhoto.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"424013972","text":"\nfrom __future__ import annotations\n\nimport asyncio\nimport logging\nfrom contextlib import closing\nfrom typing import ClassVar, Callable, Awaitable, NoReturn\nfrom typing_extensions import Final\n\nfrom aioredis import Redis, ConnectionClosedError # type: ignore\n\nfrom ._util import unwatch_pipe\nfrom .keys import RedisKey, GlobalKeys, CleanupKeys, NamespaceKeys, \\\n ContentKeys, MailboxKeys, MessageKeys\n\n__all__ = ['Cleanup', 'CleanupTask', 'CleanupThread']\n\n_log = logging.getLogger(__name__)\n\n\nclass Cleanup:\n \"\"\"Defines the logic for adding key groups to be cleaned up.\n\n Args:\n root: The root redis key.\n\n \"\"\"\n\n content_expire = 3600\n\n def __init__(self, global_keys: GlobalKeys) -> None:\n super().__init__()\n keys = CleanupKeys(global_keys)\n self.keys: Final = keys\n self._order = (keys.messages, keys.mailboxes, keys.namespaces,\n keys.contents, keys.roots)\n\n def add_namespace(self, pipe: Redis, keys: NamespaceKeys) -> None:\n \"\"\"Add the namespace to be cleaned up.\n\n Args:\n pipe: Piped redis commands.\n keys: The namespace key group.\n\n \"\"\"\n cleanup_val = keys.root.named['namespace']\n pipe.rpush(self.keys.namespaces, cleanup_val)\n\n def add_mailbox(self, pipe: Redis, keys: MailboxKeys) -> None:\n \"\"\"Add the mailbox to be cleaned up.\n\n Args:\n pipe: Piped redis commands.\n keys: The mailbox key group.\n\n \"\"\"\n namespace = keys.root.named['namespace']\n mailbox_id = keys.root.named['mailbox_id']\n cleanup_val = b'%b\\x00%b' % (namespace, mailbox_id)\n pipe.rpush(self.keys.mailboxes, cleanup_val)\n\n def add_message(self, pipe: Redis, keys: MessageKeys) -> None:\n \"\"\"Add the message to be cleaned up.\n\n Args:\n pipe: Piped redis commands.\n keys: The message key group.\n\n \"\"\"\n namespace = keys.root.named['namespace']\n mailbox_id = keys.root.named['mailbox_id']\n msg_uid = keys.root.named['uid']\n cleanup_val = b'%b\\x00%b\\x00%b' \\\n % (namespace, mailbox_id, msg_uid)\n pipe.rpush(self.keys.messages, cleanup_val)\n\n def add_content(self, pipe: Redis, keys: ContentKeys) -> None:\n \"\"\"Add the content to be cleaned up.\n\n Args:\n pipe: Piped redis commands.\n keys: The content key group.\n\n \"\"\"\n namespace = keys.root.named['namespace']\n email_id = keys.root.named['email_id']\n cleanup_val = b'%b\\x00%b' % (namespace, email_id)\n pipe.rpush(self.keys.contents, cleanup_val)\n\n def add_root(self, pipe: Redis, root: RedisKey) -> None:\n \"\"\"Add the content to be cleaned up.\n\n Args:\n pipe: Piped redis commands.\n root: The redis key prefix.\n\n \"\"\"\n cleanup_val = root.wildcard\n pipe.rpush(self.keys.roots, cleanup_val)\n\n\nclass CleanupTask:\n \"\"\"Maintains a :class:`CleanupThread` for the duration of the process\n lifetime, restarting on failure.\n\n Args:\n connect_redis: Supplies a connected redis object.\n root: The root redis key.\n\n \"\"\"\n\n #: The delay between redis reconnect attempts, on connection failure.\n connection_delay: ClassVar[float] = 5.0\n\n def __init__(self, connect_redis: Callable[[], Awaitable[Redis]],\n global_keys: GlobalKeys) -> None:\n super().__init__()\n self._connect_redis = connect_redis\n self._global_keys = global_keys\n\n async def run_forever(self) -> NoReturn:\n \"\"\"Run the cleanup loop indefinitely.\"\"\"\n while True:\n try:\n with closing(await self._connect_redis()) as redis:\n await CleanupThread(redis, self._global_keys).run()\n except (ConnectionClosedError, OSError):\n _log.warning('Redis connection failure', exc_info=True)\n await asyncio.sleep(self.connection_delay)\n\n\nclass CleanupThread:\n \"\"\"Defines the logic for monitoring and executing cleanup of various\n entities.\n\n Args:\n redis: The redis connection object.\n global_keys: The global keys group.\n\n \"\"\"\n\n def __init__(self, redis: Redis, global_keys: GlobalKeys) -> None:\n super().__init__()\n self._redis = redis\n self._cleanup = Cleanup(global_keys)\n self._global_keys = global_keys\n\n async def run(self) -> NoReturn:\n \"\"\"Run the cleanup loop indefinitely.\n\n Raises:\n :class:`~aioredis.ConnectionClosedError`: The connection to redis\n was interrupted.\n\n \"\"\"\n redis = self._redis\n cleanup = self._cleanup\n while True:\n cleanup_key, cleanup_val = await redis.blpop(\n *cleanup._order, timeout=0)\n try:\n await asyncio.shield(self._run_one(cleanup_key, cleanup_val))\n except Exception:\n _log.warning('Cleanup failed: key=%s val=%s',\n cleanup_key, cleanup_val, exc_info=True)\n raise\n\n async def _run_one(self, cleanup_key: bytes, cleanup_val: bytes) -> None:\n cleanup = self._cleanup\n if cleanup_key == cleanup.keys.namespaces:\n namespace = cleanup_val\n await self._run_namespace(namespace)\n elif cleanup_key == cleanup.keys.mailboxes:\n namespace, mailbox_id = cleanup_val.split(b'\\x00', 1)\n await self._run_mailbox(namespace, mailbox_id)\n elif cleanup_key == cleanup.keys.messages:\n namespace, mailbox_id, msg_uid = cleanup_val.split(b'\\x00', 2)\n await self._run_message(namespace, mailbox_id, msg_uid)\n elif cleanup_key == cleanup.keys.contents:\n namespace, email_id = cleanup_val.split(b'\\x00', 1)\n await self._run_content(namespace, email_id)\n elif cleanup_key == cleanup.keys.roots:\n wildcard = cleanup_val\n await self._run_root(wildcard)\n\n async def _run_namespace(self, namespace: bytes) -> None:\n redis = self._redis\n cleanup = self._cleanup\n ns_keys = NamespaceKeys(self._global_keys, namespace)\n pipe = unwatch_pipe(redis)\n pipe.hvals(ns_keys.mailboxes)\n _, mailbox_ids = await pipe.execute()\n multi = redis.multi_exec()\n multi.unlink(*ns_keys.keys)\n for mailbox_id in mailbox_ids:\n mbx_keys = MailboxKeys(ns_keys, mailbox_id)\n cleanup.add_mailbox(multi, mbx_keys)\n cleanup.add_root(multi, ns_keys.root)\n await multi.execute()\n\n async def _run_mailbox(self, namespace: bytes, mailbox_id: bytes) -> None:\n redis = self._redis\n cleanup = self._cleanup\n ns_keys = NamespaceKeys(self._global_keys, namespace)\n mbx_keys = MailboxKeys(ns_keys, mailbox_id)\n pipe = unwatch_pipe(redis)\n pipe.smembers(mbx_keys.uids)\n _, msg_uids = await pipe.execute()\n multi = redis.multi_exec()\n multi.unlink(*mbx_keys.keys)\n for msg_uid in msg_uids:\n msg_keys = MessageKeys(mbx_keys, msg_uid)\n cleanup.add_message(multi, msg_keys)\n cleanup.add_root(multi, mbx_keys.root)\n await multi.execute()\n\n async def _run_message(self, namespace: bytes, mailbox_id: bytes,\n msg_uid: bytes) -> None:\n redis = self._redis\n cleanup = self._cleanup\n ns_keys = NamespaceKeys(self._global_keys, namespace)\n mbx_keys = MailboxKeys(ns_keys, mailbox_id)\n msg_keys = MessageKeys(mbx_keys, msg_uid)\n pipe = unwatch_pipe(redis)\n pipe.hget(msg_keys.immutable, b'emailid')\n _, email_id = await pipe.execute()\n multi = redis.multi_exec()\n multi.unlink(*msg_keys.keys)\n if email_id is not None:\n ct_keys = ContentKeys(ns_keys, email_id)\n cleanup.add_content(multi, ct_keys)\n cleanup.add_root(multi, msg_keys.root)\n await multi.execute()\n\n async def _run_content(self, namespace: bytes, email_id: bytes) -> None:\n redis = self._redis\n cleanup = self._cleanup\n ns_keys = NamespaceKeys(self._global_keys, namespace)\n ct_keys = ContentKeys(ns_keys, email_id)\n pipe = unwatch_pipe(redis)\n pipe.ttl(ct_keys.data)\n pipe.hincrby(ns_keys.content_refs, email_id, -1)\n _, ttl, refs = await pipe.execute()\n if ttl < 0 and int(refs or 0) <= 0:\n await redis.expire(ct_keys.data, cleanup.content_expire)\n\n async def _run_root(self, wildcard: bytes) -> None:\n redis = self._redis\n cur = b'0'\n await redis.unwatch()\n while cur:\n cur, keys = await redis.scan(cur, match=wildcard)\n if keys:\n await redis.unlink(*keys)\n","sub_path":"pymap/backend/redis/cleanup.py","file_name":"cleanup.py","file_ext":"py","file_size_in_byte":8833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"210085458","text":"from common.primitives import build_dislosures_sha256_by_file_data\n\nimport json\nimport os\nimport shutil\n\n\nclass TStoredFileParams:\n def __init__(self, bin_file_index=None, file_offset_in_bin_file=None, file_size=None, file_extension=None,\n aux_params=None):\n self.bin_file_index = bin_file_index\n self.file_offset_in_bin_file = file_offset_in_bin_file\n self.file_size = file_size\n self.file_extension = file_extension\n self.aux_params = aux_params\n\n def read_from_string(self, value):\n items = value.split(\";\")\n assert len(items) == 4 or len(items) == 5\n self.bin_file_index, self.file_offset_in_bin_file, self.file_size, self.file_extension = items[0:4]\n self.bin_file_index = int(self.bin_file_index)\n self.file_offset_in_bin_file = int (self.file_offset_in_bin_file)\n self.file_size = int(self.file_size)\n if len(items) == 5:\n self.aux_params = items[4]\n return self\n\n def to_string(self):\n return \"{};{};{};{};{}\".format(\n self.bin_file_index,\n self.file_offset_in_bin_file,\n self.file_size,\n self.file_extension,\n self.aux_params)\n\n def to_json_str(self):\n return json.dumps(self.__dict__)\n\n\nclass TSnowBallFileStorage:\n bin_file_prefix = \"fs\"\n bin_file_extension = \".bin\"\n pdf_cnf_doc_starter = b''\n pdf_cnf_doc_ender = b''\n default_max_bin_file_size = 10 * (2 ** 30)\n\n def clear_stats(self):\n self.stats = {\n 'bin_files_count': 1,\n 'all_file_size': 0,\n 'source_doc_count': 0\n }\n\n # disc_sync_rate means that we sync with disk after each sync_period db update\n # disc_sync_rate=1 means sync after each db update\n def __init__(self, logger, data_folder, max_bin_file_size=default_max_bin_file_size):\n self.logger = logger\n self.max_bin_file_size = max_bin_file_size\n self.saved_file_params = dict()\n self.saved_file_params_file = None\n self.data_folder = data_folder\n self.bin_files = list()\n self.header_file_path = os.path.normpath(os.path.join(self.data_folder, \"header.dat\"))\n self.stats = None\n self.output_bin_file_size = 0\n self.load_from_disk()\n\n def get_bin_file_path(self, i):\n path = os.path.join(self.data_folder, \"{}_{:03d}{}\".format(\n self.bin_file_prefix, i, self.bin_file_extension))\n return os.path.normpath(path)\n\n def looks_like_a_bin_file(self, f):\n return f.startswith(self.bin_file_prefix) and f.endswith(self.bin_file_extension)\n\n def write_key_to_header(self, key, value):\n self.saved_file_params[key] = value\n self.saved_file_params_file.write(\"\\t\".join((key, value)) + \"\\n\")\n self.saved_file_params_file.flush()\n\n def get_stats_file_path(self):\n return self.header_file_path + \".stats\"\n\n def save_stats(self):\n with open(self.get_stats_file_path(), \"w\") as outp:\n json.dump(self.stats, outp, indent=4)\n\n def close_file_storage(self):\n self.save_stats()\n self.saved_file_params_file.close()\n for f in self.bin_files:\n f.close()\n\n def get_all_doc_params(self):\n self.logger.debug(\"read snow ball header {} from the beginning\".format(self.header_file_path))\n self.saved_file_params_file.seek(0)\n for line in self.saved_file_params_file:\n key, value = line.strip().split(\"\\t\")\n yield key, value\n\n def load_from_disk(self):\n assert os.path.exists(self.data_folder)\n self.saved_file_params_file = open(self.header_file_path, \"a+\")\n self.saved_file_params = dict(self.get_all_doc_params())\n\n if os.path.exists(self.get_stats_file_path()):\n with open(self.get_stats_file_path()) as inp:\n self.stats = json.load(inp)\n else:\n self.clear_stats()\n\n assert (len(self.saved_file_params) == self.stats['source_doc_count'])\n\n self.bin_files.clear()\n for i in range(self.stats['bin_files_count'] - 1):\n fp = open(self.get_bin_file_path(i), \"rb\")\n assert fp is not None\n self.bin_files.append(fp)\n\n last_bin_file_path = self.get_bin_file_path(self.stats['bin_files_count'] - 1)\n if os.path.exists(last_bin_file_path):\n self.output_bin_file_size = os.stat(last_bin_file_path).st_size\n self.logger.debug(\"open last bin file for writing: {}, file size={}\".format(\n last_bin_file_path, self.output_bin_file_size))\n else:\n self.output_bin_file_size = 0\n self.logger.debug(\"create bin file for writing: {}\".format(last_bin_file_path))\n fp = open(last_bin_file_path, \"ab+\")\n assert fp is not None\n self.bin_files.append(fp)\n\n file_in_folder = sum(1 for f in os.listdir(self.data_folder) if self.looks_like_a_bin_file(f))\n assert (file_in_folder == self.stats['bin_files_count'])\n\n self.save_stats()\n\n def rewrite_header(self, sha256_list, doc_params):\n assert len(set(sha256_list)) == len(self.saved_file_params)\n assert len(sha256_list) == len(doc_params)\n self.saved_file_params_file.close()\n self.saved_file_params_file = open(self.header_file_path, \"w\")\n self.logger.info(\"write {} doc_params to {}\".format(len(doc_params), self.header_file_path))\n for sha256, header in zip(sha256_list, doc_params):\n self.write_key_to_header(sha256, header.to_string())\n self.saved_file_params_file.close()\n self.saved_file_params_file = open(self.header_file_path, \"a+\")\n self.saved_file_params = dict(self.get_all_doc_params())\n\n def clear_db(self):\n self.close_file_storage()\n\n self.logger.info(\"rm -rf {}\".format(self.data_folder))\n shutil.rmtree(self.data_folder)\n\n self.logger.info(\"mkdir {}\".format(self.data_folder))\n os.mkdir(self.data_folder)\n\n self.clear_stats()\n self.save_stats()\n self.load_from_disk()\n\n def has_saved_file(self, sha256):\n return sha256 in self.saved_file_params\n\n def get_saved_file(self, sha256):\n file_info = self.saved_file_params.get(sha256)\n if file_info is None:\n self.logger.debug(\"cannot find key {}\".format(sha256))\n return None, None\n params = TStoredFileParams().read_from_string(file_info)\n if params.bin_file_index >= len(self.bin_files):\n self.logger.error(\"bad file no {} for key ={} \".format(params.bin_file_index, sha256))\n return None, None\n file_ptr = self.bin_files[params.bin_file_index]\n file_ptr.seek(params.file_offset_in_bin_file)\n file_contents = file_ptr.read(params.file_size)\n return file_contents, params.file_extension\n\n def create_new_bin_file(self):\n self.bin_files[-1].close()\n self.bin_files[-1] = open(self.get_bin_file_path(len(self.bin_files) - 1), \"rb\")\n self.bin_files.append(open(self.get_bin_file_path(len(self.bin_files)), \"ab+\"))\n self.output_bin_file_size = 0\n\n def write_repeat_header_to_bin_file(self, file_bytes, file_extension, output_bin_file):\n # these headers are needed if the main header is lost\n header_repeat = TSnowBallFileStorage.pdf_cnf_doc_starter + \\\n \"{};{}\".format(len(file_bytes), file_extension).encode('latin') + \\\n TSnowBallFileStorage.pdf_cnf_doc_ender\n output_bin_file.write(header_repeat)\n return len(header_repeat)\n\n def update_stats(self, file_bytes_len):\n self.stats['all_file_size'] += file_bytes_len\n self.stats['source_doc_count'] = len(self.saved_file_params)\n self.stats['bin_files_count'] = len(self.bin_files)\n self.save_stats()\n\n def save_file(self, file_bytes, file_extension, aux_params=None, force=False, sha256=None):\n if sha256 is None:\n sha256 = build_dislosures_sha256_by_file_data(file_bytes, file_extension)\n if not force and self.saved_file_params.get(sha256) is not None:\n return\n output_bin_file = self.bin_files[-1]\n if self.output_bin_file_size > self.max_bin_file_size:\n self.create_new_bin_file()\n self.save_stats()\n output_bin_file = self.bin_files[-1]\n try:\n bytes_count = self.write_repeat_header_to_bin_file(file_bytes, file_extension, output_bin_file)\n self.output_bin_file_size += bytes_count\n except IOError as exp:\n self.logger.error(\"cannot write repeat header for {} to {}, exception:{}\".format(\n sha256, output_bin_file.name, exp))\n raise\n try:\n start_file_pos = self.output_bin_file_size\n output_bin_file.write(file_bytes)\n output_bin_file.flush()\n self.output_bin_file_size += len(file_bytes)\n assert output_bin_file.tell() == self.output_bin_file_size\n except IOError as exp:\n self.logger.error(\"cannot write file {}{} (size {}) to {}, exception:{}\".format(\n sha256, file_extension, len(file_bytes), output_bin_file.name, exp))\n raise\n\n try:\n params = TStoredFileParams(\n bin_file_index=len(self.bin_files) - 1,\n file_offset_in_bin_file=start_file_pos,\n file_size=len(file_bytes),\n file_extension=file_extension,\n aux_params=str(aux_params)\n )\n self.write_key_to_header(sha256, params.to_string())\n except Exception as exp:\n self.logger.error(\"cannot add file info {} to {}, exception:{}\".format(\n sha256, self.header_file_path, exp))\n raise\n\n self.logger.debug(\"put {}{} (size={}) to bin file {}\".format(\n sha256, file_extension, len(file_bytes), len(self.bin_files) - 1))\n self.update_stats(len(file_bytes))\n\n def get_stats(self):\n return self.stats\n\n def check_storage(self, file_no=None, fix_file_offset=False, broken_stub=None, file_prefix=None,\n canon_file_extension=None):\n files = list()\n if file_no is not None:\n files.append(self.get_bin_file_path(file_no))\n else:\n for i in range(len(self.bin_files)):\n files.append(self.get_bin_file_path(i))\n sha256_list = list()\n doc_params = list()\n for key, value in self.get_all_doc_params():\n sha256_list.append(key)\n doc_params.append(TStoredFileParams().read_from_string(value))\n self.logger.info(\"read {} doc params from {}\".format(\n len(doc_params), self.header_file_path))\n errors_count = 0\n for file_path in files:\n checker = TSnowBallChecker(self.logger, file_path, doc_params,\n broken_stub=broken_stub, file_prefix=file_prefix,\n fix_offset=fix_file_offset, canon_file_extension=canon_file_extension)\n errors_count += checker.check_file()\n if fix_file_offset:\n self.rewrite_header(sha256_list, doc_params)\n return errors_count\n\n\nclass TSnowBallChecker:\n\n def __init__(self, logger, file_name, doc_params, broken_stub=None, file_prefix=None, fix_offset=False,\n canon_file_extension=None):\n self.logger = logger\n self.file_name = file_name\n self.doc_params = doc_params\n self.broken_stub = broken_stub\n self.canon_file_prefix = file_prefix\n self.file_offset = 0\n self.file_size = os.stat(file_name).st_size\n self.file_ptr = open(file_name, \"rb\")\n basename = os.path.splitext(os.path.basename(file_name))[0]\n assert basename.startswith(\"fs_\")\n self.bin_file_index = int(basename[3:])\n self.fix_offset = fix_offset\n self.canon_file_extension = canon_file_extension\n assert self.canon_file_extension is not None\n\n def read_const(self, canon_str):\n canon_str_len = len(canon_str)\n s = self.file_ptr.read(canon_str_len)\n if s != canon_str:\n message = \"bad constant at file {} offset {}, must be \\\"{}\\\", got \\\"{}\\\"\".format(\n self.file_name, self.file_offset, canon_str, s)\n self.logger.error(message)\n raise Exception(message)\n self.file_offset += canon_str_len\n\n def read_till_separator(self, separator=b';', max_count=15):\n s = b\"\"\n while True:\n ch = self.file_ptr.read(1)\n self.file_offset += 1\n if ch == separator:\n break\n s += ch\n if len(s) > max_count:\n message = \"cannot find separator \\\"{}\\\" at offset {}\".format(separator, self.file_offset)\n self.logger.error(message)\n raise Exception(message)\n return s\n\n def read_bytes(self, bytes_count):\n assert self.file_ptr.tell() == self.file_offset\n s = self.file_ptr.read(bytes_count)\n assert len(s) == bytes_count\n self.file_offset += bytes_count\n return s\n\n def close(self):\n self.file_ptr.close()\n\n def check_file(self):\n for file_index in range(len(self.doc_params)):\n if self.doc_params[file_index].bin_file_index == self.bin_file_index:\n break\n errors_count = 0\n try:\n self.logger.info(\"check {} file_size={}\".format(self.file_name, self.file_size))\n doc_index = 0\n while self.file_offset < self.file_size:\n params = self.doc_params[file_index]\n self.logger.debug(\"doc_index={}, params={}\".format(doc_index, params.to_string()))\n self.read_const(TSnowBallFileStorage.pdf_cnf_doc_starter)\n docx_size = int(self.read_till_separator())\n doc_index += 1\n self.read_const(self.canon_file_extension)\n self.read_const(TSnowBallFileStorage.pdf_cnf_doc_ender)\n params = self.doc_params[file_index]\n if params.bin_file_index != self.bin_file_index:\n errors_count += 1\n self.logger.error(\n \"params.bin_file_index != r.bin_file_index ({} !={}), doc_index={}, params={}\".format(\n params.bin_file_index, self.bin_file_index, doc_index - 1, params.to_string()\n ))\n if params.file_offset_in_bin_file != self.file_offset:\n errors_count += 1\n self.logger.error(\n \"params.file_offset_in_bin_file != r.file_offset ({} !={}), doc_index={}, params={}\".format(\n params.file_offset_in_bin_file, self.file_offset, doc_index - 1, params.to_string()\n ))\n if self.fix_offset:\n self.logger.error(\"set file offset to {}\".format(self.file_offset))\n params.file_offset_in_bin_file = self.file_offset\n\n if params.file_size != docx_size:\n errors_count += 1\n self.logger.error(\n \"params.file_size != docx_size ({} !={}), doc_index={}, params={}\".format(\n params.file_size, docx_size, doc_index - 1, params.to_string()\n ))\n file_index += 1\n file_bytes = self.read_bytes(docx_size)\n comp_prefix = self.canon_file_prefix is None or file_bytes.startswith(self.canon_file_prefix)\n comp_stub = self.broken_stub is None or file_bytes == self.broken_stub\n if not comp_prefix and not comp_stub:\n errors_count += 1\n self.logger.error(\n \"file must start with prefix {}, it starts with {}, doc_index={}, params={} \".format(\n self.canon_file_prefix,\n file_bytes[0:len(self.canon_file_prefix)],\n doc_index - 1,\n params.to_string()\n ))\n return errors_count\n finally:\n self.close()\n","sub_path":"tools/common/snow_ball_file_storage.py","file_name":"snow_ball_file_storage.py","file_ext":"py","file_size_in_byte":16402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"110343135","text":"from datetime import datetime, timedelta\n\n\nclass IntervalError(Exception):\n pass\n\n\ndef get_days_of_interval(interval_type):\n if interval_type == 'day':\n return 1\n elif interval_type == 'week':\n return 7\n elif interval_type == 'month':\n return 30\n else:\n raise IntervalError(f'Interval type \"{interval_type}\" doesn\\'t exist')\n\n\ndef get_interval_dates(number_of_intervals, interval_type):\n\n interval_date = datetime.today().date()\n days = get_days_of_interval(interval_type)\n interval_dates = [(interval_date - timedelta(days=days) * i) for i in range(number_of_intervals)]\n return {'dates': interval_dates}\n\n\ndef get_today_datetime():\n today = datetime.today()\n hours = 0\n days = 0\n return datetime(today.year, today.month, today.day, hours, days)\n\n\ndef get_timestamps(number_of_intervals, interval_type):\n\n end_interval_date = get_today_datetime()\n\n result = []\n\n days = get_days_of_interval(interval_type)\n\n for _ in range(number_of_intervals):\n\n end_timestamp = datetime.timestamp(end_interval_date)\n start_interval_date = end_interval_date - timedelta(days=days)\n start_timestamp = datetime.timestamp(start_interval_date)\n\n result.append((datetime.date(end_interval_date), end_timestamp, start_timestamp))\n\n end_interval_date = start_interval_date\n\n return result\n","sub_path":"tools/time.py","file_name":"time.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"293327434","text":"import os\nfrom functions import *\n\nclass myInit():\n\tdef __init__(self, path):\n\t\tself.path = path\n\t\tif not os.path.exists(path): return\n\t\tf = open(path)\n\t\tlines = f.readlines()\n\t\tf.close()\n\t\tfor line in lines:\n\t\t\tsl = [s.strip().rstrip(\"\\n\").strip() for s in line.split(\":\")]\n\t\t\tif sl[0][-1]==\"+\": setattr(self, sl[0][:-1], sl[1].split(\",\"))\n\t\t\telse : setattr(self, sl[0] , sl[1] )\n\tdef write(self, dictionary = {}):\n\t\tf = open(self.path, \"a\")\n\t\tfor key, val in dictionary.iteritems():\n\t\t\tf.write(key +\" : \"+ val +\"\\n\")\n\t\t\tsetAttrFromLine(self, key +\" : \"+ val)\n\t\tf.close()\n","sub_path":"lib/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"297926245","text":"# Создать список учеников подобной структуры.\n# Определить средний балл оценок по всем предметам, и вывести сведения\n# о студентах, средний балл которых больше 4.\n\npupils = [\n {\n 'firstname': 'Masha',\n 'Group': 42,\n 'physics': 7,\n 'informatics': 6,\n 'history': 8,\n },\n {\n 'firstname': 'Oleg',\n 'Group': 42,\n 'physics': 4,\n 'informatics': 8,\n 'history': 4,\n },\n {\n 'firstname': 'Denis',\n 'Group': 42,\n 'physics': 3,\n 'informatics': 4,\n 'history': 3,\n },\n]\nsumm_phy = 0\nsumm_inf = 0\nsumm_his = 0\n\ngood_pupils = []\n\nfor pupil in pupils:\n summ_phy += pupil['physics']\n summ_inf += pupil['informatics']\n summ_his += pupil['history']\n if (pupil['physics'] + pupil['informatics'] + pupil['history']) / 3 > 4:\n good_pupils.append(pupil)\n\nfor pupil in good_pupils:\n print(f'{pupil[\"firstname\"]} is good')\n\n\namount_of_pupils = len(pupils)\nmean_phy = round(summ_phy / amount_of_pupils, 2)\nmean_inf = round(summ_inf / amount_of_pupils, 2)\nmean_his = round(summ_his / amount_of_pupils, 2)\n\nprint(f'mean for physics is {mean_phy}')\nprint(f'mean for informatics is {mean_inf}')\nprint(f'mean for history {mean_his}')\n","sub_path":"src/Home-_and_classworks/Work_5_and_6[matrices]/cw_5_task_5_6.py","file_name":"cw_5_task_5_6.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"506632172","text":"#-*- coding: utf-8 -*-\nfrom pygraphviz import *\nfrom random import *\nfrom threading import Thread\nimport Image\nimport os\n\n\n\nclass Dijkstra(Thread):\n\n\tdef menorDistancias(self, grafo, v):\n\n\t\t#1º passo: iniciam-se os valores:\n\t\tdistancia = {}\n\t\n\t\tfor no in grafo:\n\t\t\tif no in grafo.neighbors(v): #se o no esta na lista dos vizinhos de v.\n\t\t\t\tdistancia[no] = (float(grafo.get_edge(v, no).attr['label']), v) # armazena o peso da aresta\n\t\t\telse: # nao vizinho ou o mesmo vertice\n\t\t\t\tdistancia[no] = (float('+inf'), None) # distancia = + infinito\n\t\n\t\t# Armazena a distância partindo de v até os outros vértices\n\t\tdistancias = distancia.keys()\n\t\tvertices = [v]\n\t\tdistanciaCopy = distancia.copy()\n\t\tlistaDist = [distanciaCopy]\n\n\t\t\t\t\n\t\twhile (len(distancias) > len(vertices)):\n\t\t\tditems = distancia.items()\n\t\t\tdaux = []\n\t\t\tfor a in ditems:\n\t\t\t\tif a[0] not in vertices:\n\t\t\t\t\tdaux += [a]\n\n\t\t\tmenor = daux[0]\n\t\t\tfor a in daux:\n\t\t\t\tif a[1][0] (menor[1][0]+float(grafo.get_edge(menor[0], no).attr['label'])):\n\t\t\t\t\t\tdistancia[no] = (menor[1][0]+float(grafo.get_edge(menor[0], no).attr['label']), menor[0])\n\n\t\t\t\n\t\t\tdistanciaCopy = distancia.copy()\n\t\t\tlistaDist += [distanciaCopy]\n\n\n\t\treturn (vertices, distancia, listaDist)\n\n\ndef criarGrafo():\n\tgrafo = AGraph(strict=False) # grafo simples = falso\n\tgrafo.add_edge('a','b' , label=\"7\")\n\tgrafo.add_edge('a','c' , label=\"9\")\n\tgrafo.add_edge('b','c' , label=\"10\")\n\tgrafo.add_edge('b','d' , label=\"15\")\n\tgrafo.add_edge('c','d' , label=\"11\")\n\tgrafo.add_edge('d','e' , label=\"6\")\n\tgrafo.add_edge('e','f' , label=\"9\")\n\tgrafo.add_edge('f','c' , label=\"2\")\n\tgrafo.add_edge('a','f' , label=\"14\")\n\t\n\t\n\treturn grafo\n\n\ndef desenharCaminho(grafo, distancia, origem, destino):\n\n\tfor el in grafo.edges():\n\t\tel.attr['color'] = 'black'\n\n\tdestinoAux = destino\n\n\twhile True:\n\t\tptr = distancia.get(destinoAux)[1]\n\t\tgrafo.get_edge(destinoAux, ptr).attr['color'] = 'red'\n\t\tdestinoAux = ptr\n\t\tif ptr == origem:\n\t\t\tbreak\n\n\n\tgrafo.draw(\"grafo.jpg\", \"jpg\", \"dot\")\n\tImage.open(\"grafo.jpg\").show();\n\n\ndef calcularDistancias(grafo):\n\tmatriz = {}\n\tfor v in grafo:\n\t\tdijk = Dijkstra()\n\t\t#calcula menor distancia de v para todos os outros vertices\n\t\tMenorDistancias = dijk.menorDistancias(grafo, v)\n\t\t# Armazena a menor distância partindo de v até os outros vértices\n\t\tmatriz[v] = MenorDistancias\n\n\treturn matriz\n\n\t\t\n\ndef main():\n\n\t# criao grafo\n\tgrafo = criarGrafo() \n\tgrafo.draw(\"grafo.jpg\", \"jpg\", \"dot\")\n\t#exibe o grafo\n\tImage.open(\"grafo.jpg\").show();\n\t#calcula as distancias\n\tmatriz = None\n\tmatriz = calcularDistancias(grafo)\n\t#seleção dos vertices\n\to = raw_input(\"\\nEscolha um vertice de origem: \")\n\t#res = matriz.get(o)\n\td = raw_input(\"Escolha um vertice destino: \")\n\tdesenharCaminho(grafo, matriz[o][1], o, d)\n\n\t\n\nmain()\n","sub_path":"doc/dijkstra.py","file_name":"dijkstra.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"52555167","text":"#!/usr/bin/env python\nimport rospy\nfrom std_msgs.msg import Float32\nfrom BLDC_model import BLDC\nfrom curve import *\n\n# BLDC1: active BLDC \nBLDC1 = BLDC()\n\n# BLDC3:compare BLDC\nBLDC3 = BLDC()\n# for BLDC2 is a reference curve \n# BLDC2 = step_cruve(bound=[-180,180],ramp=250,a=500,period=8)\n# BLDC2 = sin_cruve(period=5,bound=180)\n# BLDC2 = step_cruve_s(period=10)\n\n# for BLDC2 is a random motor \nBLDC2= BLDC()\n\ndef env_BLDC2_currentCallback(data):\n global BLDC2\n BLDC2.set_current(data.data)\n\ndef env_BLDC1_currentCallback(data):\n global BLDC1\n BLDC1.set_current(data.data)\n\ndef env_BLDC3_currentCallback(data):\n global BLDC3\n BLDC3.set_current(data.data)\n\ndef rackforce_recieverCallback(data):\n global BLDC1\n global BLDC3\n BLDC1.force_count = BLDC1.force_count + 1\n if BLDC1.force_count >= 100:\n print(\"force: \",data.data)\n BLDC1.force_count = 0\n BLDC1.force = data.data\n BLDC3.force_count = BLDC3.force_count + 1\n BLDC3.force = data.data\n\ndef main():\n rospy.init_node('simulation_train_env', anonymous=True)\n rate = rospy.Rate(500)\n count = 0\n count_max = 5\n global BLDC1\n global BLDC2\n global BLDC3\n # communication with brain\n env_BLDC1_s_pub = rospy.Publisher('env_BLDC1_s', Float32, queue_size=100)\n env_BLDC1_v_pub = rospy.Publisher('env_BLDC1_v', Float32, queue_size=100)\n\n env_BLDC2_s_pub = rospy.Publisher('env_BLDC2_s', Float32, queue_size=100)\n env_BLDC2_v_pub = rospy.Publisher('env_BLDC2_v', Float32, queue_size=100)\n\n env_BLDC3_s_pub = rospy.Publisher('env_BLDC3_s', Float32, queue_size=100)\n env_BLDC3_v_pub = rospy.Publisher('env_BLDC3_v', Float32, queue_size=100)\n\n env_BLDC12_ds_pub = rospy.Publisher('env_BLDC12_ds', Float32, queue_size=100)\n env_BLDC12_dv_pub = rospy.Publisher('env_BLDC12_dv', Float32, queue_size=100)\n\n env_BLDC32_ds_pub = rospy.Publisher('env_BLDC32_ds', Float32, queue_size=100)\n env_BLDC32_dv_pub = rospy.Publisher('env_BLDC32_dv', Float32, queue_size=100)\n\n rospy.Subscriber(\"env_BLDC1_current\", Float32, env_BLDC1_currentCallback)\n rospy.Subscriber(\"env_BLDC2_current\", Float32, env_BLDC2_currentCallback) # BLDC2 is random motor \n rospy.Subscriber(\"env_BLDC3_current\", Float32, env_BLDC3_currentCallback)\n # communication with matlab \n roadWheelAngle_pub = rospy.Publisher(\"roadWheelAngle\",Float32, queue_size=100)\n rospy.Subscriber(\"rackforce_feedback\", Float32, rackforce_recieverCallback)\n\n while not rospy.is_shutdown():\n count = count + 1\n if count >= count_max:\n count = 0\n # # for sample data \n # env_BLDC1_s_pub.publish(BLDC1.s_measure())\n # env_BLDC1_v_pub.publish(BLDC1.v_measure())\n\n # env_BLDC2_s_pub.publish(BLDC2.s_measure())\n # env_BLDC2_v_pub.publish(BLDC2.v_measure())\n\n # env_BLDC3_s_pub.publish(BLDC3.s_measure())\n # env_BLDC3_v_pub.publish(BLDC3.v_measure())\n # for real data \n env_BLDC1_s_pub.publish(BLDC1.s)\n env_BLDC2_s_pub.publish(BLDC2.s)\n env_BLDC1_v_pub.publish(BLDC1.v)\n env_BLDC2_v_pub.publish(BLDC2.v)\n env_BLDC3_s_pub.publish(BLDC3.s)\n env_BLDC3_v_pub.publish(BLDC3.v)\n roadWheelAngle_pub.publish(BLDC2.s)\n\n BLDC12_ds = BLDC1.s - BLDC2.s\n BLDC12_dv = BLDC1.v - BLDC2.v\n BLDC32_ds = BLDC3.s - BLDC2.s\n BLDC32_dv = BLDC3.v - BLDC2.v\n\n env_BLDC12_ds_pub.publish(BLDC12_ds)\n env_BLDC12_dv_pub.publish(BLDC12_dv)\n env_BLDC32_ds_pub.publish(BLDC32_ds)\n env_BLDC32_dv_pub.publish(BLDC32_dv)\n\n ######## print list ################\n # print(\"env_BLDC1_s: \"+str(BLDC1.s))\n # print(\"BLDC1_V: \"+str(BLDC1.v))\n # print(\"BLDC1_C: \"+str(BLDC1.current))\n # print(\"BLDC2_s: \"+str(BLDC2.s))\n # print(\"BLDC2_V: \"+str(BLDC2.v))\n # print(\"BLDC2_C: \"+str(BLDC2.current))\n # print(\"BLDC3_s: \"+str(BLDC3.s))\n # print(\"BLDC3_V: \"+str(BLDC3.v))\n # print(\"BLDC3_C: \"+str(BLDC3.current))\n\n BLDC1.step(0.002)\n BLDC2.step(0.002)\n BLDC3.step(0.002)\n rate.sleep()\n\n\nif __name__ == '__main__':\n main()","sub_path":"src/rl_ddpg/src/simulation_test_env.py","file_name":"simulation_test_env.py","file_ext":"py","file_size_in_byte":4293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"571011312","text":"# -*- coding=utf-8 -*-\n'''\n有点像 reverse polish notation 的变种,计算一个表达式的值的。\n要求自行设计表达式的数���结构并计算表达式的值。\n\n有几种特殊情况\n1. 单输入一个数,比如 [0],是合法,结果为0;\n2. 单输入一个运算符也是合法的。 无数字运算的 '+', '-', '/' 结果为 0,\n单个 '*' 的结果为 1.\n3. 一个运算符可以有好几个计算数字。 比如输入为 ['+', 1, 2, 3],\n结果为1 + 2 + 3 = 6.\n4. 表达式可嵌套,['+', 1, 2, ['*', 1, 3]], 这样结果为 1 + 2 + 1 * 2 = 5.\n\n输入一定合法,不用考虑给了两个连续数字却没有运算符的情况,也不用考虑除数为0的情况。\n\n我的做法为新建一个 Expression 类,用于解决输入包含运算符,数字,\n或者expression三种情况,这样输入就可以为一个Expresssion 的List,\n再用一个Queue来决定问题。不知道有没有大神有更好的做法。\n'''\n\n\nclass Solution:\n\n def eval(self, expr):\n operator = expr[0]\n expr = expr[1:]\n evaled_expr = []\n for it in expr:\n if isinstance(it, list):\n evaled = self.eval(it)\n evaled_expr.append(evaled)\n else:\n evaled_expr.append(it)\n res = 0\n if operator == '+':\n res = sum(evaled_expr)\n elif operator == '*':\n res = 1\n for it in evaled_expr:\n res *= it\n elif operator == '-':\n res = evaled_expr[0] if len(evaled_expr) > 0 else 0\n for it in evaled_expr[1:]:\n res -= it\n elif operator == '/':\n res = evaled_expr[0] if len(evaled_expr) > 0 else 0\n for it in evaled_expr[1:]:\n res /= it\n return res\n","sub_path":"Practice/Interview/Zenefits/eval/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"349646982","text":"#!/usr/bin/python\n\nimport logging\n_logger = logging.getLogger(__name__)\n\nimport os, sys, subprocess, threading\nimport re, codecs, time\n\nLIB = [r\"C:\\auto\\git\\lib\"]\nfor path in LIB:\n if path not in sys.path: sys.path.append(path)\n\nfrom tm import winutils, web_url\n\nAVAS_TOOLS = os.path.join( os.path.dirname(__file__), \"avastools\")\n\nfrom ..wfbssclient import ClientAgent\n\nclass Command(object):\n def __init__(self, cmd):\n self.cmd = cmd\n self.process = None\n\n def run(self, timeout=60):\n def target():\n self.process = subprocess.Popen(self.cmd, shell=True)\n self.process.communicate()\n\n thread = threading.Thread(target=target)\n thread.start()\n\n thread.join(timeout)\n if thread.is_alive():\n try:\n subprocess.call(['taskkill', '/F', '/T', '/PID', str(self.process.pid)])\n except:\n _logger.debug(\"kill cmd %s failed\" % str(self.cmd))\n self.process.terminate()\n \n return self.process.returncode\n\nclass _AVAS_SAMPLE(object):\n def __init__(self, **kwargs):\n self.policy = kwargs.get(\"policy\")\n self.field = kwargs.get(\"field\")\n self.sample = kwargs.get(\"sample\")\n self.program = kwargs.get(\"program\")\n\nclass _AVAS_HANDLER(object):\n SAMPLE_PATH = os.path.join(LIB[0], r'tm\\virus_sample')\n EXTRACT_TOOL_PATH = os.path.join(AVAS_TOOLS, \"Extract.exe\")\n #This is the item list of Anti-Virus client log\n AV_LOG_ITEM_MAPPING = ['Date', # YYYY/MM/DD\n 'Time', # HH/MM\n 'Threat', # Virus Name\n 'ScanActionResult', # Both action success and fail will have different Result \n 'ScanType', # Realtime, manual scan etc. \n 'Seen', # Inactive parameter\n 'Directory', # Where you caught this virus\n 'ProgramName', # Virus program name\n 'NullParameter1', # Blank parameter (inactive)\n 'Timestamp', # unix timestamp, UTP+0\n 'NullParameter2'] # Blank Parameter (inactive) \n \n #This is the item list of Anti-Spyware client log \n AS_LOG_ITEM_MAPPING = ['Date', # YYYY/MM/DD\n 'Time', # HH/MM\n 'Threat', # Virus Name\n 'ScanActionResult', # Both action success and fail will have different Result \n 'ScanType', # Realtime, manual scan etc. \n 'Seen', # Inactive parameter\n 'UnknownParameter', # Lack of information\n 'DateTimeThreat', # Combined information\n 'UserName', # User who logged in\n 'Timestamp'] # unix timestamp, UTP+0\n \n IS_X86 = not os.environ.has_key(\"PROGRAMFILES(X86)\")\n \n def __init__(self, **kwargs):\n self.package = kwargs.get(\"package\")\n self.mapping = kwargs.get(\"mapping\")\n self.password = kwargs.get(\"password\")\n self.extract_dest = kwargs.get(\"extract_dest\")\n self.sample_folder = kwargs.get(\"sample_folder\")\n \n @property\n def AV_LOG_PATH(self):\n return os.path.join( ClientAgent().get_client_installation_dir(), 'Misc', \"pccnt35.log\")\n \n @property\n def AS_LOG_PATH(self):\n return os.path.join( ClientAgent().get_client_installation_dir(), 'Misc', \"spyware.log\")\n \n def is_client_av_log_write(self, name, exec_unix_ts):\n value = self.mapping.get(name).policy\n field = self.mapping.get(name).field\n return self.is_av_log_write(value, exec_unix_ts, field)\n \n def is_client_as_log_write(self, name, exec_unix_ts):\n value = self.mapping.get(name).policy\n field = self.mapping.get(name).field\n return self.is_as_log_write(value, exec_unix_ts, field) \n \n def execute_sample(self, sample_name):\n _logger.debug(sample_name)\n timestamp = int(time.time())\n self.extract_sample()\n sample_path = os.path.join(self.extract_dest, self.sample_folder, self.mapping.get(sample_name).sample)\n _logger.debug(sample_path)\n return self.execute_avas_sample(sample_path=sample_path)\n \n def extract_sample(self, sample_name):\n # extract to destination folder\n timestamp = int(time.time())\n src = os.path.join(self.SAMPLE_PATH, self.package)\n err_level = winutils.extract_to_folder(src, self.extract_dest, self.password)\n if err_level != 0:\n raise Exception('extract sample package fail') \n time.sleep(30)\n return timestamp\n \n def extract_ole_sample(self, sample_name):\n # extract to destination folder\n timestamp = int(time.time())\n src = os.path.join(self.SAMPLE_PATH, self.package)\n winutils.extract_to_folder(src, self.extract_dest, self.password)\n return timestamp \n \n def is_av_log_write(self, expect_value, exec_unix_ts, field='Threat'):\n import unicodedata\n\n if not os.path.exists(self.AV_LOG_PATH):\n return False\n \n with codecs.open(self.AV_LOG_PATH, encoding='utf-8') as f:\n lines = f.readlines()\n _logger.debug(lines)\n\n # check every line match the timestamp and expect_value \n for line in lines:\n items = line.split('<;>')\n if len(items) > 2: # line is not empty\n\n index_of_ts = self.AV_LOG_ITEM_MAPPING.index('Timestamp')\n index_of_event_id = self.AV_LOG_ITEM_MAPPING.index(field)\n \n log_ts = int(items[index_of_ts].replace('\\x00',''))\n log_field_value = items[index_of_event_id].replace('\\x00','')\n \n _logger.debug('expect event id and tmestamp: {0}, {1}'.\\\n format(exec_unix_ts, expect_value))\n _logger.debug('event id and tmestamp in log file: {0}, {1}'.\\\n format(log_ts, log_field_value))\n # less than delta\n if (exec_unix_ts <= log_ts) and log_field_value == expect_value:\n _logger.debug(\"Log match the expected policy and time stamp!\")\n time.sleep(10)\n return True\n\n return False\n \n def is_as_log_write(self, expect_value, exec_unix_ts, field='Threat'):\n import unicodedata\n\n if not os.path.exists(self.AS_LOG_PATH):\n return False\n\n with codecs.open(self.AS_LOG_PATH, encoding='utf-8') as f:\n lines = f.readlines()\n _logger.debug(lines)\n \n # check every line match the timestamp and expect_value \n for line in lines:\n items = line.split('<;>')\n if len(items) > 2: # line is not empty\n\n index_of_ts = self.AS_LOG_ITEM_MAPPING.index('Timestamp')\n index_of_event_id = self.AS_LOG_ITEM_MAPPING.index(field)\n \n log_ts = int(items[index_of_ts].replace('\\x00',''))\n log_field_value = items[index_of_event_id].replace('\\x00','')\n \n _logger.debug('expect event id and timestamp: {0}, {1}'.\\\n format(exec_unix_ts, expect_value))\n _logger.debug('event id and timestamp in log file: {0}, {1}'.\\\n format(log_ts, log_field_value))\n # less than delta\n if (exec_unix_ts <= log_ts) and log_field_value == expect_value:\n _logger.debug(\"Log match the expected policy and time stamp!\")\n time.sleep(10)\n return True\n\n return False\n \n def execute_avas_sample(self, sample_path):\n timestamp = int(time.time())\n cur_dir = os.getcwd()\n os.chdir(os.path.dirname(sample_path))\n cmd = '\"{0}\"'.format(sample_path)\n _logger.info('Execute:{0}'.format(cmd))\n command = Command(cmd)\n err_level = command.run(timeout=60)\n os.chdir(cur_dir)\n time.sleep(30)\n return timestamp\n \n\nclass AVAS_VIRUS_HANDLER(_AVAS_HANDLER):\n \n def __init__(self):\n package = \"Virus.7z\"\n sample_folder = os.path.splitext(package)[0]\n _AVAS_Virus_TESTING_SAMPLE = { 'Joke': _AVAS_SAMPLE(policy='JOKE_TEST_VIRUS', field='Threat', sample='virus.bat', program='Joke.exe'),\n 'Packer': _AVAS_SAMPLE(policy='PE_TEST_VIRUS', field='Threat', sample='virus.bat', program='Packer.exe'),\n 'TestVirus': _AVAS_SAMPLE(policy='TESTPOLY', field='Threat', sample='virus.bat', program='TestVirus.exe'),\n 'Trojan': _AVAS_SAMPLE(policy='REG_TEST_VIRUS', field='Threat', sample='virus.bat', program='Trojan.reg'),\n 'VBS': _AVAS_SAMPLE(policy='VBS_TEST_VIRUS', field='Threat', sample='virus.bat', program='Virus.vbs'),\n 'OtherMalware': _AVAS_SAMPLE(policy='KYLG_CCFR_DOS_TEST.A', field='Threat', sample='virus.bat', program='Other Malware.COM'),\n\t\t\t\t\t\t\t\t\t 'ProbableMalware': _AVAS_SAMPLE(policy='GEN_CCFR_DOS_TEST.A', field='Threat', sample='virus.bat', program='Probable Malware.COM'),\n\t\t\t\t\t\t\t\t\t 'Eicar': _AVAS_SAMPLE(policy='Eicar_test_file', field='Threat', sample='CompressedSample', program='eicar_2.zip'),\n\t\t\t\t\t\t\t\t\t 'HTML_TEST_VIRUS': _AVAS_SAMPLE(policy='HTML_TEST_VIRUS', field='Threat', sample='virus.bat', program='test_vir.htm')\n\t\t\t\t\t\t\t\t\t }\n _AVAS_HANDLER.__init__(self, \n package=package, \n mapping=_AVAS_Virus_TESTING_SAMPLE,\n password=\"virus\",\n extract_dest=os.environ.get('tmp'),\n sample_folder=sample_folder)\n\nclass AVAS_OLE_VIRUS_HANDLER(_AVAS_HANDLER):\n \n def __init__(self):\n package = \"OLE_test_virus.7z\"\n sample_folder = os.path.splitext(package)[0]\n _AVAS_Virus_TESTING_SAMPLE = { 'OleSample': _AVAS_SAMPLE(policy='W97M_TEST_VIRUS', field='Threat', sample='OleSample', program='02_{{w97.doc}.xls}.doc') }\n _AVAS_HANDLER.__init__(self, \n package=package, \n mapping=_AVAS_Virus_TESTING_SAMPLE,\n password=\"virus\",\n extract_dest=os.environ.get('tmp'),\n sample_folder=sample_folder)\n\n\nclass AVAS_SPYWARE_HANDLER(_AVAS_HANDLER):\n \n def __init__(self):\n package = \"Spyware.7z\"\n sample_folder = os.path.splitext(package)[0]\n _AVAS_SPYWARE_TESTING_SAMPLE = { 'spyware': _AVAS_SAMPLE(policy='Spyware_Test_File', field='Threat', sample='spyware.bat', program='Spyware.exe') }\n _AVAS_HANDLER.__init__(self, \n package=package, \n mapping=_AVAS_SPYWARE_TESTING_SAMPLE,\n password=\"virus\",\n extract_dest=os.environ.get('tmp'),\n sample_folder=sample_folder)\n\nclass WfbssClientAVAS(object):\n SAMPLE_PATH = os.path.join(LIB[0], 'tm\\\\virus_sample')\n EXTRACT_TOOL_PATH = os.path.join(AVAS_TOOLS, \"Extract.exe\")\n \n def __init__(self):\n '''\n '''\n self.avas_virus_handler = AVAS_VIRUS_HANDLER()\n self.avas_ole_virus_handler = AVAS_OLE_VIRUS_HANDLER()\n self.avas_spyware_handler = AVAS_SPYWARE_HANDLER()\n \nif __name__ == '__main__':\n '''\n '''\n logging.basicConfig(\n format = '[%(asctime)s] %(levelname)s [%(funcName)s] - %(message)s [%(filename)s:%(lineno)d]',\n level = logging.DEBUG,\n datefmt = '%y-%m-%d %H:%M:%S'\n )\n \n inst = WfbssClientAVAS()\n ","sub_path":"lib/tm/wfbssclient/wfbssclientavas.py","file_name":"wfbssclientavas.py","file_ext":"py","file_size_in_byte":12555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"28231597","text":"import sys\nsys.stdin = open('4873.txt', 'r')\n\n# T = int(input())\n# for tc in range(1, T+1):\n# characters = list(input())\n# stack = []\n#\n# for i in range(len(characters)):\n# # stack = [] 거나, stack의 마지막 값이 characters[i]과 다르다면,\n# if not stack or stack[-1] != characters[i]:\n# stack.append(characters[i])\n#\n# # if가 실행안되는 경우, 다음을 실행\n# # stack = [data] 거나, stack의 마지막 값이 characters[i]와 같다면,\n# elif stack and stack[-1] == characters[i]:\n# stack.pop()\n#\n# '''\n# []\n# ['A']\n# ['A', 'B']\n# ['A']\n# '''\n#\n# print(f'#{tc}', len(stack))\n#\n\n\nfor tc in range(1, int(input())+1):\n letters = list(input())\n\n stack = []\n\n for i in range(len(letters)):\n if not stack or stack[-1] != letters[i]:\n stack.append(letters[i])\n\n elif stack or stack[-1] == letters[i]:\n stack.pop()\n\n print(stack)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"SWexpertacademy/제출/서울2반8월20일정승원/4873.py","file_name":"4873.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"379375247","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"Tests for pendingdeferred.py\n\"\"\"\n__docformat__ = \"restructuredtext en\"\n\n#-------------------------------------------------------------------------------\n# Copyright (C) 2005 Fernando Perez \n# Brian E Granger \n# Benjamin Ragan-Kelley \n#\n# Distributed under the terms of the BSD License. The full license is in\n# the file COPYING, distributed as part of this software.\n#-------------------------------------------------------------------------------\n\n#-------------------------------------------------------------------------------\n# Imports\n#-------------------------------------------------------------------------------\n\nfrom ipython1.testutils import tcommon\nfrom ipython1.testutils.tcommon import *\n\nfrom ipython1.testutils.util import DeferredTestCase\n\nfrom twisted.internet import defer\nimport ipython1.kernel.pendingdeferred as pd\nfrom ipython1.kernel import error\n\n\n#-------------------------------------------------------------------------------\n# Setup for inline and standalone doctests\n#-------------------------------------------------------------------------------\n\n\n# If you have standalone doctests in a separate file, set their names in the\n# dt_files variable (as a single string or a list thereof):\ndt_files = []\n\n# If you have any modules whose docstrings should be scanned for embedded tests\n# as examples accorging to standard doctest practice, set them here (as a\n# single string or a list thereof):\ndt_modules = []\n\n#-------------------------------------------------------------------------------\n# Regular Unittests\n#-------------------------------------------------------------------------------\n\n\nclass Foo(object):\n \n def bar(self, bahz):\n return defer.succeed('blahblah' + bahz)\n\nclass TwoPhaseFoo(pd.PendingDeferredAdapter):\n \n def __init__(self, foo):\n self.foo = foo\n pd.PendingDeferredAdapter.__init__(self)\n\n @pd.twoPhase\n def bar(self, bahz):\n return self.foo.bar(bahz)\n\n\nclass PendingDeferredManagerTest(DeferredTestCase):\n \n def setUp(self):\n pass\n \n def tearDown(self):\n pass\n \n def testBasic(self):\n pdm = pd.PendingDeferredManager(0)\n for i in range(10):\n id = pdm.getNextDeferredID()\n self.assert_(id==i)\n dDict = {}\n for i in range(10):\n d = defer.Deferred()\n pdm.savePendingDeferred(i, d)\n dDict[i] = d\n for i in range(5):\n d = pdm.getPendingDeferred(i,block=True)\n dDict[i].callback('foo')\n d.addCallback(lambda r: self.assert_(r=='foo'))\n for i in range(5,10):\n d = pdm.getPendingDeferred(i,block=False)\n d.addErrback(lambda f: self.assertRaises(error.ResultNotCompleted, f.raiseException))\n for i in range(5,10):\n dDict[i].callback('foo')\n d = pdm.getPendingDeferred(i,block=False)\n d.addCallback(lambda r: self.assert_(r=='foo'))\n for i in range(10):\n d = pdm.getPendingDeferred(i,False)\n d.addErrback(lambda f: self.assertRaises(error.InvalidDeferredID, f.raiseException))\n \n def testPDA(self):\n f = Foo()\n tpf = TwoPhaseFoo(f)\n clientID = tpf.registerClient()\n self.assert_(clientID==0)\n d = tpf.bar(clientID, True, 'hi there')\n d.addCallback(lambda r: self.assertEquals(r, 'blahblahhi there'))\n d = tpf.bar(clientID, False, 'foobah')\n d.addCallback(lambda r: \n self.assertEquals(len(tpf.pdManagers[clientID].pendingDeferreds.keys()), 1))\n d.addCallback(lambda r: tpf.flush(clientID))\n d.addCallback(lambda r: \n self.assertEquals(len(tpf.pdManagers[clientID].pendingDeferreds.keys()), 0))\n tpf.unregisterClient(clientID)\n d = tpf.bar(1000, True, 'boo')\n d.addErrback(lambda f: self.assertRaises(error.InvalidClientID, f.raiseException))\n \n \n \n#-------------------------------------------------------------------------------\n# Regular Unittests\n#-------------------------------------------------------------------------------\n\n# This ensures that the code will run either standalone as a script, or that it\n# can be picked up by Twisted's `trial` test wrapper to run all the tests.\nif tcommon.pexpect is not None:\n if __name__ == '__main__':\n unittest.main(testLoader=IPDocTestLoader(dt_files,dt_modules))\n else:\n testSuite = lambda : makeTestSuite(__name__,dt_files,dt_modules)\n","sub_path":"ipython/branches/saw/ipython1/kernel/test/test_pendingdeferred.py","file_name":"test_pendingdeferred.py","file_ext":"py","file_size_in_byte":4671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"16995439","text":"def max2(x,y):\n return x if x > y else y\nN = int(input())\nD = []\nfor i, a in enumerate(map(int, input().split())):\n D.append((a<<11) + i)\nD.sort(reverse=True)\ndp = [0]*(N+1)\nfor i, d in enumerate(D,start=1):\n x, a = d%(1<<11),d>>11\n for j in reversed(range(0, i+1)):\n dp[j] = max2((dp[j-1]+a*(x-(j-1)))*(j-1>=0), (dp[j]+a*(N-(i-j)-x))*(j<=i-1))\nprint(max(dp))","sub_path":"Python_codes/p02709/s002624789.py","file_name":"s002624789.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"207807818","text":"\"\"\"\nTest SBTarget APIs.\n\"\"\"\n\nfrom __future__ import print_function\n\n\nimport unittest2\nimport os\nimport lldb\nfrom lldbsuite.test.decorators import *\nfrom lldbsuite.test.lldbtest import *\nfrom lldbsuite.test import lldbutil\n\n\nclass TargetAPITestCase(TestBase):\n\n mydir = TestBase.compute_mydir(__file__)\n\n def setUp(self):\n # Call super's setUp().\n TestBase.setUp(self)\n # Find the line number to of function 'c'.\n self.line1 = line_number(\n 'main.c', '// Find the line number for breakpoint 1 here.')\n self.line2 = line_number(\n 'main.c', '// Find the line number for breakpoint 2 here.')\n self.line_main = line_number(\n \"main.c\", \"// Set a break at entry to main.\")\n\n # rdar://problem/9700873\n # Find global variable value fails for dwarf if inferior not started\n # (Was CrashTracer: [USER] 1 crash in Python at _lldb.so: lldb_private::MemoryCache::Read + 94)\n #\n # It does not segfaults now. But for dwarf, the variable value is None if\n # the inferior process does not exist yet. The radar has been updated.\n #@unittest232.skip(\"segmentation fault -- skipping\")\n @add_test_categories(['pyapi'])\n def test_find_global_variables(self):\n \"\"\"Exercise SBTarget.FindGlobalVariables() API.\"\"\"\n d = {'EXE': 'b.out'}\n self.build(dictionary=d)\n self.setTearDownCleanup(dictionary=d)\n self.find_global_variables('b.out')\n\n @add_test_categories(['pyapi'])\n def test_find_compile_units(self):\n \"\"\"Exercise SBTarget.FindCompileUnits() API.\"\"\"\n d = {'EXE': 'b.out'}\n self.build(dictionary=d)\n self.setTearDownCleanup(dictionary=d)\n self.find_compile_units(self.getBuildArtifact('b.out'))\n\n @add_test_categories(['pyapi'])\n @expectedFailureAll(oslist=[\"windows\"], bugnumber=\"llvm.org/pr24778\")\n def test_find_functions(self):\n \"\"\"Exercise SBTarget.FindFunctions() API.\"\"\"\n d = {'EXE': 'b.out'}\n self.build(dictionary=d)\n self.setTearDownCleanup(dictionary=d)\n self.find_functions('b.out')\n\n @add_test_categories(['pyapi'])\n def test_get_description(self):\n \"\"\"Exercise SBTarget.GetDescription() API.\"\"\"\n self.build()\n self.get_description()\n\n @add_test_categories(['pyapi'])\n @expectedFailureAll(oslist=[\"windows\"], bugnumber='llvm.org/pr21765')\n def test_resolve_symbol_context_with_address(self):\n \"\"\"Exercise SBTarget.ResolveSymbolContextForAddress() API.\"\"\"\n self.build()\n self.resolve_symbol_context_with_address()\n\n @add_test_categories(['pyapi'])\n def test_get_platform(self):\n d = {'EXE': 'b.out'}\n self.build(dictionary=d)\n self.setTearDownCleanup(dictionary=d)\n target = self.create_simple_target('b.out')\n platform = target.platform\n self.assertTrue(platform, VALID_PLATFORM)\n\n @add_test_categories(['pyapi'])\n def test_get_data_byte_size(self):\n d = {'EXE': 'b.out'}\n self.build(dictionary=d)\n self.setTearDownCleanup(dictionary=d)\n target = self.create_simple_target('b.out')\n self.assertEqual(target.data_byte_size, 1)\n\n @add_test_categories(['pyapi'])\n def test_get_code_byte_size(self):\n d = {'EXE': 'b.out'}\n self.build(dictionary=d)\n self.setTearDownCleanup(dictionary=d)\n target = self.create_simple_target('b.out')\n self.assertEqual(target.code_byte_size, 1)\n\n @add_test_categories(['pyapi'])\n def test_resolve_file_address(self):\n d = {'EXE': 'b.out'}\n self.build(dictionary=d)\n self.setTearDownCleanup(dictionary=d)\n target = self.create_simple_target('b.out')\n\n # find the file address in the .data section of the main\n # module\n data_section = self.find_data_section(target)\n data_section_addr = data_section.file_addr\n\n # resolve the above address, and compare the address produced\n # by the resolution against the original address/section\n res_file_addr = target.ResolveFileAddress(data_section_addr)\n self.assertTrue(res_file_addr.IsValid())\n\n self.assertEqual(data_section_addr, res_file_addr.file_addr)\n\n data_section2 = res_file_addr.section\n self.assertIsNotNone(data_section2)\n self.assertEqual(data_section.name, data_section2.name)\n\n @add_test_categories(['pyapi'])\n def test_read_memory(self):\n d = {'EXE': 'b.out'}\n self.build(dictionary=d)\n self.setTearDownCleanup(dictionary=d)\n target = self.create_simple_target('b.out')\n\n breakpoint = target.BreakpointCreateByLocation(\n \"main.c\", self.line_main)\n self.assertTrue(breakpoint, VALID_BREAKPOINT)\n\n # Put debugger into synchronous mode so when we target.LaunchSimple returns\n # it will guaranteed to be at the breakpoint\n self.dbg.SetAsync(False)\n\n # Launch the process, and do not stop at the entry point.\n process = target.LaunchSimple(\n None, None, self.get_process_working_directory())\n\n # find the file address in the .data section of the main\n # module\n data_section = self.find_data_section(target)\n sb_addr = lldb.SBAddress(data_section, 0)\n error = lldb.SBError()\n content = target.ReadMemory(sb_addr, 1, error)\n self.assertTrue(error.Success(), \"Make sure memory read succeeded\")\n self.assertEqual(len(content), 1)\n\n def create_simple_target(self, fn):\n exe = self.getBuildArtifact(fn)\n target = self.dbg.CreateTarget(exe)\n self.assertTrue(target, VALID_TARGET)\n return target\n\n def find_data_section(self, target):\n mod = target.GetModuleAtIndex(0)\n data_section = None\n for s in mod.sections:\n sect_type = s.GetSectionType()\n if sect_type == lldb.eSectionTypeData:\n data_section = s\n break\n elif sect_type == lldb.eSectionTypeContainer:\n for i in range(s.GetNumSubSections()):\n ss = s.GetSubSectionAtIndex(i)\n sect_type = ss.GetSectionType()\n if sect_type == lldb.eSectionTypeData:\n data_section = ss\n break\n\n self.assertIsNotNone(data_section)\n return data_section\n\n def find_global_variables(self, exe_name):\n \"\"\"Exercise SBTaget.FindGlobalVariables() API.\"\"\"\n exe = self.getBuildArtifact(exe_name)\n\n # Create a target by the debugger.\n target = self.dbg.CreateTarget(exe)\n self.assertTrue(target, VALID_TARGET)\n\n # rdar://problem/9700873\n # Find global variable value fails for dwarf if inferior not started\n # (Was CrashTracer: [USER] 1 crash in Python at _lldb.so: lldb_private::MemoryCache::Read + 94)\n #\n # Remove the lines to create a breakpoint and to start the inferior\n # which are workarounds for the dwarf case.\n\n breakpoint = target.BreakpointCreateByLocation('main.c', self.line1)\n self.assertTrue(breakpoint, VALID_BREAKPOINT)\n\n # Now launch the process, and do not stop at entry point.\n process = target.LaunchSimple(\n None, None, self.get_process_working_directory())\n self.assertTrue(process, PROCESS_IS_VALID)\n # Make sure we hit our breakpoint:\n thread_list = lldbutil.get_threads_stopped_at_breakpoint(\n process, breakpoint)\n self.assertTrue(len(thread_list) == 1)\n\n value_list = target.FindGlobalVariables(\n 'my_global_var_of_char_type', 3)\n self.assertTrue(value_list.GetSize() == 1)\n my_global_var = value_list.GetValueAtIndex(0)\n self.DebugSBValue(my_global_var)\n self.assertTrue(my_global_var)\n self.expect(my_global_var.GetName(), exe=False,\n startstr=\"my_global_var_of_char_type\")\n self.expect(my_global_var.GetTypeName(), exe=False,\n startstr=\"char\")\n self.expect(my_global_var.GetValue(), exe=False,\n startstr=\"'X'\")\n\n # While we are at it, let's also exercise the similar\n # SBModule.FindGlobalVariables() API.\n for m in target.module_iter():\n if os.path.normpath(m.GetFileSpec().GetDirectory()) == self.getBuildDir() and m.GetFileSpec().GetFilename() == exe_name:\n value_list = m.FindGlobalVariables(\n target, 'my_global_var_of_char_type', 3)\n self.assertTrue(value_list.GetSize() == 1)\n self.assertTrue(\n value_list.GetValueAtIndex(0).GetValue() == \"'X'\")\n break\n\n def find_compile_units(self, exe):\n \"\"\"Exercise SBTarget.FindCompileUnits() API.\"\"\"\n source_name = \"main.c\"\n\n # Create a target by the debugger.\n target = self.dbg.CreateTarget(exe)\n self.assertTrue(target, VALID_TARGET)\n\n list = target.FindCompileUnits(lldb.SBFileSpec(source_name, False))\n # Executable has been built just from one source file 'main.c',\n # so we may check only the first element of list.\n self.assertTrue(\n list[0].GetCompileUnit().GetFileSpec().GetFilename() == source_name)\n\n def find_functions(self, exe_name):\n \"\"\"Exercise SBTaget.FindFunctions() API.\"\"\"\n exe = self.getBuildArtifact(exe_name)\n\n # Create a target by the debugger.\n target = self.dbg.CreateTarget(exe)\n self.assertTrue(target, VALID_TARGET)\n\n list = target.FindFunctions('c', lldb.eFunctionNameTypeAuto)\n self.assertTrue(list.GetSize() == 1)\n\n for sc in list:\n self.assertTrue(\n sc.GetModule().GetFileSpec().GetFilename() == exe_name)\n self.assertTrue(sc.GetSymbol().GetName() == 'c')\n\n def get_description(self):\n \"\"\"Exercise SBTaget.GetDescription() API.\"\"\"\n exe = self.getBuildArtifact(\"a.out\")\n\n # Create a target by the debugger.\n target = self.dbg.CreateTarget(exe)\n self.assertTrue(target, VALID_TARGET)\n\n from lldbsuite.test.lldbutil import get_description\n\n # get_description() allows no option to mean\n # lldb.eDescriptionLevelBrief.\n desc = get_description(target)\n #desc = get_description(target, option=lldb.eDescriptionLevelBrief)\n if not desc:\n self.fail(\"SBTarget.GetDescription() failed\")\n self.expect(desc, exe=False,\n substrs=['a.out'])\n self.expect(desc, exe=False, matching=False,\n substrs=['Target', 'Module', 'Breakpoint'])\n\n desc = get_description(target, option=lldb.eDescriptionLevelFull)\n if not desc:\n self.fail(\"SBTarget.GetDescription() failed\")\n self.expect(desc, exe=False,\n substrs=['a.out', 'Target', 'Module', 'Breakpoint'])\n\n @not_remote_testsuite_ready\n @add_test_categories(['pyapi'])\n @no_debug_info_test\n def test_launch_new_process_and_redirect_stdout(self):\n \"\"\"Exercise SBTaget.Launch() API with redirected stdout.\"\"\"\n self.build()\n exe = self.getBuildArtifact(\"a.out\")\n\n # Create a target by the debugger.\n target = self.dbg.CreateTarget(exe)\n self.assertTrue(target, VALID_TARGET)\n\n # Add an extra twist of stopping the inferior in a breakpoint, and then continue till it's done.\n # We should still see the entire stdout redirected once the process is\n # finished.\n line = line_number('main.c', '// a(3) -> c(3)')\n breakpoint = target.BreakpointCreateByLocation('main.c', line)\n\n # Now launch the process, do not stop at entry point, and redirect stdout to \"stdout.txt\" file.\n # The inferior should run to completion after \"process.Continue()\"\n # call.\n local_path = self.getBuildArtifact(\"stdout.txt\")\n if os.path.exists(local_path):\n os.remove(local_path)\n\n if lldb.remote_platform:\n stdout_path = lldbutil.append_to_process_working_directory(self,\n \"lldb-stdout-redirect.txt\")\n else:\n stdout_path = local_path\n error = lldb.SBError()\n process = target.Launch(\n self.dbg.GetListener(),\n None,\n None,\n None,\n stdout_path,\n None,\n None,\n 0,\n False,\n error)\n process.Continue()\n #self.runCmd(\"process status\")\n if lldb.remote_platform:\n # copy output file to host\n lldb.remote_platform.Get(\n lldb.SBFileSpec(stdout_path),\n lldb.SBFileSpec(local_path))\n\n # The 'stdout.txt' file should now exist.\n self.assertTrue(\n os.path.isfile(local_path),\n \"'stdout.txt' exists due to redirected stdout via SBTarget.Launch() API.\")\n\n # Read the output file produced by running the program.\n with open(local_path, 'r') as f:\n output = f.read()\n\n self.expect(output, exe=False,\n substrs=[\"a(1)\", \"b(2)\", \"a(3)\"])\n\n def resolve_symbol_context_with_address(self):\n \"\"\"Exercise SBTaget.ResolveSymbolContextForAddress() API.\"\"\"\n exe = self.getBuildArtifact(\"a.out\")\n\n # Create a target by the debugger.\n target = self.dbg.CreateTarget(exe)\n self.assertTrue(target, VALID_TARGET)\n\n # Now create the two breakpoints inside function 'a'.\n breakpoint1 = target.BreakpointCreateByLocation('main.c', self.line1)\n breakpoint2 = target.BreakpointCreateByLocation('main.c', self.line2)\n #print(\"breakpoint1:\", breakpoint1)\n #print(\"breakpoint2:\", breakpoint2)\n self.assertTrue(breakpoint1 and\n breakpoint1.GetNumLocations() == 1,\n VALID_BREAKPOINT)\n self.assertTrue(breakpoint2 and\n breakpoint2.GetNumLocations() == 1,\n VALID_BREAKPOINT)\n\n # Now launch the process, and do not stop at entry point.\n process = target.LaunchSimple(\n None, None, self.get_process_working_directory())\n self.assertTrue(process, PROCESS_IS_VALID)\n\n # Frame #0 should be on self.line1.\n self.assertTrue(process.GetState() == lldb.eStateStopped)\n thread = lldbutil.get_stopped_thread(\n process, lldb.eStopReasonBreakpoint)\n self.assertTrue(\n thread.IsValid(),\n \"There should be a thread stopped due to breakpoint condition\")\n #self.runCmd(\"process status\")\n frame0 = thread.GetFrameAtIndex(0)\n lineEntry = frame0.GetLineEntry()\n self.assertTrue(lineEntry.GetLine() == self.line1)\n\n address1 = lineEntry.GetStartAddress()\n\n # Continue the inferior, the breakpoint 2 should be hit.\n process.Continue()\n self.assertTrue(process.GetState() == lldb.eStateStopped)\n thread = lldbutil.get_stopped_thread(\n process, lldb.eStopReasonBreakpoint)\n self.assertTrue(\n thread.IsValid(),\n \"There should be a thread stopped due to breakpoint condition\")\n #self.runCmd(\"process status\")\n frame0 = thread.GetFrameAtIndex(0)\n lineEntry = frame0.GetLineEntry()\n self.assertTrue(lineEntry.GetLine() == self.line2)\n\n address2 = lineEntry.GetStartAddress()\n\n #print(\"address1:\", address1)\n #print(\"address2:\", address2)\n\n # Now call SBTarget.ResolveSymbolContextForAddress() with the addresses\n # from our line entry.\n context1 = target.ResolveSymbolContextForAddress(\n address1, lldb.eSymbolContextEverything)\n context2 = target.ResolveSymbolContextForAddress(\n address2, lldb.eSymbolContextEverything)\n\n self.assertTrue(context1 and context2)\n #print(\"context1:\", context1)\n #print(\"context2:\", context2)\n\n # Verify that the context point to the same function 'a'.\n symbol1 = context1.GetSymbol()\n symbol2 = context2.GetSymbol()\n self.assertTrue(symbol1 and symbol2)\n #print(\"symbol1:\", symbol1)\n #print(\"symbol2:\", symbol2)\n\n from lldbsuite.test.lldbutil import get_description\n desc1 = get_description(symbol1)\n desc2 = get_description(symbol2)\n self.assertTrue(desc1 and desc2 and desc1 == desc2,\n \"The two addresses should resolve to the same symbol\")\n","sub_path":"packages/Python/lldbsuite/test/python_api/target/TestTargetAPI.py","file_name":"TestTargetAPI.py","file_ext":"py","file_size_in_byte":16584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"142000088","text":"import json\nfrom game import GameList\nfrom permissionManager import PermissionManager\nfrom discord import utils\n\nfrom discord.ext.commands import Bot\n\ngameList = GameList()\npermManag = PermissionManager()\n\nwith open('config.json') as json_data:\n d = json.load(json_data)\n TOKEN = d[\"token\"]\n SERVERNAME = d[\"server\"]\n MASTERROLE = d[\"master_role\"]\n UPPERBOUND = d[\"upper_bound\"]\n\n for e in d[\"games\"]:\n gameList.add(e[\"name\"], e[\"nickname\"])\n\nBOT_PREFIX = (\"?\", \"!\")\n\nclient = Bot(command_prefix=BOT_PREFIX)\n\n\ndef get_server(name):\n for el in client.servers:\n if el.name == name:\n print(\"Server '{0}' found\".format(name))\n return el\n raise NameError(\"Server '{0}' not found\".format(name))\n\n\ndef get_role_from_name_or_nickname(server, role_name):\n game = gameList.find_game(role_name)\n is_in_list = True\n if not game:\n name = role_name\n is_in_list = False\n else:\n name = game.name\n role = utils.get(server.roles, name=name)\n return role\n\n\n@client.event\nasync def on_ready():\n print('Logged in as')\n print(client.user.name)\n print(client.user.id)\n print('------')\n server = get_server(SERVERNAME)\n role = utils.get(server.roles, name=MASTERROLE)\n if role:\n permManag.add_master_role(role)\n else:\n print(\"Master role '{0}' not found\".format(MASTERROLE))\n role = utils.get(server.roles, name=UPPERBOUND)\n if role:\n permManag.updt_upper_bound_role(role)\n else:\n print(\"Master role '{0}' not found\".format(UPPERBOUND))\n\n\n@client.command(name=\"jeux\",\n description=\"Liste de tout jeux qui ont leurs propres channels.\",\n brief=\"Jeux disponnible.\",\n aliases=[\"games, roles\"],\n pass_context=True)\n# Retourne la liste de tout les jeux disponibles sur le serveur\nasync def get_game_list(ctx):\n string = \"Les jeux diponnibles sont:\\n\"\n print(ctx.message.author.roles)\n for el in gameList.get_list():\n string += \"- \" + el[0] + \" (\" + el[1] + \")\\n\"\n await client.say(string)\n\n\n@client.command(name=\"estPresent\",\n description=\"Dit si le jeu est présent ou non\",\n brief=\"Dit si le jeu est présent ou non\",\n aliases=[\"eP\", \"isPresent\", \"iP\"],\n pass_context=False)\nasync def search_game(search):\n result = gameList.find_game(search)\n if result:\n await client.say(result.name + \" found !\")\n return\n await client.say(\"Sorry, maybe tou should search somewhere else :/\")\n\n\n@client.command(name=\"rejoindre\",\n description=\"Rejoins un role\",\n brief=\"Rejoins un role\",\n aliases=[\"r\", \"join\", \"j\"],\n pass_context=True)\nasync def join_role(ctx, role_name):\n user = ctx.message.author\n\n role = get_role_from_name_or_nickname(user.server, role_name)\n\n if not role:\n await client.say(\"Role inconnu.\")\n return\n\n if not permManag.check_join_permission(role):\n await client.say(\"Impossible d'avoir ce rôle via cette commande\")\n return\n if role in ctx.message.author.roles:\n await client.say(\"Tu as déjà ce rôle.\")\n return\n await client.add_roles(user, role)\n await client.say(\"Tu as bien été ajouté !\")\n\n\n@client.command(name=\"quitter\",\n description=\"Quitte un role\",\n brief=\"Quitte un role\",\n aliases=[\"q\", \"quit\", \"leave\", \"l\"],\n pass_context=True)\nasync def quit_role(ctx, role_name):\n user = ctx.message.author\n\n role = get_role_from_name_or_nickname(user.server, role_name)\n\n if not permManag.check_join_permission(role):\n await client.say(\"Impossible de quitter ce rôle via cette commande\")\n return\n await client.remove_roles(user, role)\n await client.say(\"Au revoir _{0}_ :wave:\".format(role.name))\n\n\n@client.command(name=\"nouveau_jeu\",\n description=\"Ajoute un jeu à la liste, et créer leschans correspondants\",\n brief=\"Réservé aux admin\",\n hidden=True,\n aliases=[\"nJeu\", \"nj\", \"newGame\", \"ng\"],\n pass_context=True)\nasync def add_game_to_list(ctx, game, nickname=None):\n if not permManag.check_master_permission(ctx.message.author):\n await client.say(\"Sorry you're not allowed to use that :/\")\n return\n\n if gameList.add(game, nickname):\n await client.say(game + \" successfuly added !\")\n else:\n await client.say(game + \" already exist.\")\n\n\n@client.command(name=\"supprimer_jeu\",\n description=\"Enleve un jeu à la liste\",\n brief=\"Réservé aux admin\",\n hidden=True,\n aliases=[\"sJeu\", \"delGame\", \"dg\"],\n pass_context=True)\nasync def remove_game(ctx, game):\n if not permManag.check_master_permission(ctx.message.author):\n return\n\n if gameList.add(game):\n await client.say(game + \" successfuly added !\")\n else:\n await client.say(game + \" already exist.\")\n\nclient.run(TOKEN)\n","sub_path":"Bot-v1.py","file_name":"Bot-v1.py","file_ext":"py","file_size_in_byte":5104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"498567630","text":"from __future__ import print_function\nfrom uuid import uuid4\nimport os\nimport velocloud\nfrom velocloud.rest import ApiException\n# If SSL verification disabled (e.g. in a development environment)\nimport urllib3\nurllib3.disable_warnings()\nvelocloud.configuration.verify_ssl=False\n\nclient = velocloud.ApiClient(host=\"vco160-usca1.velocloud.net\")\nclient.authenticate(os.environ.get('CORP_EMAIL'), os.environ.get('VCO160_PASSWORD'), operator=False)\napi = velocloud.AllApi(client)\n\nUNIQ = str(uuid4())\nenterpriseId = 458\n\nprint(\"### GETTING ENTERPRISE CONFIGURATIONS ###\")\nparams = { \"enterpriseId\": enterpriseId }\ntry:\n res = api.enterpriseGetEnterpriseConfigurations(params)\n print(res)\nexcept ApiException as e:\n print(e)\n\nprofileId = res[1].id\n\nedgeName = \"AWS-%s\" % UNIQ\nprint(\"### PROVISIONING EDGE ###\")\nparams = { \"enterpriseId\": enterpriseId,\n \"name\": edgeName,\n \"description\": \"A test Edge generated with the VeloCloud Python SDK\",\n \"modelNumber\": \"virtual\",\n \"configurationId\": profileId }\ntry:\n res = api.edgeEdgeProvision(params)\n print(res)\nexcept ApiException as e:\n print(e)\n","sub_path":"aws/provision-vce.py","file_name":"provision-vce.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"252549394","text":"import json\nimport unittest\nimport subprocess\n\nfrom os import path, kill\nfrom copy import deepcopy\n\n\nTEST_DIR = path.dirname(path.abspath(__file__))\nBASE_URL = 'http://localhost:5000/api/v1/users'\nGOOD_USER_URL = f'{BASE_URL}/userId3'\nBAD_USER_URL = f'{BASE_URL}/userId5'\n\n\nclass TestApi(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n self.dynamodb = subprocess.Popen(['sls', 'dynamodb', 'start'], cwd=path.dirname(TEST_DIR))\n with open(path.join(TEST_DIR,'seed-users.json')) as json_file: \n users = json.load(json_file)\n self.backup_users = deepcopy(users)\n self.app = app.app.test_client()\n self.app.testing = True\n\n def test_list_users(self):\n response = self.app.get(BASE_URL)\n data = json.loads(response.get_data())\n self.assertEqual(response.status_code, 200)\n self.assertEqual(len(data['data']), 3)\n\n def test_get_user(self):\n response = self.app.get(GOOD_USER_URL)\n data = json.loads(response.get_data())\n self.assertEqual(response.status_code, 200)\n self.assertEqual(data['data']['name'], 'name3')\n\n def test_item_not_exist(self):\n response = self.app.get(BAD_USER_URL)\n self.assertEqual(response.status_code, 404)\n\n def test_create_user(self):\n # missing name field\n user = {\"userId\": \"userId4\"}\n response = self.app.post(BASE_URL,\n data=json.dumps(user),\n content_type='application/json')\n self.assertEqual(response.status_code, 400)\n # name field cannot take int\n user = {\"userId\": \"userId4\", \"name\": 0}\n response = self.app.post(BASE_URL,\n data=json.dumps(user),\n content_type='application/json')\n self.assertEqual(response.status_code, 400)\n # valid: both required fields, name takes str\n user = {\"userId\": \"userId4\", \"name\": \"name4\"}\n response = self.app.post(BASE_URL,\n data=json.dumps(user),\n content_type='application/json')\n self.assertEqual(response.status_code, 201)\n data = json.loads(response.get_data())\n self.assertEqual(data['userId'], 'userId4')\n self.assertEqual(data['name'], 'name4')\n # cannot add user with same userId again\n user = {\"name\": \"userId4\", \"name\": \"name4\"}\n response = self.app.post(BASE_URL,\n data=json.dumps(user),\n content_type='application/json')\n self.assertEqual(response.status_code, 400)\n\n def test_update_user(self):\n user = {\"name\": \"updatedName3\"}\n response = self.app.put(GOOD_USER_URL,\n data=json.dumps(user),\n content_type='application/json')\n self.assertEqual(response.status_code, 200)\n data = json.loads(response.get_data())\n self.assertEqual(data['name'], 'updatedName3')\n self.assertEqual(self.backup_users[2]['name'], 'name3')\n\n def test_update_error(self):\n # cannot edit non-existing users\n user = {\"name\": \"name5\"}\n response = self.app.put(BAD_USER_URL,\n data=json.dumps(user),\n content_type='application/json')\n self.assertEqual(response.status_code, 404)\n # name field cannot take int\n user = {\"name\": 0}\n response = self.app.put(GOOD_USER_URL,\n data=json.dumps(user),\n content_type='application/json')\n self.assertEqual(response.status_code, 400)\n\n def test_delete_user(self):\n response = self.app.delete(f'{BASE_URL}/userId2')\n self.assertEqual(response.status_code, 204)\n response = self.app.delete(BAD_USER_URL)\n self.assertEqual(response.status_code, 404)\n\n @classmethod\n def tearDownClass(self):\n # self.dynamodb.kill()\n #\n # TODO: look into why dynamodb-local is not running in the \n # foreground as expected. This causes the termination\n # process to fail when using .kill(). The current\n # workaround is less pythonic but guarantees the process\n # is killed.\n p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)\n out, err = p.communicate()\n for line in out.splitlines():\n if b'dynamodb' in line:\n pid = int(line.split(None, 1)[0])\n kill(pid, 9)\n\n\nif __name__ == \"__main__\":\n import sys\n sys.path.append(path.dirname(TEST_DIR))\n\n import app\n unittest.main()\n","sub_path":"tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":4727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"525028379","text":"import pysal\nimport numpy as np\n\nf=open(\"spi_download.csv\",'r')\nlines=f.readlines()\nf.close()\n\nlines=[line.strip().split(\",\") for line in lines]\nnames=[line[2] for line in lines[1:-5]]\ndata=np.array([map(int,line[3:]) for line in lines[1:-5]])\nsids=range(60)\nout=['\"United States 3/\"','\"Alaska 3/\"',\n '\"District of Columbia\"',\n '\"Hawaii 3/\"',\n '\"New England\"',\n '\"Mideast\"',\n '\"Great Lakes\"',\n '\"Plains\"',\n '\"Southeast\"',\n '\"Southwest\"',\n '\"Rocky Mountain\"',\n '\"Far West 3/\"']\nsnames=[name for name in names if name not in out]\nsids=[names.index(name) for name in snames]\nstates=data[sids,:]\nus=data[0]\n\nfrom pylab import *\n\nyears=np.arange(1969,2009)\nrel=states/(us*1.)\n\ngal=pysal.open('states48.gal')\nw=gal.read()\nrt=rel.transpose()\nw.transform='r'\nwrel=pysal.lag_spatial(w,rel)\n\ny1=rel[:,0]\nwy1=wrel[:,0]\ny2=rel[:,-1]\nwy2=wrel[:,-1]\n\n\nminx,miny=rel.min(),rel.min()\nmaxx,maxy=rel.max(),rel.max()\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpp\nfig=plt.figure()\n\ndx=y2-y1\ndy=wy2-wy1\n\nax=fig.add_subplot(111)\n\nminx=min(dx)\nmaxx=max(dx)\nax.axis([minx,maxx,minx,maxx])\n\nfor i in range(48):\n p2=(dx[i],dy[i])\n p1=(0,0)\n c = mpp.FancyArrowPatch(p1, p2, arrowstyle='-|>', lw=1, mutation_scale=20)\n ax.add_patch(c)\nplt.show()\n\n\n\n\"\"\"\nplot(y1,wy1)\nplot(y2,wy2)\narr=Arrow(y1[0],wy1[0],y2[0],wy2[0],width=0.10,edgecolor='white')\nax=gca()\nax.add_patch(arr)\narr.set_facecolor('g')\nscatter(y1,wy1)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import NullFormatter\n\n# the random data\nx = y1\ny = wy1\n\nnullfmt = NullFormatter() # no labels\n\n# definitions for the axes\nleft, width = 0.1, 0.65\nbottom, height = 0.1, 0.65\nbottom_h = left_h = left+width+0.02\n\nrect_scatter = [left, bottom, width, height]\nrect_histx = [left, bottom_h, width, 0.2]\nrect_histy = [left_h, bottom, 0.2, height]\n\n# start with a rectangular Figure\nplt.figure(1, figsize=(8,8))\n\naxScatter = plt.axes(rect_scatter)\naxHistx = plt.axes(rect_histx)\naxHisty = plt.axes(rect_histy)\n\n# no labels\naxHistx.xaxis.set_major_formatter(nullfmt)\naxHisty.yaxis.set_major_formatter(nullfmt)\n\n# the scatter plot:\naxScatter.scatter(x, y)\n\n# now determine nice limits by hand:\nbinwidth = 0.05\nxymax = np.max( [np.max(np.fabs(x)), np.max(np.fabs(y))] )\nlim = ( int(xymax/binwidth) + 1) * binwidth\n\naxScatter.set_xlim( (-lim, lim) )\naxScatter.set_ylim( (-lim, lim) )\n\nbins = np.arange(-lim, lim + binwidth, binwidth)\naxHistx.hist(x, bins=bins)\naxHisty.hist(y, bins=bins, orientation='horizontal')\n\naxHistx.set_xlim( axScatter.get_xlim() )\naxHisty.set_ylim( axScatter.get_ylim() )\n\nplt.show()\n\"\"\"\n","sub_path":"stars/examples/us1969_2008/stand.py","file_name":"stand.py","file_ext":"py","file_size_in_byte":2612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"172153723","text":"'''\nCreated on Mar 18, 2021\n\n@author: bsana\n'''\n\nimport psycopg2\nimport config\nfrom io import StringIO\nimport geopandas as gpd\nfrom shapely.geometry import LineString, MultiLineString\nfrom os.path import join\nimport shapely\n\nshp = r'Q:\\CMP\\LOS Monitoring 2019\\Network_Conflation\\cmp_roadway_segments.shp'\n# shp_add = r'Q:\\GIS\\Transportation\\Roads\\INRIX\\XD\\20_02\\shapefiles\\SF\\cmp_plus_add.shp'\n# out_dir = r'Q:\\CMP\\LOS Monitoring 2020\\CMP_plus_shp'\nshp_add = r'Q:\\GIS\\Transportation\\Roads\\INRIX\\XD\\21_01\\maprelease-shapefiles\\SF\\cmp_plus_add.shp'\nout_dir = r'Q:\\CMP\\LOS Monitoring 2021\\CMP_plus_shp'\n\nSCHEMA_NAME = 'cmp'\nTABLE_NAME = 'cmp_segments_plus'\nAPISCHEMA_NAME = 'api'\nVIEW_NAME = 'cmp_segments_plus'\n\nGEO_COL = 'geometry'\nFLOAT_COLS = ['length']\nOBJ_COLS = ['cmp_name', 'cmp_from', 'cmp_to', 'cls_hcm85', 'cls_hcm00', 'direction']\nINT_COLS = ['cmp_segid']\nreq_cols = [GEO_COL]+ INT_COLS + OBJ_COLS + FLOAT_COLS\n\ndf = gpd.read_file(shp)\n\ndef convert_geom(x):\n if isinstance(x, LineString):\n x = MultiLineString([x])\n return x\ndf['geometry'] = df['geometry'].apply(convert_geom)\n\ndf_add = gpd.read_file(shp_add)\ndf_add['comment'] = ''\ndf = df.append(df_add)\n\nprint(df['geometry'].apply(lambda x: x.__class__.__name__).value_counts())\n\ndf = df[req_cols]\n\ndf.reset_index(drop=True, inplace=True) # Max add\ndf = df.reset_index()\n\ndf = df.rename(columns={GEO_COL:'geom', 'index':'gid'})\nprint(df['geom'].apply(lambda x: x.__class__.__name__).value_counts())\ndf.rename(columns={'geom':'geometry'}).to_file(join(out_dir, 'cmp_segments_plus.shp'))\n\nsql_commands = ['DROP TABLE IF EXISTS %s.%s CASCADE' %(SCHEMA_NAME,TABLE_NAME)]\n\ncmd = 'CREATE TABLE %s.%s (' %(SCHEMA_NAME,TABLE_NAME)\nfor col in df.columns:\n if col in OBJ_COLS:\n df[col] = df[col].astype(str)\n df.loc[df[col]=='nan', col] = ''\n cmd += '%s text,' %col.lower()\n elif col in INT_COLS:\n df[col] = df[col].map('{:.0f}'.format)\n df.loc[df[col]=='nan', col] = 'NULL'\n cmd += '%s integer,' %col.lower()\n elif col == 'geom':\n df[col] = df[col].map(lambda x: 'SRID=4326;'+str(x))\n df.loc[df[col]=='nan', col] = 'NULL'\n cmd += 'geom geometry,'\n elif col.lower() == 'gid':\n cmd += 'gid serial,'\n elif col.lower() == 'cmp_segid':\n cmd += 'cmp_segid integer,'\n elif col.lower() == 'length':\n cmd += 'length float,'\n else:\n cmd += '%s numeric,' %col\n\ncmd += 'CONSTRAINT cmp_plus_uni UNIQUE (cmp_segid))'\nsql_commands.append(cmd)\nsql_commands.append('GRANT SELECT ON TABLE %s.%s TO anon' %(SCHEMA_NAME,TABLE_NAME))\n\nf = StringIO()\ndf.to_csv(f, sep='\\t', header=False, index=False, na_rep='NULL')\nf.seek(0)\n\n# view commands\nview_commands = ['CREATE OR REPLACE VIEW %s.%s AS' %(APISCHEMA_NAME,VIEW_NAME) +\n ' SELECT *, ST_ASGEOJSON(ST_OFFSETCURVE(ST_LINEMERGE(%s.geom), %s)) AS geometry' %(TABLE_NAME, \"'-0.0002'::numeric::double precision\") + \n ' FROM %s.%s' %(SCHEMA_NAME,TABLE_NAME)]\nview_commands.append('GRANT SELECT ON TABLE %s.%s TO anon' %(APISCHEMA_NAME,VIEW_NAME))\n\nconn = config.connect(config.dbconfig())\ndbcursor = conn.cursor()\n\nprint('total number of records: %s' %len(df))\n\ntry:\n for command in sql_commands:\n dbcursor.execute(command)\n \n dbcursor.copy_from(f, '%s.%s' %(SCHEMA_NAME,TABLE_NAME), sep='\\t', null='NULL')\n \n for command in view_commands:\n dbcursor.execute(command)\nexcept (Exception, psycopg2.DatabaseError) as error:\n print('ERROR')\n print(error)\nfinally:\n conn.commit()\n conn.close()","sub_path":"cmprt/import_CMPplus_geo.py","file_name":"import_CMPplus_geo.py","file_ext":"py","file_size_in_byte":3562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"143347134","text":"#\n# LSST Data Management System\n# Copyright 2017 LSST Corporation.\n#\n# This product includes software developed by the\n# LSST Project (http://www.lsst.org/).\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the LSST License Statement and\n# the GNU General Public License along with this program. If not,\n# see .\n#\n\"\"\"Python helpers for pybind11 wrapping of Transform classes and subclasses\n\n.. _pybind11_transform_classes:\n\nTransform Classes and Subclasses\n--------------------------------\n\nTransforms are instances of\nlsst::afw::geom::Transform\nand subclasses, such as lsst::afw::geom::SkyWcs.\n\nIn Python the templated Transform classes have names such as\n`lsst.afw.geom.TransformIcrsCoordToPoint2` for\n`lsst::afw::geom::Transform`\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\n__all__ = [\"addTransformMethods\", \"transformRegistry\"]\n\nimport lsst.pex.exceptions\n\n# registry of transform classes; a dict of class name: transform class\ntransformRegistry = {}\n\n\ndef getJacobian(self, x):\n # Force 2D matrix over numpy's protests\n matrix = self._getJacobian(x)\n matrix.shape = (self.toEndpoint.nAxes,\n self.fromEndpoint.nAxes)\n return matrix\n\n\ndef then(self, next):\n \"\"\"Concatenate two transforms\n\n The result of A.then(B) is is C(x) = B(A(x))\n \"\"\"\n if self.toEndpoint == next.fromEndpoint:\n return self._then(next)\n else:\n raise lsst.pex.exceptions.InvalidParameterError(\n \"Cannot concatenate %r and %r: endpoints do not match.\"\n % (self, next))\n\n\ndef addTransformMethods(cls):\n \"\"\"Add pure python methods to the specified Transform class, and register\n the class in `transformRegistry`\n\n All :ref:`_pybind11_transform_classes` must call this function.\n\n Parameters\n ----------\n cls : :ref:`_pybind11_transform_classes`\n A Transform class or subclass, e.g.\n `lsst.afw.geom.TransformPoint2ToIcrsCoord`\n \"\"\"\n global transformRegistry\n className = cls.__name__\n if className in transformRegistry:\n raise RuntimeError(\"Class %r=%s already registered; cannot register class %s\" %\n (className, transformRegistry[className], cls))\n transformRegistry[cls.__name__] = cls\n cls.getJacobian = getJacobian\n cls.then = then\n","sub_path":"python/lsst/afw/geom/python/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":2878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"9195126","text":"\"\"\"Helper functions for Term Deposit Analysis.\"\"\"\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score\nfrom sklearn.metrics import roc_curve, auc\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\n\nsns.set_context('talk')\n\n\ndef visualize_model_performance(x_train, x_test, y_train, y_test,\n model, threshold=0.5):\n \"\"\"Summarize and visualize (binary classifier) model performance.\"\"\"\n y_train_predp = model.predict_proba(x_train)[:, 1]\n y_test_predp = model.predict_proba(x_test)[:, 1]\n\n y_train_pred = (y_train_predp >= threshold).astype(int)\n y_test_pred = (y_test_predp >= threshold).astype(int)\n\n # Calculate accuracy, precision, recall, AUC.\n acc_train = accuracy_score(y_train, y_train_pred)\n acc_test = accuracy_score(y_test, y_test_pred)\n prec_train = precision_score(y_train, y_train_pred)\n prec_test = precision_score(y_test, y_test_pred)\n rec_train = recall_score(y_train, y_train_pred)\n rec_test = recall_score(y_test, y_test_pred)\n fpr_train, tpr_train, _ = roc_curve(y_train, y_train_predp)\n fpr_test, tpr_test, _ = roc_curve(y_test, y_test_predp)\n auc_train = auc(fpr_train, tpr_train)\n auc_test = auc(fpr_test, tpr_test)\n\n fig, ax = plt.subplots(2, 1, figsize=(12, 14))\n # Create a DataFrame (easier to plot).\n scores_df = pd.DataFrame(\n data=np.array([[acc_train, acc_test],\n [prec_train, prec_test],\n [rec_train, rec_test],\n [auc_train, auc_test]]),\n columns=['Training Set', 'Test Set'],\n index=['Accuracy', 'Precision', 'Recall', 'AUC']\n )\n scores_df.plot(kind='bar', ax=ax[0])\n ax[0].set_xlabel('')\n ax[0].set_ylabel('Score [-]')\n ax[0].set_title('Binary Classifier Performance')\n ax[0].set_ylim([0, 1.2])\n for tick in ax[0].get_xticklabels():\n tick.set_rotation(0)\n\n for p in ax[0].patches:\n ax[0].annotate(\n str(p.get_height().round(2)),\n (p.get_x() + p.get_width()/2., p.get_height() * 1.005),\n ha='center', va='center', xytext=(0, 10),\n textcoords='offset points'\n )\n # Plot the ROC Curve.\n ax[1].plot(fpr_train, tpr_train, color='navy', label='Training Set')\n ax[1].plot(fpr_test, tpr_test, color='darkorange',\n label='Test Set')\n ax[1].plot([0, 1], [0, 1], color='gray', lw=1, linestyle='--')\n ax[1].grid()\n ax[1].set_xlim([0., 1.])\n ax[1].set_ylim([0., 1.05])\n ax[1].set_xlabel('False Positive Rate [-]')\n ax[1].set_ylabel('True Positive Rate [-]')\n ax[1].set_title('ROC Curve')\n ax[1].legend(loc='lower right')\n\n return fig, ax\n\n\ndef onehot_encode(dfin, onehot_cols):\n \"\"\"One-hot encode selected columns.\"\"\"\n df = dfin.copy()\n onehot_features = []\n for col in onehot_cols:\n # Create more cols for one-hot encoded features.\n encoded_df = pd.get_dummies(dfin[col])\n # Rename columns to add combinations\n encoded_df.columns = [col.replace(' ', '.') + '.' + x\n for x in encoded_df.columns]\n onehot_features += list(encoded_df.columns)\n df = pd.concat([df, encoded_df], axis=1)\n return df[onehot_features]\n\n\ndef encode_features(dfin):\n \"\"\"Encode features in a DataFrame and return final DF.\"\"\"\n df = dfin.copy()\n # Find the non-numerical (categorical) columns.\n cnt_ft = list(df.describe().columns)\n\n cat_cols = [col for col in df.columns if col not in cnt_ft]\n\n # Find the columns to label encode (binary classes).\n label_cols = [col for col in cat_cols if\n len(df[col].unique()) <= 2]\n\n # Find he columns to one-hot encode.\n onehot_cols = [col for col in cat_cols if col not in label_cols]\n\n # One-hot encode the columns.\n df2 = onehot_encode(dfin, onehot_cols)\n\n # Label encode the columns.\n label_features = [col + '_label' for col in label_cols]\n for col in label_cols:\n firstval = df[col].iloc[0]\n df[col + '_label'] = df[col].apply(lambda x: 1\n if x == firstval else 0)\n\n # Put it all together.\n keep_features = cnt_ft + label_features\n df_model = pd.concat([df[keep_features], df2], axis=1)\n return df_model\n\n\ndef get_ratio(input_df, conversion_col):\n \"\"\"Calculate the conversion rate in a DataFrame.\"\"\"\n return input_df[conversion_col].sum() / len(input_df)\n\n\ndef binary_process(input_df, binary_col):\n \"\"\"Process conversion data.\"\"\"\n output_df = input_df.copy()\n output_df[binary_col] = output_df[binary_col].str.lower()\n return output_df[binary_col].apply(lambda x: 1 if x == 'yes'\n else 0)\n\n\ndef ratio_segmented_1(input_df, conversion_col, seg_col):\n \"\"\"Get the conversion rate on a 1D segmented dataset.\"\"\"\n n1 = input_df.groupby(by=seg_col)[conversion_col].sum()\n n2 = input_df.groupby(by=seg_col)[conversion_col].count()\n return n1 / n2\n\n\ndef ratio_segmented_2(input_df, conversion_col, seg_cols):\n \"\"\"Get the conversion rate on a 2D Segmented Dataset.\"\"\"\n n1 = (input_df.groupby(seg_cols)[conversion_col]\n .sum().unstack(seg_cols[1]).fillna(0))\n n2 = input_df.groupby(seg_cols[0])[conversion_col].count()\n return n1.divide(n2, axis=0)\n\n\ndef ratio_segmented(input_df, ratio_col, seg_cols):\n \"\"\"Get the conversion rate on a segmented dataset.\"\"\"\n df1 = input_df.groupby(seg_cols)[ratio_col].sum()\n df2 = input_df.groupby(seg_cols)[ratio_col].count()\n return df1 / df2\n\n\ndef plot_ratios_and_bins(input_df, conversion_col, seg_col):\n \"\"\"Plot conversion rates versus segmentation bins.\"\"\"\n fig, ax = plt.subplots(figsize=(10, 7))\n convs = ratio_segmented_1(input_df, conversion_col, seg_col)\n ax.plot(convs.index, convs.values, color='blue')\n ax2 = ax.twinx()\n convc = input_df.groupby(seg_col)[conversion_col].count()\n ax2.plot(convc.index, convc.values, color='red')\n ax2.set_ylabel('Number of Data Points in Group', color='red')\n ax.set_ylabel('Conversion Rate (ratio)', color='blue')\n ax.set_xlabel(seg_col)\n return fig, ax\n\n\ndef bar_ratios_and_bins(input_df, ratio_col, seg_col):\n \"\"\"Plot binary KPI ratio vs segmentation in a bar.\"\"\"\n fig, ax = plt.subplots(2, 1, figsize=(16, 15))\n convs = ratio_segmented_1(input_df, ratio_col, seg_col)\n ax[0].bar(convs.index, convs.values, color='skyblue')\n ax[0].set_ylabel(ratio_col + ' Rate [-]')\n # convc = input_df.groupby(seg_col)[ratio_col].count()\n # ax[1].bar(convc.index, convc.values, color='red')\n dummy_df = input_df.copy()\n dummy_df['dum1'] = dummy_df[ratio_col].apply(lambda x: 'Yes' if x == 1\n else 'No')\n dummy_df['KPI'] = dummy_df['dum1']\n convc2 = pd.pivot_table(dummy_df, values='dum1', columns='KPI',\n index=seg_col,\n aggfunc=len).fillna(0.0)\n convc2.plot(ax=ax[1], kind='bar', stacked='True')\n for tick1, tick2 in zip(ax[0].get_xticklabels(),\n ax[1].get_xticklabels()):\n tick1.set_rotation(30)\n tick2.set_rotation(30)\n ax[1].set_ylabel('Data Points')\n ax[1].set_xlabel(seg_col)\n return fig, ax\n\n\ndef stacked_bar_ratios(input_df, conversion_col, seg_cols):\n \"\"\"Plot a stacked bar with a segmented population.\"\"\"\n df = ratio_segmented_2(input_df, conversion_col,\n seg_cols)\n fig, ax = plt.subplots(2, 1, figsize=(16, 15))\n df.plot(ax=ax[0], kind='bar', stacked='True')\n ax[0].set_title('KPI Rates by ' + str(seg_cols[0]) + ' and ' +\n str(seg_cols[1]))\n ax[0].set_ylabel(conversion_col + ' Rate [-]')\n ax[0].set_xlabel('')\n convc = input_df.groupby(seg_cols)[conversion_col].count().unstack(\n seg_cols[1]).fillna(0)\n convc.plot(ax=ax[1], kind='bar', stacked='True')\n ax[1].set_ylabel('Data Points')\n ax[1].set_xlabel(seg_cols[0])\n for tick1, tick2 in zip(ax[0].get_xticklabels(),\n ax[1].get_xticklabels()):\n tick1.set_rotation(30)\n tick2.set_rotation(30)\n return fig, ax\n\n\ndef segment_scatter_2(input_df, col1, col2, scol1, scol2):\n \"\"\"Plot a scatter of segmented data.\"\"\"\n fig, ax = plt.subplots(figsize=(10, 7))\n inds = []\n for i in ['High', 'Low']:\n for j in ['High', 'Low']:\n inds.append(\n np.where(\n (input_df[scol1] == i) & (input_df[scol2] == j)\n )[0]\n )\n clrs = ['red', 'blue', 'orange', 'green']\n for ind, clr in zip(inds, clrs):\n ax.scatter(\n input_df[col1].iloc[ind],\n input_df[col2].iloc[ind], c=clr, s=2\n )\n ax.set_xlabel(col1)\n ax.set_ylabel(col2)\n return fig, ax\n","sub_path":"marketing-engagement/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":8863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"205772898","text":"#coding=utf-8\nfrom django.conf.urls.defaults import *\nfrom django.conf import settings\n\n# Uncomment the next two lines to enable the admin:\n#from django.contrib import admin\n#admin.autodiscover()\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\n\nurlpatterns = patterns('',\n (r'^upload_media/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),\n (r'^logview/(?P.*)$', 'django.views.static.serve', {'document_root': settings.LOGDIR}),\n (r\"^$\", 'views.welcome'), # 首页\n (r\"^index/$\", 'views.index'), # 首页\n)\n# 学生端相关URL\nurlpatterns += patterns('',\n (r'^account/', include('apps.account.urls')), # 用户基础数据\n (r'^system/', include('apps.system.urls')), # 下载、安装等\n (r'^math/', include('apps.math.urls')), # 小学数学\n (r'^math2/', include('apps.math2.urls')), # 初中数学\n (r'^english/', include('apps.english.urls')), # 小学英语\n (r'^yy/', include('apps.yy.urls')), # 新版小学英语\n (r'^getui/', include('getui.urls')), # 数据推送\n (r'^shared/', include('apps.shared.urls')), # 共享资源\n (r'^messagepush/', include('apps.messagepush.urls')), # 奥数推送\n (r'^weblog/', include('weblog.urls')), # 网站日志\n (r'^active/', include('apps.active.urls')), # 活动\n)\n# 教师端相关URLS\nurlpatterns += patterns('',\n (r'^tea/', include('tapps.urls')), # 教师端\n (r'^weixin/', include('apps.weixin.urls')), # 微信\n)","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"521964472","text":"import cv2\nimport numpy as np\nfrom time import time\nimport pickle\nimport math\nfrom time import time\n\nip_kernel_2x2 = np.ones((2,2),np.uint8)\nip_kernel_3x3 = np.ones((3,3),np.uint8)\n\n##################################\n# Format timestamp\n##################################\ndef process_time_str(start, end):\n etime = end - start\n return \"{0:.0f}:{1:.0f} minutes\".format((etime-(etime%60))/60, round(etime%60))\n\n\n##############################################################################################\n# Crop an image array and resize to VGG16 ImageNet minimum dimensions (48,48)\n# Using OpenCV for resize operation in both trainer and drive algorithms\n##############################################################################################\ndef get_viewport(image, x=0,y=65, w=320,h=80, size=(80,20)):\n #CENTER: \n x1, y1 = x+w, y+h\n img = image[y:y1, x:x1]\n img = cv2.resize(img, size, interpolation=cv2.INTER_AREA)\n return img\n\n \n##########################################################################\n#Increase Image contrast\n##########################################################################\ndef image_contrast(img, phi=1, theta=1, maxIntensity=255.0):\n img = (maxIntensity/phi)*(img/(maxIntensity/theta))**2\n return img.astype(\"uint8\")\n\n \n##########################################################################\n# Increase Image brightness\n##########################################################################\ndef image_brightness(img, phi=1, theta=1, maxIntensity=255.0):\n img = (maxIntensity/phi)*(img/(maxIntensity/theta))**0.5\n return img.astype(\"uint8\")\n\n \n# Sketch edges of image and return a black and white image in 1/3 channels\n# Applies a gradient filter with a default 2x2 kernel.\n# Assumes a color (3 channel) input image\n##########################################################################\ndef image_gradient(img, channels=3):\n newImg = cv2.morphologyEx(grayscale(img), cv2.MORPH_GRADIENT, ip_kernel_2x2, iterations=1)\n if channels == 3:\n newImg = cv2.cvtColor(newImg, cv2.COLOR_GRAY2BGR)\n return newImg\n\n \n##########################################################################\n# Sharpen images using a simple filter since a lot of images are blurred\n##########################################################################\ndef image_sharpen(img):\n #Create the filter kernel\n kernel = np.zeros( (9,9), np.float32)\n kernel[4,4] = 2.0\n boxFilter = np.ones( (9,9), np.float32) / 81.0\n kernel = kernel - boxFilter\n #Apply the filter\n return cv2.filter2D(img, -1, kernel)\n\n \n##########################################################################\n# Flip an image horizontally/vertically\n# openCV: True returns BGR, False returns RGB\n##########################################################################\ndef image_flip(img, horizontal=1):\n image = cv2.flip(img, horizontal)\n return image\n\n\n#####################################################\n#Cleanup images using OpenCV Histogram Equalization\n#####################################################\ndef image_preprocessing(image):\n #img = img.view('uint8')[:,:,::4]\n #Recast as uint8 to support OpenCV requirements\n img = image.astype(\"uint8\")\n #Convert to YUV before equalization\n img_yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)\n # equalize the histogram of the Y channel\n img_yuv[:,:,0] = cv2.equalizeHist(img_yuv[:,:,0])\n # convert the YUV image back to RGB format\n img_output = cv2.cvtColor(img_yuv, cv2.COLOR_YUV2BGR)\n return img_output\n\n############################################\n# Data-set augmentation functions compliments\n# of Vivek Yadav (posted to CarND space)\n############################################\ndef augment_brightness_camera_images(image):\n image1 = cv2.cvtColor(image,cv2.COLOR_RGB2HSV)\n random_bright = .25+np.random.uniform()\n #print(random_bright)\n image1[:,:,2] = image1[:,:,2]*random_bright\n image1 = cv2.cvtColor(image1,cv2.COLOR_HSV2RGB)\n return image1\n\ndef transform_image(img,ang_range,shear_range,trans_range):\n '''\n This function transforms images to generate new images.\n The function takes in following arguments,\n 1- Image\n 2- ang_range: Range of angles for rotation\n 3- shear_range: Range of values to apply affine transform to\n 4- trans_range: Range of values to apply translations over. \n A Random uniform distribution is used to generate different parameters for transformation\n '''\n # Rotation\n ang_rot = np.random.uniform(ang_range)-ang_range/2\n rows,cols,ch = img.shape \n Rot_M = cv2.getRotationMatrix2D((cols/2,rows/2),ang_rot,1)\n\n # Translation\n tr_x = trans_range*np.random.uniform()-trans_range/2\n tr_y = trans_range*np.random.uniform()-trans_range/2\n Trans_M = np.float32([[1,0,tr_x],[0,1,tr_y]])\n\n # Shear\n pts1 = np.float32([[5,5],[20,5],[5,20]])\n pt1 = 5+shear_range*np.random.uniform()-shear_range/2\n pt2 = 20+shear_range*np.random.uniform()-shear_range/2\n \n # Brightness \n pts2 = np.float32([[pt1,5],[pt2,pt1],[5,pt2]])\n\n shear_M = cv2.getAffineTransform(pts1,pts2)\n img = cv2.warpAffine(img,Rot_M,(cols,rows))\n img = cv2.warpAffine(img,Trans_M,(cols,rows))\n img = cv2.warpAffine(img,shear_M,(cols,rows))\n img = augment_brightness_camera_images(img)\n \n return img\n\n#\n# First preprocess each image with Histogram Equalization\n# Then apply a sharpening filter to try to lift features from blurry images\n#########################################################################################\ndef image_normalization(x, skip_hsv=False):\n start_time = time()\n for i in range(len(x)):\n x[i] = image_preprocessing(x[i])\n x[i] = image_sharpen(x[i])\n if not skip_hsv:\n x[i] = cv2.cvtColor(x[i], cv2.COLOR_BGR2HSV)\n end_time = time()\n print(\"Image Processing complete \", process_time_str(start_time, end_time))\n return x\n\n#\n#Basic data normalization for 8-bit images\n#\ndef data_normalization(x, depth=255):\n return x/depth - 0.5\n\n#\n# Generate list of indicies for each sign type\n# This supports data normalization where we need to add images to balance the dataset\n# As well as subsequent class performance evaluation to see if there is skew in the model\n# performance\n###########################################################################################\ndef data_binning(imgs, labels, class_count, scale=1):\n #Bin the test data so each sign class can be tested for accuracy\n bins = []\n label_bins = []\n img_bins = []\n bin_count = []\n \n indicies = np.arange(len(labels))\n #For each class generate the bin contents\n for t in range(class_count):\n value = int(t * scale)\n \n if scale > 1:\n condition = np.logical_and(labels >= value, labels < value+scale)\n else:\n condition = labels == value\n idx_list = np.extract(condition, indicies)\n #print(\"Bin \", t, \"count \", len(idx_list))\n bins.append(idx_list)\n label_bins.append(labels[idx_list])\n img_bins.append(imgs[idx_list])\n bin_count.append(len(idx_list))\n return bins, img_bins, label_bins, bin_count\n\n#\n# Balance the distribution of features across the classes by generating and removing selectively \n######################################################################################################\ndef balance_dataset(X_train, y_train, n_classes):\n #First generate the bins for training data and calculate the average per class\n bins, X_train_binned, y_train_binned, bin_count = data_binning(X_train, y_train, n_classes)\n average_count = round(np.mean(bin_count))\n\n #Now downsample the above average classes to average by randomly picking \n #enough samples and removing them from the training set\n removal_list = None\n for i in range(n_classes):\n if bin_count[i] > average_count:\n removal_count = int(0.90 * (bin_count[i] - average_count) )\n #print(\"removing\",removal_count, \" from class \", i)\n #generate a list of random removals\n removal_idx = np.random.choice(bin_count[i], size=removal_count, replace=False)\n if removal_list is None:\n removal_list = bins[i][removal_idx.tolist()]\n else:\n removal_list = np.append(removal_list, bins[i][removal_idx.tolist()])\n\n #Now remove the targeted samples\n X_train = np.delete(X_train, removal_list, axis=0)\n y_train = np.delete(y_train, removal_list, axis=0)\n\n #Now Add new samples for under average classes\n for i in range(n_classes):\n if bin_count[i] < average_count:\n add_count = int( 1.10 * (average_count - bin_count[i]) )\n #pick images at random to dither 10 times\n src_img_count = int(round(add_count / 10))\n print(\"class \", i, \"dither \", src_img_count)\n src_idx = np.random.choice(bin_count[i], size=src_img_count, replace=False)\n #print(\"sources\", src_idx)\n #print(\"bin size\", len(X_eval[i]))\n for src in range(src_img_count):\n nimg = X_train_binned[i][src_idx[src]]\n new_img_list = []\n for j in range(10):\n dithered_img = transform_image(nimg,10,2,5)\n new_img_list.append(dithered_img)\n\n #X_train = np.append(X_train, [nimg,nimg,nimg,nimg,nimg,nimg,nimg,nimg,nimg,nimg], axis=0)\n X_train = np.append(X_train, new_img_list, axis=0)\n y_train = np.append(y_train, [i,i,i,i,i,i,i,i,i,i])\n #Pickle the augmented data to save time\n pickle_dict = {'features': X_train, 'labels': y_train}\n pickle.dump(pickle_dict, open(\"./train_augmented.p\", \"wb\"))\n return X_train, y_train\n\n\n# Convert to grayscale\n##########################################################\ndef grayscale(img):\n \"\"\"Applies the Grayscale transform\n This will return an image with only one color channel\n but NOTE: to see the returned image as grayscale\n you should call plt.imshow(gray, cmap='gray')\"\"\"\n return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n########################################################### \n# Canny Edge Detection\n###########################################################\ndef canny(img, low_threshold, high_threshold=0):\n \"\"\"Applies the Canny transform\"\"\"\n if high_threshold == 0:\n high_threshold = low_threshold * 3\n return cv2.Canny(img, low_threshold, high_threshold)\n\n###########################################################\n# Gaussian Blur\n###########################################################\ndef gaussian_blur(img, kernel_size=3):\n \"\"\"Applies a Gaussian Noise kernel\"\"\"\n return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)\n\n###########################################################\n# Masking the region of interest\n###########################################################\ndef region_of_interest(img, vertices):\n \"\"\"\n Applies an image mask.\n \n Only keeps the region of the image defined by the polygon\n formed from `vertices`. The rest of the image is set to black.\n \"\"\"\n #defining a blank mask to start with\n mask = np.zeros_like(img) \n \n #defining a 3 channel or 1 channel color to fill the mask with depending on the input image\n if len(img.shape) > 2:\n channel_count = img.shape[2] # i.e. 3 or 4 depending on your image\n ignore_mask_color = (255,) * channel_count\n else:\n ignore_mask_color = 255\n \n #filling pixels inside the polygon defined by \"vertices\" with the fill color \n cv2.fillPoly(mask, vertices, ignore_mask_color)\n \n #returning the image only where mask pixels are nonzero\n masked_image = cv2.bitwise_and(img, mask)\n return masked_image\n\n\n###########################################################\n# Calculate line gradients\n###########################################################\ndef line_params(x1,y1,x2,y2, xsize, ysize):\n \"\"\"\n Calculate the parameters for a hough line (slope, intercept, and extrapolations)\n \"\"\"\n #Generate m, c for line equation y=mx+c\n m = (y2 - y1)/(x2-x1)\n c = y1 - m*x1\n max_y = ysize\n if not math.isnan(1/m):\n max_x = (max_y-c)/m\n else:\n max_x = x2\n max_y = y2\n \n mid_y = ysize*0.6\n if not math.isnan(1/m):\n mid_x = (mid_y-c)/m\n else:\n mid_x = x2\n mid_y = y2\n return (m, c, mid_x, mid_y, max_x, max_y)\n\n###############################################################################################\n# Draw Lines based on a weighted average of the gradients for left and right.\n# This is actually a crappy implementation. Draw Lines 2 is better\n###############################################################################################\ndef draw_lines(img, lines, color=[0, 0, 255], thickness=5, filter_lines=True, min_slope=0.25):\n #Reject almost horizontal lines to try and cleanup last video\n xsize = img.shape[1] #Shape is used to determine where to extrapolate lines\n ysize = img.shape[0]\n rx_max = 0\n rx_mid = 0\n lx_max = 0 \n lx_mid = 0\n rm = 0\n lm = 0\n \n if filter_lines:\n for line in lines:\n for x1,y1,x2,y2 in line:\n params = line_params(x1,y1,x2,y2, xsize, ysize)\n if abs(params[0]) > min_slope:\n if params[0] > 0:\n #print(\"right\", params)\n rx_max += params[0] * params[4]\n rx_mid += params[0] * params[2]\n rm += params[0]\n else:\n #print(\"left\", params)\n lx_max += -1 * params[0] * params[4]\n lx_mid += -1 * params[0] * params[2]\n lm += -1 * params[0]\n #Calculate weighted average of coordinates to try and reject some of the noise\n y_mid = int(ysize/4)\n y_max = ysize\n if rm != 0 and not math.isnan(rx_max/rm):\n #rm = 1\n rx_max = int(rx_max / rm)\n rx_mid = int(rx_mid / rm)\n cv2.line(img,(rx_max,y_max),(rx_mid,y_mid), color, thickness)\n if lm != 0 and not math.isnan(lx_max/lm):\n #lm = 1\n lx_max = int(lx_max / lm)\n lx_mid = int(lx_mid / lm)\n cv2.line(img,(lx_max,y_max),(lx_mid,y_mid), color, thickness)\n else:\n for line in lines:\n for x1,y1,x2,y2 in line:\n params = line_params(x1,y1,x2,y2, xsize, ysize)\n if abs(params[0]) > min_slope:\n cv2.line(img, (x1, y1), (x2, y2), color, thickness)\n\n###############################################################################################\n# Draw Lines by grouping them by gradient. Lines with similar gradient and zero crossing \n# are assumed to be colinear and grouped together\n###############################################################################################\ndef draw_lines2(img, lines, color=[0, 0, 255], thickness=5, filter_lines=True, min_slope=0.25):\n #Reject almost horizontal lines to try and cleanup last video\n xsize = img.shape[1] #Shape is used to determine where to extrapolate lines\n ysize = img.shape[0]\n rx_max = 0\n rx_mid = 0\n lx_max = 0 \n lx_mid = 0\n rm = 0\n lm = 0\n \n if i == 0:\n x_train = np.array([img])\n else:\n x_train = np.append(x_train,[img], axis=0)\n \n if filter_lines:\n for line in lines:\n for x1,y1,x2,y2 in line:\n m, c, mid_x, mid_y, max_x, max_y = line_params(x1,y1,x2,y2, xsize, ysize)\n if abs(params[0]) > min_slope:\n if params[0] > 0:\n #print(\"right\", params)\n rx_max += params[0] * params[4]\n rx_mid += params[0] * params[2]\n rm += params[0]\n else:\n #print(\"left\", params)\n lx_max += -1 * params[0] * params[4]\n lx_mid += -1 * params[0] * params[2]\n\n###################################################### \n# Apply Hough Transform\n######################################################\ndef hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap, filter_lines=True, min_slope=0.25):\n \"\"\"\n `img` should be the output of a Canny transform.\n \n Returns an image with hough lines drawn.\n \"\"\"\n lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)\n line_img = np.zeros((*img.shape, 3), dtype=np.uint8)\n if lines is not None:\n draw_lines(line_img, lines, filter_lines=True, min_slope=0.25)\n return line_img\n\n######################################################\n# Overlay Hough lines on Image\n######################################################\ndef weighted_img(img, initial_img, α=0.8, β=1., λ=0.):\n \"\"\"\n `img` is the output of the hough_lines(), An image with lines drawn on it.\n Should be a blank image (all black) with lines drawn on it.\n \n `initial_img` should be the image before any processing.\n \n The result image is computed as follows:\n \n initial_img * α + img * β + λ\n NOTE: initial_img and img must be the same shape!\n \"\"\"\n return cv2.addWeighted(initial_img, α, img, β, λ)\n","sub_path":"ImageProcessing.py","file_name":"ImageProcessing.py","file_ext":"py","file_size_in_byte":17494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"43605406","text":"#!/usr/bin/python3\n\"\"\"Script that start a Flash web aplication\"\"\"\nfrom flask import Flask\nfrom flask import render_template\nfrom models import storage\n\n\napp = Flask(__name__)\n\n\n@app.teardown_appcontext\ndef delete_SQLA(self):\n \"\"\"Remove the current SQLAlchemySession\"\"\"\n storage.close()\n\n\n@app.route('/states', strict_slashes=False)\n@app.route('/states/', strict_slashes=False)\ndef display_HTML(id=None):\n \"\"\"Display a html with states and id cities\"\"\"\n states = storage.all('State')\n for state in states.values():\n if state.id == id:\n states = state\n return render_template('9-states.html', states=states, id=id)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000)\n","sub_path":"web_flask/9-states.py","file_name":"9-states.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"565841636","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import JsonResponse\nfrom project.models import Project\nfrom core.models import NPCStaff\nfrom project.forms import ProjectForm, EditProjectForm\nfrom project.tables import ProjectTable\nfrom django.contrib.auth.decorators import login_required\nfrom django_tables2 import RequestConfig\nimport json\n\n\n@login_required\ndef new_project(request):\n project_form = ProjectForm()\n if request.method == 'POST':\n project_form = ProjectForm(request.POST)\n if project_form.is_valid():\n project_form.save()\n return redirect('projects')\n\n context = {'project_form': project_form}\n return render(request, 'new_project.html', context)\n\n\ndef get_user_dicts(project):\n assigned = []\n unassigned = []\n users = NPCStaff.objects.all()\n for user in users:\n if project in user.project.all():\n assigned.append(user)\n else:\n unassigned.append(user)\n return {'assigned': assigned, 'unassigned': unassigned}\n\n\n@login_required\ndef edit_project(request, slug):\n project = get_object_or_404(Project, slug=slug)\n users = get_user_dicts(project)\n context = {'project_form': EditProjectForm(instance=project), 'users': users}\n\n if request.method == 'POST':\n project_form = EditProjectForm(request.POST, instance=project)\n if project_form.is_valid():\n project.save()\n return redirect('projects')\n context['project_form'] = project_form\n\n return render(request, 'edit_project.html', context)\n\n\n@login_required\ndef projects(request):\n projects_table = ProjectTable(Project.objects.all())\n RequestConfig(request).configure(projects_table)\n context = {'projects_table': projects_table}\n return render(request, 'projects.html', context)\n\n\n@login_required\ndef delete_project(request, slug):\n project = get_object_or_404(Project, slug=slug)\n project.delete()\n return redirect('projects')\n\n\ndef ajax_assign_user(request):\n if request.is_ajax() and request.method == 'POST':\n project = get_object_or_404(Project, pk=json.loads(request.POST['project_id']))\n user = get_object_or_404(NPCStaff, pk=json.loads(request.POST['user_id']))\n project.npcstaff_set.add(user)\n project.save()\n response_data = {'name': user.full_name}\n\n return JsonResponse(response_data)\n\n\ndef ajax_unassign_user(request):\n if request.is_ajax() and request.method == 'POST':\n project = get_object_or_404(Project, pk=json.loads(request.POST['project_id']))\n user = get_object_or_404(NPCStaff, pk=json.loads(request.POST['user_id']))\n project.npcstaff_set.remove(user)\n project.save()\n response_data = {'name': user.full_name}\n\n return JsonResponse(response_data)\n","sub_path":"project/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"351487864","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/6/6 下午4:40\n# @Author : Aries\n# @Site :\n# @File : tensorflow_reg.py\n# @Software: PyCharm\n'''\nTensorFlow中线性回归\n'''\nimport os\n\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn.datasets import fetch_california_housing\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nfrom command.DataUtils import serialize_data\n\n'''\n需要加入这一行 这样http证书就不会错误了\n'''\nimport ssl\n\nssl._create_default_https_context = ssl._create_unverified_context\n\n'''\n回顾之前的scikit可知 标准方程是成本函数对权重求偏导 得到最合适的权重(即此时成本函数最小)\n'''\nhousing = fetch_california_housing()\n# housing = load_housing_data()\nprint(type(housing))\nm, n = housing.data.shape\n# 增加偏置项\nhousing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data]\nserialize_data(housing, 'housing')\nserialize_data(housing_data_plus_bias, 'housing_data_plus_bias')\n'''\n构建计算机图\n'''\nX = tf.constant(housing_data_plus_bias, dtype=tf.float32, name='x')\nY = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name='y')\nXT = tf.transpose(X)\n'''\ntf.transpose: 矩阵的转置\ntf.matmul: 乘法\ntf.matrix_inverse: -1次方\n'''\nthera = tf.matmul(tf.matmul(tf.matrix_inverse(tf.matmul(XT, X)), XT), Y)\n\nwith tf.Session() as session:\n\tthera_value = thera.eval()\nprint(thera_value)\n","sub_path":"tensorFlow_master/core/reg_model/tensorflow_reg.py","file_name":"tensorflow_reg.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"553527096","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 14 22:56:00 2018\n\n@author: tao\n\"\"\"\nimport heapq as Heap\n\nclass Solution(object):\n def __init__(self, a=[]):\n self.a = a\n Heap.heapify(self.a) #transfer array to min heap\n self.sequence = []\n self.cost = 0\n \n def MergeSequence(self):\n if len(self.a) == 1 or len(self.a) == 0: #base case\n return self.a\n if len(self.a) > 1:\n list1 = Heap.heappop(self.a)\n list2 = Heap.heappop(self.a)\n self.sequence.append(list1)\n self.sequence.append(list2)\n new_list = list1+list2\n self.cost += new_list\n Heap.heappush(self.a, new_list)\n return self.MergeSequence()\n \n def PrintSequence(self):\n for i in range(len(self.sequence)):\n if i%2 == 1:\n times = i//2 + 1\n print(times, 'times merged lists:', self.sequence[i-1:i+1])\n \n def PrintCost(self):\n return 'Totoal Cost: ' + str(self.cost)\n","sub_path":"Project_2_main.py","file_name":"Project_2_main.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"264109166","text":"\"\"\"AT_MATHEUS_MARTINS URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\n# from django.contrib import admin\nfrom django.urls import path\nfrom gerenciador_pc import views\n\nurlpatterns = [\n # path('admin/', admin.site.urls),\n path('', views.index, name='index'),\n path('pc/', views.index, name='pc'),\n path('processos/', views.processos, name='processos'),\n path('arquivos/', views.arquivos, name='arquivos'),\n path('caminho-pasta/', views.caminho_pasta, name='caminho_pasta'),\n path('rede/', views.rede, name='rede'),\n path('relatorio/', views.relatorio, name='relatorio'),\n]\n","sub_path":"AT_MATHEUS_MARTINS/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"216440814","text":"\"\"\"A helper module for the polyglot-server test suite.\n\nAlthough the module is written in Python, it interacts with the server only\nthrough the standard sockets interface, and thus it can test a server written\nin any language.\n\nAuthor: Ian Fisher (iafisher@protonmail.com)\nVersion: August 2018\n\"\"\"\nimport inspect\nimport socket\nimport sys\nimport time\n\n\n# Time to wait, in seconds, before receiving the response to a request. If you\n# get spurious \"expected b'...', got nothing\" errors, try adjusting this value\n# upwards.\nTIME_TO_WAIT = 0.1\n\n\ndef ASSERT(cond, msg, *args):\n try:\n assert cond\n except AssertionError:\n lineno = inspect.getframeinfo(inspect.stack()[-1][0]).lineno\n sys.stderr.write(('Error ({}:{}): ' + msg + '\\r\\n').format(\n __file__, lineno, *args))\n\n\ndef ASSERT_EMPTY(client):\n time.sleep(TIME_TO_WAIT)\n try:\n data = client.recv(1024, socket.MSG_DONTWAIT)\n except BlockingIOError:\n pass\n else:\n ASSERT(data == b'', 'expected nothing, got {!r}', data)\n\n\ndef A(client, request, response):\n response = to_bytes(response)\n client.send(to_bytes(request))\n time.sleep(TIME_TO_WAIT)\n try:\n data = client.recv(4096, socket.MSG_DONTWAIT)\n except BlockingIOError:\n ASSERT(False, 'expected {!r}, got nothing', response)\n else:\n ASSERT(equivalent(response, data), 'expected {!r}, got {!r}',\n response, data)\n\n\ndef new_client(credentials=None):\n client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n client.connect((socket.gethostbyname('localhost'), 8888))\n if credentials is not None:\n A(client, b'register ' + to_bytes(credentials), 'success')\n return client\n\n\ndef to_bytes(str_or_bytes):\n if isinstance(str_or_bytes, str):\n return str_or_bytes.encode('utf-8') + b'\\r\\n'\n else:\n return str_or_bytes\n\n\ndef equivalent(expected, got):\n index = expected.find(b'')\n if index != -1:\n next_space = got.find(b' ', index + 1)\n if next_space == -1:\n next_space = len(got)\n return expected[:index] == got[:index] \\\n and equivalent(expected[index+11:], got[next_space:])\n else:\n return expected == got\n\n\n# REGISTRATION AND LOG-IN\niafisher = new_client()\nA(iafisher, 'register iafisher pwd', 'success')\nA(iafisher, 'login alice pwd', 'error must not be logged in')\nA(iafisher, 'register bob pwd123', 'error must not be logged in')\nA(iafisher, 'logout', 'success')\nA(iafisher, 'login iafisher not my password', 'error invalid username or password')\nA(iafisher, 'login iafisher pwd', 'success')\nA(iafisher, 'logout', 'success')\nA(iafisher, 'register some_other_user A strong password: 2018', 'success')\nA(iafisher, 'logout', 'success')\nA(iafisher, 'login iafisher pwd', 'success')\n\n\n# MESSAGING\nalice = new_client('alice pwd')\nbob = new_client('bob ajhnb375gjnajvna')\n# Inboxes should be empty.\nA(alice, 'recv', 'error inbox is empty')\nA(iafisher, 'recv', 'error inbox is empty')\nA(bob, 'recv', 'error inbox is empty')\n# One direct message\nA(alice, 'send bob Hello!', 'success')\n# Everyone else's inboxes should still be empty.\nA(alice, 'recv', 'error inbox is empty')\nA(iafisher, 'recv', 'error inbox is empty')\nA(bob, 'recv', 'message alice bob Hello!')\nA(bob, 'recv', 'error inbox is empty')\n# A broadcast message\nA(iafisher, \"send * What's up guys?\", 'success')\nA(alice, 'recv', \"message iafisher * What's up guys?\")\nA(bob, 'recv', \"message iafisher * What's up guys?\")\nA(iafisher, 'recv', \"message iafisher * What's up guys?\")\nA(alice, 'recv', 'error inbox is empty')\nA(bob, 'recv', 'error inbox is empty')\nA(iafisher, 'recv', 'error inbox is empty')\n# Multiple messages\nA(iafisher, 'send alice Hi Alice!', 'success')\nA(iafisher, 'send alice Are you there?', 'success')\nA(iafisher, 'send * Logging off now', 'success')\n# Make sure the order of retrieval is first-sent, first-received.\nA(alice, 'recv', b\"message iafisher alice Hi Alice!\\r\\nmessage iafisher alice Are you there?\\r\\nmessage iafisher * Logging off now\\r\\n\")\nA(alice, 'recv', 'error inbox is empty')\n# Clear the last broadcast message.\nA(iafisher, 'recv', 'message iafisher * Logging off now')\nA(bob, 'recv', 'message iafisher * Logging off now')\n# Whitespace is significant.\nA(alice, 'send bob leading whitespace', 'success')\nA(bob, 'recv', 'message alice bob leading whitespace')\n# Some error cases\nA(alice, 'send charlie This should not work.', 'error recipient does not exist')\nA(alice, 'send bob ' + 'a'*257, 'error message too long')\nA(alice, 'send bob ' + 'a'*256, 'success')\nA(bob, 'recv', 'message alice bob ' + 'a'*256)\n\n\n# SYNTAX\n# Username cannot be longer than 30 characters.\nsyntax_user = new_client()\nA(syntax_user, 'register ' + 'a'*31 + ' pwd', 'error username longer than 30 chars')\nA(syntax_user, 'register ' + 'a'*30 + ' pwd', 'success')\nA(syntax_user, 'logout', 'success')\n# 30 characters, not bytes.\nA(syntax_user, 'register дддддддддддддддддддддддддддддд pwd', 'success')\nA(syntax_user, 'logout', 'success')\n# Password cannot be longer than 50 characters.\nA(syntax_user, 'register jekvnkje ' + 'a'*51, 'error password longer than 50 chars')\nA(syntax_user, 'register jekvnkje ' + 'a'*50, 'success')\nA(syntax_user, 'logout', 'success')\n\n\n# UPLOAD AND DOWNLOAD\nupload_user = new_client('upload_user pwd')\nA(upload_user, 'listfiles', 'filelist')\n# Try downloading a non-existent file.\nA(upload_user, 'download hello.txt', 'error could not read from file')\nA(upload_user, 'upload hello.txt 6 hello\\n', 'success')\nA(upload_user, 'download hello.txt', 'file hello.txt 6 hello\\n')\n# Cannot overwrite pre-existing file.\nA(upload_user, 'upload hello.txt 7 goodbye', 'error file already exists')\nA(alice, 'upload hello.txt 7 goodbye', 'error file already exists')\n# Try uploading binary data.\nA(upload_user, b'upload junk.bin 5 \\xff\\xff\\xff\\xff\\xff\\r\\n', 'success')\nA(iafisher, 'download junk.bin', b'file junk.bin 5 \\xff\\xff\\xff\\xff\\xff\\r\\n')\nA(upload_user, 'listfiles', 'filelist hello.txt junk.bin')\n\n\n# AUTHENTICATION\nauth_user = new_client()\nA(auth_user, 'logout', 'error must be logged in')\nA(auth_user, 'send alice Hello!', 'error must be logged in')\nA(auth_user, 'recv alice', 'error must be logged in')\nA(auth_user, 'upload hello.txt 5 hello', 'error must be logged in')\nA(auth_user, 'download hello.txt', 'error must be logged in')\nA(auth_user, 'listfiles', 'error must be logged in')\n\n\n# INCORRECT SYNTAX\nbad_syntax_user = new_client()\nA(bad_syntax_user, 'register', 'error wrong number of fields')\nA(bad_syntax_user, 'register bad_syntax', 'error wrong number of fields')\nA(bad_syntax_user, 'register bad_syntax bad/as[hell)', 'success')\nA(bad_syntax_user, 'logout extra', 'error wrong number of fields')\nA(bad_syntax_user, 'logout', 'success')\nA(bad_syntax_user, 'login bad_syntax', 'error wrong number of fields')\nA(bad_syntax_user, 'login bad_syntax bad/as[hell)', 'success')\nA(bad_syntax_user, 'send iafisher', 'error wrong number of fields')\nA(bad_syntax_user, 'recv extra', 'error wrong number of fields')\nA(bad_syntax_user, 'upload', 'error wrong number of fields')\nA(bad_syntax_user, 'upload whatever.txt', 'error wrong number of fields')\nA(bad_syntax_user, 'upload whatever.txt 100', 'error wrong number of fields')\nA(bad_syntax_user, 'upload whatever.txt 3a abc', 'error invalid length field of upload message')\n\n\n# LONG MESSAGES\n# Yes, your password can be all whitespace.\nlong_user = new_client('long_user ')\nA(long_user, 'upload long.txt 1025 ' + 'a'*1025, 'success')\nA(long_user, 'download long.txt', 'file long.txt 1025 ' + 'a'*1025)\n# A command that straddles a message boundary.\nA(long_user, 'upload long2.txt 1000 ' + 'a'*1000 + '\\r\\nlistfiles',\n 'success\\r\\nfilelist hello.txt junk.bin long.txt long2.txt')\n\n\n# UTF-8 SUPPORT\nutf8_user = new_client('utf8_юникод мой пароль')\nA(utf8_user, 'logout', 'success')\nA(utf8_user, 'login utf8_юникод мой пароль', 'success')\nA(iafisher, 'send utf8_юникод Hello, 世界!', 'success')\n# Test each message type and a variety of scripts (Cyrillic, Chinese, Sanskrit).\nA(utf8_user, 'recv', 'message iafisher utf8_юникод Hello, 世界!')\nA(utf8_user, 'upload दस्तावेज़ 149 ॐ\\nश्रीपरमात्मने नमः\\nअथ श्रीमद्भगवद्गीता\\nप्रथमोऽध्यायः', 'success')\nA(utf8_user, 'listfiles', 'filelist hello.txt junk.bin long.txt long2.txt दस्तावेज़')\nA(utf8_user, 'download दस्तावेज़', 'file दस्तावेज़ 149 ॐ\\nश्रीपरमात्मने नमः\\nअथ श्रीमद्भगवद्गीता\\nप्रथमोऽध्यायः')\n\n# TRYING TO BREAK THE SERVER\npentest_user = new_client()\nA(pentest_user, b'\\r\\n', 'error no such command')\n# Server shouldn't crash when client closes connection.\npentest_user.send(b'logout\\r\\n')\npentest_user.close()\npentest_user = new_client()\nA(pentest_user, 'register infowarrior prophet of disaster', 'success')\n# Lie about the length of a file upload.\n# Note that there's no point in overstating the size of the file, because the\n# server will just spin until the stated number of bytes are available.\nA(pentest_user, 'upload hacker.exe 3 1234\\r\\nrecv', 'error message not terminated with CRLF\\r\\nerror inbox is empty')\nA(pentest_user, 'logout', 'success')\n# A password of a single space is allowed (but not encouraged).\nA(pentest_user, 'register pentest ', 'success')\nA(pentest_user, 'logout', 'success')\nA(pentest_user, 'login pentest ', 'success')\n# Make sure that a valid message sent after an invalid one is still processed.\nA(pentest_user, 'upload hacker.exe 3a _\\r\\nrecv', 'error invalid length field of upload message\\r\\nerror inbox is empty')\n# Leave the server hanging.\npentest_user.send(b'logout')\npentest_user.close()\n\n\nASSERT_EMPTY(iafisher)\nASSERT_EMPTY(bob)\nASSERT_EMPTY(alice)\nASSERT_EMPTY(syntax_user)\nASSERT_EMPTY(upload_user)\nASSERT_EMPTY(auth_user)\nASSERT_EMPTY(bad_syntax_user)\nASSERT_EMPTY(long_user)\nASSERT_EMPTY(utf8_user)\n","sub_path":"test/test_all.py","file_name":"test_all.py","file_ext":"py","file_size_in_byte":10262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"287499743","text":"from os.path import (join, isfile, basename, dirname)\nimport uuid\nimport zipfile\nimport glob\nimport logging\nimport json\nfrom subprocess import Popen\nimport os\nimport csv\nimport time\nimport datetime\n\nimport matplotlib\nmatplotlib.use('Agg') # noqa\nimport matplotlib.pyplot as plt\nimport torch\nfrom torch import optim\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torch.optim.lr_scheduler import CyclicLR\nimport numpy as np\n\nfrom rastervision.utils.files import (get_local_path, make_dir, upload_or_copy,\n list_paths, download_if_needed,\n sync_from_dir, sync_to_dir, str_to_file,\n zipdir, file_to_json, json_to_file)\nfrom rastervision.utils.misc import save_img\nfrom rastervision.backend import Backend\nfrom rastervision.data.label import SemanticSegmentationLabels\nfrom rastervision.utils.misc import terminate_at_exit\nfrom rastervision.backend.torch_utils.semantic_segmentation.plot import plot_xy\nfrom rastervision.backend.torch_utils.semantic_segmentation.data import build_databunch\nfrom rastervision.backend.torch_utils.semantic_segmentation.train import (\n train_epoch, validate_epoch)\nfrom rastervision.backend.torch_utils.semantic_segmentation.model import (\n get_model)\n\nlog = logging.getLogger(__name__)\n\n\ndef make_debug_chips(databunch, class_map, tmp_dir, train_uri, max_count=30):\n \"\"\"Save debug chips for a Databunch for a semantic segmentation dataset.\n\n This saves a plot for each example in the training and validation sets into\n train-debug-chips.zip and valid-debug-chips.zip under the train_uri. This\n is useful for making sure we are feeding correct data into the model.\n\n Args:\n databunch: DataBunch for semantic segmentation\n class_map: (rv.ClassMap) class map used to map class ids to colors\n tmp_dir: (str) path to temp directory\n train_uri: (str) URI of root of training output\n max_count: (int) maximum number of chips to generate. If None,\n generates all of them.\n \"\"\"\n\n def _make_debug_chips(split):\n debug_chips_dir = join(tmp_dir, '{}-debug-chips'.format(split))\n zip_path = join(tmp_dir, '{}-debug-chips.zip'.format(split))\n zip_uri = join(train_uri, '{}-debug-chips.zip'.format(split))\n make_dir(debug_chips_dir)\n ds = databunch.train_ds if split == 'train' else databunch.valid_ds\n for i, (x, y) in enumerate(ds):\n if i >= max_count:\n break\n\n fig, ax = plt.subplots(1)\n plot_xy(ax, x, class_map, y=y)\n plt.savefig(\n join(debug_chips_dir, '{}.png'.format(i)), figsize=(6, 6))\n plt.close()\n\n zipdir(debug_chips_dir, zip_path)\n upload_or_copy(zip_path, zip_uri)\n\n _make_debug_chips('train')\n _make_debug_chips('valid')\n\n\nclass PyTorchSemanticSegmentation(Backend):\n \"\"\"Semantic segmentation backend using PyTorch and fastai.\"\"\"\n\n def __init__(self, task_config, backend_opts, train_opts):\n \"\"\"Constructor.\n\n Args:\n task_config: (SemanticSegmentationConfig)\n backend_opts: (simple_backend_config.BackendOptions)\n train_opts: (pytorch_semantic_segmentation_backend_config.TrainOptions)\n \"\"\"\n self.task_config = task_config\n self.backend_opts = backend_opts\n self.train_opts = train_opts\n self.inf_learner = None\n\n torch_cache_dir = '/opt/data/torch-cache'\n os.environ['TORCH_HOME'] = torch_cache_dir\n\n self.model = None\n self.device = 'cuda' if torch.cuda.is_available() else 'cpu'\n log.info('Device = {}'.format(self.device))\n # TODO move this into the SemanticSegmentation RV task\n self.class_map = self.task_config.class_map.copy()\n self.class_map.add_nodata_item()\n\n def log_options(self):\n log.info('backend_opts:\\n' +\n json.dumps(self.backend_opts.__dict__, indent=4))\n log.info('train_opts:\\n' +\n json.dumps(self.train_opts.__dict__, indent=4))\n\n def process_scene_data(self, scene, data, tmp_dir):\n \"\"\"Make training chips for a scene.\n\n This writes a set of image chips to {scene_id}/img/{scene_id}-{ind}.png\n and corresponding label chips to {scene_id}/labels/{scene_id}-{ind}.png.\n\n Args:\n scene: (rv.data.Scene)\n data: (rv.data.Dataset)\n tmp_dir: (str) path to temp directory\n\n Returns:\n (str) path to directory with scene chips {tmp_dir}/{scene_id}\n \"\"\"\n scene_dir = join(tmp_dir, str(scene.id))\n img_dir = join(scene_dir, 'img')\n labels_dir = join(scene_dir, 'labels')\n\n make_dir(img_dir)\n make_dir(labels_dir)\n\n for ind, (chip, window, labels) in enumerate(data):\n chip_path = join(img_dir, '{}-{}.png'.format(scene.id, ind))\n label_path = join(labels_dir, '{}-{}.png'.format(scene.id, ind))\n\n label_im = labels.get_label_arr(window).astype(np.uint8)\n save_img(label_im, label_path)\n save_img(chip, chip_path)\n\n return scene_dir\n\n def process_sceneset_results(self, training_results, validation_results,\n tmp_dir):\n \"\"\"Write zip file with chips for a set of scenes.\n\n This writes a zip file for a group of scenes at {chip_uri}/{uuid}.zip containing:\n train/img/{scene_id}-{ind}.png\n train/labels/{scene_id}-{ind}.png\n val/img/{scene_id}-{ind}.png\n val/labels/{scene_id}-{ind}.png\n\n This method is called once per instance of the chip command.\n A number of instances of the chip command can run simultaneously to\n process chips in parallel. The uuid in the path above is what allows\n separate instances to avoid overwriting each others' output.\n\n Args:\n training_results: list of directories generated by process_scene_data\n that all hold training chips\n validation_results: list of directories generated by process_scene_data\n that all hold validation chips\n \"\"\"\n self.log_options()\n\n group = str(uuid.uuid4())\n group_uri = join(self.backend_opts.chip_uri, '{}.zip'.format(group))\n group_path = get_local_path(group_uri, tmp_dir)\n make_dir(group_path, use_dirname=True)\n\n with zipfile.ZipFile(group_path, 'w', zipfile.ZIP_DEFLATED) as zipf:\n\n def _write_zip(results, split):\n for scene_dir in results:\n scene_paths = glob.glob(join(scene_dir, '**/*.png'))\n for p in scene_paths:\n zipf.write(\n p,\n join(\n '{}/{}'.format(split,\n dirname(p).split('/')[-1]),\n basename(p)))\n\n _write_zip(training_results, 'train')\n _write_zip(validation_results, 'valid')\n\n upload_or_copy(group_path, group_uri)\n\n def train(self, tmp_dir):\n \"\"\"Train a model.\n\n This downloads any previous output saved to the train_uri,\n starts training (or resumes from a checkpoint), periodically\n syncs contents of train_dir to train_uri and after training finishes.\n\n Args:\n tmp_dir: (str) path to temp directory\n \"\"\"\n self.log_options()\n\n # Sync output of previous training run from cloud.\n train_uri = self.backend_opts.train_uri\n train_dir = get_local_path(train_uri, tmp_dir)\n make_dir(train_dir)\n sync_from_dir(train_uri, train_dir)\n\n # Get zip file for each group, and unzip them into chip_dir.\n chip_dir = join(tmp_dir, 'chips')\n make_dir(chip_dir)\n for zip_uri in list_paths(self.backend_opts.chip_uri, 'zip'):\n zip_path = download_if_needed(zip_uri, tmp_dir)\n with zipfile.ZipFile(zip_path, 'r') as zipf:\n zipf.extractall(chip_dir)\n\n # Setup data loader.\n batch_size = self.train_opts.batch_size\n chip_size = self.task_config.chip_size\n class_names = self.class_map.get_class_names()\n databunch = build_databunch(chip_dir, chip_size, batch_size,\n class_names)\n log.info(databunch)\n num_labels = len(databunch.label_names)\n if self.train_opts.debug:\n make_debug_chips(databunch, self.class_map, tmp_dir, train_uri)\n\n # Setup model\n num_labels = len(databunch.label_names)\n model = get_model(\n self.train_opts.model_arch, num_labels, pretrained=True)\n model = model.to(self.device)\n model_path = join(train_dir, 'model')\n\n # Load weights from a pretrained model.\n pretrained_uri = self.backend_opts.pretrained_uri\n if pretrained_uri:\n log.info('Loading weights from pretrained_uri: {}'.format(\n pretrained_uri))\n pretrained_path = download_if_needed(pretrained_uri, tmp_dir)\n model.load_state_dict(\n torch.load(pretrained_path, map_location=self.device))\n\n # Possibly resume training from checkpoint.\n start_epoch = 0\n train_state_path = join(train_dir, 'train_state.json')\n if isfile(train_state_path):\n log.info('Resuming from checkpoint: {}\\n'.format(model_path))\n train_state = file_to_json(train_state_path)\n start_epoch = train_state['epoch'] + 1\n model.load_state_dict(\n torch.load(model_path, map_location=self.device))\n\n # Write header of log CSV file.\n metric_names = ['precision', 'recall', 'f1']\n log_path = join(train_dir, 'log.csv')\n if not isfile(log_path):\n with open(log_path, 'w') as log_file:\n log_writer = csv.writer(log_file)\n row = ['epoch', 'time', 'train_loss'] + metric_names\n log_writer.writerow(row)\n\n # Setup Tensorboard logging.\n if self.train_opts.log_tensorboard:\n log_dir = join(train_dir, 'tb-logs')\n make_dir(log_dir)\n tb_writer = SummaryWriter(log_dir=log_dir)\n if self.train_opts.run_tensorboard:\n log.info('Starting tensorboard process')\n tensorboard_process = Popen(\n ['tensorboard', '--logdir={}'.format(log_dir)])\n terminate_at_exit(tensorboard_process)\n\n # Setup optimizer, loss, and LR scheduler.\n loss_fn = torch.nn.CrossEntropyLoss()\n lr = self.train_opts.lr\n opt = optim.Adam(model.parameters(), lr=lr)\n step_scheduler, epoch_scheduler = None, None\n num_epochs = self.train_opts.num_epochs\n\n if self.train_opts.one_cycle and num_epochs > 1:\n steps_per_epoch = len(databunch.train_ds) // batch_size\n total_steps = num_epochs * steps_per_epoch\n step_size_up = (num_epochs // 2) * steps_per_epoch\n step_size_down = total_steps - step_size_up\n step_scheduler = CyclicLR(\n opt,\n base_lr=lr / 10,\n max_lr=lr,\n step_size_up=step_size_up,\n step_size_down=step_size_down,\n cycle_momentum=False)\n for _ in range(start_epoch * steps_per_epoch):\n step_scheduler.step()\n\n # Training loop.\n for epoch in range(start_epoch, num_epochs):\n # Train one epoch.\n log.info('-----------------------------------------------------')\n log.info('epoch: {}'.format(epoch))\n start = time.time()\n train_loss = train_epoch(model, self.device, databunch.train_dl,\n opt, loss_fn, step_scheduler)\n if epoch_scheduler:\n epoch_scheduler.step()\n log.info('train loss: {}'.format(train_loss))\n\n # Validate one epoch.\n metrics = validate_epoch(model, self.device, databunch.valid_dl,\n num_labels)\n log.info('validation metrics: {}'.format(metrics))\n\n # Print elapsed time for epoch.\n end = time.time()\n epoch_time = datetime.timedelta(seconds=end - start)\n log.info('epoch elapsed time: {}'.format(epoch_time))\n\n # Save model and state.\n torch.save(model.state_dict(), model_path)\n train_state = {'epoch': epoch}\n json_to_file(train_state, train_state_path)\n\n # Append to log CSV file.\n with open(log_path, 'a') as log_file:\n log_writer = csv.writer(log_file)\n row = [epoch, epoch_time, train_loss]\n row += [metrics[k] for k in metric_names]\n log_writer.writerow(row)\n\n # Write to Tensorboard log.\n if self.train_opts.log_tensorboard:\n for key, val in metrics.items():\n tb_writer.add_scalar(key, val, epoch)\n tb_writer.add_scalar('train_loss', train_loss, epoch)\n for name, param in model.named_parameters():\n tb_writer.add_histogram(name, param, epoch)\n\n if (train_uri.startswith('s3://')\n and (((epoch + 1) % self.train_opts.sync_interval) == 0)):\n sync_to_dir(train_dir, train_uri)\n\n # Close Tensorboard.\n if self.train_opts.log_tensorboard:\n tb_writer.close()\n if self.train_opts.run_tensorboard:\n tensorboard_process.terminate()\n\n # Since model is exported every epoch, we need some other way to\n # show that training is finished.\n str_to_file('done!', self.backend_opts.train_done_uri)\n\n # Sync output to cloud.\n sync_to_dir(train_dir, self.backend_opts.train_uri)\n\n def load_model(self, tmp_dir):\n \"\"\"Load the model in preparation for one or more prediction calls.\"\"\"\n if self.model is None:\n model_uri = self.backend_opts.model_uri\n model_path = download_if_needed(model_uri, tmp_dir)\n\n num_classes = len(self.class_map)\n model = get_model(\n self.train_opts.model_arch, num_classes, pretrained=True)\n model = model.to(self.device)\n model.load_state_dict(\n torch.load(model_path, map_location=self.device))\n self.model = model\n\n def predict(self, chips, windows, tmp_dir):\n \"\"\"Return a prediction for a single chip.\n\n Args:\n chips: (numpy.ndarray) of shape (1, height, width, nb_channels)\n containing a single imagery chip\n windows: List containing a single (Box) window which is aligned\n with the chip\n\n Return:\n (SemanticSegmentationLabels) containing predictions\n \"\"\"\n self.load_model(tmp_dir)\n\n chips = torch.Tensor(chips).permute((0, 3, 1, 2)) / 255.\n chips = chips.to(self.device)\n model = self.model.eval()\n\n with torch.no_grad():\n out = model(chips)['out'].cpu()\n\n def label_fn(_window):\n if _window == windows[0]:\n return out[0].argmax(0).squeeze().numpy()\n else:\n raise ValueError('Trying to get labels for unknown window.')\n\n return SemanticSegmentationLabels(windows, label_fn)\n","sub_path":"rastervision/backend/pytorch_semantic_segmentation.py","file_name":"pytorch_semantic_segmentation.py","file_ext":"py","file_size_in_byte":15591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"81373354","text":"\"\"\"\n..\n Copyright (c) 2014-2015, Magni developers.\n All rights reserved.\n See LICENSE.rst for further information.\n\nModule providing abstract superclasses for validation.\n\nRoutine listings\n----------------\nMatrixBase(object)\n Abstract base class of custom matrix classes.\n\n\"\"\"\n\n\nclass MatrixBase(object):\n \"\"\"\n Abstract base class of custom matrix classes.\n\n The `magni.utils.validation.validate_numeric` function accepts built-in\n numeric types, numpy built-in numeric types, and subclasses of the present\n class. In order to perform validation checks, the validation function needs\n to know the data type, the bounds, and the shape of the variable. Thus,\n subclasses must call the init function of the present class with these\n arguments.\n\n Parameters\n ----------\n dtype : type\n The data type of the values of the instance.\n bounds : list or tuple\n The bounds of the values of the instance.\n shape : list or tuple\n The shape of the instance.\n\n Attributes\n ----------\n bounds : list or tuple\n The bounds of the values of the instance.\n dtype : type\n The data type of the values of the instance.\n shape : list or tuple\n The shape of the instance.\n\n Notes\n -----\n `dtype` is either a built-in numeric type or a numpy built-in numeric type.\n\n If the matrix has complex values, `bounds` is a list with two values; The\n bounds on the real values and the bounds on the imaginary values. If, on\n the other hand, the matrix has real values, `bounds` has one value; The\n bounds on the real values. Each such bounds value is a list with two real,\n numeric values; The lower bound (that is, the minimum value) and the upper\n bound (that is, the maximum value).\n\n \"\"\"\n\n def __init__(self, dtype, bounds, shape):\n self._dtype = dtype\n self._bounds = bounds\n self._shape = shape\n\n bounds = property(lambda self: self._bounds)\n dtype = property(lambda self: self._dtype)\n shape = property(lambda self: self._shape)\n","sub_path":"magni/utils/validation/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"25080380","text":"### 이 코드에서 계산중에 같이 collect할 수 있을거라 생각했는데 , 포기.\nfrom collections import defaultdict\nimport timing\n\n@timing.timing\ndef freq_seq_enum(sequences, min_support):\n '''Enumerates all frequent sequences.\n\n :param sequences: A sequence of sequences.\n :param min_support: The minimal support of a set to be included.\n :rtype: A set of (frequent_sequence, support).\n '''\n freq_seqs = set()\n _freq_seq(sequences, tuple(), 0, 0, min_support, freq_seqs)\n return freq_seqs\n\n\ndef _freq_seq(sdb, prefix, prefix_support, revisit_support, min_support, freq_seqs):\n if prefix:\n# print('prefix: yes', prefix)\n freq_seqs.add((prefix, prefix_support, revisit_support))\n# print('freq seqs', freq_seqs)\n locally_frequents = _local_freq_items(sdb, prefix, min_support)\n# print('locally frequents', locally_frequents)\n if not locally_frequents:\n# print ('not locally frequents')\n return\n for (item, support1, support2) in locally_frequents:\n new_prefix = prefix + (item,)\n new_sdb = _project(sdb, new_prefix)\n# print('new_prefix', new_prefix)\n# print('new_sdb', new_sdb)\n _freq_seq(new_sdb, new_prefix, support1, support2, min_support, freq_seqs)\n\n\ndef _local_freq_items(sdb, prefix, min_support):\n items = defaultdict(int) ## for support\n items2 = defaultdict(int) ## for revisit_intention_support\n freq_items = []\n for entry in sdb:\n visited = set()\n for element in entry[0]:\n# print (element)\n if element not in visited:\n items[element] += 1\n items2[element] += entry[1]\n visited.add(element)\n # Sorted is optional. Just useful for debugging for now.\n for item in items:\n support = items[item] ## support\n support2 = items2[item] ## revisit_intention\n if support >= min_support:\n freq_items.append((item, support, support2))\n return freq_items\n\n\ndef _project(sdb, prefix):\n new_sdb = []\n if not prefix:\n return sdb\n current_prefix_item = prefix[-1]\n for entry in sdb:\n j = 0\n projection = None\n for item in entry[0]:\n if item == current_prefix_item:\n projection = (entry[0][j + 1:], entry[1])\n break\n j += 1\n if projection:\n new_sdb.append(projection)\n return new_sdb\n\n\n\n","sub_path":"MSRA_proposal_wifi_log/code/code/seqmining_sd.py","file_name":"seqmining_sd.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"580841399","text":"'''\nShift Map Analysis for Image Restoration\nReference: Correcction of Distorted Underwater Images using Shift Map Analysis\n\nAvailable datasets:\n- mp4:\n Knife.mp4 (color/mono)\n Heater1.mp4 (color/mono)\n Heater2.mp4 (color/mono)\n Pool1.mp4 (color/mono)\n Pool2.mp4 (color/mono)\n Pool3.mp4 (color/mono)\n- mat:\n expdata_brick.mat (mono)\n expdata_checkboard.mat (mono)\n expdata_middle.mat (mono)\n expdata_large.mat (mono)\n expdata_small.mat (mono)\n expdata_tiny.mat (mono)\n'''\n\nfrom Functions import loadColorImage, processStack\nimport numpy as np\nfrom PIL import Image\nimport time\nimport matplotlib.pyplot as plt\nfrom scipy.io import savemat\nfrom multiprocessing import Pool\nimport warnings\n\ndef main(fileName, frameNum, saveFile):\n #Warning supprssion (Mostly CUDA warnings) \n warnings.filterwarnings('ignore') \n \n #Data loading\n Directory = \"Datasets/\"\n print(Directory+fileName)\n \n framesR, framesG, framesB = loadColorImage(Directory+fileName, int(frameNum))\n frames_x, frames_y, frames_z = np.shape(framesR)\n original = np.zeros((frames_x,frames_y,3), \"uint8\")\n output = np.zeros((frames_x,frames_y,3), \"uint8\")\n \n original[:,:,0] = framesR[:,:,0]\n original[:,:,1] = framesG[:,:,0]\n original[:,:,2] = framesB[:,:,0]\n original = Image.fromarray(original)\n \n #Model execution\n print(\"Restoration algorithm started...\") \n tic = time.time() \n pool = Pool(processes=3)\n temp = pool.map(processStack,[framesR,framesG,framesB]) \n pool.close()\n toc = time.time() \n \n #Normalize and save\n output[:,:,0] = temp[0] \n output[:,:,1] = temp[1] \n output[:,:,2] = temp[2] \n if(np.max(output) > 255):\n output = output*255/np.max(output) \n if(int(saveFile)==1):\n savemat(str(fileName)+'_Color.mat', {'recon':output}) \n output = Image.fromarray(output) \n \n print(\"Algorithm processing time\", round(toc-tic, ndigits=2), \"seconds\")\n \n #Output display\n plt.subplot(1,2,1)\n plt.imshow(original,cmap=\"gray\")\n plt.subplot(1,2,2)\n plt.imshow(output,cmap=\"gray\")\n plt.axis('off') \n plt.show()\n \n return output\n\nimport sys \nif __name__ == \"__main__\":\n main(sys.argv[1], sys.argv[2], sys.argv[3])","sub_path":"ShiftMapColor.py","file_name":"ShiftMapColor.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"274780868","text":"#---------------------------------------------------------------------------------\n# Run by PyCharm\n# number1 = numpy.random.rand(count) #0~1\n# number2 = number1[::-1] #切片倒序排列\n#--------------------------------Parameters---------------------------------------\n# is_visualmap=True #显示滑动条\n# visual_range_size=[a,b] #滑动条范围(取决于Y值!)\n# symbol=\"diamond/arrow/缺省\"\n# symbol_size=20 #气泡的大小\n#---------------------------------------------------------------------------------\n\n\n\nimport time\nfrom pyecharts import Scatter\nimport webbrowser\nimport numpy as np\n\n\ndef get_time():\n present_time = str(time.strftime(\"%Y-%m-%d %H:%M:%S\",time.localtime()))\n return present_time\n\n\ndef draw_scatter():\n x = np.random.rand(15)*100 # [0~1]\n y1 = np.random.rand(15)*100\n y2 = y1[::-1] # 切片倒序\n scatter = Scatter(\"散点图-气泡\", title_pos=\"center\")\n scatter.add(\n '数据A',\n x,\n y1,\n legend_pos=\"left\",\n is_visualmap=True, # 展示滑动条 -> 会产生一种颜色渐变的效果\n symbol_size=20,\n symbol=\"diamond\", # 默认圆形\n visual_range_size=[0, 100] # 滑动条滑动范围\n )\n scatter.add(\n '数据B',\n x,\n y2,\n legend_pos=\"left\",\n is_visualmap=True, # 展示滑动条 -> 会产生一种颜色渐变的效果\n symbol_size=20,\n symbol=\"arrow\", # 默认圆形\n visual_range_size=[0, 100] # 滑动条滑动范围\n\n )\n file = \"./html_file/scatter-\"+get_time()+\".html\"\n scatter.render(file)\n webbrowser.open(file)\n\n\nif __name__ == \"__main__\":\n draw_scatter()\n","sub_path":"Data_Visualisation/pyecharts/Scatter_figure.py","file_name":"Scatter_figure.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"95713026","text":"from django import forms\n\nfrom project.models import *\nfrom common.limit import input_project_name,input_part_station\n\n\nclass CreateProjectForm(forms.Form):\n project_name = forms.CharField(max_length=255, required=True,\n widget=forms.TextInput(attrs={'class': 'form-control'}),\n error_messages={'required': 'Project Name is empyt!',\n \"invalid\": \"Please insert valid Project Name\"})\n\n part_number = forms.CharField(max_length=255, required=True,\n widget=forms.TextInput(attrs={'class': 'form-control'}),\n error_messages={'required': 'PartNumber is empyt!',\n \"invalid\": \"Please insert valid PartNumber\"})\n\n def clean_project_name(self):\n project_name = self.cleaned_data[\"project_name\"]\n # if Project.objects.filter(project_name=project_name).count():\n # raise forms.ValidationError(\"Your Project Name cannot be repeated.Please modify your project name.\")\n\n\n r = input_project_name\n if r.search(project_name) == None:\n raise forms.ValidationError(\"Your Project Name not match the Project Name rules.\")\n\n\n\n def clean_part_number(self):\n part_number = self.cleaned_data['part_number']\n\n r = input_part_station\n\n if r.search(part_number) == None:\n raise forms.ValidationError(\"Your PartNumber not match the PartNumber rules.\")\n\n\n\n","sub_path":"project/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"497908466","text":"# 使用ZeroMQ的REQ与REP类型,来实现简单的请求-响应对\n# \nimport zmq\nfrom datetime import datetime\n\nhost = '127.0.0.1'\nport = 6789\ncontext = zmq.Context()\nserver = context.socket(zmq.REP)\t#服务类型为REP-同步响应\nserver.bind(\"tcp://%s:%s\"%(host, port))\nwhile True:\n\t# 等待客户端的下一个请求\n\tprint(\"I'm a server, and waiting for the client to call me.\")\n\treq_bytes = server.recv()\n\treq_str = req_bytes.decode('utf-8')\n\trep_str = bytes(datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"), 'utf-8')\n\tif req_str == 'time':\n\t\tserver.send(rep_str)\n\telse:\n\t\thandle_bytes = \"暗号不对!\".encode('utf-8')\n\t\tserver.send(handle_bytes)","sub_path":"python_to_apply/11th-2_chapter_network/exercise/2_zeromq_server.py","file_name":"2_zeromq_server.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"144331969","text":"#!/usr/bin/env python\n\nimport roslib\nimport rospy\nfrom geometry_msgs.msg import Twist\nfrom sensor_msgs.msg import Joy\n\nclass Teleop(object):\n\t'''\n\tA node that listens to joystick output, scales the values, and publishes\n\tthem as velocity commands.\n\t'''\n\n\tdef __init__(self, linearAxisIndex = 3, angularAxisIndex = 2):\n\t\t'''\n\t\tInitializes the receiver class. \n\t\tport: The serial port to listen to.\n\t\tbaudrate: Baud rate for the serial communication\n\t\t'''\n\n\t\trospy.init_node('p3dxJoyTeleop')\n\n\t\tself.lin_spd = 0\n\t\tself._LinearAxisIndex = rospy.get_param(\"~linearAxisIndex\", linearAxisIndex)\n\t\tself._AngularAxisIndex = rospy.get_param(\"~angularAxisIndex\", angularAxisIndex)\n\t\tself._LinearScalingFactor = rospy.get_param(\"~linearScalingFactor\", 0.2)\n\t\tself._AngularScalingFactor = rospy.get_param(\"~angularScalingFactor\", 0.5)\n\n\t\trospy.loginfo(\"Starting teleop node with linear axis %d and angular axis %d\" % (self._LinearAxisIndex, self._AngularAxisIndex))\n\n\t\t# subscriptions\n\t\trospy.Subscriber(\"/joy\", Joy, self._HandleJoystickMessage)\n\t\tself._VelocityCommandPublisher = rospy.Publisher(\"/cmd_vel\", Twist, queue_size=5)\n\n\tdef _HandleJoystickMessage(self, joyMessage):\n\t\trospy.logwarn(\"Handling joystick message: \" + str(joyMessage))\n\t\tang = 0\n\t\tMAX_FORWARD = 0.5\n\t\tMIN_FORWARD = -0.5\n\n\t\t#controle do lab 3 1 9 0 2 //controle nosso 0 2 9 3 1\n\t\t# triangle\n\t\tif (joyMessage.buttons[0] == 1 and (self.lin_spd <= MAX_FORWARD)):\n\t\t\tself.lin_spd += 0.05\n\n\t\t# x\n\t\tif (joyMessage.buttons[2] == 1 and (self.lin_spd >= MIN_FORWARD)):\n\t\t\tself.lin_spd -= 0.05\n\n\t\t# start\n\t\tif (joyMessage.buttons[9] == 1):\n\t\t\tself.lin_spd = 0\n\n\t\t# square\n\t\tif (joyMessage.buttons[3] == 1):\n\t\t\tang = 0.5\n\n\t\t# ball\n\t\tif (joyMessage.buttons[1] == 1):\n\t\t\tang = -0.5\n\n\t\tvelocityCommand = Twist()\n\t\tvelocityCommand.linear.x = self.lin_spd # self._LinearScalingFactor * joyMessage.axes[1]\n\t\tvelocityCommand.angular.z = self._AngularScalingFactor * ang\n\t\t\n\t\tself._VelocityCommandPublisher.publish(velocityCommand)\n\n\nif __name__ == '__main__':\n\tteleop = Teleop()\n\trospy.spin()\n\n","sub_path":"p3dx_navigation/scripts/p3dxJoyTeleop.py","file_name":"p3dxJoyTeleop.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"100830963","text":"''' Summer project \n\tSubmitted by - kumar shivam\n'''\n\n\nfrom tkinter import *\nfrom tkinter import font\nimport tkinter.messagebox\n\nwindow = Tk()\nwindow.title(\"Math is Fun Game\")\n\ncanvas = Canvas(width = \"400\" , height = \"400\")\ncanvas.pack()\n\nlbfont = font.Font(family = 'Times' , size = 20)\nl1 = Label(window , text = \"To play the game ,\\n press START button \\n then move your mouse randomly on the screen \\n then enter the solution.\" , font = lbfont)\nl1.pack()\n\nvar = StringVar()\nl2 = Label(canvas , textvariable = var)\nl2.pack()\n\ne = Entry(canvas)\ne.pack()\n\n\n\ndef callback():\n\ttemp = 0\n\tglobal x\n\tglobal y\n\tglobal t\n\twhile temp < 80000000:\n\t\tx = window.winfo_pointerx()\n\t\ty = window.winfo_pointery()\n\t\ttemp = temp + int(x) + int(y)\n\telse:\n\t\tp = str(x) + \" + \" + str(y) + \" = \"\n\t\tvar.set(p)\n\nt = 0\ndef test1():\n\tglobal t\n\tans = int(e.get())\n\tif ans == (int(x) + int(y)):\n\t\ttkinter.messagebox.showinfo(\"Bravo\" , \"YOU WIN\")\n\t\te.delete(0 , END)\n\t\tt = t + 10\n\t\tcallback()\n\telse:\n\t\ttkinter.messagebox.showerror(\"OOPS! You Lost\" , \"Your score \" + str(t) + \" , hit start again to restart the game\")\n\t\te.delete(0 , END)\n\t\t\n\ncheck = Button(canvas , text = \"Check\" , command = test1)\ncheck.pack()\n\nb1 = Button(window , text = '------START------' , command = callback)\nb1.pack()\n\nl3 = Label(text = \"GAME BY KUMAR SHIVAM\")\nl3.pack()\nwindow.mainloop()\n","sub_path":"randomAlgo/randomGame.py","file_name":"randomGame.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"246077652","text":"\n\nfrom xai.brain.wordbase.verbs._deny import _DENY\n\n#calss header\nclass _DENIES(_DENY, ):\n\tdef __init__(self,): \n\t\t_DENY.__init__(self)\n\t\tself.name = \"DENIES\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"deny\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_denies.py","file_name":"_denies.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"410865219","text":"import spacy\nimport json\nimport pprint\nfrom ElasticSearchConnection import *\n\n# from QuerySearch import*\nclass ElasticSearchQuery:\n \n def __init__(self):\n pass\n\n def QueryJobStatic(self,jobnames,attributes):\n \n attributes.append('job_name')\n body={\n \"_source\":attributes,\n \"query\":{\n \"terms\":{\n \"job_name\":jobnames}}}\n return body\n\n\n def QueryJobDynamic1(self,jobnames,attributes):\n \n attributes.append('job_name')\n body={\n \"_source\":attributes,\n \"query\":{\n \"bool\":{\n \"must\":[{\n \"terms\":{\n \"job_name\":jobnames}},\n {\"match\":{\"status\":\"SUCCEEDED\"}}]\n }\n },\n \"sort\":[{\"log_date\":{\"order\":\"desc\"}}],\"size\":1\n }\n return body\n\n\n def QueryJobDynamic2(self,jobnames,attributes):\n \n attributes.append('job_name')\n body={\n \"_source\":attributes,\n \"query\":{\n \"bool\":{\n \"must\":[{\n \"terms\":{\n \"job_name\":jobnames\n }\n }]\n }\n },\"sort\":[{\"log_date\":{\"order\":\"desc\"}}],\n \"size\":1\n }\n return body\n\n def QueryCatalog1(self,attribute_name,attributes,entity_name):\n \n attributes.append('Attribute Name')\n if entity_name!=[]:\n attributes.append('Entity Name')\n if entity_name!=[]: \n body={\n \"_source\":attributes,\n \"query\":{\n \"bool\":{\n \"must\":[\n { \"terms\":{\"Attribute Name\":attribute_name}},\n {\"terms\":{\"Entity Name\":entity_name}}]}}}\n return body\n else:\n body={\n \"_source\":attributes,\n \"query\":{\n \"bool\":{\n \"must\":[\n {\"terms\":{\"Attribute Name\":attribute_name}}]}}}\n return body\n\n def QueryCatalog2(self,entity_name,entity_attributes):\n \n entity_attributes.append('Entity Name')\n body={\n \"_source\":entity_attributes,\n \"query\":{\n \"terms\":{\n \"Entity Name\":entity_name\n }\n }\n }\n return body\n\n def QueryGlossary(self,name,attributes):\n attributes.append('Name')\n body={\n \"_source\":attributes,\n \"query\":{\n \"match\":{\"Name\":name}\n }\n }\n return body\n \n def FetchJobResults(self,JobAndAttributes):\n \n NonEmptyJobNames=0\n AllAttributes=[]\n FetchedResults=[]\n \n for item in JobAndAttributes:\n JobName=item['jobname']\n \n if(JobName!=[]):\n NonEmptyJobNames+=1\n\n StaticAttributes=item['att']\n DynamicAttributes=item['att1']\n\n AllAttributes.extend(StaticAttributes)\n AllAttributes.extend(DynamicAttributes)\n\n print('Jobname: ',JobName)\n print('Static job details: ',StaticAttributes)\n print('Dynamic job details: ',DynamicAttributes)\n print('Fetching data from elastic search...') \n if StaticAttributes!=[]:\n # To fetch job details from elastic search\n body = self.QueryJobStatic(JobName,StaticAttributes)\n res = es.search(index='test',doc_type='_doc',body=body)\n # print('Data fetched from elastic search: ')\n # pprint.pprint(res)\n for i in res['hits']['hits']:\n FetchedResults.append(json.dumps(i['_source'],indent=4))\n body1={}\n if DynamicAttributes!=[]:\n # To fetch execution details from elastic search\n if (all(x in DynamicAttributes for x in ['status', 'run_duration'])):\n body1=self.QueryJobDynamic2(JobName,DynamicAttributes)\n\n elif 'run_duration' in DynamicAttributes:\n body1=self.QueryJobDynamic1(JobName,DynamicAttributes)\n\n elif 'status' in DynamicAttributes or 'log_date' in DynamicAttributes :\n body1=self.QueryJobDynamic2(JobName,DynamicAttributes) \n\n else:\n body1=self.QueryJobStatic(JobName,DynamicAttributes)\n res1 = es.search(index='test1',doc_type='_doc',body=body1)\n # print('Data fetched from elastic search: ')\n # pprint.pprint(res1)\n for i in res1['hits']['hits']:\n FetchedResults.append(json.dumps(i['_source'],indent=4))\n \n return NonEmptyJobNames,FetchedResults,AllAttributes\n\n def FetchCatalogResults(self,AttributeName,EntityName,Attributes,EntityAttributes):\n \n FetchedResults=[]\n if Attributes!=[]: \n attr_body = self.QueryCatalog1(AttributeName,Attributes,EntityName)\n res = es.search(index='ocidw',doc_type='_doc',body=attr_body)\n # print(res)\n print('Data fetched from elastic search: ',res)\n for i in res['hits']['hits']:\n FetchedResults.append(json.dumps(i['_source'],indent=4))\n\n if EntityAttributes!=[]:\n ent_body=self.QueryCatalog2(EntityName,EntityAttributes)\n # print('body1: ',body1)\n res1 = es.search(index='ocidw_ent',doc_type='_doc',body=ent_body)\n print('Data fetched from elastic search: ',res1)\n for i in res1['hits']['hits']:\n FetchedResults.append(json.dumps(i['_source'],indent=4))\n \n \n return FetchedResults\n\n def FetchGlossaryResults(self,GlossaryAndAttributes):\n \n NonEmptyGlossaryNames=0\n AllAttributes,FetchedResults=[],[]\n \n for item in GlossaryAndAttributes:\n names=item['name']\n if(names!=[]):\n NonEmptyGlossaryNames+=1\n\n attributes=item['att']\n \n AllAttributes.extend(attributes)\n print('Name: ',names)\n print('details: ',attributes)\n\n print('Fetching data from elastic search...') \n for name in names:\n if attributes!=[]:\n body = self.QueryGlossary(name,attributes)\n res = es.search(index='glossary2',doc_type='_doc',body=body)\n print('Data fetched from elastic search: ')\n pprint.pprint(res)\n for i in res['hits']['hits']:\n FetchedResults.append(json.dumps(i['_source'],indent=4))\n \n return NonEmptyGlossaryNames,FetchedResults,AllAttributes\n\n\n","sub_path":"Server/ElasticSearchQuery.py","file_name":"ElasticSearchQuery.py","file_ext":"py","file_size_in_byte":6941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"23274565","text":"#!/usr/bin/env python\nfrom runtime_context import LOGGER\nfrom lib.cf_utils import cf_function\n\n\n@cf_function(Path='/docreview/notify/reviewer')\ndef notify_reviewer(event, context):\n \"\"\"notify reviewer function\"\"\"\n LOGGER.info('Notify reviewer')\n LOGGER.info(event.get('body'))\n return {\n 'statusCode': 200\n }\n\n\n@cf_function(Path='/docreview/document/summarize')\ndef summarize_document(event, context):\n \"\"\"summarize document function\"\"\"\n LOGGER.info('Summarize document')\n LOGGER.info(event.get('body'))\n return {\n 'statusCode': 200\n }\n\n\n@cf_function(Path='/docreview/notify/uploader')\ndef notify_uploader(event, context):\n \"\"\"notify uploader function\"\"\"\n LOGGER.info('Notify uploader')\n LOGGER.info(event.get('body'))\n return {\n 'statusCode': 200\n }\n\n\n@cf_function(Path='/docreview/document/delete')\ndef delete_document(event, context):\n \"\"\"delete document function\"\"\"\n LOGGER.info('Delete document')\n LOGGER.info(event.get('body'))\n return {\n 'statusCode': 200\n }\n\n\n@cf_function(Path='/docreview/document/archive')\ndef archive_document(event, context):\n \"\"\"archive original document function\"\"\"\n LOGGER.info('Archive original document')\n LOGGER.info(event.get('body'))\n return {\n 'statusCode': 200\n }\n","sub_path":"source/functions/document_tasks.py","file_name":"document_tasks.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"558320117","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.conf import settings\nfrom rent.models import Game, Order, Rent\nfrom user.models import User\nfrom rent.views import rent_game, empty_cart\nfrom payment.models import Contend\nfrom payment.forms import newContend\nimport stripe\nfrom django.core.mail import EmailMessage\n\ndef pay(request):\n key = settings.STRIPE_PUBLISHABLE_KEY\n return render(request,'home.html',{'key':key})\n\ndef charge(request,id_cart):\n cart = get_object_or_404(Order, pk=id_cart)\n if request.method == 'POST':\n charge = stripe.Charge.create(\n amount=int(cart.get_total_price()*100),\n currency='eur',\n description='A Django charge',\n source=request.POST['stripeToken'],\n api_key=settings.STRIPE_SECRET_KEY\n )\n for item in cart.items.all():\n rent_game(request,item.game.id, item.days, item.initial_date)\n #rent_game(request,id_game)\n return redirect('/success/')\n\ndef pago_completado(request):\n empty_cart(request)\n return render(request,'pago_completado.html')\n\ndef confirm(request,id_cart):\n cart = get_object_or_404(Order, pk=id_cart)\n sum = cart.get_total_price()\n key = settings.STRIPE_PUBLISHABLE_KEY\n return render(request,'aceptacion_pago.html',{'order':cart.get_cart_items(), 'id':cart.id,'key':key, 'cent':int(sum*100), 'total':sum})\n\ndef new_contend(request,pk):\n rent = get_object_or_404(Rent,pk=pk)\n\n if request.method == \"POST\":\n form = newContend(request.POST)\n\n if form.is_valid():\n \n description = form.cleaned_data['description']\n status = 'PENDING'\n\n contend = Contend(owner=request.user,rent=rent,status=status,description=description)\n contend.save()\n\n return redirect('/myGames/')\n else:\n form = newContend()\n\n return render(request, 'newContend.html', {'form': form})\n\ndef contend_list(request):\n contends = Contend.objects.all()\n return render(request, 'contends.html', {'contends':contends})\n\ndef contend_detail(request,pk):\n contend = get_object_or_404(Contend, pk=pk)\n return render(request,'contendDetail.html', {'contend':contend})\n\ndef new_compensation(request,pk):\n price = request.POST.get('price')\n contend = get_object_or_404(Contend,pk=pk)\n\n #Contend\n Contend.objects.filter(id=pk).update(price=price,status='ACCEPTED')\n\n #Message\n title = 'Mensaje del administrador de TryOnBoard' \n body = 'Usted ha recibido una disputa.' + '\\n'\n\n body += 'Usuario que abrió la disputa:'+ contend.owner.username + '\\n'\n body += 'Sobre el juego que alquiló:'+ '\\n' \n body += contend.rent.ticker + '\\n'\n body += 'Nombre del juego:'+ contend.rent.game.name + '\\n'\n body += 'Indemnización puesta por el administrador:'+ price + '\\n'\n emailto = contend.rent.user.email\n \n email = EmailMessage(title,body,to=[emailto])\n email.send()\n\n return redirect('/contends/')","sub_path":"board/payment/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"276183332","text":"import csv, wget,urllib,shutil\n\nfileurl='https://raw.githubusercontent.com/bryangruneberg/gsm-assessment-data/master/kafka.csv'\nimgfolder = '/opt/amazee/img/'\ncsvfile=wget.download(fileurl)\nhtml = \" \"\nhtml_footer = \"\"\nimg_table = \"\"\nimg_table_footer = \"
    \"\n\nprint('\\n')\n\n#response = urllib.request.urlopen(fileurl)\n#dd = response.read();\n#tt = dd.decode('utf-8')\n\ncounter = 0\ntblcolcounter = 0\ntxtfile=open(csvfile,'r')\ntblrow=\"\"\nfor row in txtfile:\n\tif counter==0:\n\t\tprint('skip the file header')\n\t\tprint('\\n')\n\t\t## do nothing (skips the header row)\n\telse:\n\t\titem = row.split(',')\n\t\timgurl = item[6]\n\t\timgname = item[0]+'.png'\n\t\timg_w = item[1]\n\t\timg_h = item[2]\n\n\t\timgcontent=urllib.request.urlretrieve(imgurl,imgname)\n\t\t# move the image to the img folder\n\t\tshutil.move(imgname,imgfolder)\n\t\tprint(imgcontent)\n\n\tif tblcolcounter==0 and counter!=0:\n\t\ttblrow += ''+imgname+''\t\n\telif tblcolcounter==3 and counter!=0:\n\t\ttblcounter=0\n\t\ttblrow += ''+imgname+'/tr>'\n\telse:\n\t\ttblrow += ''+imgname+''\n\t\tcounter += 1\n\n\tprint(tblrow)\n\ttblcolcounter += 1\n\n\nprint('hello')\n\n","sub_path":"scenario4/backup.py","file_name":"backup.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"233042678","text":"\n#SET THE FOLLOWING ENVIRONMENT VARIABLES BEFORE RUNNING THIS PROGRAM:\n # SPOTIPY_CLIENT_ID\n # SPOTIPY_CLIENT_SECRET\n # SPOTIPY_REDIRECT_URI\n\nimport spotipy\nimport spotipy.util as util\n\n\nscope = 'user-library-read'\n\ntoken = util.prompt_for_user_token(\"harry.roxas11\", scope) #CHANGE FIRST PARAMETER TO YOUR SPOTIFY DEVELOPER ACCOUNT\n\n#Open file with track ids and their spotify ids and save to dictionary\nall_tracks = {}\nwith open(\"track_tags2.txt\") as f:\n all_tracks = dict(x.rstrip().split(None, 1) for x in f)\n\nif token: #Check if succesful connection to spotify api\n sp = spotipy.Spotify(auth=token)\n\n #GET SPOTIFY AUDIO FEATURES FOR EACH TRACK\n with open(\"dataset.csv\", 'w') as f: #save to csv file\n for id in all_tracks.keys():\n all_tracks[id] = eval(all_tracks[id])\n\n spotifyID = all_tracks[id][2]\n try:\n features = sp.audio_features(spotifyID)[0] #api call to get spotify audio features\n \n f.write(\"%s,%f,%f,%f,%f,%f,%f,%s\\n\" % (id,features['danceability'],features['acousticness'],features['energy'],features['loudness'],features['tempo'],features['valence'],all_tracks[id][0]))\n except spotipy.client.SpotifyException: # catch if token expires to renew token\n token = util.prompt_for_user_token(\"harry.roxas11\", scope)\n sp = spotipy.Spotify(auth=token)\n\n features = sp.audio_features(spotifyID)[0]\n \n f.write(\"%s,%f,%f,%f,%f,%f,%f,%s\\n\" % (id,features['danceability'],features['acousticness'],features['energy'],features['loudness'],features['tempo'],features['valence'],all_tracks[id][0]))","sub_path":"get_audio_features.py","file_name":"get_audio_features.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"438703743","text":"import matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.widgets import Slider\n\n# Configuration de l'affichage de matplotlib\n# matplotlib.use('Qt5Agg') # A utiliser sur Linux\nmatplotlib.use('TkAgg') # A utiliser sur Windows\n\n# Contact rate, beta, and mean recovery rate, gamma, (in 1/days).\nINIT_ALPHA = 0.75 # Taux d'incubation (0-1)\nINIT_BETA = 0.8 # Taux de transmission (0-1)\nINIT_GAMMA = 0.05 # Taux de guérison (0-1)\nINIT_MICRO = 0.01 # Taux de mortalité (0-1)\nINIT_NU = 0.009 # Taux de natalité (0-0.5)\n\n# Populations initiales\nN0 = 1000 # Population\nE0 = 0 # Nombre initial de personnes infectées non-infectieuses\nI0 = 5 # Nombre initial de personnes infectées infectieuses\nR0 = 0 # Nombre initial de personnes retirées\nS0 = N0 - (I0 + R0 + E0) # Nombre initial de personnes Saines\n\n# Precision et durée de la simulation\nSIM_PRECISION = 1000\nSIM_MULTIPLIER = 2\n\n\ndef solve(S0, E0, I0, R0, alpha, beta, gamma, micro, nu):\n S, E, I, R = [S0], [E0], [I0], [R0]\n h = 1/SIM_PRECISION\n for o in range(SIM_PRECISION*SIM_MULTIPLIER):\n St, Et, It, Rt = S[o-1], E[o-1], I[o-1], R[o-1]\n\n #Equations\n dSdt = -beta*St*It + nu*(St+Et+It+Rt) - micro*St\n dEdt = beta*St*It - alpha*Et - micro*Et\n dIdt = alpha*Et - gamma*It - micro*It\n dRdt = gamma*It - micro*Rt\n\n S.append(St+h* dSdt)\n E.append(Et+h* dEdt)\n I.append(It+h* dIdt)\n R.append(Rt+h* dRdt)\n return S, E, I, R\n\n\n# The function to be called anytime a slider's value changes\ndef update(_x):\n \"\"\"\n Méthode appelée a chaque changement des sliders. Recalcule les courbes et les affiche.\n \"\"\"\n S, E, I, R = solve(S0, E0, I0, R0, alpha_slider.val, beta_slider.val, gamma_slider.val, micro_slider.val, nu_slider.val)\n line1.set_ydata(S)\n line2.set_ydata(E)\n line3.set_ydata(I)\n line4.set_ydata(R)\n N = [S[i] + E[i] + I[i] + R[i] for i in range(len(S))]\n line5.set_ydata(N)\n fig.canvas.draw_idle()\n\n\nS, E, I, R = solve(S0, E0, I0, R0, INIT_ALPHA, INIT_BETA, INIT_GAMMA, INIT_MICRO, INIT_NU)\nN = [S[i] + E[i] + I[i] + R[i] for i in range(len(S))]\n\nfig, ax = plt.subplots()\nax.margins(x=0)\n\nline1, = plt.plot(S, label=\"Sains\")\nline2, = plt.plot(E, label=\"Exposed\")\nline3, = plt.plot(I, label=\"Infectes\")\nline4, = plt.plot(R, label=\"Recovered\")\nline5, = plt.plot(N, label=\"Population\")\n\n# Ajustement des tracés principaux pour faire de la place aux sliders\nplt.subplots_adjust(left=0.1, bottom=0.5, top=1)\nax.set_xlabel('Time [days]')\nax.legend()\n\n# Slider Horizontal alpha\nalpha_slider = Slider(\n ax=plt.axes([0.1, 0.25, 0.8, 0.03], facecolor=\"lightgoldenrodyellow\"),\n label='α (Incubation)',\n valmin=0,\n valmax=1,\n valinit=INIT_ALPHA,\n color=\"grey\"\n)\n\n# Slider Horizontal beta\nbeta_slider = Slider(\n ax=plt.axes([0.1, 0.20, 0.8, 0.03], facecolor=\"lightgoldenrodyellow\"),\n label='β (Transmission)',\n valmin=0,\n valmax=1,\n valinit=INIT_BETA,\n color=\"red\"\n)\n\n# Slider Horizontal gamma\ngamma_slider = Slider(\n ax=plt.axes([0.1, 0.15, 0.8, 0.03], facecolor=\"lightgoldenrodyellow\"),\n label='γ (Guérison)',\n valmin=0,\n valmax=1,\n valinit=INIT_GAMMA,\n color=\"green\"\n)\n\n# Slider Horizontal micro\nmicro_slider = Slider(\n ax=plt.axes([0.1, 0.10, 0.8, 0.03], facecolor=\"lightgoldenrodyellow\"),\n label='μ (Mortalité)',\n valmin=0,\n valmax=1,\n valinit=INIT_MICRO,\n color=\"black\"\n)\n\n# Slider Horizontal nu\nnu_slider = Slider(\n ax=plt.axes([0.1, 0.05, 0.8, 0.03], facecolor=\"lightgoldenrodyellow\"),\n label='ν (Natalité)',\n valmin=0,\n valmax=0.5,\n valinit=INIT_NU,\n color=\"pink\"\n)\n\n# register the update function with each slider\nalpha_slider.on_changed(update)\nbeta_slider.on_changed(update)\ngamma_slider.on_changed(update)\nmicro_slider.on_changed(update)\nnu_slider.on_changed(update)\n\nplt.show()\n","sub_path":"SEIR.py","file_name":"SEIR.py","file_ext":"py","file_size_in_byte":3864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"83584572","text":"import numpy as np\n\nfrom . import Geometry, GeometryType, lib\nfrom ._geometry import collections_1d, polygons_1d, simple_geometries_1d\nfrom .decorators import multithreading_enabled\n\n__all__ = [\n \"points\",\n \"linestrings\",\n \"linearrings\",\n \"polygons\",\n \"multipoints\",\n \"multilinestrings\",\n \"multipolygons\",\n \"geometrycollections\",\n \"box\",\n \"prepare\",\n \"destroy_prepared\",\n]\n\n\ndef _xyz_to_coords(x, y, z):\n if y is None:\n return x\n if z is None:\n coords = np.broadcast_arrays(x, y)\n else:\n coords = np.broadcast_arrays(x, y, z)\n return np.stack(coords, axis=-1)\n\n\n@multithreading_enabled\ndef points(coords, y=None, z=None, indices=None, **kwargs):\n \"\"\"Create an array of points.\n\n Note that GEOS >=3.10 automatically converts POINT (nan nan) to\n POINT EMPTY.\n\n Parameters\n ----------\n coords : array_like\n An array of coordinate tuples (2- or 3-dimensional) or, if `y` is\n provided, an array of x coordinates.\n y : array_like\n z : array_like\n indices : array_like or None\n Indices into the target array where input coordinates belong. If\n provided, the coords should be 2D with shape (N, 2) or (N, 3) and\n indices should be 1D with shape (N,). Missing indices will give None\n values in the output array.\n **kwargs\n For other keyword-only arguments, see the\n `NumPy ufunc docs `_.\n Ignored if ``indices`` is provided.\n \"\"\"\n coords = _xyz_to_coords(coords, y, z)\n if indices is None:\n return lib.points(coords, **kwargs)\n else:\n return simple_geometries_1d(coords, indices, GeometryType.POINT)\n\n\n@multithreading_enabled\ndef linestrings(coords, y=None, z=None, indices=None, **kwargs):\n \"\"\"Create an array of linestrings.\n\n This function will raise an exception if a linestring contains less than\n two points.\n\n Parameters\n ----------\n coords : array_like\n An array of lists of coordinate tuples (2- or 3-dimensional) or, if `y`\n is provided, an array of lists of x coordinates\n y : array_like\n z : array_like\n indices : array_like or None\n Indices into the target array where input coordinates belong. If\n provided, the coords should be 2D with shape (N, 2) or (N, 3) and\n indices should be 1D with shape (N,). Missing indices will give None\n values in the output array.\n **kwargs\n For other keyword-only arguments, see the\n `NumPy ufunc docs `_.\n Ignored if ``indices`` is provided.\n \"\"\"\n coords = _xyz_to_coords(coords, y, z)\n if indices is None:\n return lib.linestrings(coords, **kwargs)\n else:\n return simple_geometries_1d(coords, indices, GeometryType.LINESTRING)\n\n\n@multithreading_enabled\ndef linearrings(coords, y=None, z=None, indices=None, **kwargs):\n \"\"\"Create an array of linearrings.\n\n If the provided coords do not constitute a closed linestring, the first\n coordinate is duplicated at the end to close the ring. This function will\n raise an exception if a linearring contains less than three points or if\n the terminal coordinates contain NaN (not-a-number).\n\n Parameters\n ----------\n coords : array_like\n An array of lists of coordinate tuples (2- or 3-dimensional) or, if `y`\n is provided, an array of lists of x coordinates\n y : array_like\n z : array_like\n indices : array_like or None\n Indices into the target array where input coordinates belong. If\n provided, the coords should be 2D with shape (N, 2) or (N, 3) and\n indices should be 1D with shape (N,). Missing indices will give None\n values in the output array.\n **kwargs\n For other keyword-only arguments, see the\n `NumPy ufunc docs `_.\n Ignored if ``indices`` is provided.\n \"\"\"\n coords = _xyz_to_coords(coords, y, z)\n if indices is None:\n return lib.linearrings(coords, **kwargs)\n else:\n return simple_geometries_1d(coords, indices, GeometryType.LINEARRING)\n\n\n@multithreading_enabled\ndef polygons(shells, holes=None, indices=None, **kwargs):\n \"\"\"Create an array of polygons.\n\n Parameters\n ----------\n shell : array_like\n An array of linearrings that constitute the out shell of the polygons.\n Coordinates can also be passed, see linearrings.\n holes : array_like or None\n An array of lists of linearrings that constitute holes for each shell.\n indices : array_like or None\n Indices into the shells array where input holes belong. If\n provided, shells, holes, and indices should all be 1D and the size\n of holes must equal the size of indices.\n **kwargs\n For other keyword-only arguments, see the\n `NumPy ufunc docs `_.\n Ignored if ``indices`` is provided.\n \"\"\"\n shells = np.asarray(shells)\n if not isinstance(shells, Geometry) and np.issubdtype(shells.dtype, np.number):\n shells = linearrings(shells)\n\n if holes is None and indices is not None:\n raise TypeError(\"Indices provided without a holes array.\")\n elif holes is None:\n # no holes provided: initialize an empty holes array matching shells\n shape = shells.shape + (0,) if isinstance(shells, np.ndarray) else (0,)\n holes = np.empty(shape, dtype=object)\n else:\n holes = np.asarray(holes)\n # convert holes coordinates into linearrings\n if np.issubdtype(holes.dtype, np.number):\n holes = linearrings(holes)\n\n if indices is None:\n return lib.polygons(shells, holes, **kwargs)\n else:\n return polygons_1d(shells, holes, indices)\n\n\n@multithreading_enabled\ndef box(xmin, ymin, xmax, ymax, ccw=True, **kwargs):\n \"\"\"Create box polygons.\n\n Parameters\n ----------\n xmin : array_like\n ymin : array_like\n xmax : array_like\n ymax : array_like\n ccw : bool (default: True)\n If True, box will be created in counterclockwise direction starting\n from bottom right coordinate (xmax, ymin).\n If False, box will be created in clockwise direction starting from\n bottom left coordinate (xmin, ymin).\n **kwargs\n For other keyword-only arguments, see the\n `NumPy ufunc docs `_.\n\n Examples\n --------\n >>> box(0, 0, 1, 1)\n \n >>> box(0, 0, 1, 1, ccw=False)\n \n\n \"\"\"\n return lib.box(xmin, ymin, xmax, ymax, ccw, **kwargs)\n\n\n@multithreading_enabled\ndef multipoints(geometries, indices=None, **kwargs):\n \"\"\"Create multipoints from arrays of points\n\n Parameters\n ----------\n geometries : array_like\n An array of points or coordinates (see points).\n indices : array_like or None\n Indices into the target array where input geometries belong. If\n provided, both geometries and indices should be 1D and have matching\n sizes.\n **kwargs\n For other keyword-only arguments, see the\n `NumPy ufunc docs `_.\n Ignored if ``indices`` is provided.\n \"\"\"\n typ = GeometryType.MULTIPOINT\n geometries = np.asarray(geometries)\n if not isinstance(geometries, Geometry) and np.issubdtype(\n geometries.dtype, np.number\n ):\n geometries = points(geometries)\n if indices is None:\n return lib.create_collection(geometries, typ, **kwargs)\n else:\n return collections_1d(geometries, indices, typ)\n\n\n@multithreading_enabled\ndef multilinestrings(geometries, indices=None, **kwargs):\n \"\"\"Create multilinestrings from arrays of linestrings\n\n Parameters\n ----------\n geometries : array_like\n An array of linestrings or coordinates (see linestrings).\n indices : array_like or None\n Indices into the target array where input geometries belong. If\n provided, both geometries and indices should be 1D and have matching\n sizes.\n **kwargs\n For other keyword-only arguments, see the\n `NumPy ufunc docs `_.\n Ignored if ``indices`` is provided.\n \"\"\"\n typ = GeometryType.MULTILINESTRING\n geometries = np.asarray(geometries)\n if not isinstance(geometries, Geometry) and np.issubdtype(\n geometries.dtype, np.number\n ):\n geometries = linestrings(geometries)\n\n if indices is None:\n return lib.create_collection(geometries, typ, **kwargs)\n else:\n return collections_1d(geometries, indices, typ)\n\n\n@multithreading_enabled\ndef multipolygons(geometries, indices=None, **kwargs):\n \"\"\"Create multipolygons from arrays of polygons\n\n Parameters\n ----------\n geometries : array_like\n An array of polygons or coordinates (see polygons).\n indices : array_like or None\n Indices into the target array where input geometries belong. If\n provided, both geometries and indices should be 1D and have matching\n sizes.\n **kwargs\n For other keyword-only arguments, see the\n `NumPy ufunc docs `_.\n Ignored if ``indices`` is provided.\n \"\"\"\n typ = GeometryType.MULTIPOLYGON\n geometries = np.asarray(geometries)\n if not isinstance(geometries, Geometry) and np.issubdtype(\n geometries.dtype, np.number\n ):\n geometries = polygons(geometries)\n if indices is None:\n return lib.create_collection(geometries, typ, **kwargs)\n else:\n return collections_1d(geometries, indices, typ)\n\n\n@multithreading_enabled\ndef geometrycollections(geometries, indices=None, **kwargs):\n \"\"\"Create geometrycollections from arrays of geometries\n\n Parameters\n ----------\n geometries : array_like\n An array of geometries\n indices : array_like or None\n Indices into the target array where input geometries belong. If\n provided, both geometries and indices should be 1D and have matching\n sizes.\n **kwargs\n For other keyword-only arguments, see the\n `NumPy ufunc docs `_.\n Ignored if ``indices`` is provided.\n \"\"\"\n typ = GeometryType.GEOMETRYCOLLECTION\n if indices is None:\n return lib.create_collection(geometries, typ, **kwargs)\n else:\n return collections_1d(geometries, indices, typ)\n\n\ndef prepare(geometry, **kwargs):\n \"\"\"Prepare a geometry, improving performance of other operations.\n\n A prepared geometry is a normal geometry with added information such as an\n index on the line segments. This improves the performance of the following operations:\n contains, contains_properly, covered_by, covers, crosses, disjoint, intersects,\n overlaps, touches, and within.\n\n Note that if a prepared geometry is modified, the newly created Geometry object is\n not prepared. In that case, ``prepare`` should be called again.\n\n This function does not recompute previously prepared geometries;\n it is efficient to call this function on an array that partially contains prepared geometries.\n\n Parameters\n ----------\n geometry : Geometry or array_like\n Geometries are changed inplace\n **kwargs\n For other keyword-only arguments, see the\n `NumPy ufunc docs `_.\n\n See also\n --------\n is_prepared : Identify whether a geometry is prepared already.\n destroy_prepared : Destroy the prepared part of a geometry.\n \"\"\"\n lib.prepare(geometry, **kwargs)\n\n\ndef destroy_prepared(geometry, **kwargs):\n \"\"\"Destroy the prepared part of a geometry, freeing up memory.\n\n Note that the prepared geometry will always be cleaned up if the geometry itself\n is dereferenced. This function needs only be called in very specific circumstances,\n such as freeing up memory without losing the geometries, or benchmarking.\n\n Parameters\n ----------\n geometry : Geometry or array_like\n Geometries are changed inplace\n **kwargs\n For other keyword-only arguments, see the\n `NumPy ufunc docs `_.\n\n See also\n --------\n prepare\n \"\"\"\n lib.destroy_prepared(geometry, **kwargs)\n","sub_path":"pygeos/creation.py","file_name":"creation.py","file_ext":"py","file_size_in_byte":12736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"129076534","text":"import os\n\nimport nox\n\n\nnox.options.sessions = ['mypy', 'test']\nnox.options.reuse_existing_virtualenvs = True\n\n\n@nox.session(python='3.8')\ndef mypy(session):\n session.install('.', 'mypy')\n\n session.run('mypy', 'src/build')\n session.run('mypy', '--py2', 'src/build')\n\n\n@nox.session(python=['2.7', '3.5', '3.6', '3.7', '3.8', 'pypy2', 'pypy3'])\ndef test(session):\n htmlcov_output = os.path.join(session.virtualenv.location, 'htmlcov')\n xmlcov_output = os.path.join(session.virtualenv.location, f'coverage-{session.python}.xml')\n\n session.install('.[test]')\n\n session.run('pytest', '--cov', '--cov-config', 'setup.cfg',\n f'--cov-report=html:{htmlcov_output}',\n f'--cov-report=xml:{xmlcov_output}',\n 'tests/', *session.posargs)\n","sub_path":"noxfile.py","file_name":"noxfile.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"69220109","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n__title__ = ''\n__author__ = 'ZengXu'\n__mtime__ = '2018-7-18'\n\"\"\"\nfrom basic.BasicCommon import *\nfrom basic.BasicSimuCmd import BasicCmd,Switch,Load_zb_ini_file\nfrom basic.BasicProtocol import ZIGBEE\nimport ConfigParser\n\nclass SwitchCmd(BasicCmd):\n def __init__(self, logger, cprint):\n self.air_version = \"20180703\"\n self.mac = str(hex(int(time.time())))[-8:]\n self.device_type = \"Switch\"\n BasicCmd.__init__(self, logger=logger, cprint=cprint, version=self.air_version, d_type=self.device_type)\n\n\n\n\n\n\nif __name__ == '__main__':\n cf = ConfigParser.ConfigParser()\n cf.read('zigbee_devices.conf')\n port = cf.get('Common', 'port')\n cl_level = eval(cf.get('Common', 'cl_level'))\n fl_level = eval(cf.get('Common', 'fl_level'))\n rm_log = eval(cf.get('Common', 'rm_log'))\n logpath = os.path.abspath(sys.argv[0]).replace('py', 'log').replace('exe', 'log')\n if rm_log and os.path.isfile(logpath):\n os.remove(logpath)\n LOG = MyLogger(logpath, clevel=cl_level, flevel=fl_level)\n cprint = cprint(__name__)\n zigbee_obj = ZIGBEE(port, logger=LOG, savefile=True)\n Load_zb_ini_file(zb_obj=zigbee_obj, loadfile=True)\n zigbee_obj.run_forever()\n zigbee_obj.set_device(eval(\"Switch\"))\n cmd = SwitchCmd(logger=LOG, cprint=cprint)\n cmd.cmdloop()","sub_path":"Zb_SwitchSimuCmd.py","file_name":"Zb_SwitchSimuCmd.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"82880450","text":"from django.urls import path\n\nfrom . import views\n\n\nurlpatterns = [\n path(r'write',views.write,name='write'),\n path(r'error',views.errorHandle,name='error'),\n path(r'login',views.login,name='login'),\n path(r'signup',views.signup,name='signup'),\n\n path(r'', views.default, name=''),#dic #视图与url的映射关系,视图是views中的方法\n\n path(r'environment',views.environment,name=\"environment-monitoring\"),\n path(r'location',views.location,name=\"location\"),\n\n path(r'index',views.index,name='index'),#json 返回20条\n path(r'index/latest',views.indexLatest,name='index-latest'),#json 返回1条\n\n path(r'fuel-flow/recent',views.fuelFlowRecent,name='fuel-flow-recent'),#dic 返回50条\n path(r'fuel-flow/recent/json',views.fuelFlowRecentJson,name='fuel-flow-recent-json'),#json 返回50条\n path(r'fuel-flow/recent/json/latest',views.fuelFlowRecentJsonLatest,name='fuel-flow-recent-json-latest'),#json 返回1条\n path(r'fuel-flow/recent/jsonp',views.fuelFlowRecentJsonp,name='fuel-flow-recent-jsonp'),#jsonp\n path(r'fuel-flow/recent/jsonp/latest',views.fuelFlowRecentJsonpLatest,name='fuel-flow-recent-jsonp-latest'),#jsonp\n path(r'fuel-flow/history',views.fuelFlowHistory,name='fuel-flow-history'),#dic\n path(r'fuel-flow/history/json',views.fuelFlowHistoryJson,name='fuel-flow-history-json'),#json\n path(r'fuel-flow/history/json/latest',views.fuelFlowHistoryJsonLatest,name='fuel-flow-history-json-latest'),\n path(r'fuel-flow/history/jsonp',views.fuelFlowHistoryJsonp,name='fuel-flow-history-jsonp'),#jsonp\n path(r'fuel-flow/history/jsonp/latest',views.fuelFlowHistoryJsonpLatest,name='fuel-flow-history-jsonp-latest'),\n\n\n path(r'fuel-temp/recent',views.fuelTempRecent,name='fuel-temp-recent'),#dic 返回50条\n path(r'fuel-temp/recent/json',views.fuelTempRecentJson,name='fuel-temp-recent-json'),#json 返回50条\n path(r'fuel-temp/recent/json/latest',views.fuelTempRecentJsonLatest,name='fuel-temp-recent-json-latest'),#json 返回1条\n path(r'fuel-temp/recent/jsonp',views.fuelTempRecentJsonp,name='fuel-temp-recent-jsonp'),#jsonp\n path(r'fuel-temp/recent/jsonp/latest',views.fuelTempRecentJsonpLatest,name='fuel-temp-recent-jsonp-latest'),#jsonp\n path(r'fuel-temp/history',views.fuelTempHistory,name='fuel-temp-history'),#dic\n path(r'fuel-temp/history/json',views.fuelTempHistoryJson,name='fuel-temp-history-json'),#json\n path(r'fuel-temp/history/json/latest',views.fuelTempHistoryJsonLatest,name='fuel-temp-history-json-latest'),\n path(r'fuel-temp/history/jsonp',views.fuelTempHistoryJsonp,name='fuel-temp-history-jsonp'),#jsonp\n path(r'fuel-temp/history/jsonp/latest',views.fuelTempHistoryJsonpLatest,name='fuel-temp-history-jsonp-latest'),\n\n\n path(r'fuel-density/recent',views.fuelDensityRecent,name='fuel-density-recent'),#dic 返回50条\n path(r'fuel-density/recent/json',views.fuelDensityRecentJson,name='fuel-density-recent-json'),#json 返回50条\n path(r'fuel-density/recent/json/latest',views.fuelDensityRecentJsonLatest,name='fuel-density-recent-json-latest'),#json 返回1条\n path(r'fuel-density/recent/jsonp',views.fuelDensityRecentJsonp,name='fuel-density-recent-jsonp'),#jsonp\n path(r'fuel-density/recent/jsonp/latest',views.fuelDensityRecentJsonpLatest,name='fuel-density-recent-jsonp-latest'),#jsonp\n path(r'fuel-density/history',views.fuelDensityHistory,name='fuel-density-history'),#dic\n path(r'fuel-density/history/json',views.fuelDensityHistoryJson,name='fuel-density-history-json'),#json\n path(r'fuel-density/history/json/latest',views.fuelDensityHistoryJsonLatest,name='fuel-density-history-json-latest'),\n path(r'fuel-density/history/jsonp',views.fuelDensityHistoryJsonp,name='fuel-density-history-jsonp'),#jsonp\n path(r'fuel-density/history/jsonp/latest',views.fuelDensityHistoryJsonpLatest,name='fuel-density-history-jsonp-latest'),\n\n]","sub_path":"ship/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"241961866","text":"from django.contrib.auth import views as auth_views\nfrom django.urls import path\nfrom django.views.generic import TemplateView\n\nfrom . import views\nfrom .forms import (UserLoginForm)\n\napp_name = 'users'\n\nurlpatterns = [\n # homepage\n path('', views.homeview, name='home'),\n # auth user\n path('login/', auth_views.LoginView.as_view(template_name='users/registration/login.html',\n form_class=UserLoginForm), name='login'),\n path('logout/', auth_views.LogoutView.as_view(\n template_name='users/registration/logout.html'), name='logout'),\n\n # registration\n path('register/', views.account_register, name='register'),\n path('activate//)/',\n views.account_activate, name='activate'),\n # user dashboard\n path('dashboard/', views.dashboard, name='dashboard'),\n path('profile/edit/', views.edit_details, name='edit_details'),\n path('profile/delete_user/', views.delete_user, name='delete_user'),\n path('profile/delete_confirm/', TemplateView.as_view(\n template_name=\"users/user/delete_confirm.html\"), name='delete_confirmation'),\n]\n","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"589095309","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2021, Ruturaj Patil and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\nfrom frappe import _\nfrom frappe.model.document import Document\n\nclass Meeting(Document):\n\tdef validate(self):\n\t\t\"\"\"Set missing names and warn if duplicate\"\"\"\n\t\tfound=[]\n\t\tfor attendee in self.attendees:\n\t\t\tif not attendee.full_name:\n\t\t\t\tattendee.full_name=get_full_name(attendee.attendee)\n\t\t\t\n\t\t\tif attendee.attendee in found:\n\t\t\t\tfrappe.throw(_(\"Attendee {0} entered twice\").format(attendee.attendee))\n\t\t\t\n\t\t\tfound.append(attendee.attendee)\n\n\n#white Listed Methods\n@frappe.whitelist()\ndef get_full_name(attendee):\n\tuser=frappe.get_doc(\"User\",attendee)\n\n\t# the below code is concate the firstname, middleName, LastName \n\treturn \" \".join(filter(None,[user.first_name,user.middle_name,user.last_name]))\n\n\n\n# @frappe.whitelist()\n# def get_meetings(start, end):\n# if not frappe.has_permission(\"Meeting\",\"read\"):\n# raise frappe.PermissionErorr\n \n# return frappe.db.sql(\"\"\" select \n# timestamp(`date`,from_time) as start,\n# timestamp(`date`,to_time) as end,\n# name,\n# title,\n# status,\n# 0 as all_day\n# from `tabMeeting`\n# where `date` between %(start)s and %(end)s\"\"\",{\n# \"start\":start,\n# \"end\":end\n# }, as_dict=True)\n","sub_path":"meeting_management/meeting_management/doctype/meeting/meeting.py","file_name":"meeting.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"48192415","text":"import os\nimport numpy as np\nimport pickle\nimport matplotlib\nmatplotlib.use('Agg') # Disable X11\nimport matplotlib.pylab as plt\nfrom astropy.modeling import models, fitting\nimport warnings\nimport fe_temp_observed\nfrom base import read_raw_data, mask_points, extract_fit_part, save_fig\nfrom position import Location\nfrom multiprocessing import Pool, Manager\nfrom functools import partial\n\n# Define a special class for raising any exception related during the fit\n\n\nclass SpectraException(Exception):\n pass\n\n\n# Function to fit quasar with the template\ndef template_fit(wave, flux, error, image_control, init_value, rmid, mjd):\n img_directory = Location.project_loca + \"result/fit_with_temp/fig/\" + \\\n str(rmid)\n # Fit continuum\n if image_control: # Control image output\n fig = plt.figure()\n plt.plot(wave, flux)\n # Part of the spectra without any prominent emission lines\n no_line_part = [[4000.0, 4050.0], [4150.0, 4280.0], [4420, 4750], [5050, 5500]]\n cont_wave = np.array([])\n cont_flux = np.array([])\n cont_error = np.array([])\n for each_part in no_line_part:\n [pwave, pflux, perror] = extract_fit_part(wave, flux, error, each_part[0], each_part[1])\n cont_wave = np.append(cont_wave, pwave)\n cont_flux = np.append(cont_flux, pflux)\n cont_error = np.append(cont_error, perror)\n cont_fitter = fitting.LevMarLSQFitter()\n if init_value == []:\n cont = fe_temp_observed.FeII_template_obs(0.0, 2000.0, 2.6, 0.0, 2000.0, 2.6, bounds = {\"i_r_l1\": [0.0, 50.0], \"i_r_n3\": [0.0, 50.0]}) + \\\n models.PowerLaw1D(flux[0], wave[0], - np.log(abs(flux[-1]/flux[0])+0.001) / np.log(abs(wave[-1]/wave[0]) + 0.001), fixed = {\"x_0\": True})\n else:\n fe2_param = init_value[1][0:6]\n cont = fe_temp_observed.FeII_template_obs(fe2_param[0], fe2_param[1],\n fe2_param[2], fe2_param[3],\n fe2_param[4], fe2_param[5],\n bounds = {\"i_r_l1\": [0.0, 50.0], \"i_r_n3\": [0.0, 50.0]}) + \\\n models.PowerLaw1D(init_value[0][0], init_value[0][1], init_value[0][2], fixed = {\"x_0\": True})\n with warnings.catch_warnings():\n warnings.filterwarnings('error')\n try:\n cont_fit = cont_fitter(cont, cont_wave, cont_flux, weights = cont_error ** (-2), maxiter = 10000)\n except Exception as reason:\n if image_control: # Control image output\n save_fig(fig, img_directory, str(mjd) + \"-cont-failed\")\n plt.close()\n raise SpectraException(\"Continuum fit failed because of \" +\n str(reason))\n if image_control: # Control image output\n para = cont_fit.parameters[6:9]\n cont_cont = models.PowerLaw1D(para[0], para[1], para[2])\n cont_spec = cont_cont(wave)\n fit_spec = cont_fit(wave)\n plt.plot(wave, fit_spec)\n plt.plot(wave, cont_spec)\n plt.plot(wave, fit_spec - cont_spec)\n save_fig(fig, img_directory, str(mjd) + \"-cont-success\")\n plt.close()\n # Fit emission lines\n flux = flux - cont_fit(wave)\n if image_control: # Control image output\n fig1 = plt.figure()\n plt.plot(wave, flux)\n if init_value == []:\n hbeta_complex_fit_func = \\\n models.Gaussian1D(3.6, 4853.30, 7.0, bounds = {\"amplitude\": [0.0, 50.0], \"mean\": [4830, 4880], \"stddev\": [0.0001, 10.1]}) + \\\n models.Gaussian1D(3.6, 4853.30, 40.0, bounds = {\"amplitude\": [0.0, 50.0], \"mean\": [4830, 4880], \"stddev\": [10.1, 500.0]}) + \\\n models.Gaussian1D(2.0, 4346.40, 2.0, bounds = {\"amplitude\": [0.0, 50.0], \"mean\": [4323, 4369], \"stddev\": [0.0001, 50.0]}) + \\\n models.Gaussian1D(2.0, 4101.73, 2.0, bounds = {\"amplitude\": [0.0, 50.0], \"mean\": [4078, 4125], \"stddev\": [0.0001, 50.0]}) + \\\n models.Gaussian1D(5.0, 4960.0, 6.0, bounds = {\"amplitude\": [0.0, 50.0], \"mean\": [4937, 4983], \"stddev\": [0.0001, 23.8]}) + \\\n models.Gaussian1D(20.0, 5008.0, 6.0, bounds = {\"amplitude\": [0.0, 50.0], \"mean\": [4985, 5031], \"stddev\": [0.0001, 23.8]})\n else:\n hbetan_param = init_value[1][6:9]\n hbetab_param = init_value[1][9:12]\n hother_param = init_value[1][12:18]\n o3_param = init_value[1][18:24]\n hbeta_complex_fit_func = \\\n models.Gaussian1D(hbetan_param[0], hbetan_param[1], hbetan_param[2], bounds = {\"amplitude\": [0.0, 50.0], \"mean\": [4830, 4880], \"stddev\": [0.0001, 10.1]}) + \\\n models.Gaussian1D(hbetab_param[0], hbetab_param[1], hbetab_param[2], bounds = {\"amplitude\": [0.0, 50.0], \"mean\": [4830, 4880], \"stddev\": [10.1, 500.0]}) + \\\n models.Gaussian1D(hother_param[0], hother_param[1], hother_param[2], bounds = {\"amplitude\": [0.0, 50.0], \"mean\": [4323, 4369], \"stddev\": [0.0001, 50.0]}) + \\\n models.Gaussian1D(hother_param[3], hother_param[4], hother_param[5], bounds = {\"amplitude\": [0.0, 50.0], \"mean\": [4078, 4125], \"stddev\": [0.0001, 50.0]}) + \\\n models.Gaussian1D(o3_param[0], o3_param[1], o3_param[2], bounds = {\"amplitude\": [0.0, 50.0], \"mean\": [4937, 4983], \"stddev\": [0.0001, 23.8]}) + \\\n models.Gaussian1D(o3_param[3], o3_param[4], o3_param[5], bounds = {\"amplitude\": [0.0, 50.0], \"mean\": [4985, 5031], \"stddev\": [0.0001, 23.8]})\n fitter = fitting.LevMarLSQFitter()\n with warnings.catch_warnings():\n warnings.filterwarnings('error')\n try:\n fit = fitter(hbeta_complex_fit_func, wave, flux, weights = error ** (-2), maxiter = 3000)\n except Exception as reason:\n if image_control: # Control image output\n save_fig(fig1, img_directory, str(mjd) + \"-failed\")\n plt.close()\n raise SpectraException(\"Fit failed because of \" + str(reason))\n expected = np.array(fit(wave))\n if image_control: # Control image output\n plt.plot(wave, expected)\n save_fig(fig1, img_directory, str(mjd) + \"-succeed\")\n plt.close()\n rcs = 0\n for i in range(len(flux)):\n rcs = rcs + (flux[i] - expected[i]) ** 2.0\n rcs = rcs / np.abs(len(flux)-23)\n if rcs > 10.0:\n raise SpectraException(\"Reduced chi-square too large: \" + str(rcs))\n return np.append(cont_fit.parameters[0:6], fit.parameters), cont_fit.parameters[6:9], rcs, cont_fitter.fit_info['nfev'], fitter.fit_info['nfev']\n\n\n# Function to output fit result\ndef output_fit(fit_result, rmid, mjd, band):\n picklefile = open(Location.project_loca + \"result/fit_with_temp/data/\" +\\\n str(rmid) + \"/\" + str(mjd) + \"-\" + band + \".pkl\", \"wb\")\n pickle.dump(fit_result, picklefile)\n picklefile.close()\n\n\n# Exception logging process\ndef exception_logging(rmid, mjd, reason):\n log = open(Location.project_loca + \"Fe2_fit_error.log\", \"a\")\n log.write(str(rmid) + \" \" + str(mjd) + \" \" + str(reason) + \"\\n\")\n log.close()\n\n\n# Reduced chisquare logging\ndef rcs_logging(rmid, rcs):\n log = open(Location.project_loca + \"result/fit_with_temp/data/\" + str(rmid) + \"/rcs.pkl\", \"wb\")\n pickle.dump(rcs, log)\n log.close()\n\n\n# Individual working process\ndef fe_fitter_single(rmid, lock, rcs_dict, mjd):\n # Read data and preprocessing\n try:\n [wave, flux, error] = read_raw_data(rmid, mjd)\n [wave, flux, error] = mask_points(wave, flux, error)\n [wave, flux, error] = extract_fit_part(wave, flux, error, 4000.0, 5500.0)\n except Exception as reason:\n lock.acquire()\n exception_logging(rmid, mjd, reason)\n print(\"Failed for \" + str(mjd))\n lock.release()\n return\n os.chdir(Location.project_loca + \"result/fit_with_temp/data\")\n try:\n os.mkdir(str(rmid))\n except OSError:\n pass\n os.chdir(Location.project_loca + \"result/fit_with_temp/fig\")\n try:\n os.mkdir(str(rmid))\n except OSError:\n pass\n # Begin fitting and handling exception\n try:\n [fit_res, cont_res, rcs, numcont, numfit] = template_fit(wave, flux, error, True, [], rmid, mjd)\n except Exception as reason:\n lock.acquire()\n exception_logging(rmid, mjd, reason)\n print(\"Failed for \" + str(mjd))\n lock.release()\n return\n output_fit(fit_res, rmid, mjd, \"Fe2\")\n output_fit(cont_res, rmid, mjd, \"cont\")\n lock.acquire()\n rcs_dict[mjd] = rcs\n print(\"Finished for \" + str(mjd))\n lock.release()\n\n\ndef fe_fitter(rmid):\n print(\"Beginning process for \" + str(rmid))\n mjd_list = map(int, os.listdir(Location.project_loca + \"data/raw/\" + str(rmid)))\n pool = Pool(processes = 32)\n m = Manager()\n lock = m.Lock()\n rcs_dict = m.dict()\n f = partial(fe_fitter_single, rmid, lock, rcs_dict)\n pool.map(f, mjd_list)\n rcs_logging(rmid, dict(rcs_dict))\n pool.close()\n pool.join()\n","sub_path":"fe_fitter.py","file_name":"fe_fitter.py","file_ext":"py","file_size_in_byte":8928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"595112193","text":"#!/usr/bin/env python\nimport pika\n\ncredentials = pika.PlainCredentials('user', 'user')\nconnection = pika.BlockingConnection(pika.ConnectionParameters('10.20.1.54', 30672, '/', credentials))\nchannel = connection.channel()\n\nchannel.queue_declare(queue='hello')\n\nmess = [True, False, True]\nmess1 = ','.join(str(e) for e in mess)\nprint(mess1)\n\nchannel.basic_publish(exchange='',\n routing_key='hello',\n body=mess1)\n\nprint(\" [x] Sent message\")\nconnection.close()","sub_path":"data-preprocess/test-code/mq_send.py","file_name":"mq_send.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"422382491","text":"\"\"\"Miscellaneous utility functions.\n\"\"\"\nimport re\nimport numpy as np\nimport inspect\nimport itertools\n\n\ndef str_to_rgb(arg):\n \"\"\"Convert an rgb string 'rgb(x,y,z)' to a list of ints [x,y,z].\n \"\"\"\n return list(map(int, re.match(r'rgb\\((\\d+),\\s*(\\d+),\\s*(\\d+)\\)',\n arg).groups()))\n\n\ndef ensure_iterable(arg, color=False):\n \"\"\"Ensure an argument is an iterable. Useful when an input argument\n can either be a single value or a list. If a color is passed then it\n will be treated specially to determine if it is iterable.\n \"\"\"\n if is_iterable(arg, color=color):\n return arg\n else:\n return itertools.repeat(arg)\n\n\ndef has_clims(arg):\n \"\"\"Check if a layer has clims.\n \"\"\"\n if hasattr(arg, '_qt_controls'):\n if hasattr(arg._qt_controls, 'climSlider'):\n return True\n else:\n return False\n else:\n return False\n\n\ndef is_iterable(arg, color=False):\n \"\"\"Determine if a single argument is an iterable. If a color is being\n provided and the argument is a 1-D array of length 3 or 4 then the input\n is taken to not be iterable.\n \"\"\"\n if type(arg) is str:\n return False\n elif np.isscalar(arg):\n return False\n elif color and isinstance(arg, (list, np.ndarray)):\n if np.array(arg).ndim == 1 and (len(arg) == 3 or len(arg)==4):\n return False\n else:\n return True\n else:\n return True\n\n\ndef is_multichannel(meta):\n \"\"\"Determines if an image is RGB after checking its metadata.\n \"\"\"\n try:\n return meta['itype'] in ('rgb', 'rgba', 'multi', 'multichannel')\n except KeyError:\n return False\n\n\ndef guess_multichannel(shape):\n \"\"\"If last dim is 3 or 4 assume image is multichannel.\n \"\"\"\n last_dim = shape[-1]\n\n if last_dim in (3, 4):\n return True\n else:\n return False\n\n\ndef guess_metadata(image, meta, multichannel, kwargs):\n \"\"\"Guesses an image's metadata.\n\n Parameters\n ----------\n image : np.ndarray\n Image data.\n meta : dict or None\n Image metadata.\n multichannel : bool or None\n Whether the image is multichannel. Guesses if None.\n kwargs : dict\n Parameters that will be translated to metadata.\n\n Returns\n -------\n meta : dict\n Guessed image metadata.\n \"\"\"\n if isinstance(meta, dict):\n meta = dict(meta, **kwargs)\n\n if meta is None:\n meta = kwargs\n\n if multichannel is None:\n multichannel = guess_multichannel(image.shape)\n\n if multichannel:\n meta['itype'] = 'multi'\n\n return meta\n\n\ndef compute_max_shape(shapes, max_dims=None):\n \"\"\"Computes the maximum shape combination from the given shapes.\n\n Parameters\n ----------\n shapes : iterable of tuple\n Shapes to coombine.\n max_dims : int, optional\n Pre-computed maximum dimensions of the final shape.\n If None, is computed on the fly.\n\n Returns\n -------\n max_shape : tuple\n Maximum shape combination.\n \"\"\"\n shapes = tuple(shapes)\n\n if max_dims is None:\n max_dims = max(len(shape) for shape in shapes)\n\n max_shape = [0, ] * max_dims\n\n for dim in range(max_dims):\n for shape in shapes:\n try:\n dim_len = shape[dim]\n except IndexError:\n pass\n else:\n if dim_len > max_shape[dim]:\n max_shape[dim] = dim_len\n return tuple(max_shape)\n\n\ndef formatdoc(obj):\n \"\"\"Substitute globals and locals into an object's docstring.\"\"\"\n frame = inspect.currentframe().f_back\n try:\n obj.__doc__ = obj.__doc__.format(**{**frame.f_globals, **frame.f_locals})\n return obj\n finally:\n del frame\n\n\ndef segment_normal(a, b):\n \"\"\"Determines the unit normal of the vector from a to b.\n\n Parameters\n ----------\n a : np.ndarray\n Length 2 array of first point or Nx2 array of points\n b : np.ndarray\n Length 2 array of second point or Nx2 array of points\n\n Returns\n -------\n unit_norm : np.ndarray\n Length the unit normal of the vector from a to b. If a == b,\n then returns [0, 0] or Nx2 array of vectors\n \"\"\"\n d = b-a\n\n if d.ndim == 1:\n normal = np.array([d[1], -d[0]])\n norm = np.linalg.norm(normal)\n if norm == 0:\n norm = 1\n else:\n normal = np.stack([d[:, 1], -d[:, 0]], axis=0).transpose(1, 0)\n norm = np.linalg.norm(normal, axis=1, keepdims=True)\n ind = norm == 0\n norm[ind] = 1\n unit_norm = normal/norm\n\n return unit_norm\n\n\ndef segment_normal_vector(a, b):\n \"\"\"Determines the unit normal of the vector from a to b.\n\n Parameters\n ----------\n a : np.ndarray\n Length 2 array of first point\n b : np.ndarray\n Length 2 array of second point\n\n Returns\n -------\n unit_norm : np.ndarray\n Length the unit normal of the vector from a to b. If a == b,\n then returns [0, 0]\n \"\"\"\n d = b-a\n normal = np.array([d[1], -d[0]])\n norm = np.linalg.norm(normal)\n if norm == 0:\n unit_norm = np.array([0, 0])\n else:\n unit_norm = normal/norm\n return unit_norm\n","sub_path":"napari/util/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":5232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"29482579","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nwl = 8.9197264314e-2 # nm\r\n\r\n\r\ndef tth(alpha_d, wl):\r\n return 2*np.arcsin(wl / (2 * alpha_d))\r\n\r\nclass phases:\r\n\r\n def alpha (alpha_d):\r\n alpha_d = np.array([2.5271, 2.331, 2.2217, 1.7134, 1.459, 1.3237, 1.2635, 1.2367, 1.2195, 1.1655, 1.1108, 1.0584])\r\n alpha_d = np.array([d_hkl*0.1 for d_hkl in alpha_d])\r\n alpha_hkl = ['10.0', '00.2', '10.1', '10.2', '11.0', '10.3', '20.0', '11.2', '20.1', '00.4', '20.2', '10.4']\r\n alpha_tth = np.rad2deg(tth(alpha_d, wl))\r\n alpha_intensity = np.full((len(alpha_tth), 1), 15)\r\n def lines(self):\r\n for i in range(len(alpha_tth)):\r\n plt.plot([alpha_tth[i], alpha_tth[i]], [0, alpha_intensity[i]], color = 'darkgreen', alpha = 0.7)\r\n return\r\n def scatter(self):\r\n plt.scatter(alpha_tth, alpha_intensity, color = 'darkgreen', marker = '.', label = r'$\\alpha\\'/\\alpha-Ti$')\r\n return\r\n return lines(alpha_d), scatter(alpha_d)\r\n\r\n def beta (beta_d):\r\n beta_d = np.array([2.2741, 1.608, 1.3129, 1.1370, 1.0400, 0.9494, 0.8790, 0.8222])\r\n beta_d = np.array([d_hkl * 0.1 for d_hkl in beta_d])\r\n beta_hkl = ['110', '200', '211', '220', '310', '222', '321', '400']\r\n beta_tth = np.rad2deg(tth(beta_d, wl))\r\n beta_intensity = np.full((len(beta_tth), 1), 10)\r\n def lines(self):\r\n for i in range(len(beta_tth)):\r\n plt.plot([beta_tth[i], beta_tth[i]], [0, beta_intensity[i]], color='darkblue', alpha=0.7)\r\n return\r\n def scatter(self):\r\n plt.scatter(beta_tth, beta_intensity, color='darkblue', marker='.', label=r'$\\beta-Ti$')\r\n return\r\n return lines(beta_d), scatter(beta_d)\r\n\r\n'''\r\n\r\n ###omega\r\n omega_d = np.array([2.819, 2.307, 1.779, 1.632, 1.409, 1.339, 1.204, 1.162])\r\n omega_d = np.array([d_hkl*0.1 for d_hkl in omega_d])\r\n omega_hkl = []\r\n omega_tth = np.rad2deg(tth(omega_d, wl))\r\n omega_intensity = np.full((len(omega_tth), 1), 12)\r\n for i in range (len(omega_tth)):\r\n plt.plot([omega_tth[i], omega_tth[i]], [0, omega_intensity[i]], color = 'orangered', alpha = 0.2)\r\n plt.scatter(omega_tth, omega_intensity, color = 'orangered', marker = '.', label = r'$\\omega-Ti$', alpha = 0.2)\r\n \r\n\r\n\r\n ###TiC\r\n tic_d = np.array([2.4929, 2.1589, 1.5266, 1.302, 1.264, 1.0794])\r\n tic_d = np.array([d_hkl*0.1 for d_hkl in tic_d])\r\n tic_tth = np.rad2deg(tth(tic_d, wl))\r\n tic_intensity = np.full((len(tic_tth), 1), 13)\r\n for i in range (len(tic_tth)):\r\n plt.plot([tic_tth[i], tic_tth[i]], [0, tic_intensity[i]], color = 'black', alpha = 0.7)\r\n plt.scatter(tic_tth, tic_intensity, color = 'black', marker = '.', label = r'$TiC$')\r\n'''\r\n\r\ndraw_phase = phases()\r\n\r\n","sub_path":"ESRF_2017/Ti_friction (TiC)/phase_archive.py","file_name":"phase_archive.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"412951541","text":"# coding=utf-8\nfrom selenium import webdriver\nimport cv2\nimport os\nimport pytesseract\nimport sys,time\nfrom PIL import Image,ImageEnhance\n\n\nPostUrl = \"http://yjsymis.hrbeu.edu.cn/gsmis/indexAction.do\"\ndriver = webdriver.Firefox()\n\ni = 0\nwhile 1: #\n i = i+1\n try:\n elem_user = driver.find_element_by_name('id')\n elem_psw = driver.find_element_by_name('password')\n elem_code = driver.find_element_by_name('checkcode')\n except:\n break\n #对验证码进行区域截图\n driver.get_screenshot_as_file('image1.jpg')\n im = Image.open('image1.jpg')\n box = (516,417,564,437) #设置要裁剪的区域\n region = im.crop(box) #此时,region是一个新的图像对象\n region.save(\"e:/image_code.jpg\")\n\n #------------对于不能用pytesser+ocr进行识别,手动打开图片手动输入--------\n # 打开保存的验证码图片 输入\n #SecretCode = raw_input('please enter the code: ')\n #----------------------------------------------------------------------\n\n #图片增强和自动识别简单验证码\n time.sleep(3) #防止由于网速 可能图片还没保存好,就开始识别\n def image_file_to_string(file):\n cwd = os.getcwd()\n try:\n os.chdir(\"C:\\\\Users\\MrLevo\\Anaconda2\\Lib\")\n return pytesseract.image_file_to_string(file)\n finally:\n os.chdir(cwd)\n\n\n im = Image.open(\"E:\\\\image_code.jpg\")\n imgry = im.convert('L') # 图像加强,二值化\n sharpness = ImageEnhance.Contrast(imgry) # 对比度增强\n sharp_img = sharpness.enhance(2.0)\n sharp_img.save(\"E:\\\\image_code.jpg\")\n # http://www.cnblogs.com/txw1958/archive/2012/02/21/2361330.html\n # imgry.show()#这是分布测试时候用的,整个程序使用需要注释掉\n # imgry.save(\"E:\\\\image_code.jpg\")\n\n code = pytesseract.image_file_to_string(\"E:\\\\image_code.jpg\") # code即为识别出的图片数字str类型\n print(code)\n # 打印code观察是否识别正确\n\n # ----------------------------------------------------------------------\n if i <= 2: # 根据自己登录特性,我这里是验证码失败一次,重填所有,失败两次,重填验证码\n elem_user.send_keys('S315080092')\n elem_psw.send_keys('xxxxxxxxxx')\n\n elem_code.send_keys(code)\n click_login = driver.find_element_by_xpath(\"//img[@src='main_images/images/loginbutton.gif']\")\n click_login.click()\n\n# time.sleep(5)#搜索结果页面停留片刻\n# driver.save_screenshot('C:\\Users\\MrLevo\\image.jpg')\n# driver.close()\n# driver.quit()","sub_path":"图像处理/自动识别验证码进行一键登录/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"357326664","text":"from flask import Blueprint, render_template, request, redirect, url_for, flash\nfrom flask_login import login_required, current_user\nfrom .models import Book, History\nfrom . import db\n\nviews = Blueprint('views', __name__)\n\n\n@views.route('/', methods=['GET', 'POST'])\n@login_required\ndef home():\n\n books = Book.query.filter_by(user_id=current_user.id).all()\n return_books = request.form.getlist(\"book\")\n\n if request.method == 'POST':\n for returns in return_books:\n book = Book.query.filter_by(title=returns).first()\n book.user_id = None\n book.checked_out = False\n db.session.commit()\n flash('Books returned!', category='success')\n return redirect(url_for('views.home'))\n\n return render_template(\"home.html\", user=current_user, books=books)\n\n\n@views.route('/add_book', methods=['GET', 'POST'])\n@login_required\ndef add_book():\n\n # handle add book \"POST\" request from front end\n if request.method == 'POST':\n title = request.form.get('title')\n author = request.form.get('author')\n\n book = Book.query.filter_by(title=title).first()\n\n if book:\n flash('A book with this titile already exists.', category='error')\n elif len(title) < 1:\n flash('Please enter a title for the book.', category='error')\n elif len(author) < 1:\n flash('Please enter an author for the book', category='error')\n else:\n checked_out = False\n new_book = Book(title=title,\n author=author,\n checked_out=checked_out)\n db.session.add(new_book)\n db.session.commit()\n flash(f'{title} has been successfully added!')\n return redirect(url_for('views.home'))\n\n return render_template(\"add_book.html\", user=current_user)\n\n\n@views.route('/checkout', methods=['GET', 'POST'])\n@login_required\ndef checkout():\n\n if request.method == 'POST':\n\n history = History.query.filter_by(user_id=current_user.id).first()\n\n if not history:\n history = History(user_id=current_user.id)\n\n # get book titles from form to checkout\n for title in request.form.getlist(\"book\"):\n book = Book.query.filter_by(title=title).first()\n book.checked_out = True\n book.user_id = current_user.id\n if book not in history.books:\n history.books.append(book)\n\n flash('Books have been successfully checked out!', category='success')\n db.session.commit()\n\n return redirect(url_for(\"views.home\"))\n\n books = Book.query.filter_by(checked_out=False).all()\n return render_template(\"checkout.html\", books=books, user=current_user)\n\n\n@views.route('/history')\n@login_required\ndef history():\n history = History.query.filter_by(user=current_user).first()\n books = history.books\n return render_template(\"history.html\", user=current_user, books=books)\n","sub_path":"website/library/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"135354455","text":"from django.shortcuts import render_to_response, render\nfrom django.template import RequestContext\nfrom django.http import HttpResponse, Http404, HttpResponseRedirect\nfrom django.contrib.sessions.models import Session\nfrom django.utils import simplejson\nfrom core.models import *\nimport filter\nimport json\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom forms import *\nimport csv\nimport codecs\nimport datetime\nimport time\nimport mailing\n\ndef striplist(l):\n \"\"\"Take a list of string objects and return the same list\n stripped of extra whitespace.\n\n >>> l = [1, 2, 3]\n\n >>> striplist(l)\n [1, 2, 3]\n \"\"\"\n return([x.strip() for x in l])\n\ndef base_admin_view(request):\n if 'USER_GROUP' and 'USER_ID' in request.session:\n c = RequestContext(request)\n user_id = request.session['USER_ID']\n user_name = request.session['USER_NAME']\n user_group = request.session['USER_GROUP']\n \n \n user = Admin.objects.get(id=user_id)\n \n user_name = user.full_name\n logout_url = \"/base/admin/logout/\"\n title = 'Dashboard @ ' + user_name\n\n #import pdb; pdb.set_trace()\n from django.db.models import Q\n parcel = Parcel.objects.all().order_by('-r_time').exclude(status='S4')\n #parcel = Parcel.objects.filter(~(Q(status='S4')|Q(status='S8'))).order_by('-r_time')\n total_parcel = Parcel.objects.all().count()\n total_parcel_delivered = Parcel.objects.filter(status='S4').count()\n total_parcel_pickedup = Parcel.objects.filter(status='S2').count()\n total_parcel_api = Parcel.objects.filter(sendergroup='API').count()\n \n paginator = Paginator(parcel, 7) # Show 25 contacts per page\n\n page = request.GET.get('page')\n\n parcel_status_code = filter.statusCode()\n parcel_cost = filter.total_parcel_cost()\n \n agents = Agent.objects.all()\n \n try:\n parcels = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n parcels = paginator.page(1)\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n parcels = paginator.page(paginator.num_pages)\n \n return render_to_response(\"special/base_admin_dashboard.html\",locals(), c)\n else:\n return HttpResponseRedirect(\"/base/login/\")\n \ndef parcel_action(request,offset):\n user_id = request.session['USER_ID']\n user_name = request.session['USER_NAME']\n user_group = request.session['USER_GROUP']\n #parcel_id = request.GET['parcel_id']\n \n if offset == 'varify':\n res = {}\n try:\n Parcel.objects.filter(REFID=parcel_id).update(status=\"S9\")\n ps = ParcelStatus(\n REFID = parcel_id,\n status = \"S9\",\n updatergroup = user_group,\n updaterid = user_id,\n loc = 1217,\n comments = 'Parcel has been verified.',\n view = 1\n )\n ps.save()\n res['code'] = 'done'\n res['msg'] = 'Parcel has been verified.'\n except:\n res['code'] = 'error'\n res['msg'] = 'An error occurred while verifying the parcel.'\n return HttpResponse(simplejson.dumps(res), mimetype='application/json') \n \n if offset == 'deliver':\n res = {}\n try:\n parcel = Parcel.objects.get(REFID=parcel_id)\n if(parcel.status == 'S9'):\n Parcel.objects.filter(REFID=parcel_id).update(status=\"S4\")\n ps = ParcelStatus(\n REFID = parcel_id,\n status = \"S4\",\n updatergroup = user_group,\n updaterid = user_id,\n loc = 1217,\n comments = 'Parcel has been delivered.',\n view = 1\n )\n ps.save()\n res['code'] = 'done'\n res['msg'] = 'Parcel has been delivered.'\n else:\n res['code'] = 'error'\n res['msg'] = 'You must verify the parcel first.'\n except:\n res['code'] = 'error'\n res['msg'] = 'An error occurred while processing your action.'\n return HttpResponse(simplejson.dumps(res), mimetype='application/json') \n \n if offset == 'clear':\n res = {}\n try:\n Parcel.objects.filter(REFID=parcel_id).update(status=\"S12\")\n ps = ParcelStatus(\n REFID = parcel_id,\n status = \"S12\",\n updatergroup = user_group,\n updaterid = user_id,\n loc = 1217,\n comments = 'Parcel has been cleared.',\n view = 1\n )\n ps.save()\n res['code'] = 'done'\n res['msg'] = 'All issue of this parcel been cleared.'\n except:\n res['code'] = 'error'\n res['msg'] = 'An error occurred while processing your action.'\n return HttpResponse(simplejson.dumps(res), mimetype='application/json') \n \n if offset == 'opt':\n action = request.POST['parcel_action']\n parcel_id = request.POST['parcel_id']\n res = {}\n # action order\n # S10 -> S9 -> S1 -> S2 -> S13 -> S14 -> S15 -> S4\n stop = True\n action_order = {\n 'S10' : 1,\n 'S9' : 2,\n 'S1' : 3,\n 'S2' : 4,\n 'S13' : 5,\n 'S14' : 6,\n 'S15' : 7,\n 'S4' : 8\n }\n \n current_status = Parcel.objects.get(REFID=parcel_id).status \n try:\n dif = action_order[action] - action_order[current_status] if action and current_status in action_order else 1\n except:\n dif = 1\n \n if not action in action_order and action=='S':\n res['code'] = 'error'\n res['msg'] = 'You must select a status.'\n elif action in action_order and dif != 1:\n res['code'] = 'error'\n res['msg'] = 'You must follow the status order.'\n else:\n try:\n Parcel.objects.filter(REFID=parcel_id).update(status=action)\n ps = ParcelStatus(\n REFID = parcel_id,\n status = action,\n updatergroup = user_group,\n updaterid = user_id,\n loc = 1217,\n comments = 'Parcel status has been changed.',\n view = 1\n )\n ps.save()\n \n ed = EcommerceParcelDescription.objects.get(REFID=parcel_id)\n ed.monitoring_agent = user_id\n ed.save()\n \n if action == 'S4':\n try:\n p = Parcel.objects.get(REFID=parcel_id)\n group = p.sendergroup\n if group == 'ESO':\n e = Ecommerce.objects.get(id=p.senderid)\n if e.is_sms_on == True:\n sender_mobile = e.mobile\n filter.send_sms(sender_mobile, 'eCourier','Dear Merchant,your parcel ('+ parcel_id +') has been delivered to recipient.Thank you ! ecourier.com.bd.')\n except:\n return None\n \n res['code'] = 'done'\n res['msg'] = 'Parcel status has been changed.'\n except:\n res['code'] = 'error'\n res['msg'] = 'An error occurred while processing your action.'\n return HttpResponse(simplejson.dumps(res), mimetype='application/json') \n \n if offset == 'agent_assign':\n pid = request.POST['parcel_id']\n aid = request.POST['agent_id']\n if aid == '':\n return HttpResponse('Please select an agent !')\n \n try:\n ed = Parcel.objects.get(REFID=pid)\n ed.courier = 1\n ed.agent = int(aid)\n ed.save()\n return HttpResponse('Done! you have assigned an agent for this parcel.')\n except:\n return HttpResponse('Someting going wrong! please contact to the administrator.') \n\n \ndef parcel_search(request):\n c = RequestContext(request)\n parcel_id = request.POST['refid']\n filter = Parcel.objects.filter(REFID=parcel_id)\n if filter:\n parcel = Parcel.objects.get(id=filter)\n return render_to_response('special/base_admin_search_result.html',locals(),c)\n else:\n return HttpResponse('error')\n \ndef parcel_ordered(request):\n c = RequestContext(request)\n parcel = Parcel.objects.filter(status='S10').order_by('-r_time')\n return render_to_response('special/admin_parcel_ordered.html',locals(), c)\n \ndef parcel_picked(request):\n c = RequestContext(request)\n parcel = Parcel.objects.filter(status='S2').order_by('-r_time')\n return render_to_response('special/admin_parcel_picked.html',locals(), c)\n\ndef parcel_delivered(request):\n c = RequestContext(request)\n parcel = Parcel.objects.filter(status='S4').order_by('-r_time')\n return render_to_response('special/admin_parcel_delivered.html',locals(), c)\n\ndef reports_view(request):\n c = RequestContext(request)\n p = Parcel.objects.all().order_by('-r_time')\n ec = Ecommerce.objects.all()\n request.session['REPORT_DATA'] = p\n return render_to_response('special/admin_reports_view.html',locals(),c)\n\ndef reports_submit(request): \n c = RequestContext(request) \n from core.templatetags.core_filters import product_price\n start_date = request.POST['start_date']\n stop_date = request.POST['stop_date']\n parcel_status = request.POST['status']\n ecommerce = request.POST['ecommerce']\n shipping_cost = []\n product_cost = []\n \n if start_date=='Date From' or stop_date=='Date To':\n return HttpResponse('

    Please select from date and to date

    ')\n if parcel_status == 'SA':\n pf = Parcel.objects.filter(r_time__range=[start_date, stop_date + ' 23:59:59']).order_by('-r_time')\n else:\n pf = Parcel.objects.filter(r_time__range=[start_date, stop_date]).filter(status=parcel_status).order_by('-r_time')\n if ecommerce != '':\n pf = Parcel.objects.filter(r_time__range=[start_date, stop_date + ' 23:59:59'],sendergroup='ESO',senderid=ecommerce).order_by('-r_time')\n if pf:\n #for i in ld:\n #return HttpResponse(i)\n request.session['REPORT_DATA'] = pf\n for i in pf:\n shipping_cost.append(int(0 if i.r_price is None else i.r_price))\n product_cost.append(int(0 if product_price(i.REFID) is None else product_price(i.REFID)))\n \n total_shipping_cost = sum(shipping_cost)\n total_product_cost = sum(product_cost)\n request.session['REPORT_SHIPPING_COST'] = total_shipping_cost\n request.session['REPORT_PRODUCT_COST'] = total_product_cost\n return render_to_response(\"special/ecommerce_filter_view.html\",locals(),c)\n else:\n return HttpResponse('Nothing found')\n \n\ndef logout(request):\n try:\n del request.session['USER_GROUP']\n del request.session['USER_ID']\n except KeyError:\n pass\n return HttpResponseRedirect(\"/\")\n\ndef parcel_csv_import2(request):\n\n form = FileImport()\n csv_data = ''\n msg = ''\n error_msg = ''\n success_import_list = []\n type_error_import_list = []\n contact_cnt = 0\n bulk_record = []\n if request.method == 'POST':\n form = FileImport(request.POST)\n if form.is_valid():\n # col_no - field name\n # 0 - contact\n # 1 - last_name\n # 2 - first_name\n # 3 - email\n # 4 - description\n # 5 - status\n # 6 - address\n # 7 - city\n # 8 - country\n # 9 - country\n # 10 - unit_number\n # 11 - additional_vars\n # To count total rows of CSV file\n records = csv.reader(request.FILES['csv_file'],\n delimiter='|', quotechar='\"')\n total_rows = len(list(records))\n BULK_SIZE = 1000\n csv_data = csv.reader(request.FILES['csv_file'],\n delimiter='|', quotechar='\"')\n #Get Phonebook Obj\n\n #Read each Row\n \n for row in csv_data:\n row = striplist(row)\n if not row or str(row[0]) == 0:\n continue\n\n #Check field type\n if not int(row[5]):\n error_msg = _(\"invalid value for import! please check the import samples or phonebook is not valid\")\n type_error_import_list.append(row)\n break\n\n if len(row[9]) > 2:\n error_msg = _(\"invalid value for country code, it needs to be a valid ISO 3166-1 alpha-2 codes (http://en.wikipedia.org/wiki/ISO_3166-1)\")\n type_error_import_list.append(row)\n break\n\n row_11 = ''\n if row[11]:\n try:\n row_11 = json.loads(row[11])\n except:\n row_11 = ''\n\n bulk_record.append(\n Contact(\n phonebook=phonebook,\n contact=row[0],\n last_name=row[1],\n first_name=row[2],\n email=row[3],\n description=row[4],\n status=int(row[5]),\n address=row[6],\n city=row[7],\n state=row[8],\n country=row[9], # Note: country needs to be a country code (CA, ES)\n unit_number=row[10],\n additional_vars=row_11)\n )\n\n contact_cnt = contact_cnt + 1\n\n if contact_cnt < 100:\n #We want to display only 100 lines of the success import\n success_import_list.append(row)\n\n if contact_cnt % BULK_SIZE == 0:\n #Bulk insert\n Contact.objects.bulk_create(bulk_record)\n bulk_record = []\n\n # remaining record\n Contact.objects.bulk_create(bulk_record)\n bulk_record = []\n\n #check if there is contact imported\n if contact_cnt > 0:\n msg = _('%(contact_cnt)s contact(s) are uploaded successfully out of %(total_rows)s row(s) !!') \\\n % {'contact_cnt': contact_cnt,\n 'total_rows': total_rows}\n\n data = RequestContext(request, {\n 'form': form,\n 'csv_data': csv_data,\n 'msg': msg,\n 'error_msg': error_msg,\n 'success_import_list': success_import_list,\n 'type_error_import_list': type_error_import_list,\n })\n template = 'special/csv_import.html'\n return render_to_response(template, data,\n context_instance=RequestContext(request))\n \n \ndef parcel_csv_import(request):\n \n if request.POST and request.FILES:\n if request.POST['ec'] == \"\":\n return HttpResponse('Please select E-commerce.')\n if request.FILES['csv_file'].name[-3:] != 'csv':\n return HttpResponse('Only comma seperated csv(not CSV) file allowed')\n #return HttpResponse(request.FILES['csv_file'])\n csvfile = request.FILES['csv_file']\n #Edialect = csv.Sniffer().sniff(codecs.EncodedFile(csvfile, \"utf-8\").read(1024))\n #csvfile.open()\n #reader = csv.reader(codecs.EncodedFile(csvfile, \"utf-8\"), delimiter=',', dialect=dialect)\n reader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n \n now = datetime.datetime.now()\n #ostime = now.isoformat()\n ostime = now.strftime(\"%Y-%m-%d %H:%M:%S\")\n # 0 = recipient name\n # 1 = recipient mobile\n # 2 = recipient address\n # 3 = parcel type\n # 4 = recipient post code\n # 5 = coverage area inside dhaka|outside dhaka\n # 6 = timing sameday|nextday\n # 7 = weight\n # 8 = product price\n \n user_id = request.session['USER_ID']\n user_name = request.session['USER_NAME']\n user_group = request.session['USER_GROUP']\n \n \n user = Admin.objects.get(id=user_id)\n \n for j,i in enumerate(reader):\n i = striplist(i)\n if not i or str(i[0]) == 0:\n continue\n if len(i) < 9:\n return HttpResponse('Check required field in row ' + str(j+1) + ' . total 9 fields expected!') \n \n if filter.mobile(i[1]) == False:\n return HttpResponse('Invalid mobile number in row ' + str(j+1))\n \n p_price = filter.ecommercePriceCalculate(request.POST['ec'],int(i[6]),int(i[5]),int(i[7]),fixed=False)\n \n if p_price == False:\n #return HttpResponse(p_price)\n return HttpResponse(\"This user don't have any pricing package with this shipping information. Please check row. \" + str(j+1))\n \n else:\n parcel_id = filter.generate_parcel_id()\n e = Ecommerce.objects.get(id=request.POST['ec'])\n p = Parcel(\n REFID=parcel_id,\n sendergroup='ESO',\n #senderid=User.objects.get(id=USERID),\n senderid=request.POST['ec'],\n r_name=i[0],\n r_mobile=i[1],\n #r_email = email,\n r_address = i[2],\n r_type= i[3],\n r_time = ostime,\n r_loc_from = e.loc,\n r_loc_to = i[4],\n status = \"S10\" # make a dictionary of status code and put only code into database\n )\n p.save()\n \n n = Notification(\n n_from = request.POST['ec'],\n usergroup = 'ESO',\n n_to = i[4],\n n_message = 'Parcel ' + parcel_id + ' order submitted',\n n_time = ostime,\n N_REFID = parcel_id,\n parcel = Parcel.objects.get(REFID=parcel_id)\n )\n n.save()\n \n s = ParcelStatus(\n REFID=parcel_id,\n time=ostime,\n status='S10',\n updatergroup='ESO',\n updaterid=user_id,\n loc=i[4],\n comments='An order has been made by e-commerce',\n view=1\n )\n s.save() \n \n \n desc = EcommerceParcelDescription(\n REFID=parcel_id, \n coverage=1 if i[5] == 'idk' else 2,\n timing=int(i[6]),\n weight=int(i[7]),\n parcel_price=p_price,\n product_price=i[8],\n cash_on_delivery=True \n )\n desc.save()\n \n \n return HttpResponse('Upload completed! Total' + str(len(reader)) + ' records uploaded.' )\n \n ec = Ecommerce.objects.all()\n return render(request, \"special/csv_import.html\", locals())\n\ndef ecommerce_confirm(request):\n id = request.GET['ref']\n ec = Ecommerce.objects.get(id=id)\n if ec.is_active is False:\n ec.is_active = True\n ec.save()\n mailing.html_email('eCourier: your account has been approved!',\n ec.email,{'title':'','m_id': ec.MARCHENTID},\n 'ecommerce_confirm_email.html')\n res = 'Merchant has been approved'\n else:\n #mailing.html_email('eCourier: your account has been approved!',\n # ec.email,{'title':'','m_id': ec.MARCHENTID},\n # 'ecommerce_confirm_email.html')\n #ec.is_active = False\n #ec.save()\n res = 'This user already enabled'\n return HttpResponse(res)\n\ndef base_new_parcel(request):\n c = RequestContext(request)\n return render_to_response('special/base_new_parcel.html',locals(), c)\n \n \n \n\n","sub_path":"ecourier/baseAdmin.py","file_name":"baseAdmin.py","file_ext":"py","file_size_in_byte":21100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"297979595","text":"# https://atcoder.jp/contests/abc135/tasks/abc135_e\nimport sys\nsys.setrecursionlimit(2147483647)\nINF=float(\"inf\")\nMOD=10**9+7\ninput=lambda :sys.stdin.readline().rstrip()\ndef resolve():\n from math import ceil\n K=int(input())\n X,Y=map(int,input().split())\n # defaultは 0 <= Y <= X\n def trans(u,v):\n if(abs(X)K\n c=(-x-y)%K\n n=ceil((x+y)/K)+(c&1)\n l=(K*n-x-y)//2\n print(n)\n nx,ny=K-l,-l\n print(*trans(nx,ny))\n while(nx+K<=x):\n nx+=K\n print(*trans(nx,ny))\n nx,ny=x,ny+(K-(x-nx))\n print(*trans(nx,ny))\n while(ny+K<=y):\n ny+=K\n print(*trans(nx,ny))\nresolve()\n","sub_path":"ABC135/e_golf.py","file_name":"e_golf.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"261074620","text":"from tabulate import tabulate\n\n\nclass UI:\n \"\"\"\n Class controlling input/output.\n \"\"\"\n @staticmethod\n def menu():\n \"\"\"\n Prints menu, returns user input.\n :return:\n input: str\n \"\"\"\n print(\"What would you like to do: \\n\"\n \" (1) List statistics \\n\"\n \" (2) Display 3 cities with longest names \\n\"\n \" (3) Display county's name with the largest number of communities \\n\"\n \" (4) Display locations, that belong to more than one category \\n\"\n \" (5) Advanced search \\n\"\n \" (0) Exit program \\n\")\n\n return input(\"Option: \")\n\n @staticmethod\n def show_table(headers, data):\n \"\"\"\n Prints formatted table.\n \"\"\"\n table = tabulate(data, headers, tablefmt='fancy_grid')\n print(table)\n\n @staticmethod\n def get_data():\n \"\"\"\n Returns user input.\n :return:\n input: str\n \"\"\"\n return input(\"Searching for: \")\n\n @staticmethod\n def wrong_input():\n \"\"\"\n Prints wrong input message.\n \"\"\"\n print(\"Wrong input! \\n\")","sub_path":"ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"599592034","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: jl\n\"\"\"\nimport numpy as np\nimport copy\nimport cv2\nfrom matplotlib import pyplot as plt\n\n\n# --- diffusion with cyclical boundary conditions---\ndef Diffusion_c(im, D, dx):\n\n \"\"\"\n The application of diffusion using nested loops and cyclical boundary conditions\n :param im: Image in array form\n :param D: Diffusion parameter\n :return: the array after a step of diffusion\n \"\"\"\n\n\n im_var = im.copy()\n for i in range(len(im)):\n for j in range(len(im.T)):\n\n if i == 0:\n u1 = im[len(im) - 1, j]\n else:\n u1 = im[i - 1, j]\n\n if i == len(im) - 1:\n u2 = im[0, j]\n else:\n u2 = im[i + 1, j]\n\n if j == 0:\n u3 = im[i, len(im.T) - 1]\n else:\n u3 = im[i, j - 1]\n\n if j == len(im.T) - 1:\n u4 = im[i, 0]\n else:\n u4 = im[i, j + 1]\n\n u1 = int(u1)\n u2 = int(u2)\n u3 = int(u3)\n u4 = int(u4)\n\n u = (D/(dx**2))*(u1 + u2 + u3 + u4 - 4 * int(im[i, j]))\n im_var[i, j] = u\n\n im = im + im_var\n return im\n\n\n# ----diffusion using static boundary condition----\ndef Difussion(im, D, dx):\n \"\"\"\n The application of diffusion using nested loops and fixed boundary conditions\n :param im: Image in array form\n :param D: Diffusion parameter\n :return: the array after a step of diffusion\n \"\"\"\n im_var = im.copy()\n for i in range(1, len(im) - 1):\n for j in range(1, len(im.T) - 1):\n\n u1 = im[i - 1, j]\n u2 = im[i + 1, j]\n u3 = im[i, j - 1]\n u4 = im[i, j + 1]\n\n u1 = int(u1)\n u2 = int(u2)\n u3 = int(u3)\n u4 = int(u4)\n\n u = (D / (dx ** 2)) * (u1 + u2 + u3 + u4 - 4 * int(im[i, j]))\n im_var[i, j] = u\n\n im = im + im_var\n return im\n\n\n# ---diffusion using matrix method---\ndef Difussion_f(im, D, dx):\n \"\"\"\n The application of diffusion using Matrix operations and fixed boundary conditions\n :param im: Image in array form\n :param D: Diffusion parameter\n :return: the array after a step of diffusion\n \"\"\"\n im_var1 = im.copy()\n im_var2 = im.copy()\n\n a1 = np.multiply((D/dx**2), generate_matrix(len(im.T)))\n a2 = np.multiply((D/dx**2), generate_matrix(len(im)))\n\n for j in range(len(im)):\n u1 = a1.dot(im[j, :])\n im_var1[j, :] = u1\n for i in range(len(im[0])):\n u2 = a2.dot(im[:, i])\n im_var2[:, i] = u2\n\n im = im + im_var1 + im_var2\n\n return im\n\n# function to generate a matrix for the diffusion in 1D\ndef generate_matrix(n):\n a = np.multiply(-2/1, np.identity(n))\n ide = np.multiply(1/1, np.identity(n-1)).tolist()\n\n for i in ide:\n i.append(0)\n\n ide.insert(0, np.zeros(n).tolist())\n ide = np.asarray(ide)\n m = a + ide + ide.T\n\n return m\n\ndef get_neighborhood(nd_idx, radius, image):\n u1 = image[nd_idx[0] + 1, nd_idx[1]]\n u2 = image[nd_idx[0] - 1, nd_idx[1]]\n u3 = image[nd_idx[0], nd_idx[1] + 1]\n u4 = image[nd_idx[0], nd_idx[1] - 1]\n\n return u1, u2, u3, u4\n\n\n\ndef impaint_Diff(image, mask):\n\n \"\"\"\n Impainting using difussion\n :param image: image to imapaint\n :param mask: mask of which points are needed to be restored.\n :return: the image after a step of impainting using diffusion\n \"\"\"\n im_new = np.zeros(np.shape(image))\n mask = mask.astype(np.bool)\n D = 1\n dx = 1\n p = 0.001\n mask_pts = np.array(np.where(mask)).T\n for mask_pt_n, mask_pt_idx in enumerate(mask_pts):\n\n u1, u2, u3, u4 = get_neighborhood(mask_pt_idx, 1, image)\n u = (D/dx**2)*np.average([u1, u2, u3, u4]) - 4 * p * int(image[mask_pt_idx[0], mask_pt_idx[1]])\n image[mask_pt_idx[0], mask_pt_idx[1]] = int(u)\n\n #image = image+im_new\n\n return image\n","sub_path":"scripts/restr_methods/Diffusion.py","file_name":"Diffusion.py","file_ext":"py","file_size_in_byte":3977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"459997769","text":"from django.urls import path,include\nfrom . import views\n\nurlpatterns = [ \n path('', views.index, name='index'),\n path('login', views.login, name='login'),\n path('dash', views.dash, name='dash'),\n path('marcar//', views.marcar, name='marcar'),\n path('historico//', views.historico, name='historico'),\n path('minha_conta', views.minha_conta, name='minha_conta'),\n path('cadastrar', views.cadastrar, name='cadastrar'),\n path('cadUser', views.cadUser, name='cadUser'),\n path('salvar_consulta', views.salvar_consulta, name='salvar_consulta'),\n path('cadEnd', views.cadEnd, name='cadEnd'),\n path('logout_view', views.logout_view, name='logout_view'),\n path('list_consulta//', views.list_consulta, name='list_consulta'),\n path('confimar_consulta', views.confimar_consulta, name='confimar_consulta'),\n path('cancelar_consulta//', views.cancelar_consulta, name='cancelar_consulta'),\n path('alterar_consulta//', views.alterar_consulta, name='alterar_consulta'),\n path('confirmar_alteracoes', views.confirmar_alteracoes, name='confirmar_alteracoes'),\n path('alterar_meus_dados//', views.alterar_meus_dados, name='alterar_meus_dados'),\n path('salvar_meus_dados', views.salvar_meus_dados, name='salvar_meus_dados'),\n path('excluir_historico//', views.excluir_historico, name='excluir_historico'),\n \n \n]\n","sub_path":"projetoPW/pwII/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"604400927","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nliczba_a=int(input (\"Podaj a: \"))\nxr=np.arange(-10,10,0.5)\nx=[i for i in xr if i<=0]\nx1=[i for i in xr if i>=0]\ny=[(i/(-3))+liczba_a for i in xr if i<=0]\ny1=[(i*i)/3 for i in xr if i>=0]\nplt.xlabel('Nazwa osi X')\nplt.ylabel('Nazwa osi Y')\nplt.title('Tytuł Wykresu ')\nplt.plot(x,y)\nplt.plot(x1,y1)\nplt.show()\n","sub_path":"zadanie3_10.py","file_name":"zadanie3_10.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"445165556","text":"# Copyright (c) 2017-present, Facebook, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n##############################################################################\n#\n# Based on:\n# --------------------------------------------------------\n# Fast R-CNN\n# Copyright (c) 2015 Microsoft\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Ross Girshick\n# --------------------------------------------------------\n\n\"\"\"Utilities driving the train_net binary\"\"\"\n\n\n\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom shutil import copyfile\nimport cv2 # NOQA (Must import before importing caffe2 due to bug in cv2)\nimport logging\nimport numpy as np\nimport os\nimport re\n\n\n\nfrom caffe2.python import memonger\nfrom caffe2.python import workspace\n\nfrom detectron.core.config import cfg\nfrom detectron.core.config import get_output_dir\nfrom detectron.datasets.roidb import combined_roidb_for_training\nfrom detectron.modeling import model_builder\nfrom detectron.utils import lr_policy\nfrom detectron.utils.training_stats import TrainingStats\nimport detectron.utils.env as envu\nimport detectron.utils.net as nu\nif 1:\n from detectron.datasets import json_dataset\n from detectron.datasets import roidb as roidb_utils\n import detectron.modeling.FPN as fpn\n import detectron.roi_data.fast_rcnn as fast_rcnn_roi_data\n import detectron.utils.blob as blob_utils\nTrain_1 = 0\nif 1:\n def collect(inputs, is_training):\n cfg_key = 'TRAIN' if is_training else 'TEST'\n post_nms_topN = cfg[cfg_key].RPN_POST_NMS_TOP_N\n k_max = cfg.FPN.RPN_MAX_LEVEL\n k_min = cfg.FPN.RPN_MIN_LEVEL\n num_lvls = k_max - k_min + 1\n roi_inputs = inputs[:num_lvls]\n score_inputs = inputs[num_lvls:]\n if is_training:\n score_inputs = score_inputs[:-2]\n\n # rois are in [[batch_idx, x0, y0, x1, y2], ...] format\n # Combine predictions across all levels and retain the top scoring\n rois = np.concatenate([blob for blob in roi_inputs])\n scores = np.concatenate([blob for blob in score_inputs]).squeeze()\n inds = np.argsort(-scores)[:post_nms_topN]\n rois = rois[inds, :]\n return rois\n\n\n def distribute(rois, label_blobs, outputs, train):\n \"\"\"To understand the output blob order see return value of\n detectron.roi_data.fast_rcnn.get_fast_rcnn_blob_names(is_training=False)\n \"\"\"\n lvl_min = cfg.FPN.ROI_MIN_LEVEL\n lvl_max = cfg.FPN.ROI_MAX_LEVEL\n lvls = fpn.map_rois_to_fpn_levels(rois[:, 1:5], lvl_min, lvl_max)\n\n outputs[0].reshape(rois.shape)\n outputs[0].data[...] = rois\n\n # Create new roi blobs for each FPN level\n # (See: modeling.FPN.add_multilevel_roi_blobs which is similar but annoying\n # to generalize to support this particular case.)\n rois_idx_order = np.empty((0,))\n for output_idx, lvl in enumerate(range(lvl_min, lvl_max + 1)):\n idx_lvl = np.where(lvls == lvl)[0]\n blob_roi_level = rois[idx_lvl, :]\n outputs[output_idx + 1].reshape(blob_roi_level.shape)\n outputs[output_idx + 1].data[...] = blob_roi_level\n rois_idx_order = np.concatenate((rois_idx_order, idx_lvl))\n rois_idx_restore = np.argsort(rois_idx_order)\n blob_utils.py_op_copy_blob(rois_idx_restore.astype(np.int32), outputs[-1])\ndef train_model(viz, win_accuracy_cls, win_loss, win_loss_bbox, win_loss_cls):\n \"\"\"Model training loop.\"\"\"\n logger = logging.getLogger(__name__)\n model, weights_file, start_iter, checkpoints, output_dir = create_model() #for create model\n if 'final' in checkpoints:\n # The final model was found in the output directory, so nothing to do\n return checkpoints\n if 0:\n output_dir = '/home/icubic/daily_work/code/Detectron/train/coco_2014_train_ET_PH_part/generalized_rcnn_multi/'\n #output_dir = output_dir + '_101'\n setup_model_for_training(model, weights_file, output_dir)\n training_stats = TrainingStats(model)\n uuuu = model.roi_data_loader._blobs_queue_name\n CHECKPOINT_PERIOD = int(cfg.TRAIN.SNAPSHOT_ITERS / cfg.NUM_GPUS)\n print('------------train.py')\n for cur_iter in range(start_iter, cfg.SOLVER.MAX_ITER):\n training_stats.IterTic()\n lr = model.UpdateWorkspaceLr(cur_iter, lr_policy.get_lr_at_iter(cur_iter))\n #aaa_debug = workspace.FetchBlob('gpu_0/data')\n #bbb_debug = workspace.FetchBlob('gpu_0/conv1_w')\n #ccc_debug = workspace.FetchBlob('gpu_0/'+uuuu)\n try:\n workspace.RunNet(model.net.Proto().name)\n\n if 0:\n #import detectron.utils.blob as blob_utils\n inputs = [workspace.FetchBlob(\"gpu_0/rpn_rois_fpn2\"),workspace.FetchBlob(\"gpu_0/rpn_rois_fpn3\"),workspace.FetchBlob(\"gpu_0/rpn_rois_fpn4\"),workspace.FetchBlob(\"gpu_0/rpn_rois_fpn5\"), \\\n workspace.FetchBlob(\"gpu_0/rpn_rois_fpn6\"),workspace.FetchBlob(\"gpu_0/rpn_roi_probs_fpn2\"),workspace.FetchBlob(\"gpu_0/rpn_roi_probs_fpn3\"),workspace.FetchBlob(\"gpu_0/rpn_roi_probs_fpn4\"), \\\n workspace.FetchBlob(\"gpu_0/rpn_roi_probs_fpn5\"),workspace.FetchBlob(\"gpu_0/rpn_roi_probs_fpn6\"),workspace.FetchBlob(\"gpu_0/roidb\"),workspace.FetchBlob(\"gpu_0/im_info\"),\\\n ]\n rois = collect(inputs, True)\n #inputs.append(workspace.FetchBlob(\"gpu_0/rpn_rois_fpn2\"))\n im_info = inputs[-1]\n im_scales = im_info[:, 2]\n roidb = blob_utils.deserialize(inputs[-2])\n # For historical consistency with the original Faster R-CNN\n # implementation we are *not* filtering crowd proposals.\n # This choice should be investigated in the future (it likely does\n # not matter).\n json_dataset.add_proposals(roidb, rois, im_scales, crowd_thresh=0)\n roidb_utils.add_bbox_regression_targets(roidb)\n # Compute training labels for the RPN proposals; also handles\n # distributing the proposals over FPN levels\n output_blob_names = fast_rcnn_roi_data.get_fast_rcnn_blob_names()\n blobs = {k: [] for k in output_blob_names}\n fast_rcnn_roi_data.add_fast_rcnn_blobs(blobs, im_scales, roidb)\n for i, k in enumerate(output_blob_names):\n blob_utils.py_op_copy_blob(blobs[k], outputs[i])\n #if (np.sum(bb == 1))>0:\n # print('cc')\n except:\n aa = workspace.FetchBlob(\"gpu_0/rpn_rois_fpn2\")\n aaa_debug = workspace.FetchBlob('gpu_0/data')\n print('aaaaaerror')\n #print(\"blobs:\\n{}\".format(workspace.Blobs()))\n #print('train.py aaaaaaaa_debug')\n if 1:\n\n\n aaa = workspace.FetchBlob(\"gpu_0/data\") # nchw\n #img = aaa[1].copy()\n # BGR HWC -> CHW 12\n #transform_img = img.swapaxes(0, 1).swapaxes(1, 2)\n\n\n #cv2.imshow(\"image0 \", transform_img[:, :, (2, 1, 0)])\n\n #cv2.waitKey(0)\n #cv2.destroyAllWindows()\n #cv2.imshow('/home/icubic/daily_work/code/Detectron/aaa.png', aaa[0])\n aaa_debug = workspace.FetchBlob('gpu_0/data')\n bbb_debug = workspace.FetchBlob('gpu_0/conv1_w')\n ccc_debug = workspace.FetchBlob('gpu_0/' + uuuu)\n ddd_debug = workspace.FetchBlob('gpu_0/roidb')\n eee_debug = workspace.FetchBlob('gpu_0/im_info')\n #print(\"Fetched data:\\n{}\".format(workspace.FetchBlob(\"gpu_0/data\")))\n if cur_iter == start_iter:\n nu.print_net(model)\n training_stats.IterToc()\n training_stats.UpdateIterStats()\n try:\n training_stats.LogIterStats(cur_iter, lr, viz, win_accuracy_cls, win_loss, win_loss_bbox, win_loss_cls)\n except:\n training_stats.LogIterStats(cur_iter, lr)\n\n if (cur_iter + 1) % (CHECKPOINT_PERIOD/4) == 0 and cur_iter > start_iter:#((cur_iter + 1) % (CHECKPOINT_PERIOD/1) == 0 and (cur_iter > start_iter and cur_iter < 50000)) or ((cur_iter + 1) % (CHECKPOINT_PERIOD/8) == 0 and cur_iter > 50000):\n checkpoints[cur_iter] = os.path.join(\n output_dir, 'model_iter_50_{}.pkl'.format(cur_iter)\n )\n nu.save_model_to_weights_file(checkpoints[cur_iter], model)\n\n if cur_iter == start_iter + training_stats.LOG_PERIOD:\n # Reset the iteration timer to remove outliers from the first few\n # SGD iterations\n training_stats.ResetIterTimer()\n\n if np.isnan(training_stats.iter_total_loss):\n logger.critical('Loss is NaN, exiting...')\n model.roi_data_loader.shutdown()\n envu.exit_on_error()\n\n # Save the final model\n checkpoints['final'] = os.path.join(output_dir, 'model_final_50.pkl')\n nu.save_model_to_weights_file(checkpoints['final'], model)\n # Shutdown data loading threads\n model.roi_data_loader.shutdown()\n return checkpoints\n\n\ndef create_model():\n \"\"\"Build the model and look for saved model checkpoints in case we can\n resume from one.\n \"\"\"\n logger = logging.getLogger(__name__)\n start_iter = 0\n checkpoints = {}\n output_dir = get_output_dir(cfg.TRAIN.DATASETS, training=True)\n weights_file = cfg.TRAIN.WEIGHTS#'/home/icubic/daily_work/code/Detectron/train/coco_2014_train/generalized_rcnn_S1S2/model_final2.pkl'##cfg.TRAIN.WEIGHTS\n if cfg.TRAIN.AUTO_RESUME:\n # Check for the final model (indicates training already finished)\n final_path = os.path.join(output_dir, 'model_final.pkl')\n if os.path.exists(final_path):\n logger.info('model_final.pkl exists; no need to train!')\n return None, None, None, {'final': final_path}, output_dir\n\n if cfg.TRAIN.COPY_WEIGHTS:\n copyfile(\n weights_file,\n os.path.join(output_dir, os.path.basename(weights_file)))\n logger.info('Copy {} to {}'.format(weights_file, output_dir))\n\n # Find the most recent checkpoint (highest iteration number)\n files = os.listdir(output_dir)\n for f in files:\n iter_string = re.findall(r'(?<=model_iter)\\d+(?=\\.pkl)', f)\n if len(iter_string) > 0:\n checkpoint_iter = int(iter_string[0])\n if checkpoint_iter > start_iter:\n # Start one iteration immediately after the checkpoint iter\n start_iter = checkpoint_iter + 1\n resume_weights_file = f\n\n if start_iter > 0:\n # Override the initialization weights with the found checkpoint\n weights_file = os.path.join(output_dir, resume_weights_file)\n logger.info(\n '========> Resuming from checkpoint {} at start iter {}'.\n format(weights_file, start_iter)\n )\n\n logger.info('Building model: {}'.format(cfg.MODEL.TYPE))\n model = model_builder.create(cfg.MODEL.TYPE, train=True) #for create model\n if cfg.MEMONGER:\n optimize_memory(model)\n # Performs random weight initialization as defined by the model\n workspace.RunNetOnce(model.param_init_net)\n return model, weights_file, start_iter, checkpoints, output_dir\n\n\ndef optimize_memory(model):\n \"\"\"Save GPU memory through blob sharing.\"\"\"\n for device in range(cfg.NUM_GPUS):\n namescope = 'gpu_{}/'.format(device)\n losses = [namescope + l for l in model.losses]\n model.net._net = memonger.share_grad_blobs(\n model.net,\n losses,\n set(model.param_to_grad.values()),\n namescope,\n share_activations=cfg.MEMONGER_SHARE_ACTIVATIONS\n )\n\n\ndef setup_model_for_training(model, weights_file, output_dir):\n \"\"\"Loaded saved weights and create the network in the C2 workspace.\"\"\"\n logger = logging.getLogger(__name__)\n queue_name = add_model_training_inputs(model) #non with pre_data\n\n if weights_file:\n # Override random weight initialization with weights from a saved model\n nu.initialize_gpu_from_weights_file(model, weights_file, gpu_id=0)\n # Even if we're randomly initializing we still need to synchronize\n # parameters across GPUs\n\n nu.broadcast_parameters(model)\n workspace.CreateNet(model.net)\n #return\n\n\n\n\n\n logger.info('Outputs saved to: {:s}'.format(os.path.abspath(output_dir)))\n dump_proto_files(model, output_dir)\n\n # Start loading mini-batches and enqueuing blobs\n model.roi_data_loader.register_sigint_handler()\n model.roi_data_loader.start(prefill=True)\n\n return output_dir\n\n\ndef add_model_training_inputs(model):#for add input data\n \"\"\"Load the training dataset and attach the training inputs to the model.\"\"\"\n logger = logging.getLogger(__name__)\n logger.info('Loading dataset: {}'.format(cfg.TRAIN.DATASETS))\n roidb = combined_roidb_for_training(\n cfg.TRAIN.DATASETS, cfg.TRAIN.PROPOSAL_FILES\n )\n logger.info('{:d} roidb entries'.format(len(roidb)))\n queue_name = model_builder.add_training_inputs(model, roidb=roidb) #for roidb input_important\n return queue_name\n\n\ndef dump_proto_files(model, output_dir):\n \"\"\"Save prototxt descriptions of the training network and parameter\n initialization network.\"\"\"\n with open(os.path.join(output_dir, 'net.pbtxt'), 'w') as fid:\n fid.write(str(model.net.Proto()))\n with open(os.path.join(output_dir, 'param_init_net.pbtxt'), 'w') as fid:\n fid.write(str(model.param_init_net.Proto()))\n","sub_path":"Detectron/detectron/utils/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":14181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"87284034","text":"import sys\nimport os\nfrom PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QAction, QInputDialog, QLineEdit, QFileDialog, QDesktopWidget\nfrom PyQt5.QtWidgets import QComboBox, QDialog, QDialogButtonBox, QFormLayout, QGridLayout, QGroupBox, QHBoxLayout, QLabel, QLineEdit, QMenu, QMenuBar, QPushButton, QSpinBox, QTextEdit, QVBoxLayout\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtCore import pyqtSlot\n\nclass App(QMainWindow):\n\tdef __init__(self, parent=None):\n\t\tsuper().__init__()\n\t\t#Get screen size and set window\n\t\tself.title = \"Text Analyser\"\n\t\tresolution = QDesktopWidget().screenGeometry()\n\t\tself.left = (resolution.width() / 2) - (self.frameSize().width() / 2)\n\t\tself.top = (resolution.height() / 2) - (self.frameSize().height() / 2)\n\t\tself.width = 640\n\t\tself.height = 480\n\t\tself.input_nodes = 0\n\t\tself.hidden_nodes = 0\n\t\tself.output_nodes = 0\n\t\tself.learningrate = 0\n\t\tself.initUI()\n\n\tdef initUI(self):\n\t\t#Boilerplate code\n\t\tself.setWindowTitle(self.title)\n\t\tself.setGeometry(self.left, self.top, self.width, self.height)\n\t\tself.loadMenu()\n\t\tself.show()\n\n\tdef loadMenu(self):\n\t\t#Initialize menu items here\n\t\tmainMenu = self.menuBar()\n\t\tmainMenu.setNativeMenuBar(False)\n\t\tfileMenu = mainMenu.addMenu(\"File\")\n\t\teditMenu = mainMenu.addMenu(\"Edit\")\n\t\thelpMenu = mainMenu.addMenu(\"Help\")\n\n\t\tloadButton = QAction(\"Load\", self)\n\t\tloadButton.setShortcut(\"Ctrl+L\")\n\t\tloadButton.setStatusTip(\"Load Network\")\n\t\tloadButton.triggered.connect(self.loadNetwork)\n\n\t\ttrainButton = QAction(\"Train\", self)\n\t\ttrainButton.setShortcut(\"Ctrl+T\")\n\t\ttrainButton.setStatusTip(\"Train Network\")\n\t\ttrainButton.triggered.connect(self.trainNetwork)\n\n\t\tquitButton = QAction(\"Quit\", self)\n\t\tquitButton.setShortcut(\"Ctrl+Q\")\n\t\tquitButton.setStatusTip(\"Quit Application\")\n\t\tquitButton.triggered.connect(self.close)\n\n\t\tfileMenu.addAction(trainButton)\n\t\tfileMenu.addAction(loadButton)\n\t\tfileMenu.addAction(quitButton)\n\n\tdef loadNetwork(self):\n\t\t#Find file name of network user intended to load\n\t\tprint(\"Loading file browser\")\n\t\toptions = QFileDialog.Options()\n\t\toptions = QFileDialog.ShowDirsOnly\n\t\toptions |= QFileDialog.DontUseNativeDialog\n\t\t#self.networkName, _ = QFileDialog.getOpenFileName(self,\"File Broswer\", \"\",\"All Files (*);;Python Files (*.py)\", options=options)\n\t\tself.networkName = QFileDialog.getExistingDirectory(self, \"Select Network\", os.getcwd(), options=options)\n\t\tprint(self.networkName)\n\n\t\t#Attempt try catch for files in folder\n\t\t#\n\t\t#\n\t\t#\n\t\t#\n\n\tdef trainNetwork(self):\n\t\t#Loads Dialog class which inherits from\n\t\tdialog = Dialog(self)\n\t\tdialog.show()\n\n\t\t\nclass Dialog(QDialog, App):\n\tdef __init__(self, parent=None):\n\t\tQDialog.__init__(self, parent)\n\t\tself.createFormGroupBox()\n\n\t\tbuttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)\n\t\tbuttonBox.accepted.connect(self.accept)\n\t\tbuttonBox.rejected.connect(self.reject)\n\n\t\tmainLayout = QVBoxLayout()\n\t\tmainLayout.addWidget(self.formGroupBox)\n\t\tmainLayout.addWidget(buttonBox)\n\t\tself.setLayout(mainLayout)\n\t\tself.setWindowTitle(\"Network attributes\")\n\n\tdef createFormGroupBox(self):\n\t\tself.formGroupBox = QGroupBox(\"Settings\")\n\t\tlayout = QFormLayout()\n\t\tlayout.addRow(QLabel(\"Number of input neurons:\"), QLineEdit())\n\t\tlayout.addRow(QLabel(\"Number of hidden neurons:\"), QLineEdit())\n\t\tlayout.addRow(QLabel(\"Number of output neurons:\"), QLineEdit())\n\t\tlayout.addRow(QLabel(\"Learning rate:\"), QLineEdit())\n\t\tlayout.addRow(QLabel(\"Amount of epochs:\"), QLineEdit())\n\n\t\tself.formGroupBox.setLayout(layout)\n\nif __name__ == \"__main__\":\n\t#Execute application\n\tapp = QApplication(sys.argv)\n\tex = App()\n\tprint(\"Running application...\")\n\tsys.exit(app.exec_())","sub_path":"menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":3631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"377403396","text":"# -*- coding: utf-8 -*-\n\"\"\"API to declare benchmarks\n\"\"\"\n\nfrom abc import ABCMeta, abstractmethod, abstractproperty\nfrom collections import namedtuple\nimport os.path as osp\n\nfrom six import with_metaclass\n\n__all__ = [\n 'Benchmark',\n 'ExecutionContext',\n 'MetricsExtractor',\n]\n\n# Metrics have simply a unit and a type\n# namedtuples are compact and have a nice str representation\nMetric = namedtuple(\"Metric\", \"unit type\")\n\n\nExecutionContext = namedtuple(\n \"ExecutionContext\",\n [\n \"node\",\n \"tag\",\n \"nodes\",\n \"logger\",\n \"srun_options\",\n ]\n)\n\n\nclass UnexpectedMetricsException(Exception):\n def __init__(self, unset_metrics, metrics):\n self.unset_metrics = unset_metrics\n self.metrics = metrics\n\n def __str__(self):\n error = \\\n 'Could not extract some metrics: %s\\n' \\\n 'metrics set: %s'\n return error % (', '.join(self.unset_metrics),\n ', '.join(set(self.metrics)))\n\n\nclass Metrics(object): # pragma pylint: disable=too-few-public-methods\n \"\"\"List of common metrics\n \"\"\"\n Microsecond = Metric('us', float)\n Millisecond = Metric('ms', float)\n Second = Metric('s', float)\n MegaBytesPerSecond = Metric('MB/s', float)\n GigaBytesPerSecond = Metric('GB/s', float)\n Cardinal = Metric('#', int)\n Byte = Metric('B', int)\n Flops = Metric('flop/s', float)\n Bool = Metric('bool', bool)\n Ops = Metric('op/s', float)\n\n\nclass MetricsExtractor(with_metaclass(ABCMeta, object)):\n \"\"\"Extract data from a benchmark command outputs\n \"\"\"\n\n @abstractproperty\n def metrics(self):\n \"\"\"List of exported metrics\n\n :return: exported metrics\n :rtype: ``dict of\n metric_name: dict('type'=python_type, 'unit'=string)``\n\n for instance:\n\n >>> def metrics(self):\n return dict(\n rmax=dict(type=float, unit='Gflops'),\n parallel_efficiency=dict(type=float, unit='percent')\n )\n\n \"\"\"\n raise NotImplementedError # pragma: no cover\n\n @abstractmethod\n def extract_metrics(self, outdir, metas):\n \"\"\"Extract metrics from benchmark output\n\n :return: ``dict of metric_name: metric_value``\n\n ``metric_value`` type should be the one specified in\n the ``metrics`` member funtion.\n \"\"\"\n raise NotImplementedError # pragma: no cover\n\n @property\n def check_metrics(self):\n \"\"\"Ensures that metrics returned by ``extract`` member function\n is exactly what was declared.\n \"\"\"\n return True\n\n def extract(self, outdir, metas):\n metrics = self.extract_metrics(outdir, metas)\n if self.check_metrics:\n self._check_metrics(metrics)\n return metrics\n\n def _check_metrics(self, metrics):\n unset_metrics = set(self.metrics) - set(metrics)\n if any(unset_metrics):\n raise UnexpectedMetricsException(unset_metrics, metrics)\n\n @classmethod\n def stdout(cls, outdir):\n \"\"\"Get path to the file containing stdout written\n by benchmark command\n\n :param outdir: absolute path to the benchmark output directory\n :return: path to standard output file\n :rtype: string\n \"\"\"\n return osp.join(outdir, 'stdout.txt')\n\n @classmethod\n def stderr(cls, outdir):\n \"\"\"Get path to the file containing stderr written\n by benchmark command\n\n :param outdir: absolute path to the benchmark output directory\n :return: path to error output file\n :rtype: string\n \"\"\"\n return osp.join(outdir, 'stderr.txt')\n\n\nclass Benchmark(with_metaclass(ABCMeta, object)):\n \"\"\"Declare benchmark utility\n \"\"\"\n\n # --- Class \"static\" properties ---\n @abstractproperty\n def name(self):\n \"\"\"Get benchmark name\n\n :rtype: string\n \"\"\"\n raise NotImplementedError # pragma: no cover\n\n @abstractproperty\n def description(self):\n \"\"\"Get benchmark long description\n\n :rtype: string\n \"\"\"\n raise NotImplementedError # pragma: no cover\n # ---\n\n def __init__(self, attributes=None):\n self.attributes = attributes or {}\n\n @property\n def in_campaign_template(self):\n \"\"\"Should the benchmark class be reference in the\n campaign template YAML file\n \"\"\"\n return True\n\n @abstractmethod\n def execution_matrix(self, context):\n \"\"\"Describe benchmark commands\n\n :param context: `ExecutionContext` instance\n\n Provides list of commands to perform. Every returned command\n is a dictionary containing the following keys:\n\n * *command*:\n a list of string containing the command to execute.\n Variable substitution is performed on every element\n on the list, using the Python str.format\n method.\n\n Here is the list of available variables:\n process_count: number of processes to run.\n it provides the --ntasks value when using\n the `srun` execution layer.\n\n See https://docs.python.org/2/library/stdtypes.html#str.format\n\n * category*:\n a string used to group commands together.\n Most benchmark class may only need one category.\n * *metas*:\n a dictionary providing relevant information regarding the\n executed command that may be useful afterward. Typically,\n those are command's inputs.\n * *environment* (optional):\n a dictionary providing additional environment variables\n to be given to the executed command\n * *srun_nodes* (optional):\n When the `srun` execution layer is enabled,\n an integer providing the number of required nodes.\n Must be greater equal than 0 and less than the number of nodes\n of the tag the benchmark is part of.\n If 0, then the job is executed on all nodes of the tag the\n benchmark is part of.\n If a string is provided, then all nodes of the given tag will\n be used.\n Note: this parameter is ignored if -C/--constraint\n slurm option is used.\n * *shell* (optional boolean):\n when `shell` parameter is `True`, then the given command\n is considered as a shell command.\n * *cwd* (optional):\n directory where the command is executed.\n\n Execution context: for every command, a dedicated output directory\n is created and the current working directory changed to this directory\n prior command execution. Standard and error outputs are redirected\n to stdout.txt and stderr.txt respectively. Additional output files\n may be created in this directory.\n Any occurence to \"{outdir}\" in the command field will be substituted\n by the output directory.\n\n :return: commands to execute\n :rtype: list of dict. For instance:\n\n >>> def execution_matrix(self):\n for core in [1, 4, 16, 64]:\n yield dict(\n category='foo',\n command=['foo', '--cores', str(cores)],\n metas=dict(cores=cores),\n )\n yield dict(\n category='bar',\n command=['bar', '--cores', str(cores)],\n metas=dict(cores=cores),\n )\n \"\"\"\n raise NotImplementedError # pragma: no cover\n\n def pre_execute(self, execution):\n \"\"\"Method called before executing one of the commands.\n Current working directory is the execution directory.\n\n :param execution: one of the dictionary\n provided in ``execution_matrix`` member method.\n \"\"\"\n del execution # unused\n\n def post_execute(self, execution):\n \"\"\"Method called after executing one of the commands.\n Current working directory is the execution directory.\n\n :param execution: one of the dictionary\n provided in ``execution_matrix`` member method.\n \"\"\"\n del execution # unused\n\n @abstractproperty\n def metrics_extractors(self):\n \"\"\"Describe how to extract metrics from files written by\n benchmark commands.\n\n Provides metrics extractors for every categories specified\n in the ``execution_matrix`` member method.\n\n :return: metrics_extractors instances for each category\n :rtype: ``dict of list of hpcbench.api.MetricsExtractor`` instances.\n if there are dedicated extractors for each category.\n Otherwise a ``list of hpcbench.api.MetricsExtractor``\n instances of there are common extractors for all categories,\n\n The list structure can be skipped when there is one\n element. For instance if there are dedicated extractors for every\n categories:\n\n >>> def metrics_extractors(self):\n return dict(\n foo=foo_stdout_extractor(metrics=['rmax', 'efficiency']),\n bar=[bar_extractor(), foobar_extractor()]\n )\n\n If there is only one extractor:\n\n >>> def metrics_extractors(self):\n return foobar_extractor()\n\n \"\"\"\n raise NotImplementedError # pragma: no cover\n\n @property\n def plots(self):\n \"\"\"Describe figures to generate\n\n :return: figure descriptions of every category\n :rtype: ``dict of string -> list of dict``\n\n Every dictionary is a figure's description, containing\n the following keys:\n\n * *name*: string providing figure's name\n\n * *series*: dictionary describing data required to draw the figure,\n made of 2 keys:\n\n * *metas*: string list of metas to retrieve.\n Data series are sorted by metas by default.\n If meta's name starts with '-',\n then series are sorted in descending order.\n\n * *metrics*: list of metrics to use.\n\n * *plotter*:\n callable object that will be given metrics to plot\n \"\"\"\n return {}\n\n @classmethod\n def get_subclass(cls, name):\n \"\"\"Get Benchmark subclass by name\n :param name: name returned by ``Benchmark.name`` property\n :return: instance of ``Benchmark`` class\n \"\"\"\n for subclass in cls.__subclasses__():\n if subclass.name == name:\n return subclass\n raise NameError(\"Not a valid Benchmark class: \" + name)\n","sub_path":"hpcbench/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":10630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"88765186","text":"print(\"\"\"\r\n18. Faça um programa que mostre ao usuário um menu com 4 opções de operações matemáticas (as básicas, por exemplo).\r\nO usuário escolhe uma das opções e o seu programa então pede dois valores numéricos e realiza A operação, mostrando o resultado e saindo.\r\n\"\"\")\r\n\r\nprint('''\r\n[1] Soma\r\n[2] Multiplicação\r\n[3] Subtração\r\n[4] Divisão\r\n''')\r\n\r\nescolha = int(input('Escolha: '))\r\nnum1 = int(input('Primeiro valor numerico para A operação: '))\r\nnum2 = int(input('Segundo valor numerico para A operação: '))\r\n\r\nif escolha == 1:\r\n resultado = num1 + num2\r\n print(f'{num1} + {num2} = {resultado}')\r\n\r\nelif escolha == 2:\r\n resultado = num1 * num2\r\n print(f'{num1} * {num2} = {resultado}')\r\n\r\nelif escolha == 3:\r\n resultado = num1 - num2\r\n print(f'{num1} - {num2} = {resultado}')\r\n\r\nelif escolha == 4:\r\n resultado = num1 / num2\r\n print(f'{num1} / {num2} = {resultado}')\r\n\r\nelse:\r\n print('Escolha inválida.')\r\n","sub_path":"Seção_05/Exercício_18.py","file_name":"Exercício_18.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"29071785","text":"wsp=[]\nDelta=[]\ndef czytajWspolczynniki():\n wsp=[]\n a=float(input('Podaj pierwszy współczynnik:'))\n wsp.append(a)\n b=float(input('Podaj drugi współczynnik:'))\n wsp.append(b)\n c=float(input('Podaj trzeci współczynnik:'))\n wsp.append(c)\n print('Równanie kwadratowe postaci:',int(a),'x2+(',int(b),')x+(',int(c),')')\n return wsp\n\ndef obliczDelte(wsp):\n import math\n a=int(wsp[0])\n b=int(wsp[1])\n c=int(wsp[2])\n delta=math.pow(b,2)-(4*a*c)\n print (\"\\nDelta wynosi:\",delta)\n Delta.append(delta)\n return Delta\n\ndef obliczPierwiastki(wsp,Delta):\n Delta=Delta[0]\n import math\n pierwiastki=[]\n if Delta<0:\n print('Brak miejsc zerowych')\n elif Delta==0:\n z=(-wsp[1])/(2*wsp[0])\n pierwiastki.append(z)\n print('Miejsce zerowe funkcji to: x0=',*pierwiastki)\n else:\n y=(-(math.pow(Delta,-1))-wsp[1])/(2*wsp[0])\n z=(-(math.pow(Delta,-1))+wsp[1])/(2*wsp[0])\n print('Miejsca zerowe funkcji to: x1=',y,', x2=',z)","sub_path":"05-ModularProgramming/QuadraticEquation.py","file_name":"QuadraticEquation.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"118793060","text":"\nclass Node:\n\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n \nclass BinaryTree:\n\n def __init__(self, root=None):\n self.root = root\n\n def traverse(self, starting_node=None, default_traversal='in-order'):\n \n def in_order_traversal(node):\n if node.left is not None:\n in_order_traversal(node.left)\n print(node.data)\n if node.right is not None:\n in_order_traversal(node.right)\n \n def pre_order_traversal(node):\n print(node.data)\n if node.left is not None:\n pre_order_traversal(node.left)\n if node.right is not None:\n pre_order_traversal(node.right)\n\n def post_order_traversal(node):\n if node.left is not None:\n post_order_traversal(node.left)\n if node.right is not None:\n post_order_traversal(node.right)\n print(node.data)\n \n traversal_logics = {\n 'in-order' : in_order_traversal,\n 'pre-order' : pre_order_traversal,\n 'post-order' : post_order_traversal\n }\n\n try:\n traversal_func = traversal_logics[default_traversal]\n except KeyError:\n print('Invalid traversal requested. Please select any from : in-order, pre-order, postorder')\n\n if not starting_node:\n starting_node = self.root\n\n traversal_func(starting_node)\n\nif __name__ == \"__main__\":\n \n # Tree used as example was taken from this link : https://www.tutorialspoint.com/data_structures_algorithms/tree_traversal.htm\n\n A = Node('A')\n B = Node('B')\n C = Node('C')\n D = Node('D')\n E = Node('E')\n F = Node('F')\n G = Node('G')\n\n tree = BinaryTree(A)\n A.left = B\n A.right = C\n B.left = D\n B.right = E\n C.left = F\n C.right = G\n\n # set either 'in-order', 'pre-order' or 'post-order' as the default-traversal.\n tree.traverse(default_traversal='post-order')","sub_path":"Tree/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"128552975","text":"#! /home/gaofan01/develop/bin/python3\n# -*- coding:utf-8 -*-\n# author by Gaofan\n\nfrom selenium import webdriver\n\nbrowser = webdriver.Firefox()\n\n# 伊丽丝听说有一个很酷的在线待办事项应用\n# 她去看了这个应用的我首页\nbrowser.get('http://localhost:8000')\n\n# 她注意到网页的标题和头部都包含 “TO DO” 这个词\nassert 'To-Do' in browser.title\n\n# 应用邀请她输入一个待办事项\n\n# 她再一个文本框中输入了 “Buy peacock feathers” (够买孔雀羽毛)\n# 伊例丝的爱好是使用假蝇做鱼饵\n\n# 她按回车键后,页面更新了\n# 待办事项表格中显示了 “1: Buy peacock feathers���\n\n# 页面中又显示了一个文本框,可以输入其他的待办事项\n# 她输入了 “Use peacock feathers to make a fly”(使用孔雀羽毛做假蝇)\n# 伊丽丝做事很有条理\n\n# 伊丽丝想知道这个网站是否会记住她的清单\n# 她看到网站为她生成一个唯一的URL\n# 而且页面中有一些文字解说这样功能\n\n# 她访问那个URL,发现她的待办事项列表还在\n\n# 她很满意,去睡觉了\n\nbrowser.quit()","sub_path":"superlists/function_tests.py","file_name":"function_tests.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"535381253","text":"import os\nimport logging\n\n\ndef _setup_logging(logpath, print_debug=False):\n \"\"\"Setup logging.\n Args:\n logpath (str): directory to dump log files in.\n \"\"\"\n logger = logging.getLogger()\n logger.setLevel(logging.DEBUG)\n\n formatter = logging.Formatter(\"%(levelname)s - %(name)s :: %(message)s\")\n handler = logging.StreamHandler()\n handler.setFormatter(formatter)\n handler.setLevel(logging.DEBUG if print_debug else logging.INFO)\n logger.addHandler(handler)\n\n if not logpath:\n logging.info(\"file logging not configured\")\n return\n\n formatter = logging.Formatter(\"%(asctime)s - %(levelname)s - %(name)s :: %(message)s\")\n handler = logging.FileHandler(\n filename=os.path.join(logpath, \"ikabot.log\"),\n encoding=\"utf-8\",\n mode=\"a\",\n )\n handler.setFormatter(formatter)\n handler.setLevel(logging.DEBUG)\n logger.addHandler(handler)\n\n\ndef _fetch_bot_token():\n \"\"\"Fetch the token to use from the environment\n Raises:\n RuntimeError: raised if no token can be fetched.\n Returns:\n str: discord bot token.\n \"\"\"\n token = os.getenv(\"IKA_DISCORD_TOKEN\")\n if token:\n return token\n raise RuntimeError(\"no IkaBot discord token configured\")\n\n\ndef _parse_args():\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-d\", \"--debug\", action=\"store_true\", default=False,\n help=\"print debug info.\",\n )\n parser.add_argument(\n \"--log-dir\",\n help=\"directory to log files into, takes priority over the environment setting.\",\n )\n\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n args = _parse_args()\n _setup_logging(\n args.log_dir or os.getenv(\"IKA_LOG_PATH\"),\n print_debug=args.debug,\n )\n\n from .base import bot\n from .entrybanner import EntryBannerCog, EntryBannerDataStore\n\n if not os.getenv(\"IKA_DATA_PATH\"):\n raise RuntimeError(\"IKA_DATA_PATH has not been configured\")\n\n eb_data = EntryBannerDataStore(\n os.path.join(os.getenv(\"IKA_DATA_PATH\"), \"entrybanner.json\")\n )\n eb_data.load()\n\n @bot.event\n async def on_ready():\n logging.getLogger().info(\"IkaBot ready for use!\")\n bot.add_cog(EntryBannerCog(bot, eb_data))\n\n bot.run(_fetch_bot_token())\n","sub_path":"src/ikabot/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"148998809","text":"# The read4 API is already defined for you.\n# @param buf, a list of characters\n# @return an integer\n# def read4(buf):\n\nclass Solution(object):\n def __init__(self):\n # use producer - consumer model\n self.q = collections.deque([])\n\n def read(self, buf, n):\n numReadTotal = 0\n localBuf = [''] * 4\n while numReadTotal < n:\n # producer\n if not self.q: # local buffer is empty now\n numRead = read4(localBuf) # reads to localBuf\n self.q.extend(localBuf[0:numRead]) # for every read append new content to the queue\n\n # consumer\n # when there is element in queue, consumer directly from queue\n if self.q:\n buf[numReadTotal] = self.q.popleft() # append read element to buf one-by-one\n numReadTotal += 1\n else:\n break # that means EOF\n return numReadTotal\n\n","sub_path":"158_read_n_characters_given_read4_II/producer-consumer.py","file_name":"producer-consumer.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"638817178","text":"from shutil import copy\nfrom time import strftime, localtime\nfrom util.Logger import Logger\nfrom util.util import load_class_from_source_path\nfrom dict_keys.model_metadata_keys import *\nfrom env_settting import tensorboard_dir\n\nimport sys\nimport tensorflow as tf\nimport os\nimport inspect\nimport json\nimport subprocess\n\nTOTAL_EPOCH = 10000\nCHECK_POINT_INTERVAL = 1000\n\nMETA_DATA_FILE_NAME = 'model.meta'\nINSTANCE_FOLDER = 'instance'\nVISUAL_RESULT_FOLDER = 'visual_results'\n\n\ndef log_exception(func):\n def wrapper(*args):\n try:\n return func(*args)\n except Exception as e:\n self = args[0]\n self.log(str(e))\n self.log('catch error')\n\n return wrapper\n\n\nclass InstanceManager:\n def __init__(self, root_path):\n self.root_path = root_path\n self.logger = Logger(self.__class__.__name__, self.root_path)\n self.log = self.logger.get_log()\n self.model = None\n self.visualizers = []\n self.sub_process = {}\n\n def __del__(self):\n # reset tensorflow graph\n tf.reset_default_graph()\n\n for process_name in self.sub_process:\n if self.sub_process[process_name].poll is None:\n self.close_subprocess(process_name)\n\n del self.root_path\n del self.log\n del self.logger\n del self.model\n del self.visualizers\n\n def gen_instance(self, model=None, input_shapes=None):\n # gen instance id\n model_name = \"%s_%s_%.1f\" % (model.AUTHOR, model.__name__, model.VERSION)\n instance_id = model_name + '_' + strftime(\"%Y-%m-%d_%H-%M-%S\", localtime())\n self.log('gen instance id : %s' % instance_id)\n\n # init instance directory\n instance_path = os.path.join(self.root_path, INSTANCE_FOLDER)\n if not os.path.exists(instance_path):\n os.mkdir(instance_path)\n\n # init user instance directory \n instance_path = os.path.join(self.root_path, INSTANCE_FOLDER, instance_id)\n if not os.path.exists(instance_path):\n os.mkdir(instance_path)\n\n instance_visual_result_folder_path = os.path.join(instance_path, VISUAL_RESULT_FOLDER)\n if not instance_visual_result_folder_path:\n os.mkdir(instance_visual_result_folder_path)\n\n instance_source_folder_path = os.path.join(instance_path, 'src_code')\n if not os.path.exists(instance_source_folder_path):\n os.mkdir(instance_source_folder_path)\n\n instance_summary_folder_path = os.path.join(instance_path, 'summary')\n if not os.path.exists(instance_summary_folder_path):\n os.mkdir(instance_summary_folder_path)\n self.log('init instance directory')\n\n # copy model's module file to instance/src/\"model_id.py\"\n instance_source_path = os.path.join(instance_source_folder_path, instance_id + '.py')\n try:\n copy(inspect.getsourcefile(model), instance_source_path)\n except IOError as e:\n print(e)\n self.log('dump model source code')\n\n # init and dump metadata\n metadata = {\n MODEL_METADATA_KEY_INSTANCE_ID: instance_id,\n MODEL_METADATA_KEY_INSTANCE_PATH: instance_path,\n MODEL_METADATA_KEY_INSTANCE_VISUAL_RESULT_FOLDER_PATH: instance_visual_result_folder_path,\n MODEL_METADATA_KEY_INSTANCE_SOURCE_FOLDER: instance_source_folder_path,\n MODEL_METADATA_KEY_INSTANCE_SOURCE_PATH: instance_source_path,\n MODEL_METADATA_KEY_INSTANCE_CLASS_NAME: model.__name__,\n MODEL_METADATA_KEY_README: self.gen_readme(),\n MODEL_METADATA_KEY_INSTANCE_SUMMARY_FOLDER_PATH: instance_summary_folder_path\n }\n metadata_path = os.path.join(instance_path, 'instance.meta')\n self.dump_json(metadata, metadata_path)\n self.log('dump metadata')\n\n # build model\n self.model = model(metadata, input_shapes)\n self.log('build model')\n\n self.metadata_path = metadata_path\n self.metadata = metadata\n\n def load_model(self, metadata_path, input_shapes):\n metadata = self.load_json(metadata_path)\n self.log('load metadata')\n\n instance_class_name = metadata[MODEL_METADATA_KEY_INSTANCE_CLASS_NAME]\n instance_source_path = metadata[MODEL_METADATA_KEY_INSTANCE_SOURCE_PATH]\n model = load_class_from_source_path(instance_source_path, instance_class_name)\n self.log('model source code load')\n\n self.model = model(metadata, input_shapes)\n self.log('build model')\n\n instance_id = metadata[MODEL_METADATA_KEY_INSTANCE_ID]\n self.log('load instance id : %s' % instance_id)\n\n def load_visualizer(self, visualizers):\n visualizer_path = self.model.instance_visual_result_folder_path\n for visualizer, iter_cycle in visualizers:\n if not os.path.exists(visualizer_path):\n os.mkdir(visualizer_path)\n\n self.visualizers += [visualizer(visualizer_path, iter_cycle=iter_cycle)]\n self.log('visualizer %s loaded' % visualizer.__name__)\n\n self.log('visualizer fully Load')\n\n def train_model(self, dataset, epoch_time=TOTAL_EPOCH, check_point_interval=CHECK_POINT_INTERVAL, is_restore=False):\n saver = tf.train.Saver()\n save_path = os.path.join(self.model.instance_path, 'check_point')\n check_point_path = os.path.join(save_path, 'model.ckpt')\n if not os.path.exists(save_path):\n os.mkdir(save_path)\n self.log('make save dir')\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n self.log('init global variables')\n\n summary_writer = tf.summary.FileWriter(self.model.instance_summary_folder_path, sess.graph)\n self.log('init summary_writer')\n\n if is_restore:\n saver.restore(sess, check_point_path)\n self.log('restore check point')\n\n batch_size = self.model.batch_size\n iter_per_epoch = int(dataset.data_size / batch_size)\n self.log('total Epoch: %d, total iter: %d, iter per epoch: %d' % (\n epoch_time, epoch_time * iter_per_epoch, iter_per_epoch))\n\n iter_num, loss_val_D, loss_val_G = 0, 0, 0\n for epoch in range(epoch_time):\n for _ in range(iter_per_epoch):\n iter_num += 1\n self.model.train_model(sess=sess, iter_num=iter_num, dataset=dataset)\n self.__visualizer_task(sess, iter_num, dataset)\n\n self.model.write_summary(sess=sess, iter_num=iter_num, dataset=dataset,\n summary_writer=summary_writer)\n\n if iter_num % check_point_interval == 0:\n saver.save(sess, check_point_path)\n\n self.log('train end')\n\n tf.reset_default_graph()\n self.log('reset default graph')\n\n def sample_model(self, is_restore=False):\n self.log('start train_model')\n saver = tf.train.Saver()\n\n save_path = os.path.join(self.model.instance_path, 'check_point')\n check_point_path = os.path.join(save_path, 'model.ckpt')\n if not os.path.exists(save_path):\n os.mkdir(save_path)\n self.log('make save dir')\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n if is_restore:\n saver.restore(sess, check_point_path)\n self.log('restore check point')\n\n self.__visualizer_task(sess)\n\n self.log('sampling end')\n\n tf.reset_default_graph()\n self.log('reset default graph')\n\n def __visualizer_task(self, sess, iter_num=None, dataset=None):\n for visualizer in self.visualizers:\n if iter_num is None or iter_num % visualizer.iter_cycle == 0:\n try:\n visualizer.task(sess, iter_num, self.model, dataset)\n except Exception as err:\n self.log('at visualizer %s \\n %s' % (visualizer, err))\n\n def open_subprocess(self, args, process_name):\n if process_name in self.sub_process and self.sub_process[process_name].poll is not None:\n # TODO better error class\n raise AssertionError(\"process '%s'(pid:%s) already exist and still running\" % (\n process_name, self.sub_process[process_name].pid))\n\n self.sub_process[process_name] = subprocess.Popen(args)\n str_args = \" \".join(map(str, args))\n pid = self.sub_process[process_name].pid\n self.log(\"open subprocess '%s', pid: %s\" % (str_args, pid))\n\n def close_subprocess(self, process_name):\n if process_name in self.sub_process:\n self.log(\"kill subprocess '%s', pid: %s\" % (process_name, self.sub_process[process_name].pid))\n self.sub_process[process_name].kill()\n else:\n raise KeyError(\"fail close subprocess, '%s' not found\" % process_name)\n\n def open_tensorboard(self):\n python_path = sys.executable\n option = '--logdir=' + self.model.instance_summary_folder_path\n args = [python_path, tensorboard_dir(), option]\n self.open_subprocess(args=args, process_name=\"tensorboard\")\n\n def close_tensorboard(self):\n self.close_subprocess('tensorboard')\n\n @staticmethod\n def dump_json(obj, path):\n with open(path, 'w') as f:\n json.dump(obj, f)\n\n @staticmethod\n def load_json(path):\n with open(path, 'r') as f:\n metadata = json.load(f)\n return metadata\n\n @staticmethod\n def gen_readme():\n # TODO implement\n return {}\n","sub_path":"InstanceManger.py","file_name":"InstanceManger.py","file_ext":"py","file_size_in_byte":9691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"499262401","text":"#!/usr/bin/python3.8\n\n\nfrom pathlib import Path\nimport sys\nimport logging\nimport tornado\nimport datetime\nlogging.basicConfig(level=logging.DEBUG)\nsys.path.insert(0, str(Path.cwd().parent))\nimport tornado.web\nfrom pyindi.webclient import INDIWebApp, INDIHandler\n\n\n\"\"\"\nTHis script uses the INDIWebApp class to build an INDI\nclient as a tornado web application. The root page is \nclient.html (in this directory)\n\n\"\"\"\n\nclass Skeleton(INDIHandler):\n\n def get(self):\n\n self.indi_render(Path.cwd()/\"client.html\", device_name=\"SkeletonDevice\")\n\n\n\nwebport = 5905\nindiport = 7624\n\nwa = INDIWebApp( webport=webport )\nimgs = Path('./imgs')\nimgs.mkdir(exist_ok=True)\n\nprint(f\"go to http://:{webport}/\")\nprint(f\"If the server is on localhost go to:\")\nprint(f\"http://localhost:{webport}/\")\n\n\n# Build and start the application. \nwa.build_app(\n [(r\"/\", Skeleton),\n (r\"/imgs/(.*)\", tornado.web.StaticFileHandler, {\"path\": imgs})],\n debug=True)\n","sub_path":"example_clients/SkeletonClient.py","file_name":"SkeletonClient.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"438030854","text":"\nfrom unittest.mock import Mock, patch\nfrom formation.tests import mock\nfrom formation.tests.utils import PatchTranslationTestCase, django_only\n\nfrom formation import fields\n\nclass TestAddressField(PatchTranslationTestCase):\n\n def test_address_get_display_value(self):\n input_data = {\n 'address_street': '1 Main St.',\n 'address_city': 'Oakland',\n 'address_state': 'CA',\n 'address_zip': '94609',\n }\n expected_output = {\n 'street': '1 Main St.',\n 'city': 'Oakland',\n 'state': 'CA',\n 'zip': '94609'\n }\n expected_display = \"1 Main St.\\nOakland, CA\\n94609\"\n field = fields.AddressField(input_data)\n self.assertTrue(field.is_valid())\n self.assertDictEqual(field.get_current_value(), expected_output)\n self.assertEqual(field.get_display_value(), expected_display)","sub_path":"formation/tests/test_fields.py","file_name":"test_fields.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"398432620","text":"import shell\nimport os\nimport zipfile\n\ndef readBinaryFile(name):\n with open(name, 'rb') as f:\n return f.read()\n\ndef readFile(name):\n with open(name, 'r', encoding='utf-8') as f:\n return f.read()\n\ndef writeFile(name, content):\n with open(name, 'w', encoding='utf-8') as f:\n f.write(content)\n\ndef writeBinaryFile(name, content):\n with open(name, 'wb') as f:\n f.write(content)\n\ndef collectSubmissionDirs(config, baseDir=None, includeBoth=False):\n if baseDir is None:\n baseDir = config.baseDir\n dirs1 = shell.ls(baseDir, config.submissionDirGlob)\n dirs2 = []\n if includeBoth:\n dirs2 = shell.ls(config.baseDir, config.submissionDirTextGlob)\n result = [d for d in dirs1 + dirs2 if shell.isdir(d)]\n return sorted(result)\n\ndef collectSubmissionFiles(config, d):\n files = shell.ls(d, config.submissionFileGlob)\n expected = set(config.assignments)\n return sorted([f for f in files if shell.basename(f) in expected])\n\ndef findSubmissionDirForId(config, x):\n \"\"\"\n Returns the submission directory for a student with ID x.\n Prefers _file_ directory over _onlinetext_.\n \"\"\"\n dirs = [d for d in shell.ls(config.baseDir, f'*_{x}_*') if shell.isdir(d)]\n if len(dirs) == 0:\n return None\n for d in dirs:\n if d.endswith('_file_'):\n return d\n return dirs[0]\n\ndef stripSlashes(x):\n if not x:\n return x\n x = x.strip()\n if x.endswith('/'):\n return stripSlashes(x[:-1])\n else:\n return x\n\ndef hasSameContent(f1, f2):\n c1 = readBinaryFile(f1)\n c2 = readBinaryFile(f2)\n return c1 == c2\n\n# Copies srcDir/path to targetDir/path, but only if targetDir/path does not exist.\n# Outputs a warning if targetDir/path exists but is not identical to srcDir/path\ndef copyFileIfNotExists(srcDir, path, targetDir):\n srcPath = shell.pjoin(srcDir, path)\n if not shell.isFile(srcPath):\n raise IOError(f'{srcPath} must be a file')\n tgtPath = shell.pjoin(targetDir, path)\n if shell.isDir(tgtPath):\n raise IOError(f'{tgtPath} must not be a directory')\n shell.mkdir(shell.dirname(tgtPath), createParents=True)\n if shell.isFile(tgtPath):\n if not hasSameContent(srcPath, tgtPath):\n raise IOError(f'Target file {tgtPath} already exists with content different than in {srcPath}')\n else:\n shell.cp(srcPath, tgtPath)\n\ndef zipDirs(zipPath, dirs):\n zf = zipfile.ZipFile(zipPath, 'w', zipfile.ZIP_DEFLATED)\n for d in dirs:\n for root, dirs, files in os.walk(d):\n for f in files:\n zf.write(os.path.join(root, f), \n os.path.relpath(os.path.join(root, f), \n os.path.join(d, '..')))\n zf.close()","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"597531116","text":"# 이코테 92쪽\n\n'''\n다양한 수로 이루어진 배열이 있을 때 주어진 수들을 M 번 더하�� 가장 큰 수를 만드는 법칙\n특정 인덱스는 K번을 초과하여 다해질 수 없음\n\nN : 배열의 크기\nM : 숫자가 더해지는 횟수\nK : 각 인덱스당 더해질 수 있는 횟수 \n'''\n\n# 초기 값 셋팅\nN, M, K = map(int, input().split())\narray = list(map(int, input().split()))\nresult = 0\ncnt = 0\n\n# 첫 번째로 큰 값, 두 번째로 큰 값\narray.sort()\nfirst = array[N-1]\nsecond = array[N-2]\n\n# 첫 번째로 큰 값 * K + 두 번째로 큰 값 * 1 을 M번 반복\nwhile True:\n if M == 0:\n break\n if cnt < K:\n result += first\n cnt += 1\n else:\n result += second\n cnt = 0\n M -= 1\n\nprint(result)","sub_path":"이것이 취업을 위한 코딩테스트다 with 파이썬/1. 그리디 알고리즘/[092p - 2회독]큰 수의 법칙 - 그리디.py","file_name":"[092p - 2회독]큰 수의 법칙 - 그리디.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"608737498","text":"import pyodbc\nimport faker\n\n\n\n\n# 准备模拟数据\nfake = faker.Faker('zh_CN')\n# 设置种子值,不设的话每次随机的都不一样\n\n##fake.Faker.seed(47)\n\ndb_file_location = r'D:\\users\\基础链接表.mdb'\n# 这里用的是Python3.5的语法,如果是低版本Python的话需要改成普通方式\nconnection = pyodbc.connect(rf'Driver={{Microsoft Access Driver (*.mdb, *.accdb)}};DBQ={db_file_location};')\n\nconnection.autocommit = True\ncursor = connection.cursor()\nprint(\"====================完成数据库\" + db_file_location + \"连接======================\")\n# 第一次创建表,将其设置为False\n\nprint(\"====================开始创建表数据库连接======================\")\n# 第一次创建表,将其设置为False\n\n##create_table_sql = '''\\\n##create table user8\n##(\n## id autoincrement primary key,\n## username varchar(255) unique,\n## nickname varchar(255) not null,\n## password varchar(20) not null,\n## address varchar(255),\n## birthday date,\n## company varchar(30),\n## job varchar(20),\n## telephone varchar(14)\n##)\n##'''1000_RIC组装表\n\n\n### 修改数据库中int类型的值\n##value = 10\n##SQL = \"UPDATE goods \" \\\n## \"SET lowestStock=\" + str(value) + \" \" \\\n## \"WHERE goodsId='0005'\"\n## \n### 删除表users\n##crsr.execute(\"DROP TABLE users\")\n### 创建新表 users\n##crsr.execute('CREATE TABLE users (login VARCHAR(8),userid INT, projid INT)')\n### 给表中插入新数据\n##crsr.execute(\"INSERT INTO users VALUES('Linda',211,151)\")\n## \n##''''''\n### 更新数据\n##crsr.execute(\"UPDATE users SET projid=1 WHERE userid=211\")\n## \n### 删除行数据\n##crsr.execute(\"DELETE FROM goods WHERE goodNum='0001'\")\n## \n### 打印查询的结果\n##for row in crsr.execute(\"SELECT * from users\"):\n## print(row)\n##\n\n\n\n\n\n\nsql1 ='''\\\nDELETE FROM 1000REJCT汇总\n'''\ncursor.execute(sql1)\n\n\nprint(\"====================完成sql 1 ======================\")\n\n\nsqltemp ='''\\\nselect top 10 *\nfrom\n0000RIC组装表\n\n\n'''\n\n\n\n\nfor row in cursor.execute(sqltemp):\n print(row)\n\nprint(\"====================完成sql temp ======================\")\n\n\n\n##select_public_servant_sql = '''\\\n##INSERT INTO 1000_RIC组装表 ( CYLINDER, SCRNUM, SCRNO, RICNUM, ITEM, RIC_END, WASH_END_WEIGHT, COREROD, 表达式2, deltah1, deltah2, SCRETCHOD, LINK, SUBTYPE, DRAWLENGTH, REMARK, 表达式1, NEXTOUTDATE, addtime )\n##SELECT AAA_FISRICASSEMBLEPARA.CYLINDER, AAA_FISRICASSEMBLEPARA.SCRNUM, AAA_FISRICASSEMBLEPARA.SCRNO, AAA_FISRICASSEMBLEPARA.RICNUM, AAA_FISRICASSEMBLEPARA.ITEM, AAA_FISRICASSEMBLEPARA.RIC_END, AAA_TUBE.WASH_END_WEIGHT, AAA_FISSCRPARA.COREROD, Round([CYLINDERLENGTH],0) AS 表达式2, AAA_FISRICASSEMBLEPARA.DH AS deltah1, AAA_FISRICASSEMBLEPARA.CONELENGTH AS deltah2, AAA_FISRICASSEMBLEPARA.SCRETCHOD, Left([CYLINDER],8) AS LINK, AAA_FISRICASSEMBLEPARA.SUBTYPE, AAA_FISRICASSEMBLEPARA.DRAWLENGTH, AAA_FISRICASSEMBLEPARA.REMARK, Left([CYLINDER],8) AS 表达式1, AAA_FISRICASSEMBLEPARA.NEXTOUTDATE, Now() AS 表达式3\n##FROM AAA_FISSCRPARA RIGHT JOIN (AAA_FISRICASSEMBLEPARA LEFT JOIN AAA_TUBE ON AAA_FISRICASSEMBLEPARA.CYLINDER = AAA_TUBE.TUBE_ID) ON AAA_FISSCRPARA.SCRNUM = AAA_FISRICASSEMBLEPARA.SCRNO\n##WHERE (((AAA_FISRICASSEMBLEPARA.SCRNUM) Like \"*\") AND ((AAA_FISRICASSEMBLEPARA.RIC_END)>#6/1/2020#));\n\n\n\n\n##for row in cursor.execute(sql1):\n## print(row)\n\n\n\n##table_exists = False\n##if not table_exists:\n## with connection.cursor() as cursor:\n## cursor.execute(create_table_sql)\n## \n### 添加数据\n##with connection.cursor() as cursor:\n## for _ in range(3000):\n## cursor.execute(insert_table_sql, (fake.pystr(min_chars=6, max_chars=10),\n## fake.name(),\n## fake.password(length=10),\n## fake.address(),\n## fake.date_of_birth(minimum_age=0, maximum_age=120),\n## fake.company(),\n## fake.job(),\n## fake.phone_number()))\n##\n## # 查询一下所有公务员\n## cursor.execute(select_public_servant_sql)\n## results = cursor.fetchall()\n## for row in results:\n## print(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], sep='\\t')\ncursor.close\nconnection.close\n\nprint(\"====================关闭数据库,成功完成全部工作======================\")\n\n","sub_path":"access/在access建表-pyodbc-mdb-sct.py","file_name":"在access建表-pyodbc-mdb-sct.py","file_ext":"py","file_size_in_byte":4450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"306930163","text":"from collections import defaultdict\nfrom functools import partial\n\nfrom django import forms\n\nfrom dataworkspace.apps.datasets.constants import DataSetType\nfrom .models import Tag\n\n\nclass FilterWidget(forms.widgets.CheckboxSelectMultiple):\n template_name = 'datasets/filter.html'\n option_template_name = \"datasets/filter_option.html\"\n\n def __init__(\n self,\n group_label,\n hint_text=None,\n limit_initial_options=0,\n show_more_label=\"Show more\",\n *args,\n **kwargs, # pylint: disable=keyword-arg-before-vararg\n ):\n super().__init__(*args, **kwargs)\n self._group_label = group_label\n self._hint_text = hint_text\n self._limit_initial_options = limit_initial_options\n self._show_more_label = show_more_label\n\n def get_context(self, name, value, attrs):\n context = super().get_context(name, value, attrs)\n context['widget']['group_label'] = self._group_label\n context['widget']['hint_text'] = self._hint_text\n context['widget']['limit_initial_options'] = self._limit_initial_options\n context['widget']['show_more_label'] = self._show_more_label\n return context\n\n class Media:\n js = ('app-filter-show-more-v2.js',)\n\n\nclass SortSelectWidget(forms.widgets.Select):\n template_name = 'datasets/select.html'\n option_template_name = 'datasets/select_option.html'\n\n def __init__(\n self, label, *args, **kwargs, # pylint: disable=keyword-arg-before-vararg\n ):\n super().__init__(*args, **kwargs)\n self._label = label\n\n def get_context(self, name, value, attrs):\n context = super().get_context(name, value, attrs)\n context['widget']['label'] = self._label\n return context\n\n\nclass RequestAccessForm(forms.Form):\n email = forms.CharField(widget=forms.TextInput, required=True)\n goal = forms.CharField(widget=forms.Textarea, required=True)\n\n\nclass EligibilityCriteriaForm(forms.Form):\n meet_criteria = forms.TypedChoiceField(\n widget=forms.RadioSelect,\n coerce=lambda x: x == 'yes',\n choices=(('no', 'No'), ('yes', 'Yes')),\n )\n\n\nclass SourceTagField(forms.ModelMultipleChoiceField):\n def label_from_instance(self, obj):\n return obj.name\n\n\nclass DatasetSearchForm(forms.Form):\n q = forms.CharField(required=False)\n\n access = forms.MultipleChoiceField(\n choices=[('yes', 'You have access')],\n required=False,\n widget=FilterWidget(\"Access status\"),\n )\n\n unpublished = forms.MultipleChoiceField(\n choices=[('yes', 'Include unpublished')],\n required=False,\n widget=FilterWidget(\"Show unpublished\"),\n )\n\n use = forms.TypedMultipleChoiceField(\n choices=[\n (DataSetType.DATACUT.value, 'Download'),\n (DataSetType.MASTER.value, 'Analyse in tools'),\n (DataSetType.REFERENCE.value, 'Use as reference data'),\n (DataSetType.VISUALISATION.value, 'View data visualisation'),\n ],\n coerce=int,\n required=False,\n widget=FilterWidget(\"Purpose\", hint_text=\"What do you want to do with data?\"),\n )\n\n source = SourceTagField(\n queryset=Tag.objects.order_by('name').filter(type=Tag.TYPE_SOURCE),\n required=False,\n widget=FilterWidget(\n \"Source\",\n hint_text=\"Source or publishing organisation\",\n limit_initial_options=10,\n show_more_label=\"Show more sources\",\n ),\n )\n\n topic = SourceTagField(\n queryset=Tag.objects.order_by('name').filter(type=Tag.TYPE_TOPIC),\n required=False,\n widget=FilterWidget(\n \"Topics\", limit_initial_options=10, show_more_label=\"Show more topics\",\n ),\n )\n\n sort = forms.ChoiceField(\n required=False,\n choices=[\n ('-search_rank,name', 'Relevance'),\n ('-published_at', 'Date published: newest'),\n ('published_at', 'Date published: oldest'),\n ('name', 'Alphabetical (A-Z)'),\n ],\n widget=SortSelectWidget(label='Sort by'),\n )\n\n def clean_sort(self):\n data = self.cleaned_data['sort']\n if not data:\n data = '-search_rank,name'\n\n return data\n\n class Media:\n js = ('app-filter-show-more-v2.js',)\n\n def annotate_and_update_filters(\n self, datasets, matcher, number_of_matches, topic_flag_active\n ):\n counts = {\n \"access\": defaultdict(int),\n \"unpublished\": defaultdict(int),\n \"use\": defaultdict(int),\n \"source\": defaultdict(int),\n \"topic\": defaultdict(int),\n }\n\n selected_access = bool(self.cleaned_data['access'])\n selected_unpublished = bool(self.cleaned_data['unpublished'])\n selected_uses = set(self.cleaned_data['use'])\n selected_source_ids = set(source.id for source in self.cleaned_data['source'])\n selected_topic_ids = set(topic.id for topic in self.cleaned_data['topic'])\n\n # Cache these locally for performance. The source model choice field can end up hitting the DB each time.\n use_choices = list(self.fields['use'].choices)\n source_choices = list(self.fields['source'].choices)\n topic_choices = list(self.fields['topic'].choices)\n\n for dataset in datasets:\n dataset_matcher = partial(\n matcher,\n data=dataset,\n access=selected_access,\n unpublished=selected_unpublished,\n use=selected_uses,\n source_ids=selected_source_ids,\n topic_ids=selected_topic_ids,\n topic_flag_active=topic_flag_active,\n )\n\n if dataset_matcher(access=True):\n counts['access']['yes'] += 1\n\n if dataset_matcher(unpublished=True):\n counts['unpublished']['yes'] += 1\n\n for use_id, _ in use_choices:\n if dataset_matcher(use={use_id}):\n counts['use'][use_id] += 1\n\n for source_id, _ in source_choices:\n if dataset_matcher(source_ids={source_id}):\n counts['source'][source_id] += 1\n\n for topic_id, _ in topic_choices:\n if dataset_matcher(topic_ids={topic_id}):\n counts['topic'][topic_id] += 1\n\n self.fields['access'].choices = [\n (access_id, access_text + f\" ({counts['access'][access_id]})\")\n for access_id, access_text in self.fields['access'].choices\n ]\n\n self.fields['unpublished'].choices = [\n (unpub_id, unpub_text + f\" ({counts['unpublished'][unpub_id]})\")\n for unpub_id, unpub_text in self.fields['unpublished'].choices\n ]\n\n self.fields['use'].choices = [\n (use_id, use_text + f\" ({counts['use'][use_id]})\")\n for use_id, use_text in use_choices\n ]\n\n self.fields['source'].choices = [\n (source_id, source_text + f\" ({counts['source'][source_id]})\")\n for source_id, source_text in source_choices\n if source_id in selected_source_ids or counts['source'][source_id] != 0\n ]\n\n self.fields['topic'].choices = [\n (topic_id, topic_text + f\" ({counts['topic'][topic_id]})\")\n for topic_id, topic_text in topic_choices\n if topic_id in selected_topic_ids or counts['topic'][topic_id] != 0\n ]\n","sub_path":"dataworkspace/dataworkspace/apps/datasets/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":7459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"121965972","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport os,sys\nimport itertools\nfrom tqdm import tqdm\nimport pandas as pd\nfrom PIL import Image\nfrom sklearn import linear_model\nfrom sklearn import decomposition\nfrom sklearn import svm\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.model_selection import GridSearchCV, train_test_split\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom helpers import *\nfrom extract_features import *\nfrom sklearn.externals import joblib\n\ndef pca_decomposition(X_train,X_test):\n \"\"\"\n PCA decomposition performed on X_train data.\n Once model found with least significant features, transform X_test data as well.\n \"\"\"\n X_train=standardize(X_train)\n X_test=np.asarray([standardize(x) for x in X_test])\n pca=decomposition.PCA()\n pca.fit(X_train)\n id=np.argmax(np.cumsum(pca.explained_variance_ratio_)[np.cumsum(pca.explained_variance_ratio_)<0.90]) # find number of components\n pca=decomposition.PCA(n_components=id)\n X_pca=pca.fit_transform(X_train)\n X_pca=standardize(X_pca)\n X_test_pca=np.asarray([standardize(pca.transform(x)) for x in X_test])\n return X_pca, X_test_pca\n\nif __name__==\"__main__\":\n ####### Decision boolean #######\n trained=False\n logistic=False\n features = False\n test_features = False\n\n ####### Use of pretrained model ########\n if(len(sys.argv)>1):\n if(sys.argv[1]==\"trained\"):\n trained=True\n if(sys.argv[1]==\"features\"):\n features=True\n if(sys.argv[1]==\"test_features\"):\n features=True\n test_features=True\n \n ####### Load train and gt images ########\n print(\"Loading images...\")\n # Loaded a set of images\n root_dir = \"dataset/training/\"\n\n image_dir = root_dir + \"images/\"\n files = os.listdir(image_dir)\n n = min(100, len(files))\n imgs = [load_image(image_dir + files[i]) for i in tqdm(range(n))]\n\n gt_dir = root_dir + \"groundtruth/\"\n gt_imgs = [load_image(gt_dir + files[i]) for i in tqdm(range(n))]\n\n ###### Load test images #######\n test_dir = \"dataset/test_set_images/\"\n dirs = os.listdir(test_dir)\n if(len(sys.argv)>2):\n n_test=min(int(sys.argv[2]), len(dirs))\n else:\n n_test=min(50, len(dirs))\n \n imgs_test = [load_image(test_dir+dirs[i]+\"/\"+dirs[i]+\".png\") for i in tqdm(range(n_test))]\n \n if(not features):\n ###### Get patches for all images ######\n print(\"Patching the images\")\n patches_img=np.asarray([img_patches(imgs[i]) for i in range(len(imgs))])\n patches_img=patches_img.reshape((len(imgs)*patches_img.shape[1]**2,)+patches_img[0,0,0,0].shape)\n patches_glcm=np.asarray([img_patches(imgs[i],gray=True) for i in range(len(imgs))])\n patches_glcm=patches_glcm.reshape((len(imgs)*patches_glcm.shape[1]**2,)+patches_glcm[0,0,0].shape)\n patches_gt=np.asarray([img_patches(gt_imgs[i]) for i in range(len(imgs))])\n patches_gt=patches_gt.reshape((len(imgs)*patches_gt.shape[1]**2,)+patches_gt[0,0,0].shape)\n\n patches_img_test=np.asarray([img_patches(imgs_test[i]) for i in range(len(imgs_test))])\n patches_img_test=patches_img_test.reshape((\n len(imgs_test),patches_img_test.shape[1]*patches_img_test.shape[2])+patches_img_test[0,0,0,0].shape)\n patches_glcm_test=np.asarray([img_patches(imgs_test[i],gray=True) for i in range(len(imgs_test))])\n patches_glcm_test=patches_glcm_test.reshape((\n len(imgs_test),patches_glcm_test.shape[1]*patches_glcm_test.shape[2])+patches_glcm_test[0,0,0].shape)\n if not features:\n ##### Get feature vector and label vector #####\n print(\"Finding training feature\")\n X=np.asarray([extract_features_ngbr(patches_img,patches_glcm,i) for i in tqdm(range(len(imgs)*(imgs[0].shape[0]//WINDOW)**2))])\n np.savetxt(\"feature_all_patches.txt\",X,fmt='%.10e') # Save all features in file\n print(\"Finding Testing feature\")\n if not test_features:\n X_test=np.asarray([np.asarray([extract_features_ngbr(patches_img_test[i],patches_glcm_test[i],j,True) \n for j in tqdm(range((imgs_test[i].shape[0]//WINDOW)**2))]) for i in tqdm(range(patches_img_test.shape[0]))])\n else:\n X_test=pd.read_csv(\"feature_test_all_patches.txt\", delimiter=' ', header=None, dtype=np.float).as_matrix()\n X_test=X_test.reshape((50,-1,145))\n #X_test=np.asarray([extract_features_ngbr(patches_img_test,patches_glcm_test,i+10+2*imgs[0].shape[0]//WINDOW) for i in tqdm(range(len(imgs)*(imgs_test[0].shape[0]//WINDOW)**2))])\n Y=np.asarray([extract_label(patches_gt[i+2]) for i in tqdm(range(len(gt_imgs)*(imgs[0].shape[0]//WINDOW)**2))])\n if(features):\n # if use pretrained info, get already acquired features\n X=pd.read_csv(\"feature_all_patches.txt\", delimiter=' ', header=None, dtype=np.float).as_matrix()\n \n ##### PCA #####\n print(\"Running PCA\")\n X_pca,X_test_pca=pca_decomposition(X,X_test)\n \n ##### SVM ####\n if(not trained):\n print(\"splitting data in training and testing set\")\n X_train, X_test, Y_train, Y_test = train_test_split(X_pca, Y, test_size=0.25, random_state=42)\n print(\"Carrying grid search on hyperparameter, using cross-validation\")\n param_grid = {'C': [1e3, 1e4, 1e5, 1e6],\n 'gamma': [0.0001, 0.001, 0.01, 0.1], }\n clf = GridSearchCV(svm.SVC(kernel='rbf', class_weight='balanced',verbose=True), param_grid, cv=4,verbose=100,iid=False,n_jobs=8)\n clf = clf.fit(X_train,Y_train)\n Y_pred = clf.predict(X_test)\n print(classification_report(Y_test, Y_pred, labels=range(2)))\n with open('svm_model.pkl','wb') as saved_model:\n print(\"saving model\")\n joblib.dump(clf,saved_model)\n if(trained):\n with open('svm_model.pkl','rb') as saved_model:\n print(\"retrieving model\")\n clf=joblib.load(saved_model)\n \n ##### Estimating result on test set #####\n Z = [clf.predict(x) for x in X_test_pca]\n masks=[label_to_img(img.shape[0],img.shape[1],Z[i]) for i,img in enumerate(imgs_test)]\n mask_to_submission(\"submission.csv\",masks)\n \n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":6197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"462426499","text":"import os\nimport sys\nsys.path.append('../auxiliary')\nimport node_info as info\n\n\ndef create_table(tablename):\n file = open(tablename, 'w')\n head = 'Model;Weight type;Dataset;Batch size;Mode;Parameters;Infrastructure;Average time of single pass (s);Latency;FPS;'\n file.write(head + '\\n')\n file.close()\n\n\ndef add_row_to_table(tablename, row):\n file = open(tablename, 'a')\n file.write(row + '\\n')\n file.close()\n\n\ndef create_table_row(model, dataset, param, average_time, latency, fps):\n hardware = info.get_system_characteristics()\n hardware_info = ''\n for key in hardware:\n hardware_info += '{}: {}, '.format(key, hardware[key])\n hardware_info = hardware_info[:-2]\n other_param = 'Plugin: {}, Async request count: {}, Iteration count: {}, Thread count: {}, Min inference time (s): {}'.format(param.plugin,\n param.async_request, param.iteration, param.nthreads, param.min_inference_time)\n table_row = '{};{};{};{};{};{};{};{};{};{};'.format(model.name, model.datatype,\n dataset.name, param.batch_size, param.mode, other_param, hardware_info,\n average_time, latency, fps)\n return table_row","sub_path":"src/benchmark/output.py","file_name":"output.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"372870329","text":"import os\nfrom flask import Flask\nfrom app.config import DevelopmentConfig, ProductionConfig\nfrom flask_migrate import Migrate\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_restplus import Api, Resource\n\napp = Flask(__name__)\n\n\n# Setup the app with the config.py file\nENV = os.environ.get('ENV')\nif ENV == 'prod':\n app.config.from_object(ProductionConfig)\nelse:\n app.config.from_object(DevelopmentConfig)\n\n\n# Setup SQLAlchemy and migrations\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\n\n\n# Setup Flask Restplus\napi = Api(\n app,\n version='1.0',\n title='Hello API',\n description='Hello API',\n)\n\n\n# Import Models\nfrom app.modules.hello import UserModel # noqa\n\n\n# Import API Namespaces\nfrom app.modules.hello import UserNamespace # noqa\n\n\n# Healthcheck\n@api.route('/healthz', doc=False)\nclass HealthCheck(Resource):\n @api.response(200, 'OK')\n def get(self):\n version = os.getenv(\"VERSION\", \"No version\")\n return version, 200\n","sub_path":"app/app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"261415165","text":"import re\nimport json\nimport sys\nimport os\n\nargs = sys.argv\nif (len(args) < 2):\n sys.exit(1)\n\npath = args[1]\nif(path[-1:] == \"/\"):\n path = path[:-1]\n\nresult_filedata_list = []\n\ndef mode_setting(modestr):\n ownerset = modestr[1:4].replace('-','')\n groupset = modestr[4:7].replace('-','')\n etcset = modestr[7:10].replace('-','')\n mode_set = 'u=' + ownerset + ',g=' + groupset + ',o=' + etcset\n return mode_set\n\ncount = 0\nwhile True:\n # Decectory exist check\n dirpath = path + '/command/' + str(count)\n if os.path.isdir(dirpath):\n count +=1\n else:\n break\n\n filepath = dirpath + '/stdout.txt'\n set_path = ''\n if os.path.isfile(filepath):\n with open(filepath) as file_object:\n lines = file_object.readlines()\n for line in lines:\n filedata_table = {}\n params = line.split()\n if len(params) > 1:\n check_str = params[0]\n # total or 合計 skip\n if check_str == 'total' or check_str == '合計': \n continue\n # file link other skip\n if check_str[0] != '-' and check_str[0] != 'l':\n continue\n\n # state setting\n filedata_table['action'] = 'file'\n # mode setting\n mode_set = mode_setting(check_str)\n filedata_table['mode'] = mode_set\n # owner,group setting\n filedata_table['owner'] = params[2]\n filedata_table['group'] = params[3]\n # file path setting\n if set_path != '':\n filedata_table['file_path'] = set_path + '/' + params[7]\n else:\n filedata_table['file_path'] = params[7]\n # symbolic_link setting\n if check_str[0] == 'l':\n filedata_table['symbolic_link'] = params[9]\n result_filedata_list.append(filedata_table)\n elif len(params) == 1:\n set_path = params[0].rstrip(':')\n\nresult = {}\ntarget_parameter_root_key = 'VAR_RH_file_access'\nresult[target_parameter_root_key] = result_filedata_list\nprint(json.dumps(result))\n","sub_path":"RH_file_access/OS_gathering/files/extracting.py","file_name":"extracting.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"548210438","text":"# -*- coding: utf-8 -*-\n\nimport requests\nimport sys\nfrom slack_sdk import WebClient\nfrom slack_sdk.errors import SlackApiError\nfrom slack_api_token import SLACK_BOT_USER_OAUTH_TOKEN, SLACK_USER_OAUTH_TOKEN\n\n\ndef SendMessage(text: str):\n \"\"\"\n 引数のテキストをターゲットのチャンネルに投稿する関数。\n \"\"\"\n client = WebClient(token=SLACK_BOT_USER_OAUTH_TOKEN)\n try:\n response = client.chat_postMessage(\n channel='#times_sober-wizard',\n text=text\n )\n except SlackApiError as e:\n print(\"Got an Error : \", e)\n\n\ndef CheckMessage(text: str) -> bool:\n \"\"\"\n テキストが文頭に [/memo] という文字列を含む時にだけNLPする\n \"\"\"\n key_str = \"[/memo]\"\n length = len(text)\n\n if key_str in text:\n return True\n else:\n return False\n","sub_path":"butler_local.py","file_name":"butler_local.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"73141282","text":"from django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.conf.urls import url\nfrom .views import RegisterUserView\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.welcome, name='welcome'),\n url(r'^register$', view=RegisterUserView.as_view(), name='register'),\n url(r'^index/$', views.chat, name='index'),\n url(r'^home/$', views.welcome, name='welcome'),\n url(r'^detail/(?P\\d+)', views.detail, name='detail'),\n url(r'^search', views.search_results, name='search_results'),\n url(r'^new/image/$', views.new_image, name='new-image'),\n url(r'^profile/$', views.profile, name='profile'),\n url(r'^edit/$', views.edit, name='edit'),\n url(r'^new_business/$', views.new_business, name='new_business'),\n url(r'^business/details$', views.business_details, name='business_details'),\n url(r'^businesses/$', views.businesses, name='businesses'),\n url(r'^new_neighbourhood/$', views.new_neighbourhood, name='new_neighbourhood'),\n url(r'^neighbourhooders/$', views.neighbourhoods, name='neighbourhoods'),\n url(r'^contacts/$', views.chat, name='contacts'),\n url(r'^social_details/$', views.social_details, name='social'),\n url(r'^join/(\\d+)', views.join, name='joinHood'),\n url(r'^exitHood/(\\d+)', views.exitHood, name='exitHood'),\n url(r'^the_real_home/$', views.posts, name='yes'),\n # url(r'^chatty/$', views.chatty, name='chatty'),\n url(r'^lipapesa/$', views.error, name='home'),\n]\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"hood/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"565769854","text":"import sys\nsys.path.append('/home/pi/Desktop/Code/Labs')\nimport RPi.GPIO as GPIO \nimport time\nfrom gpio import lcd as lcd\n\nD4 = 4\nD5 = 5\nD6 = 6\nD7 = 0\nRS = 11\nEN = 10\n\nBUTTON = 21\n\nmsbit = 0x00 # Used for 4-bit interfacing\ncounter = 0 # Global counter\npush_flag = 0\ntime_stamp = time.time()\n\ndef ISR(pin):\n global counter\n global push_flag\n global time_stamp\n \n time_now = time.time()\n \n if pin == BUTTON and not push_flag and (time_now - time_stamp) >= 0.10: # check if button pin generated interrupt\n push_flag = 1\n counter = counter + 1\n lcd.lcd_clear()\n lcd.lcd_message(str(counter))\n push_flag = 0\n \n time_stamp = time_now\n \ndef main():\n GPIO.setwarnings(False)\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(BUTTON,GPIO.IN)\n \n global counter\n \n lcd.lcd_begin(D4,D5,D6,D7,RS,EN)\n lcd.send_cmd(0x0C)\n lcd.lcd_message(str(counter))\n GPIO.add_event_detect(BUTTON, GPIO.FALLING,ISR) # Setup interrupt to button pin, H->L, ISR, debounce time\n \n while True:\n time.sleep(1)\n \n \n \n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"Lab2/P3.py","file_name":"P3.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"126064585","text":"import time\n\nimport pkg_resources\nfrom PyQt5.QtCore import QBasicTimer, QRect, Qt, QTimer\nfrom PyQt5.QtGui import QImage, QPainter\nfrom PyQt5.QtWidgets import QHBoxLayout\n\nfrom components.Widgets import Widgets\n\n\nclass Swiper(Widgets):\n\n def __init__(self, parent=None, router=None):\n super().__init__(parent)\n img1 = QImage(pkg_resources.resource_filename(\n 'ecsdesktop.images', 'img1.jpg'))\n img2 = QImage(pkg_resources.resource_filename(\n 'ecsdesktop.images', 'img2.jpg'))\n img3 = QImage(pkg_resources.resource_filename(\n 'ecsdesktop.images', 'img3.jpg'))\n img4 = QImage(pkg_resources.resource_filename(\n 'ecsdesktop.images', 'img4.jpg'))\n img5 = QImage(pkg_resources.resource_filename(\n 'ecsdesktop.images', 'img5.jpg'))\n self.imglist = [img1, img2, img3, img4, img5]\n self.imglen = len(self.imglist)\n self.timer = QBasicTimer()\n self.timer.start(300, self)\n self.checkImgTimer = QBasicTimer()\n self.checkImgTimer.start(3000, self)\n self.opacity = 1\n self.imgIndex = 0\n self.nextImgIndex = 1\n self.router = router\n with open(pkg_resources.resource_filename(\n 'ecsdesktop.qss', 'media.qss'), 'r') as f:\n self.setStyleSheet(f.read())\n\n def checkImg(self):\n self.imgIndex = self.imgIndex + 1\n if self.imgIndex == self.imglen:\n self.imgIndex = 0\n\n self.nextImgIndex = self.imgIndex + 1\n if self.nextImgIndex == self.imglen:\n self.nextImgIndex = 0\n self.repaint()\n\n def paintEvent(self, e):\n self.qp = QPainter()\n self.qp.begin(self)\n self.drawBezier()\n self.qp.end()\n\n def mouseReleaseEvent(self, QMouseEvent):\n if QMouseEvent.button() == Qt.LeftButton:\n self.router.push('home')\n\n def timerEvent(self, e):\n # 转换为整数 解决 精度问题\n if self.timer.timerId() == e.timerId():\n self.opacity = (self.opacity * 10 - 0.1 * 10)/10\n if self.opacity < 0.5:\n self.opacity = 1\n self.timer.stop()\n self.checkImg()\n\n elif self.checkImgTimer.timerId() == e.timerId():\n self.timer.start(300, self)\n\n self.repaint()\n\n def drawBezier(self):\n QPainter.setOpacity(self.qp, self.opacity)\n rect = QRect(0, 0, self.size().width(), self.size().height())\n QPainter.drawImage(self.qp, rect, self.imglist[self.nextImgIndex])\n QPainter.drawImage(self.qp, rect, self.imglist[self.imgIndex])\n","sub_path":"内蒙古千斤鼎电子商务有限公司/ecs-desktop/ecsdesktop/widgets/swiper.py","file_name":"swiper.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"515756752","text":"import hashlib\nimport os\nimport sys\nfrom random import randrange\nfrom myTools import *\n\n# Example input\n# DSA.py -keygen 160 dsa_privatekey.pem dsa_publickey.pem\n# DSA.py -sign dsa_privatekey.pem dsa_publickey.pem doc.txt doc.sig\n# DSA.py -verify dsa_publickey.pem doc.txt doc.sig\n\n\nhelp_message = '''\nUsage:\tRSA.py COMMAND\n\nCommand:\n -keygen [] []\n -sign []\n -verify \n -help\n \n * bit-length only support 160 bits.\n'''\nbit_len = 160\np_len = 1024\n\n\ndef keygen():\n # Generate p, q\n while True:\n q = randrange(2 ** (bit_len-1), 2 ** bit_len)\n if miller_rabin(q):\n break\n while True:\n padding = randrange(2 ** (p_len - bit_len - 1) - 1, 2 ** (p_len - bit_len))\n p = q * padding + 1\n if miller_rabin(p):\n break\n\n # Generate a\n h = 2\n exponent = (p - 1) // q\n while True:\n a = square_and_multiply(h, exponent, p)\n if p > 1:\n break\n h = h + 1\n\n # Generate d, b\n d = randrange(1, q)\n b = square_and_multiply(a, d, p)\n\n return p, q, a, b, d\n\n\ndef read_publickey(file_name):\n file = open(file_name, 'r')\n p = q = a = b = 0\n while True:\n key = file.readline().replace('\\n', '')\n if key == '-----BEGIN PUBLIC KEY-----':\n p = int(file.readline().replace('\\n', ''), 16)\n q = int(file.readline().replace('\\n', ''), 16)\n a = int(file.readline().replace('\\n', ''), 16)\n b = int(file.readline().replace('\\n', ''), 16)\n elif key == '-----END PUBLIC KEY-----':\n file.close()\n break\n return p, q, a, b\n\n\ndef read_privatekey(file_name):\n file = open(file_name, 'r')\n d = 0\n while True:\n key = file.readline().replace('\\n', '')\n if key == '-----BEGIN DSA PRIVATE KEY-----':\n d = int(file.readline().replace('\\n', ''), 16)\n elif key == '-----END DSA PRIVATE KEY-----':\n file.close()\n break\n return d\n\n\ndef read_signature(file_name):\n file = open(file_name, 'r')\n r = s = 0\n while True:\n key = file.readline().replace('\\n', '')\n if key == '-----BEGIN SIGNATURE-----':\n r = int(file.readline().replace('\\n', ''), 16)\n s = int(file.readline().replace('\\n', ''), 16)\n elif key == '-----END SIGNATURE-----':\n file.close()\n break\n return r, s\n\n\ndef write_publickey(file_name, p, q, a, b):\n publickey_file = open(file_name, 'w+')\n publickey_file.write('-----BEGIN PUBLIC KEY-----' + '\\n')\n publickey_file.write(hex(p)[2:] + '\\n')\n publickey_file.write(hex(q)[2:] + '\\n')\n publickey_file.write(hex(a)[2:] + '\\n')\n publickey_file.write(hex(b)[2:] + '\\n')\n publickey_file.write('-----END PUBLIC KEY-----' + '\\n')\n publickey_file.close()\n\n\ndef write_privatekey(file_name, d):\n privatekey_file = open(file_name, 'w+')\n privatekey_file.write('-----BEGIN DSA PRIVATE KEY-----' + '\\n')\n privatekey_file.write(hex(d)[2:] + '\\n')\n privatekey_file.write('-----END DSA PRIVATE KEY-----' + '\\n')\n privatekey_file.close()\n\n\ndef write_signature(file_name, r, s):\n signature_file = open(file_name, 'w+')\n signature_file.write('-----BEGIN SIGNATURE-----' + '\\n')\n signature_file.write(hex(r)[2:] + '\\n')\n signature_file.write(hex(s)[2:] + '\\n')\n signature_file.write('-----END SIGNATURE-----' + '\\n')\n signature_file.close()\n\n\ndef main():\n # Argv error handling\n if len(sys.argv) <= 1:\n raise Exception(help_message)\n\n if sys.argv[1] == '-keygen':\n # Error Handling\n if len(sys.argv) < 3:\n raise Exception(help_message)\n if int(sys.argv[2]) != bit_len:\n raise Exception('bit-length only support 160 bits.')\n\n privatekey_name = 'dsa_privatekey.pem'\n publickey_name = 'dsa_publickey.pem'\n\n try:\n privatekey_name = sys.argv[3]\n publickey_name = sys.argv[4]\n except IndexError:\n pass\n\n # Key Generate\n p, q, a, b, d = keygen()\n\n # Write into files\n write_publickey(publickey_name, p, q, a, b)\n write_privatekey(privatekey_name, d)\n\n elif sys.argv[1] == '-sign':\n # Error Handling\n if len(sys.argv) < 5:\n raise Exception(help_message)\n d = read_privatekey(sys.argv[2])\n p, q, a, b = read_publickey(sys.argv[3])\n message_file = open(sys.argv[4], 'r')\n signature_name = os.path.splitext(message_file.name)[0] + '.sig'\n try:\n signature_name = sys.argv[5]\n except IndexError:\n pass\n\n # Compute hashed message\n sha = hashlib.sha1()\n message = message_file.read().encode('utf-8')\n sha.update(message)\n hash_message = sha.hexdigest()\n\n # Generate ke, r, s\n ke = randrange(1, q)\n r = square_and_multiply(a, ke, p) % q\n s1 = (int(hash_message, 16) + d * r) % q\n s2 = modinv(ke, q) % q\n s = (s1 * s2) % q\n\n # Write into files\n write_signature(signature_name, r, s)\n\n elif sys.argv[1] == '-verify':\n # Error Handling\n if len(sys.argv) < 5:\n raise Exception(help_message)\n p, q, a, b = read_publickey(sys.argv[2])\n message_file = open(sys.argv[3], 'r')\n r, s = read_signature(sys.argv[4])\n\n # Compute hashed message\n sha = hashlib.sha1()\n message = message_file.read().encode('utf-8')\n sha.update(message)\n hash_message = sha.hexdigest()\n\n # Generate w, v\n w = modinv(s, q)\n v1 = square_and_multiply(a, (w * int(hash_message, 16)) % q, p)\n v2 = square_and_multiply(b, (w * r) % q, p)\n v = ((v1 * v2) % p) % q\n\n if r == v:\n print('Verified OK')\n else:\n print('Verification Failure')\n\n elif sys.argv[1] == '-help':\n print(help_message)\n else:\n raise Exception(help_message)\n\n exit()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"hw5/DSA.py","file_name":"DSA.py","file_ext":"py","file_size_in_byte":6171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"365465610","text":"from typing import List\nfrom fastapi import Depends, FastAPI, HTTPException\nfrom sqlalchemy.orm import Session\nimport models, schemas, crud\nfrom database import engine, SessionLocal\n\n\n\napp = FastAPI()\nmodels.Base.metadata.create_all(bind=engine)\n\n\n# Dependency\ndef get_db():\n try:\n db = SessionLocal()\n yield db\n finally:\n db.close()\n\n\n@app.get(\"/\")\ndef home():\n return {\"message\":\"Authentication\"}\n\n@app.post(\"/users/\", response_model=schemas.User)\ndef create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):\n db_user = crud.get_user(db, user_name=user.username)\n if db_user:\n raise HTTPException(status_code=400, detail=\"username already registered\")\n return crud.create_user(db=db, user=user)\n\n","sub_path":"core/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"553939725","text":"from graphene import Mutation, Field, Int\nfrom graphql import GraphQLError\n\n\nfrom .type import GodParentType, GodParentInput\nfrom ..employe.helper import serializerEmployee\nfrom ..error.employeeException import EmailAlreadyExistException\nfrom ..models import GodParent\nfrom ..serializers.serializer import GodParentSerializer\n\n\nclass CreateGodParent(Mutation):\n godparent = Field(GodParentType)\n\n class Arguments:\n godparent = GodParentInput()\n\n def mutate(self, info, **args):\n user = info.context.user\n if user.is_anonymous:\n raise GraphQLError(\"Log in to add a GodParent!\")\n print(args.get('godparent'))\n godparent = GodParent(**args.get('godparent'))\n serializer = serializerEmployee(data=godparent, modelSerializer=GodParentSerializer)\n if serializer.is_valid(raise_exception=True):\n godparents = GodParent.objects.filter(email__icontains=godparent.email)\n if len(list(godparents)):\n raise EmailAlreadyExistException(godparent.email)\n godparent.save()\n return CreateGodParent(godparent=godparent)\n\n\nclass UpdateGodParent(Mutation):\n godparent = Field(GodParentType)\n\n class Arguments:\n godparent_id = Int(required=True)\n godparent = GodParentInput()\n\n def mutate(self, info, **args):\n user = info.context.user\n if user.is_anonymous:\n raise GraphQLError(\"Log in to update a GodParent!\")\n print(\"-----------\")\n print(args.get('godparent_id'))\n old_godparent = GodParent.objects.get(id=args.get('godparent_id'))\n print(old_godparent)\n print('------------')\n print(args.get('godparent'))\n old_godparent.__dict__.update(args.get('godparent'))\n email = old_godparent.email\n godparents = GodParent.objects.filter(email__icontains=old_godparent.email)\n serializer = serializerEmployee(data=old_godparent, modelSerializer=GodParentSerializer)\n if serializer.is_valid(raise_exception=True):\n if old_godparent.email != email and len(list(godparents)):\n raise EmailAlreadyExistException(old_godparent.email)\n old_godparent.save()\n return UpdateGodParent(godparent=old_godparent)\n\n\nclass DeleteGodParent(Mutation):\n godparent_id = Int()\n\n class Arguments:\n godparent_id = Int(required=True)\n\n def mutate(self, info, godparent_id):\n user = info.context.user\n if user.is_anonymous:\n raise GraphQLError(\"Log in to delete a GodParent!\")\n godparent = GodParent.objects.get(id=godparent_id)\n godparent.delete()\n return DeleteGodParent(godparent_id=godparent_id)\n","sub_path":"dmdbBaseManagement/godParent/mutation.py","file_name":"mutation.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"442910383","text":"import math\n\na = 4\nb = 13\nc = 15\n\n# Ploščino bomo izračunali s pomočjo Heronovega obrazca\ns = (a + b + c) / 2\nploscina1 = math.sqrt(s * (s - a) * (s - b) * (s - c))\nploscina2 = (s * (s - a) * (s - b) * (s - c)) ** (1 / 2)\n","sub_path":"datoteke-s-predavanj/2018-19/01-uvod-v-python/trikotnik.py","file_name":"trikotnik.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"633091605","text":"import argparse\nimport os\n\nimport cv2\nimport numpy as np\nimport torch\nfrom torch.autograd import Variable\n\nimport config\nfrom calc_mean import calc_mean\nfrom modules.model import build_ssd\n\ncfg, temp = config.get_config()\nnow_path = os.getcwd()\n\nCOLOR_PRED = (0, 0, 255)\nCOLOR_TRUTH = (0, 255, 0)\nFONT = cv2.FONT_HERSHEY_SIMPLEX\nlabelmap = ['person']\n\n\ndef plot_pred_rect(net, img, transform):\n height, width = img.shape[:2]\n # to rgb\n img_x = img[:, :, (2, 1, 0)]\n img_x = torch.from_numpy(transform(img_x)[0]).permute(2, 0, 1)\n\n temp = Variable(img_x.unsqueeze(0))\n\n temp = Variable(temp.cuda())\n y = net(temp, 'test')\n detections = y.data\n\n scale = torch.Tensor([width, height, width, height])\n\n for i in range(detections.size(1)):\n j = 0\n while detections[0, i, j, 0] >= 0.60:\n print(detections[0, i, j, 0])\n pt = (detections[0, i, j, 1:] * scale).cpu().numpy()\n cv2.rectangle(img,\n (int(pt[0]), int(pt[1])),\n (int(pt[2]), int(pt[3])),\n COLOR_PRED, 2)\n cv2.putText(img, labelmap[i - 1], (int(pt[0]), int(pt[1])),\n FONT, 1, COLOR_PRED, 2, cv2.LINE_AA)\n j += 1\n\n return img\n\n\ndef base_transform(image, size, mean):\n x = cv2.resize(image, (size, size)).astype(np.float32)\n x -= mean\n x = x.astype(np.float32)\n return x\n\n\nclass BaseTransform:\n def __init__(self, size, mean):\n self.size = size\n self.mean = np.array(mean, dtype=np.float32)\n\n def __call__(self, image, boxes=None, labels=None):\n return base_transform(image, self.size, self.mean), boxes, labels\n\n\ndef visible_pred(image_file, net):\n image_list = os.listdir(image_file)\n mean = calc_mean(image_file)\n\n for i in range(len(image_list)):\n img = cv2.imread(image_file + '/' + image_list[i])\n transform = BaseTransform(net.size, mean)\n\n image_plot = plot_pred_rect(net, img, transform)\n\n pic_file = now_path + '/visible_test/'\n cv2.imwrite(pic_file + 'test_' + str(i + 1) + '.png', image_plot)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='test')\n parser.add_argument(\"--model\", default=now_path + '/ckpt/',\n type=str, help='Trained state_dict file path')\n parser.add_argument('--cuda', default=True, type=bool, help='Use cuda in live demo')\n args = parser.parse_args()\n\n net = build_ssd()\n models_list = os.listdir(args.model)\n if models_list != []:\n model_last = args.model + models_list[len(models_list) - 1]\n add = os.listdir(model_last)[0]\n print(model_last + '/' + add)\n trained_model = torch.load(model_last + '/' + add)\n\n # load variables from checkpoint\n net.load_state_dict(trained_model['model_state'], strict=True)\n net.cuda()\n net.eval()\n\n test_img = '/home/yzh/ssd_head_detector/test_image/'\n visible_pred(test_img, net)\n","sub_path":"demo/visible_test_pred.py","file_name":"visible_test_pred.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"314604055","text":"from nclib import *\r\nimport base64\r\nfrom math import *\r\n\r\n\r\n# Took from SO\r\ndef egcd(a, b):\r\n if a == 0:\r\n return (b, 0, 1)\r\n g, y, x = egcd(b%a,a)\r\n return (g, x - (b//a) * y, y)\r\n\r\ndef modinv(a, m):\r\n g, x, y = egcd(a, m)\r\n if g != 1:\r\n raise Exception('No modular inverse')\r\n return x%m\r\n\r\n\r\nHOSTNAME = \"18.179.251.168\"\r\nPORT = 21700\r\n\r\ndef saferecv():\r\n out = ''\r\n chr = ' '\r\n while chr != '\\n':\r\n chr = nc.recv_exactly(1).decode()\r\n if chr != '\\n':\r\n out += chr\r\n return out.encode()\r\n\r\ndef sendA(number):\r\n nc.recv_exactly(5)\r\n nc.send_line(b'A')\r\n nc.recv_exactly(7)\r\n string = hex(number)[2:]\r\n if len(string) % 2 == 1:\r\n string = '0' + string\r\n nc.send_line(string.encode())\r\n #print(string.encode())\r\n string = saferecv()\r\n #print(string)\r\n return int(string, 16)\r\n \r\ndef sendB(number):\r\n nc.recv_exactly(5)\r\n nc.send_line(b'B')\r\n nc.recv_exactly(7)\r\n string = hex(number)[2:]\r\n if len(string) % 2 == 1:\r\n string = '0' + string\r\n nc.send_line(string.encode())\r\n string = saferecv()\r\n #print(string)\r\n return int(string, 16)\r\n\r\nnc = Netcat((HOSTNAME, PORT))\r\nprint(nc.recv_exactly(18))\r\n\r\nflag = int(saferecv(), 16)\r\n\r\nN = 0\r\nfor i in range(10):\r\n k = i*7 + 3\r\n a1 = sendA(k)\r\n a2 = sendA(k*k)\r\n N = gcd(N, a1*a1 - a2)\r\n \r\nprint(N)\r\n\r\nsflag = \"\"\r\nvflag = 0\r\n\r\nfor i in range(65):\r\n potinv = modinv(2**(8*i), N)\r\n enck = sendA(potinv)\r\n print(potinv)\r\n print((potinv * (2**(8*i))) % N)\r\n msg = sendB(enck * flag)\r\n msg = (msg - (potinv * vflag) % N) % 256\r\n print(msg)\r\n vflag += msg * 2**(8*i)\r\n sflag = chr(msg) + sflag\r\n print(sflag)","sub_path":"hitcon/lostkey/lostkeysolve.py","file_name":"lostkeysolve.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"352078112","text":"# coding=utf-8\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\ntry:\n # noinspection PyUnresolvedReferences\n from typing import Any, Callable, Dict, List, Optional, Text, Type\nexcept ImportError:\n pass\n\nfrom django.core.files.base import ContentFile\nfrom django.http import HttpResponse, HttpRequest\nfrom django.template import loader\nfrom django.utils.http import urlquote\nfrom io import BytesIO\nfrom weasyprint import CSS, HTML, default_url_fetcher\n\n__all__ = [\n 'html_to_pdf', 'encode_filename', 'make_response',\n 'render_to_pdf', 'render_to_pdf_response', 'render_to_content_file'\n]\n\nCONTENT_TYPE = 'application/pdf'\n\n\ndef html_to_pdf(content, stylesheets=None, base_url=None, url_fetcher=default_url_fetcher, media_type='print'):\n # type: (Text, Optional[List[CSS]], Optional[Text], Callable, Text) -> bytes\n \"\"\"\n Converts HTML ``content`` into PDF document.\n\n The HTML document can contain references to image, font and style resources provided\n as absolute or relative URLs. If resources are referenced by relative URLs the\n ``base_url`` param must also be specified so the ``url_fetcher`` is able to load the files.\n\n Resource URLs can use either external ``http://`` or ``https://`` protocol\n or local ``file://`` protocol (for example when embedding images from ``STATIC_ROOT`` directory).\n\n Keep that in mind and always specify and validate URLs for linked resources in case\n of user generated content is rendered to PDF documents to avoid potential security issues.\n\n :param str content: HTML content to render\n :type stylesheets: list of :class:`weasyprint.CSS` or :obj:`None`\n :param stylesheets:\n Additional :class:`weasyprint.CSS` stylesheets or :obj:`None`.\n See https://weasyprint.readthedocs.io/en/latest/tutorial.html#stylesheet-origins.\n :param base_url:\n The base used to resolve relative URLs. See WeasyPrint docs.\n :param url_fetcher:\n A function or other callable with the same signature\n as :func:`weasyprint.default_url_fetcher` called to fetch external resources\n such as stylesheets and images.\n See https://weasyprint.readthedocs.io/en/latest/tutorial.html#url-fetchers.\n :param media_type:\n The media type to use for ``@media``. Defaults to ``'print'``.\n\n :rtype: :class:`bytes`\n :returns: PDF content\n \"\"\"\n\n html = HTML(string=content, base_url=base_url, url_fetcher=url_fetcher, media_type=media_type)\n dest = BytesIO()\n html.write_pdf(dest, stylesheets=stylesheets)\n return dest.getvalue()\n\n\ndef encode_filename(filename): # type: (Text) -> Text\n \"\"\"\n Encodes filename part for ``Content-Disposition: attachment``.\n\n :param str filename: Filename to encode\n\n :rtype: str\n :returns: Encoded filename for use in ``Content-Disposition`` header\n\n >>> print(encode_filename(\"abc.pdf\"))\n filename=abc.pdf\n >>> print(encode_filename(\"aa bb.pdf\"))\n filename*=UTF-8''aa%20bb.pdf\n >>> print(encode_filename(u\"zażółć.pdf\"))\n filename*=UTF-8''za%C5%BC%C3%B3%C5%82%C4%87.pdf\n \"\"\"\n # TODO: http://greenbytes.de/tech/webdav/rfc6266.html\n # TODO: http://greenbytes.de/tech/tc2231/\n\n quoted = urlquote(filename)\n if quoted == filename:\n return \"filename=%s\" % filename\n else:\n return \"filename*=UTF-8''%s\" % quoted\n\n\ndef make_response(content, download_filename=None, content_type=CONTENT_TYPE, response_class=HttpResponse,\n inline_filename=None):\n # type: (bytes, Optional[Text], Text, Type[HttpResponse]) -> HttpResponse\n \"\"\"\n Wraps file content into HTTP response.\n\n If ``filename`` is specified then ``Content-Disposition: attachment``\n header is added to the response.\n\n Default ``Content-Type`` is ``'application/pdf'``.\n\n :param bytes content: Response content\n :param str download_filename: Optional filename for file download\n :param str content_type: Response content type\n :param response_class: Response class to instantiate\n :param inline_filename: Optional filename for file when displayed in browser\n\n :rtype: :class:`django.http.HttpResponse`\n :returns: Django response\n \"\"\"\n response = response_class(content, content_type=content_type)\n if download_filename is not None:\n response[\"Content-Disposition\"] = \"attachment; %s\" % encode_filename(download_filename)\n if inline_filename is not None:\n response[\"Content-Disposition\"] = \"inline; %s\" % encode_filename(inline_filename)\n return response\n\n\ndef render_to_pdf(template, context, using=None, request=None, **render_kwargs):\n # type: (Text, Dict, Any, Any, Any) -> bytes\n \"\"\"\n Creates PDF document from Django HTML template.\n\n :param str template: Path to Django template\n :param dict context: Template context\n :param using: Optional Django template engine\n :param request: Optional Django Request\n\n :rtype: :class:`bytes`\n :returns: Rendered PDF document\n\n Additional ``**render_kwargs`` are passed to :func:`html_to_pdf`.\n \"\"\"\n content = loader.render_to_string(template, context, request=request, using=using) # type: Text\n return html_to_pdf(content, **render_kwargs)\n\n\ndef render_to_pdf_response(request, template, context, using=None,\n download_filename=None, content_type=CONTENT_TYPE,\n response_class=HttpResponse,\n inline_filename=None,\n **render_kwargs):\n # type: (HttpRequest, Text, Dict, Any, Optional[Text], Text, Type[HttpResponse], Any) -> HttpResponse\n \"\"\"\n Renders a PDF response using given ``request``, ``template`` and ``context``.\n\n If ``download_filename`` param is specified then the response ``Content-Disposition``\n header will be set to ``attachment`` making the browser display\n a \"Save as..\" dialog.\n\n :param request: Django HTTP request\n :type request: :class:`django.http.HttpRequest`\n :param str template: Path to Django template\n :param dict context: Template context\n :param using: Optional Django template engine\n :param str download_filename: Optional filename to use for file download\n :param str content_type: Response content type\n :param response_class: Default is :class:`django.http.HttpResponse`\n :param str inline_filename: Optional filename to use for file when displayed in browser\n\n :rtype: :class:`django.http.HttpResponse`\n :returns: Django HTTP response\n\n Additional ``**render_kwargs`` are passed to :func:`html_to_pdf`.\n \"\"\"\n pdf = render_to_pdf(template, context, using=using, request=request, **render_kwargs)\n return make_response(pdf, download_filename, content_type=content_type, response_class=response_class,\n inline_filename=inline_filename)\n\n\ndef render_to_content_file(template, context, using=None, **render_kwargs):\n # type: (Text, Dict, Any, Any) -> ContentFile\n \"\"\"\n Example:\n\n >>> content = render_to_content_file('doc.html')\n\n Then save to Django storage:\n\n >>> from django.core.files.storage import default_storage\n >>> default_storage.save('file.pdf', content)\n\n Or attach to a model instance:\n\n >>> instance.attachment.save('file.pdf', content, save=True)\n\n :param str template: Path to Django template\n :param context: Template context\n :type context: :class:`dict` or :class:`django.template.Context`\n :param using: Optional Django template engine\n\n :rtype: :class:`django.core.files.base.ContentFile`\n :returns: Django content file\n\n Additional ``**render_kwargs`` are passed to :func:`html_to_pdf`.\n \"\"\"\n content = render_to_pdf(template, context, using=using, **render_kwargs)\n return ContentFile(content)\n","sub_path":"easy_pdf/rendering.py","file_name":"rendering.py","file_ext":"py","file_size_in_byte":7835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"340058565","text":"\"\"\"\nFile that contains the class definition of a\npoint load\n\"\"\"\n\nimport logging\n\nfrom lolFem.core.boundary_conditions.boundary_condition import BoundaryCondition, SetTypeError\nfrom lolFem.core.node_set import NodeSet\n\nlogger = logging.getLogger(__name__)\n\n\nclass PointLoad(BoundaryCondition):\n\n \"\"\"\n A point load represents a force applied at a single infinitesimal point.\n \"\"\"\n\n def __init__(self, value, dof_ids, set_applied_to):\n\n # First check if set is of correct type\n if not isinstance(set_applied_to, NodeSet):\n raise SetTypeError(\n \"It is only possible to apply point loads to node sets.\")\n essential = False\n\n # Call base boundary condition, with the flag that\n # this is not an essential bc.\n super(PointLoad, self).__init__(value,\n dof_ids,\n essential,\n set_applied_to)\n\n def __str__(self):\n return super(PointLoad, self).print_out(\"Point Load\")\n","sub_path":"lolFem/core/boundary_conditions/point_load.py","file_name":"point_load.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"511892569","text":"from __future__ import print_function, division\r\nimport os\r\nimport torch\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport random\r\nfrom torch.utils.data import Dataset, DataLoader\r\nfrom torchvision import transforms\r\nfrom skimage import io, transform\r\n# Ignore warnings\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\nplt.ion() # interactive mode\r\n\r\n\r\nclass ClipSubstractMean(object):\r\n\r\n def __init__(self, b=104, g=117, r=123):\r\n self.means = np.array((r, g, b))\r\n\r\n def __call__(self, sample):\r\n video_x, video_label = sample['video_x'], sample['video_label']\r\n new_video_x = video_x - self.means\r\n return {'video_x': new_video_x, 'video_label': video_label}\r\n\r\n\r\nclass Rescale(object):\r\n \"\"\"\r\n Resize the image in a sample into a given scale\r\n \"\"\"\r\n def __init__(self, output_size=(224, 224)):\r\n assert isinstance(output_size, (int, tuple))\r\n self.output_size = output_size\r\n\r\n def __call__(self, sample):\r\n video_x, video_label = sample['video_x'], sample['video_label']\r\n h, w = video_x.shape[1], video_x.shape[2]\r\n if isinstance(self.output_size, int):\r\n if h > w:\r\n new_h, new_w = self.output_size * h / w, self.output_size\r\n else:\r\n new_h, new_w = self.output_size, self.output_size * w / h\r\n else:\r\n new_h, new_w = self.output_size\r\n new_h, new_w = int(new_h), int(new_w)\r\n new_video_x = np.zeros((64, new_h, new_w, 3))\r\n for i in range(64):\r\n image = video_x[i, :, :, :]\r\n img = transform.resize(image, (new_h, new_w))\r\n new_video_x[i, :, :, :] = img\r\n return {'video_x': new_video_x, 'video_label': video_label}\r\n\r\n\r\nclass RandomCrop(object):\r\n \"\"\"\r\n randomly crop the image in a sample\r\n \"\"\"\r\n def __init__(self):\r\n print('nothing')\r\n\r\n def __call__(self):\r\n print('random crop the image')\r\n return 0\r\n\r\n\r\nclass ToTensor(object):\r\n \"\"\"\r\n convert the ndarrys in a sample to Tensor\r\n\r\n transpose: swap the axis to meet the model input(batch_size, C, H, W)\r\n \"\"\"\r\n def __call__(self, sample):\r\n video_x, video_label = sample['video_x'], sample['video_label']\r\n video_x = video_x.transpose((3, 0, 1, 2))\r\n video_x = np.array(video_x)\r\n video_x = torch.from_numpy(video_x)\r\n video_x = video_x.type(torch.FloatTensor)\r\n\r\n video_label = video_label.type(torch.LongTensor)\r\n # video_label is one-hot tensor, not need any processing\r\n return {'video_x': video_x, 'video_label': video_label}\r\n\r\n\r\nclass UCF101(Dataset):\r\n \"\"\"UCF101 Landmarks dataset\r\n\r\n Args:\r\n info_list (string): Path to the info list file with annotations.\r\n root_dir (string): Directory with all the video frames.\r\n transform (callable, optional): Optional transform to be applied\r\n on a sample.\r\n \"\"\"\r\n\r\n def __init__(self, info_list, root_dir, transform=None):\r\n self.landmarks_frame = pd.read_csv(info_list, delimiter=' ', header=None)\r\n self.root_dir = root_dir\r\n self.transform = transform\r\n\r\n def __len__(self):\r\n return len(self.landmarks_frame)\r\n\r\n def __getitem__(self, idx):\r\n video_path = os.path.join(self.root_dir, self.landmarks_frame.iloc[idx, 0])\r\n video_label = torch.LongTensor([[(int(self.landmarks_frame.iloc[idx, 1])-1)]])\r\n video_label = video_label.view(1)\r\n # video_label_onehot = torch.zeros(1, 101).scatter_(1, video_label, 1)\r\n # video_label_onehot = video_label.squeeze(1)\r\n # video_label_onehot = video_label_onehot.view(101)\r\n video_x = self.get_single_video_x(video_path)\r\n sample = {'video_x': video_x, 'video_label': video_label}\r\n\r\n if self.transform:\r\n sample = self.transform(sample)\r\n return sample\r\n\r\n def get_single_video_x(self, video_path):\r\n slash_row = video_path.split('.')\r\n dir_name = slash_row[0]\r\n video_jpgs_path = os.path.join(self.root_dir, dir_name)\r\n video_name = video_jpgs_path.split('/')[4]\r\n data = pd.read_csv(os.path.join(video_jpgs_path, 'n_frames.txt'), delimiter='\\t', header=None)\r\n frame_count = int(data[0][0])\r\n video_x = np.zeros((64, 240, 320, 3)) # random select 64 frames\r\n if frame_count < 65:\r\n for i in range(frame_count):\r\n image_name = video_name + '_image_' + str(i) + '.jpg'\r\n image_path = video_jpgs_path + '/' + image_name\r\n tmp_image = io.imread(image_path)\r\n video_x[i, :, :, :] = tmp_image\r\n return video_x\r\n image_start = random.randint(0, frame_count-64)\r\n image_id = image_start\r\n for i in range(64):\r\n s = image_id\r\n image_name = video_name + '_image_' + str(s) + '.jpg'\r\n image_path = video_jpgs_path + '/' + image_name\r\n tmp_image = io.imread(image_path)\r\n video_x[i, :, :, :] = tmp_image\r\n s += 1\r\n return video_x\r\n\r\n\r\ndef getUCFDataloader(batch_size,shuffle=True):\r\n root_list = 'F:/04UCF101/UCF101_jpgs/'\r\n info_list = 'F:/04UCF101/ucfTrainTestlist/trainlist01.txt'\r\n myUCF010 = UCF101(info_list, root_list, transform=transforms.Compose([ClipSubstractMean(), Rescale(), ToTensor()]))\r\n dataloader = DataLoader(myUCF010, batch_size=batch_size, shuffle=shuffle)\r\n return dataloader\r\n\r\nif __name__ == '__main__':\r\n root_list = 'F:/04UCF101/UCF101_jpgs/'\r\n info_list = 'F:/04UCF101/ucfTrainTestlist/trainlist01.txt'\r\n myUCF010 = UCF101(info_list, root_list, transform=transforms.Compose([ClipSubstractMean(), Rescale(), ToTensor()]))\r\n dataloader = DataLoader(myUCF010, batch_size=1, shuffle=True)\r\n for i_batch, sample_batch in enumerate(dataloader):\r\n print(i_batch, sample_batch['video_x'].size(), sample_batch['video_label'].size())","sub_path":"dataload.py","file_name":"dataload.py","file_ext":"py","file_size_in_byte":6000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"289744183","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nfrom googlesearch import search\n\n\ndef findStock(StockName):\n #Ask what stock\n #StockName = input('Enter the name of the stock you want information for: ')\n #Specify this input is a stock that exists on the nasdaq and format the input\n StockPage = \"Nasdaq Stock \" + StockName\n print(StockPage)\n #Search the web for the first page that is returned from the given input\n StockQuote = searchStockInfo(StockPage)\n #Set the page that we will be scraping\n quote_page = StockQuote\n #Query the website and return the html to the variable 'html_page'\n html_page = urlopen(quote_page)\n #Parse the html using beautfil soup and store in the variable 'soup'\n soup = BeautifulSoup(html_page, 'html.parser')\n #Get the price\n stock_price_box = soup.find('div', attrs={'class':'qwidget-dollar'})\n #Print the price\n print(stock_price_box.text)\n return stock_price_box.text\n\n# Currently returns the first website queried from request\n# Goal: return stock acronym, price, recent news\ndef searchStockInfo(stockString):\n url = \"\"\n for url in search(stockString,num=1, start=1, stop=2):\n print(url)\n return url\n\n\nif __name__ == '__main__':\n try:\n print(\"Welcome to the Stock Price Search!\")\n #print(\"Press Ctrl + C to leave the search.\")\n findStock(\"Tesla\")\n except KeyboardInterrupt:\n print(\"Program Interrupted\")\n","sub_path":"IndividualStock.py","file_name":"IndividualStock.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"404027173","text":"#! python3\nfrom StatusText import createmsg\nfrom urllib.request import urlopen\nimport json\n\ndef ISSLocation():\n # announce that we are grabbing the ISS's location\n createmsg(\"INFO\",\"requesting the coordinates of the ISS\")\n\n # Get the dataset\n response = urlopen(\"http://api.open-notify.org/iss-now.json\")\n\n # Convert bytes to string type and string type to dict\n string = response.read().decode('utf-8')\n json_obj = json.loads(string)\n\n # put the date into varibles\n latitude = float(json_obj['iss_position']['latitude'])\n longitude = float(json_obj['iss_position']['longitude'])\n\n createmsg(\"INFO\",\"ISS Latitude: \" + str(latitude))\n createmsg(\"INFO\",\"ISS Longitude: \" + str(longitude))\n\n return latitude, longitude\n\n#latitude, longitude = ISSLocation()\n","sub_path":"bin/GrabLocation.py","file_name":"GrabLocation.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"348318998","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 14 12:17:35 2019\n\n@author: ridhi\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndf = pd.read_excel(r'HUNL_EXAMPLE SINGLE_stack_20000_ LBR Total,tag_Evaluation_MBB_per_G.xlsx')\n\n\ndf = df.loc[df['Step'] <= 80]\n\nx = df['Step']\ny_val = df['Value LBR']\ny6 = df['Param = .6']\ny7 = df['Param = .7']\ny8 = df['Param = .8']\ny85 = df['Param = 0.85']\ny9 = df['Param=.9']\n\nplt.figure(figsize=(10, 10))\n#plt.plot(x, y_val)\n#plt.plot(x, y6, label='.6')\n#plt.plot(x, y7, label='.7')\n#plt.plot(x, y8, label='.8')\nplt.scatter(x, y85, label='.85')\n#plt.legend()\nplt.plot(x, y85)\n#plt.plot(x, y9, label='.9')\n\nplt.ylabel('Exploitability (mbb/g)', fontsize=15)\nplt.xlabel('Iteration', fontsize=15)\n\nplt.title('Exploitability vs Iterations: training for HUNL', \n fontsize=20)\n\nplt.savefig('HUNL_results_final.png')\nplt.show()\n\n\n","sub_path":"plot_HUNL.py","file_name":"plot_HUNL.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"312019724","text":"# -*- coding: utf-8 -*-\n\nfrom openerp import models, fields, api\n\nclass Media(models.Model): \n _name = \"hc.res.media\" \n _description = \"Media\" \n\n identifier_ids = fields.One2many(\n comodel_name=\"hc.media.identifier\", \n inverse_name=\"media_id\", \n string=\"Identifiers\", \n help=\"Identifier(s) for the image.\") \n type = fields.Selection(string=\"Media Type\", \n required=\"True\", \n selection=[\n (\"photo\", \"Photo\"), \n (\"video\", \"Video\"), \n (\"audio\", \"Audio\")], \n help=\"Whether the media is a photo (still image), an audio recording, or a video recording.\") \n subtype_id = fields.Many2one(\n comodel_name=\"hc.vs.digital.media.subtype\", \n string=\"Subtype\", \n help=\"The type of acquisition equipment/process.\")\n view_id = fields.Many2one(\n comodel_name=\"hc.vs.media.view\", \n string=\"View\", \n help=\"Imaging view e.g Lateral or Antero-posterior.\") \n subject_type = fields.Selection(\n string=\"Subject Type\", \n selection=[\n (\"Patient\", \"Patient\"), \n (\"Practitioner\", \"Practitioner\"), \n (\"Group\", \"Group\"), \n (\"Device\", \"Device\"), \n (\"Specimen\", \"Specimen\")], \n help=\"Type of patient observations supporting recommendation.\") \n subject_name = fields.Char(\n string=\"Subject\", \n compute=\"_compute_subject_name\", \n store=\"True\", \n help=\"Who/What this Media is a record of.\") \n subject_patient_id = fields.Many2one(\n comodel_name=\"hc.res.patient\", \n string=\"Subject Patient\", \n help=\"Patient this media is a record of.\") \n subject_practitioner_id = fields.Many2one(\n comodel_name=\"hc.res.practitioner\", \n string=\"Subject Practitioner\", \n help=\"Practitioner this media is a record of.\") \n subject_group_id = fields.Many2one(\n comodel_name=\"hc.res.group\", \n string=\"Subject Group\", \n help=\"Group this media is a record of.\") \n subject_device_id = fields.Many2one(\n comodel_name=\"hc.res.device\", \n string=\"Subject Device\", \n help=\"Device this media is a record of.\") \n subject_specimen_id = fields.Many2one(\n comodel_name=\"hc.res.specimen\", \n string=\"Subject Specimen\", \n help=\"Specimen this media is a record of.\") \n operator_id = fields.Many2one(\n comodel_name=\"hc.res.practitioner\", \n string=\"Operator\", \n help=\"The person who generated the image.\") \n device_name = fields.Char(\n string=\"Device Name\", \n help=\"Name of the device/manufacturer.\") \n height = fields.Integer(\n string=\"Height\", \n help=\"Height of the image in pixels(photo/video).\") \n width = fields.Integer(\n string=\"Width\", \n help=\"Width of the image in pixels (photo/video).\") \n frames = fields.Integer(\n string=\"Frames\", \n help=\"Number of frames if > 1 (photo).\") \n duration = fields.Integer(\n string=\"Duration\", \n help=\"Length in seconds (audio / video).\") \n duration_uom_id = fields.Many2one(\n comodel_name=\"hc.vs.time.uom\", \n string=\"Duration UOM\",\n default=\"s\",\n help=\"Duration unit of measure.\" ) \n content_attachment_id = fields.Many2one(\n comodel_name=\"hc.media.content.attachment\", \n string=\"Content Attachment\", \n required=\"True\", \n help=\"Actual Media - reference or data.\") \n\n @api.multi \n def _compute_subject_name(self): \n for hc_res_media in self: \n if hc_res_media.subject_type == 'Patient': \n hc_res_media.subject_name = hc_res_media.subject_patient_id.name\n elif hc_res_media.subject_type == 'Practitioner': \n hc_res_media.subject_name = hc_res_media.subject_practitioner_id.name\n elif hc_res_media.subject_type == 'Group': \n hc_res_media.subject_name = hc_res_media.subject_group_id.name\n elif hc_res_media.subject_type == 'Device': \n hc_res_media.subject_name = hc_res_media.subject_device_id.name\n elif hc_res_media.subject_type == 'Specimen': \n hc_res_media.subject_name = hc_res_media.subject_specimen_id.name\n\nclass MediaIdentifier(models.Model): \n _name = \"hc.media.identifier\" \n _description = \"Media Identifier\" \n _inherit = [\"hc.basic.association\", \"hc.identifier\"]\n\n media_id = fields.Many2one(\n comodel_name=\"hc.res.media\", \n string=\"Media\", \n help=\"Media associated with this media content identifier.\") \n\nclass MediaContentAttachment(models.Model): \n _name = \"hc.media.content.attachment\" \n _description = \"Media Content Attachment\" \n _inherit = [\"hc.basic.association\", \"hc.attachment\"]\n\nclass DigitalMediaSubtype(models.Model): \n _name = \"hc.vs.digital.media.subtype\" \n _description = \"Digital Media Subtype\" \n _inherit = [\"hc.value.set.contains\"]\n\nclass MediaView(models.Model): \n _name = \"hc.vs.media.view\" \n _description = \"Media View\" \n _inherit = [\"hc.value.set.contains\"]\n","sub_path":"addons/hc_media/models/hc_res_media.py","file_name":"hc_res_media.py","file_ext":"py","file_size_in_byte":5478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"598917255","text":"import json\n\nimport requests\n\nHAYSTACK_URL = 'http://challenge.code2040.org/api/haystack'\nHAYSTACK_SUCCESS_URL = 'http://challenge.code2040.org/api/haystack/validate'\nMY_API_TOKEN = '403181110917fab69f13ca79fb75bb8a'\n\n\ndef complete_step_three():\n\t# Send request to server and receive data\n\tr = requests.post(\n\t\turl=HAYSTACK_URL,\n\t\tdata={\n\t\t\t'token': MY_API_TOKEN\n\t\t}\n\t)\n\n\t# Load information from server into a dictionary\n\tapi_dict = json.loads(r.content.decode('utf-8'))\n\n\t# Assign given information into readable variables\n\tneedle = api_dict['needle']\n\n\t# Store counter\n\tcounter = 0\n\n\tfor hay in api_dict['haystack']:\n\t\t# Found the needle, so need to break\n\t\tif hay == needle:\n\t\t\tbreak\n\n\t\tcounter += 1\n\n\t# Setup request to send to server\n\tp = requests.post(\n\t\turl=HAYSTACK_SUCCESS_URL,\n\t\tdata={\n\t\t\t'token': MY_API_TOKEN,\n\t\t\t'needle': counter\n\t\t}\n\t)\n\n\tassert p.status_code == 200\n","sub_path":"src/step_three.py","file_name":"step_three.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"334336066","text":"# Google Search\n# pip install Google\n\nfrom googlesearch import search\n\nquery = input(\"Enter your query:\\n\")\n\nfor i in search(query, tld=\"co.in\", num=5, stop=5, pause=2):\n print(i)\n\n\n# EXplanation\n\n# val: This is the text that you want to search for.\n\n# tld: This refers to the top level domain value like co.in or com which will specify which Google website we want to use.\n\n# lang: This parameter stands for language.\n\n# num: This is used to specify the number of results we want.\n\n# start: This is to specify from where to start the results. We should keep it 0 to begin from the very start.\n\n# stop: The last result to retrieve. Use None to keep searching forever.\n\n# pause: This parameter is used to specify the number of seconds to pause between consecutive HTTP requests because if we hit too many requests, Google can block our IP address.\n","sub_path":"Python-Programs/google_Search.py","file_name":"google_Search.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"406152600","text":"skroty = {\"Chleb\": \"sztuki\",\n \"Coca-Cola\": \"sztuki\",\n \"Makaron\": \"sztuki\",\n \"Ziemniaki\": \"kilogramy\",\n \"Czipsy\": \"opakowania\",\n \"Mieszanka Wedlowska\": \"kilogramy\",\n \"Cytryna\": \"kilogramy\",\n \"Jablka\": \"kilogramy\",\n \"Piwo\": \"sztuki\",\n \"Papierosy z kiosku\": \"sztuki\",\n \"Gumy do zucia\": \"opakowania\"}\n\n#print(skroty.values())\n#wartosci = [if \"sztuki\" in skroty.values()]\n#wartosci = {key: value == \"sztuki\" for key, value in skroty.items()}\n#print(wartosci)\n\n\n#for klucz in skroty.keys():\n # if(skroty.values() == \"sztuki\":\n # print(klucz)\n\n#for produkt, wartosc in skroty.items():\n # if wartosc == \"sztuki\":\n # print(produkt)\nwartosci = [k for k,wartosc in skroty.items() if wartosc == \"sztuki\"]\nprint(wartosci)","sub_path":"zadanie3x.py","file_name":"zadanie3x.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"355239197","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThe basic view logic here.\n\nFor example: signin, signup, homepage , etc.\n\"\"\"\n\nimport logging\nimport functools\n\nfrom django.views import generic\n\nfrom portal import forms\nfrom portal import models\nfrom portal.views import utils\n\nLOG = logging.getLogger(__name__)\n\n\ndef require_auth(func):\n \"\"\"The decorator will check username existed in session. If it is continue.\n \"\"\"\n @functools.wraps(func)\n def _require_auth(request, *args, **kwargs):\n username = request.session.get('username')\n if not username:\n return signin(request, *args, **kwargs)\n else:\n return func(request, *args, **kwargs)\n\n return _require_auth\n\n\nclass SignIn(generic.FormView):\n\n form_class = forms.SignInForm\n template_name = 'portal/sign_in.html'\n\n def form_valid(self, form):\n data = form.cleaned_data\n users = models.User.objects.filter(username=data['username'])\n if users and users[0].password == data['password']:\n LOG.debug('%s login success.' % users)\n utils.set_session(self.request, users[0].username)\n\n return portal(self.request)\n else:\n LOG.debug(\"%s login failed.\" % users)\n return utils.render('sign_in.html',\n {'errors': 'Username or password is wrong',\n 'form': form})\n\nsignin = SignIn.as_view()\n\n\nclass SignUp(generic.FormView):\n\n template_name = 'portal/sign_up.html'\n form_class = forms.SignUpForm\n\n def form_valid(self, form):\n data = form.cleaned_data\n user = models.User(**data)\n user.save()\n content = 'Welcome to zufangbao! You have successed to sign up!'\n sendmessage(self.request, content)\n content = data['username'] + ' registration succeed!'\n utils.send_mail(data['email'], content)\n return utils.render('portal.html', {})\n\nsignup = SignUp.as_view()\n\n\n@require_auth\ndef portal(request):\n# user = utils.get_user_obj(request)\n return utils.render('portal.html', {})\n\n\nclass ChargeRent(generic.FormView):\n form_class = forms.ChargeRentForm\n template_name = 'portal/charge_rent.html'\n\n def form_valid(self, form):\n data = form.cleaned_data\n me = utils.get_user_obj(self.request)\n house = models.House(owner=me,\n house_name=data['location_area'],\n house_size=int(data['house_size']))\n house.save()\n return portal(self.request)\n\nchargerent = require_auth(ChargeRent.as_view())\n\n\n@require_auth\ndef logout(request):\n username = request.session['username']\n utils.unset_session(request, username)\n return portal(request)\n\n\ndef sendmessage(request, content):\n \"\"\"send message in the website\"\"\"\n user = utils.get_user_obj(request)\n message = models.Message(owner_id=user.id, content=content)\n message.save()\n","sub_path":"portal/views/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"572914980","text":"# Script to track house occupancy.\n\nimport appdaemon.plugins.hass.hassapi as hass\nimport datetime\nimport time\n\n\nclass Presence(hass.Hass):\n\n def initialize(self):\n\n # Device trackers to use\n deviceTrackers = [\n \"device_tracker.meta_walden\",\n \"device_tracker.meta_kristina\",\n # \"device_tracker.meta_emilie\",\n # \"device_tracker.meta_naia\",\n \"input_boolean.guest_mode\"\n ]\n\n for device in deviceTrackers:\n self.listen_state(self.emptyHome,device)\n\n # Check if anyone is home. Returns True/False.\n def occupancy(self, entity_id):\n aephir = 'device_tracker.meta_walden' == 'home'\n kristina = 'device_tracker.meta_kristina' == 'home'\n emilie = 'device_tracker.meta_emilie' == 'home'\n naia = 'device_tracker.meta_naia' == 'home'\n guest_mode = 'input_boolean.guest_mode' == 'on'\n anyoneHome = any([\n aephir,\n # naia,\n # emilia,\n kristina,\n guest_mode\n ])\n return anyoneHome\n\n\n def emptyHome(self, entity, attribute, old, new, kwargs):\n\n # Lists of entities to turn off.\n offList = [\n 'light.all_lights',\n 'switch.switch',\n 'switch.fountain'\n # TVs and music...?\n ]\n\n # If \"occupancy\" returns 'False', then turn off all entities in offList, and notify the one who leaves last.\n if not self.occupancy:\n for entityID in offList:\n self.turn_off(entityID)\n if entity == 'device_tracker.meta_walden' or entity == 'input_boolean.guest_mode':\n self.call_service(\"notify/home_aephir_bot\", message=\"The house is empty. I have turned off everything.\", data={\"inline_keyboard\":\"Turn espresso machine back on:/espresso_on, Thanks!:/removekeyboard\"})\n elif entity == 'device_tracker.meta_kristina':\n self.call_service(\"notify/ios_kristinas_iphone\", message=\"The house is empty. I have turned off everything.\", data={\"inline_keyboard\":\"Turn espresso machine back on:/espresso_on, Thanks!:/removekeyboard\"})\n","sub_path":"appdaemon/apps/device_tracker/power_off_empty_home.py","file_name":"power_off_empty_home.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"351370094","text":"import string\nimport os.path\n\nname = input(\"Enter the input filename: \")\n\nwhile not name.endswith(\".txt\") or not os.path.isfile(name):\n if not name.endswith(\".txt\"):\n name = input(\"Invalid filename extension. Please re-enter the input filename: \")\n else:\n name = input(\"File not found. Please re-enter the input filename: \")\n\nfile = open(name, \"r\")\n\nkey = int(file.readline().strip())\nmessage = file.readline().strip().lower()\n\ndecode = \"\"\n\nfor char in message:\n if not char == \" \": \n charVal = string.ascii_lowercase.find(char)\n charVal -= key\n if charVal < 0:\n charVal = 26 + charVal\n decode += string.ascii_lowercase[charVal]\n else:\n decode += char\n\nfile.close()\n\nprint(decode) \n","sub_path":"lectures/caesar.py","file_name":"caesar.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"103247715","text":"import sys, os\nfrom pyspark.sql import SparkSession, types, functions\nfrom pyspark import SparkConf, SparkContext\nimport sys, re, datetime, uuid\n\nos.environ[\"PYSPARK_PYTHON\"]=\"python3\"\nos.environ[\"PYSPARK_DRIVER_PYTHON\"]=\"python3\"\n\ncluster_seeds = ['199.60.17.171', '199.60.17.188']\n\ncluster_seeds = ['199.60.17.171', '199.60.17.188']\n\nconf = SparkConf().setAppName('example code') \\\n .set('spark.cassandra.connection.host', ','.join(cluster_seeds))\n\nspark = SparkSession.builder.appName('Big Data Project').getOrCreate()\nsc = spark.sparkContext\nassert sys.version_info >= (3, 4) # make sure we have Python 3.4+\nassert spark.version >= '2.2' # make sure we have Spark 2.2+\n\n\n\nschema = types.StructType([types.StructField('state_code', types.StringType(), True),\n types.StructField('month', types.StringType(), True),\n types.StructField('year',types.StringType(), True),\n types.StructField('observation_count', types.DoubleType(),True),\n types.StructField('observation_percent', types.DoubleType(), True),\n types.StructField('max_value', types.DoubleType(), True),\n types.StructField('max_hour', types.DoubleType(), True),\n types.StructField('arithmetic_mean', types.DoubleType(), True),\n types.StructField('am_wind', types.DoubleType(), True),\n types.StructField('am_temp', types.DoubleType(), True),\n types.StructField('am_rh', types.DoubleType(), True),\n types.StructField('am_press', types.DoubleType(), True)])\n\n\nitr=0\nfor j in ['88101']:\n train_final={}\n train_final[itr] = spark.createDataFrame(sc.emptyRDD(), schema=schema)\n\n for year in range (1998, 2018):\n training = spark.read.csv(\"/home/ldua/Desktop/BigDataProject/pm_25/daily_\"+ str(j) +\"_\" + str(year) + \".csv\", header = True)\n train = training[\n ['State Code', 'Date Local', 'Observation Count', 'Observation Percent', '1st Max Value', '1st Max Hour',\n 'Arithmetic Mean']]\n\n split_col = functions.split(train['Date Local'], '-')\n train = train.withColumn('Year', split_col.getItem(0))\n train = train.withColumn('Month', split_col.getItem(1))\n\n train = train.drop('Date Local')\n train.createOrReplaceTempView('train')\n train_g = train.groupBy(train['State Code'], train['Month'], train['Year']).agg(\n functions.avg(train['Observation Count']).alias('Observation Count'),\n functions.avg(train['Observation Percent']).alias('Observation Percent'),\n functions.avg(train['1st Max Value']).alias('1st Max Value'),\n functions.avg(train['1st Max Hour']).alias('1st Max Hour'),\n functions.avg(train['Arithmetic Mean']).alias('Arithmetic Mean'))\n supportl = ['WIND', 'TEMP', 'RH_DP', 'PRESS']\n for i in supportl:\n support = spark.read.csv(\n \"/home/ldua/Desktop/BigDataProject/support/daily_\" + str(i) + \"_\" + str(year) + \".csv\", header=True)\n support_f = support.select('State Code', 'Date Local', 'Arithmetic Mean')\n split_col = functions.split(support_f['Date Local'], '-')\n support_f = support_f.withColumn('Year', split_col.getItem(0))\n support_f = support_f.withColumn('Month', split_col.getItem(1))\n support_f = support_f.drop('Date Local')\n support_t = support_f.groupBy([support_f['State Code'], support_f['Month'], support_f['Year']]).agg(\n functions.avg(support_f['Arithmetic Mean']).alias('AM'))\n support_g = support_t.select(support_t['State Code'].alias('sc'), support_t['Month'].alias('m'),\n support_t['Year'].alias('y'), support_t['AM'])\n train_g = train_g.join(support_g, [\n (train_g['State Code'] == support_g['sc']) & (train_g['Year'] == support_g['y']) & (\n train_g['Month'] == support_g['m'])\n ]).drop('sc', 'm', 'y').select('*').sort('State Code', 'Year', 'Month')\n\n train_final[itr] = train_final[itr].union(train_g)\n\n train_final[itr].coalesce(1).write.csv('/home/ldua/Desktop/FinalBig/FinalOutput/' + str(j), sep=',', header=True)\n\n itr += 1\n","sub_path":"LocalBigData/88101.py","file_name":"88101.py","file_ext":"py","file_size_in_byte":4396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"25314587","text":"\"\"\"\nPyramid\nFrom the brief:\nPlease write a web service that takes in a string and \nreturns a boolean to indicate whether a word is a pyramid word. \nA word is a ‘pyramid’ word if you can arrange the letters in \nincreasing frequency, starting with 1 and continuing without gaps \nand without duplicates.\nExamples:\nbanana is a pyramid word because you have 1 'b', 2 'n's, and 3 'a's.\nbandana is not a pyramid word because you have 1 'b' and 1 'd'.\n\"\"\"\n\n\ndef is_pyramid(text):\n \"\"\"is_pyramid - determines if text is pyramid form\n ::param:: text - the text to analyze\n ::return:: True if pyramid form, False if not\n \"\"\"\n result = False\n\n # print(text, isinstance(text, str), (text or isinstance(text, str)))\n\n if isinstance(text, str) and text != \"\":\n letters = {}\n for char in text:\n if not letters.get(char):\n letters[char] = 1\n else:\n letters[char] = letters[char] + 1\n\n items = sorted(letters.values())\n result = items == list(range(1, len(items) + 1))\n\n return result\n","sub_path":"pyramid.py","file_name":"pyramid.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"456293714","text":"# -*- coding: utf-8 -*-\n# Created at 2020-06-13 \n\n\nclass Solution(object):\n def numIslands(self, grid):\n \"\"\"\n :type grid: List[List[str]]\n :rtype: int\n \"\"\"\n row_num = len(grid)\n if row_num == 0:\n return 0\n\n column_num = len(grid[0])\n res = 0\n for r in range(row_num):\n for c in range(column_num):\n if grid[r][c] == \"1\":\n res += 1\n self.dfs(grid, r, c)\n\n return res\n\n def dfs(self, grid, r, c):\n grid[r][c] = 0\n row_num, column_num = len(grid), len(grid[0])\n for x, y in ((r-1, c), (r+1, c), (r, c-1), (r, c+1)): # 四个方向查找\n if 0 <= x < row_num and 0 <= y < column_num and grid[x][y] == \"1\":\n self.dfs(grid, x, y)\n\n","sub_path":"Week_04/06_number_of_islands.py","file_name":"06_number_of_islands.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"447475678","text":"import streamlit as st\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\ndef app(car_df):\r\n\tst.header('View Data')\r\n\twith st.beta_expander('View Dataset'):\r\n\t\tst.table(car_df)\r\n\tst.subheader('Columns description')\r\n\tbeta_col1,beta_col2=st.beta_columns(2)\r\n\r\n\twith beta_col1:\r\n\t\tif st.checkbox('Show all columns names'):\r\n\t\t\tst.table(list(car_df.columns))\r\n\twith beta_col2:\r\n\t\tif st.checkbox('View column data'):\r\n\t\t\tcolumn_data=st.selectbox('select columns',('enginesize','horsepower','carwidth','drivewheel','price'))\r\n\t\t\tif column_data=='drivewheel':\r\n\t\t\t\tst.write(car_df['drivewheel'])\r\n\t\t\telif column_data=='carwidth':\r\n\t\t\t\tst.write(car_df['carwidth'])\r\n\t\t\telif column_data=='enginesize':\r\n\t\t\t\tst.write(car_df['enginesize'])\r\n\t\t\telif column_data=='horsepower':\r\n\t\t\t\tst.write(car_df['horsepower'])\r\n\t\t\telse:\r\n\t\t\t\tst.write(car_df['price'])\r\n\tif st.checkbox('Show summary'):\r\n\t\tst.table(car_df.describe())\r\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"279978602","text":"import socket\nimport threading\nimport logging\nfrom pathlib import Path\nfrom queue import Queue\n\nFORMAT='%(asctime)s %(message)s'\nlogging.basicConfig(format=FORMAT, level=logging.INFO)\n\nclass Ftpcilent:\n def __init__(self, raddr='127.0.0.1', port=9999):\n self.addr = (raddr, port)\n self.sock = socket.socket()\n self.event = threading.Event()\n self.queue = Queue()\n self.dir = self.makedir()\n\n def makedir(self):\n path = Path('./recvfile')\n path.mkdir(exist_ok=True)\n return path\n\n def start(self):\n self.sock.connect(self.addr)\n logging.info('已经连接到主机')\n # threading.Thread(target=self.recv, name='CilentRecv').start()\n\n def recv(self):\n while not self.event.is_set():\n try:\n data = self.sock.recv(1024).decode('GBK')\n except Exception as e:\n logging.info(e)\n break\n logging.info(data)\n\n def stop(self):\n self.sock.close()\n self.event.wait(3)\n self.event.set()\n logging.info('client stop')\n\n def run(self):\n self.start()\n while not self.event.is_set():\n cmd = input('>>>')\n if cmd == 'list':\n self.sock.send(cmd.encode('GBK'))\n logging.info(self.sock.recv(1024).decode('GBK'))\n elif cmd.startswith('upload'):\n *_, filepath = cmd.partition(' ')\n path = Path(filepath)\n self.sock.send(cmd.encode('GBK'))\n try:\n with open('{}'.format(path), 'rb') as f:\n fileinfo = f.read()\n filelength = len(fileinfo)\n self.sock.send(str(filelength).encode('GBK'))\n self.sock.recv(1024)\n logging.info(str(filelength))\n width = 0\n while True:\n width = self.sock.send(fileinfo[width:])\n if not width:\n break\n\n except FileNotFoundError as e:\n logging.info(e)\n\n elif cmd.startswith('download'):\n self.sock.send(cmd.encode('GBK')) #发送要下载的是哪个文件\n *_, filename = cmd.rpartition(' ') #download XXX.txt\n self.sock.setblocking(True)\n length = int(self.sock.recv(1024))\n print(filename)\n self.sock.send('ack'.encode('GBK'))\n remote_filedata = b''\n while True:\n info = self.sock.recv(1024)\n remote_filedata += info\n if len(remote_filedata) >= length:\n break\n with open(r'recvfileclient\\{}'.format(filename, ), 'wb') as f:\n f.write(remote_filedata)\n print('download done')\n\n elif cmd.startswith('quit'):\n self.stop()\n\nfc = Ftpcilent()\nfc.run()\n\n","sub_path":"P17081-zhoujing/homework6/homework_cilent.py","file_name":"homework_cilent.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"463406768","text":"##############################################################################\n#\n# Copyright (c) 2004 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Tests for the Code Documentation Module\n\n$Id$\n\"\"\"\nimport os\nimport unittest\nimport doctest\nimport re\n\nfrom zope.component.interfaces import IFactory\nfrom zope.configuration import xmlconfig\nfrom zope.interface import implements\nfrom zope.testing import renormalizing\nfrom zope.traversing.interfaces import IContainmentRoot\n\nimport zope.app\nimport zope.app.appsetup.appsetup\nfrom zope.app.renderer.rest import ReStructuredTextSourceFactory\nfrom zope.app.renderer.rest import IReStructuredTextSource\nfrom zope.app.renderer.rest import ReStructuredTextToHTMLRenderer\nfrom zope.app.testing import placelesssetup, setup, ztapi\nfrom zope.app.testing.functional import BrowserTestCase\nfrom zope.app.testing.functional import FunctionalDocFileSuite\n\nfrom zope.app.apidoc.interfaces import IDocumentationModule\nfrom zope.app.apidoc.apidoc import APIDocumentation\nfrom zope.app.apidoc.codemodule.interfaces import IAPIDocRootModule\nfrom zope.app.apidoc.codemodule.codemodule import CodeModule\nfrom zope.app.apidoc.testing import APIDocLayer\nfrom zope.app.apidoc.zcmlmodule import ZCMLModule\n\n# Just for loading purposes\nimport zope.app.apidoc.codemodule.browser.module\nimport zope.app.apidoc.codemodule.browser.class_\nimport zope.app.apidoc.codemodule.browser.function\nimport zope.app.apidoc.codemodule.browser.text\nimport zope.app.apidoc.codemodule.browser.zcml\n\n\ndef foo(cls, bar=1, *args):\n \"\"\"This is the foo function.\"\"\"\nfoo.deprecated = True\n\nmeta = '''\n\n \n \n \n \n\n'''\n\ndef setUp(test):\n test.globs['rootFolder'] = setup.placefulSetUp(True)\n\n class RootModule(str):\n implements(IAPIDocRootModule)\n\n # Register zope package to apidoc\n ztapi.provideUtility(IAPIDocRootModule, RootModule('zope'), \"zope\")\n\n # Set up apidoc module\n test.globs['apidoc'] = APIDocumentation(test.globs['rootFolder'],\n '++apidoc++')\n\n # Register documentation modules\n ztapi.provideUtility(IDocumentationModule, CodeModule(), \"Code\")\n ztapi.provideUtility(IDocumentationModule, ZCMLModule(), \"ZCML\")\n\n # Register Renderer Components\n ztapi.provideUtility(IFactory, ReStructuredTextSourceFactory,\n 'zope.source.rest')\n ztapi.browserView(IReStructuredTextSource, '',\n ReStructuredTextToHTMLRenderer)\n # Cheat and register the ReST factory for STX as well.\n ztapi.provideUtility(IFactory, ReStructuredTextSourceFactory,\n 'zope.source.stx')\n\n # Register ++apidoc++ namespace\n from zope.app.apidoc.apidoc import apidocNamespace\n from zope.traversing.interfaces import ITraversable\n ztapi.provideAdapter(None, ITraversable, apidocNamespace, name=\"apidoc\")\n ztapi.provideView(None, None, ITraversable, \"apidoc\", apidocNamespace)\n\n # Register ++apidoc++ namespace\n from zope.traversing.namespace import view\n from zope.traversing.interfaces import ITraversable\n ztapi.provideAdapter(None, ITraversable, view, name=\"view\")\n ztapi.provideView(None, None, ITraversable, \"view\", view)\n\n context = xmlconfig.string(meta)\n\n # Fix up path for tests.\n global old_context\n old_context = zope.app.appsetup.appsetup.__config_context\n zope.app.appsetup.appsetup.__config_context = context\n\n # Fix up path for tests.\n global old_source_file\n old_source_file = zope.app.appsetup.appsetup.__config_source\n zope.app.appsetup.appsetup.__config_source = os.path.join(\n os.path.dirname(zope.app.zcmlfiles.__file__), 'meta.zcml')\n\n # Register the index.html view for codemodule.class_.Class\n from zope.publisher.browser import BrowserView\n from zope.app.apidoc.codemodule.class_ import Class\n from zope.app.apidoc.codemodule.browser.class_ import ClassDetails\n class Details(ClassDetails, BrowserView):\n pass\n ztapi.browserView(Class, 'index.html', Details)\n\n\ndef tearDown(test):\n setup.placefulTearDown()\n global old_context, old_source_file\n zope.app.appsetup.appsetup.__config_context = old_context\n zope.app.appsetup.appsetup.__config_source = old_source_file\n\n\nclass CodeModuleTests(BrowserTestCase):\n \"\"\"Just a couple of tests ensuring that the templates render.\"\"\"\n\n def testMenu(self):\n response = self.publish('/++apidoc++/Code/menu.html',\n basic='mgr:mgrpw')\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.assert_(body.find('Zope Source') > 0)\n self.checkForBrokenLinks(body, '/++apidoc++/Code/menu.html',\n basic='mgr:mgrpw')\n\n def testMenuCodeFinder(self):\n response = self.publish('/++apidoc++/Code/menu.html',\n basic='mgr:mgrpw',\n form={'path': 'Code', 'SUBMIT': 'Find'})\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.assert_(\n body.find('zope.app.apidoc.codemodule.codemodule.CodeModule') > 0)\n self.checkForBrokenLinks(body, '/++apidoc++/Code/menu.html',\n basic='mgr:mgrpw')\n\n def testModuleDetailsView(self):\n response = self.publish('/++apidoc++/Code/zope/app/apidoc/apidoc',\n basic='mgr:mgrpw')\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.assert_(body.find('Zope 3 API Documentation') > 0)\n self.checkForBrokenLinks(\n body, '/++apidoc++/Code/zope/app/apidoc/apidoc', basic='mgr:mgrpw')\n\n def testClassDetailsView(self):\n response = self.publish(\n '/++apidoc++/Code/zope/app/apidoc/apidoc/APIDocumentation',\n basic='mgr:mgrpw')\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.assert_(body.find('Represent the complete API Documentation.') > 0)\n self.checkForBrokenLinks(\n body, '/++apidoc++/Code/zope/app/apidoc/apidoc/APIDocumentation',\n basic='mgr:mgrpw')\n\n def testFunctionDetailsView(self):\n response = self.publish(\n '/++apidoc++/Code/zope/app/apidoc/apidoc/handleNamespace',\n basic='mgr:mgrpw')\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.assert_(body.find('handleNamespace(ob, name)') > 0)\n self.checkForBrokenLinks(\n body, '/++apidoc++/Code/zope/app/apidoc/apidoc/handleNamesapce',\n basic='mgr:mgrpw')\n\n def testTextFileDetailsView(self):\n response = self.publish(\n '/++apidoc++/Code/zope/app/apidoc/README.txt/index.html',\n basic='mgr:mgrpw')\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.checkForBrokenLinks(\n body, '/++apidoc++/Code/zope/app/apidoc/README.txt/index.html',\n basic='mgr:mgrpw')\n\n def testZCMLFileDetailsView(self):\n response = self.publish(\n '/++apidoc++/Code/zope/app/apidoc/configure.zcml/index.html',\n basic='mgr:mgrpw')\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.checkForBrokenLinks(\n body, '/++apidoc++/Code/zope/app/apidoc/configure.zcml/index.html',\n basic='mgr:mgrpw')\n\n\ndef test_suite():\n checker = renormalizing.RENormalizing([\n (re.compile(r\" with base 10: 'text'\"), r': text'),\n ])\n CodeModuleTests.layer = APIDocLayer\n introspector = FunctionalDocFileSuite(\n \"introspector.txt\",\n optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE)\n introspector.layer = APIDocLayer\n return unittest.TestSuite((\n doctest.DocFileSuite(\n 'README.txt',\n setUp=setUp, tearDown=tearDown,checker=checker,\n optionflags=doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS),\n doctest.DocTestSuite(\n 'zope.app.apidoc.codemodule.browser.menu',\n setUp=setUp, tearDown=tearDown,\n optionflags=doctest.NORMALIZE_WHITESPACE),\n unittest.makeSuite(CodeModuleTests),\n introspector,\n ))\n\nif __name__ == '__main__':\n unittest.main(default=\"test_suite\")\n","sub_path":"src/zope/app/apidoc/codemodule/browser/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":9140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"607126024","text":"#!/usr/bin/python3\n\ndef main():\n with open(\"dict.txt\", \"w\") as f:\n for i in range(0, 1000000):\n len_for_i = len( str(i) );\n if len_for_i != 6:\n new_i = \"0\" * (6-len_for_i) + str(i);\n f.write(new_i + \"\\n\");\n else:\n f.write(str(i) + \"\\n\");\n\nmain();\n","sub_path":"数字相关字典/digital-dict-generator.py","file_name":"digital-dict-generator.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"56978588","text":"# encoding: utf-8\n\"\"\"\n@author : zhirui zhou\n@contact: evilpsycho42@gmail.com\n@time : 2020/4/3 14:33\n\"\"\"\nimport torch\nimport copy\nimport numpy as np\n\n\nclass TimeSeries:\n\n def __init__(self, values, idx_map=None):\n \"\"\"\n\n Args:\n values: shape(N, dim, seq)\n idx_map: dict\n \"\"\"\n assert isinstance(values, np.ndarray)\n assert len(values.shape) == 3\n self.values = values\n self.idx_map = idx_map\n\n def read_batch(self, series_idx, time_idx, seq_last):\n \"\"\"\n Args:\n series_idx: shape(I)\n time_idx: shape(J, seq)\n seq_last(bool)\n\n Returns:\n shape(batch, dim, seq)\n \"\"\"\n if self.idx_map is not None:\n series_idx = np.array([self.idx_map[i] for i in series_idx])\n batch_size = series_idx.shape[0] * time_idx.shape[0]\n seq_len = time_idx.shape[1]\n if seq_last:\n dim = self.values.shape[1]\n batch = self.values[series_idx][:, :, time_idx].transpose(0, 2, 1, 3).reshape(batch_size, dim, seq_len)\n else:\n dim = self.values.shape[2]\n batch = self.values[series_idx][:, time_idx].reshape(batch_size, seq_len, dim)\n return batch\n\n\nclass Property:\n\n def __init__(self, values, idx_map=None):\n \"\"\"\n\n Args:\n values (np.ndarray): shape(N, dim)\n idx_map: dict\n \"\"\"\n self.values = values\n self.idx_map = idx_map\n\n def read_batch(self, series_idx, time_idx, seq_last):\n \"\"\"\n\n Args:\n series_idx: shape(J)\n time_idx: (I, seq)\n seq_last(bool)\n\n Returns:\n shape(N, dim, seq)\n \"\"\"\n if self.idx_map is not None:\n series_idx = np.array([self.idx_map[i] for i in series_idx])\n if seq_last:\n batch = np.repeat(np.expand_dims(self.values[series_idx], axis=2), time_idx.shape[1], axis=2)\n else:\n batch = np.repeat(np.expand_dims(self.values[series_idx], axis=1), time_idx.shape[1], axis=1)\n return batch\n\n\nclass FeatureStore:\n\n def __init__(self, features=None):\n self.features = features\n\n def read_batch(self, series_idx, time_idx, seq_last):\n if self.features is None:\n return None\n else:\n if seq_last:\n batch = np.concatenate([f.read_batch(series_idx, time_idx, seq_last) for f in self.features], axis=1)\n else:\n batch = np.concatenate([f.read_batch(series_idx, time_idx, seq_last) for f in self.features], axis=2)\n return batch\n\n\nclass Seq2SeqDataLoader:\n\n def __init__(self, xy, batch_size, enc_lens, dec_lens, use_cuda=False, weights=None,\n time_free_space=0, time_interval=1, mode=\"train\", drop_last=False, seq_last=True,\n enc_num_feats=None, dec_num_feats=None, enc_cat_feats=None, dec_cat_feats=None, random_seed=42):\n self.xy = xy\n self.series_size = xy.values.shape[0]\n self.series_idx = np.arange(xy.values.shape[0])\n self.time_dim = 2 if seq_last else 1\n self.time_size = xy.values.shape[self.time_dim]\n self.time_idx = np.arange(xy.values.shape[self.time_dim])\n self.batch_size = batch_size\n self.enc_lens = enc_lens\n self.dec_lens = dec_lens\n self.seq_last = seq_last\n\n self.use_cuda = use_cuda\n self._time_free_space = time_free_space\n self.time_interval = time_interval\n self.mode = mode\n self.drop_last = drop_last\n\n self.weights = FeatureStore([weights]) if weights is not None else None\n self.enc_num_feats = FeatureStore(enc_num_feats)\n self.dec_num_feats = FeatureStore(dec_num_feats)\n self.enc_cat_feats = FeatureStore(enc_cat_feats)\n self.dec_cat_feats = FeatureStore(dec_cat_feats)\n self.random = np.random.RandomState(random_seed)\n\n @property\n def time_free_space(self):\n if self.mode == \"train\": return self._time_free_space\n else: return 0\n\n def get_time_free(self):\n if self.time_free_space == 0: return 0\n else: return self.random.randint(-self.time_free_space, self.time_free_space)\n\n @property\n def val_time_start_idx(self):\n return self.time_idx[:-self.dec_lens-self.enc_lens-self.time_free_space*2+1][::self.time_interval]\n\n def __len__(self):\n \"\"\" return num batch in one epoch\"\"\"\n if self.series_size == 1:\n size = len(self.val_time_start_idx) // self.batch_size\n if len(size) % self.batch_size == 0 or self.drop_last:\n return size // self.batch_size\n else:\n return size // self.batch_size + 1\n else:\n if self.drop_last or self.series_size % self.batch_size == 0:\n return self.series_size // self.batch_size\n else:\n return self.series_size // self.batch_size + 1\n\n def __iter__(self):\n if self.series_size == 1:\n series_idx = np.array([0])\n time_idx = copy.copy(self.val_time_start_idx)\n if self.mode == \"train\": self.random.shuffle(time_idx)\n for i in range(len(self)):\n batch_start = time_idx[i * self.batch_size: (i + 1) * self.batch_size]\n enc_len = self.enc_lens + self.get_time_free()\n dec_len = self.dec_lens + self.get_time_free()\n enc_time_idx, dec_time_idx = [], []\n for start in batch_start:\n enc_time_idx.append(np.arange(start, start + enc_len))\n dec_time_idx.append(np.arange(start + enc_len, start + enc_len + dec_len))\n enc_time_idx = np.stack(enc_time_idx, 0)\n dec_time_idx = np.stack(dec_time_idx, 0)\n yield self.read_batch(series_idx, enc_time_idx, dec_time_idx)\n else:\n series_idx = copy.copy(self.series_idx)\n time_idx = copy.copy(self.val_time_start_idx)\n if self.mode == \"train\": self.random.shuffle(series_idx)\n for i in range(len(self)):\n start = self.random.choice(time_idx)\n enc_len = self.enc_lens + self.get_time_free()\n dec_len = self.dec_lens + self.get_time_free()\n enc_time_idx = np.stack([np.arange(start, start + enc_len)], 0)\n dec_time_idx = np.stack([np.arange(start + enc_len, start + enc_len + dec_len)], 0)\n batch_series_idx = series_idx[i * self.batch_size: (i + 1) * self.batch_size]\n yield self.read_batch(batch_series_idx, enc_time_idx, dec_time_idx)\n\n def read_batch(self, batch_series_idx, enc_time_idx, dec_time_idx):\n\n dec_len = dec_time_idx.shape[1]\n enc_x = self.xy.read_batch(batch_series_idx, enc_time_idx, self.seq_last)\n feed_dict = {\n \"enc_x\": self.check_to_tensor(enc_x, 'float32'),\n \"enc_num\": self.check_to_tensor(\n self.enc_num_feats.read_batch(batch_series_idx, enc_time_idx, self.seq_last), 'float32'),\n \"enc_cat\": self.check_to_tensor(\n self.enc_cat_feats.read_batch(batch_series_idx, enc_time_idx, self.seq_last), 'int64'),\n \"dec_num\": self.check_to_tensor(\n self.dec_num_feats.read_batch(batch_series_idx, dec_time_idx, self.seq_last), 'float32'),\n \"dec_cat\": self.check_to_tensor(\n self.dec_cat_feats.read_batch(batch_series_idx, dec_time_idx, self.seq_last), 'int64'),\n \"dec_len\": dec_len\n }\n\n if self.mode != \"test\":\n dec_x = self.xy.read_batch(batch_series_idx, dec_time_idx, self.seq_last)\n if self.weights is not None:\n weights = self.weights.read_batch(batch_series_idx, dec_time_idx, self.seq_last)\n return feed_dict, self.check_to_tensor(dec_x, 'float32'), self.check_to_tensor(weights, 'float32')\n else:\n return feed_dict, self.check_to_tensor(dec_x, 'float32').float(), None\n else:\n return feed_dict\n\n def cuda(self):\n self.use_cuda = True\n return self\n\n def cpu(self):\n self.use_cuda = False\n return self\n\n def train(self):\n self.mode = 'train'\n return self\n\n def eval(self):\n self.mode = 'eval'\n return self\n\n def test(self):\n self.mode = 'test'\n return self\n\n def check_to_tensor(self, x, dtype):\n if x is None:\n return x\n x = torch.as_tensor(x)\n if dtype == 'float32':\n x = x.float()\n elif dtype == 'int64':\n x = x.long()\n if self.use_cuda:\n x = x.cuda()\n return x\n\n\ndef forward_split(time_idx, enc_len, dec_len, valid_size):\n if valid_size < 1:\n valid_size = int(len(time_idx) * valid_size)\n valid_idx = time_idx[-(valid_size + enc_len + dec_len):]\n train_idx = time_idx[:-valid_size]\n return train_idx, valid_idx\n","sub_path":"deepseries/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":9032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"90361932","text":"import pandas\nimport numpy\nimport scipy\nimport datetime\nimport logging\nimport geopandas\nfrom tqdm import tqdm\nfrom igraph import *\nfrom math import sqrt, sin, cos, pi, asin\nfrom ..utils import utils\nfrom ..core.trajectorydataframe import TrajDataFrame\nfrom ..models.markov_diary_generator import MarkovDiaryGenerator\n\n\n'''\nImplementation of STS-EPR\n\n'''\n\nclass STS_epr():\n \n \"\"\"STS-EPR model.\n \n The STS-EPR (Spatial, Temporal and Social EPR model) model of individual human mobility consists of the following mechanisms [CRP2020]_: \n \n \n **Action selection**. With probability :math:`P_{exp}=\\\\rho S^{-\\\\gamma}`, where :math:`S` is the number of distinct locations previously visited by the agent, \n the agent visits a new location (Exploration), otherwise with a complementary probability :math:`P_{ret}=1-P{exp}` it returns to a previously visited location (Return). \n At that point, the agent determines whether or not the location’s choice will be affected by the other agents; with a probability :math:`\\\\alpha`, the agent’s social contacts influence its\n movement (Social). With a complementary probability of :math:`1-\\\\alpha`, the agent’s choice is not influenced by the other agents (Individual).\n\n Parameters :math:`\\\\rho`, :math:`\\\\gamma`, and :math:`\\\\alpha=` correspond to arguments `rho`, `gamma`, and `alpha` of the constructor, respectively.\n \n After the selection of the spatial mechanism (Exploration or Return) and the social mechanism (Individual or Social) \n decides which location will be the destination of its next displacement during the **Location selection phase**.\n For an agent :math:`a`, we denote the sets containing the indices of the locations :math:`a` can explore or return, as :math:`exp_{a}` and :math:`ret_{a}`, respectively.\n\n **Individual Exploration**. If the agent :math:`a` is currently in location :math:`i`, and explores a new location without the influence of its social contacts, then the new location :math:`j \\\\neq i` is an unvisited location for the agent (:math:`i \\\\in exp_{a}`) \n and it is selected according to the gravity model with probability proportional to :math:`p_{ij} = \\\\frac{r_i r_j}{dist_{ij}^2}`, where :math:`r_{i (j)}` is the location's relevance, that is, the probability of a population to visit location :math:`i(j)`, :math:`dist_{ij}` is the geographic distance between :math:`i` and :math:`j`, \n The number of distinct locations visited, :math:`S`, is increased by 1.\n\n **Social Exploration**. If the agent :math:`a` is currently in location :math:`i`, and explores a new location with the influence of a social contact, it first selects a social contact :math:`c` \n with probability :math:`p(c) \\\\propto mob_{sim}(a,c)` [THSG2015]_. At this point, the agent :math:`a` explores an unvisited location for agent :math:`a` that was visited by agent :math:`c`, i.e., the location :math:`j \\\\neq i` is selected\n from set :math:`A = exp_a \\\\cap ret_c`; the probability :math:`p(j)` for a location :math:`j \\\\in A`, to be selected is proportional to :math:`\\Pi_j = f_j`, where :math:`f_j` is the visitation frequency of location :math:`j` for the agent :math:`c`. The number of distinct locations visited, :math:`S`, is increased by 1. \n\n **Individual Return**. If the agent :math:`a`, currently at location :math:`i`, returns to a previously visited location :math:`j \\\\in ret_a`, it is chosen with probability \n proportional to the number of time the agent visited :math:`j`, i.e., :math:`\\Pi_j = f_j`, where :math:`f_j` is the visitation frequency of location :math:`j`.\n\n **Social Return**. If the agent :math:`a` is currently in location :math:`i`, and returns to a previously visited location with the influence of a social contact, it first selects a social contact :math:`c` \n with probability :math:`p(c) \\\\propto mob_{sim}(a,c)` [THSG2015]_. At this point, the agent :math:`a` returns to a previously visited location for agent :math:`a` that was visited by agent :math:`c` too, i.e., the location :math:`j \\\\neq i` is selected\n from set :math:`A = ret_a \\\\cap ret_c`; the probability :math:`p(j)` for a location :math:`j \\\\in A`, to be selected is proportional to :math:`\\Pi_j = f_j`, where :math:`f_j` is the visitation frequency of location :math:`j` for the agent :math:`c`.\n\n \n \n parameters\n ----------\n name : str, optional\n the name of the instantiation of the STS-EPR model. The default value is \"STS-EPR\".\n rho : float, optional\n it corresponds to the parameter :math:`\\\\rho \\in (0, 1]` in the Action selection mechanism :math:`P_{exp} = \\\\rho S^{-\\gamma}` and controls the agent's tendency to explore a new location during the next move versus returning to a previously visited location. The default value is :math:`\\\\rho = 0.6` [SKWB2010]_.\n gamma : float, optional\n it corresponds to the parameter :math:`\\gamma` (:math:`\\gamma \\geq 0`) in the Action selection mechanism :math:`P_{exp} = \\\\rho S^{-\\gamma}` and controls the agent's tendency to explore a new location during the next move versus returning to a previously visited location. The default value is :math:`\\gamma=0.21` [SKWB2010]_.\n alpha : float, optional\n it corresponds to the parameter `\\\\alpha` in the Action selection mechanism and controls the influence of the social contacts for an agent during its location selection phase. The default value is :math:`\\\\alpha=0.2` [THSG2015]_.\n \n \n Attributes\n ----------\n name : str\n the name of the instantiation of the model.\n rho : float\n the input parameter :math:`\\\\rho`.\n gamma : float\n the input parameters :math:`\\gamma`.\n alpha: float\n the input parameter :math:`\\\\alpha`. \n \n References\n ----------\n .. [PSRPGB2015] Pappalardo, L., Simini, F. Rinzivillo, S., Pedreschi, D. Giannotti, F. & Barabasi, A. L. (2015) Returners and Explorers dichotomy in human mobility. Nature Communications 6, https://www.nature.com/articles/ncomms9166\n .. [PSR2016] Pappalardo, L., Simini, F. Rinzivillo, S. (2016) Human Mobility Modelling: exploration and preferential return meet the gravity model. Procedia Computer Science 83, https://www.sciencedirect.com/science/article/pii/S1877050916302216\n .. [SKWB2010] Song, C., Koren, T., Wang, P. & Barabasi, A.L. (2010) Modelling the scaling properties of human mobility. Nature Physics 6, 818-823, https://www.nature.com/articles/nphys1760\n .. [THSG2015] Toole, Jameson & Herrera-Yague, Carlos & Schneider, Christian & Gonzalez, Marta C.. (2015). Coupling Human Mobility and Social Ties. Journal of the Royal Society, Interface / the Royal Society. 12. 10.1098/rsif.2014.1128. \n .. [CRP2020] Cornacchia, Giuliano & Rossetti, Giulio & Pappalardo, Luca. (2020). Modelling Human Mobility considering Spatial,Temporal and Social Dimensions. \n .. [PS2018] Pappalardo, L. & Simini, F. (2018) Data-driven generation of spatio-temporal routines in human mobility. Data Mining and Knowledge Discovery 32, 787-829, https://link.springer.com/article/10.1007/s10618-017-0548-4\n \n See Also\n --------\n EPR, SpatialEPR, Ditras\n \"\"\"\n\n def __init__(self, name='STS-EPR', rho=0.6, gamma=0.21, alpha=0.2):\n \n self.name = name\n self.rho = rho\n self.gamma = gamma\n self.alpha = alpha\n self.agents = {}\n self.lats_lngs = []\n self.distance_matrix = None\n self.map_uid_gid = None\n \n #dicts for efficient access\n self.dict_uid_to_gid = {}\n self.dict_gid_to_uid = {}\n \n # dict_uid_to_gid and dict_gid_to_uid are used to map the user_id into a graph_id\n # where graph_id is an integer in [0, n_agents) and user_id is the id of the agent\n \n\n #return the graph_id (user_id) of an agent given its user_id (graph_id)\n def uid_2_gid(self, uid):\n return self.dict_uid_to_gid[uid]\n \n def gid_2_uid(self, gid):\n return self.dict_gid_to_uid[gid]\n \n \n '''\n Location selection methods\n - make_social_action\n - make_individual_return_action\n - make_individual_exploration_action\n \n Notation:\n - exp(x): set containing the indices of the locations x can explore \n - ret(x): set containing the indices of the locations x can return \n '''\n \n def make_social_action(self, agent, mode):\n \n ''' \n The agent A makes a social choice in the following way:\n\n 1. The agent A selects a social contact C with probability proportional to the \n mobility similarity between them\n \n 2. The candidate location to visit or explore is selected from the set composed of \n the locations visited by C (ret(C)), that are feasible according to A's action: \n - exploration: exp(A) \\intersect ret(C)\n - return: ret(A) \\intersect ret(C)\n \n 3. select one of the feasible locations (if any) with a probability proportional\n to C's visitation frequency\n '''\n \n contact_sim = []\n \n #check and update the mobility similarity of the agent's edges if 'expired'\n for ns in self.social_graph.neighbors(agent):\n eid = self.social_graph.get_eid(agent,ns)\n\n if self.social_graph.es(eid)['next_update'][0] <= self.current_date:\n #update\n lv1 = self.agents[agent]['location_vector']\n lv2 = self.agents[ns]['location_vector']\n self.social_graph.es(eid)['mobility_similarity'] = self.cosine_similarity(lv1,lv2)\n self.social_graph.es(eid)['next_update'] = self.current_date + datetime.timedelta(hours=self.dt_update_mobSim)\n\n contact_sim.append(self.social_graph.es(eid)['mobility_similarity'][0])\n\n contact_sim = numpy.array(contact_sim)\n\n if len(contact_sim)!=0:\n if numpy.sum(contact_sim)!=0:\n contact_pick = self.random_weighted_choice(contact_sim) \n else:\n contact_pick = numpy.random.randint(0, len(contact_sim))\n\n contact = [i for i in self.social_graph.neighbors(agent)][contact_pick]\n\n else:\n #no contact in the social network, can not make a social choice\n return -1\n\n # get the location vectors of the agent and contact\n location_vector_agent = self.agents[agent]['location_vector']\n location_vector_contact = self.agents[contact]['location_vector']\n\n # id_locs_feasible, a vector of indices containing all the agent's feasible location (depend on the mode)\n if mode == 'exploration':\n id_locs_feasible = numpy.where(location_vector_agent==0)[0]\n if mode == 'return':\n id_locs_feasible = numpy.where(location_vector_agent>=1)[0]\n \n # the constraint set is of the form {current_location, starting_location}\n id_locs_constrain_diary = [self.agents[agent]['current_location']]+[self.agents[agent]['home_location']]\n id_locs_feasible = [loc_id for loc_id in id_locs_feasible if loc_id not in id_locs_constrain_diary]\n \n #no location selectable for the agent in the current mode\n if len(id_locs_feasible) == 0:\n return -1\n\n id_locs_valid = id_locs_feasible\n \n #project v_location with the indices in id_locs_valid\n v_location_proj = [location_vector_contact[i] for i in id_locs_valid]\n\n if numpy.sum(v_location_proj) != 0:\n #weighted choice\n idx = self.random_weighted_choice(v_location_proj)\n location_id = id_locs_valid[idx]\n else:\n location_id = -1\n \n return location_id\n \n \n\n def make_individual_return_action(self, agent): \n \n ''' \n The agent A makes a preferential choice selecting a VISITED location \n (i.e., in ret(A)) with probability proportional to the number of visits \n to that location. \n '''\n \n v_location = self.agents[agent]['location_vector']\n \n # compute the indices of all the feasible locations for the agent A (the visited ones)\n id_locs_feasible = numpy.where(v_location>=1)[0]\n \n # the constraint set is of the form {current_location, starting_location}\n id_locs_constrain_diary = [self.agents[agent]['current_location']]+[self.agents[agent]['home_location']]\n \n id_locs_feasible = [loc_id for loc_id in id_locs_feasible if loc_id not in id_locs_constrain_diary ]\n #id_locs_valid = id_locs_feasible\n \n if len(id_locs_feasible)==0:\n #no location selectable for the agent in the current mode\n return -1\n\n #project v_location with the indices in id_locs_valid\n v_location_proj = [v_location[i] for i in id_locs_feasible]\n \n idx = self.random_weighted_choice(v_location_proj)\n location_id = id_locs_feasible[idx]\n \n return location_id\n \n\n\n def make_individual_exploration_action(self, agent): \n '''\n The agent A, current at location i selects an UNVISITED location (i.e., in exp(A))\n j with probability proportional to (r_i * r_j)/ d_ij^2\n\n '''\n \n v_location = self.agents[agent]['location_vector'] \n \n # compute the indices of all the feasible locations for the agent A (the unvisited ones)\n id_locs_feasible = numpy.where(v_location==0)[0]\n \n id_locs_constrain_diary = [self.agents[agent]['current_location']]+[self.agents[agent]['home_location']]\n \n id_locs_feasible = [loc_id for loc_id in id_locs_feasible if loc_id not in id_locs_constrain_diary ]\n \n if len(id_locs_feasible) == 0:\n return -1\n \n \n src = self.agents[agent]['current_location']\n self.compute_od_row(src)\n distance_row = numpy.array((self.distance_matrix[src].todense())[0])[0]\n id_locs_valid = id_locs_feasible \n \n #this is made to avoid d/0 \n distance_row[src]=1\n \n relevance_src = self.relevances[src]\n distance_row_score = numpy.array(1/distance_row**2)\n distance_row_score = distance_row_score * self.relevances * relevance_src\n \n #avoid self return\n distance_row[src]=0\n\n v_location_proj = numpy.array([distance_row_score[i] for i in id_locs_valid])\n\n #weighted choice\n idx = self.random_weighted_choice(v_location_proj)\n location_id = id_locs_valid[idx]\n\n return location_id\n \n \n\n def random_weighted_choice(self, weights):\n \n probabilities = weights/numpy.sum(weights)\n t = numpy.random.multinomial(1, probabilities)\n pos_choice = numpy.where(t==1)[0][0]\n \n return pos_choice\n\n \n '''\n Initialization methods\n '''\n \n \n def init_agents(self):\n self.agents = {}\n \n for i in range(self.n_agents):\n agent = {\n 'ID':i,\n 'current_location':-1,\n 'home_location':-1,\n 'location_vector':numpy.array([0]*self.n_locations),\n 'S':0,\n 'alpha':self.alpha,\n 'rho':self.rho,\n 'gamma':self.gamma, \n 'time_next_move':self.start_date,\n 'dt':0,\n 'mobility_diary':None,\n 'index_mobility_diary':None\n }\n self.agents[i] = agent\n \n\n\n def init_social_graph(self, mode = 'random'):\n \n #generate a random graph\n if isinstance(mode, str):\n if mode == 'random':\n self.social_graph = (Graph.GRG(self.n_agents, 0.5).simplify())\n \n #edge list (src,dest):\n elif isinstance(mode, list): \n #assuming mode is a list of couple (src,dest)\n user_ids = []\n for edge in mode:\n user_ids.append(edge[0])\n user_ids.append(edge[1])\n \n user_ids = list(set(user_ids))\n graph_ids = numpy.arange(0,len(user_ids))\n \n #update the number of agents n_agents\n self.n_agents = len(user_ids)\n \n #create dicts for efficient access\n self.dict_uid_to_gid = {}\n self.dict_gid_to_uid = {}\n for j in range(len(user_ids)):\n self.dict_uid_to_gid[user_ids[j]]=graph_ids[j]\n self.dict_gid_to_uid[graph_ids[j]]=user_ids[j]\n \n #create an empty Graph and add the vertices\n self.social_graph = Graph()\n self.social_graph.add_vertices(len(user_ids))\n \n #add the edges to the graph \n for edge in mode:\n uid_src = edge[0]\n uid_dest = edge[1] \n gid_src = self.uid_2_gid(uid_src)\n gid_dest = self.uid_2_gid(uid_dest) \n e = (gid_src,gid_dest) \n self.social_graph.add_edges([e])\n \n\n \n def assign_starting_location(self, mode='uniform'):\n\n #For each agent\n for i in range(self.n_agents):\n if mode == 'uniform': \n #compute a random location\n rand_location = numpy.random.randint(0, self.n_locations)\n if mode == 'relevance':\n #random choice proportional to relevance\n p_location = self.relevances / numpy.sum(self.relevances)\n t = numpy.random.multinomial(1, p_location)\n rand_location = numpy.where(t==1)[0][0]\n\n \n #update the location vector of the user\n self.agents[i]['location_vector'][rand_location] = 1\n #set the number of unique location visited to 1 (home)\n self.agents[i]['S'] = 1\n #update currentLocation\n self.agents[i]['current_location'] = rand_location\n #set the home location\n self.agents[i]['home_location'] = rand_location\n \n #update timeNextMove \n self.agents[i]['time_next_move'] = self.agents[i]['mobility_diary'].loc[1]['datetime']\n self.agents[i]['index_mobility_diary']= 1\n self.agents[i]['dt'] = 1\n\n if self.map_ids:\n i = self.gid_2_uid(i)\n\n lat = self.lats_lngs[rand_location][0]\n lng = self.lats_lngs[rand_location][1]\n self.trajectories.append((i, lat, lng, self.current_date))\n\n \n\n def compute_mobility_similarity(self):\n #compute the mobility similarity from every connected pair of agents\n \n for edge in self.social_graph.es:\n lv1 = self.agents[edge.source]['location_vector']\n lv2 = self.agents[edge.target]['location_vector']\n self.social_graph.es(edge.index)['mobility_similarity'] = self.cosine_similarity(lv1,lv2)\n self.social_graph.es(edge.index)['next_update'] = self.current_date + datetime.timedelta(hours=self.dt_update_mobSim)\n\n\n \n def cosine_similarity(self,x,y):\n '''Cosine Similarity (x,y) = /(||x||*||y||)'''\n num = numpy.dot(x,y)\n den = numpy.linalg.norm(x)*numpy.linalg.norm(y)\n return num/den\n \n \n \n def store_tmp_movement(self, t, agent, loc, dT): \n self.tmp_upd.append({'agent':agent, 'timestamp':t, 'location':loc, 'dT':dT})\n \n\n \n def update_agent_movement_window(self, to):\n \n # take each tuple in tmp_upd and if timestamp <= to update the agent info, namely:\n # S, locationVector, current location, and trajectory\n toRemove=[]\n i=0\n\n for el in self.tmp_upd:\n if el['timestamp'] <= to:\n agent=int(el['agent'])\n\n if self.agents[agent]['location_vector'][el['location']] == 0:\n self.agents[agent]['S']+=1\n\n self.agents[agent]['location_vector'][el['location']] += 1\n #current location \n self.agents[agent]['current_location'] = el['location']\n \n if self.map_ids:\n agent = self.gid_2_uid(agent)\n \n lat = self.lats_lngs[el['location']][0]\n lng = self.lats_lngs[el['location']][1]\n self.trajectories.append((agent, lat, lng, el['timestamp']))\n toRemove.append(i)\n \n i+=1 \n #remove the updated tuples\n toRemove.reverse()\n\n for ind in toRemove:\n self.tmp_upd.pop(ind)\n \n \n\n def compute_distance_matrix(self):\n \n self.distance_matrix = numpy.zeros((len(self.spatial_tessellation),len(self.spatial_tessellation)))\n \n for i in range(0,len(self.spatial_tessellation)):\n for j in range(0,len(self.spatial_tessellation)):\n if i != j:\n d = self.distance_earth_km({'lat':self.lats_lngs[i][0],'lon':self.lats_lngs[i][1]},\n {'lat':self.lats_lngs[j][0],'lon':self.lats_lngs[j][1]})\n self.distance_matrix[i,j] = d\n \n\n \n def compute_od_row(self, row):\n \n ## if the \"row\" is already computed do nothing\n ## I test two column, say column 1 and 0: if they are both zero i'am sure that the row has to be computed\n if self.distance_matrix[row,0] != 0 or self.distance_matrix[row,1] != 0:\n return\n \n for i in range(0,len(self.spatial_tessellation)):\n if i != row:\n d = self.distance_earth_km({'lat':self.lats_lngs[i][0],'lon':self.lats_lngs[i][1]},\n {'lat':self.lats_lngs[row][0],'lon':self.lats_lngs[row][1]})\n self.distance_matrix[row,i] = d\n\n \n \n def distance_earth_km(self, src, dest):\n \n lat1, lat2 = src['lat']*pi/180, dest['lat']*pi/180\n lon1, lon2 = src['lon']*pi/180, dest['lon']*pi/180\n dlat, dlon = lat1-lat2, lon1-lon2\n\n ds = 2 * asin(sqrt(sin(dlat/2.0) ** 2 + cos(lat1) * cos(lat2) * sin(dlon/2.0) ** 2))\n return 6371.01 * ds\n \n\n \n def init_mobility_diaries(self, hours, start_date):\n #For each agent generate a mobility diary\n for i in range(self.n_agents):\n rand_seed_diary = numpy.random.randint(0,10**6)\n diary = self.diary_generator.generate(hours, start_date, random_state=rand_seed_diary) \n #ensure mobility (at least two checkins)\n while len(diary) < 2:\n rand_seed_diary = numpy.random.randint(0,10**6)\n diary = self.diary_generator.generate(hours, start_date, random_state=rand_seed_diary) \n \n self.agents[i]['mobility_diary'] = diary\n \n\n \n def get_current_abstract_location_from_diary(self, agent):\n row = self.agents[agent]['index_mobility_diary']\n return self.agents[agent]['mobility_diary'].loc[row]['abstract_location']\n \n \n\n def confirm_action(self, agent, location_id):\n \n from_ = self.agents[agent]['current_location']\n \n self.agents[agent]['current_location'] = location_id \n self.agents[agent]['index_mobility_diary']+=1\n \n row_diary = self.agents[agent]['index_mobility_diary'] \n \n if row_diary < len(self.agents[agent]['mobility_diary']):\n self.agents[agent]['time_next_move'] = self.agents[agent]['mobility_diary'].loc[row_diary]['datetime']\n delta_T = self.agents[agent]['time_next_move']-self.current_date\n dT = delta_T.components[0]*24 + delta_T.components[1]\n next_move = str(self.agents[agent]['time_next_move'])\n else:\n self.agents[agent]['time_next_move'] = self.end_date + datetime.timedelta(hours=1)\n dT = 1\n next_move = \"None\"\n \n self.agents[agent]['dt'] = dT \n self.store_tmp_movement(self.current_date, agent, location_id, dT)\n \n return {'from':from_, 'to': location_id, 'next_move':next_move}\n\n \n \n def action_correction_diary(self, agent, choice):\n \n ''' \n The implementation of the action-correction phase, executed by an agent if\n the location selection phase does not allow movements in any location \n '''\n corrections=[]\n \n if choice == 'social_return':\n location_id = self.make_individual_return_action(agent)\n corrections.append('individual_return')\n if location_id < 0:\n choice = 'individual_return'\n\n elif choice == 'social_exploration':\n location_id = self.make_individual_exploration_action(agent)\n corrections.append('individual_exploration')\n if location_id < 0:\n choice = 'individual_exploration'\n\n if choice == 'individual_return':\n location_id = self.make_individual_exploration_action(agent)\n corrections.append('individual_exploration')\n\n elif choice == 'individual_exploration':\n location_id = self.make_individual_return_action(agent)\n corrections.append('individual_return')\n \n return location_id, corrections\n \n \n\n def init_spatial_tessellation(self, spatial_tessellation, relevance_column, min_relevance):\n\n if type(spatial_tessellation) == pandas.DataFrame:\n if len(spatial_tessellation)<3:\n raise ValueError(\"Argument `spatial_tessellation` must contain at least 3 tiles.\")\n self.n_locations = len(spatial_tessellation)\n self.spatial_tessellation = spatial_tessellation\n g=[]\n for i in range(len(spatial_tessellation)):\n lat_ = spatial_tessellation.iloc[i].latitude\n lng_ = spatial_tessellation.iloc[i].longitude\n g.append([lat_,lng_])\n self.lats_lngs = numpy.array(g)\n\n elif type(spatial_tessellation) == geopandas.GeoDataFrame:\n if len(spatial_tessellation)<3:\n raise ValueError(\"Argument `spatial_tessellation` must contain at least 3 tiles.\")\n self.n_locations = len(spatial_tessellation)\n self.spatial_tessellation = spatial_tessellation\n self.lats_lngs = self.spatial_tessellation.geometry.apply(utils.get_geom_centroid, args=[True]).values\n else:\n raise TypeError(\"Argument `spatial_tessellation` should be of type pandas.DataFrame or geopandas.GeoDataFrame.\")\n\n if list(self.spatial_tessellation.columns).count(relevance_column) == 0:\n raise IndexError(\"the column `relevance_columns` is invalid\")\n\n self.relevances = numpy.array(self.spatial_tessellation[relevance_column])\n\n #map relevance 0 in min_rel \n self.relevances = numpy.where(self.relevances == 0, min_relevance, self.relevances)\n\n\n\n def init_agents_and_graph(self, social_graph):\n\n if isinstance(social_graph, str):\n if social_graph == 'random': \n self.map_ids = False\n self.init_agents()\n self.init_mobility_diaries(self.total_h, self.start_date)\n self.assign_starting_location(mode = self.starting_locations_mode)\n self.init_social_graph(mode = social_graph)\n self.compute_mobility_similarity()\n else:\n raise ValueError(\"When the argument `social_graph` is a str it must be 'random'.\")\n\n #in this case the parameter n_agents is inferred from the edge list \n elif isinstance(social_graph, list):\n if len(social_graph)>0:\n self.map_ids = True\n self.init_social_graph(mode = social_graph) \n self.init_agents()\n self.init_mobility_diaries(self.total_h, self.start_date)\n self.assign_starting_location(mode = self.starting_locations_mode)\n self.compute_mobility_similarity()\n else:\n raise ValueError(\"The argument `social_graph` cannot be an empty list.\")\n else:\n raise TypeError(\"Argument `social_graph` should be a string or a list.\")\n \n\n \n def generate(self, start_date, end_date, spatial_tessellation, diary_generator,\n social_graph='random', n_agents=500, rsl=False, distance_matrix=None, \n relevance_column=None, min_relevance = 0.1, dt_update_mobSim = 24*7, \n indipendency_window = 0.5, random_state=None, log_file=None, verbose=0,\n show_progress=False): \n\n \"\"\"\n Start the simulation of a set of agents at time `start_date` till time `end_date`.\n \n Parameters\n ----------\n start_date : datetime\n the starting date of the simulation, in \"YYY/mm/dd HH:MM:SS\" format.\n end_date : datetime\n the ending date of the simulation, in \"YYY/mm/dd HH:MM:SS\" format.\n spatial_tessellation : pandas DataFrame or geopandas GeoDataFrame\n the spatial tessellation, i.e., a division of the territory in locations.\n diary_generator : MarkovDiaryGenerator\n the diary generator to use for generating the mobility diary [PS2018]_.\n social_graph : \"random\" or an edge list\n the social graph describing the sociality of the agents. The default is \"random\". \n n_agents : int, optional\n the number of agents to generate. If `social_graph` is \"random\", `n_agents` are initialized and connected, otherwise the number of agents is inferred from the edge list. The default is 500. \n rsl: bool, optional\n if Truen the probability :math:`p(i)` for an agent of being assigned to a starting physical location :math:`i` is proportional to the relevance of location :math:`i`; otherwise, if False, it is selected uniformly at random. The defailt is False.\n distance_matrix: numpy array or None, optional\n the origin destination matrix to use for deciding the movements of the agent. If None, it is computed “on the fly” during the simulation. The default is None.\n relevance_column: str, optional\n the name of the column in spatial_tessellation to use as relevance variable. The default is “relevance”.\n min_relevance: float, optional\n the value in which to map the null relevance. The default is 0.1.\n random_state : int or None, optional\n if int, it is the seed used by the random number generator; if None, the random number generator is the RandomState instance used by np.random and random.random. The default is None. \n dt_update_mobSim: float, optional\n the time interval (in hours) that specifies how often to update the weights of the social graph. The default is 24*7=168 (one week).\n indipendency_window: float, optional\n the time window (in hours) that must elapse before an agent's movements can affect the movements of other agents in the simulation. The default is 0.5.\n log_file : str or None, optional\n the name of the file where to write a log of the execution of the model. The logfile will contain all decisions made by the model. The default is None.\n verbose: int, optional\n the verbosity level of the model relative to the standard output. If `verbose` is equal to 2 the initialization info and the decisions made by the model are printed, if `verbose` is equal to 1 only the initialization info are reported. The default is 0.\n show_progress : boolean, optional\n if True, show a progress bar. The default is False.\n \n Returns\n -------\n TrajDataFrame\n the synthetic trajectories generated by the model\n \"\"\"\n\n \n \n # check arguments\n if n_agents<=0:\n raise ValueError(\"Argument 'n_agents' must be > 0.\")\n if start_date > end_date :\n raise ValueError(\"Argument 'start_date' must be prior to 'end_date'.\")\n if type(rsl) != bool:\n raise TypeError(\"Argument `rsl` must be a bool.\")\n\n \n \n # init data structures and parameters \n self.n_agents = n_agents\n self.tmp_upd = []\n self.trajectories = []\n self.dt_update_mobSim = dt_update_mobSim\n self.indipendency_window = indipendency_window\n self.verbose = verbose\n self.log_file = log_file\n\n if rsl: \n self.starting_locations_mode = 'relevance'\n else:\n self.starting_locations_mode = 'uniform'\n \n self.start_date, self.current_date, self.end_date = start_date, start_date, end_date\n\n \n # INITIALIZATION\n \n #if specified, fix the random seeds to guarantee the reproducibility of the simulation\n if random_state is not None:\n numpy.random.seed(random_state)\n \n #log_file\n if log_file is not None:\n self._log_file = log_file\n logging.basicConfig(format='%(message)s', filename=log_file, filemode='w', level=logging.INFO)\n \n #Mobility diary generator\n if type(diary_generator) == MarkovDiaryGenerator:\n self.diary_generator = diary_generator\n else:\n raise TypeError(\"Argument `diary_generator` should be of type skmob.models.markov_diary_generator.MarkovDiaryGenerator.\")\n \n #time interval of the simulation \n delta_T = (self.end_date - self.start_date)\n self.total_h = delta_T.components[0]*24 + delta_T.components[1]\n #init. a progress bar with hourly precision\n if show_progress:\n last_t = self.start_date\n pbar = tqdm(total=self.total_h) \n elapsed_h = 0\n \n #init. the spatial tessellation\n self.init_spatial_tessellation(spatial_tessellation, relevance_column, min_relevance) \n \n #distance matrix \n if distance_matrix is not None:\n self.distance_matrix = distance_matrix\n print(\"Pre-computed matrix\")\n else:\n self.distance_matrix = scipy.sparse.lil_matrix((len(self.spatial_tessellation),len(self.spatial_tessellation)))\n \n \n #init. the agents and social graph \n self.init_agents_and_graph(social_graph)\n \n \n #log init. info\n if self.log_file is not None:\n logging.info(\"model:\\t\"+self.name)\n logging.info(\"time interval:\\t[\"+str(self.start_date)+\" - \"+str(self.end_date)+\"]\")\n logging.info(\"#agents:\\t\"+str(self.n_agents))\n logging.info(\"#locations:\\t\"+str(len(self.spatial_tessellation)))\n logging.info(\"starting locations:\\t\"+self.starting_locations_mode)\n if self.map_ids:\n logging.info(\"social graph:\\t argument\")\n else:\n logging.info(\"social graph:\\t random\")\n logging.info(\"#edges:\\t\"+str(len(self.social_graph.es)))\n logging.info(\"random state:\\t\"+str(random_state)+\"\\n\\n\")\n \n if self.verbose>0:\n print(\"Model:\\t\"+self.name)\n print(\"time interval:\\t[\"+str(self.start_date)+\" - \"+str(self.end_date)+\"]\")\n print(\"#agents:\\t\"+str(self.n_agents))\n print(\"#locations:\\t\"+str(len(self.spatial_tessellation)))\n print(\"starting locations:\\t\"+self.starting_locations_mode)\n if self.map_ids:\n print(\"social graph:\\t argument\")\n else:\n print(\"social graph:\\t random\")\n print(\"#edges:\\t\"+str(len(self.social_graph.es)))\n print(\"random state:\\t\"+str(random_state)+\"\\n\\n\")\n \n \n while self.current_date < self.end_date:\n \n # we can update all the trajectories made OUTSIDE the indipendence window. \n sup_indipendency_win = self.current_date - datetime.timedelta(hours=self.indipendency_window) \n self.update_agent_movement_window(sup_indipendency_win)\n \n min_time_next_move = self.end_date\n \n #for every agent\n #1. Select the Action it will execute (Action Selection phase)\n #2. Select the destination of its next displacement (Location Selection phase)\n #3. If the agent cannot move at any location, the action is corrected (Action Correction phase)\n \n for agent in range(self.n_agents):\n \n location_id = None\n \n #if the user is spending its visiting time do nothing \n if self.current_date != self.agents[agent]['time_next_move']:\n if self.agents[agent]['time_next_move'] < min_time_next_move:\n min_time_next_move = self.agents[agent]['time_next_move']\n continue\n \n #check the current abstract location, if it is 0 i can skip all the\n #location selection phase and return at the Home Location, otherwise \n #the abstract location is mapped to a physical one through the standard procedure \n abstract_location = self.get_current_abstract_location_from_diary(agent)\n \n #home location\n if abstract_location == 0: \n location_id = self.agents[agent]['home_location']\n \n if location_id is None: \n #compute p_exp, the probability that the agent will explore a new location \n p_exp = self.agents[agent]['rho'] * (self.agents[agent]['S'] ** -self.agents[agent]['gamma'])\n\n #generate a random number for the choice: Explore or Return respectively with probability pS^-gamma and 1-pS^-gamma \n p_rand_exp = numpy.random.rand() \n\n #generate a random number for the social or solo choice (alpha, 1-alpha)\n p_rand_soc = numpy.random.rand() \n \n p_action = ''\n else:\n p_action = 'home_return'\n \n \n # ACTION CORRECTION PHASE\n if p_action == '':\n # compute which action the agent will execute\n if p_rand_exp < p_exp:\n if p_rand_soc < self.agents[agent]['alpha']:\n choice = 'social_exploration'\n else:\n choice = 'individual_exploration'\n else:\n if p_rand_soc < self.agents[agent]['alpha']:\n choice = 'social_return'\n else:\n choice = 'individual_return' \n else:\n choice = p_action\n \n # LOCATION SELECTION PHASE\n if choice == 'social_exploration': \n location_id = self.make_social_action(agent, 'exploration')\n \n elif choice == 'individual_exploration':\n location_id = self.make_individual_exploration_action(agent)\n\n elif choice == 'social_return':\n location_id = self.make_social_action(agent, 'return')\n\n elif choice == 'individual_return':\n location_id = self.make_individual_return_action(agent)\n \n #ACTION CORRECTION PHASE\n # -1 means no selectable location\n \n corrections=None\n if location_id == -1:\n location_id, corrections = self.action_correction_diary(agent, choice) \n \n if location_id >= 0:\n info_move = self.confirm_action(agent, location_id)\n\n if self.log_file is not None:\n logging.info(\"Agent \"+str(agent))\n logging.info(\"Moved from loc. \"+str(info_move['from'])+\" to loc. \" \n +str(info_move['to'])+\" at timestamp \"\n +str(self.current_date))\n logging.info(\"Action: \"+choice)\n if corrections is None:\n logging.info(\"Corrections: None\")\n else:\n str_corr = choice\n for corr in corrections:\n str_corr+=\" -> \"+corr\n logging.info(\"Corrections: \"+str_corr)\n logging.info(\"Next move: \"+str(info_move['next_move'])+\"\\n\")\n \n if self.verbose>1:\n print(\"Agent \"+str(agent))\n print(\"Moved from loc. \"+str(info_move['from'])+\" to loc. \" \n +str(info_move['to'])+\" at timestamp \"\n +str(self.current_date))\n print(\"Action: \"+choice)\n if corrections is None:\n print(\"Corrections: None\")\n else:\n str_corr = choice\n for corr in corrections:\n str_corr+=\" -> \"+corr\n print(\"Corrections: \"+str_corr)\n print(\"Next move: \"+str(info_move['next_move'])+\"\\n\")\n else:\n #this should never happen, since n_loc>2\n raise Exception(\"Fatal error, unable to correct the location\") \n \n if self.agents[agent]['time_next_move']< min_time_next_move:\n min_time_next_move = self.agents[agent]['time_next_move']\n \n \n self.current_date = min_time_next_move\n \n if show_progress: \n dT2 = self.current_date - last_t \n if(dT2.components[0]!=0 or dT2.components[1]!=0):\n pbar.update(dT2.components[0]*24 + dT2.components[1])\n last_t = self.current_date\n elapsed_h += dT2.components[0]*24 + dT2.components[1]\n \n if show_progress:\n pbar.update(self.total_h - elapsed_h)\n pbar.close()\n \n if self.log_file is not None:\n logging.shutdown()\n \n self.update_agent_movement_window(self.end_date)\n tdf = TrajDataFrame(self.trajectories, user_id=0, latitude=1, longitude=2, datetime=3)\n tdf = tdf.sort_by_uid_and_datetime() \n return tdf\n ","sub_path":"skmob/models/sts_epr.py","file_name":"sts_epr.py","file_ext":"py","file_size_in_byte":43797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"501098992","text":"import pyrealsense2 as rs\nimport numpy as np\nimport cv2\nimport math\nimport serialtest as st\nimport time\n# Configure depth and color streams\n# Create a pipeline\npipeline = rs.pipeline()\n\n#Create a config and configure the pipeline to stream\nconfig = rs.config()\nconfig.enable_stream(rs.stream.depth, 640, 360, rs.format.z16, 30)\nconfig.enable_stream(rs.stream.color, 640, 360, rs.format.bgr8, 30)\n\n# Start streaming\nprofile = pipeline.start(config)\n\n# Getting the depth sensor's depth scale (see rs-align example for explanation)\n#Also sets up clipping_distance\ndepth_sensor = profile.get_device().first_depth_sensor()\ndepth_scale = depth_sensor.get_depth_scale()\nclipping_distance = 3 / depth_scale\n\n#Upper and lower bounds for the lines of tape\nb_lower = (90, 100, 100)\nb_upper = (110,255,200)\n\ny_lower = (25, 150, 100)\ny_upper = (30,255,255)\n\n#:reps the aligning\nalign_to = rs.stream.color\nalign = rs.align(align_to)\nangle_buf = []\n\n#High/low speed for the car\nlow_speed = 1510\nhigh_speed = 1585\n\n#Sets the starting speed, this hardly lasts, because it gets overwritten very quickly\n#st.move(str(int(1565)))\noldTime=time.time()\ntry:\n while True:\n delta=time.time()-oldTime()\n print (1/delta)\n # Wait for a coherent pair of frames: depth and color\n frames = pipeline.wait_for_frames()\n color_frame = frames.get_color_frame()\n depth_frame = frames.get_depth_frame()\n if not color_frame:\n continue\n\n #Aligns the colour frame to the depth frame, not really in use atm\n aligned_frames = align.process(frames)\n aligned_depth_frame = aligned_frames.get_depth_frame()\n \n #Converts the raw frame data into np arrays\n depth_image = np.asanyarray(aligned_depth_frame.get_data())\n color_image = np.asanyarray(color_frame.get_data())\n\n #Applies a blur to the image, probs should change this to use c2 at some point\n color_image = cv2.blur(color_image,(3,3))\n \n #Creates a copy of the color image, which we draw a bunch of stuff on. \n c2 = color_image.copy()\n\n depth_image_3d = np.dstack((depth_image,depth_image,depth_image)) #depth image is 1 channel, color is 3 channels\n\n \n #This line removes all pixels out of a set distance, not really in use.\n #c2 = np.where((depth_image_3d > clipping_distance) | (depth_image_3d <= 0), 153, c2)\n \n #Crops the top half of the image\n c2 = c2[160:320, 0:640]\n\n #Converts the remaining image from RGB to HSV\n hsv = cv2.cvtColor(c2, cv2.COLOR_BGR2HSV)\n\n #Creates masks, and then applies those masks to the image.\n y_mask = cv2.inRange(hsv, y_lower, y_upper)\n b_mask = cv2.inRange(hsv, b_lower, b_upper)\n y_result = cv2.bitwise_and(hsv, hsv, mask=y_mask)\n b_result = cv2.bitwise_and(hsv, hsv, mask=b_mask)\n\n #Runs canny edge detection on the remaining images, not really in use, but useful for some stuff\n y_edges = cv2.Canny(y_result, 300, 200)\n b_edges = cv2.Canny(b_result, 300, 200)\n\n #Combines the edges\n edges = cv2.addWeighted(y_edges, 1, b_edges, 1, 1)\n\n #Some setup for hough_lines late on, once again, not in use atm, but could be very useful for corner/straight detection.\n minLineLength = 100\n maxLineGap = 10\n\n y_lines = cv2.HoughLinesP(y_edges, 1, np.pi/180, 40, minLineLength=minLineLength, maxLineGap=maxLineGap)\n b_lines = cv2.HoughLinesP(b_edges, 1, np.pi/180, 30, minLineLength=minLineLength, maxLineGap=maxLineGap)\n\n #Finds contours in our individual images. This is what we actually use to determine our 2 points of interest.\n #hierarchy isn't in use, but if its not there, the function doesn't work.\n b_contours, hierarchy = cv2.findContours(cv2.cvtColor(b_result, cv2.COLOR_BGR2GRAY), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n y_contours, hierarchy = cv2.findContours(cv2.cvtColor(y_result, cv2.COLOR_BGR2GRAY), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n \n ##################################################################################################################\n #The below is no longer in use, but it is what we used to determine where the lines are. It doesn't work spectacularly well, but could come in handy later.\n \n # depth_intrin = depth_frame.profile.as_video_stream_profile().intrinsics\n # y_deg = 0\n # x_deg = 0\n # try:\n # a = None\n # c = 100000\n # for a in y_lines:\n # for x1,y1,x2,y2 in a:\n # if y1 < c:\n # c = y1\n # a = b\n # #cv2.line(c2,(x1,y1),(x2,y2),(0,255,0),2)\n # for x1,y1,x2,y2 in a:\n # #cv2.line(c2,(x1,y1),(x2,y2),(0,0,255),2)\n # angle = math.atan2( (y2 - y1), (x2 - x1))\n # y_deg = math.degrees(angle) \n # except:\n # print(\"No yellow\")\n\n # try:\n # a = None\n # c = 0\n # for b in b_lines:\n # for x1,y1,x2,y2 in b:\n # if y1 > c:\n # c = x1\n # a = b\n # #cv2.line(c2,(x1,y1),(x2,y2),(0,255,0),2)\n # for x1,y1,x2,y2 in a:\n # #\\cv2.line(c2,(x1,y1),(x2,y2),(0,0,255),2)\n # angle = math.atan2((y2 - y1), (x2 - x1))\n # x_deg = math.degrees(angle) \n # except:\n # print(\"No blue\")\n\n # if x_deg is not 0 and y_deg is not 0:\n # angle_buf.append((y_deg+x_deg)/2)\n # if len(angle_buf) > 20:\n # angle_buf.pop(0)\n\n\n ########################################################################################\n # This is the actually important stuff. \n # The code below finds the lowest point in contours (by y value of the pixel) on each image (yellow/blue).\n # Also draws them\n # This could use some improvment.\n\n\n b_y = -1\n\n if(b_contours):\n lowest_point = 0\n p = -1\n q = -1\n for i in range(len(b_contours)):\n if len(b_contours[i]) < 20:\n continue\n for f in range(len(b_contours[i])):\n if b_contours[i][f][0][1] > lowest_point:\n lowest_point = b_contours[i][f][0][1]\n p = i\n q = f\n\n cv2.circle(c2, (b_contours[p][q][0][0], b_contours[p][q][0][1]), 4, (0, 255, 255))\n b_y = b_contours[p][q][0][1]\n \n y_y = -1\n \n if(y_contours):\n lowest_point = 0\n p = -1\n q = -1\n for i in range(len(y_contours)):\n if len(y_contours[i]) < 20:\n continue\n for f in range(len(y_contours[i])):\n if y_contours[i][f][0][1] > lowest_point:\n lowest_point = y_contours[i][f][0][1]\n p = i\n q = f\n\n cv2.circle(c2, (y_contours[p][q][0][0], y_contours[p][q][0][1]), 4, (255, 0, 255))\n y_y = y_contours[p][q][0][1]\n\n ########################################################################################\n # This is the part where we actually decide things.\n \n # Simply subtracts the height of the blue pixel from the yellow pixel.\n # Multiplier is arbitrary.\n temp = (b_y - y_y) * 0.3\n\n # Centers the difference on 90 degrees\n angle = 90 - temp\n\n #Full lock cases.\n if angle > 135:\n angle = 135\n elif angle < 45:\n angle = 45\n\n # Very rudimentary straightness formula, but basically, the more straight the wheels are, the more zoom zoom\n # This is not great, as we need to slow before we start turning, and start speeding up when straightening.\n straightness = 1 - (abs(angle-90) / 45)\n speed = low_speed + (high_speed - low_speed) * straightness\n \n #This is for safety, should never actually be invoked.\n if speed > high_speed:\n speed = high_speed\n elif speed < low_speed:\n speed = low_speed\n\n st.move(str(int(round(angle))))\n st.move(str(1565))\n\n #If we can't see either line, don't move.\n #This is rudimentary and needs work.\n # if b_y == -1 and y_y == -1:\n ## pass\n # st.move(str(1650))\n # else:\n # st.move(str(int(round(speed))))\n\n # Show various images, don't uncomment these when this is on the board, as it has a headless version of opencv, and doesn't suppport them.\n # Uncomment waitKey when you're using these.\n # The best ones to show are ('Color', c2) and ('Edges', edges) \n\n #cv2.namedWindow('RealSense', cv2.WINDOW_AUTOSIZE)\n #cv2.imshow('Edges', edges)\n cv2.imshow('Color', c2)\n #cv2.imshow('mask', o)\n #cv2.imshow('asdd', depth_colormap)\n cv2.waitKey(1)\n\nfinally:\n\n # Stop streaming\n pipeline.stop() \n","sub_path":"old/see.py","file_name":"see.py","file_ext":"py","file_size_in_byte":9209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"145736864","text":"'''\nMIT License\n\nCopyright (c) 2017 Grok\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n'''\n\nimport discord\nimport random\nimport io\nfrom discord.ext import commands\nfrom datetime import date\nfrom enum import Enum\nfrom urllib.request import urlopen\nfrom PIL import Image\n\nhalloween = date(2018, 10, 31)\nchristmas = date(2017, 12, 25)\n\nclass RPSLS(Enum):\n rock = \"\\N{RAISED FIST}\"\n paper = \"\\N{RAISED HAND WITH FINGERS SPLAYED}\"\n scissors = \"\\N{BLACK SCISSORS}\"\n lizard = \"\\N{LIZARD}\"\n spock = \"\\N{RAISED HAND WITH PART BETWEEN MIDDLE AND RING FINGERS}\"\n\n\nclass RPSLSParser:\n def __init__(self, argument):\n argument = argument.lower()\n if argument == \"rock\":\n self.choice = RPSLS.rock\n elif argument == \"paper\":\n self.choice = RPSLS.paper\n elif argument == \"scissors\":\n self.choice = RPSLS.scissors\n elif argument == \"lizard\":\n self.choice = RPSLS.lizard\n elif argument == \"spock\":\n self.choice = RPSLS.spock\n else:\n raise\n\n\nclass Misc:\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command()\n async def invite(self, ctx):\n '''Official url to invite bot to your guild.'''\n inviter = discord.utils.oauth_url(self.bot.user.id, permissions=discord.Permissions(permissions=473295983))\n await ctx.send(f'Invite me to *__your__* guild with this link: \\n\\n<{inviter}>')\n\n @commands.command()\n async def reverse(self, ctx, *, msg: str = None):\n '''Writes backwards because reasons, in Embed.'''\n e = discord.Embed()\n e.colour = discord.Colour(0x8e44ad)\n if msg is None:\n usage = 'Write a message after command'\n e.description = usage\n else:\n e.description = f'\\N{LEFTWARDS BLACK ARROW} `{msg.lower()[::-1]}`'\n await ctx.send(embed=e)\n await ctx.delete_message(msg)\n\n @commands.command(aliases=['dvwl'])\n async def devowel(self, ctx, *, text):\n '''Removes vowels from text!'''\n dvl = text.replace('a', '').replace('A', '').replace('e', '')\\\n .replace('E', '').replace('i', '').replace('I', '')\\\n .replace('o', '').replace('O', '').replace('u', '').replace('U', '')\n e = discord.Embed()\n e.color = await ctx.get_dominant_color(ctx.author.avatar_url)\n e.set_author(name=f'{ctx.author.display_name}', icon_url=ctx.author.avatar_url)\n e.description = f'\\N{SMALL BLUE DIAMOND}​ ~~{text}~~\\n\\N{WHITE SMALL SQUARE}​ {dvl}'\n await ctx.message.delete()\n await ctx.send(embed=e)\n\n @commands.command(aliases=['thisis'])\n async def thisistisis(self, ctx, *, text):\n '''Replaces vowels with the letter \"i\", pretty useless.'''\n sis = text.replace('a', 'i').replace('A', 'I').replace('e', 'i').replace('E', 'I')\\\n .replace('o', 'i').replace('O', 'I').replace('u', 'i').replace('U', 'I')\n author = ctx.message.author\n e = discord.Embed()\n e.color = await ctx.get_dominant_color(ctx.author.avatar_url)\n e.set_author(name=f'{author.display_name}', icon_url=author.avatar_url)\n e.description = f'\\N{SMALL BLUE DIAMOND}​ ~~{text}~~\\n\\N{WHITE SMALL SQUARE}​ {sis}'\n await ctx.message.delete()\n await ctx.send(embed=e)\n\n @commands.command(aliases=['christmas', 'xmas'])\n async def isitchristmas(self, ctx):\n '''Is it Christmas yet?'''\n if date.today() == christmas:\n await ctx.send(\"Yes, it is Christmas today.\")\n else:\n msg = f'No, it is not Christmas today. There are {(christmas - date.today()).days} days until Christmas.'\n await ctx.send(msg)\n\n @commands.command(aliases=['halloween', 'hween', 'hwn'])\n async def isithalloween(self, ctx):\n '''Is it Halloween yet?'''\n if date.today() == halloween:\n await ctx.send(\"Yes, it is Halloween today.\")\n else:\n msg = f'No, it is not Halloween today. There are {(halloween - date.today()).days} days until Halloween.'\n await ctx.send(msg)\n\n\n @commands.command(aliases=['tinyurl'])\n async def tiny_url(self, ctx, str = None):\n '''Shorten URL'''\n tinyurl = urlopen(\"http://tinyurl.com/api-create.php?url=\" + str).read().decode(\"utf-8\")\n usage = f'Usage: {ctx.prefix}tinyurl https://github.com/verixx/grokbot'\n url = ctx.message.starts_with('https://')\n if str is None:\n await ctx.send(usage)\n if str is int:\n await ctx.send(usage)\n if str is url:\n await ctx.send(tinyurl)\n else:\n pass\n\n @commands.command(aliases=['qr','qrgen'])\n async def generateqr(self, ctx, *, str = None):\n '''Generate a QR code'''\n if str == None:\n await ctx.send(f\"You must include text or a link to convert to a QR code, {ctx.message.author.mention}\")\n else:\n url = f'https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl={str}&choe=UTF-8'\n with urlopen(url) as link:\n\n qrimg = io.BytesIO(link.read())\n #qrimg = Image.open(qrimgpage)\n await ctx.send(file=qrimg)\n\n @commands.command(aliases=['rock', 'paper', 'scissors', 'lizard', 'spock', 'rps'])\n async def settle(self, ctx, your_choice : RPSLSParser= None):\n '''Play rock paper scissors lizard spock '''\n if your_choice != None:\n author = ctx.message.author.display_name\n grok = self.bot.user.name\n player_choice = your_choice.choice\n available = RPSLS.rock, RPSLS.paper, RPSLS.scissors, RPSLS.lizard, RPSLS.spock\n bot_choice = random.choice((available))\n cond = {\n (RPSLS.rock, RPSLS.paper) : False,\n (RPSLS.rock, RPSLS.scissors) : True,\n (RPSLS.rock, RPSLS.lizard) : True,\n (RPSLS.rock, RPSLS.spock) : False,\n (RPSLS.paper, RPSLS.rock) : True,\n (RPSLS.paper, RPSLS.scissors) : False,\n (RPSLS.paper, RPSLS.lizard) : False,\n (RPSLS.paper, RPSLS.spock) : True,\n (RPSLS.scissors, RPSLS.rock) : False,\n (RPSLS.scissors, RPSLS.paper) : True,\n (RPSLS.scissors, RPSLS.lizard) : True,\n (RPSLS.scissors, RPSLS.spock) : False,\n (RPSLS.lizard, RPSLS.rock) : False,\n (RPSLS.lizard, RPSLS.paper) : True,\n (RPSLS.lizard, RPSLS.scissors) : False,\n (RPSLS.lizard, RPSLS.spock) : True,\n (RPSLS.spock, RPSLS.rock) : True,\n (RPSLS.spock, RPSLS.paper) : False,\n (RPSLS.spock, RPSLS.scissors) : True,\n (RPSLS.spock, RPSLS.lizard) : False\n }\n em = discord.Embed()\n em.color = await ctx.get_dominant_color(ctx.author.avatar_url)\n em.add_field(name=f'{author}', value=f'{player_choice.value}', inline=True)\n em.add_field(name=f'{grok}', value=f'{bot_choice.value}', inline=True)\n if bot_choice == player_choice:\n outcome = None\n else:\n outcome = cond[(player_choice, bot_choice)]\n if outcome is True:\n em.set_footer(text=\"You win!\")\n await ctx.send(embed=em)\n elif outcome is False:\n em.set_footer(text=\"You lose...\")\n await ctx.send(embed=em)\n else:\n em.set_footer(text=\"We're square\")\n await ctx.send(embed=em)\n else:\n msg = 'rock, paper, scissors, lizard, OR spock'\n await ctx.send(f'Enter: `{ctx.prefix}{ctx.invoked_with} {msg}`', delete_after=5)\n\n\ndef setup(bot):\n return bot.add_cog(Misc(bot))\n","sub_path":"cogs/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":9022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"514737392","text":"\"\"\"\nutils/param.py\n\nImplements `Param` object, a helper class for specifying the parameters of a\nmodel instance.\n\"\"\"\nimport os\nfrom functools import reduce\nfrom math import pi as PI\nimport torch\n\nclass Param:\n def __init__(\n self,\n beta: float = 6.0, # inverse coupling const\n lat: list = [64, 64], # lattice shape\n tau: float = 2.0, # trajectory length\n nstep: int = 50, # number of leapfrog steps\n ntraj: int = 256, # number of trajectories\n nrun: int = 4, # number of runs\n nprint: int = 256, # print freq ??\n seed: int = 11*13, # seed\n randinit: bool = False, # randomly intitialize?\n nth: int = int(os.environ.get('OMP_NUM_THREADS', '2')), # num threads\n nth_interop: int = 2, # num interop threads\n ):\n \"\"\"Parameter object for runing the Field Transformation HMC.\n\n NOTE: When running HMC, we generate configurations by the following loop:\n -----\n ```python\n field = param.initializer()\n trajectories = []\n for n in range(param.nrum):\n for i in range(param.ntraj):\n field = hmc(param, field)\n trajectories.append(field)\n ```\n \"\"\"\n self.beta = beta\n self.lat = lat\n self.nd = len(lat)\n self.volume = reduce(lambda x, y: x * y, lat)\n self.tau = tau\n self.nstep = nstep\n self.dt = self.tau / self.nstep\n self.ntraj = ntraj\n self.nrun = nrun\n self.nprint = nprint\n self.seed = seed\n self.randinit = randinit\n self.nth = nth\n self.nth_interop = nth_interop\n\n def initializer(self):\n if self.randinit:\n return torch.empty((self.nd,) + self.lat).uniform_(-PI, PI)\n else:\n return torch.zeros((self.nd,) + self.lat)\n\n def summary(self):\n status = {\n 'latsize': self.lat,\n 'volume': self.volume,\n 'beta': self.beta,\n 'trajs': self.ntraj,\n 'tau': self.tau,\n 'steps': self.nstep,\n 'seed': self.seed,\n 'nth': self.nth,\n 'nth_interop': self.nth_interop,\n }\n\n # return ', '.join('='.join((str(k), str(v))) for k, v in status.items())\n s = ', '.join('='.join((str(k), str(v))) for k, v in status.items())\n return f'{s}\\n'\n\n def uniquestr(self):\n lat = \".\".join(str(x) for x in self.lat)\n return (\n f'out_l{lat}_b{self.beta}_n{self.ntraj}'\n f'_t{self.tau}_s{self.nstep}.out'\n )\n","sub_path":"utils/param.py","file_name":"param.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"113321560","text":"# myTeam.py\n# ---------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\nimport sys\nsys.path.append('teams/Pretty Rooster/')\nfrom captureAgents import CaptureAgent\nimport random, time, util\nfrom game import Directions\nimport game\nfrom collections import defaultdict\nfrom collections import Counter\nimport math\nimport random\nimport numpy as np\n\n#################\n# Team creation #\n#################\n\n\ndef createTeam(firstIndex, secondIndex, isRed,\n first = 'HeuristicOffensiveAgent', second = 'HeuristicOffensiveAgent2'):\n \"\"\"\n This function should return a list of two agents that will form the\n team, initialized using firstIndex and secondIndex as their agent\n index numbers. isRed is True if the red team is being created, and\n will be False if the blue team is being created.\n\n As a potentially helpful development aid, this function can take\n additional string-valued keyword arguments (\"first\" and \"second\" are\n such arguments in the case of this function), which will come from\n the --redOpts and --blueOpts command-line arguments to capture.py.\n For the nightly contest, however, your team will be created without\n any extra arguments, so you should make sure that the default\n behavior is what you want for the nightly contest.\n \"\"\"\n\n # The following line is an example only; feel free to change it.\n return [eval(first)(firstIndex), eval(second)(secondIndex)]\n\ndef nullHeuristic(state):\n return 0\n\n\n##########\n# Agents #\n##########\n\nclass HeuristicAgent(CaptureAgent):\n '''\n Agent for heuristic search.\n Attributes:\n start: The start position of agent in a game\n goal: The goal position\n opponents: The opponent list\n '''\n def registerInitialState(self, gameState):\n ''' This method handles the initial setup of the agent to populate useful fields '''\n self.start = gameState.getAgentPosition(self.index)\n self.goal = []\n self.opponents = set()\n super().registerInitialState(gameState)\n\n def waStarSearch(self, gameState, heuristic, W = 2):\n '''\n WA* algorithm\n\n Args\n gameState: gameState used in Agent\n heuristic: heuristic function\n W: weight in WA*\n\n Returns\n actions: Action list\n '''\n closedList = set()\n queue = util.PriorityQueue()\n ''' In the queue, there are start states, cost, action list '''\n queue.push((gameState, 0, []), W * heuristic(gameState))\n bestCost = {}\n i = 0\n\n while not queue.isEmpty():\n (currentState, currentCost, actions) = queue.pop()\n currentPosition = currentState.getAgentPosition(self.index)\n if currentPosition not in closedList or currentPosition not in bestCost or currentCost < bestCost[currentPosition]:\n closedList.add(currentPosition)\n bestCost[currentPosition] = currentCost\n if self.isGoalState(currentState):\n #print(i)\n return actions \n legalActions = self.getLegalActions(currentState)\n i += 1\n for legalAction in legalActions:\n state = self.getSuccessor(currentState, legalAction)\n g = currentCost + 1\n h = heuristic(state)\n nextActions = actions.copy()\n nextActions.append(legalAction)\n queue.push((state, g, nextActions), g + W * h)\n return None\n\n def isGoalState(self, gameState):\n return gameState.getAgentPosition(self.index) in self.goal\n\n def getLegalActions(self, currentState):\n ''' get away from opponents '''\n legalActions = currentState.getLegalActions(self.index)\n currentPositionX, currentPositionY = currentState.getAgentPosition(self.index)\n for a in legalActions:\n dx, dy = game.Actions.directionToVector(a)\n newPosition = (currentPositionX + dx, currentPositionY + dy)\n if newPosition in self.opponents:\n legalActions.remove(a)\n return legalActions\n\n def getSuccessor(self, gameState, action):\n \"\"\"\n Finds the next successor which is a grid position (location tuple).\n \"\"\"\n successor = gameState.generateSuccessor(self.index, action)\n pos = successor.getAgentState(self.index).getPosition()\n if pos != util.nearestPoint(pos):\n # Only half a grid position was covered\n return successor.generateSuccessor(self.index, action)\n else:\n return successor\n\n def heuristicMST(self, gameState):\n '''\n MST heuristic function\n '''\n h = 0\n seletedNodes = [gameState.getAgentPosition(self.index)]\n candidateNodes = self.goal.copy()\n\n while len(candidateNodes) > 0:\n endNode, minWeight = 0, 999999\n for i in seletedNodes:\n for j in candidateNodes:\n #if util.manhattanDistance(i, j) < minWeight:\n if self.getMazeDistance(i, j) < minWeight:\n minWeight = util.manhattanDistance(i, j)\n endNode = j\n h += minWeight\n seletedNodes.append(endNode)\n candidateNodes.remove(endNode)\n return h\n\n def heuristicZero(self, gameState):\n return 0\n\n def heuristicMin(self, gameState):\n distanceToGoal = [self.getMazeDistance(gameState.getAgentPosition(self.index), eachGoal) for eachGoal in self.goal]\n return min(distanceToGoal)\n\n def heuristicMax(self, gameState):\n distanceToGoal = [self.getMazeDistance(gameState.getAgentPosition(self.index), eachGoal) for eachGoal in self.goal]\n return max(distanceToGoal)\n\n def isOnDeffenceSide(self, currentPosition, gameState):\n ''' Check if agent is on its deffensive side'''\n borderLine = gameState.data.layout.width // 2\n x, y = currentPosition\n if self.red:\n return x < borderLine\n else:\n return x >= borderLine\n\n def getSafePoints(self, gameState, safePositionX = 0):\n ''' Get the grid of valid border points on own side '''\n borderGrid = game.Grid(gameState.data.layout.width, gameState.data.layout.height)\n borderLine = gameState.data.layout.width // 2\n if self.red:\n for i in range(gameState.data.layout.height):\n safeX = 0\n if borderLine - 1 - safePositionX > safeX:\n safeX = borderLine - 1 - safePositionX\n if not gameState.getWalls()[safeX][i]:\n borderGrid[safeX][i] = True\n else:\n for i in range(gameState.data.layout.height):\n safeX = gameState.data.layout.width - 1\n if borderLine + safePositionX < safeX:\n safeX = borderLine + safePositionX\n if not gameState.getWalls()[safeX][i]:\n borderGrid[safeX][i] = True\n return borderGrid \n\n def findCloestPositionAndDistance(self, positionList, currentPosition):\n '''\n Find the cloest position to agent and distance between them\n\n Args:\n positionList: List of positions\n currentPosition: Position to start\n\n Returns:\n cloestPosition: Cloest position\n minDistance: Minimum Distance between the position and agent\n\n '''\n minDistance = 999999\n cloestPosition = None\n if len(positionList) > 0:\n for pos in positionList:\n distanceToPosition = self.getMazeDistance(currentPosition, pos)\n if distanceToPosition < minDistance:\n minDistance = distanceToPosition\n cloestPosition = pos\n return cloestPosition, minDistance\n\n def findFurthestPositionAndDistance(self, positionList, currentPosition):\n '''\n Find the furthrest position to agent and distance between them\n\n Args:\n positionList: List of position \n currentPosition: Position to start\n\n Returns:\n furthestPosition: Furthest position\n furthestDistance: Maximum Distance between the position and agent\n\n '''\n\n furthestPosition = None\n furthestDistance = 0\n if len(positionList) > 0:\n for pos in positionList:\n distanceToPosition = self.getMazeDistance(currentPosition, pos)\n if distanceToPosition > furthestDistance:\n furthestPosition = pos\n furthestDistance = distanceToPosition\n return furthestPosition, furthestDistance\n\nclass MyQueue(util.Queue):\n '''\n Queue that has capicity\n Attributes:\n capicity: The maximum capicity\n '''\n def __init__(self, capicity = 0):\n super().__init__()\n self.capicity = capicity\n\n def push(self, item):\n ''' Push 'item' onto the stack and if it is full pop it '''\n super().push(item)\n if len(self.list) > self.capicity:\n self.pop()\n\n def remove(self, item):\n ''' Remove item from list '''\n self.list.remove(item)\n\n def copyList(self):\n return self.list.copy()\n\nclass HeuristicOffensiveAgent(HeuristicAgent):\n '''\n Offence agent in heuristic search\n \n Attributes:\n safeDistance: Minimum distance to defenders is considered as safe state\n safeDistanceBehindBorder: Minimum distance to border\n safePoints: Grid of positions that is safe for agent (Grid object)\n borderPoints: Grid of positions that is on border\n beingChased: A boolean variable that record if the agent is chased\n numCapsule: Number of capsules on map\n scaredTimer: Timer after eating capsules\n safeTimer: The timer of returning escaping\n catchup: Defference between number of food I got and total score to decide coming back\n returnFood: The number of food I ate to return \n maxQueueCapicity: Maximum capicity of MyQueue \n numHistoryObserve: Number of history observed my positions\n observedDefender: MyQueue object record defender position\n observeCurrentPosition: My history position \n repeatLimit: Limit time of repeat\n returnFlag: if repeat too much, return\n minDistanceFoodStart: Start searching the food first smallest food or second smallest\n myFood: The food I am resposible to eat (only initialized at start, or changed if it is empty)\n\n '''\n def registerInitialState(self, gameState):\n super().registerInitialState(gameState)\n self.safeDistance = 4\n self.safeDistanceBehindBorder = 1\n self.safePoints = self.getSafePoints(gameState, self.safeDistanceBehindBorder)\n self.borderPoints = self.getSafePoints(gameState)\n self.beingChased = False\n self.numCapsule = len(self.getCapsules(gameState))\n self.scaredTimer = 0\n self.safeTimer = 4\n self.catchup = 3\n self.returnFood = 10\n self.maxQueueCapicity = 4\n self.observedDefender = MyQueue(self.maxQueueCapicity)\n self.numHistoryObserve = 16\n self.observeCurrentPosition = MyQueue(self.numHistoryObserve)\n self.repeatLimit = 2\n self.returnFlag = False\n self.minDistanceFoodStart = 1\n self.myFood = []\n\n def chooseAction(self, gameState):\n '''\n Choose action according to the state whether the agent is chased.\n If it is chased, use WA* back to safe points\n Otherwise, eating food until getting 18 food\n Specially, if the capsule is eaten within safe time, eat food normally\n '''\n currentPosition = util.nearestPoint(gameState.getAgentPosition(self.index))\n enemies = [gameState.getAgentState(i) for i in self.getOpponents(gameState)]\n currentObserveDefenders = [util.nearestPoint(a.getPosition()) for a in enemies if not a.isPacman and a.getPosition() != None]\n\n ''' Expected defenders position '''\n for opponentPosition in self.observedDefender.copyList():\n if opponentPosition not in currentObserveDefenders:\n self.observedDefender.remove(opponentPosition)\n for cod in currentObserveDefenders:\n self.observedDefender.push(cod)\n expectedDefenders = self.observedDefender.copyList()\n self.opponents = set(self.getDefenderBlockingPosition(gameState, expectedDefenders))\n\n ''' Observed defenders position and state within safe distance '''\n distanceToDefenders = [self.getMazeDistance(currentPosition, d) for d in currentObserveDefenders]\n cloestDefender, cloestDistanceToDefender = self.findCloestPositionAndDistance(currentObserveDefenders, currentPosition)\n if cloestDistanceToDefender > self.safeDistance:\n cloestDefender = None\n cloestDefenderState = None\n for a in enemies:\n if cloestDefender is not None and a.getPosition() == cloestDefender:\n cloestDefenderState = a\n break\n \n ''' Record current position in history '''\n self.observeCurrentPosition.push(currentPosition) \n\n if self.beingChased and cloestDefender is None or \\\n cloestDefenderState is not None and cloestDefenderState.scaredTimer > self.safeTimer:\n ''' In capsule power time '''\n self.beingChased = False\n self.opponents = set()\n\n elif (not self.beingChased and self.isReadyOffensing(gameState.getAgentPosition(self.index)) and \n cloestDefender is not None and min(distanceToDefenders) < self.safeDistance):\n self.beingChased = True\n\n #print(self.opponents)\n\n ''' counting food I ate '''\n myScore = gameState.getAgentState(self.index).numCarrying \n\n ''' Initialize returnFlag '''\n if currentPosition in self.safePoints.asList():\n self.returnFlag = False\n \n ''' Number of food left '''\n numOfFood = len(self.getFood(gameState).asList())\n\n ''' Adjust my food '''\n if currentPosition == self.start:\n distanceToFoods = self.getFoodSortedByDistance(currentPosition, gameState)\n self.myFood = [foods[0] for i, foods in enumerate(distanceToFoods) if i >= self.minDistanceFoodStart]\n self.myFood = [food for food in self.myFood if food in self.getFood(gameState).asList()]\n if len(self.myFood) == 0:\n self.myFood = self.getFood(gameState).asList()\n\n ''' Action '''\n if numOfFood < 3:\n ''' Number of food is smaller than 3 '''\n self.goal = self.borderPoints.asList()\n elif self.beingChased or self.returnFlag:\n ''' Chased by defender '''\n self.goal = self.safePoints.asList()\n self.goal.extend(self.getCapsules(gameState))\n elif self.getScore(gameState) < 0 and myScore + self.getScore(gameState) > self.catchup:\n #or myScore >= self.returnFood:\n ''' Come back if I ate a lot or I can reverse score '''\n self.goal = self.borderPoints.asList()\n else:\n positionCounter = Counter(self.observeCurrentPosition.list)\n numRepeat = positionCounter[currentPosition] - self.repeatLimit\n\n if numRepeat <= 0:\n self.goal = self.myFood\n\n elif numRepeat >= self.numHistoryObserve // 2 - self.repeatLimit or numRepeat >= numOfFood - 1:\n ''' Repeat too much and return to safe points '''\n self.goal = self.safePoints.asList()\n self.returnFlag = True\n else:\n ''' Pick another goal '''\n minStart = (self.minDistanceFoodStart + random.randint(numRepeat, numOfFood - 1)) % (numOfFood)\n distanceToFoods = self.getFoodSortedByDistance(currentPosition, gameState)\n self.goal = [foods[0] for i, foods in enumerate(distanceToFoods) if i >= minStart]\n if len(self.goal) == 0:\n self.goal = self.safePoints.asList()\n\n actions = self.waStarSearch(gameState, self.heuristicMin, 10)\n if actions is None or len(actions) == 0:\n randomActions = self.getLegalActions(gameState)\n if len(randomActions) > 1 and Directions.STOP in randomActions:\n randomActions.remove(Directions.STOP)\n return random.choice(self.getLegalActions(gameState))\n return actions[0]\n\n def isReadyOffensing(self, currentPosition):\n ''' Check if agent is about to cross border or has crossed '''\n return self.red and currentPosition[0] >= self.borderPoints.asList()[0][0] \\\n or not self.red and currentPosition[0] <= self.borderPoints.asList()[0][0]\n\n def getDefenderBlockingPosition(self, gameState, opponentsPos):\n '''\n Block position around defenders\n Args:\n opponentsPos: List of positions of defenders\n Return:\n blockingPositions: List of positions at and around defenders\n '''\n blockingPositions = opponentsPos.copy()\n for opponentX, opponentY in opponentsPos:\n for dx in range(-1, 2):\n for dy in range(-1, 2):\n if gameState.hasWall(opponentX + dx, opponentY + dy):\n continue\n blockingPositions.append((opponentX + dx, opponentY + dy))\n return blockingPositions\n\n def getFoodSortedByDistance(self, currentPosition, gameState):\n ''' Get Food sorted by distance to current position '''\n foodDistance = {}\n for food in self.getFood(gameState).asList():\n foodDistance[food] = self.getMazeDistance(currentPosition, food)\n return sorted(foodDistance.items(), key = lambda item: item[1])\n\n\nclass HeuristicOffensiveAgent2(HeuristicOffensiveAgent):\n '''\n Defence agent in heuristic search\n \n Attributes:\n safeInvaderDistance: Safe Distance to invaders\n chaseDistance: Distance to invader to chase\n\n '''\n def registerInitialState(self, gameState):\n super().registerInitialState(gameState)\n self.safeInvaderDistance = 3\n self.chaseDistance = 999999\n self.minDistanceFoodStart = 0\n\n def observationFunction(self, gameState):\n #print(gameState)\n return gameState.makeObservation(self.index)\n\n def chooseAction(self, gameState):\n '''\n Choose action of defending.\n If it see invaders, use WA* back to chase invaders\n Otherwise, Offence!!\n '''\n\n currentPosition = gameState.getAgentPosition(self.index)\n enemies = [gameState.getAgentState(i) for i in self.getOpponents(gameState)]\n invaders = [a.getPosition() for a in enemies if a.isPacman and a.getPosition() != None]\n cloestInvader, cloestDistanceToInvader = self.findCloestPositionAndDistance(invaders, currentPosition)\n nextAction = None\n\n if gameState.getAgentState(self.index).scaredTimer > 0 and cloestDistanceToInvader < self.safeInvaderDistance:\n ''' I am chased by power invader '''\n if self.red and cloestInvader[0] >= currentPosition[0] \\\n or not self.red and cloestInvader[0] <= currentPosition[0]:\n ''' Invader chases from their side '''\n self.goal = [self.start]\n else:\n self.goal = self.getFood(gameState).asList()\n actions = self.waStarSearch(gameState, self.heuristicMin, 10)\n if actions is None or len(actions) == 0:\n randomActions = self.getLegalActions(gameState)\n if len(randomActions) > 1 and Directions.STOP in randomActions:\n randomActions.remove(Directions.STOP)\n nextAction = random.choice(self.getLegalActions(gameState))\n else:\n nextAction = actions[0]\n\n elif cloestInvader is not None and cloestDistanceToInvader < self.chaseDistance:\n ''' I am chasing '''\n self.goal = [cloestInvader]\n actions = self.waStarSearch(gameState, self.heuristicMin, 10)\n if actions is None or len(actions) == 0:\n randomActions = self.getLegalActions(gameState)\n if len(randomActions) > 1 and Directions.STOP in randomActions:\n randomActions.remove(Directions.STOP)\n nextAction = random.choice(self.getLegalActions(gameState))\n else:\n nextAction = actions[0]\n\n else:\n nextAction = super().chooseAction(gameState)\n\n #print(self.getSuccessor(gameState, nextAction).isOver())\n\n return nextAction\n\nclass HeuristicDefensiveAgent(HeuristicAgent):\n '''\n Defence agent in heuristic search\n \n Attributes:\n safePosition: Safe position of defensice agent\n safeDistance: Safe Distance to invaders\n keyDefendFood: The \"key\" food I am defending\n numDefendFood: Number of food I am defending\n thresholdFood: Number of food being eaaten then start patrolling\n patrolling: Flag of patrolling\n chaseDistance: Distance to invader to chase\n\n '''\n def registerInitialState(self, gameState):\n super().registerInitialState(gameState)\n self.goal = self.getFoodYouAreDefending(gameState).asList()\n\n self.safePosition = None\n self.safeDistance = 3\n self.keyDefendFood = None\n self.numDefendFood = len(self.getFoodYouAreDefending(gameState).asList())\n self.thresholdFood = 2\n self.patrolling = False\n self.chaseDistance = 6\n\n def chooseAction(self, gameState):\n '''\n Choose action of defending.\n If it see invaders, use WA* back to chase invaders\n Otherwise, travel to center of food it is defending\n Specially, if the my capsule is eaten, back to start\n '''\n\n currentPosition = gameState.getAgentPosition(self.index)\n enemies = [gameState.getAgentState(i) for i in self.getOpponents(gameState)]\n invaders = [a.getPosition() for a in enemies if a.isPacman and a.getPosition() != None]\n cloestInvader, cloestDistanceToInvader = self.findCloestPositionAndDistance(invaders, currentPosition)\n\n\n if gameState.getAgentState(self.index).scaredTimer > 0 and cloestDistanceToInvader < self.safeDistance:\n ''' I am chased by power invader '''\n if self.red and cloestInvader[0] >= currentPosition[0] \\\n or not self.red and cloestInvader[0] <= currentPosition[0]:\n ''' Invader chases from their side '''\n self.safePosition = self.start\n else:\n safePoints = self.getSafePoints(gameState).asList()\n if self.safePosition is None or self.safePosition not in safePoints and currentPosition == self.safePosition:\n furthestPosition, furthestDistance = self.findFurthestPositionAndDistance(safePoints, currentPosition)\n self.safePosition = furthestPosition\n #print(cloestDistanceToInvader)\n self.goal = [self.safePosition]\n\n elif cloestInvader is not None:\n ''' I am chasing '''\n if cloestDistanceToInvader < self.chaseDistance and self.patrolling:\n #if self.patrolling:\n self.patrolling = False\n self.keyDefendFood = None\n #print('here')\n self.goal = [cloestInvader]\n\n else:\n ''' No one chases me and I do not observe invader '''\n if (self.keyDefendFood is None or \n self.keyDefendFood not in self.getFoodYouAreDefending(gameState).asList()):\n ''' Just start or be captured or the food is eaten by invader'''\n predictedOpponentStartPosition = (gameState.data.layout.width - 1 - self.start[0], gameState.data.layout.height - 1 - self.start[1])\n self.keyDefendFood, _ = self.findCloestPositionAndDistance(self.getFoodYouAreDefending(gameState).asList(), predictedOpponentStartPosition)\n self.numDefendFood = len(self.getFoodYouAreDefending(gameState).asList())\n self.goal = [self.keyDefendFood]\n #print('111')\n\n elif self.keyDefendFood is not None and currentPosition == self.keyDefendFood:\n ''' I have arrived the furthest food and make sure not cross the border'''\n #print('222')\n actions = gameState.getLegalActions(self.index)\n borderPoints = self.getSafePoints(gameState).asList()\n if self.red and currentPosition in borderPoints and Directions.EAST in actions:\n actions.remove(Directions.EAST)\n if not self.red and currentPosition in borderPoints and Directions.WEST in actions:\n actions.remove(Directions.WEST)\n return random.choice(actions)\n\n elif not self.patrolling and len(self.getFoodYouAreDefending(gameState).asList()) < self.numDefendFood - self.thresholdFood:\n self.keyDefendFood = self.getCenterDefendFood(gameState)\n self.patrolling = True\n self.goal = [self.keyDefendFood]\n #print('333')\n\n else:\n #print('444')\n self.goal = [self.keyDefendFood]\n #print(self.goal)\n\n actions = self.waStarSearch(gameState, self.heuristicMin, 10)\n if actions is None or len(actions) == 0:\n return Directions.STOP\n return actions[0]\n\n \n def getCenterDefendFood(self, gameState):\n ''' Get next food from food I am defending '''\n defendfoodPositions = self.getFoodYouAreDefending(gameState).asList()\n distanceToFoods = {}\n for d in defendfoodPositions:\n distanceToFoods[d] = self.getMazeDistance(gameState.getAgentPosition(self.index), d)\n distanceToFoods = sorted(distanceToFoods.items(), key = lambda item: item[1])\n return distanceToFoods[len(defendfoodPositions) // 2][0]\n \n","sub_path":"myTeam.py","file_name":"myTeam.py","file_ext":"py","file_size_in_byte":27356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"2805900","text":"def recover_secret(triplets):\n secret = []\n while triplets:\n second_and_third_letters = [letter for array in triplets for letter in array[1:]]\n for array in triplets:\n if array[0] not in second_and_third_letters:\n secret.append(array[0])\n triplets = list(map(\n lambda array: array[1:] if secret[-1] == array[0] else array, triplets))\n break\n triplets = list(filter(lambda array: bool(array), triplets))\n return ''.join(secret)\n\n\nrecoverSecret = recover_secret","sub_path":"Codewars/Recover a String From Random Triplets.py","file_name":"Recover a String From Random Triplets.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"451815608","text":"from xml.etree import ElementTree as ET\nimport os\n\nxml_path = \"/home/zmc/Documents/mAP/Annotations/\"\nxml_files = os.listdir(xml_path)\nfor file_ in xml_files:\n temp = []\n per = ET.parse(xml_path+file_)\n p = per.findall(\"./object\")\n for object in p:\n for child in object.getchildren():\n temp_info = []\n if child.tag == \"name\":\n res_name = child.text\n temp_info.append(res_name)\n elif child.tag == \"bndbox\":\n for cchild in child.getchildren():\n if cchild.tag == \"xmin\":\n xmin = \" \"+cchild.text\n temp_info.append(xmin)\n elif cchild.tag == \"ymin\":\n ymin = \" \"+cchild.text\n temp_info.append(ymin)\n elif cchild.tag == \"xmax\":\n xmax = \" \"+cchild.text\n temp_info.append(xmax)\n elif cchild.tag == \"ymax\":\n ymax = \" \"+cchild.text+\"\\n\"\n temp_info.append(ymax)\n temp.append(temp_info)\n txt_file_name = file_.split(\".\")[0]+\".txt\"\n ground_truth = open(\"./ground-truth/\"+txt_file_name, \"wr\")\n for box_info in temp:\n for info in box_info:\n ground_truth.write(info)\n ground_truth.close()\n print(\"Saving ... ...\")\nprint(\"Done ... ...\")\n","sub_path":"xml2txt.py","file_name":"xml2txt.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"340300059","text":"\"\"\"\nInstaller for PyTimber for the SWAN environment.\n\nInstalls PyTimber into a special directory and then sets the sys.path\nto point to it.\n\n\"\"\"\n# Note: This script must be run inside Python so that it can control\n# things like the sys.path\n\n_locals_before = set(locals())\n\nimport os\nimport site\nimport subprocess\nimport sys\n\n\ndef run_w_stream(cmd, env=None):\n full_env = os.environ.copy()\n full_env.update(env or {})\n print('Running: ', ' '.join(cmd))\n proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False, env=full_env)\n while not proc.poll():\n line = proc.stdout.readline()\n if line:\n sys.stdout.write(line)\n else:\n break\n # Capture any remaining stdout.\n for line in proc.stdout.readlines():\n sys.stdout.write(line)\n\ninstall_loc=os.path.join(os.environ['HOME'], 'python', 'environments', 'pytimber3')\n\n\n# Disable site.getusersitepackages so that we have non .local JARs (bad practice).\n# This doesn't prevent .local/lib from working (it would still be on the sys.path) but does\n# influence how cmmnbuild-dep-manager searches for its JARs.\n# https://gitlab.cern.ch/scripting-tools/cmmnbuild-dep-manager/-/blob/v2.4.0/cmmnbuild_dep_manager/cmmnbuild_dep_manager.py#L217\nif hasattr(site, 'getusersitepackages'):\n site.__dict__.pop('getusersitepackages')\n\n\n# Put the environment on the path:\nenv_pkgs = os.path.join(install_loc, 'lib', 'python3.6', 'site-packages')\nif sys.path[2] != env_pkgs:\n sys.path.insert(2, env_pkgs) \n \n\nif not os.path.exists(install_loc):\n print('Creating an environment in {}. This can take a while.'.format(install_loc))\n # This is quite slow on EOS, so try to not call it if we can avoid.\n cmd = [sys.executable, '-m', 'venv', install_loc, '--system-site-packages']\n run_w_stream(cmd)\n\n env_py = os.path.join(install_loc, 'bin', 'python')\n cmd = [env_py, '-m', 'pip', 'install', '--upgrade', 'pip', '--prefix={}'.format(install_loc)]\n run_w_stream(cmd)\n\n env = {'PIP_INDEX_URL': 'http://acc-py-repo.cern.ch:8081/repository/vr-py-releases/simple',\n 'PIP_TRUSTED_HOST': 'acc-py-repo.cern.ch'}\n cmd = [env_py, '-m', 'pip', 'install', 'pytimber==3.*']\n run_w_stream(cmd, env)\n \n print('Resolving JARs for PyTimber')\n import cmmnbuild_dep_manager\n cmmnbuild_dep_manager.Manager().resolve()\n print('All done!')\nelse:\n print('Using existing environment in {}'.format(install_loc))\n\n\nimport pytimber\nif not pytimber.__version__.startswith('3.'):\n print(\"Error installing newer version of PyTimber. \" +\n \"You have version {}. \".format(pytimber.__version__) +\n \"Please try restarting the kernel and re-running.\")\n\n# Tidy up since this is being run in the active kernel environment\nfor local_before in set(locals()) - _locals_before:\n locals().pop(local_before)\nlocals().pop('_local_before', None)","sub_path":"install_pytimber_swan.py","file_name":"install_pytimber_swan.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"234779271","text":"import requests\r\nimport random\r\nfrom lxml import etree\r\nimport os\r\nimport re\r\nrequests.adapters.DEFAULT_RETRIES = 5\r\nheaders = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0\"}\r\npost_url = \"http://192.168.4.253/index.php/Login/login\"\r\npost_data = [{\"username\": \"luochen\", \"password\": \"password\"}]\r\nBig_url = \"http://192.168.4.253/index.php/Study/studydetail?taskid={}\"\r\npost_data = random.choice(post_data)\r\nsession = requests.session()\r\nsession.post(post_url, data=post_data, headers=headers)\r\nfor i in range(1, 3):\r\n one_url = \"http://192.168.4.253/index.php/Study/listunderway?per_page={}\"\r\n first_data = session.get(one_url.format(i), headers=headers)\r\n\r\n html = etree.HTML(first_data.content.decode())\r\n ret = html.xpath('//div[@class=\"taskimg\"]//a/@taskid')\r\n Big_url = []\r\n for i in range(0, len(ret)):\r\n Big_url.append(\"http://192.168.4.253/index.php/Study/studydetail?taskid={}\".format(ret[i]))\r\n print(Big_url)\r\n\r\n Bigtit_list = html.xpath('//div[@class=\"taskimg\"]//a/@title')\r\n print(Bigtit_list)\r\n for Bigtit in Bigtit_list:\r\n # print(Bigtit,Bighref)\r\n if os.path.exists(Bigtit) == False: # 判断有无此文件夹\r\n os.mkdir(Bigtit)\r\n\r\n for bigurl, bigtitle in zip(Big_url, Bigtit_list):\r\n second_data = session.get(bigurl, headers=headers)\r\n html = etree.HTML(second_data.content.decode())\r\n Little_title_list = html.xpath('//p[@class=\"itemTitle\" ]//a/text()')\r\n Little_url_list = html.xpath('//p[@class=\"itemTitle\" ]//a//@href')\r\n\r\n for little_url, little_title in zip(Little_url_list, Little_title_list):\r\n vedio_page_data = session.get(little_url, headers=headers)\r\n html = etree.HTML(vedio_page_data.content.decode())\r\n vedio_url = html.xpath('//video//source/@src')\r\n if len(vedio_url) > 0:\r\n # ren = \".*?(:)*?\"\r\n little_title= re.sub(':', \" \", little_title) #替换掉标题中的冒号\r\n print(bigtitle)\r\n path = bigtitle + \"\\\\\" + little_title + \".mp4\"\r\n try:\r\n vedio_data=session.get(vedio_url[0])\r\n with open(path, 'wb') as output:\r\n while True:\r\n buffer = vedio_data.read(1024 * 256);\r\n if not buffer:\r\n break\r\n # received += len(buffer)\r\n output.write(buffer)\r\n output.close()\r\n print(little_title + \".mp4下载成功\")\r\n\r\n except Exception as e:\r\n print(e)\r\n\r\n else:\r\n try:\r\n html_data = vedio_page_data.content\r\n fail_path = bigtitle + \"\\\\\" + little_title + \".html\"\r\n with open(fail_path, \"w\",encoding=\"utf-8\") as f:\r\n f.write(html_data)\r\n f.close()\r\n print(little_title + \".html下载成功\")\r\n except Exception as e:\r\n print(e)\r\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"505380800","text":"import urlparse\n\nfrom django.contrib.auth import REDIRECT_FIELD_NAME\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.models import User\nfrom django.contrib.sites.models import get_current_site\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response, redirect\nfrom django.template import RequestContext\nfrom django.views.decorators.cache import never_cache\nfrom django.views.decorators.csrf import csrf_protect\n\nfrom forms import RegistrationForm\n\n@csrf_protect\n@never_cache\ndef signup(request, template_name='registration/signup.html',\n redirect_field_name=REDIRECT_FIELD_NAME,\n signup_form=RegistrationForm,\n current_app=None, extra_context=None):\n \"\"\"\n Displays the signup form and handles the signup action.\n This actually could be nearly identical to the generic login view,\n except it does sign up.\n \"\"\"\n\n redirect_to = request.REQUEST.get(redirect_field_name, '')\n\n if request.method == \"POST\":\n form = signup_form(data=request.POST)\n if form.is_valid():\n netloc = urlparse.urlparse(redirect_to)[1]\n\n # Light security check -- make sure redirect_to isn't garbage.\n if not redirect_to or ' ' in redirect_to:\n redirect_to = settings.LOGIN_REDIRECT_URL\n\n # Heavier security check -- don't allow redirection to a different\n # host.\n elif netloc and netloc != request.get_host():\n redirect_to = settings.LOGIN_REDIRECT_URL\n\n # Okay, security checks complete. Sign up\n # We need to use the password out of the form\n # because authenticate() requires it to be in plaintext.\n password = form.cleaned_data['password1']\n new_user = form.create_user()\n # This is required to set the auth backend.\n new_user = authenticate(username=new_user.email,\n password=password)\n # Log in the user.\n login(request, new_user)\n\n if request.session.test_cookie_worked():\n request.session.delete_test_cookie()\n\n return HttpResponseRedirect(redirect_to)\n else:\n form = signup_form()\n\n request.session.set_test_cookie()\n\n current_site = get_current_site(request)\n\n context = {\n 'form': form,\n redirect_field_name: redirect_to,\n 'site': current_site,\n 'site_name': current_site.name,\n }\n context.update(extra_context or {})\n return render_to_response(template_name, context,\n context_instance=RequestContext(request, current_app=current_app))\n\n","sub_path":"auth_utils/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"327701622","text":"import torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\nfrom torch.autograd import Variable\nimport torch.optim as optim\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn import DataParallel\nfrom gazenet import GazeNet\n\nimport time\nimport os\nimport numpy as np\nimport json\nimport cv2\nfrom PIL import Image, ImageOps\nimport random\nfrom tqdm import tqdm\nimport operator\nimport itertools\nfrom scipy.io import loadmat, savemat\nimport logging\n\nfrom scipy import signal\n\nfrom utils import data_transforms\nfrom utils import get_paste_kernel, kernel_map\n\n# log setting\nlog_dir = 'log/'\nif not os.path.exists(log_dir):\n os.makedirs(log_dir)\nlog_file = log_dir + 'test_ourdata.log'\n\nlogging.basicConfig(level=logging.INFO,\n format='%(levelname)s: %(message)s',\n filename=log_file,\n filemode='w')\nconsole = logging.StreamHandler()\nconsole.setLevel(logging.INFO)\nlogging.getLogger('').addHandler(console)\n\n\nclass GazeDataset(Dataset):\n def __init__(self, root_dir, mat_file, training='train'):\n assert (training in set(['train', 'test']))\n self.root_dir = root_dir\n self.mat_file = mat_file\n self.jsonData = json.load(open(self.mat_file))\n self.training = training\n\n self.bboxes = self.jsonData['boxes']\n self.gazes = self.jsonData['points']\n self.paths = self.jsonData['path']\n self.image_num = len(self.paths)\n\n logging.info('%s contains %d images' % (self.mat_file, self.image_num))\n\n def generate_data_field(self, eye_point):\n \"\"\"eye_point is (x, y) and between 0 and 1\"\"\"\n height, width = 224, 224\n x_grid = np.array(range(width)).reshape([1, width]).repeat(height, axis=0)\n y_grid = np.array(range(height)).reshape([height, 1]).repeat(width, axis=1)\n grid = np.stack((x_grid, y_grid)).astype(np.float32)\n\n x, y = eye_point\n x, y = x * width, y * height\n\n grid -= np.array([x, y]).reshape([2, 1, 1]).astype(np.float32)\n norm = np.sqrt(np.sum(grid ** 2, axis=0)).reshape([1, height, width])\n # avoid zero norm\n norm = np.maximum(norm, 0.1)\n grid /= norm\n return grid\n\n def __len__(self):\n return self.image_num\n\n def __getitem__(self, idx):\n image_path = self.paths[idx]\n image_path = os.path.join(self.root_dir, image_path)\n image = cv2.imread(image_path, cv2.IMREAD_COLOR)\n box = self.bboxes[idx]\n point = self.gazes[idx]\n h, w = image.shape[:2]\n eye = [(box[0] + 0.5 * box[2]) / w, (box[1] + 0.5 * box[3]) /h ]\n gaze = [point[0] / w, point[1] / h]\n\n\n if random.random() > 0.5 and self.training == 'train':\n eye = [1.0 - eye[0], eye[1]]\n gaze = [1.0 - gaze[0], gaze[1]]\n image = cv2.flip(image, 1)\n \n # crop face\n x_c, y_c = eye\n x_0 = x_c - 0.15\n y_0 = y_c - 0.15\n x_1 = x_c + 0.15\n y_1 = y_c + 0.15\n if x_0 < 0:\n x_0 = 0\n if y_0 < 0:\n y_0 = 0\n if x_1 > 1:\n x_1 = 1\n if y_1 > 1:\n y_1 = 1\n h, w = image.shape[:2]\n face_image = image[int(y_0 * h):int(y_1 * h), int(x_0 * w):int(x_1 * w), :]\n # process face_image for face net\n face_image = cv2.cvtColor(face_image, cv2.COLOR_BGR2RGB)\n face_image = Image.fromarray(face_image)\n face_image = data_transforms[self.training](face_image)\n # process image for saliency net\n #image = image_preprocess(image)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n image = Image.fromarray(image)\n image = data_transforms[self.training](image)\n\n # generate gaze field\n gaze_field = self.generate_data_field(eye_point=eye)\n # generate heatmap\n heatmap = get_paste_kernel((224 // 4, 224 // 4), gaze, kernel_map, (224 // 4, 224 // 4))\n '''\n direction = gaze - eye\n norm = (direction[0] ** 2.0 + direction[1] ** 2.0) ** 0.5\n if norm <= 0.0:\n norm = 1.0\n\n direction = direction / norm\n '''\n sample = {'image' : image,\n 'face_image': face_image,\n 'eye_position': torch.FloatTensor(eye),\n 'gaze_field': torch.from_numpy(gaze_field),\n 'gt_position': torch.FloatTensor(gaze),\n 'gt_heatmap': torch.FloatTensor(heatmap).unsqueeze(0)}\n\n return sample\n\n\ndef test(net, test_data_loader):\n net.eval()\n total_loss = []\n total_error = []\n info_list = []\n heatmaps = []\n\n for data in test_data_loader:\n image, face_image, gaze_field, eye_position, gt_position, gt_heatmap = \\\n data['image'], data['face_image'], data['gaze_field'], data['eye_position'], data['gt_position'], data['gt_heatmap']\n image, face_image, gaze_field, eye_position, gt_position, gt_heatmap = \\\n map(lambda x: Variable(x.cuda(), volatile=True), [image, face_image, gaze_field, eye_position, gt_position, gt_heatmap])\n\n direction, predict_heatmap = net([image, face_image, gaze_field, eye_position])\n\n heatmap_loss, m_angle_loss = \\\n F_loss(direction, predict_heatmap, eye_position, gt_position, gt_heatmap)\n\n loss = heatmap_loss + m_angle_loss\n\n\n total_loss.append([heatmap_loss.data[0],\n m_angle_loss.data[0], loss.data[0]])\n logging.info('loss: %.5lf, %.5lf, %.5lf'%( \\\n heatmap_loss.data[0], m_angle_loss.data[0], loss.data[0]))\n\n middle_output = direction.cpu().data.numpy()\n final_output = predict_heatmap.cpu().data.numpy()\n target = gt_position.cpu().data.numpy()\n eye_position = eye_position.cpu().data.numpy()\n for m_direction, f_point, gt_point, eye_point in \\\n zip(middle_output, final_output, target, eye_position):\n f_point = f_point.reshape([224 // 4, 224 // 4])\n heatmaps.append(f_point)\n\n h_index, w_index = np.unravel_index(f_point.argmax(), f_point.shape)\n f_point = np.array([w_index / 56., h_index / 56.])\n\n f_error = f_point - gt_point\n f_dist = np.sqrt(f_error[0] ** 2 + f_error[1] ** 2)\n\n # angle \n f_direction = f_point - eye_point\n gt_direction = gt_point - eye_point\n\n norm_m = (m_direction[0] **2 + m_direction[1] ** 2 ) ** 0.5\n norm_f = (f_direction[0] **2 + f_direction[1] ** 2 ) ** 0.5\n norm_gt = (gt_direction[0] **2 + gt_direction[1] ** 2 ) ** 0.5\n \n m_cos_sim = (m_direction[0]*gt_direction[0] + m_direction[1]*gt_direction[1]) / \\\n (norm_gt * norm_m + 1e-6)\n m_cos_sim = np.maximum(np.minimum(m_cos_sim, 1.0), -1.0)\n m_angle = np.arccos(m_cos_sim) * 180 / np.pi\n\n f_cos_sim = (f_direction[0]*gt_direction[0] + f_direction[1]*gt_direction[1]) / \\\n (norm_gt * norm_f + 1e-6)\n f_cos_sim = np.maximum(np.minimum(f_cos_sim, 1.0), -1.0)\n f_angle = np.arccos(f_cos_sim) * 180 / np.pi\n\n \n total_error.append([f_dist, m_angle, f_angle])\n info_list.append(list(f_point))\n\n #info_list = np.array(info_list)\n #np.savez('multi_scale_concat_prediction.npz', info_list=info_list)\n\n #heatmaps = np.stack(heatmaps)\n #np.savez('multi_scale_concat_heatmaps.npz', heatmaps=heatmaps)\n\n logging.info('average loss : %s'%str(np.mean(np.array(total_loss), axis=0)))\n logging.info('average error: %s'%str(np.mean(np.array(total_error), axis=0)))\n error_list = np.array(total_error)\n print(error_list.shape)\n #np.savez('error_our_data_our_method.npz', error_list=error_list)\n #savemat(\"error_our_data_our_method.mat\", {\"distance\":error_list[:, 0], \"angle\":error_list[:, 2]})\n\n net.train()\n return\n\n\ndef main():\n\n test_set = GazeDataset(root_dir='../OurData/',\n mat_file='../OurData/annotation.json',\n training='test')\n test_data_loader = DataLoader(test_set, batch_size=1,\n shuffle=False, num_workers=8)\n\n net = GazeNet()\n net = DataParallel(net)\n net.cuda()\n\n pretrained_dict = torch.load('../model/pretrained_model.pkl')\n model_dict = net.state_dict()\n pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}\n model_dict.update(pretrained_dict)\n net.load_state_dict(model_dict)\n test(net, test_data_loader)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"code/test_ourdata.py","file_name":"test_ourdata.py","file_ext":"py","file_size_in_byte":8666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"89785949","text":"#============================================================================================\n# PROJETO FINAL - SISTEMAS EMBARCADOS 2\n#\n# Servidor tcp que recebe os dados da modelagem e processa o \n# controle para a correção da trajetória. Utiliza-se um controlador\n# proporcional derivativo (PD).\n#============================================================================================\n\nimport numpy as np\nimport socket\nimport sys\nimport struct\n\n# Criando um servidor TCP/IP para socket\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# Transmissão (bind) do socket para a porta\nserver_address = ('localhost',30000)\nsock.bind(server_address)\n\n# Colocando o socket para escutar conexões\nsock.listen(1)\n\nwhile True:\n # esperando a conexão\n print(\"Esperando por nova conexao...\")\n connection, client_address = sock.accept()\n \n e_p = 0\n count = 0\n try:\n while True:\n #Controlador PD\n data = connection.recv(100)\n if data:\n e = struct.unpack('f',data)\n e = e[0]\n print('Erro recebido: ', e)\n u = 0.5*e + 100*(e - e_p)\n print('Controle enviado: ', u)\n e_p = e\n u_s = struct.pack('f', u)\n connection.sendall(u_s)\n \n count = count + 1\n if(count % 1e3) == 0:\n print(count)\n else:\n print('Não foi recebido nenhum dado de ', client_address)\n break\n finally:\n # Encerrando e limpando os dados da conexao\n connection.close()\n \n \n","sub_path":"pd_controller_server.py","file_name":"pd_controller_server.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"55628915","text":"\"\"\"Unit tests for :mod:`esmvalcore.preprocessor._weighting`.\"\"\"\nfrom unittest import mock\n\nimport iris\nimport numpy as np\nimport pytest\nfrom cf_units import Unit\n\nimport esmvalcore.preprocessor._weighting as weighting\n\nCUBE_SFTLF = iris.cube.Cube(\n [10.0, 0.0, 100.0],\n var_name='sftlf',\n standard_name='land_area_fraction',\n units=Unit('%'),\n)\nCUBE_SFTOF = iris.cube.Cube(\n [100.0, 0.0, 50.0, 70.0],\n var_name='sftof',\n standard_name='sea_area_fraction',\n units=Unit('%'),\n)\nCUBE_3 = iris.cube.Cube(\n [10.0, 20.0, 0.0],\n var_name='dim3',\n)\nCUBE_4 = iris.cube.Cube(\n [1.0, 2.0, -1.0, 2.0],\n var_name='dim4',\n)\nFRAC_SFTLF = np.array([0.1, 0.0, 1.0])\nFRAC_SFTOF = np.array([0.0, 1.0, 0.5, 0.3])\nEMPTY_FX_FILES = {\n 'sftlf': [],\n 'sftof': [],\n}\nL_FX_FILES = {\n 'sftlf': 'not/a/real/path',\n 'sftof': [],\n}\nO_FX_FILES = {\n 'sftlf': [],\n 'sftof': 'not/a/real/path',\n}\nFX_FILES = {\n 'sftlf': 'not/a/real/path',\n 'sftof': 'i/was/mocked',\n}\nWRONG_FX_FILES = {\n 'wrong': 'test',\n 'sftlf': 'not/a/real/path',\n 'sftof': 'i/was/mocked',\n}\n\nLAND_FRACTION = [\n (CUBE_3, {}, [], None, [\"No fx files given\"]),\n (CUBE_3, {'sftlf': []}, [], None, [\"'sftlf' not found\"]),\n (CUBE_3, {'sftlf': 'a'}, [CUBE_SFTLF], FRAC_SFTLF, []),\n (CUBE_3, {'sftof': 'a'}, [CUBE_SFTOF], None, [\"not broadcastable\"]),\n (CUBE_3, EMPTY_FX_FILES, [], None,\n [\"'sftlf' not found\", \"'sftof' not found\"]),\n (CUBE_3, L_FX_FILES, [CUBE_SFTLF], FRAC_SFTLF, []),\n (CUBE_3, O_FX_FILES, [CUBE_SFTOF], None,\n [\"'sftlf' not found\", \"not broadcastable\"]),\n (CUBE_3, FX_FILES, [CUBE_SFTLF, CUBE_SFTOF], FRAC_SFTLF, []),\n (CUBE_3, {'wrong': 'a'}, [CUBE_SFTLF], None,\n [\"expected 'sftlf' or 'sftof'\"]),\n (CUBE_3, {'wrong': 'a'}, [CUBE_SFTOF], None, [\"not broadcastable\"]),\n (CUBE_3, WRONG_FX_FILES, [CUBE_SFTLF, CUBE_SFTLF, CUBE_SFTOF], FRAC_SFTLF,\n [\"expected 'sftlf' or 'sftof'\"]),\n (CUBE_3, WRONG_FX_FILES, [CUBE_SFTOF, CUBE_SFTLF, CUBE_SFTOF], FRAC_SFTLF,\n [\"not broadcastable\"]),\n (CUBE_4, {}, [], None, [\"No fx files given\"]),\n (CUBE_4, {'sftlf': []}, [], None, [\"'sftlf' not found\"]),\n (CUBE_4, {'sftlf': 'a'}, [CUBE_SFTLF], None, [\"not broadcastable\"]),\n (CUBE_4, {'sftof': 'a'}, [CUBE_SFTOF], FRAC_SFTOF, []),\n (CUBE_4, EMPTY_FX_FILES, [], None,\n [\"'sftlf' not found\", \"'sftof' not found\"]),\n (CUBE_4, L_FX_FILES, [CUBE_SFTLF], None,\n [\"not broadcastable\", \"'sftof' not found\"]),\n (CUBE_4, O_FX_FILES, [CUBE_SFTOF], FRAC_SFTOF, [\"'sftlf' not found\"]),\n (CUBE_4, FX_FILES, [CUBE_SFTLF, CUBE_SFTOF], FRAC_SFTOF,\n [\"not broadcastable\"]),\n (CUBE_4, {'wrong': 'a'}, [CUBE_SFTLF], None, [\"not broadcastable\"]),\n (CUBE_4, {'wrong': 'a'}, [CUBE_SFTOF], None,\n [\"expected 'sftlf' or 'sftof'\"]),\n (CUBE_4, WRONG_FX_FILES, [CUBE_SFTLF, CUBE_SFTLF, CUBE_SFTOF], FRAC_SFTOF,\n [\"not broadcastable\", \"not broadcastable\"]),\n (CUBE_4, WRONG_FX_FILES, [CUBE_SFTOF, CUBE_SFTLF, CUBE_SFTOF], FRAC_SFTOF,\n [\"expected 'sftlf' or 'sftof'\", \"not broadcastable\"]),\n]\n\n\n@pytest.mark.parametrize('cube,fx_files,fx_cubes,out,err', LAND_FRACTION)\n@mock.patch.object(weighting, 'iris', autospec=True)\ndef test_get_land_fraction(mock_iris, cube, fx_files, fx_cubes, out, err):\n \"\"\"Test calculation of land fraction.\"\"\"\n mock_iris.load_cube.side_effect = fx_cubes\n (land_fraction, errors) = weighting._get_land_fraction(cube, fx_files)\n if land_fraction is None:\n assert land_fraction == out\n else:\n assert np.allclose(land_fraction, out)\n assert len(errors) == len(err)\n for (idx, error) in enumerate(errors):\n assert err[idx] in error\n mock_iris.reset_mock()\n\n\nSHAPES_TO_BROADCAST = [\n ((), (1, ), True),\n ((), (10, 10), True),\n ((1, ), (10, ), True),\n ((1, ), (10, 10), True),\n ((2, ), (10, ), False),\n ((10, ), (), True),\n ((10, ), (1, ), True),\n ((10, ), (10, ), True),\n ((10, ), (10, 10), True),\n ((10, ), (7, 1), True),\n ((10, ), (10, 7), False),\n ((10, ), (7, 1, 10), True),\n ((10, ), (7, 1, 1), True),\n ((10, ), (7, 1, 7), False),\n ((10, ), (7, 10, 7), False),\n ((10, 1), (1, 1), True),\n ((10, 1), (1, 100), True),\n ((10, 1), (10, 7), True),\n ((10, 12), (10, 1), True),\n ((10, 12), (), True),\n ((10, 12), (1, ), True),\n ((10, 12), (12, ), True),\n ((10, 12), (1, 1), True),\n ((10, 12), (1, 12), True),\n ((10, 12), (10, 10, 1), True),\n ((10, 12), (10, 12, 1), False),\n ((10, 12), (10, 12, 12), False),\n ((10, 12), (10, 10, 12), True),\n]\n\n\n@pytest.mark.parametrize('shape_1,shape_2,out', SHAPES_TO_BROADCAST)\ndef test_shape_is_broadcastable(shape_1, shape_2, out):\n \"\"\"Test check if two shapes are broadcastable.\"\"\"\n is_broadcastable = weighting._shape_is_broadcastable(shape_1, shape_2)\n assert is_broadcastable == out\n\n\nCUBE_3_L = CUBE_3.copy([1.0, 0.0, 0.0])\nCUBE_3_O = CUBE_3.copy([9.0, 20.0, 0.0])\nCUBE_4_L = CUBE_4.copy([0.0, 2.0, -0.5, 0.6])\nCUBE_4_O = CUBE_4.copy([1.0, 0.0, -0.5, 1.4])\n\nWEIGHTING_LANDSEA_FRACTION = [\n (CUBE_3, {}, 'land', ValueError),\n (CUBE_3, {}, 'sea', ValueError),\n (CUBE_3, EMPTY_FX_FILES, 'land', ValueError),\n (CUBE_3, EMPTY_FX_FILES, 'sea', ValueError),\n (CUBE_3, L_FX_FILES, 'land', CUBE_3_L),\n (CUBE_3, L_FX_FILES, 'sea', CUBE_3_O),\n (CUBE_3, O_FX_FILES, 'land', ValueError),\n (CUBE_3, O_FX_FILES, 'sea', ValueError),\n (CUBE_3, FX_FILES, 'land', CUBE_3_L),\n (CUBE_3, FX_FILES, 'sea', CUBE_3_O),\n (CUBE_3, FX_FILES, 'wrong', TypeError),\n (CUBE_4, {}, 'land', ValueError),\n (CUBE_4, {}, 'sea', ValueError),\n (CUBE_4, EMPTY_FX_FILES, 'land', ValueError),\n (CUBE_4, EMPTY_FX_FILES, 'sea', ValueError),\n (CUBE_4, L_FX_FILES, 'land', ValueError),\n (CUBE_4, L_FX_FILES, 'sea', ValueError),\n (CUBE_4, O_FX_FILES, 'land', CUBE_4_L),\n (CUBE_4, O_FX_FILES, 'sea', CUBE_4_O),\n (CUBE_4, FX_FILES, 'land', CUBE_4_L),\n (CUBE_4, FX_FILES, 'sea', CUBE_4_O),\n (CUBE_4, FX_FILES, 'wrong', TypeError),\n]\n\n\n@pytest.mark.parametrize('cube,fx_files,area_type,out',\n WEIGHTING_LANDSEA_FRACTION)\n@mock.patch.object(weighting, 'iris', autospec=True)\ndef test_weighting_landsea_fraction(mock_iris,\n cube,\n fx_files,\n area_type,\n out):\n \"\"\"Test landsea fraction weighting preprocessor.\"\"\"\n # Exceptions\n if isinstance(out, type):\n with pytest.raises(out):\n weighted_cube = weighting.weighting_landsea_fraction(\n cube, fx_files, area_type)\n return\n\n # Regular cases\n fx_cubes = []\n if fx_files.get('sftlf'):\n fx_cubes.append(CUBE_SFTLF)\n if fx_files.get('sftof'):\n fx_cubes.append(CUBE_SFTOF)\n mock_iris.load_cube.side_effect = fx_cubes\n weighted_cube = weighting.weighting_landsea_fraction(\n cube, fx_files, area_type)\n assert weighted_cube == cube\n assert weighted_cube is cube\n mock_iris.reset_mock()\n","sub_path":"tests/unit/preprocessor/_weighting/test_weighting_landsea_fraction.py","file_name":"test_weighting_landsea_fraction.py","file_ext":"py","file_size_in_byte":7088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"230247356","text":"from datetime import timedelta, date, datetime\nfrom typing import Callable\n\nimport pandas as pd\nimport pytest\nimport requests\n\nfrom pybaseball.statcast import (_SC_SINGLE_GAME_REQUEST, _SC_SMALL_REQUEST, sanitize_input, statcast,\n statcast_single_game, DATE_FORMAT)\n\n# For an explanation of this type, see the note on GetDataFrameCallable in tests/pybaseball/conftest.py\nfrom .conftest import GetDataFrameCallable\n\n\n@pytest.fixture()\ndef small_request_raw(get_data_file_contents: Callable[[str], str]) -> str:\n return get_data_file_contents('small_request_raw.csv')\n\n\n@pytest.fixture()\ndef small_request(get_data_file_dataframe: GetDataFrameCallable) -> pd.DataFrame:\n return get_data_file_dataframe('small_request.csv', parse_dates=[2])\n\n@pytest.fixture()\ndef single_game_raw(get_data_file_contents: Callable[[str], str]) -> str:\n return get_data_file_contents('single_game_request_raw.csv')\n\n\n@pytest.fixture()\ndef single_game(get_data_file_dataframe: GetDataFrameCallable) -> pd.DataFrame:\n return get_data_file_dataframe('single_game_request.csv', parse_dates=[2])\n\nclass TestStatcast:\n def test_sanitize_input_nones(self) -> None:\n yesterday = date.today() - timedelta(days=1)\n\n start_dt, end_dt = sanitize_input(None, None)\n\n assert start_dt == yesterday\n assert end_dt == date.today()\n \n def test_sanitize_input_no_end_dt(self) -> None:\n yesterday = date.today() - timedelta(days=1)\n\n start_dt, end_dt = sanitize_input(str(yesterday), None)\n\n assert start_dt == yesterday\n assert end_dt == yesterday\n \n def test_sanitize_input(self) -> None:\n start_dt, end_dt = sanitize_input('2020-05-06', '2020-06-06')\n\n assert start_dt == datetime.strptime('2020-05-06', DATE_FORMAT).date()\n assert end_dt == datetime.strptime('2020-06-06', DATE_FORMAT).date()\n \n def test_sanitize_input_bad_start_dt(self) -> None:\n with pytest.raises(ValueError) as ex_info:\n sanitize_input('INVALID', '2020-06-06')\n\n assert str(ex_info.value) == 'Incorrect data format, should be YYYY-MM-DD'\n \n def test_sanitize_input_bad_end_dt(self) -> None:\n with pytest.raises(ValueError) as ex_info:\n sanitize_input('2020-05-06', 'INVALID')\n\n assert str(ex_info.value) == 'Incorrect data format, should be YYYY-MM-DD'\n\n def test_statcast(\n self,\n response_get_monkeypatch: Callable,\n small_request_raw: str,\n small_request: pd.DataFrame\n ) -> None:\n start_dt, end_dt = sanitize_input(None, None)\n response_get_monkeypatch(\n small_request_raw.encode('UTF-8'),\n _SC_SMALL_REQUEST.format(\n start_dt=start_dt,\n end_dt=end_dt,\n team=''\n )\n )\n\n statcast_result = statcast().reset_index(drop=True)\n\n pd.testing.assert_frame_equal(statcast_result, small_request)\n \n def test_statcast_team(\n self,\n response_get_monkeypatch: Callable,\n small_request_raw: str,\n small_request: pd.DataFrame\n ) -> None:\n start_dt, end_dt = sanitize_input(None, None)\n response_get_monkeypatch(\n small_request_raw.encode('UTF-8'),\n _SC_SMALL_REQUEST.format(\n start_dt=start_dt,\n end_dt=end_dt,\n team='TB'\n )\n )\n\n statcast_result = statcast(None, None, team='TB').reset_index(drop=True)\n\n pd.testing.assert_frame_equal(statcast_result, small_request)\n\n def test_statcast_single_game_request(\n self,\n response_get_monkeypatch: Callable,\n single_game_raw: str,\n single_game: pd.DataFrame\n ) -> None:\n game_pk = '631614'\n\n response_get_monkeypatch(\n single_game_raw.encode('UTF-8'),\n _SC_SINGLE_GAME_REQUEST.format(game_pk=game_pk)\n )\n\n statcast_result = statcast_single_game(game_pk).reset_index(drop=True)\n\n pd.testing.assert_frame_equal(statcast_result, single_game)\n","sub_path":"tests/pybaseball/test_statcast.py","file_name":"test_statcast.py","file_ext":"py","file_size_in_byte":4108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"78819127","text":"from typing import Callable, Type\n\nimport jax\nimport jax.numpy as jnp\nfrom jax import random\nfrom jaxlib.xla_extension import DeviceArray\n\nfrom .distributions import DistributionType\nfrom .model_parameters import ModelParameters\nfrom .object_tagger import ObjectTagger\n\nsamplers = ObjectTagger()\n\n\n@samplers(\"simple\")\nclass SimpleSampler:\n def __init__(\n self,\n params: Type[ModelParameters],\n base_distribution: Type[DistributionType],\n true_log_prob_fn: Callable[[DeviceArray], DeviceArray],\n ):\n \"\"\"\n This sampler ignores the true_log_prob_fn and just samples from the base distribution\n \"\"\"\n self._params = params\n self._base_distribution = base_distribution(\n mean=self._params.raw,\n cov=self._params.cov_raw,\n )\n self._true_log_prob_fn = true_log_prob_fn\n self._laplace_log_prob_fn = self._params.transform_logpdf(\n self._base_distribution.logpdf\n )\n\n def __call__(self, prng_key: DeviceArray, n_samples: int) -> DeviceArray:\n raw_params_rvs = self._base_distribution.rvs(\n prng_key=prng_key, n_samples=n_samples\n )\n vec_transform = jax.vmap(self._params.transform)\n params_rvs = vec_transform(raw_params_rvs)\n return params_rvs\n\n\n@samplers(\"importance\")\nclass ImportanceSampler(SimpleSampler):\n \"\"\"\n This sampler performs importance sampling, which samples from the base distribution and then re-samples\n based on weights calculated from the true_log_prob_fn\n \"\"\"\n\n def _get_raw_importance_weights(self, samples: DeviceArray) -> DeviceArray:\n true_log_prob = self._true_log_prob_fn(samples).reshape(-1)\n laplace_logpdf_vec = jax.vmap(self._laplace_log_prob_fn)\n base_log_prob = laplace_logpdf_vec(samples).reshape(-1)\n\n weights = jnp.exp(\n true_log_prob\n - base_log_prob\n - jnp.mean(true_log_prob)\n + jnp.mean(base_log_prob)\n )\n return weights\n\n def _truncate_importance_weights(self, weights: DeviceArray) -> DeviceArray:\n weights /= jnp.mean(weights)\n max_weight = jnp.sqrt(len(weights))\n truncated_weights = jnp.minimum(weights, max_weight)\n return truncated_weights\n\n def _resample(\n self, prng_key: DeviceArray, samples: DeviceArray, weights: DeviceArray\n ) -> DeviceArray:\n idx = jnp.arange(len(weights))\n rand_idx = random.choice(key=prng_key, a=idx, shape=idx.shape, p=weights)\n\n return samples[rand_idx, :]\n\n def __call__(self, prng_key: DeviceArray, n_samples: int) -> DeviceArray:\n prng_key_1, prng_key_2 = random.split(prng_key)\n\n simple_samples = super().__call__(prng_key=prng_key_1, n_samples=n_samples)\n\n weights = self._get_raw_importance_weights(simple_samples)\n truncated_weights = self._truncate_importance_weights(weights)\n\n importance_samples = self._resample(\n prng_key=prng_key_2, samples=simple_samples, weights=truncated_weights\n )\n\n return importance_samples\n","sub_path":"src/melvin/samplers.py","file_name":"samplers.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"171437519","text":"import time\nimport random\nimport telegram\nimport requests\nimport apiai,json\nfrom bs4 import BeautifulSoup\nfrom telegram.ext import Updater,CommandHandler,MessageHandler,Filters\nfrom modules import *\n\n\n\n#--------------------------------------------------------\n#Functions for each command\n#--------------------------------------------------------\n\n\ndef gif(bot,update):\n data=dict()\n global db,user,root \n chat_id = update.message.chat_id\n username=update.message.from_user.first_name\n bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)\n gif,thumb,caption=get_gif()\n bot.send_animation(chat_id, animation=gif, duration=10, width=536, height=354, thumb=thumb, caption=caption)\n\n\ndef meme(bot,update):\n data=dict()\n global db,user,root\n chat_id = update.message.chat_id\n username=update.message.from_user.first_name\n bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)\n meme=get_meme()\n bot.send_photo(chat_id=chat_id, photo=meme)\n\n \n\ndef joke(bot,update):\n data=dict()\n global db,user,root\n chat_id = update.message.chat_id\n username=update.message.from_user.first_name\n bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)\n joke = get_joke()\n bot.send_message(chat_id=chat_id, text=joke)\n\n \n\ndef youtube(bot,update):\n data=dict()\n global db,user,root\n chat_id = update.message.chat_id\n username=update.message.from_user.first_name\n bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)\n link=get_youtube()\n bot.send_message(chat_id=chat_id, text=\"[ ](\"+link+\").\", parse_mode=telegram.ParseMode.MARKDOWN)\n\n\ndef wallpaper(bot, update):\n data=dict()\n global db,user,root\n chat_id = update.message.chat_id\n username=update.message.from_user.first_name\n bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)\n image_url = get_image()\n bot.send_photo(chat_id=chat_id, photo=image_url)\n\n \ndef currency(bot, update):\n data=dict()\n global db,user,root\n chat_id = update.message.chat_id\n username=update.message.from_user.first_name\n bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)\n currency=get_currency()\n bot.send_message(chat_id=chat_id, text=currency)\n\n\ndef bitcoin(bot,update):\n data=dict()\n global db,user,root\n chat_id = update.message.chat_id\n username=update.message.from_user.first_name\n bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)\n bitcoin=get_bitcoin()\n bot.send_message(chat_id=chat_id, text=bitcoin)\n\n\n\n\ndef start(bot,update):\n try:\n data=dict()\n global db,user,root\n chat_id = update.message.chat_id\n username=update.message.from_user.first_name\n bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)\n bot.send_message(chat_id=chat_id, text=\"Hai.. \"+username+\"\\n\\nI'm am Bulo98 your personal chatbot, Lets get to bussiness...\")\n help_text=print_help() \n time.sleep(2.0)\n bot.send_message(chat_id=chat_id, text=help_text) \n except Exception as e:\n print(\"Error!: \",str(e)) \n\ndef profile_gen(bot,update):\n data=dict()\n global db,user,root\n chat_id = update.message.chat_id\n username=update.message.from_user.first_name\n bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)\n profile=get_fake_data()\n bot.send_message(chat_id=chat_id, text=profile)\n\n\ndef quote(bot,update):\n data=dict()\n global db,user,root\n chat_id = update.message.chat_id\n username=update.message.from_user.first_name\n bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)\n quote=get_quote()\n lines=\" \\n\"\n qt='\"'\n bot.send_message(chat_id=chat_id, text=qt+quote['Quote']+qt+\"\\n\"+lines+\"By: \"+quote['Author']+\"\\n\"+lines+\"Category: \"+quote['Category'])\n\n\n\ndef not_command(bot,update):\n data=dict()\n global db,user,root\n chat_id = update.message.chat_id\n username=update.message.from_user.first_name\n bot.send_chat_action(chat_id=chat_id, action=telegram.ChatAction.TYPING)\n user_response=update.message.text\n user_response=user_response.lower()\n print(user_response)\n request=apiai.ApiAI('Your-Dialog-flow-api-key-goes-here').text_request()\n request.lang='en'\n request.session_id='any-random-number-with-string'\n request.query=user_response\n responseJson=json.loads(request.getresponse().read().decode('utf-8'))\n response=responseJson['result']['fulfillment']['speech']\n if response:\n bot.send_message(chat_id=update.message.chat_id,text=response)\n else:\n response=search(str(user_response))\n if response==\"\":\n no_result=[\"Sorry...I guess my 6th sense is down!\",\"Sorry..there is something wrong with my systems.\",\"I can't fetch you any infomation on that!\",\"Pardon Me...I don't know.\",\"I have no answers for that.\",\"Sorry for dissappointing you..I'll be better.\"]\n response=str(random.choice(no_result))\n bot.send_message(chat_id=update.message.chat_id,text=str(response))\n else:\n bot.send_message(chat_id=update.message.chat_id,text=str(response))\n \n\n\ndef main():\n TOKEN = \"Your-telegram-bot-token\"\n\n updater = Updater(TOKEN)\n dp = updater.dispatcher\n text_message_handler=MessageHandler(Filters.text,not_command)\n dp.add_handler(text_message_handler) #Following are command handlers\n dp.add_handler(CommandHandler('start',start))\n dp.add_handler(CommandHandler('wallpaper',wallpaper))\n dp.add_handler(CommandHandler('bitcoin',bitcoin))\n dp.add_handler(CommandHandler('currency',currency))\n dp.add_handler(CommandHandler('joke',joke))\n dp.add_handler(CommandHandler('meme',meme)) \n dp.add_handler(CommandHandler('gif',gif))\n dp.add_handler(CommandHandler('video',youtube))\n dp.add_handler(CommandHandler('profile',profile_gen))\n dp.add_handler(CommandHandler('quote',quote))\n \n\n updater.start_polling(clean=True) #Async happens here\n updater.idle()\n \n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"487896513","text":"# coding: utf-8\nfrom __future__ import unicode_literals\n\nimport html\n\nfrom sqlalchemy.orm import joinedload, joinedload_all\n\nfrom clld.db.meta import DBSession\nfrom clld.db.util import get_distinct_values\nfrom clld.db.models.common import Value, Contribution, ValueSet, Parameter, Language, Source\nfrom clld.web.util.helpers import external_link, linked_references, link\n\nfrom clld.web.datatables.base import Col, IdCol, LinkCol, LinkToMapCol, DataTable\nfrom clld.web.datatables.language import Languages\nfrom clld.web.datatables.parameter import Parameters\nfrom clld.web.datatables.value import Values\nfrom clld.web.datatables.contribution import Contributions\nfrom clld.web.datatables.source import Sources\n\nfrom clld_glottologfamily_plugin.datatables import MacroareaCol, FamilyCol as FamilyLinkCol\nfrom clld_glottologfamily_plugin.models import Family\n\nfrom .models import (\n LexiRumahLanguage, Counterpart, Concept, Provider, LexiRumahSource,\n CounterpartReference, Cognateset, CognatesetCounterpart,\n)\n\nclass TextCol(Col):\n def format(self, item):\n\t return html.escape(super().format(item))\n\n\nclass ProviderCol(LinkCol):\n def __init__(self, dt, name='reference', **kw):\n kw.setdefault('model_col', Provider.name)\n kw.setdefault('get_object', lambda i: i.provider)\n kw['choices'] = [(p.id, p.name) for p in DBSession.query(Provider)]\n LinkCol.__init__(self, dt, name, **kw)\n\n def search(self, qs):\n return Contribution.id == qs\n\n\nclass SourcesCol(LinkCol):\n def format(self, item):\n links = []\n for it in self.get_obj(item):\n try:\n links.append(\n link(self.dt.req, it, **self.get_attrs(it)))\n except AssertionError:\n links.append(it)\n return '; '.join(links)\n\n\nfrom clld.web.datatables.base import DataTable, Col, LinkCol, DetailsRowLinkCol\nfrom clld.web.datatables.source import TypeCol\nclass LexiRumahSources(Sources):\n def base_query(self, query):\n query = Sources.base_query(self, query)\n query = query.join(LexiRumahSource.provider).options(joinedload(LexiRumahSource.provider))\n return query\n\n def col_defs(self):\n return [\n DetailsRowLinkCol(self, 'd'),\n LinkCol(self, 'name'),\n Col(self, 'author'),\n Col(self, 'year'),\n Col(self, 'title'),\n TypeCol(self, 'bibtex_type'),\n ]\n\ndef get_counterpart_references(counterpart):\n for i in counterpart.references:\n yield i.source\n\n\nclass ItalicsCol(TextCol):\n def format(self, value):\n return \"{:}\".format(super().format(value))\n\n\nclass Counterparts(Values):\n __constraints__ = [Parameter, Contribution, Language, Source]\n\n def base_query(self, query):\n query = query.join(ValueSet).options(\n joinedload(Value.valueset),\n joinedload_all(Counterpart.references, CounterpartReference.source)\n )\n\n if self.language:\n query = query \\\n .join(ValueSet.parameter) \\\n .join(ValueSet.contribution) \\\n .options(\n joinedload(Value.valueset, ValueSet.contribution),\n joinedload(Value.valueset, ValueSet.parameter))\n return query.filter(ValueSet.language_pk == self.language.pk)\n\n if self.parameter:\n query = query \\\n .join(ValueSet.language) \\\n .outerjoin(LexiRumahLanguage.family) \\\n .options(joinedload_all(\n Value.valueset, ValueSet.language, LexiRumahLanguage.family))\n return query.filter(ValueSet.parameter_pk == self.parameter.pk)\n\n if self.contribution:\n query = query.join(ValueSet.parameter)\n return query.filter(ValueSet.contribution_pk == self.contribution.pk)\n\n if self.source:\n query = query.filter(self.source.pk == CounterpartReference.source_pk)\n query = query.filter(CounterpartReference.counterpart_pk == Value.pk)\n return query\n\n return query \\\n .join(ValueSet.parameter)\\\n .join(ValueSet.language)\\\n .options(\n joinedload(Value.valueset, ValueSet.parameter),\n joinedload(Value.valueset, ValueSet.language),\n )\n\n def col_defs(self):\n template = [\n FamilyLinkCol(self, 'family', LexiRumahLanguage, get_object=lambda i: i.valueset.language),\n LinkCol(\n self,\n 'lect',\n model_col=LexiRumahLanguage.name,\n get_object=lambda i: i.valueset.language),\n LinkCol(\n self,\n 'concept',\n model_col=Concept.name,\n get_object=lambda i: i.valueset.parameter),\n LinkCol(\n self,\n 'Form (IPA)',\n sTitle='Form (IPA)',\n model_col=Counterpart.name),\n ItalicsCol(\n self,\n 'orthography',\n model_col=Counterpart.orthographic_form),\n # Col(self, 'loan', model_col=Counterpart.loan),\n TextCol(self, 'comment', model_col=Counterpart.comment),\n SourcesCol(\n self,\n 'sources',\n model_col=LexiRumahSource.name,\n get_object=get_counterpart_references),\n TextCol(\n self,\n 'given as',\n model_col=CounterpartReference.form_given_as,\n get_object=lambda i: i.references[0] if i.references else None),\n ]\n if self.source:\n del template[6]\n if self.parameter:\n del template[2]\n if self.language:\n del template[1]\n del template[0]\n return template\n\n\n#class FeatureIdCol(IdCol):\n# def search(self, qs):\n# if self.model_col:\n# return self.model_col.contains(qs)\n\n# def order(self):\n# return Feature.sortkey_str, Feature.sortkey_int\n\n\nclass LanguageIdCol(LinkCol):\n def get_attrs(self, item):\n return dict(label=item.id)\n\n\nclass GlottologLinkCol(Col):\n __kw__ = {'bSearchable': False, 'bSortable': False}\n\n def format(self, item):\n if item.glottolog_url:\n return external_link(item.glottolog_url, label=item.glottocode)\n else:\n return ''\n\n\nclass EthnologueLinkCol(Col):\n __kw__ = {'bSearchable': False, 'bSortable': False}\n\n def format(self, item):\n if item.ethnologue_url:\n return external_link(item.ethnologue_url, label=item.iso_code)\n else:\n return ''\n\n\nclass LexiRumahLanguages(Languages):\n __constraints__ = [Contribution]\n\n def base_query(self, query):\n if self.contribution:\n sq = DBSession.query(ValueSet.language_pk)\\\n .filter(ValueSet.contribution_pk == self.contribution.pk)\\\n .distinct()\\\n .subquery()\n query = query.filter(LexiRumahLanguage.pk.in_(sq))\n return query.outerjoin(Family).options(joinedload(LexiRumahLanguage.family))\n\n def col_defs(self):\n return [\n LanguageIdCol(self, 'id'),\n LinkCol(self, 'name'),\n LinkToMapCol(self, 'm'),\n Col(self,\n 'latitude',\n sDescription='The geographic latitude'),\n Col(self,\n 'longitude',\n sDescription='The geographic longitude'),\n Col(self, 'region', model_col=LexiRumahLanguage.region),\n FamilyLinkCol(self, 'family', LexiRumahLanguage),\n GlottologLinkCol(self, 'Glottolog'),\n EthnologueLinkCol(self, 'Ethnologue'),\n ]\n\n\nclass ConcepticonLink(Col):\n __kw__ = {'bSearchable': False, 'bSortable': False}\n\n def format(self, item):\n if item.concepticon_url:\n return external_link(item.concepticon_url)\n else:\n return ''\n\n\nclass Concepts(Parameters):\n def col_defs(self):\n return [\n LinkCol(self, 'name', sTitle='Concept'),\n Col(self, 'indonesian',\n model_col=Concept.indonesian,\n bSearchable=True),\n Col(self, '# lects', model_col=Concept.representation,\n bSearchable=False,\n sDescription='The number of languages where this concept is given'),\n Col(self, 'semantic_field', model_col=Concept.semanticfield, choices=get_distinct_values(Concept.semanticfield)),\n ConcepticonLink(self, 'Concepticon'),\n ]\n\n\nclass Providers(Contributions):\n def col_defs(self):\n return [\n IdCol(self, 'id'),\n LinkCol(self, 'reference'),\n #Col(self, 'description', model_col=Contribution.description),\n Col(self, 'language_count', sTitle='# lects', model_col=Provider.language_count),\n Col(self, 'parameter_count', sTitle='# concepts', model_col=Provider.parameter_count),\n Col(self,\n 'lexeme_count',\n sTitle='# lexemes',\n model_col=Provider.lexeme_count,\n format=lambda i: '{:,}'.format(i.lexeme_count)),\n Col(self,\n 'synonymy',\n sDescription=Provider.synonym_index.doc,\n model_col=Provider.synonym_index,\n format=lambda i: '{:.3f}'.format(i.synonym_index))\n ]\n\n\ndef get_cognateset_references(cognateset):\n for i in cognateset.references:\n yield i.source\n\n\nclass CognateSourcesCol(SourcesCol):\n def format(self, item):\n links = set()\n for rel in item.counterparts:\n for source in rel.sources:\n try:\n links.add(\n link(self.dt.req, source, **self.get_attrs(source)))\n except AssertionError:\n links.add(str(source))\n return '; '.join(links)\n\n\nclass Cognatesets(DataTable):\n def base_query(self, query):\n return query\n\n def col_defs(self):\n result = [\n# IdCol(self, 'id'),\n Col(\n self,\n \"Sources\",\n model_col=Cognateset.source_cache),\n LinkCol(self, 'name'),\n Col(self, 'cognates', model_col=Cognateset.representation),\n ]\n return result\n \n\n\ndef includeme(config):\n config.register_datatable('cognatesets', Cognatesets)\n config.register_datatable('languages', LexiRumahLanguages)\n config.register_datatable('contributions', Providers)\n config.register_datatable('parameters', Concepts)\n config.register_datatable('values', Counterparts)\n config.register_datatable('sources', LexiRumahSources)\n","sub_path":"lexirumah/datatables.py","file_name":"datatables.py","file_ext":"py","file_size_in_byte":10860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"309945164","text":"# Dependencies\nimport turtle\nimport tkinter\n\n\n# Greeting Msg\nprint(\" _________________________________\\n\"\n \"| |\\n\"\n \"| |\\n\"\n \"| .,-;-;-,. /'_\\ |\\n\"\n \"| _/_/_/_|_\\_\\) / |\\n\"\n \"| '-<_><_><_><_>=/\\ |\\n\"\n \"| `/_/====/_/-'\\_\\ |\\n\"\n \"| |\\n\"\n \"| |\\n\"\n \"| Welcome to Bowser! |\\n\"\n \"| Let's start drawing turtles |\\n\"\n \"|_________________________________|\\n\")\n\n\n# Cria uma lista de números\ndef mk_list(keys):\n dynamic_list = []\n\n for key in range(keys):\n dynamic_list.append(key)\n\n return dynamic_list\n\n\n# Derivando a classe , cria uma classe \n# cujos atributos são os inputs do utilizador e um método\n# que desenha um poligono mediante o input introduzido.\nclass Polygon(turtle.Turtle):\n def __init__(self):\n # Deriva a classe base\n super().__init__(visible=False)\n\n # Guarda o input do user\n self.edge_num = int(input(' • Number of edges: '))\n self.edge_len = int(input(' • Edge length: '))\n self.border_color = input(' • Line color: ')\n self.fill = input(' • Background color: ')\n\n # Chama o método que renderiza o poligono\n self.draw_poly()\n\n # Declara o método que desenha o poligono\n def draw_poly(self):\n # Lista sobre a qual se vai iterar\n edges = mk_list(self.edge_num)\n\n # Ângulo feito pela intercepção dos lados do poligono\n angle = 360/self.edge_num\n\n # Parâmetros de cor\n self.color(self.border_color)\n self.fillcolor(self.fill)\n\n self.begin_fill()\n\n for _ in edges:\n self.fd(self.edge_len)\n self.lt(angle)\n\n self.end_fill()\n tkinter.mainloop()\n\n# Func que chama e devolve o objeto Polygon\ndef get_polygon():\n print('Alright, let us draw a polygon.\\n')\n return Polygon()\n\n# get_polygon()\n\n#\nclass Star(turtle.Turtle):\n def __init__(self):\n super().__init__(visible=False)\n self.draw_star()\n\n def draw_star(self):\n self.shape('circle')\n self.color('white')\n self.stamp()\n self.screen.bgcolor('blue')\n\n angle = 360/8\n tips = mk_list(9)\n\n for _ in tips:\n self.pendown()\n self.fd(200)\n self.pensize(5)\n self.stamp()\n\n self.home()\n\n self.rt(angle)\n angle = angle + 45\n\n tkinter.mainloop()\n\ndef get_star():\n print('Last but not least, we are rendering a star shape.\\n')\n return Star()\n\n# get_star()\n\n\n#\n# Func que gera o relógio\ndef gen_clock():\n print(\"K, now we're rendering a clock made of tiny turtles!\\n\")\n\n bowser = turtle.Pen()\n bowser.shape('turtle')\n bowser.color('blue')\n bowser.stamp()\n bowser.screen.bgcolor('lightgreen')\n\n angle = 360 / 12\n hours = mk_list(12)\n\n for _ in hours:\n # Espaçamento do mostrador\n bowser.penup()\n bowser.fd(200)\n\n # Linha de marcação das horas/minutos\n bowser.pendown()\n bowser.fd(30)\n\n # Espaçamento pequeno e carimbo da tartaruga\n bowser.penup()\n bowser.fd(30)\n bowser.stamp()\n\n # Regresso à posição central\n bowser.home()\n\n # Rotação\n bowser.rt(angle)\n angle = angle + 30\n\n tkinter.mainloop()\n\n# gen_clock()\n\n\ndef draw_shape(edge_num):\n bowser = turtle.Pen()\n\n edges = mk_list(edge_num)\n angle = 360/edge_num\n\n for _ in edges:\n bowser.fd(100)\n bowser.rt(angle)\n\n\ndraw_shape(3)\ndraw_shape(6)\ndraw_shape(8)\ntkinter.mainloop()","sub_path":"Trabalhos/RE03/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":3787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"262425206","text":"class Solution:\n def numDistinctIslands(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n if len(grid) == 0 or len(grid[0]) == 0:\n return 0\n islandSet = set()\n visited = [[False for c in range(len(grid[0]))]\n for r in range(len(grid))]\n for r in range(len(grid)):\n for c in range(len(grid[0])):\n if visited[r][c] or grid[r][c] == 0:\n continue\n islandSet.add(self.bfs(grid, r, c, visited))\n return len(islandSet)\n\n def bfs(self, grid, row, col, visited):\n directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n rows = len(visited)\n cols = len(visited[0])\n visited[row][col] = True\n q = [(row, col)]\n island = ''\n while len(q) > 0:\n nq = []\n for r, c in q:\n island += str(r - row) + ',' + str(c - col) + '|'\n for dr, dc in directions:\n nr, nc = r + dr, c + dc\n if nr >= 0 and nr < rows and nc >= 0 and nc < cols and not visited[nr][nc] and grid[nr][nc] == 1:\n nq.append((nr, nc))\n visited[nr][nc] = True\n q = nq\n return island\n","sub_path":"src/number-of-distinct-islands.py","file_name":"number-of-distinct-islands.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"268490340","text":"# -*- coding: utf-8 -*-\n__author__ = '__L1n__w@tch'\n\nimport socket\nimport threading\nimport time\n\n\ndef main():\n server_address = (\"127.0.0.1\", 8084)\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server.bind(server_address)\n server.listen(5)\n while True:\n client, addr = server.accept()\n client_thread = threading.Thread(target=serve, args=(client, addr))\n client_thread.start()\n\n\ndef serve(sock, addr):\n rs_thread = threading.Thread(target=repeat_send, args=(sock, addr))\n rs_thread.start()\n\n while True:\n data = sock.recv(1024).decode(\"utf8\")\n print(\"address = {0}, receive: {1}\".format(addr, data))\n\n\ndef repeat_send(sock, addr):\n while True:\n print(\"Send to {0}\".format(addr))\n sock.send(\"send\".encode(\"utf8\"))\n time.sleep(3)\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"密码学相关/密码学竞赛复赛/test_server.py","file_name":"test_server.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"554010298","text":"from pyrh import Robinhood\nimport numpy as np\nimport tulipy as ti\nimport sched, time\n# Log in to app (will prompt for two-factor)\nrh = Robinhood()\nrh.login(username=\"RobinHood Login Email Here\", password=\"Robinhood Password Here\")\nenteredTrade = False\ns = sched.scheduler(time.time, time.sleep)\ndef run(sc): \n global enteredTrade\n print(\"Getting historical quotes\")\n # do your stuff\n historical_quotes = rh.get_historical_quotes(\"F\", \"5minute\", \"day\")\n closePrices = [];\n #format close prices for RSI\n for key in historical_quotes[\"results\"][0][\"historicals\"]:\n closePrices.append(float(key['close_price']))\n DATA = np.array(closePrices)\n #Calculate RSI\n rsi = ti.rsi(DATA, period=5)\n instrument = rh.instruments(\"F\")[0]\n #If rsi is less than or equal to 30 buy\n if rsi[len(rsi)-1] <= 30 and not enteredTrade:\n enteredTrade = True\n rh.place_buy_order(instrument, 1)\n #Sell when RSI reaches 70\n if rsi[len(rsi)-1] >= 70 and enteredTrade:\n rh.place_sell_order(instrument, 1)\n enteredTrade = False\n print(rsi[len(rsi)-1])\n s.enter(60, 1, run, (sc,))\n\ns.enter(60, 1, run, (s,))\ns.run()","sub_path":"RobinhoodBot.py","file_name":"RobinhoodBot.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"352173922","text":"import os\nfrom flask import Flask, render_template ,request ,send_from_directory\nfrom threading import Timer\n# import serial\nfrom flask_socketio import SocketIO\nimport time\nimport requests\nimport json\nimport websocket \nfrom flask_cors import CORS, cross_origin\n\n\n# -------------------Database Setup----------------------------------------\n#\n# from database_setup import Base,Restaurant,MenuItem\n# from sqlalchemy import create_engine\n# from sqlalchemy.orm import sessionmaker\n\n# Connecting date base to server\n# engine=create_engine('sqlite:///restaurant.db')\n# Base.metadata.bind=engine\n\n# DBSession=sessionmaker(bind=engine)\n# session =DBSession()\n#\n# -------------------------------------------------------------------------\n\napp=Flask(__name__)\ncors = CORS(app, resources={r\"/api/*\": {\"origins\": \"*\"}})\n# wrapping our app in SocketIO\nsocketio = SocketIO(app)\n\nroot = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"app\", \"static\", \"dist\")\n#ser = serial.Serial('/dev/ttyACM0', 9600)\nthread = None;\nthread2 = None;\nk = 0;\ncar_lat = 20.005450\ncar_lon = 77.000400\ncar_id = 'ass9987'\ncar_type = 'emergency'\ncar_status = 'on'\ndriver_id = 3\njourney_id = None\nws_css = None\nemergency_status = False\nemergency_needed = \"safe\"\n#----------------------------------------------------------------------------------------\n#This code is for taking lat and lon from serial monitor \n# def set_interval(update_location, sec):\n# def func_wrapper():\n# set_interval(update_location, sec) \n# update_location() \n# t = threading.Timer(sec, func_wrapper)\n# t.start()\n# return t\nclass InfiniteTimer():\n \"\"\"A Timer class that does not stop, unless you want it to.\"\"\"\n\n def __init__(self, seconds, target):\n self._should_continue = False\n self.is_running = False\n self.seconds = seconds\n self.target = target\n self.thread = None\n\n def _handle_target(self):\n self.is_running = True\n self.target()\n self.is_running = False\n self._start_timer()\n\n def _start_timer(self):\n if self._should_continue: # Code could have been running when cancel was called.\n self.thread = Timer(self.seconds, self._handle_target)\n self.thread.start()\n\n def start(self):\n if not self._should_continue and not self.is_running:\n self._should_continue = True\n self._start_timer()\n else:\n print(\"Timer already started or running, please wait if you're restarting.\")\n\n def cancel(self):\n if self.thread is not None:\n self._should_continue = False # Just in case thread is running and cancel fails.\n self.thread.cancel()\n else:\n print(\"Timer never started or failed to initialize.\")\n\nclass InfiniteTimer2():\n \"\"\"A Timer class that does not stop, unless you want it to.\"\"\"\n\n def __init__(self, seconds, target):\n self._should_continue = False\n self.is_running = False\n self.seconds = seconds\n self.target = target\n self.thread = None\n\n def _handle_target(self):\n self.is_running = True\n self.target()\n self.is_running = False\n self._start_timer()\n\n def _start_timer(self):\n if self._should_continue: # Code could have been running when cancel was called.\n self.thread = Timer(self.seconds, self._handle_target)\n self.thread.start()\n\n def start(self):\n if not self._should_continue and not self.is_running:\n self._should_continue = True\n self._start_timer()\n else:\n print(\"Timer already started or running, please wait if you're restarting.\")\n\n def cancel(self):\n if self.thread is not None:\n self._should_continue = False # Just in case thread is running and cancel fails.\n self.thread.cancel()\n else:\n print(\"Timer never started or failed to initialize.\")\n\n\n\ndef update_location():\n global car_lat, car_lon, thread, k\n # read_serial = ser.readline()\n # car_lat = float(read_serial[0:9])\n # car_lon = float(read_serial[10:19])\n # send_url = 'http://freegeoip.net/json'\n # r = requests.get(send_url)\n # j = json.loads(r.text)\n # car_lat = j['latitude']\n # car_lon = j['longitude']\n print(car_lat,car_lon,\" \")\n socketio.emit('location',{\n 'lat': car_lat,\n 'lon': car_lon,\n 'car_status': car_status,\n 'car_type': car_type\n }, namespace = \"/socket/location\")\n if k != 0:\n if k == 1:\n time.sleep(3)\n k = 2\n if car_status =='on':\n update_car_status()\n update_emrgency_status()\n #print(read_serial)\n#-----------------------------------------------------------------------------------------\n\n# This function make journey entry in django server\ndef register_start_journey():\n global car_lat, car_lon, journey_id\n data = {\n \"jstart_lat\": str(car_lat),\n \"jstart_lon\": str(car_lon),\n \"jend_lat\": str(car_lat),\n \"jend_lon\": str(car_lon),\n \"javg_speed\": \"0.000000\",\n \"jfuel_con\": \"0.000000\",\n \"jend_status\": car_status,\n \"jcar_number\": car_id,\n \"jdriver_id\": 1\n }\n # json_data = json.dumps(data)\n res = requests.post('http://544b1e41.ngrok.io/api/v1/cars/journey/', json = data)\n print(res.text)\n json_response = json.loads(res.text)\n print(json_response['id'])\n journey_id = json_response['id']\n\n#This function modifies journey entry in django server\ndef register_end_journey():\n global car_lat, car_lon\n data = {\n \"jend_lat\": str(round(car_lat + 6,6)),\n \"jend_lon\": str(round(car_lon + 6,6)),\n \"javg_speed\": \"0.5000\",\n \"jfuel_con\": \"0.5000\",\n \"jend_status\": car_status,\n \"jcar_number\": car_id,\n \"jdriver_id\": 1\n }\n # json_data = json.dumps(data)\n res = requests.put('http://544b1e41.ngrok.io/api/v1/cars/AUBT9863/journeys/' + str(journey_id) + \"/\", json = data)\n print(res.text)\n\n\n#This functions connect to websocket for car status update\n\ndef css_on_message(ws, message):\n json_message = json.loads(message)\n if json_message['stream'] == \"status\":\n socketio.emit('emergency', json_message['payload'], namespace = \"/socket/location\")\n if json_message['stream'] == \"emergency\":\n print(message)\n socketio.emit('emergency_needed', json_message['payload'], namespace = \"/socket/location\")\n\ndef css_on_error(ws, error):\n print(error)\n\ndef css_on_close(ws):\n print(\"### closed ###\")\n\ndef css_on_open(ws):\n print(\"### Connection started ###\")\n\ndef car_status_socket():\n global ws_css, k\n print(\"Entered in car socket\")\n if k == 0:\n ws_css = websocket.WebSocketApp(\"ws://544b1e41.ngrok.io/status/\",\n on_message = css_on_message,\n on_error = css_on_error,\n on_close = css_on_close)\n ws_css.on_open = css_on_open\n k = k + 1\n ws_css.run_forever()\n\n\ndef update_car_status():\n global ws_css, car_lat, car_lon,car_id,car_status\n data = {\n \"car_lat\": str(car_lat),\n \"car_lon\": str(car_lon),\n \"car_speed\": \"0.000000\",\n \"car_fuel\": \"0.00033\",\n \"car_temp\": \"0.000000\",\n \"car_status\": car_status,\n \"car_number\": car_id,\n \"car_driver_id\": 1\n }\n req_data = {\n \"stream\": \"status\",\n \"payload\": data\n }\n # print(req_data)\n ws_css.send(json.dumps(req_data))\n\ndef update_car_end_status():\n global ws_css, car_lat, car_lon,car_id,car_status\n data = {\n \"car_lat\": str(car_lat),\n \"car_lon\": str(car_lon),\n \"car_speed\": \"0.000000\",\n \"car_fuel\": \"0.00033\",\n \"car_temp\": \"0.000000\",\n \"car_status\": 'off',\n \"car_number\": car_id,\n \"car_driver_id\": 1\n }\n req_data = {\n \"stream\": \"status\",\n \"payload\": data\n }\n # print(req_data)\n ws_css.send(json.dumps(req_data))\n\n\ndef update_emrgency_status():\n global ws_css, car_lat, car_lon\n data = {\n \"ec_start_lat\": str(car_lat),\n \"ec_start_lon\": str(car_lon),\n \"ec_end_lat\": str(car_lat),\n \"ec_end_lon\": str(car_lon),\n \"ec_current_lat\": str(car_lat),\n \"ec_current_lon\": str(car_lon),\n \"vc_end_status\": emergency_needed,\n \"ec_car_number\": car_id,\n \"ec_driver_id\": driver_id,\n }\n req_data = {\n \"stream\": \"emergency\",\n \"payload\": data\n }\n # print(req_data)\n ws_css.send(json.dumps(req_data))\n\ndef update_emrgency_end_status():\n global ws_css, car_lat, car_lon\n data = {\n \"ec_start_lat\": str(car_lat),\n \"ec_start_lon\": str(car_lon),\n \"ec_end_lat\": str(car_lat),\n \"ec_end_lon\": str(car_lon),\n \"ec_current_lat\": str(car_lat),\n \"ec_current_lon\": str(car_lon),\n \"vc_end_status\": emergency_needed,\n \"ec_car_number\": car_id,\n \"ec_driver_id\": driver_id,\n }\n req_data = {\n \"stream\": \"emergency\",\n \"payload\": data\n }\n # print(req_data)\n ws_css.send(json.dumps(req_data))\n#///////////////////////////////////////////////////////////////////////////\n# Simple flask routes for front end application\n\n\n\n@app.route('/', methods=['GET'])\ndef static_proxy(path):\n return send_from_directory(root, path)\n\n@app.route('/', methods=['GET'])\ndef redirect_to_index():\n return send_from_directory(root, 'index.html')\n\n@app.route('/login', methods=['GET'])\ndef redirect_to_login():\n # set_interval(func, 1)\n return send_from_directory(root, 'index.html')\n\n@app.route('/api/emergency', methods=['GET','POST'])\ndef emergency_switch():\n global emergency_status, emergency_needed\n print(\"Emergency called\")\n if(emergency_status):\n emergency_status = False\n emergency_needed = \"safe\"\n update_emrgency_end_status()\n else:\n emergency_status = True\n emergency_needed = \"need\"\n return \"Recived signal\"\n#/////////////////////////////////////////////////////////////////////////////\n\n# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# SocketIo routes\n@socketio.on('connect', namespace='/socket/location')\ndef start_journey():\n register_start_journey()\n global thread, thread2\n thread = InfiniteTimer(1, update_location)\n thread2 = InfiniteTimer2(1, car_status_socket)\n thread.start()\n thread2.start()\n\n\n@socketio.on('disconnect', namespace=\"/socket/location\")\ndef end_journey():\n global thread, ws_css, car_status\n car_status = 'off'\n time.sleep(2)\n update_car_end_status()\n thread.cancel();\n ws_css.close();\n thread2.cancel();\n register_end_journey();\n os.system(\"sudo shutdown -h now\")\n #@reboot /usr/bin/python /path/to/myFile.py\n#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n\nif __name__ == '__main__':\n app.debug = True\n socketio.run(app,host = '0.0.0.0', port=4000)\n\n\n","sub_path":"emergency.py","file_name":"emergency.py","file_ext":"py","file_size_in_byte":10908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"632206825","text":"import dxfwrite\nfrom dxfwrite import DXFEngine as dxf\nimport os\nimport xlrd\n\ncab_type_pow = dict(Cab1='ВВГнг(A)-LS 4х1,5',\n Cab2='ВВГнг(A)-LS 4х2,5',\n Cab3='ВВГнг(A)-LS 4х4',\n Cab4='ВВГнг(A)-LS 4х6',\n Cab5='ВВГнг(A)-LS 4х10',\n Cab6='ВВГнг(A)-LS 4х16',\n Cab7='ВВГнг(A)-LS 4х25',\n Cab8='ВВГнг(A)-LS 4х35',\n Cab9='ВВГнг(A)-LS 4х50',\n Cab10='ВВГнг(A)-LS 4х70',\n Cab11='ВВГнг(A)-LS 4х95',\n Cab12='ВВГнг(A)-LS 4х120',\n Cab13='ВВГнг(A)-LS 4х150',\n Cab14='ВВГнг(A)-LS 4х185',\n Cab15='ВВГнг(A)-LS 4х240',\n Cab16='ВВГнг(A)-LS 5х1,5',\n Cab17='ВВГнг(A)-LS 5х2,5',\n Cab18='ВВГнг(A)-LS 5х4',\n Cab19='ВВГнг(A)-LS 5х6',\n Cab20='ВВГнг(A)-LS 5х10',\n Cab21='ВВГнг(A)-LS 5х16',\n Cab22='ВВГнг(A)-LS 5х25',\n Cab23='ВВГнг(A)-LS 5х35',\n Cab24='ВВГнг(A)-LS 5х50',\n Cab25='ВВГнг(A)-LS 5х70',\n Cab26='ВВГнг(A)-LS 5х95',\n Cab27='ВВГнг(A)-LS 5х120',\n Cab28='ВВГнг(A)-LS 5х150',\n Cab29='ВВГнг(A)-LS 5х185',\n Cab30='ВВГнг(A)-LS 5х240')\n\ncab_type_cont = dict(Cab1='КВВГЭнг(А)-LS 5x1',\n Cab2='КВВГЭнг(А)-LS 7x1',\n Cab3='КВВГЭнг(А)-LS 10x1',\n Cab4='КВВГЭнг(А)-LS 14x1',\n Cab5='КВВГЭнг(А)-LS 19x1',\n Cab6='КВВГЭнг(А)-LS 27x1')\n\ncab_diam_pow = dict(Cab1='12,1 мм',\n Cab2='13 мм',\n Cab3='14,6 мм',\n Cab4='15,8 мм',\n Cab5='18,7 мм',\n Cab6='22,6 мм',\n Cab7='25,6 мм',\n Cab8='28 мм',\n Cab9='32 мм',\n Cab10='36,1 мм',\n Cab11='40,2 мм',\n Cab12='43,6 мм',\n Cab13='47,4 мм',\n Cab14='51,4 мм',\n Cab15='57,8 мм',\n Cab16='12,8 мм',\n Cab17='13,9 мм',\n Cab18='15,7 мм',\n Cab19='17 мм',\n Cab20='20,3 мм',\n Cab21='24,9 мм',\n Cab22='27,9 мм',\n Cab23='30,6 мм',\n Cab24='35,5 мм',\n Cab25='39,6 мм',\n Cab26='44,8 мм',\n Cab27='48 мм',\n Cab28='51,8 мм',\n Cab29='57,2 мм',\n Cab30='63,5 мм')\n\ncab_stu = dict(Cab1='MG-20',\n Cab2='MG-20',\n Cab3='MG-25',\n Cab4='MG-25',\n Cab5='MG-32',\n Cab6='MG-32',\n Cab7='MG-40',\n Cab8='MG-40',\n Cab9='MG-50',\n Cab10='MG-50',\n Cab11='MG-63',\n Cab12='MG-63',\n Cab13='-',\n Cab14='-',\n Cab15='-',\n Cab16='MG-20',\n Cab17='MG-20',\n Cab18='MG-25',\n Cab19='MG-25',\n Cab20='MG-32',\n Cab21='MG-32',\n Cab22='MG-40',\n Cab23='MG-40',\n Cab24='MG-50',\n Cab25='MG-63',\n Cab26='-',\n Cab27='-',\n Cab28='-',\n Cab29='-',\n Cab30='-')\n\ndef one_line_circ(x, name, power):\n\n type = 'Автомат'\n data = 'Автомат'\n\n drawing.add(dxf.line((x - 7, -9), (x - 7, -13)))\n\n drawing.add(dxf.line((x - 8, -12), (x - 6, -14)))\n drawing.add(dxf.line((x - 6, -12), (x - 8, -14)))\n\n drawing.add(dxf.line((x - 7, -19), (x - 7, -23)))\n drawing.add(dxf.line((x - 10.5, -13), (x - 7, -19)))\n\n drawing.add(dxf.mtext(str(name)+'QF1',insert=(x + 5.5, -11), rotation=0, height=2.5, valign=dxfwrite.MIDDLE,\n halign=dxfwrite.CENTER, style='txt', xscale=0.7))\n drawing.add(dxf.mtext(str(type), insert=(x + 5.5, -14.5), rotation=0, height=2.5, valign=dxfwrite.MIDDLE,\n halign=dxfwrite.CENTER, style='txt', xscale=0.7))\n drawing.add(dxf.mtext(str(data), insert=(x + 5.5, -18), rotation=0, height=2.5, valign=dxfwrite.MIDDLE,\n halign=dxfwrite.CENTER, style='txt', xscale=0.7))\n\ndef one_line_kont(x, name, power):\n\n type = 'Контактор'\n data = 'Контактор'\n\n drawing.add(dxf.line((x - 7, -37), (x - 7, -41)))\n drawing.add(dxf.line((x - 7, -47), (x - 7, -51)))\n drawing.add(dxf.line((x - 10.5, -41), (x - 7, -47)))\n\n drawing.add(dxf.mtext(str(name)+'KM1',insert=(x + 5.5, -39), rotation=0, height=2.5, valign=dxfwrite.MIDDLE,\n halign=dxfwrite.CENTER, style='txt', xscale=0.7))\n drawing.add(dxf.mtext(str(type),insert=(x + 5.5, -42.5), rotation=0, height=2.5, valign=dxfwrite.MIDDLE,\n halign=dxfwrite.CENTER, style='txt', xscale=0.7))\n drawing.add(dxf.mtext(str(data),insert=(x + 5.5, -46), rotation=0, height=2.5, valign=dxfwrite.MIDDLE,\n halign=dxfwrite.CENTER, style='txt', xscale=0.7))\n\n\ndef one_line_table(x, name, discr, power, voltage):\n\n if voltage == 380:\n current = round(float(power) / 1.73 / float(voltage / 1000) / 0.8, 2)\n else:\n current = round(float(power) / float(voltage / 1000) / 0.8, 2)\n\n if start_type == 'ПП':\n max_current = round(current * 7, 2)\n else:\n max_current = round(current * 4, 2)\n max_current = str(max_current) + ',(' + str(round(current * 7, 2)) + ')'\n\n# print('\\t -+- \\t')\n# print('Номер тех. позиции:', name)\n# print('Описание:', discr)\n# print('Мощность:', round(power, 2))\n# print('Напряжение:', voltage)\n# print('ЧРП/УПП:', start_type)\n# print('Ток:', current)\n# print('Пусковой ток:', max_current)\n\n line1 = dxf.mtext(str(name) + 'M1', insert=(x, -154.50), rotation=0, height=2.5, valign=dxfwrite.MIDDLE,\n halign=dxfwrite.CENTER, style='txt', xscale=0.7)\n line2 = dxf.mtext('*', insert=(x, -161.5), rotation=0, height=2.5, valign=dxfwrite.MIDDLE, halign=dxfwrite.CENTER,\n style='txt', xscale=0.7)\n line3 = dxf.mtext(str(round(power, 2)), insert=(x, -168.5), rotation=0, height=2.5, valign=dxfwrite.MIDDLE,\n halign=dxfwrite.CENTER, style='txt', xscale=0.7)\n line4 = dxf.mtext(str(current), insert=(x, -175.5), rotation=0, height=2.5, valign=dxfwrite.MIDDLE,\n halign=dxfwrite.CENTER, style='txt', xscale=0.7)\n line5 = dxf.mtext(str(max_current), insert=(x, -182.5), rotation=0, height=2.5, valign=dxfwrite.MIDDLE,\n halign=dxfwrite.CENTER, style='txt', xscale=0.7)\n line6 = dxf.mtext(str((discr.replace(' ', '\\n'))), insert=(x, -198.0), rotation=0, height=2.5,\n valign=dxfwrite.MIDDLE, halign=dxfwrite.CENTER, style='txt', xscale=0.7)\n line7 = dxf.mtext(str(name), insert=(x, -214), rotation=0, height=2.5, valign=dxfwrite.MIDDLE,\n halign=dxfwrite.CENTER, style='txt', xscale=0.7, color=3)\n line8 = dxf.mtext('-;-', insert=(x, -230), rotation=0, height=2.5, valign=dxfwrite.MIDDLE, halign=dxfwrite.CENTER, xscale=0.7,\n style='txt')\n\n drawing.add(line1)\n drawing.add(line2)\n drawing.add(line3)\n drawing.add(line4)\n drawing.add(line5)\n drawing.add(line6)\n drawing.add(line7)\n drawing.add(line8)\n\n drawing.add(dxf.rectangle(insert=(x - 15, -151), width=(30), height=(-83)))\n for i in range(1, 6):\n drawing.add(dxf.line((x - 15, -151 - i * 7), (x + 15, -151 - i * 7)))\n for i in range(3, 6):\n drawing.add(dxf.line((x - 15, -186 - i * 8), (x + 15, -186 - i * 8)))\n\n drawing.add(dxf.line((x - 15, 40), (x + 15, 40)))\n drawing.add(dxf.line((x - 15, 35), (x + 15, 35)))\n drawing.add(dxf.line((x - 15, -55.5), (x + 15, -55.5)))\n\ndef one_line_cab_power(x, name, cab_pow):\n\n pow_cab_name = dxf.mtext('н1-' + str(name), insert=(x - 7, -97.75), style='txt', rotation=90, xscale=0.7, height=2.5, valign=dxfwrite.BOTTOM, halign=dxfwrite.CENTER)\n pow_cab_type = dxf.mtext(str(cab_type_pow[cab_pow]), insert=(x - 6, -97.75), style='txt', rotation=90, xscale=0.7, height=2.5, valign=dxfwrite.TOP, halign=dxfwrite.CENTER)\n drawing.add(pow_cab_name)\n drawing.add(pow_cab_type)\n\n drawing.add(dxf.line((x - 7, -54), (x - 7, -140), color=6))\n\n polyline1= dxf.polyline(linetype='DOT', color=6)\n polyline2 = dxf.polyline(linetype='DOT', color=6)\n\n polyline1.add_vertices([(x - 7, -57.23), (x - 6, -55.5), (x - 8, -55.5), (x - 7, -57.23)])\n polyline2.add_vertices([(x - 7, -134.76), (x - 6, -136.5), (x - 8, -136.5), (x - 7, -134.76)])\n\n drawing.add(polyline1)\n drawing.add(polyline2)\n\ndef one_line_cab_cont(x, name, cab_cont):\n\n cont_cab_name = dxf.mtext('к1-' + str(name), insert=(x + 7.50, -97.75), style='txt', rotation=90, xscale=0.7, height=2.5, valign=dxfwrite.BOTTOM, halign=dxfwrite.CENTER)\n cont_cab_type = dxf.mtext(str(cab_type_cont[cab_cont]), insert=(x + 8.50, -97.75), style='txt', rotation=90, xscale=0.7, height=2.5, valign=dxfwrite.TOP, halign=dxfwrite.CENTER)\n drawing.add(cont_cab_name)\n drawing.add(cont_cab_type)\n\n drawing.add(dxf.line((x + 7.5, -54), (x + 7.5, -140), color=3))\n\n polyline1 = dxf.polyline(linetype='DOT', color=3)\n polyline2 = dxf.polyline(linetype='DOT', color=3)\n\n polyline1.add_vertices([(x + 7.5, -57.23), (x + 6.5, -55.5), (x + 8.5, -55.5), (x + 7.5, -57.23)])\n polyline2.add_vertices([(x + 7.5, -134.76), (x + 6.5, -136.5), (x + 8.5, -136.5), (x + 7.5, -134.76)])\n\n drawing.add(polyline1)\n drawing.add(polyline2)\n\ndirectory = os.getcwd()\ndrawing = dxf.drawing('Oneline.dxf')\n\ndrawing.add_style('txt',\n height='2.5',\n font='txt',\n width='0.6')\ndrawing.add_layer('_hide_data',\n color='8')\n\nwr = xlrd.open_workbook('Расчет по мотор листу.xls', encoding_override='cp1252')\nws = wr.sheet_by_index(1)\nx = 0\n\nfor row_index in range(ws.nrows):\n\n name = ws.row(row_index)[0].value\n discr = ws.row(row_index)[1].value\n power = ws.row(row_index)[2].value\n voltage = ws.row(row_index)[3].value\n start_type = ws.row(row_index)[4].value\n scheme_code = ws.row(row_index)[5].value\n\n cab_pow = 'Cab1'\n cab_cont = 'Cab1'\n\n one_line_table(x,name,discr,power,voltage)\n one_line_cab_power(x, name, cab_pow)\n one_line_cab_cont(x, name, cab_cont)\n one_line_circ(x, name, power)\n one_line_kont(x, name, power)\n\n\n x = x + 30\n\ndrawing.save()","sub_path":"Draw/one_line txt.py","file_name":"one_line txt.py","file_ext":"py","file_size_in_byte":11296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"597279638","text":"#!/usr/bin/env python\n# coding:utf8\n\n\"\"\"\nthis module reads strings.csv, which contains all\nthe strings, and lets the main app use it\n\"\"\"\n\nimport sys\nimport csv\nimport os\nfrom flask import Markup\nimport configparser\n\nconfig = configparser.RawConfigParser()\npath = '../hseling_api_diachrony_webvectors/hseling_api_diachrony_webvectors/webvectors.cfg'\nassert os.path.isfile(path), \"Current path: {}\".format(os.getcwd())\nconfig.read(path)\n\nroot = config.get('Files and directories', 'root')\nl10nfile = config.get('Files and directories', 'l10n')\n\n# open the strings database:\ncsvfile = open(\"../hseling_lib_diachrony_webvectors/hseling_lib_diachrony_webvectors/\" + l10nfile, 'rU')\nacrobat = csv.reader(csvfile, dialect='excel', delimiter=',')\n\n# initialize a dictionary for each language:\nlanguage_dicts = {}\nlangnames = config.get('Languages', 'interface_languages').split(',')\nheader = next(acrobat)\nincluded_columns = []\nfor langname in langnames:\n language_dicts[langname] = {}\n included_columns.append(header.index(langname))\n\n# read the csvfile, populate language_dicts:\nfor row in acrobat:\n for i in included_columns: # range(1, len(row)):\n # Markup() is used to prevent autoescaping in templates\n if sys.version_info[0] < 3:\n language_dicts[header[i]][row[0]] = Markup(row[i].decode('utf-8'))\n else:\n language_dicts[header[i]][row[0]] = Markup(row[i])\n","sub_path":"hseling_lib_diachrony_webvectors/hseling_lib_diachrony_webvectors/strings_reader.py","file_name":"strings_reader.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"51634504","text":"\nimport numpy as np\n\nfrom tqdm import tqdm\nfrom layers import Linear, Softmax, ReLU, BatchNorm\n\nclass Net():\n # layers, weight regularization term, learning rate\n def __init__(self, layers=[], lam=0.1, l_rate=0.001, decay=None, mom=None):\n self.layers = layers\n self.lam = lam\n self.l_rate = l_rate\n self.decay = decay\n self.mom = mom\n\n def forward(self, inp, train=False):\n out = inp\n for l in self.layers:\n out = l.forward(out) if type(l) is not BatchNorm else l.forward(out, train)\n return out\n\n def backward(self, truth):\n for l in self.layers[::-1]:\n grad = l.backward(truth) if type(l) is Softmax else l.backward(grad)\n return grad\n\n def cost(self, truth, inp=None, out=None):\n out = self.forward(inp) if out is None else out\n c = [(l.cost(truth, out) if type(l) is Softmax else l.cost()) for l in self.layers]\n return np.sum(c)\n\n def accuracy(self, truth, inp=None, out=None):\n pred = self.forward(inp) if out is None else out\n N = truth.shape[1]\n pred = np.argmax(pred, axis=0)\n truth = np.argmax(truth, axis=0)\n return np.sum(pred == truth) / N\n\n def cost_acc(self, truth, inp=None, out=None):\n return self.cost(truth, inp, out), self.accuracy(truth, inp, out)\n\n def hidden_size(self):\n for l in self.layers:\n if not l.isActivation: return l.out_size\n return -1\n\n def trainMiniBatch(self, train, val, epochs=10, batch_size=200, shuffle=False):\n N = train['images'].shape[0]\n ind = np.arange(N)\n\n a_train, c_train, a_val, c_val = [], [], [], []\n trainImgT = train['images'].T\n trainTruthT = train['one_hot'].T\n valImgT = val['images'].T\n valTruthT = val['one_hot'].T\n\n for e in tqdm(range(epochs), ncols=50):\n if shuffle:\n np.random.shuffle(ind)\n\n for i in range(0, N, batch_size):\n batch_ind = ind[i: i + batch_size]\n x = train['images'][batch_ind].T\n truth = train['one_hot'][batch_ind].T\n\n # do the learning\n self.forward(x)\n self.backward(truth)\n self.update() if self.mom is None else self.updateMom()\n\n if self.decay is not None:\n self.l_rate *= self.decay\n\n\n # Measure each epoch\n cost, acc = self.cost_acc(trainTruthT, trainImgT)\n c_train.append(cost)\n a_train.append(acc)\n\n cost, acc = self.cost_acc(valTruthT, valImgT)\n c_val.append(cost)\n a_val.append(acc)\n\n if c_train[0]*3 < c_train[-1]:\n print(\"Cost is rising, early stopping...\")\n break\n return {\n 'epochs': epochs,\n 'N_hidden' : self.hidden_size(),\n 'lam' : self.lam,\n 'learning rate' : self.l_rate,\n 'decay rate' : self.decay,\n 'momentum' : self.mom,\n 'last_a_train' : a_train[-1],\n 'last_c_train' : c_train[-1],\n 'last_a_val' : a_val[-1],\n 'last_c_val' : c_val[-1],\n 'a_train' : a_train,\n 'c_train' : c_train,\n 'a_val' : a_val,\n 'c_val' : c_val,\n }\n\n def train(self, train, ind):\n inp = train['images'][:,ind]\n truth = train['one_hot'][:,ind]\n\n def update(self):\n for l in self.layers:\n l.update(self.l_rate)\n\n def updateMom(self):\n for l in self.layers:\n l.updateMom(self.l_rate, self.mom)\n","sub_path":"lab2/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":3647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"237778326","text":"import TypeGrille\nimport TypeBateau\nimport TypeFlotte\nimport TypeJoueur\n\ndef Main():\n print(\"Joueur1 veuillez posez vos bateaux :\")\n GrilleJoueur1=TypeGrille.Grille(21,21)\n Joueur1=InitJoueur(GrilleJoueur1)\n GrilleJoueur1.Affichage()\n print(\"Joueur2 veuillez posez vos bateaux :\")\n GrilleJoueur2=TypeGrille.Grille(21,21)\n Joueur2=InitJoueur(GrilleJoueur2)\n GrilleJoueur2.Affichage()\n cpt=1\n while Joueur1.FlotteJoueur().BateauxRestants()>0 and Joueur2.FlotteJoueur().BateauxRestants()>0:\n if cpt%2==1:\n print(\"C'est au tour de Joueur 1\")\n Joueur2=TourDeJeu(Joueur2)\n else:\n print(\"C'est au tour de Joueur 2\")\n Joueur1=TourDeJeu(Joueur1)\n cpt=cpt+1\n if Joueur1.FlotteJoueur().BateauxRestants()==0:\n print(\"Jeu terminé ! Victoire de Joueur 2 !\")\n else:\n print(\"Jeu terminé ! Victoire de Joueur 1 !\")\n\n\ndef TourDeJeu(joueur):\n#Données : Prend le joueur auquel ce n'est pas le tour\n#Résultat : Effectue un tour de jeu : demande des coordonnées de tir, vérifie si le tir est touché, à l'eau ou en vue. Dans le cas où le bateau est touché, verifie si ce bateau est coulé. Renvoie le joueur modifié.\n print(\"Donnez la coordonnée X de tir :\")\n TirX=int(input())\n print(\"Donnez la coordonnée Y de tir :\")\n TirY=int(input())\n if joueur.GrilleJoueur().Touche(TirX,TirY):\n tmp=joueur.GrilleJoueur().ValeurCoord(TirX,TirY)\n joueur.GrilleJoueur().ModifVal(0,TirX,TirY)\n print(\"Touché !\")\n if joueur.FlotteJoueur().Coule(tmp,joueur.GrilleJoueur()):\n print(\"Coulé !\")\n print(\"Nombre de bateaux restants : \",end=\" \")\n print(joueur.FlotteJoueur().BateauxRestants())\n elif joueur.GrilleJoueur().EnVue(TirX,TirY):\n print(\"En Vue !\")\n else:\n print(\"A l'eau !\")\n return joueur\n \n \n \n \ndef InitJoueur(Grille):\n#Données: prend une grille\n#Résultat : retourne un joueur qui a une flotte et une grille avec les 5 bateaux placés\n Bateau1=AjouterBateau(1,1,Grille)\n Grille.PositionnerBateau(Bateau1)\n Bateau2=AjouterBateau(2,2,Grille)\n Grille.PositionnerBateau(Bateau2)\n Bateau3=AjouterBateau(3,3,Grille)\n Grille.PositionnerBateau(Bateau3)\n Bateau4=AjouterBateau(3,4,Grille)\n Grille.PositionnerBateau(Bateau4)\n Bateau5=AjouterBateau(4,5,Grille)\n Grille.PositionnerBateau(Bateau5)\n Flotte=TypeFlotte.Flotte(Bateau1,Bateau2,Bateau3,Bateau4,Bateau5)\n Joueur=TypeJoueur.Joueur(Flotte,Grille)\n return Joueur\n\n\ndef AjouterBateau(taille,numero,grille):\n#Données: prend une taille de bateau, un numéro de bateau et une grille\n#Résultat: Demande les coordonnées et la direction d'un bateau et renvoie le bateau créer si la position est valide, retourne la fonction sinon\n#P1 : taille>0\n#P2 : numero>0\n print(\"Entrez la colonne du bateau numero \",end=\" \")\n print(numero,end=\" \")\n print(\" de taille \",end=\" \")\n print(taille)\n PosX=int(input())\n print(\"Entrez la ligne du bateau numero \",end=\" \")\n print(numero,end=\" \")\n print(\" de taille \",end=\" \")\n print(taille)\n PosY=int(input())\n print(\"Entrez la direction du bateau numero \",end=\" \")\n print(numero,end=\" \")\n print(\" de taille \",end=\" \")\n print(taille,end=\" \")\n print(\"(0 pour horizontale et 1 pour verticale)\")\n Direction=int(input())\n Bateau=TypeBateau.Bateau(PosX,PosY,taille,numero,Direction)\n if grille.Verification(Bateau):\n print(\"Bateau bien positionner\")\n return Bateau\n else:\n print(\"Position invalide, recommencer\")\n return AjouterBateau(taille,numero,grille)\n\n \nif __name__ == '__main__':\n Main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"612099466","text":"import tensorflow as tf\nimport numpy as np\n\nclass Constants:\n GLOBAL_SCOPE = 'Global'\n\n DEFAULT_ACTIONS = [\n 0, # no_op ()\n #1, # move_camera (1/minimap [64, 64])\n #5, # select_unit (8/select_unit_act [4]; 9/select_unit_id [500])\n 7, # select_army (7/select_add [2])\n 331, # Move_screen (3/queued [2]; 0/screen [84, 84])\n 332 # Move_minimap (3/queued [2]; 1/minimap [64, 64])\n ]\n\n UNIT_ELEMENTS = 7\n MAXIMUM_CARGO = 10\n MAXIMUM_BUILD_QUEUE = 10\n MAXIMUM_MULTI_SELECT = 10\n\n\ndef print_tensors(obj):\n for variable_name, tensor in vars(obj).items():\n if isinstance(tensor, tf.Tensor):\n print('{}:\\t({} Shape={})'.format(variable_name, tensor.name, tensor.shape))\n\n\ndef discount_rewards(rewards, gamma = 0.99):\n \"\"\" take 1D float array of rewards and compute discounted reward \"\"\"\n discounted_rewards = np.zeros_like(rewards)\n running_add = 0\n for t in reversed(range(0, len(rewards))):\n running_add = running_add * gamma + rewards[t]\n discounted_rewards[t] = running_add\n return discounted_rewards\n","sub_path":"SquaredAI/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"235878038","text":"from __future__ import print_function\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport tarfile\nimport urllib.request\nimport zipfile\nfrom glob import glob\nimport argparse\n\nfrom config import data_url, data_dir\n\ndef download_flight_data(url, data_dir=\"data\", n_rows=None):\n flights_raw = os.path.join(data_dir, 'nycflights.tar.gz')\n flightdir = os.path.join(data_dir, 'nycflights')\n jsondir = os.path.join(data_dir, 'flightjson')\n\n if not os.path.exists(data_dir):\n os.mkdir(data_dir)\n\n if not os.path.exists(flights_raw):\n print(\"- Downloading NYC Flights dataset... \", end='', flush=True)\n urllib.request.urlretrieve(url, flights_raw)\n print(\"done\", flush=True)\n\n if not os.path.exists(flightdir):\n print(\"- Extracting flight data... \", end='', flush=True)\n tar_path = os.path.join('data', 'nycflights.tar.gz')\n with tarfile.open(tar_path, mode='r:gz') as flights:\n flights.extractall('data/')\n print(\"done\", flush=True)\n\n # Note: I opted not to bother with JSON here\n\n print(\"** Finished! **\")\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n \n parser.add_argument('-u', '--url',\n default=data_url,\n help=\"Dataset source URL\")\n parser.add_argument('-d', '--datadir', default=data_dir, \n help=\"output directory\")\n parser.add_argument('-n', '--nrows',default=None,\n help=\"Number of rows to keep\")\n\n args = parser.parse_args()\n download_flight_data(url=args.url, data_dir=args.datadir, n_rows=args.nrows)\n\n","sub_path":"Week 2/Day 3/Submissions/satyarth/download_flights_data.py","file_name":"download_flights_data.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"395288753","text":"import os\nli = []\n\nfor filename in os.listdir(os.getcwd()):\n if 'icons8' in filename:\n name = filename.replace('icons8-','')\n name = name.replace('-50','')\n li.append('icons/' + name + '')\n os.rename(filename,name)\n\n with open('qrc.txt', 'w') as f:\n for item in li:\n f.write(\"%s\\n\" % item)","sub_path":"icons/renamer.py","file_name":"renamer.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"235138723","text":"\nimport torch\nfrom torch.utils.data import DataLoader\nimport torchvision\nfrom torchvision import transforms\nfrom torchvision.datasets import MNIST, CIFAR10\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass Encoder(torch.nn.Module):\n def __init__(self, input_size):\n super().__init__()\n self.fc1 = torch.nn.Linear(input_size, 512)\n self.fc2 = torch.nn.Linear(512, 64)\n self.fc3 = torch.nn.Linear(64, 16)\n self.fc4 = torch.nn.Linear(16, 2)\n def forward(self, x):\n x = torch.relu(self.fc1(x))\n x = torch.relu(self.fc2(x))\n x = torch.relu(self.fc3(x))\n x = self.fc4(x)\n return x\n\nclass Decoder(torch.nn.Module):\n def __init__(self, output_size):\n super().__init__()\n self.fc1 = torch.nn.Linear(2, 16)\n self.fc2 = torch.nn.Linear(16, 64)\n self.fc3 = torch.nn.Linear(64, 512)\n self.fc4 = torch.nn.Linear(512, output_size)\n def forward(self, x):\n x = torch.relu(self.fc1(x))\n x = torch.relu(self.fc2(x))\n x = torch.relu(self.fc3(x))\n x = torch.tanh(self.fc4(x)) # -1~1に変換\n return x\n\nclass AutoEncoder(torch.nn.Module):\n def __init__(self, org_size):\n super().__init__()\n self.enc = Encoder(org_size)\n self.dec = Decoder(org_size)\n def forward(self, x):\n x = self.enc(x)\n x = self.dec(x)\n return x\n\ndef get_dataset(batch_size):\n\n transform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n\n trainset = torchvision.datasets.CIFAR10(root='./data', train=True,\n download=True, transform=transform)\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,\n shuffle=True, num_workers=2)\n\n testset = torchvision.datasets.CIFAR10(root='./data', train=False,\n download=True, transform=transform)\n testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,\n shuffle=False, num_workers=2)\n\n return trainloader, testloader\n\n\ndef imshow(img):\n img = torchvision.utils.make_grid(img)\n img = img / 2 + 0.5\n npimg = img.detach().numpy()\n plt.imshow(np.transpose(npimg, (1, 2, 0)))\n plt.show()\n# plt.savefig('figure.png') # -----(2)\n\ndef train(net, criterion, optimizer, epochs, trainloader, input_size):\n losses = []\n output_and_label = []\n\n for epoch in range(1, epochs+1):\n print(f'epoch: {epoch}, ', end='')\n running_loss = 0.0\n for counter, (img, _) in enumerate(trainloader, 1):\n optimizer.zero_grad()\n img = img.reshape(-1, input_size)\n output = net(img)\n loss = criterion(output, img)\n loss.backward()\n optimizer.step()\n running_loss += loss.item()\n avg_loss = running_loss / counter\n losses.append(avg_loss)\n print('loss:', avg_loss)\n output_and_label.append((output, img))\n print('finished')\n return output_and_label, losses\n\ndef main():\n\n\n batch_size = 10\n\n trainloader, testloader = get_dataset(batch_size) #train用とtest用のdatasetを作成\n \"\"\"\n iterator = iter(trainloader)\n x, _ = next(iterator)\n imshow(x)\n \"\"\"\n\n input_size = 32 * 32\n net = AutoEncoder(input_size)\n criterion = torch.nn.MSELoss()\n optimizer = torch.optim.SGD(net.parameters(), lr=0.1)\n EPOCHS = 100\n\n output_and_label, losses = train(net, criterion, optimizer, EPOCHS, trainloader, input_size)\n\n plt.plot(losses)\n\n\n output, org = output_and_label[-1]\n imshow(org.reshape(-1, 3, 32, 32))\n imshow(output.reshape(-1, 3, 32, 32))\n\nif __name__ == '__main__':\n main()\n","sub_path":"autoencoder_linear_cifar.py","file_name":"autoencoder_linear_cifar.py","file_ext":"py","file_size_in_byte":3853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"273700399","text":"# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\nimport treecode.energy_and_momentum as EM\r\n\r\n\r\ndef is_gravity_field_weak(particles, C_2):\r\n # Функция, выдающая ошибку, если гравитационное поле становится\r\n # слишком сильным для применения используемой модели\r\n ERROR_NAME = ''\r\n # Считаем величину phi / c^2, где phi - гравитационный потенциал\r\n array_phi = abs(particles[:, 10] / C_2)\r\n # если модуль phi / c^2 превышает определенное значение, то\r\n # гравитационное поле считаем сильным что выходит за границы\r\n # применимости используемой модели\r\n array_phi = array_phi >= 0.05\r\n if array_phi.any():\r\n ERROR_NAME = 'Strong gravity field error'\r\n return ERROR_NAME\r\n\r\n\r\ndef speed_limit(particles, C_2):\r\n # Функция, выдающая ошибку если скорость материальной\r\n # точки станет больше скорости света\r\n ERROR_NAME = ''\r\n v = np.zeros([np.size(particles, 0), 3])\r\n v = np.multiply(particles[:, 3:6], particles[:, 3:6])\r\n v_2 = v.sum(axis=1) >= C_2\r\n if v_2.any():\r\n ERROR_NAME = 'FTL error'\r\n return ERROR_NAME\r\n\r\n\r\ndef enegry_parameters(q, X):\r\n # Считаем количество вылетевших из системы частиц\r\n part_num = 0\r\n while X[part_num, 11] < 0:\r\n part_num += 1\r\n if part_num == (np.size(X, 0)):\r\n break\r\n momentum = EM.momentum_of_system(X)\r\n kinetic_energy = EM.system_kinetic_energy(X)\r\n potential_energy = EM.system_potential_energy(X)\r\n kinetic_in_volume = EM.kinetic_energy_in_volume(X, part_num)\r\n potential_in_volume = EM.potential_energy_in_volume(X, part_num)\r\n virial_coeff_system = - kinetic_energy / potential_energy\r\n virial_coeff_selected_volume = - kinetic_in_volume / potential_in_volume\r\n# momentum_in_volume = EM.momentum_of_system_in_volume(X, part_num)\r\n # Записываем энергию системы в отдельный массив\r\n # 1) номер шага\r\n # 2) кинетическая энергия всей системы\r\n # 3) потенциальная энергия всей системы\r\n # 4) полная энергия всей системы\r\n # 5) максимальная разница в кинетической энергии\r\n # между исследуемым шагом и предыдущим\r\n # 6) максимальная разница в потенциальной энергии\r\n # между исследуемым шагом и предыдущим\r\n # 7) импульс системы по оси X\r\n # 8) импульс системы по оси Y\r\n # 9) импульс системы по оси Z\r\n # 10) кинетическая энергия всех частиц в объеме\r\n # 11) потенциальная энергия всех частиц в объеме\r\n # 12) полная энергия всех частиц в объеме\r\n ENERGY = [q,\r\n kinetic_energy,\r\n potential_energy,\r\n EM.system_energy_Newton(X),\r\n EM.max_dT(X),\r\n EM.max_dU(X),\r\n momentum[0],\r\n momentum[1],\r\n momentum[2],\r\n kinetic_in_volume,\r\n potential_in_volume,\r\n EM.system_energy_in_volume(X, part_num),\r\n virial_coeff_system,\r\n virial_coeff_selected_volume]\r\n return ENERGY\r\n","sub_path":"treecode/telemetry.py","file_name":"telemetry.py","file_ext":"py","file_size_in_byte":3760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"452708048","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 3 07:37:58 2020\n\n@author: cweic\n\"\"\"\n\nfrom __future__ import print_function\nimport cv2\nimport numpy as np\n \n \nMAX_FEATURES = 40000\nGOOD_MATCH = 100\n \n \ndef alignImages(im1, im2):\n \n # Convert images to grayscale\n im1Gray = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY)\n im2Gray = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY)\n \n # Detect ORB features and compute descriptors.\n orb = cv2.ORB_create(nfeatures = MAX_FEATURES, scaleFactor = 1.2,\n nlevels = 4, edgeThreshold = 20,\n firstLevel = 0, WTA_K = 3,\n patchSize = 20, fastThreshold = 20)\n keypoints1, descriptors1 = orb.detectAndCompute(im1Gray, None)\n keypoints2, descriptors2 = orb.detectAndCompute(im2Gray, None)\n \n # Match features.\n matcher = cv2.DescriptorMatcher_create(cv2.DESCRIPTOR_MATCHER_BRUTEFORCE_HAMMING)\n matches = matcher.match(descriptors1, descriptors2, None)\n \n # Sort matches by score\n matches.sort(key=lambda x: x.distance, reverse=False)\n \n # Remove not so good matches\n # numGoodMatches = int(len(matches) * GOOD_MATCH_PERCENT)\n matches = matches[:GOOD_MATCH]\n SumMatches = 0\n for m in matches:\n #print(m.distance)\n SumMatches = SumMatches+m.distance\n \n # Draw top matches\n imMatches = cv2.drawMatches(im1, keypoints1, im2, keypoints2, matches, None)\n cv2.imwrite(\"matches.jpg\", imMatches)\n \n # Extract location of good matches\n points1 = np.zeros((len(matches), 2), dtype=np.float32)\n points2 = np.zeros((len(matches), 2), dtype=np.float32)\n \n for i, match in enumerate(matches):\n points1[i, :] = keypoints1[match.queryIdx].pt\n points2[i, :] = keypoints2[match.trainIdx].pt\n \n # Find homography\n M, mask = cv2.findHomography(points1, points2, cv2.RANSAC)\n \n \n # Use homography\n h,w = im1Gray.shape\n pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2)\n dst = cv2.perspectiveTransform(pts,M)\n im1Reg = cv2.polylines(im2Gray,[np.int32(dst)],True,255,3, cv2.LINE_AA)\n #im1Reg = cv2.warpPerspective(im1, h, (width, height))\n \n return im1Reg, SumMatches\n \n \nif __name__ == '__main__':\n \n # Read reference image\n refFilename = \"Find2.jpg\"\n print(\"Reading reference image : \", refFilename)\n imReference = cv2.imread(refFilename, cv2.IMREAD_COLOR)\n \n # Read image to be aligned\n imFilename = \"Orig4.jpg\"\n print(\"Reading image to align : \", imFilename); \n im = cv2.imread(imFilename, cv2.IMREAD_COLOR)\n \n print(\"Aligning images ...\")\n # Registered image will be resotred in imReg. \n # The estimated homography will be stored in h. \n imReg, SumMatches = alignImages(im, imReference)\n \n # Write aligned image to disk. \n outFilename = \"aligned.jpg\"\n print(\"Saving aligned image : \", outFilename); \n cv2.imwrite(outFilename, imReg)\n \n # Print estimated homography\n print(\"Estimated Quality : \\n\", SumMatches)","sub_path":"Homography.py","file_name":"Homography.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"533686259","text":"import pygame, sys\nfrom pygame.locals import *\npygame.init()\n\nscreen = pygame.display.set_mode((640, 480))\nscreen.fill((0, 0, 0, 255))\npygame.display.set_caption(\"Pygame Music Player\")\n\npygame.mixer.music.load(\"Superman.mp3\")\nprint(\"Superman The Movie Theme!\")\nprint(\"Loading Music...\")\npygame.mixer.music.play(-1, 0.0)\n\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n pygame.display.update()\n","sub_path":"Pygame Music Player/MusicPlay.py","file_name":"MusicPlay.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"169414651","text":"# encoding: utf-8\r\n\r\n\"\"\"\r\n@author: Hengyu Jiang\r\n@file: app.py\r\n@time: 2019/7/7 20:05\r\n\"\"\"\r\n\r\nfrom MatrixManager import MatrixTransformer, MT\r\nfrom MainUI import mainUI\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n matrix = [[1, -2, 1],\r\n [-2, 1, 1],\r\n [1, 1, -2]]\r\n MT = MatrixTransformer(matrix=None)\r\n\r\n mainUI(MT)\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"90045176","text":"from modules.Modules import Core\n\nclass Lab2App():\n def __init__(self):\n while 1:\n\n self.Core = Core()\n print('\\nВведите число из которого необходимо извлечь корень:')\n self.Input = input()\n self.Output = self.Core.Sqrt(float(self.Input))\n print(round(self.Output, 5))\n print('\\nДля продолжения введите 1 \\nДля выхода введите 2')\n p = input()\n if p == '2':\n break;\n","sub_path":"OOP/lab2/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"151679273","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\nait=pd.read_csv(\"Python programs/atria_ise.csv\")\r\nait.set_index('USN', inplace=True)\r\nusn=input(\"Enter USN for result(eg:RES15IS063):\")\r\nmarks=ait.loc[usn] \r\nsubject = ['ME','CN','ADV JAVA','DBMS','FLAT','CC','CN Lab','DBMS Lab']\r\n\r\ncolors = []\r\nfor i in marks: \r\n if i < 40:\r\n colors.append('red')\r\n else:\r\n colors.append('blue')\r\n \r\n\r\nplt.bar(range(len(marks)), marks, color = colors,width=0.50) \r\nplt.xlabel('SUBJECT')\r\nplt.ylabel('SCORE')\r\nplt.title(usn,color='green')\r\nplt.xticks(range(len(marks)), subject)\r\nplt.xticks(rotation=0)\r\nplt.ylim(0,100)\r\nplt.legend(title='RESULT',labels=['Pass','Fail'])\r\nplt.show()\r\n \r\n\r\n #marks.plot(kind = 'bar', color = colors)\r\n\r\n \r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"result_bar.py","file_name":"result_bar.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"181394804","text":"###############################################################################\n# -*- coding: utf-8 -*- \n# Authors: Pu Du\n###############################################################################\n\nimport numpy as np\nfrom numpy.linalg import norm\nfrom loader import XYZLoader\n\ndef angle(A, B, C):\n \"\"\"calculate the cos(theta)\"\"\"\n BA = A - B\n BC = C - B\n theta = np.dot(BA, BC)/(norm(BA)*norm(BC))\n return theta\n\ndef fc(Rij, Rc):\n \"\"\"cutoff function\"\"\"\n if Rij > Rc:\n return 0.\n else:\n return 0.5 * (np.cos(np.pi * Rij / Rc) + 1.)\n\ndef g1(Rij, Rc):\n \"\"\"type 1 of fingerprint\"\"\"\n return fc(Rij, Rc)\n\ndef g2(Rij, Rc, Rs, etha):\n \"\"\"type 1 of fingerprint\"\"\"\n return np.exp(-eta * (Rij - Rs) ** 2 / (Rc ** 2)) * fc(Rij, Rc)\n\ndef g3(Rij, Rc, kappa):\n \"\"\"type 3 of fingerprint\"\"\"\n return np.cos(kappa * Rij) * fc(Rij, Rc)\n\ndef g4(Rij, Rik, Rjk, Rc, Rs, zeta, lmb, theta, etha):\n \"\"\"type 4 of fingerprint\"\"\"\n return (1 + lmb * theta) * np.exp(-etha * (Rij ** 2 + Rik ** 2 + Rjk ** 2)) * \\\n fc(Rij, Rc) * fc(Rik, Rc) * fc(Rjk, Rc)\n\ndef g5(Rij, Rik, Rjk, Rc, Rs, zeta, lmb, theta, etha):\n \"\"\"type 4 of fingerprint\"\"\"\n return (1 + lmb * theta) * np.exp(-etha * (Rij ** 2 + Rik ** 2)) * \\\n fc(Rij, Rc) * fc(Rik, Rc)\n\n\nclass FingerPrint(object):\n \"\"\"class of calculating fingerprints\"\"\"\n\n def __init__(self, trajectory):\n self.traj = trajectory\n\n def neighbors(self, coords):\n \"\"\"calculate neighbors\"\"\"\n n_atoms = self.traj.n_atoms\n dist = np.zeros([n_atoms, n_atoms], dtype=np.float)\n for i in range(n_atoms):\n tmp = np.sqrt((coords - coords[i]) ** 2).sum(axis=1)\n dist[:, i] = tmp\n return dist\n\n def G1(self, coords, Rc):\n \"\"\" calculate g1 fingerprints\"\"\"\n dist = self.neighbors(coords)\n x, y = dist.shape\n finger = np.zeros(x).reshape(x,1)\n for i in range(x):\n for j in range(y):\n if i != j:\n tmp = g1(dist[i][j], Rc)\n finger[i] += tmp\n return finger\n \n def G2(self, coords, Rc, Rs, theta):\n \"\"\" calculate g2 fingerprints\"\"\"\n dist = self.neighbors(coords)\n x, y = dist.shape\n finger = np.zeros(x).reshape(x,1)\n for i in range(x):\n for j in range(y):\n if i != j:\n tmp = g2(dist[i][j], Rc, Rs, theta)\n finger[i] += tmp\n return finger\n\n def G3(self, coords, Rc, kappa):\n \"\"\" calculate g3 fingerprints\"\"\"\n dist = self.neighbors(coords)\n x, y = dist.shape\n finger = np.zeros(x).reshape(x,1)\n for i in range(x):\n for j in range(y):\n if i != j:\n tmp = g3(dist[i][j], Rc, kappa)\n finger[i] += tmp\n return finger \n\n \n def G4(self, coords, Rc, Rs, zeta, lmb, theta, etha):\n \"\"\" calculate g4 fingerprints\"\"\"\n dist = self.neighbors(coords)\n x, y = dist.shape\n finger = np.zeros(x).reshape(x,1)\n for i in range(x):\n for j in range(x):\n for k in range(x):\n if i != j and j != k and i != k:\n tmp = g4(dist[i][j],\n dist[i][k],\n dist[j][k],\n Rc, Rs, zeta, lmb,\n theta, etha)\n finger[i] += tmp\n return finger\n\n def G5(self, coords, Rc, Rs, zeta, lmb, etha):\n \"\"\" calculate g4 fingerprints\"\"\"\n dist = self.neighbors(coords)\n x, y = dist.shape\n finger = np.zeros(x).reshape(x,1)\n for i in range(x):\n for j in range(x):\n for k in range(x):\n if i != j and j != k and i != k:\n theta = angle(coords[i], coords[j], coords[k])\n\n tmp = g5(dist[i][j], dist[i][k], dist[j][k],\n Rc, Rs, zeta, lmb, theta, etha)\n\n finger[i] += tmp\n return finger\n\nif __name__ == '__main__':\n\n a = XYZLoader('hcl_10_wat-traj.xyz')\n b = FingerPrint(a)\n #finger1 = b.G1(b.traj.coords[0], 4)\n finger1 = b.G5(b.traj.coords[0], 4, 0, 1, 0, 0)\n for c in b.traj.coords:\n print(c.shape)","sub_path":"blackbox/fingerprint.py","file_name":"fingerprint.py","file_ext":"py","file_size_in_byte":4394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"463414860","text":"from django.contrib.auth.models import User\nfrom django.db import models\n\n\nclass TimeStampedModel(models.Model):\n created = models.DateTimeField(\n 'criado em',\n auto_now_add=True,\n auto_now=False\n )\n modified = models.DateTimeField(\n 'modificado em',\n auto_now_add=False,\n auto_now=True\n )\n\n class Meta:\n abstract = True\n\n\nclass Active(models.Model):\n active = models.BooleanField('ativo', default=True)\n\n class Meta:\n abstract = True\n\n\nclass UserProfile(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n\n class Meta:\n verbose_name = 'Perfil'\n verbose_name_plural = 'Profiles'\n\n\nclass Company(models.Model):\n name = models.CharField('Nome', max_length=50)\n address = models.CharField('Endereço', max_length=100)\n phone = models.CharField('Telefone', max_length=20)\n website = models.URLField('Website')\n facebook = models.URLField('Facebook')\n instagram = models.URLField('Instagram')\n\n def __str__(self):\n return str(self.name)\n\n class Meta:\n verbose_name = 'Informações da Empresa'\n verbose_name_plural = 'Informações da Empresa'\n","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"651540293","text":"\"\"\"\r\nwizard mode for html_builder project (user inputs)\r\nauthor: aby tiet\r\nfile name: html_builder_wizardmode.py\r\n\"\"\"\r\n\r\nimport html_builder\r\n\r\ndef image_inputs():\r\n \"\"\"\r\n takes in user info about images for a paragraph\r\n :return: list of images\r\n \"\"\"\r\n img_list = []\r\n image_check = input(\"Do you want to add images? [yes] \")\r\n if image_check == \"yes\" or image_check == \"\":\r\n while True:\r\n my_img = input(\"Image file name: \")\r\n if my_img in html_builder.IMAGES:\r\n img_list.append(html_builder.Image(my_img, None))\r\n break\r\n else:\r\n print(\"Please provide an image that is in the images folder\")\r\n while True:\r\n another_img = input(\"Do you want to add another image? [yes] \")\r\n if another_img == \"yes\" or \"\":\r\n while True:\r\n my_img = input(\"Image file name: \")\r\n if my_img in html_builder.IMAGES:\r\n img_list.append(html_builder.Image(my_img, None))\r\n break\r\n else:\r\n print(\"Please provide an image that is in the images folder\")\r\n else:\r\n return img_list\r\n else:\r\n return img_list\r\n\r\n\r\ndef paragraph_inputs():\r\n \"\"\"\r\n takes in user inputs for paragraphs\r\n :return: list of paragraph objects\r\n \"\"\"\r\n paragraph_list = []\r\n while True:\r\n p_heading = input(\"Title of your paragraph: \")\r\n content = input(\"Content of your paragraph (single line)\\n\")\r\n img_list = image_inputs()\r\n paragraph_list.append(html_builder.Paragraph(p_heading, content, img_list))\r\n more_para = input(\"Do you want to add another paragraph? [yes] \")\r\n if more_para == \"yes\" or \"\":\r\n pass\r\n else:\r\n return paragraph_list","sub_path":"html_builder_wizardmode.py","file_name":"html_builder_wizardmode.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"633642876","text":"\n'''_____Standard imports_____'''\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n'''_____Project imports_____'''\nfrom toolbox.maths import unwrap_phase\nfrom toolbox.loadings import load_data\nfrom toolbox.filters import butter_highpass_filter\nfrom toolbox.plottings import plots_signals\n\n\nclass Spectra(object):\n\n def __init__(self, data_dir, background_dir = None, ref_dir = None, sample_dir = None):\n\n self.data_dir = data_dir\n\n self.background_dir = background_dir\n\n self.ref_dir = ref_dir\n\n self.sample_dir = sample_dir\n\n\n def load_data(self):\n \"\"\" This method serve to load the data, i.e, mirror, darf_ref, dark_not,\n dark_sample.\n\n \"\"\"\n self.raw = []\n\n file = open(self.data_dir,'r')\n\n for line in file:\n\n self.raw.append(float(line))\n\n self.raw = np.array(self.raw)\n\n\n def get_phase(self):\n \"\"\" This method compute the phase of the processed spectra.\n\n \"\"\"\n self.phase = unwrap_phase(self.sub_raw)\n\n self.phase -= self.phase[0]\n\n\n def process_data(self, plot=True):\n \"\"\" This method compute the processing of data, i.e,\n background removal + high pass filter.\n\n \"\"\"\n\n self.sub_raw = self.raw\n self.sub_raw -= self.sub_raw[0]\n if self.background_dir:\n self.background = load_data(self.background_dir)\n self.sub_raw += self.background\n\n if self.sample_dir:\n self.sample = load_data(self.sample_dir)\n self.sub_raw -= self.sample\n\n if self.ref_dir:\n self.ref = load_data(self.ref_dir)\n self.sub_raw -= self.ref\n\n self.sub_raw = butter_highpass_filter(self.sub_raw,\n cutoff=280,\n fs=40000,\n order=4)\n\n\n if plot:\n\n plots_signals(self.raw,\n self.sub_raw,\n [1],\n [1],\n [1])\n \"\"\"\n plots_signals(self.raw,\n self.sub_raw,\n self.ref,\n self.sample,\n self.background)\"\"\"\n","sub_path":"PyOCTCalibration/toolbox/PySpectra.py","file_name":"PySpectra.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"613535604","text":"import os\nimport numpy as np\n\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Conv2D, Dropout, Flatten, MaxPooling2D\nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras import activations\nfrom functools import partial\n\nfrom matplotlib import pyplot as plt\nfrom sklearn.datasets import make_regression\n\n# MNIST digits data\n#data_dict = np.load(\"./Data/mnist.npz\")\n#x_train, y_train = data_dict['x_train'], data_dict['y_train']\n#x_test, y_test = data_dict['x_test'], data_dict['y_test']\n\n# MNIST fashion data\n(x_train, y_train), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data()\n\ntrain_sample_size = 60000 #60000\ntest_sample_size = 100\n\nx_train, y_train, x_test, y_test = x_train[:train_sample_size], y_train[:train_sample_size], x_test[:test_sample_size], y_test[:test_sample_size]\n\n# Flatten the images to 1D array for the DNN model input\nx_train = x_train.reshape(train_sample_size, 784)\nx_test = x_test.reshape(test_sample_size, 784)\ninput_shape = (784, )\n\n# Input shape and data type\ninput_shape = (784, )\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\n\n# Normalizing the RGB codes by dividing it to the max RGB value.\nx_train /= 255\nx_test /= 255\n\n# Optimizers for DNN\nlearning_rate = 0.1\nSGD = optimizers.SGD(learning_rate)\n#ADAM = optimizers.Adam(learning_rate)\n\nnodes_list1 = [[8, 8, 8], [16, 16, 16], [32, 32, 32], [64, 64, 64], [256, 256, 256]]\nnodes_list2 = [[8, 16, 32], [16, 32, 64], [32, 64, 128], [64, 128, 256], [128, 256, 512]]\nnodes_list3 = [[16, 8, 4], [32, 16, 8], [64, 32, 16], [128, 64, 32], [512, 256, 128]]\nnodes_list4 = [[16, 8, 16], [32, 16, 32], [64, 32, 64], [128, 64, 128], [512, 256, 512]]\nnodes_list5 = [[8, 16, 8], [16, 32, 16], [32, 64, 32], [64, 128, 64], [256, 512, 256]]\nnodes_lists = nodes_list1 + nodes_list2 + nodes_list3 + nodes_list4 + nodes_list5\n\nalpha_step_size = 0.1\nalpha_steps = 11 #11\narch_shapes = len(nodes_lists)\nsamples = 20 #20\nepochs = 20 #30\n\nPerf_array = np.zeros((samples, arch_shapes, alpha_steps, 4), dtype=np.float32)\n\nfor sample in range(samples):\n print(\"\\nSample [\", sample, \"] =======================>>\")\n \n for arch in range(arch_shapes):\n print(\"\\n........ ARC [\", nodes_lists[arch], \"] ........\")\n \n nodes1, nodes2, nodes3 = nodes_lists[arch][0], nodes_lists[arch][1], nodes_lists[arch][2]\n \n for i in range(alpha_steps):\n\n alpha = i*alpha_step_size\n\n if i == 0:\n act = activations.relu\n else:\n act = partial(tf.nn.leaky_relu, alpha=alpha)\n\n model = Sequential()\n model.add(Dense(nodes1, activation=act, input_shape=input_shape))\n model.add(Dense(nodes2, activation=act))\n model.add(Dense(nodes3, activation=act))\n model.add(Dense(10, activation='softmax'))\n\n model.compile(optimizer=SGD,\n loss=\"sparse_categorical_crossentropy\",\n metrics=['accuracy'])\n\n history = model.fit(x_train, y_train, validation_split=0.33, epochs=epochs, batch_size=64, verbose=0)\n\n tr_acc = np.amax(history.history['accuracy'])\n tr_loss = np.amin(history.history['loss'])\n val_acc = np.amax(history.history['val_accuracy'])\n val_loss= np.amin(history.history['val_loss'])\n\n Perf_array[sample][arch][i][:] = tr_acc*100.0, tr_loss, val_acc*100.0, val_loss\n\n print(np.round(alpha, 2), ',\\t', np.round(val_loss, 4), ',\\t', np.round(val_acc*100.0, 4))\n \nnp.save(\"./par_alpha_Results/performance_fashion_num_par_vs_alpha.npy\", Perf_array)\nprint(\"\\n_______ END_______\\n\")\n \n","sub_path":"Performance_vs_num_par/num_par_vs_alpha_fashion.py","file_name":"num_par_vs_alpha_fashion.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"108856604","text":"\"\"\"\n Constants and Utility Functions\n\"\"\"\n\nimport os\nimport cv2\nimport torch\nfrom torchvision import transforms\nfrom termcolor import colored\nos.system(\"color\")\n\n# Self Aware Dataset Directory\nDATASET_PATH = os.path.join(os.getcwd(), \"Datasets\")\nif not os.path.exists(DATASET_PATH):\n os.makedirs(DATASET_PATH)\n# DATASET_PATH = os.path.join(os.path.dirname(__file__), \"Datasets\")\n\n# Capture object Attributes\nCAM_WIDTH, CAM_HEIGHT, FPS, DELAY = 640, 360, 30, 5\n\n# DL Model Constants\nIMAGENET_MEAN = [0.485, 0.456, 0.406]\nIMAGENET_STD = [0.229, 0.224, 0.225]\nROI_TRANSFORM = transforms.Compose([transforms.ToTensor(), ])\nFEA_TRANSFORM = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD),])\nDEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nSIZE = 224\nSEED = 0\nRELIEF = 25\nFEATURE_VECTOR_LENGTH = 2048\n\n# GUI Color Schemes\nGUI_ORANGE = (255, 165, 0)\nGUI_RED = (255, 0, 0)\nGUI_GREEN = (0, 255, 0)\n\n# ****************************************** Default CLI Arguments *************************************************** #\nembed_layer_size = 2048\nnum_samples = 2500\nepochs = 1000\nlower_bound_confidence = 0.95\nupper_bound_confidence = 0.99\ndevice_id = 0\nearly_stopping_step = 50\n# ******************************************************************************************************************** #\n\n# LineBreaker\ndef breaker(num=50, char=\"*\"):\n print(colored(\"\\n\" + num*char + \"\\n\", color=\"magenta\"))\n\n\n# Custom Print Function\ndef myprint(text, color, on_color=None):\n print(colored(text, color=color, on_color=on_color))\n\n\n# CLAHE Preprocessing (Cliplimit: 2.0, TileGridSize: (2, 2))\ndef clahe_equ(image):\n clahe = cv2.createCLAHE(clipLimit=2, tileGridSize=(2, 2))\n for i in range(3):\n image[:, :, i] = clahe.apply(image[:, :, i])\n return image\n\n\n# Center Crop (Resize to 256x256, then center crop the 224x224 region)\ndef preprocess(image, change_color_space=True):\n if change_color_space:\n image = cv2.cvtColor(src=image, code=cv2.COLOR_BGR2RGB)\n image = cv2.resize(src=image, dsize=(256, 256), interpolation=cv2.INTER_AREA)\n h, w, _ = image.shape\n cx, cy = w // 2, h // 2\n return image[cy - 112:cy + 112, cx - 112:cx + 112, :]\n\n# ******************************************************************************************************************** #\n\n# Normalize the vector to a min-max of [0, 1]\ndef normalize(x):\n for i in range(x.shape[0]):\n x[i] = (x[i] - torch.min(x[i])) / (torch.max(x[i]) - torch.min(x[i]))\n return x\n\n# ******************************************************************************************************************** #\n\n# Extract the feature vector from a single image\ndef get_single_image_features(model=None, transform=None, image=None):\n \"\"\"\n model : Pretrained Deep Learning Feature Extractor Model (Pytorch)\n transform : Transform expected to be performed on the input\n image : Image File\n \"\"\"\n with torch.no_grad():\n features = model(transform(image).to(DEVICE).unsqueeze(dim=0))\n return normalize(features).detach().cpu().numpy()\n\n# ******************************************************************************************************************** #","sub_path":"Siamese Models/Real World Positive and Negative Base Samples/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"527701570","text":"import pygame\n\npygame.init() # 초기화\n\n# 화면 크기 설정\nscreen_width = 480 # 가로\nscreen_height = 640 # 세로\nscreen = pygame.display.set_mode((screen_width, screen_height))\n\n# 화면 타이틀 설정\npygame.display.set_caption('Nado Game') # 게임 이름\n\n# 이벤트 루프\nrunning = True # 게임 진행 중인지\nwhile running:\n for event in pygame.event.get(): # 어떤 이벤트가 발생하는지\n if event.type == pygame.QUIT: # 창이 닫히는 이벤트 발생하는지\n running = False # 게임 진행중 아님\n\n# pygame 종료\npygame.quit()\n","sub_path":"pygame_basic/1_create_frame.py","file_name":"1_create_frame.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"334770947","text":"\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 8 02:14:06 2017\n\n@author: Anushree\n\n\nCreated on Python 3.5\n\n\nWe are trying to find out smallest prime factor of number of questions in each contest.\n\nSince we need only the smallest prime factor of a number, we need to check the divisibility of the number with only prime numbers\nupto the square root of that number.Because we will get minimum prime factor only till sqrt(n),otherwise the number itslef is the smallest \nprime factor.\n\nGenerate prime numbers using variant of seive of eranthoses .\n\nCheck prime numbers from 2 onwards until the square root of larget number or until all smallest prime factors are fetched\n --Check for each contest if smallest prime is already found \n --If smallest prime is not found then check divisibility with this prime\n --If it is divisible update the smallest prime factor for that contest\n --Also mark the mutiples of this prime number as not prime so that they are not checked later\n \n\n\nThis differes from Seive of Erathoses because we do not get all prime number till sqaure root of N but we stop when we have found \nsmallest prime number for all contests.\n\n\"\"\"\n\nimport sys\nimport math\n\ndef main():\n \n print(\"Input: \\n\")\n problems=[]\n #Get line by line input from user\n try:\n while True:\n line = input()\n if line:\n num=int(line)\n if num<=1000000 and num>=1:\n problems.append(num)\n else:\n sys.exit(2)\n else:\n break\n \n if (problems[0]!=len(problems)-1): \n sys.exit(3)\n \n #Check if input is in correct form \n except SystemExit as e:\n if e.code==2:\n print(\"T and N not in specified range\")\n if e.code==3:\n print(\"Length mismatch between T specified and N's entered\")\n return\n \n #Take the largest no of problems,lar,out of all contest and find primes till sqrt(lar)\n lar=max(problems[1:])\n contests=problems[0]\n \n sqrt_lar=int(math.sqrt(lar))\n \n #Flag is true if the index at that place is a prime \n flag=[True for i in range(0,sqrt_lar+1)]\n \n #Flag is false if smallest prime is not yet found for that contest\n found_p=[False for i in range(0,contests+1)]\n \n #Stores the smallest prime for every contest,initialed with number itself\n small_p=[problems[i] for i in range(0,contests+1)]\n \n pr=2\n count=0\n \n \n #Loop until prime <=sqrt_lar or all the contests have got smallest prime\n while(pr<=sqrt_lar and count!=contests):\n \n #See if pr is a prime by checking the flag\n if(flag[pr]==True):\n \n #If pr is prime ,check divisibility with this prime for all the contest which do not have smallest prime yet\n for k in range(1,contests+1):#\n if(found_p[k]==False):\n if(problems[k]%pr==0):\n small_p[k]=pr\n count=count+1\n found_p[k]=True\n \n #Since this prime is checked ,mark flag false for multiples of this prime as they cannot be prime \n for i in range(pr*2,sqrt_lar,pr):\n flag[i]=False\n\n pr=pr+1\n \n #Print the result :First one is problem solved by herbal that is the smallest prime factor in given contest,second one is problem solved by naren\n print(\"Output: \\n\")\n for i in range(1,contests+1):\n print(\"%s %s \\n\"%(small_p[i],problems[i]-small_p[i]))\n\nif __name__ == \"__main__\":\n main() \n \n \n \n \n \n \n \n \n \n \n \n \n \n","sub_path":"submission.py","file_name":"submission.py","file_ext":"py","file_size_in_byte":3721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"163035774","text":"# Copyright (c) 2013, VHRS and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\n\nimport frappe\nfrom frappe import _, msgprint\n\n\ndef execute(filters=None):\n if not filters:\n filters = {}\n\n columns = get_columns()\n\n data = []\n row1 = row2 = row3 = row4 = row5 = row6 = row7 = []\n row8 = row9 = row10 = row11 = row12 = row13 = []\n row14 = row15 = []\n basics = 0\n da = 0\n b_total = 0\n da_total = 0\n oa_total = 0\n ot_total = 0\n wg_total = 0\n pf_total = 0\n esic_total = 0\n canteen_total = 0\n pt_total = 0\n otesic_total = 0\n sc_total = 0\n otsc_total = 0\n eesic_total = 0\n eotesic_total = 0\n epf_total = 0\n conditions, filters = get_conditions(filters)\n salary_components = get_salary_components(conditions,filters)\n # for ss in salary_components:\n from_date = filters.get(\"from_date\")\n to_date = filters.get(\"to_date\")\n ssp = frappe.get_all(\"Salary Slip\",filters={'start_date':from_date,'end_date':to_date })\n for ss in ssp:\n basics = frappe.db.sql(\"\"\"select td.amount as basic from `tabSalary Detail` td where \n td.salary_component='Basic' and td.parent=%s\"\"\",(ss['name']),as_dict=1)\n for b in basics:\n b_total += b['basic']\n da = frappe.db.sql(\"\"\"select td.amount as da from `tabSalary Detail` td where \n td.salary_component='Dearness Allowance' and td.parent=%s\"\"\",(ss['name']),as_dict=1)\n for d in da:\n da_total += d['da']\n oa = frappe.db.sql(\"\"\"select td.amount as oa from `tabSalary Detail` td where \n td.salary_component='Other Allowances' and td.parent=%s\"\"\",(ss['name']),as_dict=1)\n for o in oa:\n oa_total += o['oa'] \n ot = frappe.db.sql(\"\"\"select td.amount as ot from `tabSalary Detail` td where \n td.salary_component='Overtime' and td.parent=%s\"\"\",(ss['name']),as_dict=1)\n for t in ot:\n ot_total += t['ot'] \n wg = frappe.db.sql(\"\"\"select td.amount as wg from `tabSalary Detail` td where \n td.salary_component='Wages' and td.parent=%s\"\"\",(ss['name']),as_dict=1)\n for w in wg:\n wg_total += w['wg']\n pf = frappe.db.sql(\"\"\"select td.amount as pf from `tabSalary Detail` td where \n td.salary_component='Provident Fund' and td.parent=%s\"\"\",(ss['name']),as_dict=1)\n for p in pf:\n pf_total += p['pf'] \n esic = frappe.db.sql(\"\"\"select td.amount as esic from `tabSalary Detail` td where \n td.salary_component='ESIC' and td.parent=%s\"\"\",(ss['name']),as_dict=1)\n for e in esic:\n esic_total += e['esic'] \n canteen = frappe.db.sql(\"\"\"select td.amount as canteen from `tabSalary Detail` td where \n td.salary_component='Canteen' and td.parent=%s\"\"\",(ss['name']),as_dict=1)\n for c in canteen:\n canteen_total += c['canteen'] \n ptax = frappe.db.sql(\"\"\"select td.amount as pt from `tabSalary Detail` td where \n td.salary_component='Professional Tax' and td.parent=%s\"\"\",(ss['name']),as_dict=1)\n for pt in ptax:\n pt_total += pt['pt'] \n otesic = frappe.db.sql(\"\"\"select td.amount as otesic from `tabSalary Detail` td where \n td.salary_component='OT ESIC' and td.parent=%s\"\"\",(ss['name']),as_dict=1)\n for ote in otesic:\n otesic_total += ote['otesic']\n sc = frappe.db.sql(\"\"\"select td.amount as sc from `tabSalary Detail` td where \n td.salary_component='Service Charge' and td.parent=%s\"\"\",(ss['name']),as_dict=1)\n for s in sc:\n sc_total += s['sc'] \n otsc = frappe.db.sql(\"\"\"select td.amount as otsc from `tabSalary Detail` td where \n td.salary_component='OT Service Charge' and td.parent=%s\"\"\",(ss['name']),as_dict=1)\n for os in otsc:\n otsc_total += os['otsc']\n eesic = frappe.db.sql(\"\"\"select td.amount as eesic from `tabSalary Detail` td where \n td.salary_component='Employer ESIC' and td.parent=%s\"\"\",(ss['name']),as_dict=1)\n for ee in eesic:\n eesic_total += ee['eesic']\n eotesic = frappe.db.sql(\"\"\"select td.amount as eotesic from `tabSalary Detail` td where \n td.salary_component='Employer OT ESIC' and td.parent=%s\"\"\",(ss['name']),as_dict=1)\n for eote in eotesic:\n eotesic_total += eote['eotesic'] \n epf = frappe.db.sql(\"\"\"select td.amount as epf from `tabSalary Detail` td where \n td.salary_component='Employer PF' and td.parent=%s\"\"\",(ss['name']),as_dict=1)\n for ep in epf:\n epf_total += ep['epf']\n \n if b_total:\n row1 = ['Basic',b_total]\n else:\n row1= [\"\",\"\"]\n if da_total:\n row2 = ['Dearness Allowance',da_total]\n else:\n row2= [\"\",\"\"]\n if oa_total:\n row3 = ['Other Allowances',oa_total]\n else:\n row3= [\"\",\"\"]\n if ot_total:\n row4 = ['Overtime',ot_total]\n else:\n row4 = [\"\",\"\"]\n if wg_total:\n row5 = ['Wages',wg_total]\n else:\n row5 = [\"\",\"\"]\n if pf_total:\n row6 = ['Provident Fund',pf_total]\n else:\n row6 = [\"\",\"\"]\n if esic_total:\n row7 = ['ESIC', esic_total]\n else:\n row7 = [\"\",\"\"]\n if canteen_total:\n row8 = ['Canteen',canteen_total]\n else:\n row8 = [\"\",\"\"]\n if pt_total :\n row9 = ['Professional Tax',pt_total ]\n else:\n row9 = [\"\",\"\"]\n if otesic_total:\n row10 = ['OT ESIC',otesic_total]\n else:\n row10 = [\"\",\"\"]\n if sc_total :\n row11 = ['Service Charge',sc_total ]\n else:\n row11 = [\"\",\"\"]\n if otsc_total:\n row12 = ['OT Service Charge',otsc_total]\n else:\n row12 = [\"\",\"\"]\n if eesic_total :\n row13 = ['Employer ESIC', eesic_total ]\n else:\n row13 = [\"\",\"\"]\n if eotesic_total:\n row14 = ['Employer OT ESIC',eotesic_total]\n else:\n row14 = [\"\",\"\"]\n if epf_total:\n row15 = ['Employer PF',epf_total]\n else:\n row15 = [\"\",\"\"]\n data.append(row1)\n data.append(row2)\n data.append(row3)\n data.append(row4)\n data.append(row5)\n data.append(row6)\n data.append(row7)\n data.append(row8)\n data.append(row9)\n data.append(row10)\n data.append(row11)\n data.append(row12)\n data.append(row13)\n data.append(row14)\n data.append(row15)\n\n return columns,data\n\n\ndef get_columns():\n columns = [\n _(\"Salary Components\") + \":Data:180\",\n _(\"Amount\") + \":Currency:180\",\n ]\n return columns\n\ndef get_salary_components(conditions,filters):\n salary_components = frappe.db.sql(\"\"\"select name from `tabSalary Component` order by name\"\"\" , as_dict=1)\n return salary_components\n\n\ndef get_conditions(filters):\n conditions = \"\"\n if filters.get(\"from_date\"): conditions += \" and start_date >= %(from_date)s\"\n if filters.get(\"to_date\"): conditions += \" and end_date >= %(to_date)s\" \n return conditions, filters","sub_path":"minda_custom/minda_custom/report/associate_dashboard/associate_dashboard.py","file_name":"associate_dashboard.py","file_ext":"py","file_size_in_byte":7053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"530309712","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\ndef heap_sort2(seq):\n for start in range((len(seq)-2)//2, -1, -1):\n siftdown(seq, start, len(seq)-1)\n for end in range(len(seq)-1, 0, -1):\n seq[end], seq[0] = seq[0], seq[end]\n siftdown(seq, 0, end-1)\n return seq\n\ndef siftdown(seq, start, end):\n root = start\n while True:\n child = root*2 + 1\n if child > end:\n break\n if child+1 <= end and seq[child] < seq[child+1]:\n child += 1\n if seq[root] < seq[child]:\n seq[root], seq[child] = seq[child], seq[root]\n root = child\n else:\n break\n","sub_path":"src/datastructure/heap_sort2.py","file_name":"heap_sort2.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"295721664","text":"\"\"\"\nWordnik API.\n\nFor when you want to do terrible things with words.\n\"\"\"\nimport requests\n\nfrom kochira import config\nfrom kochira.service import Service, background, Config\n\nservice = Service(__name__, __doc__)\n\n@service.command(r\"^:amatsukaze:$\")\n@background\ndef amatsukaze(ctx):\n \"\"\"\n :amatsukaze:\n\n That's surely very advanced for computers.\n \"\"\"\n adjective = requests.get(\"http://api.wordnik.com/v4/words.json/randomWord\", params={\n 'hasDictionaryDef': 'false',\n 'includePartOfSpeech': 'adjective',\n 'minCorpusCount': 1000,\n 'minLength': 5,\n 'api_key': 'a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5',\n }).json()['word']\n noun = requests.get(\"http://api.wordnik.com/v4/words.json/randomWord\", params={\n 'hasDictionaryDef': 'true',\n 'includePartOfSpeech': 'noun',\n 'minCorpusCount': 1000,\n 'minLength': 5,\n 'api_key': 'a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5',\n }).json()['word']\n\n ctx.message(\"That's surely very {adjective} for {noun}.\".format(\n adjective=adjective,\n noun=noun,\n ))\n\n","sub_path":"kochira_caa/wordnik.py","file_name":"wordnik.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"301454674","text":"import numpy as np\nimport numpy.random as rnd\nimport matplotlib.pyplot as plt\n\n\ndef make_circle_problem(n,nx,PLOT):\n # This python-script uses the following three input parameters:\n # n - Number of points.\n # nx - Resolution of the plotting.\n # PLOT - Boolean variable for plotting.\n\n # Defining function handles.\n transform_domain = lambda r : 2*r-1\n rad = lambda x1,x2 : np.sqrt(x1**2+x2**2)\n\n # Initializing essential parameters.\n r = np.linspace(0,1,nx)\n x = transform_domain(r)\n dx = 2/nx\n x1,x2 = np.meshgrid(x,x)\n\n # Creating the data structure 'problem' in terms of dictionaries.\n problem = {'domain':{'x1':x,'x2':x},'classes':[None,None]}\n group1 = {'mean_rad':0,'sigma':0.1,'prob_unscaled':lambda x1,x2: 0,'prob':lambda x1,x2: 0,'density':0}\n group1['prob_unscaled'] = lambda x,y : np.exp(-(rad(x,y)-group1['mean_rad'])**2/(2*group1['sigma']**2))\n density_group1 = group1['prob_unscaled'](x1,x2)\n int_density_group1 = (dx**2)*sum(sum(density_group1))\n group1['density'] = density_group1/int_density_group1\n group2 = {'mean_rad':0.5,'sigma':0.1,'prob_unscaled':lambda x1,x2: 0,'prob':lambda x1,x2: 0,'density':0}\n group2['prob_unscaled'] = lambda x,y : np.exp(-(rad(x,y)-group2['mean_rad'])**2/(2*group2['sigma']**2))\n density_group2 = group2['prob_unscaled'](x1,x2)\n int_density_group2 = (dx**2)*sum(sum(density_group2))\n group2['density'] = density_group2/int_density_group2\n problem['classes'][0] = group1\n problem['classes'][1] = group2\n\n # Creating the arrays x1 and x2.\n x1 = np.zeros((n,2))\n x2 = np.zeros((n,2))\n count = 0\n for i in range(0,n):\n count += 1\n N1 = 'x1_'+str(count)+'.png'\n N2 = 'x2_'+str(count)+'.png'\n x1[i,0],x1[i,1] = pinky(problem['domain']['x1'],problem['domain']['x2'],problem['classes'][0]['density'],PLOT,N1)\n x2[i,0],x2[i,1] = pinky(problem['domain']['x1'],problem['domain']['x2'],problem['classes'][1]['density'],PLOT,N2)\n\n # Creating the data structure 'data' in terms of dictionaries.\n x = np.concatenate((x1[0:n,:],x2[0:n,:]),axis=0)\n y = np.concatenate((np.ones((n,1)),2*np.ones((n,1))),axis=0)\n i = rnd.permutation(2*n)\n data = {'x':x[i,:],'y':y[i]}\n\n return data, problem\n\n\ndef pinky(Xin,Yin,dist_in,PLOT,NAME):\n # Checking the input.\n if len(np.shape(dist_in)) > 2:\n print(\"The input must be a N x M matrix.\")\n return\n sy,sx = np.shape(dist_in)\n if (len(Xin) != sx) or (len(Yin) != sy):\n print(\"Dimensions of input vectors and input matrix must match.\")\n return\n for i in range(0,sy):\n for j in range(0,sx):\n if dist_in[i,j] < 0:\n print(\"All input probability values must be positive.\")\n return\n\n # Create column distribution. Pick random number.\n col_dist = np.sum(dist_in,1)\n col_dist /= sum(col_dist)\n Xin2 = Xin\n Yin2 = Yin\n\n # Generate random value index and saving first value.\n ind1 = gendist(col_dist,1,1,PLOT,NAME)\n ind1 = np.array(ind1,dtype=\"int\")\n x0 = Xin2[ind1]\n\n # Find corresponding indices and weights in the other dimension.\n A = (x0-Xin)**2\n val_temp = np.sort(A)\n ind_temp = np.array([i[0] for i in sorted(enumerate(A), key=lambda x:x[1])])\n eps = 2**-52\n if val_temp[0] < eps:\n row_dist = dist_in[:,ind_temp[0]]\n else:\n low_val = min(ind_temp[0:2])\n high_val = max(ind_temp[0:2])\n Xlow = Xin[low_val]\n Xhigh = Xin[high_val]\n w1 = 1-(x0-Xlow)/(Xhigh-Xlow)\n w2 = 1-(Xhigh-x0)/(Xhigh-Xlow)\n row_dist = w1*dist_in[:,low_val]+w2*dist_in[:,high_val]\n row_dist = row_dist/sum(row_dist)\n ind2 = gendist(row_dist,1,1,PLOT,NAME)\n y0 = Yin2[ind2]\n\n return x0,y0\n\n\ndef gendist(P,N,M,PLOT,NAME):\n # Checking input.\n if min(P) < 0:\n print('All elements of first argument, P, must be positive.')\n return\n if (N < 1) or (M < 1):\n print('Output matrix dimensions must be greater than or equal to one.')\n return\n\n # Normalizing P and creating cumlative distribution.\n Pnorm = np.concatenate([[0],P],axis=0)/sum(P)\n Pcum = np.cumsum(Pnorm)\n\n # Creating random matrix.\n R = rnd.rand()\n\n # Calculate output matrix T.\n V = np.linspace(0,len(P)-1,len(P))\n hist,inds = np.histogram(R,Pcum)\n hist = np.argmax(hist)\n T = int(V[hist])\n\n # Plotting graphs.\n if PLOT == True:\n Pfreq = (N*M*P)/sum(P)\n LP = len(P)\n fig,ax = plt.subplots()\n ax.hist(T,np.linspace(1,LP,LP))\n ax.plot(Pfreq,color='red')\n ax.set_xlabel('Frequency')\n ax.set_ylabel('P-vector Index')\n fig.savefig(NAME)\n\n return T\n\ndef YC(n, nx, bool):\n data, problem = make_circle_problem(int(n/2), nx, bool)\n Y0 = np.zeros((n, 4))\n Y0[..., 0:2] = np.array([data['x']])\n C = np.array([data['y']])\n C = np.reshape(C, n)-1\n return Y0, C\n\nif __name__=='__main__':\n data, problem = make_circle_problem(10,50,False)\n","sub_path":"Project2/make_circle_problem.py","file_name":"make_circle_problem.py","file_ext":"py","file_size_in_byte":5038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"382575646","text":"# binary search tree\nclass Node(object):\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n\nclass BST(object):\n def __init__(self, root):\n self.root = Node(root)\n\n def print(self, traversal_type):\n if traversal_type == \"preOrder\":\n return self.pre_Order(tree.root, \"\")\n else:\n print(\"traversal not supported\")\n return False\n\n def pre_Order(self, start, traversal):\n \"\"\"start : will store the updated root\n traversal : will store the string and print out at last\n depth first search : root -> left -> right\"\"\"\n if start:\n traversal += (str(start.value) + \"-\")\n traversal = self.pre_Order(start.left, traversal)\n traversal = self.pre_Order(start.right, traversal)\n return traversal\n\n\n# 1\n# / \\\n# 2 3\n# / \\ / \\\n# 4 5 6 7\n\n# set up tree\n\ntree = BST(1)\ntree.root.left = Node(2)\ntree.root.right = Node(3)\ntree.root.left.left = Node(4)\ntree.root.left.right = Node(5)\ntree.root.right.left = Node(6)\ntree.root.right.right = Node(7)\n\n# three ways to search : pre order, post order , in order\n# two ways to implement : depth first , breadth first\n\nprint(tree.print(\"preOrder\"))\n\n","sub_path":"oop/bst.py","file_name":"bst.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"426595670","text":"#https://stepik.org/lesson/3369/step/9?unit=952\n\nnums = [int (i) for i in input().split()]\nnumber = int(input())\n\nif number not in nums:\n print(\"Отсутствует\")\nelse:\n voc = {}\n for i in range(len(nums)):\n if nums[i] in voc.keys():\n voc[nums[i]] += [i]\n else:\n voc[nums[i]] = [i]\n for i in range(len(voc[number])):\n print(voc[number][i], end=\" \")\n","sub_path":"LESSON2.6-9.py","file_name":"LESSON2.6-9.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"459140050","text":"\"\"\"\nFlask Documentation: http://flask.pocoo.org/docs/\nJinja2 Documentation: http://jinja.pocoo.org/2/documentation/\nWerkzeug Documentation: http://werkzeug.pocoo.org/documentation/\nThis file creates your application.\n\"\"\"\n\nfrom app import app, db\nfrom flask import render_template, request, redirect, url_for, flash, jsonify\nfrom forms import NewUser\nfrom models import UserProfile\nimport os\nfrom werkzeug.utils import secure_filename\nfrom sqlalchemy.sql import exists\nimport random \nimport time\n\n\n\n###\n# Routing for your application.\n###\n\n@app.route('/')\ndef home():\n \"\"\"Render website's home page.\"\"\"\n return render_template('home.html')\n\n@app.route('/about/')\ndef about():\n \"\"\"Render the website's about page.\"\"\"\n return render_template('about.html')\n \n\n\n\n@app.route(\"/profile\", methods = [\"GET\", \"POST\"])\ndef aprofile():\n \n file_folder = app.config[\"UPLOAD_FOLDER\"]\n form = NewUser()\n \n if request.method == 'POST' and form.validate_on_submit():\n firstname = request.form[\"firstname\"]\n lastname = request.form[\"lastname\"]\n username = request.form[\"username\"]\n age = request.form[\"age\"]\n bio = request.form[\"bio\"]\n gender = request.form[\"gender\"]\n image = request.files['img']\n date = time.strftime('%Y/%b/%d')\n \n \n while True:\n userid = random.randint(620000000, 629999999) \n if not db.session.query(exists().where(UserProfile.userid == str(userid))).scalar():\n break\n \n \n ##file = request.files['file']\n ### filename = secure_filename(file.filename)\n #os.rename(secure_filename(file.filename), id)\n \n filename = \"{}-{}\".format(userid,secure_filename(image.filename))\n filepath = \"app/static/uploads/{}\".format(filename)\n image.save(filepath)\n \n user = UserProfile(str(userid), firstname, lastname, username, age, bio, gender, date, filename)\n db.session.add(user)\n db.session.commit()\n \n #file.save(os.path.join(file_folder, filename))\n \n \n \n flash(\"User Added!\", category='success')\n return redirect(url_for(\"profiles\")) #profiles is where it will display all the users\n \n # submiting to the db, validate info(if not ask user to fix errors), submit to the db then upload photo to the upload\n else:\n return render_template(\"profile.html\")\n\n\n\n@app.route(\"/profile/\", methods = [\"GET\", \"POST\"])\ndef userProfile(userid):\n # UserProfile.query.filter_by(username = userid).all()\n ##f request.method == \"POST\":\n ## return \"something\"\n ##else:\n ## return \"something else\"\n user = db.session.query(UserProfile).filter(UserProfile.userid == str(userid)).first()\n if not user:\n flash(\"Cannot Find User\", category = \"danger\")\n else: \n if request.headers.get('content-type') == 'application/json' or request.method == 'POST':\n return jsonify(userid = user.userid, username = user.username, image = user.image, gender = user.gender, age = user.age,\\\n created_on = user.created_on)\n return render_template('profile.html', user = user)\n return redirect(url_for('profiles'))\n \n \n \n \n\n\n@app.route(\"/profiles\", methods = [\"GET\", \"POST\"])\n## if request.methos == \"POST\":\n ## return render_template('profiles.html', users = db.session.query(UserProfile).query.all() )\n ## else:\n ## return \"something else\"\n \ndef profiles():\n \"\"\"View a list of profiles\"\"\"\n userlist = []\n result = db.session.query(UserProfile).all()\n for user in result:\n userlist.append({\"username\":user.username,\"userid\":user.userid})\n if request.headers.get('content-type') == 'application/json' or request.method == 'POST':\n return jsonify(users = userlist)\n return render_template('profiles.html', userlist = userlist)\n \n \n \n \n \n\n###\n# The functions below should be applicable to all Flask apps.\n###\n\n@app.route('/.txt')\ndef send_text_file(file_name):\n \"\"\"Send your static text file.\"\"\"\n file_dot_text = file_name + '.txt'\n return app.send_static_file(file_dot_text)\n\n\n@app.after_request\ndef add_header(response):\n \"\"\"\n Add headers to both force latest IE rendering engine or Chrome Frame,\n and also to cache the rendered page for 10 minutes.\n \"\"\"\n response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'\n response.headers['Cache-Control'] = 'public, max-age=0'\n return response\n\n\n@app.errorhandler(404)\ndef page_not_found(error):\n \"\"\"Custom 404 page.\"\"\"\n return render_template('404.html'), 404\n\n\nif __name__ == '__main__':\n app.run(debug=True,host=\"0.0.0.0\",port=\"8080\")\n","sub_path":"app/.~c9_invoke_53kzhj.py","file_name":".~c9_invoke_53kzhj.py","file_ext":"py","file_size_in_byte":4791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"456534414","text":"#!/usr/bin/python3\n\"\"\"\nStarts a Flask web application with the following conditions\n\n- listens on 0.0.0.0, port 5000\n- routes\n - /states: lists state objects in dbstorage\n - /states/: displays a state with specified id\n\"\"\"\n\nfrom flask import Flask\nfrom flask import render_template\nfrom models import storage\n\napp = Flask(__name__)\n\n\n@app.route('/states', strict_slashes=False)\n@app.route('/states/', strict_slashes=False)\ndef states_id(id=None):\n \"\"\" displays a state with specified id \"\"\"\n all_states = storage.all('State')\n if id:\n state_id = 'State.' + id\n if state_id in all_states:\n states = all_states[state_id]\n else:\n states = None\n else:\n states = all_states.values()\n return render_template('9-states.html',\n states=states,\n id=id)\n\n\n@app.teardown_appcontext\ndef teardown(self):\n \"\"\"Remove the current SQLAlchemy session.\"\"\"\n storage.close()\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')\n","sub_path":"web_flask/9-states.py","file_name":"9-states.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"475999344","text":"#-*-coding: utf-*-\n\nimport os\n\n#web\nsettings = dict(\n web_title = 'Piscium',\n template_path = os.path.join(os.path.dirname(__file__), 'templates'),\n static_path = os.path.join(os.path.dirname(__file__), 'static'),\n cookie_secret = \"b'B54pC+IfQvi/URHzbEUM+I4qazxvHEXZgXiRN2lWtBk='\",\n xsrf_cookies = True,\n debug = True,\n)\n\n#mariadb\nmariadb_option = dict(\n host='127.0.0.1',\n user='admin',\n password='511',\n database='piscium'\n)\n\n#redis\nredis_option = dict(\n host='127.0.0.1',\n port='6379'\n)\n\n#log\nlog_file = os.path.join(os.path.dirname(__file__), \"logs/log\")\nlog_level = \"debug\"","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"221413412","text":"from django.urls import path\nfrom django.contrib.auth import views as standart_views\n\nfrom . import views\n\napp_name = 'posts'\nurlpatterns = [\n path('delete/', views.delete_post, name = 'delete_post'),\n path('news/', views.news, name = 'news'),\n path('like_news/', views.like_news, name = 'like_news'),\n path('friend_news/', views.friend_news, name = 'friend_news'),\n path('post//', views.like_or_dislike, name = 'like_or_dislike'),\n path('post/user_like', views.user_like, name = 'user_like'),\n]\n","sub_path":"social_network/apps/posts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"576273525","text":"from django.urls import path\nfrom pages import views\n\nurlpatterns = [\n path('curriculum/', views.CurriculumView.as_view(), name='curriculum'),\n path('gallery/', views.GalleryView.as_view(), name='gallery'),\n path('sampleDay/', views.SampleDayView.as_view(), name='sampleDay'),\n path('register/', views.register, name='register'),\n path('contact/', views.contact, name='contact'),\n path('about/', views.AboutView.as_view(), name='about'),\n path('inquiry/', views.InquiryView.as_view(), name='inquiry'),\n path('faq/', views.FAQView.as_view(), name='faq'),\n path('index/', views.IndexView.as_view(), name='index'),\n path('', views.WelcomePageView.as_view(), name='welcome'),\n]","sub_path":"pages/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"337950353","text":"import tkinter\nimport socket\nimport threading\n\nwin = tkinter.Tk()\nwin.title('QQ客户端')\nwin.geometry('500x400+400+100')\n\nclientSocket = None\n# 将消息发送到服务器\ndef sendMessage():\n content = eSendContent.get()\n user = eSender.get()\n clientSocket.send((content+':'+user))\n\n# 从服务器获取消息进行显示到Text控件上\ndef getInfo():\n while True:\n data = clientSocket.recv(1024)\n text.insert(tkinter.INSERT,data.decode('utf-8'))\n# 连接服务器\ndef connectServer():\n # 通过使用全局变量,以便于全局使用这个socket\n global clientSocket\n userName = eUser.get()\n ip = eIp.get()\n port = ePort.get()\n client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n client.connect((ip,int(port)))\n print('连接成功......')\n client.send(userName.encode('utf-8'))\n clientSocket = client\n t = threading.Thread(target=getInfo)\n t.start()\n\nuserName = tkinter.Label(win,text='userName').grid(row=0,column=0)\nlabelIp = tkinter.Label(win,text='Ip').grid(row=1,column=0)\nlabelPort = tkinter.Label(win,text='Port').grid(row=2,column=0)\neUser = tkinter.Variable()\neIp = tkinter.Variable()\nePort = tkinter.Variable()\nentryUser = tkinter.Entry(win,textvariable=eUser).grid(row=0,column=1)\nentryIp = tkinter.Entry(win,textvariable=eIp).grid(row=1,column=1)\nentryPort = tkinter.Entry(win,textvariable=ePort).grid(row=2,column=1)\nbutton1 = tkinter.Button(win,text='连接',command=connectServer).grid(row=2,column=2)\ntext = tkinter.Text(win,width=30,height=10)\ntext.grid(row=3,column=1)\nsendContent = tkinter.Label(win,text='发送内容:').grid(row=4,column=0)\nsender = tkinter.Label(win,text='发送者:').grid(row=5,column=0)\neSendContent = tkinter.Variable()\neSender = tkinter.Variable()\nentrySendContent = tkinter.Entry(win,textvariable=eSendContent).grid(row=4,column=1)\nentrySender = tkinter.Entry(win,textvariable=eSender).grid(row=5,column=1)\nbutton = tkinter.Button(win,text='发送',command=sendMessage).grid(row=5,column=2)\n\nwin.mainloop()","sub_path":"test/QQ/client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"158070000","text":"from typing import Optional\n\nfrom ..mixin import ProtoTypeMixin\nfrom ...excepts import BadNamedScoreType\nfrom ...helper import typename\nfrom ...proto import jina_pb2\n\n__all__ = ['NamedScore']\n\n\nclass NamedScore(ProtoTypeMixin):\n \"\"\"\n :class:`NamedScore` is one of the **primitive data type** in Jina.\n\n It offers a Pythonic interface to allow users access and manipulate\n :class:`jina.jina_pb2.NamedScoreProto` object without working with Protobuf itself.\n\n To create a :class:`NamedScore` object, simply:\n\n .. highlight:: python\n .. code-block:: python\n\n from jina.types.score import NamedScore\n score = NamedScore()\n score.value = 10.0\n\n :class:`NamedScore` can be built from ``jina_pb2.NamedScoreProto`` (as a weak reference or a deep copy)\n or from a set of `attributes` from ``jina_pb2.NamedScoreProto`` passed to the constructor.\n .. highlight:: python\n .. code-block:: python\n\n from jina.types.score import NamedScore\n from jina_pb2 import NamedScoreProto\n score = NamedScore(value=10.0, op_name='ranker', description='score computed by ranker')\n\n score_proto = NamedScoreProto()\n score_proto.value = 10.0\n score = NamedScore(score_proto)\n\n :param score: The score to construct from, depending on the ``copy``,\n it builds a view or a copy from it.\n :type score: Optional[jina_pb2.NamedScoreProto]\n :param copy: When ``score`` is given as a :class:`NamedScoreProto` object, build a\n view (i.e. weak reference) from it or a deep copy from it.\n :type copy: bool\n :param kwargs: Other parameters to be set\n\n \"\"\"\n\n def __init__(self, score: Optional[jina_pb2.NamedScoreProto] = None,\n copy: bool = False, **kwargs):\n \"\"\"Set constructor.\"\"\"\n self._pb_body = jina_pb2.NamedScoreProto()\n try:\n if isinstance(score, jina_pb2.NamedScoreProto):\n if copy:\n self._pb_body.CopyFrom(score)\n else:\n self._pb_body = score\n elif score is not None:\n # note ``None`` is not considered as a bad type\n raise ValueError(f'{typename(score)} is not recognizable')\n except Exception as ex:\n raise BadNamedScoreType(f'fail to construct a NamedScore from {score}') from ex\n\n self.set_attrs(**kwargs)\n\n @property\n def ref_id(self) -> str:\n \"\"\"Return computed score between doc ``id`` and ``ref_id``.\"\"\"\n return self._pb_body.ref_id\n\n @ref_id.setter\n def ref_id(self, val: str):\n \"\"\"Set the ``ref_id`` to :param: `val`.\"\"\"\n self._pb_body.ref_id = val\n\n def set_attrs(self, **kwargs):\n \"\"\"Udate Document fields with key-value specified in kwargs.\n\n .. seealso::\n :meth:`get_attrs` for bulk get attributes\n \"\"\"\n for k, v in kwargs.items():\n if isinstance(v, (list, tuple)):\n self._pb_body.ClearField(k)\n getattr(self._pb_body, k).extend(v)\n elif isinstance(v, dict):\n self._pb_body.ClearField(k)\n getattr(self._pb_body, k).update(v)\n else:\n if hasattr(NamedScore, k) and isinstance(getattr(NamedScore, k), property) and getattr(NamedScore,\n k).fset:\n # if class property has a setter\n setattr(self, k, v)\n elif hasattr(self._pb_body, k):\n # no property setter, but proto has this attribute so fallback to proto\n setattr(self._pb_body, k, v)\n else:\n raise AttributeError(f'{k} is not recognized')\n","sub_path":"jina/types/score/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"16343949","text":"#!/bin/python3\n\nimport sys\n\ndef solve(year):\n gregorian = (year >1918)\n if not gregorian:\n if year == 1918:\n return '26.09.1918'\n if year % 4 ==0:\n return \"12.09.\" + str(year)\n else:\n return \"13.09.\" + str(year)\n else:\n if (year % 4 ==0 and year % 100!=0) or year%400==0:\n return \"12.09.\" + str(year)\n else:\n return \"13.09.\" + str(year)\n\nyear = int(input().strip())\nresult = solve(year)\nprint(result)\n","sub_path":"algorithms/implementation/day_of_the_programmer.py","file_name":"day_of_the_programmer.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"494523303","text":"__author__ = 'Kalyan'\n\nmax_marks = 30\n\nproblem_notes ='''\nThis problem deals with a custom encryption/decryption scheme that works as follows. \n\nGiven a string like \"how are you?\" and m * n grid. The characters of the string are filled \ninto the grid row wise top to bottom. So for 3 * 5 you get\n\nh o w _ a\nr e _ y o\nu ? * * *\n\nIn the above example _ is shown visually where there is a space character. Unfilled cells are filled with *'s\n\nThe encrypted string is found by starting at a specified corner and going clockwise in \na decreasing spiral till all the cells are covered. So if corner is top right you get \"ao***?urhow y e\"\n\n\nNotes:\n1. raise TypeError if text is not a str or key is not EncryptKey\n2. raise ValueError if the grid cannot accomodate the text or if rows/cols are <= 0 \n3. returns the encrypted string as specified above.\n4. see the definitions for Corner and EncryptKey in mock1common.py\n'''\n\nfrom mock1common import EncryptKey, Corner\n\nfinal_result = ''\n\ndef encrypt(text, key):\n global final_result\n if type(text).__name__ != 'str' or type(key) != EncryptKey:\n raise TypeError\n if len(text) > key.rows * key.cols or key.rows <= 0 or key.cols <= 0:\n raise ValueError\n grid = []\n base = 0\n length = len(text)\n while base < length:\n grid.append(list(text[base: base + key.cols]))\n base = base + 5\n if len(grid[-1]) < key.cols:\n grid[-1] += list('*' * (key.cols - len(grid[-1])))\n if len(grid) != key.rows:\n grid = grid + [[list('*' * key.cols)] for i in key.rows - len(grid)]\n final_result = ''\n def turnRight(x, y):\n global final_result\n y += 1\n while grid[x][y] != -1 and y <= key.cols:\n final_result = final_result + grid[x][y]\n grid[x][y] = -1\n y = y + 1\n if grid[x + 1][y - 1] == -1:\n return\n turnDown(x, y - 1)\n\n def turnLeft(x, y):\n global final_result\n y -= 1\n while grid[x][y] != -1 and y >= 0:\n final_result += grid[x][y]\n grid[x][y] = -1\n y -= 1\n if grid[x - 1][y - 1] == -1:\n return\n turnUp(x, y + 1)\n\n def turnUp(x, y):\n global final_result\n x -= 1\n while grid[x][y] != -1 and x >= 0:\n final_result += grid[x][y]\n grid[x][y] = -1\n x -= 1\n if grid[x + 1][y + 1] == -1:\n return\n turnRight(x + 1, y)\n\n def turnDown(x, y):\n global final_result\n x += 1\n while grid[x][y] != -1 and x <= key.rows:\n final_result += grid[x][y]\n grid[x][y] = -1\n x += 1\n if grid[x - 1][y - 1] == -1:\n return\n turnLeft(x - 1, y)\n\n def startDown():\n global final_result\n x, y = 0, key.cols - 1\n while x < key.rows:\n final_result += grid[x][y]\n grid[x][y] = -1\n x += 1\n turnLeft(x - 1, y)\n\n def startLeft():\n global final_result\n x, y = key.rows - 1, key.cols - 1\n while y >= 0:\n final_result += grid[x][y]\n grid[x][y] = -1\n y -= 1\n turnUp(x, y + 1)\n\n def startUp():\n global final_result\n x, y = key.rows - 1, 0\n while x >= 0:\n final_result += grid[x][y]\n grid[x][y] = -1\n x -= 1\n turnRight(x + 1, y)\n\n def startRight():\n global final_result\n x, y = 0, 0\n while y < key.cols:\n final_result += grid[x][y]\n grid[x][y] = -1\n y += 1\n turnDown(x, y - 1)\n\n if key.corner == Corner.TOP_RIGHT:\n startDown()\n elif key.corner == Corner.TOP_LEFT:\n startRight()\n elif key.corner == Corner.BOTTOM_LEFT:\n startUp()\n elif key.corner == Corner.BOTTOM_RIGHT:\n startLeft()\n\n return final_result\n\n# a basic test is given, write your own tests based on constraints.\ndef test_encrypt():\n assert \"ao***?urhow y e\" == encrypt(\"how are you?\", EncryptKey(3, 5, Corner.TOP_RIGHT))\n\n","sub_path":"mocktest1_problem3.py","file_name":"mocktest1_problem3.py","file_ext":"py","file_size_in_byte":4459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"626601757","text":"import tensorflow as tf\nimport numpy as np\nimport argparse\nimport os,sys\nimport math\nimport random\nimport cv2\nimport matplotlib.image as mpimg\nfrom type import category\n\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\n\ndef inference(input=0,inputType=1):\n slim = tf.contrib.slim\n sys.path.append('../')\n from nets import ssd_vgg_300, ssd_common, np_methods\n from preprocessing import ssd_vgg_preprocessing\n from notebooks import visualization\n # TensorFlow session: grow memory when needed. TF, DO NOT USE ALL MY GPU MEMORY!!!\n gpu_options = tf.GPUOptions(allow_growth=True)\n config = tf.ConfigProto(log_device_placement=False, gpu_options=gpu_options)\n isess = tf.InteractiveSession(config=config)\n\n # Input placeholder.\n net_shape = (300, 300)\n data_format = 'NHWC'\n img_input = tf.placeholder(tf.uint8, shape=(None, None, 3))\n # Evaluation pre-processing: resize to SSD net shape.\n image_pre, labels_pre, bboxes_pre, bbox_img = ssd_vgg_preprocessing.preprocess_for_eval(\n img_input, None, None, net_shape, data_format, resize=ssd_vgg_preprocessing.Resize.WARP_RESIZE)\n image_4d = tf.expand_dims(image_pre, 0)\n\n # Define the SSD model.\n reuse = True if 'ssd_net' in locals() else None\n ssd_net = ssd_vgg_300.SSDNet()\n with slim.arg_scope(ssd_net.arg_scope(data_format=data_format)):\n predictions, localisations, _, _ = ssd_net.net(image_4d, is_training=False, reuse=reuse)\n\n # Restore SSD model.\n ckpt_filename = '../checkpoints/ssd_300_vgg.ckpt'\n # ckpt_filename = '../checkpoints/VGG_VOC0712_SSD_300x300_ft_iter_120000.ckpt'\n isess.run(tf.global_variables_initializer())\n saver = tf.train.Saver()\n saver.restore(isess, ckpt_filename)\n\n # SSD default anchor boxes.\n ssd_anchors = ssd_net.anchors(net_shape)\n\n # Main image processing routine.\n def process_image(img, select_threshold=0.5, nms_threshold=.45, net_shape=(300, 300)):\n # Run SSD network.\n rimg, rpredictions, rlocalisations, rbbox_img = isess.run([image_4d, predictions, localisations, bbox_img],\n feed_dict={img_input: img})\n\n # Get classes and bboxes from the net outputs.\n rclasses, rscores, rbboxes = np_methods.ssd_bboxes_select(\n rpredictions, rlocalisations, ssd_anchors,\n select_threshold=select_threshold, img_shape=net_shape, num_classes=21, decode=True)\n\n rbboxes = np_methods.bboxes_clip(rbbox_img, rbboxes)\n rclasses, rscores, rbboxes = np_methods.bboxes_sort(rclasses, rscores, rbboxes, top_k=400)\n rclasses, rscores, rbboxes = np_methods.bboxes_nms(rclasses, rscores, rbboxes, nms_threshold=nms_threshold)\n # Resize bboxes to original image shape. Note: useless for Resize.WARP!\n rbboxes = np_methods.bboxes_resize(rbbox_img, rbboxes)\n return rclasses, rscores, rbboxes\n\n # input is a image\n inputType = int(inputType)\n if inputType is 1:\n if input == 0:\n print(\"At least indicate 1 input video\")\n exit(-1)\n # Test on some demo image and visualize output.\n img = mpimg.imread(input)\n rclasses, rscores, rbboxes = process_image(img)\n\n # Find the name of the category num\n print(list(map(lambda i:\"{}:{}\".format(i,category[i]),list(rclasses))))\n rclasses = np.array(list(map(lambda i:\"{}:{}\".format(i,category[i]),list(rclasses))))\n\n # visualization.bboxes_draw_on_img(img, rclasses, rscores, rbboxes, visualization.colors_plasma)\n # plot the image directly\n visualization.plt_bboxes(img, rclasses, rscores, rbboxes)\n elif inputType == 2:\n # input is the video\n # plot the boxes into the image\n cap = cv2.VideoCapture(input)\n fps = cap.get(cv2.CAP_PROP_FPS)\n size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n fourcc = cap.get(cv2.CAP_PROP_FOURCC)\n #fourcc = cv2.CAP_PROP_FOURCC(*'CVID')\n print('fps=%d,size=%r,fourcc=%r'%(fps,size,fourcc))\n delay=10/int(fps)\n print(delay)\n if delay <= 1:\n delay = 1\n while (cap.isOpened()):\n ret, frame = cap.read()\n print(ret)\n if ret == True:\n image = frame\n # the array based representation of the image will be used later in order to prepare the\n # result image with boxes and labels on it.\n image_np = image\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_np, axis=0)\n # Actual detection.\n rclasses, rscores, rbboxes = process_image(image_np)\n\n #print(list(map(lambda i: \"{}:{}\".format(i, category[i]), list(rclasses))))\n rclasses = np.array(list(map(lambda i: \"{}:{}\".format(i, category[i]), list(rclasses))))\n\n # Visualization of the results of a detection.\n visualization.bboxes_draw_on_img(image_np, rclasses, rscores, rbboxes)\n cv2.imshow('frame', image_np)\n #cv2.waitKey(np.uint(delay))\n if cv2.waitKey(delay) & 0xFF == ord('q'):\n break\n print('Ongoing...')\n else:\n break\n cap.release()\n cv2.destroyAllWindows()\n elif inputType ==3:\n print(\"save video\")\n if input == 0:\n print(\"At least indicate 1 input video\")\n exit(-1)\n def save_image(image_np):\n rclasses, rscores, rbboxes = process_image(image_np)\n # print(list(map(lambda i: \"{}:{}\".format(i, category[i]), list(rclasses))))\n rclasses = np.array(list(map(lambda i: \"{}:{}\".format(i, category[i]), list(rclasses))))\n visualization.bboxes_draw_on_img(image_np, rclasses, rscores, rbboxes)\n return image_np\n\n from moviepy.editor import VideoFileClip\n cap = cv2.VideoCapture(input)\n fps = cap.get(cv2.CAP_PROP_FPS)\n cap.release()\n cv2.destroyAllWindows()\n\n video = VideoFileClip(input)\n result = video.fl_image(save_image)\n output = os.path.join(\"./videos/output_{}\".format(input.split(\"/\")[-1]))\n result.write_videofile(output, fps=fps)\n else:\n cap = cv2.VideoCapture(0)\n\n while (True):\n # Capture frame-by-frame\n ret, frame = cap.read()\n\n #cv2.imshow('frame', frame)\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(frame, axis=0)\n # Actual detection.\n rclasses, rscores, rbboxes = process_image(frame)\n\n # print(list(map(lambda i: \"{}:{}\".format(i, category[i]), list(rclasses))))\n rclasses = np.array(list(map(lambda i: \"{}:{}\".format(i, category[i]), list(rclasses))))\n # Visualization of the results of a detection.\n visualization.bboxes_draw_on_img(frame, rclasses, rscores, rbboxes)\n cv2.imshow('frame', frame)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n # When everything done, release the capture\n cap.release()\n cv2.destroyAllWindows()\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', \"--input_image\", help=\"the path of the input image\", dest='input',\n default=os.path.join(sys.path[0], \"images/mouse.jpeg\"))\n parser.add_argument('-t', \"--input_type\", help=\"the type of the input: image or video\", dest='type',\n default=1)\n args = parser.parse_args()\n inference(args.input,args.type)\n","sub_path":"inference/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":7849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"445376977","text":"import math\nimport os\nimport random\nimport re\nimport sys\nfrom pprint import pprint\n\n\nclass Solution:\n\n def check(self, page, not_broken, num_list):\n length = len(page)\n if length == 0:\n return \"9999999\"\n small = list(filter(lambda x: x in not_broken,\n num_list[0: int(page[0])]))\n big = list(filter(lambda x: x in not_broken,\n num_list[int(page[0]) + 1: 10]))\n\n a = small[-1] + not_broken[-1] * (length - 1) if len(small) else \"9999999\"\n b = page[0] if length == 1 and page[0] in not_broken else page[0] + self.check(page[1:], not_broken,\n num_list) if page[0] in not_broken else \"9999999\"\n c = big[0] + not_broken[0] * (length - 1) if len(big) else \"9999999\"\n abcde = [a, b, c]\n if length == len(page):\n d = not_broken[-1] * (length - 1) if len(not_broken) and length >= 2 else \"9999999\"\n e = ((not_broken[0] if not_broken[0] != '0' else not_broken[1] if len(\n not_broken) > 1 else \"9999999\") + not_broken[0] * length) if len(not_broken) else \"9999999\"\n abcde += [d, e]\n abcde.sort(key=lambda x: len(x))\n abs_page = list(map(lambda x: abs(int(page) - int(x)), abcde))\n return str(abcde[abs_page.index(min(abs_page))])\n\n def solution(self, page, broken):\n broken = [str(word) for word in broken]\n num_list = list(map(str, range(10)))\n not_broken = list(filter(lambda x: x not in broken, num_list))\n near_num = self.check(str(page), not_broken, num_list)\n return min(abs(page - int(near_num)) + len(near_num), abs(100 - page))\n\n\nsolution = Solution()\nprint(solution.solution(5457, [6, 7, 8]))\nprint(solution.solution(100, [1, 0, 5]))\nprint(solution.solution(99999, [0, 2, 3, 4, 5, 6, 7, 8, 9]))\n# print(solution.solution(158, [1, 9, 2, 5, 4]))\n# print(solution.solution(151241, [0, 1, 2, 3, 4, 7, 8, 9]))\n","sub_path":"코테/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"23333433","text":"import interest.Compound as Compound\nimport value.Present as Present\nimport value.Future as Future\n\ndef mainMenuSelect(opt):\n while(opt!=\"0\"):\n if (opt == \"1\"):\n Compound.compound()\n elif (opt == \"2\"):\n Present.getPresentValue()\n elif(opt == \"3\"):\n Future.getFutureValue()\n print(\"\\nChoose the required option: \\n\")\n print(\"0. Exit\\n1. Calculate compounded amount\\n2. Calculate present value\\n3. Calculate future value\\n\")\n opt = input(\"Please type the number against the option\\n\")\n\n\nprint(\"Hi! I am Nithi, your financial assistant. How may I help you?\")\nprint(\"0. Exit\\n1. Calculate compounded amount\\n2. Calculate present value\\n3. Calculate future value\\n\")\nopt = input(\"Please type the number against the option\\n\")\nmainMenuSelect(opt)","sub_path":"nithi/HiNithi.py","file_name":"HiNithi.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"564408487","text":"import os\nimport requests\nimport requests_cache\n\nrequests_cache.install_cache('../cache')\nurl = 'https://adventofcode.com/' + os.path.abspath(__file__).split('/')[-2] + '/day/' + __file__.split('.')[0] + '/input'\ns = requests.get(url, cookies={\"session\": os.environ['SESSION']}).text.strip()\n\nsum = 0\nfor i in range(len(s)):\n if s[i] == s[(i + len(s) // 2) % len(s)]:\n sum += int(s[i])\nprint(sum)\n","sub_path":"2017/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"400371244","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.db import migrations\n\n\ndef add_record(apps, schema_editor):\n payment_gateway = apps.get_model('payment_gateway', 'PaymentGateway')\n payment_gateway.objects.create(\n slug='payu',\n title='PayU India',\n body='Simplified payment solutions. Build to deliver an awesome customer experience',\n is_active=True\n )\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('payment_gateway', '0001_initial'),\n ]\n\n operations = [\n migrations.RunPython(\n code=add_record,\n reverse_code=migrations.RunPython.noop,\n )\n ]\n","sub_path":"payment_gateway/migrations/0005_add_payu.py","file_name":"0005_add_payu.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"149506688","text":"#!/usr/bin/env python\n\n# Copyright (c) 2017 Riverbed Technology, Inc.\n#\n# This software is licensed under the terms and conditions of the MIT License\n# accompanying the software (\"License\"). This software is distributed \"AS IS\"\n# as set forth in the License.\n\n\"\"\"\nShow available packet sources.\n\"\"\"\n\nfrom steelscript.appresponse.core.app import AppResponseApp\nfrom steelscript.common.datautils import Formatter\n\n\nclass PacketCaptureApp(AppResponseApp):\n\n def console(self, source_type, data, headers):\n print('')\n print(source_type)\n print('-' * len(source_type))\n\n Formatter.print_table(data, headers)\n\n def main(self):\n\n # Show capture jobs\n headers = ['id', 'name', 'mifg_id', 'filter', 'state',\n 'start_time', 'end_time', 'size']\n data = []\n for job in self.appresponse.capture.get_jobs():\n data.append([job.id, job.name,\n job.data.config.mifg_id,\n getattr(job.data.config, 'filter',\n dict(string=None))['string'],\n job.data.state.status.state,\n job.data.state.status.packet_start_time,\n job.data.state.status.packet_end_time,\n job.data.state.status.capture_size])\n self.console('Capture Jobs', data, headers)\n\n # Show clips\n\n headers = ['id', 'job_id', 'start_time', 'end_time', 'filters']\n data = []\n for clip in self.appresponse.clips.get_clips():\n data.append([clip.id, clip.data.config.job_id,\n clip.data.config.start_time,\n clip.data.config.end_time,\n getattr(clip.data.config, 'filters',\n dict(items=None))['items']])\n self.console('Clips', data, headers)\n\n # Show files\n\n headers = ['type', 'id', 'link_type', 'format',\n 'size', 'created', 'modified']\n data = []\n for obj in self.appresponse.fs.get_files():\n data.append([obj.data.type, obj.id, obj.data.link_type,\n obj.data.format, obj.data.size,\n obj.data.created, obj.data.modified])\n self.console('Uploaded Files/PCAPs', data, headers)\n\n\nif __name__ == '__main__':\n app = PacketCaptureApp()\n app.run()\n","sub_path":"examples/list_sources.py","file_name":"list_sources.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"25666982","text":"import ROOT\n\nfrom config import *\n\n\ndef setup():\n\tsignal_file = ROOT.TFile(SIGNALPROCFNM)\n\tbg_file = ROOT.TFile(BGPROCFNM)\n\n\tsignal_tree = signal_file.Get(TREENM)\n\tbg_tree = bg_file.Get(TREENM)\n\n\n\tfout = ROOT.TFile(\"test.root\",\"RECREATE\")\n\n\n\tfactory = ROOT.TMVA.Factory(\"TMVAClassification\", fout,\n \":\".join([ \"!V\",\n \"!Silent\",\n \"Color\",\n \"DrawProgressBar\",\n \"Transformations=I;D;P;G,D\",\n \"AnalysisType=Classification\"]\n ))\n\tdataloader = ROOT.TMVA.DataLoader(\"dataset\")\n\n\tdataloader.AddVariable(\"mJJ\",\"F\")\n\tdataloader.AddVariable(\"deltaYJJ\",\"F\")\n\tdataloader.AddVariable(\"metPt\",\"F\")\n\tdataloader.AddVariable(\"ptBalance\",\"F\")\n\tdataloader.AddVariable(\"subleadJetEta\",\"F\")\n\tdataloader.AddVariable(\"leadJetPt\",\"F\")\n\tdataloader.AddVariable(\"photonEta\",\"F\")\n\tdataloader.AddVariable(\"ptBalanceRed\",\"F\")\n\tdataloader.AddVariable(\"nJets\",\"F\")\n\tdataloader.AddVariable(\"sinDeltaPhiJJOver2\",\"F\")\n\tdataloader.AddVariable(\"deltaYJPh\",\"F\")\n\t# dataloader.AddVariable(\"nLeptons\", \"F\")\n\n\tcut = make_selections()\n\n\tdataloader.AddSignalTree(signal_tree)\n\tdataloader.AddBackgroundTree(bg_tree)\n\tdataloader.PrepareTrainingAndTestTree(cut, \n \t\":\".join([\"nTrain_Signal=0\",\n \"nTrain_Background=0\",\n \"SplitMode=Random\",\n \"NormMode=NumEvents\",\n \"!V\"\n ]))\n\n\n\tmethod = factory.BookMethod(dataloader, ROOT.TMVA.Types.kBDT, \"BDTadaboost\",\n\t \":\".join([ \"!H\",\n\t \"!V\",\n\t \"NTrees=850\",\n\t \"nEventsMin=150\",\n\t \"MaxDepth=3\",\n\t \"BoostType=AdaBoost\",\n\t \"AdaBoostBeta=0.5\",\n\t \"SeparationType=GiniIndex\",\n\t \"nCuts=20\",\n\t \"PruneMethod=NoPruning\",\n\t ]))\n\n\tmethod = factory.BookMethod(dataloader, ROOT.TMVA.Types.kBDT, \"BDTgrad\",\n \":\".join([ \"!H\",\n \"!V\",\n \"NTrees=850\",\n \"nEventsMin=150\",\n \"MaxDepth=3\",\n \"BoostType=Grad\",\n \"AdaBoostBeta=0.5\",\n \"SeparationType=GiniIndex\",\n \"nCuts=20\",\n \"PruneMethod=NoPruning\",\n ]))\n\n\tfactory.TrainAllMethods()\n\tfactory.TestAllMethods()\n\tfactory.EvaluateAllMethods()\n\tfout.Close()\n\n\tROOT.TMVA.TMVAGui(\"test.root\")\n\tROOT.gApplication.Run()\n\n\ndef make_selections():\n\tcut = ROOT.TCut(\"(mJJ > 300)&&(phCentrality < 0.6)&&(nJets > 1)&&(nLeptons == 0)\")\n\treturn cut\n\n\nif __name__ == \"__main__\":\n\tROOT.TMVA.Tools.Instance()\n\n\tsetup()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"274238629","text":"import argparse\nimport numpy as np\nfrom arch_search.arch_search_densenet_net2net import arch_search_densenet\nfrom arch_search.arch_search_convnet_net2net import arch_search_convnet\n\nimport os\nimport tensorflow as tf\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \n\n_SEED = 110\nnp.random.seed(_SEED)\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n '--setting', type=str, default='convnet', choices=['convnet', 'densenet'],\n)\n\nargs = parser.parse_args()\nif args.setting == 'convnet':\n \"\"\"\n Architecture Search on Convnet\n \"\"\"\n arch_search_convnet(\n start_net_path='../start_nets/start_net_convnet_C10+_normal',\n arch_search_folder='../arch_search/Convnet/C10+/Conv_C10+_normal_original',\n net_pool_folder='../net_pool/Convnet/C10+/Conv_C10+_normal_original',\n max_episodes=30,\n random=False,\n baseline=False,\n acer=False,\n )\nelif args.setting == 'densenet':\n \"\"\"\n Architecture Search on DenseNet\n \"\"\"\n arch_search_densenet(\n start_net_path='placeholder',\n arch_search_folder='placeholder',\n net_pool_folder='placeholder',\n max_episodes=15,\n )\nelse:\n pass\n","sub_path":"code/arch_search.py","file_name":"arch_search.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"459094233","text":"import argparse\n\nimport Models\nfrom Models import VGGUnet, VGGSegnet, FCN8, FCN32\n\nfrom keras.models import load_model\nimport glob\nimport cv2\nimport numpy as np\nimport random\nimport os\n\n'''\npython predict_onepic.py --input=test.png --output=test_label.png\n'''\n\n\nclass SegnetLabel:\n\tdef __init__(self, n_classes, input_height, input_width, save_weights_path, epoch_number):\n\n\t\tself.limit_gpu_memory()\n\n\t\tmodelFN = Models.VGGSegnet.VGGSegnet\n\n\t\tself.m = modelFN( n_classes , input_height=input_height, input_width=input_width )\n\t\tself.m.load_weights( save_weights_path + \".\" + str( epoch_number ) )\n\t\tself.m.compile(loss='categorical_crossentropy',\n\t\t\toptimizer= 'adadelta' ,\n\t\t\tmetrics=['accuracy'])\n\n\t\tself.n_classes = n_classes\n\t\tself.input_height = input_height\n\t\tself.input_width = input_width\n\n\n\tdef limit_gpu_memory(self):\n\t\t# ---- limit GPU memory resource-----#\n\t\timport tensorflow as tf\n\t\tfrom keras.backend.tensorflow_backend import set_session\n\t\tconfig = tf.ConfigProto()\n\t\tconfig.gpu_options.per_process_gpu_memory_fraction = 0.4\n\t\tset_session(tf.Session(config=config))\n\n\tdef predict(self, inName):\n\t\tX = self.getImageArr(inName , self.input_width , self.input_height , ordering='None' )\n\t\tpr = self.m.predict( np.array([X]) )[0]\n\t\tpr = pr.reshape(( self.m.outputHeight , self.m.outputWidth , self.n_classes ) ).argmax( axis=2 )\n\t\treturn pr\n\n\tdef getImageArr(self, path , width , height , imgNorm=\"sub_mean\" , ordering='channels_first' ):\n\n\t\ttry:\n\t\t\timg = cv2.imread(path, 1)\n\n\t\t\tif imgNorm == \"sub_and_divide\":\n\t\t\t\timg = np.float32(cv2.resize(img, ( width , height ))) / 127.5 - 1\n\t\t\telif imgNorm == \"sub_mean\":\n\t\t\t\timg = cv2.resize(img, ( width , height ))\n\t\t\t\timg = img.astype(np.float32)\n\t\t\t\timg[:,:,0] -= 103.939\n\t\t\t\timg[:,:,1] -= 116.779\n\t\t\t\timg[:,:,2] -= 123.68\n\t\t\telif imgNorm == \"divide\":\n\t\t\t\timg = cv2.resize(img, ( width , height ))\n\t\t\t\timg = img.astype(np.float32)\n\t\t\t\timg = img/255.0\n\n\t\t\tif ordering == 'channels_first':\n\t\t\t\timg = np.rollaxis(img, 2, 0)\n\n\t\t\t# print('img -> ', img.shape)\n\t\t\treturn img\n\t\texcept Exception as e:\n\t\t\tprint(path , e)\n\t\t\timg = np.zeros(( height , width , 3 ))\n\t\t\tif ordering == 'channels_first':\n\t\t\t\timg = np.rollaxis(img, 2, 0)\n\t\t\treturn img\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"--save_weights_path\", type = str, default='weights/ex1' )\n\tparser.add_argument(\"--epoch_number\", type = int, default = 10 )\n\tparser.add_argument(\"--input\", type = str , default = \"\")\n\tparser.add_argument(\"--output\", type = str , default = \"\")\n\tparser.add_argument(\"--input_height\", type=int , default = 224 )\n\tparser.add_argument(\"--input_width\", type=int , default = 224 )\n\tparser.add_argument(\"--n_classes\", type=int , default = 2)\n\n\targs = parser.parse_args()\n\n\n\ts = SegnetLabel(args.n_classes, args.input_height , args.input_width, args.save_weights_path, args.epoch_number )\n\tseg_img = s.predict(args.input)\n\n\tprint('output seg_img.shape = ', seg_img.shape)\n\n\tcv2.imwrite(args.output , seg_img)\n\tcv2.imwrite(args.output +'_x255.jpg', seg_img*255.0)\n\tprint('Save to ' + args.output)\n\tprint('Save to ' + args.output +'_x255.jpg ---> for SHOW')","sub_path":"predict_onepic.py","file_name":"predict_onepic.py","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"376631970","text":"#create.py\nimport gradecheckerror \nimport customer\ndef create_customer():\n name = input('이름 : ')\n tel = input('전화번호 : ')\n email = input('이메일 : ')\n age = int(input('나이 : '))\n grade = None\n while True : \n grade = int(input('고객등급(1 ~ 5) : '))\n if 1 <= grade <= 5 : break\n else : \n #raise gradecheckerror.GradeCheckError()\n print('고객 등급은 1 ~ 5등급만 유효합니다.')\n continue\n etc = input('기타정보 : ')\n mycustomer = customer.Customer(name, tel, age, grade, email, etc)\n return mycustomer","sub_path":"CodePractice/CustomerMgmtProgram(g)/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"295225124","text":"import argparse\nimport logging\nimport readwrite\n\nclass SimpleIOBase(object):\n \n \"\"\"\n Class for ensuring consistency in the definition of simple tools with a single input and single output.\n \n Classes defining operations with low numbers of inputs can inherit from this one and overwrite the \n update method. Child classes can be run in standalone mode if suitable readers and writers have been\n implemented for input and output.\n \n @param self.input the input to the tool\n @return self.output the tool output \n \"\"\"\n \n def __init__(self):\n self.input = None\n self.output = None\n self.tool_name = \"Default\"\n \n def set_input(self, my_input):\n self.input = my_input\n \n def update(self):\n pass\n \n def get_output(self):\n return self.output\n \n def run_standalone(self, sys_args):\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-i\",\"--input\", help=\"Input file path\",type=str)\n parser.add_argument(\"-o\", \"--output\", help=\"Output file path\",type=str)\n args = parser.parse_args()\n logging.info(\"Starting: \" + self.tool_name)\n logging.info(\"Reading: \" + args.input)\n self.input = readwrite.read(args.input)\n logging.info(\"Running: \" + self.tool_name)\n self.update()\n logging.info(\"Writing: \" + args.output)\n readwrite.write(self.output, args.output)\n logging.info(\"Finished: \" + self.tool_name)\n ","sub_path":"src/python/microvessel_chaste/utility/bases.py","file_name":"bases.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"156762334","text":"#! python\n# fromExcelToCsv.py - get the excel data to the csv data\n# XI 2020 Arnold Cytrowski\n\nimport os, csv, openpyxl\n\nfor filename in os.listdir('.'):\n if filename.endswith('.xlsx'):\n wb = openpyxl.load_workbook(filename)\n \n\n for sheet_name in wb.get_sheet_names():\n sheet = wb.get_sheet_by_name(sheet_name)\n\n csv_name = filename[:-5]\n csv_file = open(f'{csv_name}_{sheet_name}.csv', 'w', newline='')\n csv_writer = csv.writer(csv_file)\n\n for row_num in range(1, sheet.max_row + 1):\n row_data = []\n for col_num in range(1, sheet.max_col + 1):\n row_data.append(sheet.cell(row = row_num, column = col_num).value)\n\n for row in row_data:\n csv_writer.writerow(row_num)\n\n csv_file.close()\n\n ","sub_path":"fromExcelToCsv.py","file_name":"fromExcelToCsv.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"457477279","text":"goods = [\n {'title': 'Ковер', 'price': 2000, 'colour': 'green'},\n {'title': 'Диван для отдыха', 'price': 5300, 'colour': 'black'}\n]\n\n\ndef field(items, *args):\n try:\n assert len(items) != 0 and len(args) != 0\n except:\n print(\"Вы не передали аргументы\")\n return_list = []\n for item in items:\n temp_dict = {}\n if len(args) == 1:\n for key, value in item.items():\n if key in args and value != None:\n return_list.append(value)\n else:\n for key, value in item.items():\n if key in args and value != None:\n temp_dict[key] = value\n if len(temp_dict) > 0:\n return_list.append(temp_dict)\n\n return return_list\n\n\ndef main():\n print(str(field(goods, 'title'))[1:-1])\n print(str(field(goods, 'title', 'price'))[1:-1])\n print(str(field(goods, 'title', 'price', 'colour'))[1:-1])\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Lab3/lab_python_fp/field.py","file_name":"field.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"502916612","text":"#!/usr/bin/env python3\n\n\nfrom scapy.all import *\nfrom netfilterqueue import NetfilterQueue\n\n\nresponderIPs = set([])\n\npotentialResponders = set([])\nfor ip in open(\"input-ping.iplist\"):\n ip = ip.strip()\n if ip == \"\":\n continue\n potentialResponders.add(ip)\n\n\n\ndef record(packet):\n #print packet\n pkt = IP(packet.get_payload()) #converts the raw packet to a scapy compatible string\n responderIP = str(pkt[IP].src)\n if responderIP in potentialResponders and responderIP not in responderIPs:\n responderIPs.add(responderIP)\n with open(\"responders-ping.iplist\", 'w') as f:\n f.write(\"\\n\".join(list(responderIPs)))\n print(\"{} Unique hosts. PING found from {}. \".format(len(responderIPs), responderIP))\n packet.accept() #accept the packet \n\n\n\nnfqueue = NetfilterQueue()\n#1 is the iptabels rule queue number, modify is the callback function\nnfqueue.bind(2, record) \ntry:\n print(\"[*] waiting for data\")\n nfqueue.run()\nexcept KeyboardInterrupt:\n pass\n","sub_path":"spread-measure/record_ping.py","file_name":"record_ping.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"36970737","text":"import cv2\nimport numpy as np\nimport math\n\ndef show_img(str, img):\n cv2.imshow(str, img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\ndef get_length(line):\n x1, y1 = line[0], line[1]\n x2, y2 = line[2], line[3]\n length = math.sqrt(abs(x1-x2)**2 + abs(y1-y2)**2)\n return length\n\ndef line_angle(line):\n x1, y1 = line[0],line[1]\n x2, y2 = line[2], line[3]\n\n if y1 - y2 == 0:\n return 0\n\n if x1 - x2 == 0:\n return 90\n\n angle = np.rad2deg(np.arctan2(y2 - y1, x2 - x1))\n\n # make it in multiplcation of 5\n angle = 5 * (int(angle / 5))\n return angle\n\n\ndef filter_angles(lines, angles):\n lines_filtered = [line for line in lines if line_angle(line) in angles]\n return lines_filtered\n\n\ndef proximal_pts(p1, p2, threshold):\n if (abs(p1[0]-p2[0]) < threshold and abs(p1[1]-p2[1]) < threshold):\n return True\n else:\n return False\n \n\nimg_in = cv2.imread(\"./input_images/test_images/stop_249_149_blank.png\")\n\nsign = img_in.copy()\nsign_hsv = cv2.cvtColor(sign, cv2.COLOR_BGR2HSV)\nlower = np.array([0, 43, 46])\nupper = np.array([10, 255, 230])\n\nsign_draw = cv2.inRange(sign_hsv, lower, upper)\nshow_img(\"\",sign_draw)\nedges = cv2.Canny(sign, 100, 200)\nshow_img(\"edges of tl\", edges)\n\n\nlines = cv2.HoughLinesP(edges, rho=1, theta=np.pi / 36, threshold=20, minLineLength=5, maxLineGap=5)\n\nlines = lines.reshape(lines.shape[0], lines.shape[2])\n\nprint(len(lines))\n\n# show_img(\"\", edges)\n\nlengths = [5 * int(get_length(line) / 5) for line in lines]\n# print(sorted(lengths))\n\nlines = np.array([lines[i] for i in range(len(lines)) if 25 <= lengths[i] <= 40])\n# print(len(lines))\n\ni = 0\nfor line in lines:\n if 40 >= 5 * int(get_length(line) / 5) >= 25 or lengths[i] == 995:\n i += 1\n cv2.line(sign_draw, (line[0], line[1]), (line[2], line[3]), (0, 0, 0), 2)\n# show_img(\"\", sign_draw)\nlinesS = filter_angles(lines, [0, 90])\nlinesA = filter_angles(lines, [45, -45])\noctagons = []\ncommons = []\nfor l1 in linesS:\n p1 = (l1[0], l1[1])\n p2 = (l1[2], l1[3])\n for l2 in linesA:\n p3 = (l2[0], l2[1])\n p4 = (l2[2], l2[3])\n for pin1 in [p1, p2]:\n for pin2 in [p3, p4]:\n # print(\"{} {} {} {}\".format(pin1, pin2, abs(pin1[0]-pin2[0]), abs(pin1[1]-pin2[1])))\n if proximal_pts(pin1, pin2, 10):\n common = [int((pin1[0] + pin2[0]) / 2) + 2, int((pin1[1] + pin2[1]) / 2) - 3]\n placed = False\n l1t = tuple(l1)\n l2t = tuple(l2)\n ct = tuple(common)\n l1end = p2 if pin1 == p1 else p1\n l2end = p4 if pin2 == p3 else p3\n\n # check pin1 distance from l2end and pin2 distance from l1end => whatever matches the length take that one\n l1_length = get_length(l1)\n l2_length = get_length(l2)\n l = max(l1_length, l2_length)\n pin1l2 = get_length([pin1[0], pin1[1], l2end[0], l2end[1]])\n pin2l1 = get_length([pin2[0], pin2[1], l1end[0], l1end[1]])\n if abs(pin1l2-l) < abs(pin2l1-l):\n ct = tuple(pin1)\n else:\n ct = tuple(pin2)\n #print(ct)\n commons.append(ct)\n for octagon in octagons:\n if l1t in octagon[\"lines\"] or l2t in octagon[\"lines\"]:\n octagon[\"lines\"].add(l1t)\n octagon[\"lines\"].add(l2t)\n octagon[\"common\"].add(ct)\n octagon[\"common\"].add(l1end)\n octagon[\"common\"].add(l2end)\n placed = True\n if not placed:\n octagon = {\"lines\": set([l1t, l2t]), \"common\": set({ct, l1end, l2end})}\n octagons.append(octagon)\n\nfo = {\"lines\": set(), \"common\": set()}\nif len(octagons) == 0:\n print(\"no octagons\")\nfor o in octagons:\n if len(o[\"lines\"]) >= 3:\n fo[\"lines\"] = fo[\"lines\"].union(o[\"lines\"])\n fo[\"common\"] = fo[\"common\"].union(o[\"common\"])\nprint(len(fo[\"lines\"]))\nprint(fo[\"common\"])\nfor line in fo[\"lines\"]:\n cv2.line(sign, (line[0], line[1]), (line[2], line[3]), (0,0,0), thickness=2)\n\nshow_img(\"\", sign)\n# cv2.destroyAllWindows()\n\n\"\"\"through list of common points + l1end and l2end\"\"\"\n\npoints = list(fo[\"common\"])\npd = list([0 for i in range(len(fo[\"common\"]))])\n\nfor i in range(len(points)):\n distances = [proximal_pts(points[i], pt, 15) for pt in points]\n distances[i] = False\n for j in range(i + 1, len(distances)):\n if pd[j] == 0 and distances[j]:\n pd[j] = 1\n# print(pd)\n\ncenterx = int(np.mean([points[i][0] for i in range(len(points)) if pd[i] == 0]))\ncentery = int(np.mean([points[i][1] for i in range(len(points)) if pd[i] == 0]))\n\n\"\"\"through ct and lines\"\"\"\nfor l in fo[\"lines\"]:\n p1 = tuple([l[0],l[1]])\n p2 = tuple([l[2], l[3]])\n for p in [p1,p2]:\n distances =[proximal_pts(c, p, 20) for c in commons]\n if (p in commons) or (sum(distances) >= 1):\n continue\n else:\n commons.append(p)\ncx = int(np.mean([c[0] for c in commons]))\ncy = int(np.mean([c[1] for c in commons]))\n\nprint(len(commons))\n\nprint(\"{} {}\".format(cx, cy))\n\narea = sign[centery - 5:centery + 5, centerx - 5:centerx + 5]\nred = np.mean(area[:, :, 2])\ngreen = np.mean(area[:, :, 1])\nblue = np.mean(area[:, :, 0])\nif red > 200:\n print(\"{} {}\".format(centerx, centery))\nelse:\n print(\"did not find one :(\")","sub_path":"ps02/playing_stop.py","file_name":"playing_stop.py","file_ext":"py","file_size_in_byte":5626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"120084521","text":"import rsa\nimport urllib\nimport zoo\nimport base64\n\ndef ChangeDjango(conf,inputs,outputs):\n\tcrypto = inputs[\"url\"][\"value\"]\n\t\n\tprivatefile = open('rsa/privateKey.pem')\n\tkeydata = privatefile.read()\n\tprivatekey = rsa.PrivateKey.load_pkcs1(keydata)\n\tunquote = urllib.unquote(base64.b64decode(crypto))\n\t#try:\n\tnewurl = rsa.decrypt(unquote,privatekey)\n\t#except:\n\t#\tconf[\"lenv\"][\"message\"] = str(inputs)\n\t# return zoo.SERVICE_FAILED\n\n\tDjangoServer = open('DjangoServer','w')\n\tDjangoServer.write(newurl)\n\n\treturn zoo.SERVICE_SUCCEEDED\n","sub_path":"ChangeDjango.py","file_name":"ChangeDjango.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"290383610","text":"\nfrom os.path import join, exists, abspath\nfrom os import getcwd\n\ndef getParent(d):\n if not exists(d):\n return None\n return abspath(join(d, '..'))\n\ndef getLogger(loggerName):\n #print \"getlogger called\"\n import logging\n logger = logging.getLogger(loggerName)\n if not logger.handlers:\n #print 'loading log config'\n import logging.config\n \n d = getcwd()\n f = join(d, 'mythbox_log.ini')\n \n while not exists(f) and d:\n d = getParent(d)\n f = join(d, 'mythbox_log.ini')\n \n if d:\n #print 'loading log config from %s' % f\n logging.config.fileConfig(f)\n logger = logging.getLogger(loggerName)\n \n return logger\n","sub_path":"resources/test/mythboxtest/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"382236093","text":"#!/usr/bin/python27\r\nimport xml.sax\r\nimport xml.etree.ElementTree as ET\r\nfrom openpyxl import Workbook\r\n\r\nk = 2\r\nbook = Workbook()\r\nsheet = book.active\r\n\r\nsheet['A1'] = \"product no\"\r\nsheet['B1'] = \"id\"\r\nsheet['C1'] = \"brand\"\r\nsheet['D1'] = \"size\"\r\nsheet['E1'] = \"price\"\r\n#from pathlib import Path\r\nimport os\r\n\r\nclass MovieHandler( xml.sax.ContentHandler ):\r\n def __init__(self):\r\n #self.CurrentData = \"\"\r\n #self.type = \"\"\r\n #self.format = \"\"\r\n #self.year = \"\"\r\n #self.rating = \"\"\r\n #self.stars = \"\"\r\n #self.description = \"\"\r\n self.value = \"\"\r\n\r\n # Call when an element starts\r\n def startElement(self, tag, attributes):\r\n self.CurrentData = tag\r\n if tag == \"product_no\": \r\n title = attributes[\"value\"]\r\n print(title)\r\n block = 'A'+str(k+int(title)-1)\r\n sheet[block] = k-1\r\n self.value = int(title)\r\n\r\n # Call when an elements ends\r\n def endElement(self, tag):\r\n if self.CurrentData == \"id\":\r\n #print (\"id:\", self.type)\r\n block = 'B'+str(k)\r\n sheet[block] = int(self.type)\r\n elif self.CurrentData == \"brand\":\r\n #print (\"Brand:\", self.year)\r\n block = 'C'+str(k)\r\n sheet[block] = self.year\r\n elif self.CurrentData == \"size\":\r\n #print (\"size:\", self.rating)\r\n block = 'D'+str(k)\r\n sheet[block] = int(self.rating)\r\n elif self.CurrentData == \"price\":\r\n block = 'E'+str(k)\r\n sheet[block] = int(self.stars)\r\n #print (\"price:\", self.stars)\r\n \r\n self.CurrentData = \"\"\r\n\r\n # Call when a character is read\r\n def characters(self, content):\r\n if self.CurrentData == \"id\":\r\n self.type = content\r\n elif self.CurrentData == \"brand\":\r\n self.year = content\r\n elif self.CurrentData == \"size\":\r\n self.rating = content\r\n elif self.CurrentData == \"price\":\r\n self.stars = content\r\n \r\nif ( __name__ == \"__main__\"):\r\n \r\n # create an XMLReader\r\n parser = xml.sax.make_parser()\r\n # turn off namepsaces\r\n parser.setFeature(xml.sax.handler.feature_namespaces, 0)\r\n\r\n # override the default ContextHandler\r\n Handler = MovieHandler()\r\n parser.setContentHandler( Handler )\r\n\r\n\r\n\r\n directory_in_str = \"C:\\\\Users\\\\SC0C70493\\\\Desktop\\\\codes\\\\xml\"\r\n\r\n for subdir, dirs, files in os.walk(directory_in_str):\r\n for file in files:\r\n path = os.path.join(subdir,file)\r\n path_in_str = str(path)\r\n #tree = ET.parse(str(path))\r\n parser.parse(path_in_str)\r\n f = open('logfile.txt','a')\r\n f.write(\"read file name:\"+ path_in_str+\"\\n\")\r\n #with open(\"logfile.txt\",\"a\") as text_file2:\r\n #print (\"read file name:\", path_in_str, file = text_file2 )\r\n\r\n #root = tree.getroot()\r\n k = k+1\r\nbook.save(\"sample.xlsx\")\r\n\r\n\r\n'''\r\n pathlist = Path(directory_in_str).glob('**/*.xml')\r\n \r\n for path in pathlist:\r\n path_in_str = str(path)\r\n k = k+1\r\n #print(path_in_str)\r\n parser.parse(path_in_str)\r\n #with open(\"logfile.txt\",\"a\") as text_file2:\r\n #print (\"read file name:\", path_in_str, file = text_file2 )\r\n\r\n\r\n'''\r\n","sub_path":"wbook27.py","file_name":"wbook27.py","file_ext":"py","file_size_in_byte":3242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"305043457","text":"# import patient, lab, observation\r\n\r\nfrom os import listdir\r\nfrom os.path import isfile, join\r\nimport os\r\nimport pandas as pd\r\nimport json\r\nos.environ['KMP_DUPLICATE_LIB_OK'] = 'True'\r\n\r\n## load data to memory\r\ndata_folder = os.path.dirname(__file__)+ '/res/'\r\n\r\nx=os.getcwd()\r\nonlyfiles = [f for f in listdir(data_folder) if (isfile(join(data_folder, f)) & ('.json' in f))]\r\nvarMapping = {}\r\nfor i in onlyfiles:\r\n f = None\r\n name = i.split('.')[0]\r\n n = name\r\n\r\n# f = open('data.json',)\r\n exec('f=open(' + \"'\"+ data_folder + i+\"'\"+')' )\r\n# print(name +'=json.load('+ f+')')\r\n exec(name+' =json.load(f)')\r\n exec('f.close(' + ')' )\r\n varMapping[n] = name\r\n\r\n\r\n# onlyfiles\r\n\r\nvar =[]\r\nvarNames = []\r\nfor key,val in (varMapping.items()):\r\n exec('var.append('+key+')')\r\n exec('varNames.append('+ \"'\"+ key +\"'\"+')')\r\n\r\n\r\ndef mapping(df,map_dic):\r\n# print(df)\r\n v1 = df.values\r\n# print(df[0])\r\n v2 = map_dic[df['index']]\r\n# print(v1)\r\n# print(v2)\r\n return bool(len(list(set(v1) & set(v2))))\r\n\r\n# p.apply(mapping, args=(icd9_map_ahrq,), axis=0)\r\n\r\ndef icd2diseases(icd, map_dic_name):\r\n map_dic=eval(map_dic_name)\r\n p = pd.DataFrame(columns = map_dic.keys())\r\n for v in p.columns.values:\r\n p[v] = icd\r\n pt = p.transpose().reset_index()\r\n d=pd.DataFrame(pt.apply(mapping, args=(map_dic,),axis=1)).transpose()\r\n d.columns = map_dic.keys()\r\n return d\r\n\r\ndef printrepos():\r\n return varNames\r\n\r\ndef getrepo(dic_name):\r\n return eval(dic_name)\r\n\r\ndef printdiseases(dic_name):\r\n keys=[]\r\n for key,val in (eval(dic_name).items()):\r\n keys.append(key)\r\n return keys\r\n","sub_path":"icdMapping/icd2map.py","file_name":"icd2map.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"194884150","text":"import numpy as np\nfrom creation import load_profile\nfrom classes import ExerciseBank\nimport matplotlib\n\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\nfrom cluster_util import compute_serial_matrix, compute_clusters\n\ndef sample_exercises(number, profile, exercise_bank, initial_sampling_probs, distance_matrix,\n repetition_penalty=1, verbose=False):\n exercises = []\n sampling_prob = np.copy(initial_sampling_probs)\n ex_index = -1\n last_equipment = []\n for i in range(number):\n # renormalize\n norm_probs = sampling_prob / np.sum(sampling_prob)\n # if verbose:\n # print('Currrent exercise: {}\\n'.format(self.all_exercises[ex_index].name) if ex_index != -1 else 'None')\n # sort_ind = np.argsort(norm_probs)\n # for i in sort_ind:\n # print('{}: {:.3f}'.format(self.all_exercises[i].name, norm_probs[i]))\n # print('\\n\\n\\n')\n\n ex_index = np.nonzero(np.random.multinomial(1, norm_probs))[0][0]\n new_equip = exercise_bank.get_exercise(ex_index).get_preferred_equipment(profile['equipment'])\n attempts = 0\n num_humans = 1 if 'num_humans' not in profile else profile['num_humans']\n if num_humans > 1:\n # for now, assume only one of each equipment for set of humans\n while (new_equip in last_equipment and new_equip != 'bodyweight'):\n ex_index = np.nonzero(np.random.multinomial(1, norm_probs))[0][0] # resample until you get a valid one\n new_equip = exercise_bank.get_exercise(ex_index).get_preferred_equipment(profile['equipment'])\n if attempts == 10000:\n print('Couldnt find exercises with different equipment')\n break # no valid ones are likely\n attempts += 1\n exercises.append(exercise_bank.get_exercise(ex_index))\n sampling_prob *= distance_matrix[ex_index, :]\n #make that particulat exercise even less likely\n sampling_prob[ex_index] /= repetition_penalty\n last_equipment.append(new_equip)\n if len(last_equipment) >= num_humans:\n last_equipment.pop(0)\n return exercises\n\n\nif __name__ == '__main__':\n\n profile = load_profile()\n exercise_bank = ExerciseBank(profile['equipment'])\n\n ex_names = []\n distance_matrix = np.copy(exercise_bank.dissimilarity)\n\n rep_penalty = 20\n num_clusters = 12\n singleton_correction = 5\n\n diag_mask = np.eye(distance_matrix.shape[0]).astype(np.int) == 1\n distance_matrix[diag_mask] = 0\n seriated_dist, res_order, res_linkage = compute_serial_matrix(distance_matrix, 'complete')\n clusters = compute_clusters(res_linkage, num_clusters=num_clusters)\n cluster_weighting = np.ones(exercise_bank.get_num_valid_exercises())\n for cluster_indices in clusters:\n for i in cluster_indices:\n cluster_weighting[i] = len(cluster_indices)\n\n\n\n initial_sampling_probs = np.ones(exercise_bank.get_num_valid_exercises())\n inverse_weighting = 1 / (cluster_weighting + singleton_correction)\n dissimilarity = np.sqrt(np.dot(inverse_weighting[:, None], inverse_weighting[None, :]))\n\n\n for i in range(500):\n print('{} \\r'.format(i), end='')\n exercises = sample_exercises(10, profile, exercise_bank,\n initial_sampling_probs, dissimilarity, repetition_penalty=rep_penalty)\n ex_set_names = [e.get_name(profile['equipment']) for e in exercises]\n ex_names.extend(ex_set_names)\n # print(ex_set_names)\n\n unique_ex_names = [e.get_name(profile['equipment']) for e in exercise_bank._all_exercises]\n\n sorted_ex_names = []\n colors = []\n for cluster_count, cluster_indices in enumerate(clusters):\n for i in cluster_indices:\n sorted_ex_names.append(unique_ex_names[i])\n colors.append(['red', 'blue', 'orange', 'green', 'gray', 'purple'][cluster_count % 6])\n\n #plot exercise frequency\n gs = GridSpec(4, 4)\n plt.figure()\n ax = plt.subplot(gs[1:])\n y_pos = np.arange(len(sorted_ex_names))\n freq = [ len(list(filter(lambda x: e == x, ex_names))) for e in sorted_ex_names]\n freq = np.array(freq)\n freq = freq / np.sum(freq)\n\n ax.barh(y_pos, freq, align='center', color=colors)\n ax.set_yticks(y_pos)\n ax.set_yticklabels(sorted_ex_names)\n ax.invert_yaxis() # labels read top-to-bottom\n ax.set_xlabel('frequency')\n plt.show()\n\n\n #plot uniqueness score\n # plt.figure()\n\n # plt.imshow(exercise_bank._adjacency_mat)\n # plt.imshow(dist)\n\n\n # plt.imshow(diag_mask)\n # distance_matrix = np.copy(exercise_bank.dissimilarity)\n # plt.imshow(distance_matrix, cmap='inferno')\n # plt.gca().set_yticks(range(len(unique_ex_names)))\n # plt.gca().set_yticklabels(unique_ex_names)\n\n # distance_matrix = np.copy(exercise_bank.dissimilarity)\n # diag_mask = np.eye(distance_matrix.shape[0]).astype(np.int) == 1\n # distance_matrix[diag_mask] = 0\n # seriated_dist, res_order, res_linkage = compute_serial_matrix(distance_matrix, 'complete')\n # plt.imshow(seriated_dist, cmap='inferno')\n # plt.gca().set_yticks(range(len(unique_ex_names)))\n # plt.gca().set_yticklabels([unique_ex_names[i] for i in res_order])\n #\n\n # clusters = compute_clusters(res_linkage, num_clusters=24, names=unique_ex_names)\n # for cluster in clusters:\n # print([unique_ex_names[i] for i in cluster])\n #\n #\n # #visualize clistering\n # gs = GridSpec(4, 4)\n # plt.figure()\n # ax = plt.subplot(gs[1:])\n # y_pos = np.arange(len(unique_ex_names))\n # freq = [len(list(filter(lambda x: e == x, ex_names))) for e in unique_ex_names]\n # freq = np.array(freq)\n # freq = freq / np.sum(freq)\n # ax.barh(y_pos, freq, align='center')\n # ax.set_yticks(y_pos)\n # ax.set_yticklabels(unique_ex_names)\n # ax.invert_yaxis() # labels read top-to-bottom\n # ax.set_xlabel('frequency')\n # plt.show()\n\n\n\n","sub_path":"sampler.py","file_name":"sampler.py","file_ext":"py","file_size_in_byte":6019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"595327788","text":"'''\nThe following code was influenced by Pratik Nabriya's article written on Towards Datascience about SMA's and EMA's\n\nThis article can be found at the following link:\n\nhttps://towardsdatascience.com/making-a-trade-call-using-simple-moving-average-sma-crossover-strategy-python-implementation-29963326da7a\n\nThe purpose of this code is to track a few stocks using a EMA, and send an email when there is a crossover which indicates\na buying or selling point. This project was done as a fun introduntion into developing a trading bot, and SHOULD NOT be used\nas financial advice in any way.\n\n'''\n\n\nfrom send_email import email\nimport yfinance as yf\nimport numpy as np\nimport time\n\n# A list of stocks you want to track\nstocklist = ['ETH-USD', 'BTC-USD', 'AAPL', 'TSLA',\n 'AMZN', 'BCH-USD', 'GOOGL', 'LTC-USD', 'XLM-USD']\n\nshort_ma = 20\nlong_ma = 50\nperiod = '3mo'\nemodel = email()\n\n\nwhile True:\n\n for stock in stocklist:\n\n # Download the stock data for each day from yfinance\n stockdata = yf.download(tickers=stock, period=period, interval='60m')\n # We are going to use the close price as the predictor\n # Therefore we drop the rest of the tables\n stockdata = stockdata.drop(\n ['Volume', 'Open', 'High', 'Low', 'Adj Close'], axis=1)\n\n # Create the shorter exponential moving average column\n stockdata[f'{short_ma}_EMA'] = stockdata['Close'].ewm(\n span=short_ma, adjust=False).mean()\n # Create the longer exponential moving average column\n stockdata[f'{long_ma}_EMA'] = stockdata['Close'].ewm(\n span=long_ma, adjust=False).mean()\n\n stockdata['Signal'] = 0.0\n stockdata['Signal'] = np.where(\n stockdata[f'{short_ma}_EMA'] > stockdata[f'{long_ma}_EMA'], 1.0, 0.0)\n\n stockdata['Position'] = stockdata['Signal'].diff()\n\n # If the last entry indicates a buy or a sell, then send an email\n if(stockdata.iloc[-1]['Position'] == 1):\n subject = f'BUY {stock}'\n message = f\"Hi Mitch,\\n\\nI just thought I would let you know that it may be a good idea to buy some {stock} stock.\\n\\nThe current price in USD is {round(stockdata.iloc[-1]['Close'],2)}.\\n\\nKind regards,\\n\\nMietsBot\"\n print(subject)\n emodel.send_email(subject, message)\n elif(stockdata.iloc[-1]['Position'] == -1):\n subject = f'SELL {stock}'\n message = f\"Hi Mitch,\\n\\nI just thought I would let you know that it may be a good idea to sell some {stock} stock.\\n\\nThe current price in USD is {round(stockdata.iloc[-1]['Close'],2)}.\\n\\nKind regards,\\n\\nMietsBot\"\n print(subject)\n emodel.send_email(subject, message)\n else:\n # If we are holding then we do not want to send an email\n subject = f'HOLD {stock}'\n print(subject)\n\n time.sleep(3600)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"486010929","text":"from typing import List\nimport discord\nimport yaml\n\nfrom src.utils.embeds_manager import EmbedsManager\nfrom src.utils.permissions_manager import PermissionsManager\n\n\nasync def add_reason(client: discord.Client, message: discord.Message, args: List[str]):\n with open('run/config/config.yml', 'r') as file:\n config = yaml.safe_load(file)\n\n # Check permissions\n if not PermissionsManager.has_perm(message.author, 'manage_reason'):\n return await message.channel.send(\n embed=EmbedsManager.error_embed(\n \"Vous n'avez pas les permissions pour cette commande.\"\n )\n )\n\n # Help message\n if args and args[0] == '-h':\n return await message.channel.send(\n embed=EmbedsManager.information_embed(\n \"Rappel de la commande : \\n\"\n f\"`{config['prefix']}reason_add `\"\n )\n )\n\n # Check inputs\n if len(args) < 2:\n return await message.channel.send(\n embed=EmbedsManager.error_embed(\n f\":x: Merci de mettre une raison d'au moins deux mots.\"\n )\n )\n\n # Process code\n with open('run/config/reasons.yml', 'r', encoding='utf8') as file:\n reasons = yaml.safe_load(file)\n reasons.append((' '.join(args)))\n\n with open('run/config/reasons.yml', 'w', encoding='utf8') as outfile:\n yaml.dump(reasons, outfile, default_flow_style=False, allow_unicode=True)\n\n await message.channel.send(\n embed=EmbedsManager.complete_embed(\n f\"{message.author.mention} La raison `{reasons[-1]}` a été ajouté à la liste.\\n\"\n f\"Son numéro d'attribution est le {len(reasons)}.\"\n )\n )\n","sub_path":"src/eventsHandler/on_message/moderation/reasons/add_reason.py","file_name":"add_reason.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"237258883","text":"#!/usr/bin/env python3\nimport sqlite3\nimport os\nfrom dotenv import load_dotenv\n\n# .envファイルの内容を読み込みます\nload_dotenv()\n\n\ndbname = os.environ[\"DBNAME\"]\nconn = sqlite3.connect(dbname)\ncur = conn.cursor()\n\n# instagramContentsというtableを作成してみる\ncur.execute(\n 'CREATE TABLE instagramContents(id INTEGER PRIMARY KEY AUTOINCREMENT, post_content STRING);')\nconn.commit()\nconn.close()\n","sub_path":"db_init.py","file_name":"db_init.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"142144030","text":"# coding=utf-8\n\"\"\"Taxon model definition.\n\n\"\"\"\n\nfrom django.db import models\nfrom django.dispatch import receiver\nfrom bims.models.iucn_status import IUCNStatus\nfrom bims.utils.iucn import get_iucn_status\n\n\nclass Taxon(models.Model):\n \"\"\"Taxon model.\"\"\"\n\n gbif_id = models.IntegerField(\n verbose_name='GBIF id',\n null=True,\n blank=True,\n )\n iucn_status = models.ForeignKey(\n IUCNStatus,\n models.SET_NULL,\n null=True,\n blank=True,\n )\n common_name = models.CharField(\n max_length=100,\n blank=True,\n default='',\n )\n scientific_name = models.CharField(\n max_length=100,\n blank=True,\n default='',\n )\n author = models.CharField(\n max_length=100,\n blank=True,\n default='',\n )\n\n # noinspection PyClassicStyleClass\n class Meta:\n \"\"\"Meta class for project.\"\"\"\n app_label = 'bims'\n verbose_name_plural = 'Taxa'\n verbose_name = 'Taxon'\n\n def __str__(self):\n return \"%s (%s)\" % (self.common_name, self.iucn_status)\n\n\n@receiver(models.signals.pre_save, sender=Taxon)\ndef taxon_pre_save_handler(sender, instance, **kwargs):\n \"\"\"Get iucn status before save.\"\"\"\n if instance.common_name and not instance.iucn_status:\n iucn_status = get_iucn_status(\n species_name=instance.common_name\n )\n if iucn_status:\n instance.iucn_status = iucn_status\n","sub_path":"bims/models/taxon.py","file_name":"taxon.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"563761089","text":"import gym\nimport numpy as np\nimport random\nimport time\n\n# Q(st,at)=Q(st, at)+lr*(R_t+1+gama*Q(s_t+1, a_t+1) - Q(st, at))\nclass SarsaAgent:\n def __init__(self, action_space, state_space, lr=0.1, gama=0.9):\n self.action_space=action_space\n self.state_space = state_space\n self.lr=lr\n self.gama=gama\n self.explore_rate=0.1\n self.Q=np.random.random([self.state_space, self.action_space])\n\n def sample(self, state):\n _p=np.random.uniform()\n if _p=1)and(exponent>=2)):\n for e in range(exponent):\n result*=numerator\n print(result)\nelse:\n print(\"Invalid Option!\")\n","sub_path":"Livros/Introdução à Programação - 500 Algoritmos resolvidos/Capitulo 4/Exercicios 4a/Algoritmo187_para14.py","file_name":"Algoritmo187_para14.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"369516837","text":"import time\nimport CAN_SPEC\n\nXBEE_BAUD = 111111 #This is the ACTUAL baudrate the xbee runs at after dividing\n #down it's 16MHz clock\n\nTIME = 0\nBATTERY_SOC = 1\nBATTERY_TEMP = 2\nBATTERY_VOLTAGE = 3\nTHROTTLE = 4\nBRAKE = 5\nSPEED = 6\n\n\nTIME_POS = 0\nDATA_TYPE_POS = 1\nDATA_POS = 2\n\ndef read_packet(xbee_stream):\n #timestamp_ID_MSGLEN_MSG_LineCount\n xbeeData = ''\n val = xbee_stream.read(1)\n print(val)\n try:\n xbeeData += val.decode()\n except UnicodeDecodeError:\n print('out of sync')\n return None\n\n under_count = 0\n while under_count < 3:\n if xbee_stream.in_waiting > 0:\n val = xbee_stream.read(1).decode()\n if val == '_':\n under_count = under_count + 1\n xbeeData += val\n\n split_data = xbeeData.split('_')\n payload_len = int(split_data[2])\n payload = xbee_stream.read(payload_len)\n\n newline = 0\n while not newline:\n if xbee_stream.in_waiting > 0:\n val = xbee_stream.read(1)\n val = val.decode()\n if val == '\\n':\n newline = 1\n break\n xbeeData += val\n\n return xbeeData, payload\n\ndef parseMessage(data_line, log_start):\n\n print(\"Raw metadata: {0}\".format(data_line[0:5]))\n print(\"Raw payload: {0}\".format(data_line[5:]))\n meta = int.from_bytes(data_line[0:5], byteorder='little')\n payload = data_line[6:]\n\n timestamp = log_start + (meta>>11)/1000\n\n print('Timestamp: {0}'.format(timestamp))\n ID = meta & 0b11111111111 #ID is in least significant 11 bits\n ID = CAN_SPEC.ID_Dict.get(ID)\n if ID == None:\n return None, None, None\n print('ID Name: {0}'.format(ID))\n data_dict = CAN_SPEC.Data_Pos_Dict[ID]\n MSG_data = {}\n\n #Endianess is BULLSHIT\n if CAN_SPEC.is_little_endian[ID]:\n payload = bytearray(payload)\n payload.reverse()\n print(\"PAYLOAD LITTLE: {0}\".format(payload))\n print(\"BYTE 0: {0}\".format(payload[0]))\n MSG = int.from_bytes(payload, byteorder='little')\n print(\"MSG LITTLE: {0}\".format(MSG))\n for k, v in data_dict.items():\n mask = 0\n for i in range(v[0], v[1]+1):\n mask = mask + (1<>v[0];\n else:\n if ID != 1320:\n payload = bytearray(payload)\n payload.reverse()\n # for i in range(0,len(payload)):\n # print(bin(payload[i]))\n print(\"PAYLOAD BIG: {0}\".format(payload))\n print(\"BYTE 0: {0}\".format(payload[0]))\n MSG = int.from_bytes(payload, byteorder='big')\n print(bin(MSG))\n print(\"MSG BIG: {0}\".format(MSG))\n for k, v in data_dict.items():\n mask = 0\n for i in range(v[0], v[1]+1):\n mask = mask + (1<>v[0])))\n MSG_data[k] = (MSG & mask)>>v[0];\n # print(\"PAYLOAD BIG: {0}\".format(payload))\n # for k, v in data_dict.items():\n # mask = payload[(v[0]//8):((v[1]//8)+1)]\n # MSG_data[k] = int.from_bytes(mask, byteorder='big')\n # print(\"MSG BIG: {0}\".format(MSG_data[k]))\n\n # print(\"--- Data Dictionary ---\")\n # print(MSG_data)\n # print(\"--- Data Dictionary ---\")\n\n return timestamp, ID, MSG_data\n\n\n\ndef syncXbee(xBeeSerial):\n notSync = True\n ack = 'a'\n print('sync')\n while(notSync):\n print('send ack' + ack)\n xBeeSerial.write(ack.encode('utf-8'))\n print('sleep')\n if xBeeSerial.in_waiting > 0:\n val = xBeeSerial.read(1)\n print(val.decode())\n if val.decode() == 'b':\n notSync = False\n\n time.sleep(.5)\n\ndef batteryTempParse(data):\n batteryData = data.split('-')\n outputDict = {}\n for i in splitMessage:\n cellData = batteryData.split('=')\n outputDict[cellData[0]] = cellData[1]/10\n\n return outputDict\n","sub_path":"xbeeParser.py","file_name":"xbeeParser.py","file_ext":"py","file_size_in_byte":4138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"425505410","text":"'''\nCreated on Apr 5, 2016\n\n@author: Jakub Bernat\n'''\nimport numpy as np\nimport numpy.linalg as la\nimport matplotlib.pyplot as plt\nimport random\nimport core.observerlibrary as mo\nimport core.tools as ctls\nimport logging \n\nclass Simulation: \n \n logger = logging.getLogger('Simulation') \n \n def __init__(self, name, x0_1 = -0.25, x0_2 = -0.25, x0_3 = -0.25):\n self.name = name;\n self.Tp = 0.0001;\n self.Np = 450;\n self.N = 3 # state size\n self.M = 1 # output number\n self.P = 1 # input number\n # motor parameters\n self.R = 3.2 # Ohm\n self.L = 0.0086 # mH\n self.Kt = 0.0319 # Nm/A \n self.fd = 0.00012 # Nms/rad\n self.J = 30*10.0**-6 # kgm2\n self.mi = -0.06 # Nm/As\n # DC motor \n self.A = np.matrix(np.zeros((self.N-1,self.N-1)))\n self.A[0,0] = - self.fd/self.J \n self.A[0,1] = self.Kt/self.J \n self.A[1,0] = - self.Kt/self.L \n self.A[1,1] = - self.R/self.L \n self.B = np.matrix(np.zeros((self.N-1,self.N-1))) \n self.B[0,0] = - 1.0/self.J\n self.B[1,1] = 1.0/self.L\n self.C = np.matrix(np.zeros((1,self.N-1)))\n self.C[0,0] = 0.0\n self.C[0,1] = 1.0 \n # observer definition\n self.Ao = np.matrix(np.zeros((self.N,self.N)))\n self.Ao[0,0] = - self.fd/self.J \n self.Ao[0,1] = self.Kt/self.J\n self.Ao[0,2] = - 1.0/self.J\n self.Ao[1,0] = - self.Kt/self.L \n self.Ao[1,1] = - self.R/self.L \n self.Bo = np.matrix(np.zeros((self.N,1)))\n self.Bo[0,0] = 0.0\n self.Bo[1,0] = 1.0/self.L\n self.Bo[2,0] = 0.0\n self.Co = np.matrix(np.zeros((1,self.N)))\n self.Co[0,0] = 0.0\n self.Co[0,1] = 1.0\n self.Co[0,2] = 0.0 \n # observer gain\n self.Lo = np.matrix(np.zeros((self.N,1)))\n self.Lo[2,0] = -self.mi \n # check closed loop\n self.logger.debug('Ao-LoCo:')\n self.logger.debug(self.Ao-self.Lo*self.Co)\n w, _ = la.eig(self.Ao-self.Lo*self.Co)\n self.logger.debug('Poles of matrix Ao-LoCo:')\n self.logger.debug(w)\n \ndef runObserverMulti(s, observerType='RLS', mapping='integral-finite'):\n\n # time definition\n time = np.linspace(0.0, (s.Np-1)*s.Tp, s.Np) \n # input signal\n u = np.asmatrix(10.0*np.sign(np.sin(2*np.pi*(1.0/8.0)*time)))\n # DC motor virtual input\n v = np.asmatrix(np.zeros((2,1)))\n # output signal\n y = np.asmatrix(np.zeros((1,s.Np))) \n # plant state \n x = np.asmatrix(np.zeros((2,s.Np))) \n # load torque\n Tload = 0.01*np.asmatrix(np.ones((1,s.Np))) \n # multi-observer \n mmObserver = mo.MMObserverLTI(s.N, s.M, s.Tp, s.Ao, s.Bo, s.Co, s.Lo, mapping, observerType, 50.0, 1.0, [100.0, 1.0, 0.02]) \n # estimated state\n xe = np.asmatrix(np.zeros((3,s.Np))) \n # simulation\n for n in range(s.Np-1): \n # virtual input - load torque\n v[0,0] = Tload[0,n]\n # virtual input - voltage\n v[1,0] = u[0,n]\n # calculate system state\n x[:,n+1] = x[:,n] + s.Tp*(s.A*x[:,n] + s.B*v)\n y[:,n] = s.C*x[:,n] + 0.05*(random.random()-0.5)\n # call observer\n xe[:,n] = mmObserver.observe(u[:,n], y[:,n])\n # last iteration\n n = s.Np-1 \n y[:,n] = s.C*x[:,n] + 0.05*(random.random()-0.5)\n xe[:,n] = mmObserver.observe(u[:,n], y[:,n])\n \n result = dict()\n result['time'] = time\n result['e1'] = xe[0,:]-x[0,:]\n result['e2'] = xe[1,:]-x[1,:]\n result['e3'] = xe[2,:]-Tload\n result['x1'] = x[0,:]\n result['x2'] = x[1,:]\n result['x3'] = Tload \n result['xe1'] = xe[0,:]\n result['xe2'] = xe[1,:]\n result['xe3'] = xe[2,:]\n result['u'] = u\n return result\n\nctls.configureLogger()\n\ns = Simulation('Simple example')\n\n# run simulation without second layer (single model)\nra = runObserverMulti(s, 'none')\n# run simulation with second layer (multi model)\nrMMa = runObserverMulti(s, 'RLS')\n\ntime = ra['time']\n\nx1 = ra['x1']\nx2 = ra['x2']\nx3 = ra['x3']\n\nxe1S = ra['xe1']\nxe2S = ra['xe2']\nxe3S = ra['xe3']\n\nxe1M = rMMa['xe1']\nxe2M = rMMa['xe2']\nxe3M = rMMa['xe3']\n\ne1 = ra['e1']\ne2 = ra['e2']\ne3 = ra['e3']\n\ne1MM = rMMa['e1']\ne2MM = rMMa['e2']\ne3MM = rMMa['e3']\n\ncon = 10000.0\nsuffix = '.png'\n\nax = plt.subplot(111)\nax.plot(time, ctls.to_plot_array(x1, con), label='motor speed $\\\\omega(t)$', linewidth=3.0)\nax.plot(time, ctls.to_plot_array(xe1S, con), label='estimated motor speed (SO) $\\\\hat{\\\\omega}(t)$', linewidth=3.0)\nax.plot(time, ctls.to_plot_array(xe1M, con), label='estimated motor speed (MO) $\\\\hat{\\\\omega}(t)$', linewidth=3.0)\nplt.xlabel('time $[s]$')\nplt.ylabel('motor speed $[rad/s]$')\nplt.legend(loc = 4)\nplt.savefig('sensorless_speed' + suffix, bbox_inches=0);\nplt.clf();\n\nax = plt.subplot(111) \nax.plot(time, ctls.to_plot_array(x2, con), label='motor current $i(t)$', linewidth=3.0)\nax.plot(time, ctls.to_plot_array(xe2S, con), label='estimated motor current (SO) $\\\\hat{i}(t)$', linewidth=3.0)\nax.plot(time, ctls.to_plot_array(xe2M, con), label='estimated motor current (MO) $\\\\hat{i}(t)$', linewidth=3.0)\nplt.xlabel('time $[s]$')\nplt.ylabel('motor current $[A]$')\nplt.legend(loc = 4)\nplt.savefig('sensorless_current' + suffix, bbox_inches=0);\nplt.clf();\n\nax = plt.subplot(111) \nax.plot(time, ctls.to_plot_array(x3, con), label='load torque $T_L(t)$', linewidth=3.0)\nax.plot(time, ctls.to_plot_array(xe3S, con), label='estimated load torque (SO) $\\\\hat{T}_L(t)$', linewidth=3.0)\nax.plot(time, ctls.to_plot_array(xe3M, con), label='estimated load torque (MO) $\\\\hat{T}_L(t)$', linewidth=3.0)\nplt.xlabel('time $[s]$')\nplt.ylabel('load torque $[Nm]$')\nplt.legend(loc = 4)\nplt.savefig('sensorless_load_torque' + suffix, bbox_inches=0);\nplt.clf();\n\nax = plt.subplot(111) \nax.plot(time, ctls.to_plot_array(e1, con), label='single layer observer $e_1(t)$', linewidth=3.0)\nax.plot(time, ctls.to_plot_array(e1MM, con), label='multi layer observer $e_1(t)$', linewidth=3.0)\nplt.xlabel('time $[s]$')\nplt.ylabel('observation error $e_1$')\nplt.savefig('sensorless_e1' + suffix, bbox_inches=0);\nplt.clf();\n\nax = plt.subplot(111) \nax.plot(time, ctls.to_plot_array(e2, con), label='single layer observer $e_2(t)$', linewidth=3.0)\nax.plot(time, ctls.to_plot_array(e2MM, con), label='multi layer observer $e_2(t)$', linewidth=3.0)\nplt.xlabel('time $[s]$')\nplt.ylabel('observation error $e_2$')\nplt.savefig('sensorless_e2' + suffix, bbox_inches=0);\nplt.clf();\n\nax = plt.subplot(111) \nax.plot(time, ctls.to_plot_array(e3, con), label='single layer observer $e_3(t)$', linewidth=3.0)\nax.plot(time, ctls.to_plot_array(e3MM, con), label='multi layer observer $e_3(t)$', linewidth=3.0)\nplt.xlabel('time $[s]$')\nplt.ylabel('observation error $e_3$')\nplt.savefig('sensorless_e3' + suffix, bbox_inches=0);\nplt.clf();\n","sub_path":"examples/sensorlessDCmotor.py","file_name":"sensorlessDCmotor.py","file_ext":"py","file_size_in_byte":7047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"278387600","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom woaiwojia.items import AgentItem\nfrom woaiwojia.settings import *\n\n\nclass AijiaSpider(scrapy.Spider):\n name = 'aijia'\n allowed_domains = ['hz.5i5j.com']\n # start_urls = ['http://hz.5i5j.com/']\n\n # def start_requests(self):\n # base_url = \"https://hz.5i5j.com/ershoufang/n{}/\"\n # for page in range(1, MAX_PAGE+1):\n # yield scrapy.Request(url=base_url.format(page), dont_filter=True, callback=self.parse_link)\n\n def start_requests(self):\n base_url = \"https://hz.5i5j.com/ershoufang/n1/\"\n yield scrapy.Request(url=base_url, dont_filter=True, callback=self.parse_link)\n\n def parse_link(self, response):\n # print(response.text)\n links = response.xpath(\"//ul[@class='pList']/li\")\n for link in links:\n short_url = link.xpath(\".//div[@class='listImg']/a/@href\").get()\n domain = \"https://hz.5i5j.com\"\n yield scrapy.Request(url=domain+short_url, dont_filter=True, callback=self.parse_detail)\n\n def parse_detail(self, response):\n # print(response.text)\n item = AgentItem()\n info = response.xpath(\"//li[@class='daikcon fl']\")\n item[\"name\"] = info.xpath(\".//h3/a/text()\").get()\n item[\"tel\"] = info.xpath(\".//label/text()\").get()\n # if not item[\"name\"] or not item[\"tel\"]:\n # yield scrapy.Request(url=response.url, dont_filter=True, callback=self.parse_detail)\n yield item\n","sub_path":"woaiwojia/spiders/aijia.py","file_name":"aijia.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"212339617","text":"import discord\nfrom discord.ext import commands\nimport asyncio\nimport random\nimport pickle\nimport sys\nimport math\nimport time\n\n#Levels\n#Formula = prev. + (prev. * 1.1)\nlvls_xp = [(5*(i**3)+50*i+100) for i in range(500)]\n\n#Colouring\ndef RankColour(rank):\n if rank == 1:\n return 0xFFFF11\n elif rank == 2:\n return 0xAAAAAA\n elif rank == 3:\n return 0x994400\n elif rank > 3 and rank <= 5:\n return 0x00FFFF\n elif rank > 5 and rank <= 10:\n return 0xFF3377\n elif rank > 10 and rank <= 25:\n return 0x00CC66\n elif rank > 25 and rank <= 50:\n return 0xCC4411\n elif rank > 50 and rank <= 100:\n return 0x990055\n elif rank > 100 and rank <= 250:\n return 0x9999FF\n else:\n return 0xFFFFFF\n\n#Format:\n#User Name Points Participations\nclass CPCog:\n def __init__(self, bot):\n self.bot = bot\n\n @commands.group(name=\"cp\")\n async def CP(self, ctx):\n if ctx.invoked_subcommand is None:\n if ctx.channel.id != 433349202433802250:\n await ctx.message.delete()\n await ctx.send(content=\"Wrong channel. Please use #bot_spammin.\",delete_after=5)\n return\n await ctx.send(\"You haven't sent a Clan Points subcommand. Use `&help cp` to find out how to use the command.\")\n\n @CP.command(name='stats')\n async def TCheck(self, ctx, *, member: discord.Member=None):\n if ctx.channel.id != 433349202433802250:\n await ctx.message.delete()\n await ctx.send(content=\"Wrong channel. Please use #bot_spammin.\",delete_after=5)\n return\n if member is None:\n member = ctx.author\n if ctx.guild == None:\n return\n CPList = []\n CPList = pickle.load(open('CP.data', 'rb'))\n added = False\n for y in range(len(CPList)):\n if CPList[y][0] == (member.id):\n added = True\n placement = y\n break\n if added == True:\n embed = discord.Embed(title=\"Stats for\",\n description=member.name,\n colour=RankColour(placement))\n embed.set_author(name=member.display_name,\n icon_url=member.avatar_url_as(format='png'))\n #icon_url=self.bot.user.avatar_url_as(format='png'))\n #icon_url='https://cdn.discordapp.com/avatars/421718079265964032/7805693d09954641ab8bbb51f3582f07.png')\n #embed.set_thumbnail(url=ctx.author.avatar_url_as(format='png'))\n embed.add_field(name='Rank',\n value=(placement)+1)\n embed.add_field(name='Points',\n value=(CPList[placement][2]))\n embed.set_footer(text=ctx.guild.name,\n icon_url=ctx.guild.icon_url_as(format='png'))\n\n await ctx.send(content='**Displaying user CPs**', embed=embed)\n print(CPList)\n print('')\n \n @CP.command(name='rank')\n async def TRank(self, ctx, placement:int=None):\n if ctx.channel.id != 433349202433802250:\n await ctx.message.delete()\n await ctx.send(content=\"Wrong channel. Please use #bot_spammin.\",delete_after=5)\n return\n if ctx.guild == None:\n return\n if placement == None:\n placement = 1\n CPList = []\n CPList = pickle.load(open('CP.data', 'rb'))\n added = False\n if (placement) >= len(CPList) or placement < 1:\n await ctx.send(\"There isn't a person at that rank.\")\n return\n \n member = self.bot.get_user(int(CPList[placement][0]))\n embed = discord.Embed(title=\"Clan Points for\",\n description=member.display_name,\n colour=RankColour(placement))\n embed.set_author(name=member.display_name,\n icon_url=member.avatar_url_as(format='jpg'))\n\n embed.add_field(name='Rank',\n value=(placement))\n embed.add_field(name='Points',\n value=(CPList[placement][2]))\n if placement == 1:\n embed.add_field(name='CPs to next rank',\n value=\"You are #1!\")\n else:\n embed.add_field(name='CPs to next rank',\n value=((CPList[placement-1][2])-(CPList[placement][2]))+1)\n embed.set_footer(text=ctx.guild.name,\n icon_url=ctx.guild.icon_url_as(format='png'))\n\n await ctx.send(content='**Displaying rank CPs**', embed=embed)\n print(CPList)\n print('')\n \n @CP.command(name='top')\n async def CPTop(self,ctx):\n #if ctx.channel.id != 433349202433802250:\n # await ctx.message.delete()\n # await ctx.send(content=\"Wrong channel. Please use #bot_spammin.\",delete_after=5)\n # return\n if ctx.guild == None:\n return\n XPList=[]\n XPList = pickle.load(open('CP.data','rb'))\n placement = 1\n value1 = \"•**Name:** \"+str(ctx.guild.get_member(XPList[1][0]))+\"\\n•**CPs:** \"+str(XPList[1][2])\n value2 = \"•**Name:** \"+str(ctx.guild.get_member(XPList[2][0]))+\"\\n•**CPs:** \"+str(XPList[2][2])\n value3 = \"•**Name:** \"+str(ctx.guild.get_member(XPList[3][0]))+\"\\n•**CPs:** \"+str(XPList[3][2])\n value4 = \"•**Name:** \"+str(ctx.guild.get_member(XPList[4][0]))+\"\\n•**CPs:** \"+str(XPList[4][2])\n value5 = \"•**Name:** \"+str(ctx.guild.get_member(XPList[5][0]))+\"\\n•**CPs:** \"+str(XPList[5][2])\n embed = discord.Embed(title=\"Season 1 results!\",\n description=\"Ranks 1-5\",\n colour=0xFFd700)\n embed.set_author(icon_url=self.bot.user.avatar_url_as(format='png'),\n name=self.bot.user.name)\n embed.add_field(name='#1',\n value=value1)\n embed.add_field(name='#2',\n value=value2)\n embed.add_field(name='#3',\n value=value3)\n embed.add_field(name='#4',\n value=value4)\n embed.add_field(name='#5',\n value=value5)\n embed.set_footer(text=ctx.guild.name,\n icon_url=ctx.guild.icon_url_as(format='png'))\n\n await ctx.send(content='**Displaying top CP**', embed=embed)\n \n\n \n# The setup fucntion below is neccesarry. Remember we give bot.add_cog() the name of the class in this case MembersCog.\n# When we load the cog, we use the name of the file.\ndef setup(bot):\n bot.add_cog(CPCog(bot))\n random.seed()\n","sub_path":"cogs/CP.py","file_name":"CP.py","file_ext":"py","file_size_in_byte":6849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"587707197","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport pywikibot, re, sys, argparse\n\nimport blib\nfrom blib import getparam, rmparam, msg, errandmsg, site, tname, pname\n\nimport lalib\n\ndef process_form(page, index, slot, form, pos, pagemsg):\n orig_pagemsg = pagemsg\n def pagemsg(txt):\n orig_pagemsg(\"%s %s %s: %s\" % (index, slot, form, txt))\n\n notes = []\n\n pagemsg(\"Processing\")\n\n if not page.exists():\n pagemsg(\"Skipping form value %s, page doesn't exist\" % form)\n return None, None\n\n text = str(page.text)\n\n retval = lalib.find_latin_section(text, pagemsg)\n if retval is None:\n return None, None\n\n sections, j, secbody, sectail, has_non_latin = retval\n\n if pos == \"pn\":\n from_header = \"==Noun==\"\n to_header = \"==Proper noun==\"\n from_headword_template = \"la-noun-form\"\n to_headword_template = \"la-proper noun-form\"\n from_pos = \"noun form\"\n to_pos = \"proper noun form\"\n from_lemma_pos = \"noun\"\n to_lemma_pos = \"proper noun\"\n elif pos == \"part\":\n from_header = \"==Adjective==\"\n to_header = \"==Participle==\"\n from_headword_template = \"la-adj-form\"\n to_headword_template = \"la-part-form\"\n from_pos = \"adjective form\"\n to_pos = \"participle form\"\n from_lemma_pos = \"adjective\"\n to_lemma_pos = \"participle\"\n else:\n raise ValueError(\"Unrecognized POS %s\" % pos)\n\n subsections = re.split(\"(^==+[^=\\n]+==+\\n)\", secbody, 0, re.M)\n for k in range(2, len(subsections), 2):\n if (re.search(r\"\\{\\{%s([|}])\" % from_headword_template, subsections[k]) or\n re.search(r\"\\{\\{head\\|la\\|%s([|}])\" % from_pos, subsections[k])):\n newsubsec = subsections[k]\n newsubsec = re.sub(r\"\\{\\{%s([|}])\" % from_headword_template, r\"{{%s\\1\" % to_headword_template, newsubsec)\n newsubsec = re.sub(r\"\\{\\{head\\|la\\|%s([|}])\" % from_pos, r\"{{head|la|%s\\1\" % to_pos, newsubsec)\n newheadersubsec = subsections[k - 1]\n newheadersubsec = newheadersubsec.replace(from_header, to_header)\n if newsubsec != subsections[k] or newheadersubsec != subsections[k - 1]:\n notes.append(\"non-lemma %s -> %s in header and headword\" % (\n from_lemma_pos, to_lemma_pos))\n subsections[k] = newsubsec\n subsections[k - 1] = newheadersubsec\n\n secbody = \"\".join(subsections)\n sections[j] = secbody + sectail\n text = \"\".join(sections)\n return text, notes\n\ndef process_page(page, index):\n global args\n pagetitle = str(page.title())\n def pagemsg(txt):\n msg(\"Page %s %s: %s\" % (index, pagetitle, txt))\n def errandpagemsg(txt):\n errandmsg(\"Page %s %s: %s\" % (index, pagetitle, txt))\n def expand_text(tempcall):\n return blib.expand_text(tempcall, pagetitle, pagemsg, args.verbose)\n\n text = str(page.text)\n\n retval = lalib.find_heads_and_defns(text, pagemsg)\n if retval is None:\n return None, None\n\n (\n sections, j, secbody, sectail, has_non_latin, subsections,\n parsed_subsections, headwords, pronun_sections, etym_sections\n ) = retval\n\n part_headwords = []\n adj_headwords = []\n pn_headwords = []\n noun_headwords = []\n\n for headword in headwords:\n ht = headword['head_template']\n tn = tname(ht)\n if tn == \"la-part\" or tn == \"head\" and getparam(ht, \"1\") == \"la\" and getparam(ht, \"2\") in [\"participle\", \"participles\"]:\n part_headwords.append(headword)\n elif tn == \"la-adj\" or tn == \"head\" and getparam(ht, \"1\") == \"la\" and getparam(ht, \"2\") in [\"adjective\", \"adjectives\"]:\n adj_headwords.append(headword)\n elif tn == \"la-proper noun\" or tn == \"head\" and getparam(ht, \"1\") == \"la\" and getparam(ht, \"2\") in [\"proper noun\", \"proper nouns\"]:\n pn_headwords.append(headword)\n elif tn == \"la-noun\" or tn == \"head\" and getparam(ht, \"1\") == \"la\" and getparam(ht, \"2\") in [\"noun\", \"nouns\"]:\n noun_headwords.append(headword)\n headwords_to_do = None\n if part_headwords and not adj_headwords:\n pos = \"part\"\n headwords_to_do = part_headwords\n expected_inflt = \"la-adecl\"\n elif pn_headwords and not noun_headwords:\n pos = \"pn\"\n headwords_to_do = pn_headwords\n expected_inflt = \"la-ndecl\"\n\n if not headwords_to_do:\n return None, None\n\n for headword in headwords_to_do:\n for inflt in headword['infl_templates']:\n infltn = tname(inflt)\n if infltn != expected_inflt:\n pagemsg(\"WARNING: Saw bad declension template for %s, expected {{%s}}: %s\" % (\n pos, expected_inflt, str(inflt)))\n continue\n inflargs = lalib.generate_infl_forms(pos, str(inflt), errandpagemsg, expand_text)\n forms_seen = set()\n slots_and_forms_to_process = []\n for slot, formarg in inflargs.items():\n forms = formarg.split(\",\")\n for form in forms:\n if \"[\" in form or \"|\" in form:\n continue\n form_no_macrons = lalib.remove_macrons(form)\n if form_no_macrons == pagetitle:\n continue\n if form_no_macrons in forms_seen:\n continue\n forms_seen.add(form_no_macrons)\n slots_and_forms_to_process.append((slot, form))\n for formindex, (slot, form) in blib.iter_items(sorted(slots_and_forms_to_process,\n key=lambda x: lalib.remove_macrons(x[1]))):\n def handler(page, formindex, parsed):\n return process_form(page, formindex, slot, form, pos, pagemsg)\n blib.do_edit(pywikibot.Page(site, lalib.remove_macrons(form)),\n \"%s.%s\" % (index, formindex),\n handler, save=args.save, verbose=args.verbose, diff=args.diff)\n\nparser = blib.create_argparser(\"Correct headers/headwords of non-lemma forms with the wrong part of speech\",\n include_pagefile=True)\nargs = parser.parse_args()\nstart, end = blib.parse_start_end(args.start, args.end)\n\nblib.do_pagefile_cats_refs(args, start, end, process_page,\n default_cats=[\"Latin participles\", \"Latin proper nouns\"])\n","sub_path":"correct_latin_wrong_pos_form.py","file_name":"correct_latin_wrong_pos_form.py","file_ext":"py","file_size_in_byte":5769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"212551338","text":"from data.init_database import get_connection\nimport config\n\n\nclass PictureQuota:\n def __init__(self, qq_id=0):\n self.qq_id = qq_id\n self.c = get_connection()\n\n def get_one_picture(self) -> bool:\n cursor = self.c.cursor()\n existing_data_record = cursor.execute('SELECT * '\n 'FROM picture_quota'\n ' WHERE qq_id=%s', (self.qq_id,))\n existing_data: (str, int) = cursor.fetchone()\n print(existing_data_record)\n if existing_data_record == 0:\n cursor.execute('INSERT INTO picture_quota (qq_id, count) '\n 'VALUES (%s, %s)', (self.qq_id, 1))\n else:\n original_count = existing_data[1]\n if original_count >= config.PICTURE_QUOTA:\n return False\n original_count += 1\n cursor.execute('UPDATE picture_quota SET count=%s WHERE qq_id=%s'\n , (original_count, self.qq_id))\n\n self.c.commit()\n return True\n\n def clear_quota(self):\n # noinspection SqlWithoutWhere\n self.c.cursor().execute('DELETE FROM picture_quota')\n self.c.commit()\n","sub_path":"data/picture_quota.py","file_name":"picture_quota.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"630548886","text":"from pathlib2 import Path\nROOT = Path(__file__).absolute().parent\n\n# 字符常��:\nEPOCH_ = 'epoch'\nSCENE_ = 'scene'\nTURN_ = 'turn'\n\n# area name:\nMENU_ = 'menu'\nSTART_MISSION_ = 'StartMission'\nAP_RECOVER_ = 'AP_recover'\nATK_ = 'atk'\nFUFU_ = 'fufu'\nNORMAL_SCENE_ = 'normal-scene'\nFINAL_SCENE_ = 'final-scene'\nBATTLE_FINISH_ = 'BattleFinish'\nTOTAL_EPOCH_ = 'total_epoch'\nON_CD_SKILLS_ = 'onCD-skills'\n\n# monitor status name:\nNEXT_TURN_ = 'next-turn'\nWAIT_MENU_ = 'wait-menu'\nBATTLE_OVER_ = 'battle-over'\nNEXT_SCENE_ = 'next-scene'\n\n# config字段\nSUPPORT_ = 'support'\nTURNS_ = 'turns'\nSKILLS_ = 'skills'\nORDER_ = 'order'\nULTS_ = 'ultimate'\nMASTER_SKILLS_ = 'master-skills'\nPREFER_CARD_ = 'prefer-card'\nSKILL_TARGETS_ = 'skill-targets'\nSKILL_ID_ = 'skill-id'\nTARGET_ID_ = 'target_id'\n\nKEEP_ = 'keep'\nCLEAR_AP_ = 'clear-ap'\nOCR_ = 'ocr'\nNO_FOCUS_ = 'no-focus'\nSHUTDOWN_ = 'shutdown'\nNEXT_BATTLE_ = 'next-battle'\nFULLSCREEN_ = 'full-screen'\nMODE_ = 'mode'\n","sub_path":"constant.py","file_name":"constant.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"333309470","text":"#! python 3\n# Script para adicionar bullet points\n\nimport pyperclip\n\n# Copiando o conteúdo o do Clpboard\ntext = pyperclip.paste()\nline = text.split('\\n')\n\n# Modificando a lista\nfor n in range(len(line)):\n line[n] = '* ' + line[n]\n\ntext = '\\n'.join(line)\n\n# Colando a lista modificada para o clipboard\npyperclip.copy(text)\n \n \n\n\n\n","sub_path":"Automate the Boring Stuff with Python/06.01 bulletPointAdder.py","file_name":"06.01 bulletPointAdder.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"358494609","text":"from torch.utils.data.dataloader import DataLoader\nfrom torchvision.datasets import ImageFolder\nfrom torchvision import transforms\n\n\ndef create_datasource(base_folder,training=True):\n if training:\n transformations = transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n else:\n transformations = transforms.Compose([\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n\n datasource = ImageFolder(base_folder, transformations)\n dataloader = DataLoader(datasource, batch_size=16,shuffle=True)\n\n return datasource, dataloader\n","sub_path":"picnic_ai_challenge/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"218995984","text":"# 정수형\na = 1\n\n# 소수점\na = 1.4\na = 7.25E10 # 7.25 * 10^10\na = 4.95e-10 # 4.95 * 10^-10\n\n# 2진법, 8진법, 16진법\n# 2진법은 0b로시작한다.\n# 8진법은 0o, 0O로 시작한다. (숫자0 다음에 영어 o)\n# 16진법은 0x, 0X로 시작한다.\na = 0b110 # 6\na = 0o06 # 6\na = 0xa # 10\n\n# 2진법, 8진법, 16진법으로 변환하는 방법.\n# 숫자에서 문자열로 변환해준다.\na = bin(6) # '0b110'\na = oct(10) # '0o12'\na = hex(10) # '0xa'\n\n# 2진법, 8진법, 16진법 문자열을 숫자로 변환하는법\n# 문자열을 넣고, 다음 파라메터에 몇진수인지 적는다.\na = int('0b110',2) # 6\na = int('0o6',8) # 6\na = int('0xa',16) # 10\n\n# 사칙연산\n# c언어와 비슷하지만, 다른점은 /를 할때 정수로 나눠지지 않는다.\na = 5\nb = 2\na + b # 7\na - b # 3\na * b # 10\na / b # 2.5\n\n# 거듭제곱 하는방법\na ** b # 25 (5 ^ 2)\n\n# 나머지 구하기\na % b # 1\n\n# 몫 구하기\na // b # 2\n\n# 허수\n# 실제적으로 사용할 일은 거의 없지만, 실수부는 real, 허수부는 imag, 켤레 복소수는 conjugate()로 알수 있다.\na = 2 + 3j # 2 + 3i\na.real # 2.0\na.imag # 3.0\na.conjugate() # 2 - 3i\n\n# 수학에 필요한 기본함수\n# 내장되어 있는 함수이다.\nround() # 반올림\nabs() # 절대값\n\n# c언어로 치면 math.h에 해당되는 모듈\n# 선언법은 import 묘듈\nimport math\n# 사용법은 math.함수이름이다.\nmath.pi # 3.141592.....\nmath.e # 2.7182818...., 자연상수\nmath.trunc() # 내림\nmath.factorial(n) # 펙토리얼\nmath.degress() # rad -> degress\nmath.radians() # degress -> rad\n# cos(),sin(),tan(),acos(),asin(),atan() # 삼각함수\nmath.pow(a,b) # a ^ b 거듭제곱\nmath.sqrt(a) # root a 루트\nmath.log(a,b) # log b a // default = e 로그\nmath.log10(a) # log10 a 로그\n","sub_path":"1주차/1. integer.py","file_name":"1. integer.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"385806721","text":"import os\nimport os.path\nimport logging\nimport json\nimport dirsync\n\n# from util import FileTool\n\nfrom gii.core import *\nfrom gii.moai.MOAIRuntime \\\n\timport \\\n\tMOAIRuntime, MOAILuaDelegate, LuaTableProxy, _G, _LuaTable, _LuaObject\n\n\nsignals.register ( 'mock.init' )\n##----------------------------------------------------------------##\n_MOCK = LuaTableProxy( None )\n_MOCK_EDIT = LuaTableProxy( None )\n\n_MOCK_GAME_CONFIG_NAME = 'game_config.json'\n\ndef isMockInstance( obj, name ):\n\tif isinstance( obj, _LuaObject ):\n\t\treturn _MOCK.isInstance( obj, name )\n\telse:\n\t\treturn False\n\ndef getMockClassName( obj ):\n\tif isinstance( obj, _LuaTable ):\n\t\tclas = obj.__class\n\t\tif clas: return clas.__name\n\treturn None\n\ndef loadMockAsset( path ):\n\tresult = _MOCK.loadAsset( path )\n\tif not result: return None\n\treturn result[ 0 ]\n\ndef getGameModule( name ):\n\treturn _G.getGameModule( name )\n\ndef findMockClass( name ):\n\treturn _G.findClass( name )\n\t\n##----------------------------------------------------------------##\nclass MockRuntime( EditorModule ):\n\t\n\tdef getDependency(self):\n\t\treturn [ 'moai', 'game_preview', 'script_library' ]\n\n\tdef getName(self):\n\t\treturn 'mock'\n\n\tdef onLoad(self):\n\t\tself.affirmConfigFile()\n\t\tself.runtime = self.getManager().affirmModule( 'moai' )\n\n\t\tself.setupLuaModule()\t\t\n\n\t\tsignals.connect( 'project.load', self.onProjectLoaded )\n\t\tsignals.connect( 'moai.reset', self.onMoaiReset )\n\t\tsignals.connect( 'moai.ready', self.onMoaiReady )\n\n\t\tsignals.connect( 'app.asset_scanned', self.postAssetScan )\n\t\tsignals.connect( 'project.post_deploy', self.postDeploy )\n\t\tsignals.connect( 'project.presave', self.preProjectSave )\n\n\t\tself.initMock()\n\n\t\tself.syncBuiltinAsset()\n\n\tdef affirmConfigFile( self ):\n\t\tproj = self.getProject()\n\t\tself.configPath = proj.getConfigPath( _MOCK_GAME_CONFIG_NAME )\n\t\tasetIndexPath = proj.getRelativePath( self.getAssetLibrary().assetIndexOutputPath )\n\n\t\tif os.path.exists( self.configPath ):\n\t\t\tdata = JSONHelper.loadJSON( self.configPath )\n\t\t\t#fix invalid field\n\t\t\tif data.get( 'asset_library', None ) != asetIndexPath: #fix assetlibrary path\n\t\t\t\tdata['asset_library'] = asetIndexPath\n\t\t\t\tJSONHelper.trySaveJSON( data, self.configPath)\n\t\t\treturn\n\t\t#create default config\n\t\tdefaultConfigData = {\n\t\t\t\"asset_library\": asetIndexPath ,\n\t\t\t\"texture_library\": \"env/config/texture_library.json\",\n\t\t\t\"layers\" : [\n\t\t\t\t{ \"name\" : \"default\",\n\t\t\t\t\t\"sort\" : \"priority_ascending\",\n\t\t\t\t\t\"clear\": False\n\t\t\t\t },\n\t\t\t]\n\t\t}\n\t\tJSONHelper.trySaveJSON( defaultConfigData, self.configPath )\n\n\n\tdef postAssetScan( self ):\n\t\tself.postInitMock()\n\t\t# self.getModule( 'game_preview' ).updateView()\n\n\tdef postDeploy( self, context ):\n\t\tconfigDeployPath = context.requestFile( 'game_config', package = 'config' )\n\t\tcontext.setMeta( 'game_config', configDeployPath )\n\t\tgame = _MOCK.game\n\t\tdata = json.loads( game.saveConfigToString( game ) )\n\t\tdata[ 'asset_library' ] = context.getMeta( 'mock_asset_library', False )\n\t\tdata[ 'texture_library' ] = context.getMeta( 'mock_texture_library', False )\n\t\tdata[ 'script_library' ] = context.getMeta( 'mock_script_library', False )\n\t\tJSONHelper.trySaveJSON( data, context.getAbsPath( configDeployPath ), 'deploy game info' )\n\n\tdef setupLuaModule( self ):\n\t\tfrom gii.qt.controls.GLWidget import GLWidget\n\t\t# GLWidget.getSharedWidget().makeCurrent()\n\t\tGLWidget.makeMainContextCurrent()\n\t\t\n\t\tproject = self.getProject()\n\t\tself.runtime.requireModule( 'mock_edit' )\n\t\t_MOCK._setTarget( _G['mock'] )\n\t\t_MOCK_EDIT._setTarget( _G['mock_edit'] )\n\t\t_MOCK.setDeveloperMode()\n\t\t_MOCK.setupEnvironment( \n\t\t\tproject.getPath(),\n\t\t\tproject.getGameConfigPath()\n\t\t)\n\n\tdef syncAssetLibrary(self): #TODO:\n\t\tpass\n\n\tdef syncBuiltinAsset( self ):\n\t\tproject = self.getProject()\n\t\tassetRootPath = project.getAssetPath( '__mock' )\n\t\tsrcPath = project.getScriptLibPath( 'mock/builtin_asset' )\n\t\tif os.path.exists( srcPath ):\n\t\t\tdirsync.sync( str(srcPath), str(assetRootPath), 'sync', purge = True, verbose = True, create = True )\n\n\tdef initMock( self ):\n\t\tlogging.info( 'init mock runtime' )\n\t\ttry:\n\t\t\t_MOCK.init( self.configPath, True )\n\t\texcept Exception as e:\n\t\t\traise e\n\n\tdef postInitMock( self ):\n\t\tlogging.info( 'init mock common data' )\n\t\ttry:\n\t\t\tgame = _MOCK.game\n\t\t\tgame.initCommonDataFromEditor( game )\n\t\t\tw, h = game.getTargetDeviceResolution( game )\n\t\t\tpreview = self.getModule( 'game_preview' )\n\t\t\tif preview:\n\t\t\t\tpreview.setTargetScreenSize( w, h )\n\t\t\tsignals.emit( 'mock.init' )\n\t\t\tproj = self.getProject()\n\t\t\t_MOCK.addEntityIconFolder( app.getPath( 'data/gizmo' ) )\n\t\t\t_MOCK.addEntityIconFolder( app.getUserPath( 'data/gizmo' ) )\n\t\t\t_MOCK.addEntityIconFolder( proj.getEnvDataPath( 'gizmo' ) )\n\t\texcept Exception as e:\n\t\t\traise e\n\n\n\tdef onProjectLoaded(self,prj):\n\t\tself.syncAssetLibrary()\n\n\tdef preProjectSave( self, prj ):\n\t\tgame = _MOCK.game\n\t\tgame.saveConfigToFile( game, self.configPath )\n\n\tdef onMoaiReset(self):\t\t\n\t\tself.setupLuaModule()\n\n\tdef onMoaiReady( self ):\n\t\tself.initMock()\n\n\tdef getMockEnv( self ):\n\t\treturn _MOCK\n\n\tdef getMockEditEnv( self ):\n\t\treturn _MOCK_EDIT\n\n\tdef getLuaEnv( self ):\n\t\treturn _G\n\n\tdef getComponentTypeList( self ):\n\t\tpass\n\n\tdef getEntityTypeList( self ):\n\t\tpass\n\n\n##----------------------------------------------------------------##\t\nMockRuntime().register()\n\n","sub_path":"lib/mock/MockRuntime.py","file_name":"MockRuntime.py","file_ext":"py","file_size_in_byte":5257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"320354763","text":"#\n# Definition for binary tree:\n# class Tree(object):\n# def __init__(self, x):\n# self.value = x\n# self.left = None\n# self.right = None\n\n'''\nSolution is O(t1 * t2) as we may need to check the same nodes in t1 as many\ntimes as there are nodes in t2\n'''\ndef isSubtree(t1, t2):\n # if t2 is None, we've traversed that subtree fully, so can return True\n if t2 is None:\n return True\n # however if t2 is not None and t1 is, we've reached a bad traversal, as there's\n # still more to t2. t1's current traversal can't be a subtree, so return False.\n if t1 is None:\n return False\n\n # if we have both t1 and t2, we can check for their equivalence, or\n # try to find a subtree from another starting point in t1.\n return is_equal(t1, t2) or isSubtree(t1.left, t2) or isSubtree(t1.right, t2)\n \ndef is_equal(t1, t2):\n if not t1 and not t2:\n return True\n elif not t1 or not t2:\n return False\n elif t1.value != t2.value:\n return False\n \n # Getting through our base cases above, we know we have a node that's equal, so\n # we can traverse both subtrees and keep looking for equality until we hit\n # leaf nodes on both sides or we hit values that aren't equal\n return is_equal(t1.left, t2.left) and is_equal(t1.right, t2.right)","sub_path":"isSubtree/isSubtree.py","file_name":"isSubtree.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"283603977","text":"\nfrom datetime import date, datetime\nfrom approx_dates.models import ApproxDate\nimport calendar\nimport six\nimport json\nfrom copy import deepcopy\n\ndef approx_date_to_iso(approx_date):\n #duplicated here until approx_date package updated\n \n if approx_date.earliest_date == approx_date.latest_date:\n return approx_date.earliest_date.isoformat()\n else:\n #is it a vague month?\n ed = approx_date.earliest_date\n ld = approx_date.latest_date\n if ed.month == ld.month and ed.year == ld.year:\n days_in_month = calendar.monthrange(ed.year, ed.month)[1]\n if ed.day == 1 and ld.day == days_in_month:\n return ed.strftime(\"%Y-%m\")\n #is it a vague year\n if ed.year == ld.year:\n if ed.month == 1 and ed.day == 1:\n if ld.month == 12 and ld.day == 31:\n return \"{0}\".format(ed.year)\n\n return \"{0} to {1}\".format(ed.isoformat(),ld.isoformat())\n\ndef approx_date_getter(iso8601_date_string):\n #duplicated here until approx_date package updated\n if \" to \" in iso8601_date_string: #extract double date\n start,end = iso8601_date_string.split(\" to \")\n start_date = ApproxDate.from_iso8601(start)\n end_date = ApproxDate.from_iso8601(end)\n combined = ApproxDate(start_date.earliest_date,\n end_date.latest_date,\n iso8601_date_string)\n return combined\n else:\n return ApproxDate.from_iso8601(iso8601_date_string) \n\n\ndef first(l):\n '''Return the first item of a list, or None if it's empty'''\n return l[0] if l else None\n\nclass Attribute(object):\n '''\n Exposes raw json values for getting and setting.\n \n Works in conjecture with PopoloObject\n \n so:\n \n id = Attribute()\n \n will give a PopoloObject with an id attribute that gets and\n sets the 'id' attr of self.data.\n \n id = Attribute(default=\"16\")\n \n Sets a default extraction value of 16.\n \n id = Attribute(null=True)\n \n will return None rather than an error if the value is absent.\n \n '''\n def __init__(self,attr=\"\",default=None,null=False,allow_multiple=False):\n self.attr = attr\n self._default_value = default\n self.allow_null_default = null\n self.allow_multiple = allow_multiple\n\n @property\n def default_value(self):\n \"\"\"\n safe guard against default being shared between instances\n \"\"\"\n return deepcopy(self._default_value)\n \n def __get__(self, obj, type=None):\n if self.allow_null_default == False and self.default_value == None:\n return obj.data.get(self.attr)\n else:\n try:\n result = obj.data[self.attr]\n except KeyError:\n result = self.default_value\n obj.data[self.attr] = result\n return result\n\n def __set__(self,obj,value):\n if six.PY2 and isinstance(value,str):\n nv = unicode(value)\n else:\n nv = value\n \n obj.data[self.attr] = nv\n\nclass RelatedAttribute(Attribute):\n \"\"\"\n returns 'related' objects - e.g. if person_id = 5, returns Person 5\n \"\"\"\n def __init__(self,attr=\"\",default=None,null=False,\n id_attr=None,collection=None):\n self.attr = attr\n self._default_value = default\n self.allow_null_default = null\n self._collection = collection\n \n @property\n def id_attr(self):\n return self.attr + \"_id\"\n \n @property \n def collection(self):\n if self._collection:\n return self._collection\n else:\n return self.attr + \"s\" \n \n def __get__(self, obj, type=None):\n collection = getattr(obj.all_popolo,self.collection)\n return collection.lookup_from_key[getattr(obj,self.id_attr)]\n \n def __set__(self,obj,value):\n setattr(obj,self.id_attr,value.id)\n\nclass DateAttribute(Attribute):\n \"\"\"\n Interacts with ApproxDates - sets iso, retrieves ApproxDate\n \"\"\"\n def __get__(self, obj, type=None):\n return obj.get_date(self.attr,self.default_value)\n \n def __set__(self,obj,value):\n if isinstance(value,ApproxDate):\n obj.data[self.attr] = approx_date_to_iso(value)\n elif isinstance(value,datetime):\n obj.data[self.attr] = value.date().isoformat()\n elif isinstance(value,date):\n obj.data[self.attr] = value.isoformat()\n else:\n obj.data[self.attr] = value\n\n\nclass IdentiferAttribute(Attribute):\n \"\"\"\n For getting and setting values deeper in linked data.\n \"\"\"\n getter = \"identifier_values\"\n \n def __get__(self, obj, type=None):\n getter = getattr(obj,self.__class__.getter)\n v = getter(self.attr)\n if v:\n if self.allow_multiple:\n return v\n else:\n return first(v)\n else:\n return self.default_value\n \n def __set__(self,obj,value):\n setter = getattr(obj,\"set_\" + self.__class__.getter)\n setter(self.attr,value)\n \nclass LinkAttribute(IdentiferAttribute):\n getter = \"link_values\"\n \nclass ContactAttribute(IdentiferAttribute):\n getter = \"contact_detail_values\"\n\nclass PopoloMeta(type):\n \n def __new__(cls, name, parents, dct):\n \n \"\"\"\n If attr value not specified for an attribute, gives it the name assigned.\n \n This specifies the key of the popolo dict the property refers to.\n \n so \n \n name = Attribute()\n \n is equivalent to:\n \n name = Attribute(attr=\"name\")\n \"\"\"\n \n for k,v in six.iteritems(dct):\n if isinstance(v,Attribute) :\n if v.attr == \"\":\n v.attr = k \n\n cls = super(PopoloMeta, cls).__new__(cls, name, parents, dct)\n return cls\n \n\nclass PopoloObject(six.with_metaclass(PopoloMeta,object)):\n\n class DoesNotExist(Exception):\n pass\n\n class MultipleObjectsReturned(Exception):\n pass\n\n def __init__(self, data=None, all_popolo=None,**kwargs):\n if data == None:\n data = {}\n data.update(kwargs)\n self.data = data\n self.all_popolo = all_popolo\n\n @property\n def json(self):\n return json.dumps(self.data)\n\n def get_date(self, attr, default):\n d = self.data.get(attr)\n if d:\n return approx_date_getter(d)\n return default\n\n def get_related_object_list(self, popolo_array):\n return self.data.get(popolo_array, [])\n\n def get_related_values(\n self, popolo_array, info_type_key, info_type, info_value_key):\n '''Get a value from one of the Popolo related objects\n\n For example, if you have a person with related links, like\n this:\n\n {\n \"name\": \"Dale Cooper\",\n \"links\": [\n {\n \"note\": \"wikipedia\",\n \"url\": \"https://en.wikipedia.org/wiki/Dale_Cooper\"\n }\n ]\n }\n\n When calling this method to get the Wikipedia URL, you would use:\n\n popolo_array='links'\n info_type_key='note'\n info_type='wikipedia'\n info_value_key='url'\n\n ... so the following would work:\n\n self.get_related_value('links', 'note', 'wikipedia', 'url')\n # => 'https://en.wikipedia.org/wiki/Dale_Cooper'\n '''\n return [\n o[info_value_key]\n for o in self.get_related_object_list(popolo_array)\n if o[info_type_key] == info_type\n ]\n\n def del_related_values(self,popolo_array, info_type_key, info_type):\n obj_list = self.get_related_object_list(popolo_array)\n if obj_list:\n for x,o in enumerate(obj_list):\n if o[info_type_key] == info_type:\n break\n \n if obj_list[x][info_type_key] == info_type:\n del obj_list[x]\n \n\n def set_related_values(self, popolo_array\n , info_type_key, info_type, info_value_key,new_value):\n \"\"\"\n allows related values to be set\n \"\"\"\n \n obj_list = self.get_related_object_list(popolo_array)\n for o in obj_list:\n if o[info_type_key] == info_type:\n o[info_value_key] = new_value\n return\n new = {info_type_key:info_type,\n info_value_key:new_value}\n obj_list.append(new)\n self.data[popolo_array] = obj_list\n\n def identifier_values(self, scheme):\n return self.get_related_values(\n 'identifiers', 'scheme', scheme, 'identifier')\n\n def set_identifier_values(self, scheme,value):\n \"\"\"\n set an identifer value\n \"\"\"\n self.set_related_values(\n 'identifiers', 'scheme', scheme, 'identifier',value)\n\n def identifier_value(self, scheme):\n return first(self.identifier_values(scheme))\n\n def link_values(self, note):\n return self.get_related_values('links', 'note', note, 'url')\n\n def set_link_values(self, note,value):\n \"\"\"\n set a link value\n \"\"\"\n self.set_related_values('links', 'note', note, 'url',value)\n\n def del_link_values(self, note):\n \"\"\"\n set a link value\n \"\"\"\n self.del_related_values('links', 'note', note)\n\n\n def link_value(self, note):\n return first(self.link_values(note))\n\n def contact_detail_values(self, contact_type):\n return self.get_related_values(\n 'contact_details', 'type', contact_type, 'value')\n\n def del_contact_detail_values(self, contact_type):\n return self.del_related_values(\n 'contact_details', 'type', contact_type)\n \n def set_contact_detail_values(self, contact_type,new_value):\n if not new_value:\n return self.del_contact_detail_values(contact_type)\n else:\n return self.set_related_values(\n 'contact_details', 'type', contact_type, 'value',new_value)\n\n def contact_detail_value(self, contact_type):\n return first(self.contact_detail_values(contact_type))\n\n def absorb(self,other):\n \"\"\"\n other is about to be discarded for it's (hopefully) better\n equiv self.\n \n Override if there's anything you want to salvage from other\n and pass into self. \n \"\"\"\n pass\n\n @property\n def key_for_hash(self):\n return self.id\n\n def __eq__(self, other):\n if isinstance(other, self.__class__):\n return self.id == other.id\n return NotImplemented\n\n def __ne__(self, other):\n if isinstance(other, self.__class__):\n return self.id != other.id\n return NotImplemented\n\n def __lt__(self,other):\n \"\"\"\n is this less \"full\" than the other?\n Based entirely on how much info is in there - len of dict.\n \"\"\"\n if self.__class__ == other.__class__:\n ours = len(self.json)\n theirs = len(other.json)\n return ours < theirs\n else:\n return NotImplemented\n \n def __gt__(self,other):\n \"\"\"\n is this more \"full\" than the other?\n Based entirely on how much info is in there - len of dict.\n \"\"\" \n if self.__class__ == other.__class__:\n ours = len(self.json)\n theirs = len(other.json)\n return ours > theirs\n else:\n return NotImplemented\n\n def __hash__(self):\n return hash(self.key_for_hash)\n\n def repr_helper(self, enclosed_text):\n fmt = str('<{0}: {1}>')\n class_name = type(self).__name__\n if six.PY2:\n return fmt.format(class_name, enclosed_text.encode('utf-8'))\n return fmt.format(class_name, enclosed_text)\n\n def __repr__(self):\n \"\"\"\n generic __repr__ for different models - will repr with\n whichever value is present in object.\n \"\"\"\n preferred_order = [\"name\",\"label\",\"id\"]\n for o in preferred_order:\n if hasattr(self,o):\n return self.repr_helper(getattr(self,o))\n\n\nclass CurrentMixin(object):\n\n def current_at(self, when):\n return ApproxDate.possibly_between(\n self.start_date, when, self.end_date)\n\n @property\n def current(self):\n return self.current_at(date.today())\n\n","sub_path":"popolo_data/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":12652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"28089885","text":"#!/usr/bin/env python3\n\n\"\"\"Gaussian elimination algorithm implementation.\"\"\"\n\n\nimport time\nfrom utils import error_exit\n\n\n# this is taken from\n# https://martin-thoma.com/solving-linear-equations-with-gaussian-elimination/\n#\ndef gauss(AugMat):\n \"\"\"\n This function solves the equation AX=Y matrix equation.\n Input is a (n+1)*n 2D list in the form of an augmented matrix.\n The last column is the right side of the matrix equation (the Y).\n Entries are instances of Fraction.\n\n The result is X, a vector (list) with n entries of Fraction.\n \"\"\"\n n = len(AugMat)\n\n t1 = time.time()\n for i in range(0, n):\n if (time.time() - t1) > 5:\n error_exit('Gaussian elimination is taking a long time! Force-stopping ...')\n maxr = _max_row(AugMat, i)\n _swap_rows(AugMat, i, maxr)\n _zero_below(AugMat, i)\n return _back_solve(AugMat)\n\n\ndef _max_row(Mat, i):\n \"\"\"Search for the maximum row in the i column of matrix Mat.\"\"\"\n n = len(Mat)\n e = abs(Mat[i][i])\n maxr = i\n for k in range(i + 1, n):\n if abs(Mat[k][i]) > e:\n e = abs(Mat[k][i])\n maxr = k\n return maxr\n\n\ndef _swap_rows(Mat, i, j):\n \"\"\"Swap rows i and j in the matrix Mat.\"\"\"\n n = len(Mat)\n for k in range(i, n + 1):\n tmp = Mat[j][k]\n Mat[j][k] = Mat[i][k]\n Mat[i][k] = tmp\n\n\ndef _zero_below(Mat, i):\n \"\"\"Make rows below row i zero in current column of matrix Mat.\"\"\"\n n = len(Mat)\n for k in range(i + 1, n):\n c = -Mat[k][i] / Mat[i][i]\n for j in range(i, n + 1):\n if i == j:\n Mat[k][j] = 0\n else:\n Mat[k][j] += c * Mat[i][j]\n\n\ndef _back_solve(Mat):\n \"\"\"Solve the upper triangular matrix 'Mat' by back-substitution.\"\"\"\n n = len(Mat)\n x = [0 for i in range(n)]\n for i in range(n - 1, -1, -1):\n x[i] = Mat[i][n] / Mat[i][i]\n for k in range(i - 1, -1, -1):\n Mat[k][n] -= Mat[k][i] * x[i]\n return x\n","sub_path":"year3_1920/epitech/mathematics/306radiator/src/elimination.py","file_name":"elimination.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"424035761","text":"#!/usr/bin/env python3\n\n# 列表去重(保持原有顺序)\n\ndef list_dedupe(lst_in):\n from functools import reduce\n func = lambda x,y:x if y in x else x + [y]\n lst_out = reduce(func, [[], ] + lst_in)\n return lst_out\n\n# IP转换为数字\n\ndef ip2digitstr(ip):\n import socket, struct\n packedIP = socket.inet_aton(ip)\n digit = struct.unpack(\"!L\", packedIP)[0]\n return str(digit)\n\n# 数字转换为IP\n\ndef digitstr2ip(digitstr):\n import socket, struct\n digit = int(digitstr)\n packedIP = struct.pack('!L', digit)\n ip = socket.inet_ntoa(packedIP)\n return ip\n\n# 判断是否为IP\n\ndef is_v4_ip(str_ip):\n if '.' not in str_ip:\n return False\n elif str_ip.count('.') != 3:\n return False\n else:\n flag = True\n lst_ip = str_ip.split('.')\n for i in lst_ip:\n try:\n num = int(i)\n if num >=0 and num <= 255:\n pass\n else:\n flag = False\n except:\n flag = False\n return flag\n\n# 判断是否为uuid\n\ndef is_uuid(str_uuid):\n import re\n r = \"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$\"\n match = re.match(r, str_uuid)\n try:\n if match.string == str_uuid:\n return True\n else:\n return False\n except:\n return False\n\n# 添加字符串输出效果\n\ndef printe(string, fcolor, bcolor=\"\", bold=False, \n underscore=False, blink=False, reverse=False):\n # Print enhanced.\n import sys\n fcolor_code_map = {\n \"black\": 30,\n \"red\": 31,\n \"green\": 32,\n \"yellow\": 33,\n \"blue\": 34,\n \"magenta\": 35,\n \"cyan\":36,\n \"white\": 37\n }\n bcolor_code_map = {\n \"black\": 40,\n \"red\": 41,\n \"green\": 42,\n \"yellow\": 43,\n \"blue\": 44,\n \"magenta\": 45,\n \"cyan\":46,\n \"white\": 47\n }\n code_list = []\n # Foreground colors.\n if fcolor in fcolor_code_map:\n fcolor_code = fcolor_code_map[fcolor]\n code_list.append(fcolor_code)\n # Background colors\n if bcolor in bcolor_code_map:\n bcolor_code = bcolor_code_map[bcolor]\n code_list.append(bcolor_code)\n # Text attributes\n if bold:\n code_list.append(1)\n if underscore:\n code_list.append(4)\n if blink:\n code_list.append(5)\n if reverse:\n code_list.append(7)\n code = \"0\"\n for i in code_list:\n code = code + \";\" + str(i)\n enhanced_string = \"\\033[{0}m{1}\\033[0m\".format(code, string)\n sys.stdout.write(enhanced_string)\n # line break\n print()\n\n# 输出数字进度符\n\ndef printpi(percent):\n # Print progress indicator.\n import sys, time\n time.sleep(0.1)\n string = \"\\033[1000D{0}%\\033[0m\".format(percent)\n sys.stdout.write(string)\n sys.stdout.flush()\n if percent == 100:\n print()\n\n# 输出进度条\n\ndef printpb(percent):\n # Print progress bar.\n import sys, time\n time.sleep(0.1)\n width = int(percent / 4)\n bar = \"[\" + \"#\" * width + \" \" * (25 - width) + \"]\"\n string = \"\\033[1000D{0}\\033[0m\".format(bar)\n sys.stdout.write(string)\n sys.stdout.flush()\n if percent == 100:\n print()\n\n# 得到程序文件运行时的目录\n\ndef get_path():\n # Only work in a file.\n import os\n return os.path.dirname(os.path.realpath(__file__))\n\ndef get_path():\n from pathlib import Path\n p = Path(__file__)\n s = p.resolve().parent\n return str(s)\n\n# 文件日志示例\n\nimport logging\nimport os\nfrom logging.handlers import RotatingFileHandler\n\nclass LogHandler(logging.Logger):\n\n _fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n _datefmt = \"%a, %d %b %Y %H:%M:%S\"\n _logpath = \"/var/log/pylog\"\n\n def __init__(self, name=None):\n logging.Logger.__init__(self, name)\n self._prepare()\n self.log_file = \"{0}/py.log\".format(self._logpath)\n formatter = logging.Formatter(self._fmt, self._datefmt)\n rfhandler = RotatingFileHandler(self.log_file, maxBytes=1024*1024, backupCount=5)\n rfhandler.setFormatter(formatter)\n #shandler = logging.StreamHandler()\n #shandler.setFormatter(formatter)\n self.addHandler(rfhandler)\n #self.addHandler(shandler)\n #self.setLevel(logging.INFO)\n\n def _prepare(self):\n if os.path.exists(self._logpath):\n return\n else:\n os.mkdir(self._logpath)\n# 动态定义变量(慎用)\n\n\ndef dynamic_define_vars():\n local_vars = globals()\n VARS = {\"a\": 1, \"b\": 2, \"c\": 3}\n for i in VARS:\n name = \"int_\" + i\n value = VARS[i]\n local_vars[name] = value\n\n\n# 设置执行超时\n\n\nimport signal\nimport time\n\n\ndef set_timeout(num, callback):\n def wrap(func):\n def handle(signum, frame): # 收到信号 SIGALRM 后的回调函数,第一个参数是信号的数字,第二个参数是the interrupted stack frame.\n raise RuntimeError\n\n def to_do(*args, **kwargs):\n try:\n signal.signal(signal.SIGALRM, handle) # 设置信号和回调函数\n signal.alarm(num) # 设置 num 秒的闹钟\n print('start alarm signal.')\n r = func(*args, **kwargs)\n print('close alarm signal.')\n signal.alarm(0) # 关闭闹钟\n return r\n except RuntimeError as e:\n callback()\n\n return to_do\n\n return wrap\n\n\nif __name__ == '__main__':\n def after_timeout(): # 超时后的处理函数\n print(\"do something after timeout.\")\n\n @set_timeout(2, after_timeout) # 限时 2 秒\n def connect(): # 要执行的函数\n time.sleep(1) # 函数执行时间,写大于2的值,可测试超时\n return 'connect success.'\n\n print(connect())\n\n\ndef run_cmd(cmd):\n import subprocess\n p = subprocess.Popen(bash_cmd, shell=True, stdout=subprocess.PIPE)\n output = p.stdout.read()\n return output\n","sub_path":"usefulcode.py","file_name":"usefulcode.py","file_ext":"py","file_size_in_byte":6314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"334960015","text":"#!/usr/bin/env python\nimport numpy as np\nimport matplotlib as mpl\nmpl.use('Agg')\nfrom matplotlib import pyplot as plt\nfrom pyhdf.SD import SD, SDC\nimport os,datetime,sys,fnmatch\nfrom jdcal import gcal2jd\nfrom plot_global_map_no_colorbar import *\nimport math\nfrom netCDF4 import Dataset\n\n##########################\n#### Main Program\n\nwith open('causality_w500_by_ENSO.txt') as f:\n data = [map(float, line.split()) for line in f]\nprint(len(data))\n \nnc_f= 'air.mon.mean.nc'\nnc_fid=Dataset(nc_f,'r')\nlat_bnd = nc_fid.variables['lat'][:] # extract/copy the data\nlon_bnd = nc_fid.variables['lon'][:]\n\nnlon= len(lon_bnd)\nnlat= len(lat_bnd)\ncausality_SLP = np.zeros((nlat,nlon))\n\nnc_f2= 'land.nc'\nnc_fid2=Dataset(nc_f2,'r')\nland = nc_fid2.variables['land'][:]\n\nfor i in np.arange(nlat):\n for j in np.arange(nlon):\n print(i,j)\n causality_SLP[i,j]=data[i][j]*(1-land[0,i,j])\n\ncausality_SLP[causality_SLP!=1]=np.NaN\n\nlon_bnd[nlon-1]=360.01\nprint('plot global map')\nplot_global_map(lat_bnd,lon_bnd,causality_SLP, cmap= plt.get_cmap('rainbow'), \\\n vmin=0.01,vmax=1.0001,title='Granger Causality of, ENSO -> w500', figure_name='w500_caused_by_ENSO')\n","sub_path":"year-1-projects/team-4/Causality/Plot_causality_w500_by_ENSO.py","file_name":"Plot_causality_w500_by_ENSO.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"457586528","text":"sentence = '나는 소년입니다'\nprint(sentence)\n\nsentence2 = \"python is too easy\"\nprint(sentence2)\n\nsentence3 = \"\"\"\ni am a boy,\npython is easy\n\"\"\"\nprint(sentence3)\n\nsentence4 = '''\ni love you adorable_sol\n'''\nprint(sentence4)","sub_path":"string1.py","file_name":"string1.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"412490727","text":"from sklearn.model_selection import KFold\nimport numpy as np\nimport tensorflow as tf\nimport time\nimport matplotlib.pyplot as plt\n\n\ndef train_and_test(session, optimizer, cost, x_train, y_train, x_test, y_test, x, y):\n start_time = time.clock()\n _, training_error = session.run([optimizer, cost], feed_dict={x: x_train, y: y_train})\n test_error = session.run([cost], feed_dict={x: x_test, y: y_test})\n computing_time = time.clock() - start_time\n\n return training_error, test_error, computing_time\n\n\ndef cross_validation(k, session, optimizer, cost, input_data, output_data, x, y, saver):\n training = []\n test = []\n computing_time = []\n kf = KFold(n_splits=k)\n for train_i, test_i in kf.split(input_data, output_data):\n #saver.save(session, \"models/model.ckpt\")\n '''for i in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES):\n print(session.run(i))\n print('************************')\n print('----------------------')'''\n x_train = input_data[train_i]\n x_test = input_data[test_i]\n y_train = output_data[train_i]\n y_test = output_data[test_i]\n training_error, test_error, cp_time = train_and_test(session, optimizer,\n cost, x_train, y_train,\n x_test, y_test, x, y)\n test.append(test_error)\n computing_time.append(cp_time)\n training.append(training_error)\n saver.restore(session, \"models/model.ckpt\")\n\n test_error = np.mean(test)\n desviation_test_error = np.std(test)\n average_time = np.mean(computing_time)\n\n print('**********************************************************')\n print(str(k) + '-fold Cross Validation ')\n print('Average test error in ' + str(k) + ' iterations : ' + str(test_error))\n print('Average standar desviaton in cross validation ' + str(k) + ' iterations : ' + str(desviation_test_error))\n print('Average computing time in cross validation : ' + str(average_time))\n print('**********************************************************')\n\n '''axis_x = np.arange(10)\n plt.figure()\n ax = plt.subplot(211)\n ax.set_title(\"Errors in training and test\")\n ax.plot(axis_x, training, 'bo')\n ax.plot(axis_x, test, 'ro')\n ax.set_xlabel('Iterations')\n ax.set_ylabel('Error')\n ax.legend(('Train', 'Test'))\n ax = plt.subplot(212)\n ax.set_title(\"Compute time per iteration\")\n ax.plot(computing_time, 'g')\n name_img = 'Net_Report/cross_validation' + name + '.png'\n plt.savefig(name_img)\n plt.show()'''\n\n return test_error, desviation_test_error, average_time, training, test, computing_time","sub_path":"cross_validation.py","file_name":"cross_validation.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"166114789","text":"# 오답\n\nT = int(input())\n\nfor i in range(T):\n\n n, m, k = map(int, input().split())\n\n oStr = input()\n oList = list(oStr[:])\n\n for j in range(m):\n x, y = map(int, input().split())\n sList = oList[x-1:y]\n sBinary = \"\".join(sList)\n mask = '1'*(y-x+1)\n\n sBinary = int(mask, 2) - int(sBinary, 2)\n sBinary = \"{0:b}\".format(sBinary)\n # print(sBinary)\n # print(sList[0], mask[2])\n if x!=y and sList[0]=='1':\n sBinary = '0'+sBinary\n # print(type(sBinary), sBinary)\n oList = oList[:y] + list(sBinary) + oList[y:]\n print(\"\".join(oList[:k]))","sub_path":"studyTH/etc/codejam/F-2.main.py","file_name":"F-2.main.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"25255464","text":"from setuptools import setup, find_packages\r\n\r\nwith open('README.md') as f:\r\n readme = f.read()\r\n\r\nsetup(\r\n name='trimbot',\r\n version='0.3',\r\n description='Automated Turbot Account Cleanup',\r\n long_description=readme,\r\n author='Turbot Inc',\r\n py_modules=['main'],\r\n install_requires=[\r\n 'click==8.0.1',\r\n 'jsonschema==3.2.0',\r\n 'PyYAML==5.4.1',\r\n 'boto3==1.18.55',\r\n \"requests==2.26.0\",\r\n \"urllib3==1.26.7\"\r\n ],\r\n packages=['trimbot_modules'],\r\n entry_points='''\r\n [console_scripts]\r\n trimbot=main:cli\r\n ''',\r\n)\r\n","sub_path":"trimbot/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"503354675","text":"password = \"zzxxcc111\"\nMONGO_URI = \"mongodb+srv://kel:\" + password + \"@werf-11lw7.azure.mongodb.net/test?retryWrites=true&w=majority\"\n\n\n# По умолчанию Eve запускает API в режиме \"read-only\" (т.е. поддерживаются только GET запросы),\n# мы включаем поддержку методов POST, PUT, PATCH, DELETE.\nRESOURCE_METHODS = ['GET', 'POST', 'DELETE']\nITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']\n\nX_DOMAINS = '*'\nX_HEADERS = '*'\n\n\nDOMAIN = {\n # Описываем ресурс `/users`\n 'users': {\n 'schema': {\n 'username': {\n 'type': 'string',\n 'minlength': 5,\n 'maxlength': 32,\n 'required': True,\n # уникальное поле (индекс не создаётся, значение должно быть уникальным)\n 'unique': True,\n },\n\t\t\t'email': {\n 'type': 'string',\n 'minlength': 5,\n 'maxlength': 32,\n 'required': True,\n # уникальное поле (индекс не создаётся, значение должно быть уникальным)\n 'unique': True,\n },\n 'firstname': {\n 'type': 'string',\n 'minlength': 1,\n 'maxlength': 10,\n 'required': True,\n },\n 'lastname': {\n 'type': 'string',\n 'minlength': 1,\n 'maxlength': 15,\n 'required': True,\n },\n 'born': {\n 'type': 'datetime',\n },\n 'active': {\n 'type': 'boolean',\n 'default': True\n },\n\t\t\t'sx': {\n 'type': 'boolean',\n 'default': False\n },\n 'preferences': {\n 'type': 'list', # тип: список\n 'default': [], # по умолчанию: пустой список\n # описываем \"схему\" списка\n 'schema': {\n 'type': 'string',\n 'minlength': 5,\n 'maxlength': 32,\n }\n }\n }\n },\n\n # Описываем ресурс `/events`\n 'events': {\n # Описываем модель данных\n 'schema': {\n 'title': {\n 'type': 'string',\n 'minlength': 5,\n 'maxlength': 32,\n 'required': True,\n 'unique': True\n },\n 'tags': {\n 'type': 'list',\n 'default': [], # по умолчанию: пустой список\n # описываем \"схему\" списка\n 'schema': {\n 'type': 'string',\n 'minlength': 5,\n 'maxlength': 32,\n }\n },\n 'users': {\n 'type': 'list', # тип: список\n 'default': [], # по умолчанию: пустой список\n # описываем \"схему\" списка\n 'schema': {\n 'type': 'objectid', # тип данных: objectid\n # ссылаемся на запись в другой коллекции\n 'data_relation': {\n 'resource': 'users', # на ресурс `users` (который мы описали выше)\n 'field': '_id', # на поле `_id`\n 'embeddable': True #разрешено встраивание модели\n }\n }\n }\n }\n }\n}","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"114318219","text":"class Node:\n\tdef __init__(self, data = None):\n\t\tself.data = data\n\t\tself.next = None\n\n\nclass LinkeList:\n\tdef __init__(self):\n\t\tself.head = None\n\n\tdef push(self,newdata):\n\t\tNewNode = Node(newdata)\n\t\tif self.head is None:\n\t\t\tself.head = NewNode\n\t\t\tself.head.next = None\n\t\t\treturn \n\n\t\telse:\n\t\t\tlast = self.head \n\t\t\twhile last is not None:\n\t\t\t\tprev = last\n\t\t\t\tlast = last.next\n\t\t\tprev.next = NewNode\n\t\t\t\n\tdef printlist(self):\n\t\tprintvalue = self.head\n\t\twhile printvalue is not None:\n\t\t\tprint(printvalue.data)\n\t\t\tprintvalue = printvalue.next\n\n\nl = LinkeList()\nl.push(1)\nl.push(2)\nl.push(3)\nl.printlist()\n","sub_path":"advanced_python/linkedlist1.py","file_name":"linkedlist1.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"47312747","text":"# -*- coding: iso-8859-15 -*-\n\nimport urllib\nimport re\n\nfrom BeautifulSoup import BeautifulSoup as bs\n\nclass DataMeaning:\n\turl = \"http://michaelis.uol.com.br/moderno/portugues/index.php\"\n\tdata = \"?lingua=portugues-portugues&palavra=\"\n\n\tdef getDataMeaning(self, word):\n\t\tcomplete_url = self.url + self.data + urllib.quote(word.encode(\"iso-8859-1\"))\n\t\t\n\t\tsock = urllib.urlopen(complete_url)\n\t\thtml = sock.read()\n\t\tsock.close()\n\t\t\n\t\thtml = html[22000:]\n\t\tparse = bs(html)\n\t\t\n\t\ttitle = str(parse.find(\"span\", {\"class\":\"palavraComPontos\"}))\n\t\tdescription = str(parse.find(\"span\", {\"class\":\"descricao\"}))\n\t\t\n\t\tif description == \"None\": return None\n\t\t\n\t\tresponse = \"

    \" + title + \"

    \" + description + \"

    \"\n\t\tresponse += '

    Fonte: Dicionário Michaelis

    '\n\t\n\t\treturn response\n\t\t\nclass DataSynonym:\n\turl = \"http://www.dicio.com.br/pesquisa.php\"\n\tdata = \"?q=\"\n\n\tdef getDataSynonym(self, word):\n\t\tcomplete_url = self.url + self.data + urllib.quote(word.encode(\"iso-8859-1\"))\n\t\t\n\t\tsock = urllib.urlopen(complete_url)\n\t\thtml = sock.read()\n\t\tsock.close()\n\t\t\n\t\tparse = bs(html)\n\t\t\n\t\tsynonym = parse.find(\"p\", {\"class\":\"adicional sinonimos\"})\n\t\t\n\t\tif not synonym: return None\n\t\t\n\t\tresponse = '
      '\n\t\t\n\t\ta = synonym.a\n\t\n\t\twhile a:\n\t\t\tw = str(a)\n\t\t\tif w != \", \" and w != \" e \":\n\t\t\t\ta['href'] = \"#w:\" + a.contents[0]\n\t\t\t\n\t\t\t\tresponse += \"
    • \" + str(a) + \"
    • \"\n\t\t\t\t\n\t\t\ta = a.nextSibling\n\t\t\t\t\n\t\tresponse += \"
    \"\n\t\tresponse += '

    Fonte: Dicio

    '\n\t\n\t\treturn response\n","sub_path":"dic/data_query.py","file_name":"data_query.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"102600965","text":"#! /usr/bin/env python3\n\"\"\"test from_PyCMDS\"\"\"\n\n\n# --- import --------------------------------------------------------------------------------------\n\n\nimport os\nimport numpy as np\n\nimport WrightTools as wt\nfrom WrightTools import datasets\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\n\n# --- test ----------------------------------------------------------------------------------------\n\n\ndef test_w1_000():\n p = datasets.PyCMDS.w1_000\n data = wt.data.from_PyCMDS(p)\n assert data.shape == (51,)\n assert data.axis_expressions == (\"w1\",)\n assert \"w1_points\" in data.variable_names\n data.close()\n\n\ndef test_w1_wa_000():\n p = datasets.PyCMDS.w1_wa_000\n data = wt.data.from_PyCMDS(p)\n assert data.shape == (25, 256)\n assert data.axis_expressions == (\"w1=wm\", \"wa\")\n assert data.wa_centers.shape == (25, 1)\n assert data.wa_points.shape == (1, 256)\n data.close()\n\n\ndef test_w2_w1_000():\n p = datasets.PyCMDS.w2_w1_000\n data = wt.data.from_PyCMDS(p)\n assert data.shape == (81, 81)\n assert data.axis_expressions == (\"w2\", \"w1\")\n data.close()\n\n\ndef test_wm_w2_w1_000():\n p = datasets.PyCMDS.wm_w2_w1_000\n data = wt.data.from_PyCMDS(p)\n assert data.shape == (35, 11, 11)\n assert data.axis_expressions == (\"wm\", \"w2\", \"w1\")\n data.close()\n\n\ndef test_wm_w2_w1_001():\n p = datasets.PyCMDS.wm_w2_w1_001\n data = wt.data.from_PyCMDS(p)\n assert data.shape == (29, 11, 11)\n assert data.axis_expressions == (\"wm\", \"w2\", \"w1\")\n data.close()\n\n\ndef test_incomplete():\n p = os.path.join(here, \"test_data\", \"incomplete.data\")\n data = wt.data.from_PyCMDS(p)\n assert data.shape == (9, 9)\n assert data.axis_expressions == (\"d1\", \"d2\")\n assert np.allclose(\n data.d1.points, np.array([-1., -1.125, -1.25, -1.375, -1.5, -1.625, -1.75, -1.875, -2.])\n )\n data.close()\n\n\ndef test_ps_delay():\n p = os.path.join(here, \"test_data\", \"ps_delay.data\")\n data = wt.data.from_PyCMDS(p)\n assert data.shape == (11, 15, 15)\n assert data.axis_expressions == (\"d1\", \"w2\", \"w1\")\n data.close()\n\n\ndef test_tolerance():\n p = os.path.join(here, \"test_data\", \"tolerance.data\")\n data = wt.data.from_PyCMDS(p)\n assert data.d1.shape == (4, 1, 1)\n assert data.shape == (4, 36, 36)\n assert data.axis_expressions == (\"d1\", \"w2\", \"w1=wm\")\n data.close()\n\n\n# --- run -----------------------------------------------------------------------------------------\n\n\nif __name__ == \"__main__\":\n test_w1_000()\n test_w1_wa_000()\n test_w2_w1_000()\n test_wm_w2_w1_000()\n test_wm_w2_w1_001()\n test_incomplete()\n test_ps_delay()\n test_tolerance()\n","sub_path":"tests/data/from_PyCMDS.py","file_name":"from_PyCMDS.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"219557747","text":"from django.db import models, connection, transaction\nfrom django.db.models import Sum\nfrom Indigo7.models import IBT\nfrom TermsCond.models import *\nfrom Indigo7.timezone import EST\nfrom Warehouse.models import Warehouse\nfrom Stockitems.models import Stockitems\nimport operator\nimport datetime\nfrom datetime import timedelta\n\nclass ProposalDetailsManager(models.Manager):\n def detail_exists(self, warehouse, stockitem, company):\n result = self.filter(\n proposal=None, \n stockitem = stockitem, \n warehouse = warehouse,\n company = company)\n if len(result) > 0:\n return True\n return False\n \n def set_proposal(self, stockitem, warehouse, proposal, company):\n self.filter(\n stockitem = stockitem, \n warehouse = warehouse,\n company = company).update(\n proposal = proposal, processed = True )\n \n def purge(self):\n self.delete_old_details('Monitor')\n \n def get_quantity_between_dates(self, stockitem, warehouse, fromdate, todate, company):\n result = self.filter(\n proposal=None, \n stockitem = stockitem, \n warehouse = warehouse, \n company = company,\n deliverydate__range=(fromdate,todate)\n ).aggregate(Sum('quantity'))\n \n if result['quantity__sum'] is None:\n return 0\n return result['quantity__sum']\n \n def get_warehouse_stockitems_from_details(self, warehouse, company):\n fromdate = datetime.date.today() - timedelta(days=100)\n todate = datetime.date.today() + timedelta(days=360) \n warehouse = Warehouse.objects.get(warehouse = warehouse)\n result_list = []\n cursor = connection.cursor()\n \n sSql = \"\"\" SELECT DISTINCT ON (stockitem_id) stockitem_id \n FROM \"Purchase_proposaldetails\" \n where proposal_id is null AND warehouse_id = \"\"\" \\\n + str(warehouse.id) + \"\"\" AND company_id = \"\"\" + str(company.id) + \"\"\" \n ORDER BY stockitem_id \"\"\" \n \n cursor.execute(sSql)\n \n stockitem_list = cursor.fetchall() \n for stockitem_unique in stockitem_list: \n stock_rec = Stockitems.objects.get(id=stockitem_unique[0]) \n detail = ProposalDetails.objects.filter(\n stockitem=stock_rec, warehouse=warehouse, company=company).order_by('deliverydate')[:1][0]\n \n detail.quantity = self.get_quantity_between_dates(\n stock_rec, warehouse, fromdate, todate, company)\n \n result_list.append(detail)\n \n return result_list \n \n def delete_old_details(self, source, company): \n detail_list = ProposalDetails.objects.filter(\n proposal__orderitem=None, source=source, company=company)\n if len(detail_list) > 0:\n try:\n for detail in detail_list:\n detail.delete()\n except:\n transaction.rollback()\n return None \n transaction.commit()\n return len(detail_list)\n \n def create_proposal(self):\n return ProposalDetails()\n \nclass ProposalDetails(IBT): \n source = models.CharField(max_length=100)\n created = models.DateField(blank=False, null=False, default=datetime.datetime.now())\n supplier = models.ForeignKey('Supplier.Suppliers', null=True)\n deliverydate = models.DateField(blank=False, null=False, default=datetime.datetime.now(),db_index=True) \n stockitem = models.ForeignKey('Stockitems.Stockitems', null=True)\n quantity = models.DecimalField(max_digits=10, decimal_places=2, default=0) \n price = models.DecimalField(max_digits=10, decimal_places=2,default=0)\n warehouse = models.ForeignKey('Warehouse.Warehouse', null=True) \n processed = models.BooleanField(default=False)\n proposal = models.ForeignKey('Proposal', null=True) \n \n objects = ProposalDetailsManager()\n \n def __unicode__(self): \n return u'%s %s %s %s' % (self.supplier, self.deliverydate, self.stockitem, self.warehouse)\n \n class Meta:\n ordering = ['supplier', 'deliverydate', 'stockitem', 'warehouse'] \n app_label = 'Purchase' ","sub_path":"Purchase/models/proposaldetails.py","file_name":"proposaldetails.py","file_ext":"py","file_size_in_byte":4417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"605120286","text":"import pyodbc\r\nimport json\r\nimport requests\r\n\r\nconn_str = (\r\n \"DRIVER={PostgreSQL ODBC Driver(ANSI)};\"\r\n \"DATABASE=postgres;\"\r\n \"UID=postgres;\"\r\n \"PWD=postgres;\"\r\n \"SERVER=localhost;\"\r\n \"PORT=5432;\"\r\n)\r\nconn = pyodbc.connect(conn_str)\r\ncursor = conn.cursor()\r\n\r\ncursor.execute(\r\n \"\"\"SELECT \r\n\r\nid,\r\nst_x(geom),\r\nst_y(geom)\r\n\r\nFROM public.cities\r\nwhere cntry_name in \r\n('Brazil','Australia','Canada','United Kingdom')\"\"\"\r\n)\r\n\r\nprint(cursor)\r\ncolumns = [column[0] for column in cursor.description]\r\n\r\nresults = []\r\nfor row in cursor.fetchall():\r\n results.append(dict(zip(columns, row)))\r\n\r\nfor city in results:\r\n id = city[\"id\"]\r\n st_x = str(city[\"st_x\"])\r\n st_y = str(city[\"st_y\"])\r\n print(id)\r\n print(st_x)\r\n print(st_y)\r\n\r\n # request\r\n url = \"https://places.cit.api.here.com/places/v1/autosuggest\"\r\n params = {\r\n \"app_code\": \"djPZyynKsbTjIUDOBcHZ2g\",\r\n \"app_id\": \"xWVIueSv6JL0aJ5xqTxb\",\r\n \"at\": st_y + \",\" + st_x,\r\n \"q\": \"gas\",\r\n }\r\n\r\n data = requests.get(url, params=params)\r\n datain = data.text\r\n print(data)\r\n\r\n # insert jsondump\r\n insert_sql = \"update public.cities set pois = ? where id = ?\"\r\n cursor = conn.cursor()\r\n cursor.execute(insert_sql, (datain, id))\r\n\r\n # ejecuta\r\n cursor.commit()\r\n","sub_path":"python/herepois.py","file_name":"herepois.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"510918216","text":"import numpy as np\r\nfrom numpy import loadtxt\r\nfrom sklearn.model_selection import KFold\r\nfrom sklearn import preprocessing, linear_model\r\nfrom numpy import loadtxt\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\r\nfrom sklearn.model_selection import KFold\r\nfrom sklearn.metrics import accuracy_score\r\nfrom math import sqrt\r\nimport numpy as numpy\r\nimport xgboost as xgb\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.metrics import explained_variance_score\r\nimport matplotlib.pyplot as pyplot\r\nfrom sklearn.ensemble import RandomForestRegressor\r\n\r\n# load data\r\ndataset = loadtxt('Adhesivestrength-32.csv', delimiter=\",\")\r\n\r\n# split data into X and y\r\ny = dataset[:,4]\r\nX = dataset[:,0:4]\r\n\r\n# Standard Scalar\r\nscaler = StandardScaler()\r\nprint(scaler.fit(np.array(X)))\r\nX_scaled = scaler.transform(np.array(X))\r\nprint('X=', X)\r\nprint('X_scaled=', X_scaled)\r\nprint('mean of X_scaled =', X_scaled.mean(axis=0))\r\nprint('std of X_scaled =', X_scaled.std(axis=0))\r\n\r\n# RF Regressor\r\nmodel = linear_model.ElasticNet(alpha=0.1)\r\n\r\n# k-fold split into train, test data\r\nn_splits=32\r\nkf = KFold(n_splits)\r\nkf.get_n_splits(X_scaled)\r\nprint(kf) \r\n\r\nR=1\r\ny_test_tot = np.zeros(32)\r\ny_pred_test_tot = np.zeros(32)\r\n\r\nfor train_index, test_index in kf.split(X_scaled):\r\n print(\"Round\", R, \"-\", \"TRAIN:\", train_index, \"TEST:\", test_index)\r\n X_train, X_test = X_scaled[train_index], X_scaled[test_index]\r\n y_train, y_test = y[train_index], y[test_index] \r\n R=R+1\r\n \r\n # Early stopping\r\n model.fit(X_train, y_train)\r\n \r\n # Prediction for train and test data\r\n y_pred_test = model.predict(X_test)\r\n y_pred_train = model.predict(X_train)\r\n \r\n # Evaludation RSME, MAE and R^2 for train and test data \r\n print('Test data')\r\n print(\"Root mean squared error: %.2f\" % sqrt(mean_squared_error(y_test, y_pred_test)))\r\n print('Mean absolute error: %.2f' % mean_absolute_error(y_test,y_pred_test))\r\n print(' ')\r\n y_test_tot[R-2]=y_test\r\n y_pred_test_tot[R-2]=y_pred_test\r\n \r\n print('Train data')\r\n print(\"Root mean squared error: %.2f\" % sqrt(mean_squared_error(y_train, y_pred_train)))\r\n print('Mean absolute error: %.2f' % mean_absolute_error(y_train,y_pred_train))\r\n print('Variance score: %.2f' % r2_score(y_train, y_pred_train))\r\n print(' ')\r\n \r\n # Plot observation VS prediction\r\n fig, ax = plt.subplots()\r\n ax.scatter(y_test, y_pred_test, edgecolors=(0, 1, 0))\r\n ax.plot([0, 30], [0, 30], 'k--', lw=4)\r\n plt.ylim(0, 30)\r\n plt.xlim(0, 30)\r\n ax.set_xlabel('observed y (test data)')\r\n ax.set_ylabel('Predicted y (test data)')\r\n plt.show()\r\n\r\n fig, ax = plt.subplots()\r\n ax.scatter(y_train, y_pred_train, edgecolors=(0, 0, 0))\r\n ax.plot([0, 30], [0, 30], 'k--', lw=4)\r\n plt.ylim(0, 30)\r\n plt.xlim(0, 30)\r\n ax.set_xlabel('observed y (train data)')\r\n ax.set_ylabel('Predicted y (train data)')\r\n plt.show()\r\n\r\nprint('Summary')\r\n\r\n# Plot observation VS prediction\r\nfig, ax = plt.subplots()\r\nax.scatter(y_test_tot, y_pred_test_tot, edgecolors=(0, 1, 0))\r\nax.plot([-5, 35], [-5, 35], 'k--', lw=4)\r\nplt.ylim(-5, 35)\r\nplt.xlim(-5, 35)\r\nax.set_xlabel('observed y (test data)')\r\nax.set_ylabel('Predicted y (test data)')\r\nplt.show()\r\n\r\nprint('Variance score: %.2f' % r2_score(y_test_tot, y_pred_test_tot))\r\nprint('Mean absolute error: %.2f' % mean_absolute_error(y_test_tot, y_pred_test_tot))\r\nprint('Root mean absolute error: %.2f' % sqrt(mean_squared_error(y_test_tot, y_pred_test_tot)))\r\n\r\n# feature importance\r\nprint(model.feature_importances_)\r\n# plot\r\npyplot.bar(range(len(model.feature_importances_)),\r\nmodel.feature_importances_)\r\npyplot.show()\r\n","sub_path":"Random forest model.py","file_name":"Random forest model.py","file_ext":"py","file_size_in_byte":3839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"586043707","text":"import pandas as pd\nimport requests\nfrom bs4 import BeautifulSoup\n\n#In this exercise we will be fetching data from a website.\n#We will get Germany's FIFA soccer world cup team\n\nlstNames = []\nlstNums = []\n\n#URL to Germany's team\nres = requests.get(\"https://es.fifa.com/worldcup/teams/team/43948/\")\nsoup = BeautifulSoup(res.text, 'html.parser')\n\n#Search for each player's name\nfor itemText in soup.find_all('span', attrs={'class':\"fi-p__nShorter\"}) :\n lstNames.append(itemText.text)\n\n#Removing the coach from the list\nlstNames.pop()\n\n#Getting each players shirt's number\nfor itemText in soup.find_all('span', attrs={'class', 'fi-p__num'}) :\n lstNums.append(itemText.text)\n\n#Coverting to DataFrame\nlstPlayers = {'name: ' : lstNames, 'shirtnumber: ':lstNums}\ndf = pd.DataFrame(lstPlayers)\nprint(df)","sub_path":"sample_4.py","file_name":"sample_4.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"278440155","text":"import datetime\nx = datetime.datetime.now()\nprint(\"Today is \" + str(x))\nyear = x.year\nnowMonth = x.month\nnowDay = x.day\nnowHour = x.hour\nnowMinute = x.minute\nnowSec = x.second\n\nprint(\"The year is\", year, \"The month is\", nowMonth, \"the day is\", nowDay, \"the hour is\", nowHour, \"the minute is\", nowMinute, \"the seconds are\", nowSec)\n\ny = datetime.datetime(2019, 1, 1)\nnyMonth = y.month\nprint(nyMonth)\nprint(y)\n","sub_path":"module4/getdate.py","file_name":"getdate.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"120521822","text":"# Make estimation table\n\n''' This script uses the estimation results to make nice estimation tables.\n'''\n\n#------------------------------------------------------------\n# Import necessary packages\n#------------------------------------------------------------\n\nimport os\nos.chdir(r'D:/RUG/PhD/Materials_papers/2-Working_paper_competition')\n\nimport numpy as np\nimport pandas as pd\n\n#------------------------------------------------------------\n# Make functions\n#------------------------------------------------------------\n\ndef estimationTable(df, show = 'pval', stars = False, col_label = 'Est. Results'):\n ''' This function takes a df with estimation results and returns \n a formatted column. \n \n Input: df = pandas dataframe estimation results\n show = Str indicating what to show (std, tval, or pval)\n stars = Boolean, show stars based on pval yes/no\n col_label = Str, label for the resulting pandas dataframe\n \n Output: Pandas dataframe\n '''\n # Prelims\n ## Set dictionary for index and columns\n dictionary = {'ls_num':'Loan Sales',\n 'ls_val':'Loan Sales (\\$)',\n 'ls_gse_num':'LS GSE',\n 'ls_priv_num':'LS Private',\n 'sec_num':'Securitization',\n 'perc_broadband':'Internet',\n 'perc_noint':'No Internet',\n 'lti':'LTI',\n 'ln_loanamout':'Loan Value',\n 'ln_appincome':'Income',\n 'subprime':'Subprime',\n 'ln_ta':'Size',\n 'ln_emp':'Employees',\n 'ln_num_branch':'Branches',\n 'cb':'Bank',\n 'ln_density':'Density',\n 'ln_pop_area':'Population',\n 'ln_mfi':'MFI',\n 'hhi':'HHI',\n 'params':'Parameter',\n 'std':'Standard Deviation',\n 't':'$t$-value',\n 'p':'$p$-value',\n 'nobs':'Observations',\n 'adj_rsquared':'Adj. $R^2$',\n 'depvar_notrans_mean':'Depvar mean',\n 'depvar_notrans_median':'Depvar median',\n 'depvar_notrans_std':'Depvar SD',\n 'fixed effects':'FE',\n 'msamd':'MSAs/MDs',\n 'cert':'Lenders',\n 'intercept':'Intercept'}\n \n # Get parameter column and secondary columns (std, tval, pval)\n params = df.params.round(4)\n \n if show == 'std':\n secondary = df.std\n elif show == 'tval':\n secondary = df.t\n else:\n secondary = df.p\n\n # Transform secondary column \n # If stars, then add stars to the parameter list\n if stars:\n stars_count = ['*' * i for i in sum([df.p <0.10, df.p <0.05, df.p <0.01])]\n params = ['{:.4f}{}'.format(val, stars) for val, stars in zip(params,stars_count)]\n secondary_formatted = ['({:.4f})'.format(val) for val in secondary]\n \n # Zip lists to make one list\n results = [val for sublist in list(zip(params, secondary_formatted)) for val in sublist]\n \n # Make pandas dataframe\n ## Make index col (make list of lists and zip)\n lol_params = list(zip([dictionary[val] for val in params.index],\\\n ['{} {}'.format(show, val) for val in [dictionary[val] for val in params.index]]))\n index_row = [val for sublist in lol_params for val in sublist]\n \n # Make df\n results_df = pd.DataFrame(results, index = index_row, columns = [col_label]) \n \n # append N, lenders, MSAs, adj. R2, Depvar, and FEs\n ## Make stats lists and maken index labels pretty\n stats = df[['nobs', 'adj_rsquared', 'depvar_notrans_mean',\\\n 'depvar_notrans_median', 'depvar_notrans_std',\\\n 'fixed effects', 'msamd', 'cert']].iloc[0,:].apply(lambda x: round(x, 4) if isinstance(x, (int, float)) else x)\n stats.index = [dictionary[val] for val in stats.index]\n \n ### Make df from stats\n stats_df = pd.DataFrame(stats)\n stats_df.columns = [col_label]\n \n ## Append to results_df\n results_df = results_df.append(stats_df)\n\n return results_df \n\ndef resultsToLatex(results, caption = '', label = '', wide_table = False):\n # Prelim\n if wide_table:\n function_parameters = dict(na_rep = '',\n index_names = False,\n column_format = 'p{2cm}' + 'p{1.0cm}' * results.shape[1],\n escape = False,\n multicolumn = True,\n multicolumn_format = 'c',\n caption = caption,\n label = label)\n else: \n function_parameters = dict(na_rep = '',\n index_names = False,\n column_format = 'p{2.5cm}' + 'p{1.5cm}' * results.shape[1],\n escape = False,\n multicolumn = True,\n multicolumn_format = 'c',\n caption = caption,\n label = label)\n \n # To Latex\n return results.to_latex(**function_parameters)\n\n\ndef concatResults(path_list, show = 'pval', stars = False, col_label = None, caption = '', label = '', wide_table = False):\n '''Calls estimationTable and returns a concatenated table '''\n \n list_of_results = []\n for df_path, lab in zip(path_list, col_label):\n # Read df\n df = pd.read_csv(df_path, index_col = 0)\n \n # Call estimationTable and append to list\n list_of_results.append(estimationTable(df, show = 'pval', stars = False,\\\n col_label = lab))\n\n # Concat all list of dfs to a single df\n results = pd.concat(list_of_results, axis = 1)\n \n # Order results\n ## Get column indexes that are not in fist column and insert in index column 0\n missing_cols = [var for i in range(len(list_of_results)-3,-1,-1) for var in list_of_results[i+1].index if var not in list_of_results[0].index]\n target_cols = list_of_results[0].index.tolist()\n for i in range(len(missing_cols)):\n target_cols.insert(i + 2, missing_cols[i])\n \n # order results \n results = results.loc[target_cols,:]\n\n # Rename index\n results.index = [result if not show in result else '' for result in results.index]\n \n \n # Rename columns if multicolumn\n if '|' in results.columns:\n col_names = np.array([string.split('|') for string in results.columns])\n results.columns = pd.MultiIndex.from_arrays([col_names[:,0], col_names[:,1]], names = ['Method','Number'])\n \n # To latex\n results_latex = resultsToLatex(results, caption, label, wide_table)\n \n ## Add table placement\n location = results_latex.find('\\begin{table}\\n')\n results_latex = results_latex[:location + len('\\begin{table}\\n') + 1] + '[th!]' + results_latex[location + len('\\begin{table}\\n') + 1:]\n \n ## Make the font size of the table footnotesize\n size_string = '\\\\tiny \\n'\n location = results_latex.find('\\centering\\n')\n results_latex = results_latex[:location + len('\\centering\\n')] + size_string + results_latex[location + len('\\centering\\n'):]\n \n # Add midrule above 'Observations'\n size_midrule = '\\\\midrule'\n location = results_latex.find('\\nObservations')\n results_latex = results_latex[:location] + size_midrule + results_latex[location:]\n \n ## Add note to the table\n # TODO: Add std, tval and stars option\n note_string = '\\justify\\n\\\\scriptsize{\\\\textit{Notes.} P-value in parentheses. All models are estimated with clustered standard errors on the MSA-level. Model (5) is estimated with an intercept. }\\n'\n location = results_latex.find('\\end{tabular}\\n')\n results_latex = results_latex[:location + len('\\end{tabular}\\n')] + note_string + results_latex[location + len('\\end{tabular}\\n'):]\n \n return results, results_latex\n \n\n#------------------------------------------------------------\n# Call concatResults\n#------------------------------------------------------------\n \n# Set path list\npath_list = ['Robustness_checks/Robust_{}.csv'.format(i) for i in range(1,5+1)]\n\n# Set column labels\ncol_label = ['({})'.format(i) for i in range(1,len(path_list) + 1)]\n\n# Set title and label\ncaption = 'Robustness checks'\nlabel = 'tab:robust'\n\n# Call function\ndf_results, latex_results = concatResults(path_list, col_label = col_label,\\\n caption = caption, label = label, wide_table = False)\n\n#------------------------------------------------------------\n# Save df and latex file\n#------------------------------------------------------------\n\ndf_results.to_csv('Robustness_checks/Robust_df.csv')\n\ntext_file_latex_results = open('Robustness_checks/Robust_latex.tex', 'w')\ntext_file_latex_results.write(latex_results)\ntext_file_latex_results.close()\n\n","sub_path":"Robustness_tables_v2.py","file_name":"Robustness_tables_v2.py","file_ext":"py","file_size_in_byte":9063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"104703298","text":"#!/usr/bin/env python3\n# coding=utf-8\n\nfrom socket import *\nimport mydes\nfrom mydes import ECB\nfrom mysha import sha1\nimport myrsa\nimport threading\nimport pickle\n\nrsa_d = '12788CB7287926A6D'\nrsa_e = '99885B20644FBC5'\nrsa_n = 'B0E65CAF148B87A7D'\n\n# 客户端的公钥\nc_e = '788A3184838677445'\nc_n = 'F6FCE42A9B245B691'\n\n\nhost = \"127.0.0.1\"\nport = 19900\naddr = (host, port)\n\n\n# 子线程\ndef link(sock, addr):\n # 密钥分配\n print('接入新连接', addr)\n key = ''\n while True:\n data = sock.recv(2048)\n key = myrsa.decrypt(c_e, c_n, pickle.loads(data))\n encrypted_key = myrsa.encrypt(rsa_d, rsa_n, key)\n # print(encrypted_key)\n sock.send(pickle.dumps(encrypted_key))\n data = sock.recv(2048)\n if pickle.loads(data) == 'Y':\n print('密钥分配完成\\n')\n break\n \n\n\n # 格式化密钥\n key = mydes.h_bin(myrsa.b16encode(key))\n # 信息处理\n while True:\n # 接受密文\n data = sock.recv(2048)\n if not data:\n print('连接已断开', addr,'\\n')\n return\n # 反序列化\n data = pickle.loads(data)\n ecb = ECB(key, cipher=data[0], fill=data[1])\n # 解密\n plain = ecb.decrypt()\n plain = myrsa.b16decode(mydes.b_hex(plain))\n # 验证签名\n if sha1(plain) == myrsa.decrypt(c_e,c_n,data[2]):\n #if data[2] == myrsa.encrypt(c_e, c_n, sha1(plain)):\n # 发送确认消息\n sock.send(pickle.dumps('Y'))\n print(addr, '>>>', plain)\n elif data[2]==myrsa.encrypt(c_e,c_n,sha1(plain.lower())):\n sock.send(pickle.dumps('Y'))\n print(addr, '>>>', plain.lower())\n else:\n print(plain)\n sock.send(pickle.dumps('N'))\n\n\nTCP = socket(AF_INET, SOCK_STREAM)\nTCP.bind(addr)\nTCP.listen(5)\nprint('服务器启动...\\n')\n\nwhile True:\n sock, addr = TCP.accept()\n # 为每个连接启用新线程\n t = threading.Thread(target=link, args=(sock, addr))\n t.start()\n\nTCP.close()\n","sub_path":"python/cipher/sever.py","file_name":"sever.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"340639578","text":"from ruamel.yaml import YAML\n\nstream = open(\"./content/formulas.yaml\", 'r')\n\nyaml = YAML()\nyaml_formulas = yaml.load(stream)\n\nyaml_formulas['title']['html_pattern'] = 'hey'\n\n#formulas = []\n\n\"\"\" for i, (key, value) in enumerate(yaml_formulas.items()):\n print(key)\n for j, (jkey, jvalue) in enumerate(value.items()):\n print(jvalue) \"\"\"\n\n\nfor i, (key, value) in enumerate(yaml_formulas.items()):\n print(i, key)\n mydict = dict(value)\n print(mydict)\n\n","sub_path":"source/sandbox/yaml.py","file_name":"yaml.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"279342986","text":"# coding:utf-8\nfrom django.conf.urls import url\nfrom django.views.decorators.csrf import csrf_exempt\nimport views\n\napp_name = 'website'\n\nurlpatterns = [\n url(r'^$', views.Home.as_view(), name='home'),\n url(r'^validate/$', csrf_exempt(views.Validation.as_view()), name='validate'),\n url(r'^register/$', views.Register.as_view(), name='register'),\n url(r'^thanks/$', views.Thanks.as_view(), name='thanks'),\n]\n","sub_path":"project/apps/website/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"27510102","text":"#! python3\n\"\"\"\nHave the user enter a number.\nDisplay the multiples of that number, up to 12 times that number:\nAll numbers should be on the same line.\n(2 marks)\n\ninputs:\nint number\n\noutputs:\nmultiples of that number on one line\n\nexample:\nEnter a number: 4\n4 8 12 16 20 24 28 32 36 40 44 48\n\"\"\"\nimport math \na=(input(\"Enter a number\")).strip()\na=int(a)\nb=a*12\ni=1 \nwhile b>=(a*i):\n x=int(a*i)\n print(x,end=' ')\n i=(i+1)\n","sub_path":"problem2.py","file_name":"problem2.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"35599500","text":"#/usr/bin/env python\n# -*- coding:utf-8 -*-\n'''\n @File : excel-1.py \n @Contact : guoxin@126.com\n @License : (C)Copyright 2018-2019, xguo\n\n@Modify Time @Author @Version @Desciption\n------------ ------- -------- -----------\n2020/3/30 10:44 xguo 1.0 None\n\n'''\n\nimport xlsxwriter\n\ndef main():\n datas = (\n ['Rent', 1000],\n ['Gas', 100],\n ['Food', 300],\n ['Gym', 50]\n )\n\n workbook = xlsxwriter.Workbook('ex01.xlsx')\n worksheet = workbook.add_worksheet('data')\n\n bold = workbook.add_format({'bold': True})\n money = workbook.add_format({'num_format': '$#,##0'})\n\n worksheet.write('A1', 'Item', bold)\n worksheet.write('B1', 'Cost', bold)\n\n row, col = 1, 0\n\n for item, cost in datas:\n\n worksheet.write(row,col,item)\n worksheet.write(row, col+1, cost)\n\n row += 1\n\n worksheet.write(row, 0, 'Total', bold)\n worksheet.write(row, 1, '=SUM(B1:B4)', money)\n\n workbook.close()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"py/excel-1.py","file_name":"excel-1.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"401411656","text":" # 设计一个函数返回传入的列表中最大和第二大的元素的值。\ndef max2(x):\n if x[0] > x[1]:\n m1, m2 = x[0], x[1]\n elif x[0] < x[1]:\n m1, m2 = x[1], x[0]\n for index in range(1,len(x)):\n if x[index] > m1:\n m2 = m1\n m1 = x[index]\n elif x[index] > m2:\n m2 = x[index]\n return m1, m2\n\na = [1, 4, 3, 2, 6, 9, 8, 7, 5]\nprint(max2(a))\nx, y = max2(a)\nprint(x, y)\n \n \n ","sub_path":"文件/python-100-days练习/函数返回传入列表的最大和第二大的元素的值.py","file_name":"函数返回传入列表的最大和第二大的元素的值.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"251888722","text":"#%%\nimport numpy as np\nimport pandas as pd \nimport bokeh.io\nfrom bokeh.models import *\nimport bokeh.layouts\nimport bokeh.plotting\nimport prot.viz\nimport tqdm\ncolors, palette = prot.viz.bokeh_theme()\ndataset_colors = prot.viz.dataset_colors()\n\n# ##############################################################################\n# DATA CLEANING AND AGGREGATION\n# ##############################################################################\n# Load the data\ncplx_prot_numeric_df = pd.read_csv('./cplx_prot_numeric.csv')\ncplx_prot_desc_df = pd.read_csv('./cplx_prot_desc.csv')\ncplx_prot_numeric_source = ColumnDataSource(cplx_prot_numeric_df)\ncplx_prot_desc_source = ColumnDataSource(cplx_prot_desc_df)\nprot_numeric_df = pd.read_csv('./prot_numeric.csv')\nprot_desc_df = pd.read_csv('prot_desc.csv')\nprot_numeric_source = ColumnDataSource(prot_numeric_df)\nprot_desc_source = ColumnDataSource(prot_desc_df)\n\n\n# Define the data sources\ncplx_df = pd.read_csv('../../../data/compiled_annotated_complexes.csv')\ncplx_desc_df = pd.read_csv('./cplx_desc.csv')\ncplx_numeric_df = pd.read_csv('./cplx_numeric.csv')\ncplx_source_data = ColumnDataSource(cplx_df)\ncplx_desc_source = ColumnDataSource(cplx_desc_df)\ncplx_numeric_source = ColumnDataSource(cplx_numeric_df)\n\n# Define the display sources. \ncplx_display_source = ColumnDataSource({'x':[], 'y':[], 'c':[], 'l':[],\n 'condition': [], 'cond':[]})\ncplx_table_source = ColumnDataSource({'protein':[], 'subunits':[], \n 'relative_subunits':[],\n 'observed':[],\n 'func':[]})\ncplx_prot_display_source = ColumnDataSource({'x':[], 'y':[], 'c':[], 'l':[],\n 'condition':[]})\nprot_display_source = ColumnDataSource({'x':[], 'y':[], 'c':[], 'l':[],\n 'condition':[]})\n\n\n# ##############################################################################\n# FIGURE CANVAS DECLARATION AND INTERACTION INSTANTIATION\n# ##############################################################################\nbokeh.io.output_file('./data_explorer.html')\n\n# Define the menu for selecting complexes \ncog_menu = [g for g in np.sort(cplx_desc_df['cog'].unique())]\ncomplex_menu = {d:g for g, d in zip(cplx_desc_df['complex_annotation'].values, cplx_desc_df['complex'].values)}\ncomplex_menu = [(k, v) for k, v in complex_menu.items()]\nclass_selection = Select(value='select COG functional class',\n options=cog_menu,\n width=400)\ncomplex_selection = Select(\n value='select annotation',\n options=[],\n width=400)\n\n# Define the menu for selecting proteins\nprotein_selection = Select(options=[], value='select gene product')\nprotein_name_selection = Select(options=[], value='select gene product')\n\n# Define the slector for min, max, or median complex abundance\nagg_fn = RadioButtonGroup(labels=['minimum', 'maximum', 'median', 'mean'],\n active=3)\n\n\n# Define the hover for callbacks and interactions.\nTOOLTIPS = [('growth rate [per hr]', '@x'),\n ('abundance [per cell]', '@y{int}'),\n ('growth condition', '@condition'),\n ('data source', '@l')]\n \n# Define the figure canvases\ncomplex_canvas = bokeh.plotting.figure(width=500, height=400, \n x_axis_label='growth rate [per hr]',\n y_axis_label='complex abundance per cell',\n y_axis_type='log',\n tooltips=TOOLTIPS)\ncomplex_canvas.y_range.range_padding = 1 \ncomplex_canvas.y_range.range_padding_units = 'percent'\nprot_canvas = bokeh.plotting.figure(width=500, height=400, \n x_axis_label='growth rate [per hr]',\n y_axis_label='protein abundance per cell',\n y_axis_type='log', \n tooltips=TOOLTIPS)\nprot_canvas.y_range.range_padding = 1 \nprot_canvas.y_range.range_padding_units = 'percent'\n\n# Populate the canvases.\ncomplex_canvas.circle(x='x', y='y', color='c', legend_field='l',\n source=cplx_display_source, line_color='black', size=10)\nprot_canvas.circle(x='x', y='y', color='c', legend_field='l',\n source=cplx_prot_display_source, line_color='black', size=10)\n\n# Define description divs and tables. \nclass_title = Div(text='Clusters of Orthologous Groups (COG) class')\nselector_title = Div(text=' EcoCyc complex annotation')\nagg_title = Div(text='complex abundance aggregation method')\nprot_title = Div(text='EcoCyc primary gene name')\ncomplex_description_field = Div(text=\"\")\nprotein_description_field = Div(text=\"\")\ncomplex_table_cols = [\n TableColumn(field='protein', title='protein name'),\n TableColumn(field='relative_subunits', title='expected stoichiometry'),\n TableColumn(field='observed', title='observed stoichiometry')\n]\ncomplex_table = DataTable(columns=complex_table_cols, source=cplx_table_source,\n width=450)\n# ##############################################################################\n# CALLBACK DEFINTITION AND ASSIGNMENT\n# ##############################################################################\n\n# Arguments for COG class selection widget\nclass_args = {'class_select_input': class_selection,\n 'complex_select_input': complex_selection,\n 'cplx_desc_source': cplx_desc_source,\n 'prot_desc_source': cplx_prot_desc_source,\n 'prot_select_input':protein_selection}\n\n# Arguments for complex selection\ncplx_args = {'cplx_desc_source': cplx_desc_source, \n 'cplx_numeric_source':cplx_numeric_source, \n 'cplx_select_input': complex_selection,\n 'cplx_table_source': cplx_table_source,\n 'agg_method_input': agg_fn,\n 'cplx_desc_field':complex_description_field,\n 'cplx_display_source': cplx_display_source}\n\n# Arguments for hover callback\ncplx_hover_args = { 'cplx_desc_source': cplx_desc_source,\n 'cplx_source_data':cplx_source_data, \n 'cplx_select_input':complex_selection,\n 'cplx_table_source': cplx_table_source,\n 'cplx_display_source':cplx_display_source}\n\n# Arguments for protein selection.\ncplx_prot_args = {'prot_numeric_source': cplx_prot_numeric_source,\n 'prot_display_source': cplx_prot_display_source,\n 'prot_select_input': protein_selection,\n 'prot_div': protein_description_field}\nprot_args = {'prot_numeric_source': prot_numeric_source,\n 'prot_display_source': prot_display_source,\n 'prot_select_input': protein_selection,\n 'prot_div': protein_description_field}\n\nclass_cb = prot.viz.load_js('class_selection.js', args=class_args)\nhover_cb = prot.viz.load_js('explorer_subunits.js', args=cplx_hover_args)\ncplx_cb = prot.viz.load_js('explorer_complex.js',args=cplx_args)\nprot_cb = prot.viz.load_js('prot_explorer.js', args=cplx_prot_args)\nprot_name_cb = prot.viz.load_js('prot_name_explorer.js', args=prot_args)\nclass_selection.js_on_change('value', class_cb)\nprotein_selection.js_on_change('value', prot_cb)\ncomplex_selection.js_on_change('value', cplx_cb)\nagg_fn.js_on_change('active', cplx_cb)\ncomplex_canvas.hover.callback = hover_cb\n\n# Define the widget boxes \ncomplex_box = bokeh.layouts.column(class_title, class_selection, selector_title,\n complex_selection, agg_title, agg_fn,\n complex_description_field, complex_table)\n\nprot_box = bokeh.layouts.column(class_title, class_selection, prot_title, protein_selection,\n protein_description_field)\ncomplex_plots = bokeh.layouts.column(complex_canvas)\ncomplex_layout = bokeh.layouts.row(complex_plots, complex_box)\nprotein_layout = bokeh.layouts.row(prot_canvas, prot_box)\n\n# Define the tabs\ncomplex_tab = Panel(child=complex_layout, title='Explore By Complex Annotation')\nprot_tab = Panel(child=protein_layout, title='Explore By Individual Protein')\ntabs = Tabs(tabs=[complex_tab, prot_tab])\nbokeh.io.save(tabs)\n\n# %%\n","sub_path":"code/figures/exploratory/explorer.py","file_name":"explorer.py","file_ext":"py","file_size_in_byte":8411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"443580259","text":"import numpy as np\n\n\n\nclass NeuralNetwork(object):\n def __init__(self):\n self.inputLayerSize = 2 # Количество входов (зависимые пары)\n self.outPutLayerSize = 1\n self.hiddenLayerSize = 3\n\n self.W1 = np.random.randn(self.inputLayerSize, \\\n self.hiddenLayerSize)\n\n self.W2 = np.random.randn(self.hiddenLayerSize, \\\n self.outPutLayerSize)\n\n def forward(self, X):\n\n self.z2 = np.dot(X, self.W1) # произведение сумм весов первого слоя и синапсов\n self.a2 = self.sigmoid(self.z2) # выход из нейрона после сигмоида. По z2.\n self.z3 = np.dot(self.a2, self.W2) # произведение сумм весов второго слоя и синапсов\n yHat = self.sigmoid(self.z3) # решение сети\n return yHat\n\n @staticmethod\n def sigmoid(z):\n return 1 / (1 + np.exp(-z))\n","sub_path":"core/neuraln.py","file_name":"neuraln.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"452883727","text":"#!/usr/bin/python3\n\n#sudo pip3 install opencv-contrib-python\n\n#This program is stating how to load an image in different modes and how to close it properly.\n\nimport cv2\nimg = cv2.imread('my.jpg',1) #reading image in colour mode/colourful\n\n\n#img1 = cv2.imread('my.jpg',0) # 0 for removing all colours/greyscale\n\n#img[0][0] check colour at pixel position\n\n#img1 = img[0:200,0:300]\n\ncv2.imshow('adhoc',img) #adhoc is the name of the image\n #here image can be closed by pressing any key\n\n\n\n\n#cv2.rectangle(img,(100,100),(300,300),(0,0,76),5)\ncv2.circle(img,(200,200),(100),(0,255,0),-1)\n\t# name center rad color width\n\n# polygon eclipse text \n\n\ncv2.imwrite('my1.jpg',img) ######### to save the image locally\n\n\n\ncv2.imshow('windowsname',img)\t\t#_____________-to display the image\ncv2.waitKey(0) # 0 for waiting lifetime action/ infinite time\n#cv2.waitKey(time) waiting time in ms\n\ncv2.destroyAllWindows() #to close all windows properly\n","sub_path":"cv.py","file_name":"cv.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"398347974","text":"import os\n\nimport mock\n\nimport utils\n\nfrom core import checks\nfrom core import known_bugs_utils\n\nfrom plugins.juju.pyparts import (\n machines,\n charms,\n units,\n)\n\nFAKE_PS = \"\"\"root 615 0.0 0.0 21768 980 ? Ss Apr06 0:00 bash /etc/systemd/system/jujud-machine-0-lxd-11-exec-start.sh\nroot 731 0.0 0.0 2981484 81644 ? Sl Apr06 49:01 /var/lib/juju/tools/machine-0-lxd-11/jujud machine --data-dir /var/lib/juju --machine-id 0/lxd/11 --debug\"\"\" # noqa\n\n\nclass TestJujuPluginPartServices(utils.BaseTestCase):\n\n def test_get_machine_info(self):\n expected = {'machine': '1',\n 'version': '2.9.8'}\n inst = machines.JujuMachineChecks()\n inst.get_machine_info()\n self.assertTrue(inst.plugin_runnable)\n self.assertEquals(inst.output, expected)\n\n @mock.patch.object(machines, 'CLIHelper')\n def test_get_lxd_machine_info(self, mock_cli_helper):\n mock_helper = mock.MagicMock()\n mock_cli_helper.return_value = mock_helper\n mock_helper.ps.return_value = FAKE_PS.split('\\n')\n expected = {'machine': '0-lxd-11',\n 'version': '2.9.9'}\n\n with mock.patch('core.plugins.juju.JujuMachine') as m:\n mock_machine = mock.MagicMock()\n m.return_value = mock_machine\n mock_machine.id = '0-lxd-11'\n mock_machine.version = '2.9.9'\n inst = machines.JujuMachineChecks()\n self.assertTrue(inst.plugin_runnable)\n inst.get_machine_info()\n\n self.assertEquals(inst.output, expected)\n\n\nclass TestJujuPluginPartCharms(utils.BaseTestCase):\n\n def test_get_charm_versions(self):\n expected = {'charms': ['ceph-osd-495', 'neutron-openvswitch-443',\n 'nova-compute-564']}\n inst = charms.JujuCharmChecks()\n inst()\n self.assertTrue(inst.plugin_runnable)\n self.assertEquals(inst.output, expected)\n\n\nclass TestJujuPluginPartUnits(utils.BaseTestCase):\n\n def test_get_unit_info(self):\n expected = {'local': ['ceph-osd-1', 'neutron-openvswitch-1',\n 'nova-compute-0']}\n inst = units.JujuUnitChecks()\n inst()\n self.assertTrue(inst.plugin_runnable)\n self.assertEquals(inst.output, {\"units\": expected})\n\n\nclass TestJujuPluginPartKnown_bugs(utils.BaseTestCase):\n\n def setUp(self):\n super().setUp()\n os.environ[\"PLUGIN_NAME\"] = \"juju\"\n\n def test_detect_known_bugs(self):\n checks.BugChecksBase()()\n expected = {'bugs-detected':\n [{'id': 'https://bugs.launchpad.net/bugs/1910958',\n 'desc':\n ('Unit unit-rabbitmq-server-2 failed to start due '\n 'to members in relation 236 that cannot be '\n 'removed.'),\n 'origin': 'juju.01part'}]}\n self.assertEqual(known_bugs_utils._get_known_bugs(), expected)\n","sub_path":"tests/unit/test_juju.py","file_name":"test_juju.py","file_ext":"py","file_size_in_byte":2979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"71337766","text":"# !usr/bin/evn python\n\"\"\"\n类似7、37、67、97、107、137、167、197,这样由素数组成的数列叫做等差素数数列。\n素数数列具有项数的限制,一般指素数数列的项数有多少个连续项,最多可以存在多少个连续项。\n\n编程找出100以内的等差素数数列。\n\n思路:\n1、通过筛法找出100内的所有素数\n2、对于素数list内有两俩组合,构成等差数列a0,a1项\n3、计数出a2,查表判断a2是否是素数,如果是则能构成素数等差序列,计算a3\n\"\"\"\n\n\ndef fun(arg):\n li = [True] * arg\n pt = []\n for i in range(2, arg):\n if not li[i]:\n continue\n pt.append(i)\n for j in range(i**2, arg, i):\n li[j] = False\n return li, pt\n\nli, pt = fun(100)\n\nfor k in range(len(pt)):\n for v in range(k+1, len(pt)):\n a0, a1 = pt[k], pt[v]\n an = a1 + a1 - a0\n lis = []\n while an < 100 and li[an]:\n lis.append(an)\n an += a1 - a0\n if lis:\n # lis.insert(0, a0)\n # lis.insert(1, a1)\n print([a0, a1] + lis)\n","sub_path":"等差素数数列.py","file_name":"等差素数数列.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"418495015","text":"# -*- coding: UTF-8 -*-\n\nimport datetime\nfrom ..core import BaseService, db, after_commit\nfrom ..models import Inspiration, DesignerInspiration, ProductInspiration, Product, Designer\n\n\nclass InspirationService(BaseService):\n __model__ = Inspiration\n\n def create_inspiration(self, **kwargs):\n inspiration = Inspiration()\n self._set_inspiration(inspiration, **kwargs)\n self.save(inspiration)\n self. _add_designer(inspiration, kwargs.get('designer_ids', []))\n return inspiration\n\n def update_inspiration(self, inspiration_id, **kwargs):\n inspiration = self.get_or_404(inspiration_id)\n self._set_inspiration(inspiration, **kwargs)\n self.save(inspiration)\n self. _add_designer(inspiration, kwargs.get('designer_ids', []))\n return self.save(inspiration)\n\n def delete_inspiration(self, inspiration_id):\n inspiration = self.get_or_404(inspiration_id)\n self.delete(inspiration)\n\n def _set_inspiration(self, inspiration, **kwargs):\n inspiration.name = kwargs.get('name')\n inspiration.title = kwargs.get('title')\n inspiration.intro = kwargs.get('intro')\n\n def _add_designer(self, inspiration, designer_ids):\n keys = ['designer:%s:inspiration_ids' % designer_id for designer_id in inspiration.designer_ids]\n DesignerInspiration.query.filter(DesignerInspiration.inspiration_id==inspiration.id).delete(synchronize_session=False)\n\n for designer_id in designer_ids:\n db.session.add(DesignerInspiration(designer_id=designer_id, inspiration_id=inspiration.id))\n\n def do_after_commit():\n keys.extend(['designer:%s:inspiration_ids' % designer_id for designer_id in designer_ids])\n if keys:\n DesignerInspiration.cache_region().delete_multi(keys)\n\n DesignerInspiration.cache_region().delete('inspiration:%s:designer_ids' % inspiration.id)\n\n after_commit(do_after_commit)\n\ninspiration_service = InspirationService()\n\n\n\n","sub_path":"ca/services/product_inspirations.py","file_name":"product_inspirations.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"488941699","text":"\"\"\"\n\tIndicatorDetails.py\n\t\n\tContains information on all available indicators and patterns to\n\tmake use of when evolving strategies.\n\"\"\"\nbDebug = True\n\nfrom _modules.base.pair\t\t\t\timport Pair\nfrom _modules.base.pairActions \t\timport Self_TrendUp\t\t\t\tas TrendUp_Func\nfrom _modules.base.pairActions \t\timport Self_TrendDown\t\t\tas TrendDown_Func\nfrom _modules.base.pairActions \t\timport Line_vs_Line_Lesser\t\tas Lesser_Func\nfrom _modules.base.pairActions \t\timport Line_vs_Line_Greater\t\tas Greater_Func\nfrom _modules.base.pairActions \t\timport Line_vs_Line_Crossed\t\tas Crossed_Func\nfrom _modules.base.pairActions \t\timport Line_vs_Line_Diverging\tas Diverging_Func\nfrom _modules.base.pairActions \t\timport Line_vs_Line_Converging\tas Converging_Func\n\nfrom _modules.evolution.marketEmulator import cMarketEmulator\n\nfrom _modules.utilities.cvsTool\t\timport WriteCSV\t\t\t\t\tas csvOut\nfrom talib.abstract \t\t\t\timport *\n\nimport pprint\nimport random\nimport copy\n\ng_iId = 0\n\ng_DetailListing = {\n\t\"INDICATOR\":{\n\t\t\"EMA\":{\n\t\t\t\"function\"\t: (lambda x,period,price: x.indicator_EMA(period,price)),\n\t\t\t\"type\"\t\t: \"LINE\",\n\t\t\t\"params\"\t: [\t{\"name\" : \"timeperiod\",\t\"value\" : (lambda: random.randint(2,200))},\n\t\t\t\t\t\t\t{\"name\" : \"price\",\t\t\"value\" : (lambda: random.choice([\"close\",\"open\",\"high\",\"low\"]))}],\n\t\t\t\"action\"\t: {\t\"SELF\"\t: (lambda: random.choice([\"TRENDUP\", \"TRENDDOWN\"])),\n\t\t\t\t\t\t\t\"VSLINE\": (lambda: random.choice([\"CROSSED\", \"CONVERGING\", \"DIVERGING\", \"GREATER\", \"LESSER\"]))},\n\t\t},\n\t\t\"SMA\":{\n\t\t\t\"function\"\t: (lambda x,period,price: x.indicator_SMA(period,price)),\n\t\t\t\"type\"\t\t: \"LINE\",\n\t\t\t\"params\"\t: [\t{\"name\" : \"timeperiod\",\t\"value\" : (lambda: random.randint(2,200))},\n\t\t\t\t\t\t\t{\"name\" : \"price\",\t\t\"value\" : (lambda: random.choice([\"close\",\"open\",\"high\",\"low\"]))}],\n\t\t\t\"action\"\t: {\t\"SELF\"\t: (lambda: random.choice([\"TRENDUP\", \"TRENDDOWN\"])),\n\t\t\t\t\t\t\t\"VSLINE\": (lambda: random.choice([\"CROSSED\", \"CONVERGING\", \"DIVERGING\", \"GREATER\", \"LESSER\"]))},\n\t\t},\n#\t\t\"MACD\":{\n#\t\t\t\"function\"\t: (lambda x,fastperiod,slowperiod,trigger: x.indicator_MACD(fastperiod,slowperiod,trigger)),\n#\t\t\t\"type\"\t\t: \"LINE-DOT\",\n#\t\t\t\"params\"\t: [\t{\"name\" : \"fastperiod\",\t\"value\" : (lambda: random.randint(2,200))},\n#\t\t\t\t\t\t\t{\"name\" : \"slowperiod\",\t\"value\" : (lambda: random.randint(2,200))},\n#\t\t\t\t\t\t\t{\"name\" : \"trigger\",\t\"value\" : (lambda: random.uniform(-1.0,1.0))}],\n#\t\t\t\"action\"\t: {\t\"SELF\"\t: (lambda: random.choice([\"TRENDUP\", \"TRENDDOWN\", \"CROSSED\", \"CONVERGING\", \"DIVERGING\", \n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"FASTGREATERPOINT\", \"FASTLESSPOINT\", \"SLOWGREATERPOINT\",\"SLOWLESSPOINT\"])),\n#\t\t\t\t\t\t\t\"VSLINE\": (lambda: random.choice([\"CROSSED\", \"CONVERGING\", \"DIVERGING\", \"GREATER\", \"LESSER\", \n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"POINTCONVERGING\", \"POINTDIVERGING\", \"POINTGREATER\", \"POINTLESS\"]))},\n#\t\t},\n\t},\n\t\"hardTypes\"\t\t: [ \"INDICATOR\", ],\n\t\"legalActions\"\t: { \"SELF\"\t\t: [\"ANY\"],\n\t\t\t\t\t\t\"VSLINE\"\t: [\"EMA\", \"SMA\"],\n\t\t\t\t\t},\n\t\"actionSelfMaps\": {\t\"TRENDUP\"\t: TrendUp_Func,\n\t\t\t\t\t\t\"TRENDDOWN\"\t: TrendDown_Func,\n\t\t\t\t\t\t\"CROSSED\"\t: Crossed_Func,\n\t\t\t\t\t\t\"CONVERGING\": Converging_Func,\n\t\t\t\t\t\t\"DIVERGING\"\t: Diverging_Func,\n\t\t\t\t\t},\n\t\"actionVSLineMaps\":{\"CROSSED\"\t: Crossed_Func,\n\t\t\t\t\t\t\"CONVERGING\": Converging_Func,\n\t\t\t\t\t\t\"DIVERGING\"\t: Diverging_Func,\n\t\t\t\t\t\t\"GREATER\"\t: Greater_Func,\n\t\t\t\t\t\t\"LESSER\"\t: Lesser_Func,\n\t\t\t\t\t}\n}\n\n#\n# geneRange consists of a range 0-2 with 1 being the source and 0,3 being the targets\n#\ndef evaluateGene(targetPair, prevGene=None, currGene=None, nextGene=None):\n\t#print(\"Previous\t: {}\".format(prevGene))\n\t#print(\"?] Current\t\t: {}\".format(currGene))\n\t#print(\"Next\t\t: {}\".format(nextGene))\n\t#print(\"---\")\n\t#return\n\tres = None\n\t# Check the subtype\n\tif currGene._SubType == \"EMA\":\n\t\t# Evaluate the EMA indicator and store the results\n\t\tmainResult = g_DetailListing[\"INDICATOR\"][currGene._SubType][\"function\"](targetPair,currGene._Params[\"timeperiod\"], currGene._Params[\"price\"])\n\t\t# Check what type of action it's assigned for if conditions allow it to execute.\n\t\t# Check SELF actions first\n\t\tif currGene._Action in g_DetailListing[\"actionSelfMaps\"].keys():\n\t\t\t# Call that particular function. No prep required since it only works with its own data\n\t\t\treturn g_DetailListing[\"actionSelfMaps\"][currGene._Action](mainResult)\n\t\t# Check VSLINE actions next\n\t\telif currGene._Action in g_DetailListing[\"actionVSLineMaps\"].keys():\n\t\t\t# Verify there is a gene to compare against\n\t\t\tif nextGene == None: return False\n\t\t\t# Verify it's a legal target\n\t\t\tif nextGene._SubType not in g_DetailListing[\"legalActions\"][\"VSLINE\"]: return False\n\t\t\t# Calculate the next genes values to compare against\n\t\t\tnextResult = g_DetailListing[\"INDICATOR\"][nextGene._SubType][\"function\"](targetPair,nextGene._Params[\"timeperiod\"], nextGene._Params[\"price\"])\n\t\t\treturn g_DetailListing[\"actionVSLineMaps\"][currGene._Action](mainResult, nextResult)\n\tif currGene._SubType == \"SMA\":\n\t\t# Evaluate the EMA indicator and store the results\n\t\tmainResult = g_DetailListing[\"INDICATOR\"][currGene._SubType][\"function\"](targetPair,currGene._Params[\"timeperiod\"], currGene._Params[\"price\"])\n\t\t# Check what type of action it's assigned for if conditions allow it to execute.\n\t\t# Check SELF actions first\n\t\tif currGene._Action in g_DetailListing[\"actionSelfMaps\"].keys():\n\t\t\t# Call that particular function. No prep required since it only works with its own data\n\t\t\treturn g_DetailListing[\"actionSelfMaps\"][currGene._Action](mainResult)\n\t\t# Check VSLINE actions next\n\t\telif currGene._Action in g_DetailListing[\"actionVSLineMaps\"].keys():\n\t\t\t# Verify there is a gene to compare against\n\t\t\tif nextGene == None: return False\n\t\t\t# Verify it's a legal target\n\t\t\tif nextGene._SubType not in g_DetailListing[\"legalActions\"][\"VSLINE\"]: return False\n\t\t\t# Calculate the next genes values to compare against\n\t\t\tnextResult = g_DetailListing[\"INDICATOR\"][nextGene._SubType][\"function\"](targetPair,nextGene._Params[\"timeperiod\"], nextGene._Params[\"price\"])\n\t\t\treturn g_DetailListing[\"actionVSLineMaps\"][currGene._Action](mainResult, nextResult)\n\treturn res\n\t\nclass cGene:\n\tdef __init__(self):\n\t\t# Determine the Gene type\n\t\tself._Type\t\t= random.choice(g_DetailListing[\"hardTypes\"])\n\t\tself._SubType\t= None\n\t\tself._Action\t= None\n\t\tself._Requires\t= 200 # TODO\n\t\tself._Params\t= {}\n\t\tself._SelfAssign()\n\t\t#print(\"{}-{}-[{}]\".format(self._Type, self._SubType, self._Action))\n\t\t#print(self._Params)\n\t\t\n\tdef __repr__(self):\n\t\treturn \"{}-{}-{}-[{}]\".format(self._Type, self._SubType, self._Action, self._Params)\n\tdef DumpCVS(self):\n\t\treturn [self._Type, self._SubType, self._Action] + list(zip(self._Params.keys(),self._Params.values()))\n\tdef xlsxDetails(self):\n\t\treturn [self._Type, self._SubType, self._Action] + [p for p in self._Params]\n\tdef _SelfAssign(self, bMutate = False, fMutationChance=.05):\n\t\tif self._Type\t== \"INDICATOR\":\n\t\t\tif bMutate or self._SubType == None:\n\t\t\t\tself._SubType = random.choice(list(g_DetailListing[self._Type].keys()))\n\t\t\treturn self._SelfParamIndicator(bMutate, fMutationChance)\n\t\telse:\n\t\t\treturn False\n\tdef _SelfParamIndicator(self, bMutate = False, fMutationChance=.05):\n\t\tbMutated = False\n\t\tif bMutate:\n\t\t\t# Grab the selected area of the dict\n\t\t\tselectedType = g_DetailListing[self._Type][self._SubType]\n\t\t\t\n\t\t\t# Assign parameters from the listing\n\t\t\tfor param in selectedType[\"params\"]:\n\t\t\t\tif random.uniform(0,1) < fMutationChance:\n\t\t\t\t\t#print(\"Mutated {}\".format(param[\"name\"]))\n\t\t\t\t\tbMutated = True\n\t\t\t\t\tself._Params[param[\"name\"]] = param[\"value\"]()\t# Generate random values for parameters\n\t\t\t\t\n\t\t\t# Set the action type by randomizing a random choice\n\t\t\tif random.uniform(0,1) < fMutationChance:\n\t\t\t\t#print(\"Mutated Action\")\n\t\t\t\tbMutated = True\n\t\t\t\tself._Action = selectedType[\"action\"][random.choice(list(selectedType[\"action\"].keys()))]()\n\t\telse:\n\t\t\t# Grab the selected area of the dict\n\t\t\tselectedType = g_DetailListing[self._Type][self._SubType]\n\t\t\t\n\t\t\t# Assign parameters from the listing\n\t\t\tfor param in selectedType[\"params\"]:\n\t\t\t\tself._Params[param[\"name\"]] = param[\"value\"]()\t# Generate random values for parameters\n\t\t\t\t\n\t\t\t# Set the action type by randomizing a random choice\n\t\t\tself._Action = selectedType[\"action\"][random.choice(list(selectedType[\"action\"].keys()))]()\n\t\t\t\n\t\treturn bMutated\n\tdef AttemptMutation(self, fMutationChance):\n\t\tbMutated = False\n\t\t# Did the main type change?\n\t\tif random.uniform(0,1) < fMutationChance:\n\t\t\t# Create a brand new random set for it\n\t\t\tbMutated = True\n\t\t\t#print(\"Mutated hardType\")\n\t\t\t#print(\"Re-assigning SubType\")\n\t\t\tself._Type\t= random.choice(g_DetailListing[\"hardTypes\"])\n\t\t\tself._SubType = None\n\t\t\t\n\t\t\t# A new hardType requires a new set of parameters, act as if it's new\n\t\t\tself._SelfAssign()\n\t\t\treturn bMutated\n\t\t\t\n\t\t# Attempt to mutate parameters\n\t\tbMutated = self._SelfAssign(True, fMutationChance)\n\t\treturn bMutated\nclass cDNA:\n\tdef __init__(self, iGeneLength=0, bEnableGeneGrowth=False):\n\t\tglobal g_iId\n\t\tself._iId \t\t\t= g_iId\n\t\tg_iId+=1\n\t\tself._Genes \t\t= []\n\t\tself._iTradeID \t\t= 0\n\t\tself._iDeltaValue = 0\n\t\tself._TotalTriggers = 0\n\t\tif iGeneLength > 2:\n\t\t\tself.InitGenePool(iGeneLength, bEnableGeneGrowth)\n\t\t\n\tdef __repr__(self):\n\t\treturn \"{}\".format([a._SubType for a in self._Genes])\n\tdef Details(self):\n\t\treturn \"{}\".format([a for a in self._Genes])\n\tdef DumpCVS(self):\n\t\tret = [a.DumpCVS() for a in self._Genes]\n\t\treturn ret\n\t\t\n\tdef xlsxDetails(self):\n\t\toBack = []\n\t\tfor x in self._Genes:\n\t\t\toBack += x.xlsxDetails()\n\t\treturn oBack\n\tdef InitGenePool(self, iGeneLength, bEnableGeneGrowth= False):\n\t\tself._bGeneGrowth\t= bEnableGeneGrowth\t\t\t# Allow the DNA strand to grow or shrink\n\t\tself._iGeneLength\t= max(iGeneLength, 3)\t# Starting length of DNA strand, 3 min\n\t\tfor _ in range(self._iGeneLength):\n\t\t\tnewGene = cGene()\n\t\t\tself._Genes.append(newGene)\n\tdef CreateChildWith(self, Parent):\n\t\t_child = cDNA()\n\t\t_iSplicePoint = random.randint(0, min(len(Parent._Genes), len(self._Genes)))\n\t\t_child._Genes = self._Genes[:_iSplicePoint]+Parent._Genes[_iSplicePoint:]\n\t\treturn _child\n\tdef AttemptMutation(self, fMutationChance):\n\t\tfor gene in self._Genes:\n\t\t\tback = copy.deepcopy(gene)\n\t\t\tif gene.AttemptMutation(fMutationChance):\n\t\t\t\treturn True\n\t\t\t\t#if bDebug: print(\"?] {} -> {}\".format(back, gene))\n\t\t\t\t#else: pass\n\t\t\t\tpass\n\t\treturn False\n\tdef Reset(self):\n\t\tself._iTradeID \t\t= 0\n\t\tself._TotalTriggers = 0\n\t\tself._iDeltaValue \t= 0\n\t\tself._TradeListing\t= []\n\tdef AttemptEvaluation(self, targetPair, marketEmulator):\n\t\tres = []\n\t\tret = False\n\t\td = 0.0\n\t\t\n\t\t\n\t\t# Find the highest pair range required\n\t\tfor currentGene in range(0, len(self._Genes)):\n\t\t\t# Generate a gene range if possible\n\t\t\tprevGene = self._Genes[currentGene-1]\tif currentGene >= 1 else None\n\t\t\tcurrGene = self._Genes[currentGene]\n\t\t\tnextGene = self._Genes[currentGene+1]\tif currentGene < len(self._Genes)-1 else None\n\t\t\tres.append(evaluateGene(targetPair, prevGene, currGene, nextGene))\n\t\t\t\n\t\t# Check if this DNA Strand already has an open trade\n\t\tif marketEmulator.HasActiveTrade(self._iId):\n\t\t\tb = int((\"{0:.4f}\".format(targetPair._currentPrice)).replace('.', ''))\n\t\t\tif marketEmulator.UpdateTrailing(self._iId, b):\n\t\t\t\tself._iDeltaValue += marketEmulator.CloseTrade(self._iId, b)\n\t\t\t\t#print(\"Closing trade {}. New Gene {} value [{}].\".format(self._iTradeID, self._iId, self._iDeltaValue))\n\t\t\t\t\n\t\telif all(x for x in res):\n\t\t\tself._TotalTriggers+=1\n\t\t\tself._iTradeID +=1\n\t\t\tb = int((\"{0:.4f}\".format(targetPair._currentPrice)).replace('.', ''))\n\t\t\tmarketEmulator.OpenTrade(self._iId, b)\n\t\t\t#print(\"Opened trade for Gene {}.\".format(self._iId))\n\t\t\tret = True\n\t\t\t\n\t\treturn ret\n\t\t\n\nclass cEvolutionChamber:\n\tdef __init__(self, rawPairData, resourceHandle):\n\t\tglobal g_oXlsx\n\t\tself._rawPairData\t\t= rawPairData\n\t\tself._resourceHandle\t= resourceHandle\n\t\tself._marketEmulator\t= cMarketEmulator(self._rawPairData, self._resourceHandle)\n\t\t\n\t\tprint(\"{} Total Data Points...\".format(len(self._rawPairData[\"candles\"])))\n\t\tself._PreservationSize\t= 20\t# Maximum Top performers to carry over into next generation\n\t\tself._SuperiorChildren\t= 5\t\t# Maximum number of children to breed from top 2 performers\n\t\tself._ChildrenSize\t\t= 100\t# Generic breeding randomly from the top # performers previously\n\t\tself._PopulationSize\t= 200\t# Maximum population size, fill in extras with randomly generated\n\t\tself._TopPerformers\t\t= []\t# Store the top performers from each Epoch/Generation\n\t\tself._CurrentPerformers\t= []\t# Current Generation being tested\n\t\tself._CurrentEpoch\t\t= 0\t\t# Current Generation/Epoch\n\t\tself._MaxEpoch\t\t\t= 10000\t# Maximum Epoch to test to\n\t\tself._WindowEntrance\t= 0\t\t# Starting point for data points to be pulled from\n\t\tself._WindowSize\t\t= 200\t# Total size of data range to evaluate with each gene, soft-limit\n\t\tself._WindowMaxSize\t\t= 10000\t# There's no need to go beyond this...\n\t\tself._TestWindow\t\t= 100\t# Preserve # of the dataset to test against\n\t\tself._VariableGeneLength= False\t# Allow genes to increase or decrease in size over Epochs\n\t\tself._GeneLength\t\t= 5\t\t# Initial Gene lengths\n\t\tself._SelectionCriteria\t= \"PIPS\"# How to grade a particular \"dna\" fragment in fitness\n\t\tself._PipTarget\t\t\t= 800\t# Bogus thing... Change it TODO\n\t\tself._HighestPip\t\t= 0\t\t# Bogus thing... Change it TODO\n\t\tself._WinRateTarget\t\t= .80\t# Bogus thing... Change it TODO\n\t\tself._HighestWinRate\t= 0.0\t# Bogus thing... Change it TODO\n\t\tself._TakeProfitPip\t\t= 10\t# Any trades >= x pips = success\n\t\tself._StopLossPip\t\t= -10\t# Any trades <= x pips = failure\n\t\t\n\t\t# Make sure the settings are properly set within their own limits\n\t\tif (self._PreservationSize + self._SuperiorChildren + self._ChildrenSize) > self._PopulationSize:\n\t\t\tprint(\"!](Settings-Mismatch)! Next generation total exceeds allowed Population size!\")\n\t\t\timport sys\n\t\t\tsys.exit(1)\n\t\t\n\t# Break apart a huge dataset into managed pairs\n\tdef GenerateActiveData(self, startX, sizeY):\n\t\treturn Pair({\n\t\t\t\t\t\"granularity\":\tself._rawPairData[\"granularity\"],\n\t\t\t\t\t\"instrument\":\tself._rawPairData[\"instrument\"],\n\t\t\t\t\t\"candles\"\t:\tself._rawPairData[\"candles\"][startX:(startX+sizeY)],\n\t\t\t\t})\n\n\t# Create Epoch from scratch, Epoch 0 basically\n\tdef CreateEpoch(self):\n\t\tif bDebug: print(\"?] Creating Epoch 0 Genes.\")\n\t\t# Generate the initial population\n\t\tfor _ in range(self._PopulationSize):\n\t\t\t_new = cDNA(self._GeneLength, self._VariableGeneLength)\n\t\t\tself._CurrentPerformers.append(_new)\n\t\t\n\t\tpass\n\t# Start the evolution process. This should be branched off with a thread.\n\tdef Evolve(self):\n\t\ttry:\n\t\t\tself.CreateEpoch()\n\t\t\tfor x in range(0, self._MaxEpoch):\n\t\t\t\tself.EvaluateEpoch(x)\n\t\t\t\tself.PostEpoch(x)\n\t\t\t\tself.PrepareEpoch(x)\n\t\t\t\tself._CurrentEpoch+=1\n\t\t\tself.Cleanup()\n\t\texcept KeyboardInterrupt:\n\t\t\tself.Cleanup()\n\t\t\treturn\n\t\t\n\t# Create a new DNA strands from the previous epoch\n\tdef PrepareEpoch(self, bFirstEpoch):\n\t\tif bFirstEpoch == 0: return\n\t\tprint(\"+] Breeding Generation {}\".format(bFirstEpoch))\n\t\t#print(\" ] Total top performers {}\".format(len(self._TopPerformers)))\n\t\t# Breed the top 2 instantly, generate ## variations\n\t\ti=0\n\t\tfor _ in range(0, self._SuperiorChildren):\n\t\t\t_A = copy.deepcopy(self._TopPerformers[0])\n\t\t\t_B = copy.deepcopy(self._TopPerformers[1])\n\t\t\tif random.random() > 0.5:\n\t\t\t\t# Breed A with B\n\t\t\t\t_kid = _A.CreateChildWith(_B)\n\t\t\t\t#print(\"SC[A] ({}) + ({}) = {}\".format(_A, _B, _kid))\n\t\t\telse:\n\t\t\t\t# Breed B with A\n\t\t\t\t_kid = _B.CreateChildWith(_A)\n\t\t\t\t#print(\"SC[B] ({}) + ({}) = {}\".format(_B, _A, _kid))\n\t\t\tself._CurrentPerformers.append(_kid)\n\t\t\ti+=1\n\t\ti = 0\n\t\t\n\t\tfor _ in range(0, self._ChildrenSize):\n\t\t\t_AR = random.randint(0, self._PreservationSize-1)\n\t\t\t_BR = random.randint(0, self._PreservationSize-1)\n\t\t\t_A = copy.deepcopy(self._TopPerformers[_AR])\n\t\t\t_B = copy.deepcopy(self._TopPerformers[_BR])\n\t\t\t_kid = _A.CreateChildWith(_B)\n\t\t\t_kid.AttemptMutation(.05)\n\t\t\tself._CurrentPerformers.append(_kid)\n\t\t\ti+=1\n\t\ti=0\n\t\t\n\t\tfor _ in range(0, self._PopulationSize-len(self._CurrentPerformers)):\n\t\t\t_new = cDNA(self._GeneLength, self._VariableGeneLength)\n\t\t\t_new.AttemptMutation(.05)\n\t\t\tself._CurrentPerformers.append(_new)\n\t\t\t#print(\"SC[{},{}] ({}) + ({}) = {}\".format(_AR,_BR,_A, _B, _kid))\n\t\t\ti+=1\n\t\ti=0\n\t\t#print(\" ] SC({})\".format(i))\n\t\t#print(\" ] Total size of next Generation {}\".format(len(self._CurrentPerformers)))\n\t\t\n\t\tpass\n\t# Test each DNA strand against the historic data\n\tdef EvaluateEpoch(self, epoch):\n\t\tprint(\"+] Testing current Epoch.\")\n\t\ttotalTrades = 0\n\t\t\n\t\t# Rotate through entire dataset\n\t\tfor x in range(0, self._WindowMaxSize):\n\t\t\tif x%35==0:\n\t\t\t\tprint(\"{}] Evaluating {}-{}/{} - Trades[{}]\".format(random.choice([\"/\",\"|\",\"\\\\\",\"-\"]),x, x+self._WindowSize, self._WindowMaxSize, totalTrades), end='\\r')\n\t\t\t# Grab a subset of entire dataset\n\t\t\tpairWindow = self.GenerateActiveData(x, self._WindowSize)\n\t\t\t#if x == 0: print(\" ] Testing window \\n{}\".format((pairWindow)))\n\t\t\t# Break if we are missing data (at the end)\n\t\t\tif len(pairWindow.inputs[\"close\"]) != self._WindowSize: break\n\t\t\t#if x >= self._TestWindow: return True\n\t\t\t# Test each DNA strange against the subset\n\t\t\tfor individual in self._CurrentPerformers:\n\t\t\t\t# Increment totalTrades if a trade occured\n\t\t\t\tif individual.AttemptEvaluation(pairWindow, self._marketEmulator):\n\t\t\t\t\ttotalTrades +=1\n\t\t\t\t\t#print(\" ] {} Delta!\".format(individual._iDeltaValue))\n\t\t#for e in self._CurrentPerformers:\n\t\t#\tprint(\"{} = {}\".format(e._iId, e._iDeltaValue)\n\t\tprint(\"\\n ] {} Trades!\".format(totalTrades))\n\t\treturn False\n\t# Preserve top performers, update graphs, update spreadsheets, get the girl, save the world, etc...\n\tdef PostEpoch(self, epoch):\n\t\tglobal g_oXlsx\n\t\tprint(\"+] Evaluating Epoch results, surviving high performers, killing off underperformers and other stuff...\")\n\t\tself._TopPerformers = []\n\t\t# Close all open trades\n\t\tfor e in self._CurrentPerformers:\n\t\t\tself._marketEmulator.CloseTrade(e._iId)\n\t\t# Sort the top performers by who performed best\n\t\tfor x in self._CurrentPerformers:\n\t\t\t#print(\"{} = {}\".format(x._iId, x._iDeltaValue))\n\t\t\tif len(self._TopPerformers) == 0:\n\t\t\t\tself._TopPerformers.append(copy.deepcopy(x))\n\t\t\telse:\n\t\t\t\tfor e in range(0, min(self._PreservationSize,len(self._TopPerformers)-1)):\n\t\t\t\t\tif x._iDeltaValue > abs(self._TopPerformers[e]._iDeltaValue):\t# Comparison, current set for buy \n\t\t\t\t\t\tself._TopPerformers.insert(e, copy.deepcopy(x))\n\t\t\t\t\t\tbreak\n\t\t\t\t\telif x._iDeltaValue == self._TopPerformers[e]._iDeltaValue:\n\t\t\t\t\t\tself._TopPerformers.append(copy.deepcopy(x))\n\t\t\t\t\t\tbreak\n\t\t\t\tself._TopPerformers.append(copy.deepcopy(x))\n\t\t\t\t\n\t\t# Record statistics into the CVS file TODO\n\t\tcsvOut(\"testSheet.cvs\",[epoch, self._TopPerformers[0]._iId])\n\t\tfor e in self._TopPerformers[0].DumpCVS():\n\t\t\tcsvOut(\"testSheet.cvs\", [\"\",\"\",e[0],e[1],e[2]]+list(e[3])+list(e[4]))\n\t\t\n\t\t# Preserve only the top players\n\t\tself._TopPerformers = copy.deepcopy(self._TopPerformers[:self._PreservationSize])\n\t\t# Kill off the rest\n\t\tself._CurrentPerformers = self._TopPerformers\n\t\tprint(\" ] Highest traders {}-{}\".format(len(self._TopPerformers), [(e._iId,e._iDeltaValue) for e in self._TopPerformers[:4]]))\n\t\tpp=pprint.PrettyPrinter(indent=1, depth=2)\n\t\tprint(\" ] Best Performer:\")\n\t\tpp.pprint(self._TopPerformers[0].Details())\n\t\tprint(\"\")\n\t\tfor e in self._TopPerformers:\n\t\t\te.Reset()\n\t\t\n\t\tpass\n\t\t\nif __name__ == \"__main__\":\n\trandom.seed()\n\ttest = cDNA()\n\ttest.InitGenePool(4, False)\n\ttest.AttemptMutation(.02)\n\t","sub_path":"most-complex-project/Kinix-master/_modules/evolution/indicatorDetails.py","file_name":"indicatorDetails.py","file_ext":"py","file_size_in_byte":19059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"162141739","text":"#This script downloads disease statistics from data.gov.sg\n#download for the month.\n\nimport sys\nimport os\nimport json\nimport csv\nimport logging\n\nlogger = logging.getLogger()\nlogger.addHandler(logging.NullHandler())\n\nDIRECTORY = '../../Data/raw/disease_SG'\nOUTFILE = \"../../Data/raw/disease_SG/weekly-dengue-malaria.csv\"\nDISEASE_LIST = [\"Dengue Fever\", \"Dengue Haemorrhagic Fever\", \"Malaria\"]\n\nURL = 'https://data.gov.sg/api/action/datastore_search?resource_id=ef7e44f1-9b14-4680-a60a-37d2c9dda390&limit=10000'\n \ndef download():\n \"\"\"Download disease data from data.gov.sg\"\"\"\n logger.info('Downloading raw weekly SG Dengue and Malaria data')\n \n # Python 2\n if sys.version_info < (3, 0):\n try:\n os.makedirs(DIRECTORY)\n except OSError as e:\n pass\n \n import urllib2\n\n request = urllib2.Request(URL, headers={'User-Agent' : \"Magic Browser\"})\n fileobj = urllib2.urlopen(request)\n \n temp=json.loads(fileobj.read())\n with open(OUTFILE, 'wb') as csvfile:\n logger.debug('py2: open file for writing')\n writethis = csv.writer(csvfile, delimiter=',')\n writethis.writerow([\"epi_week\",\"disease\",\"no_of_cases\"])\n for i in temp[\"result\"][\"records\"]:\n if i[\"disease\"] in DISEASE_LIST:\n writethis.writerow([i[\"epi_week\"], i[\"disease\"], i[\"no._of_cases\"]])\n # Python 3\n else:\n os.makedirs(DIRECTORY, exist_ok=True)\n import requests\n \n fileobj = requests.get(URL)\n temp=json.loads(fileobj.text)\n \n with open(OUTFILE, 'w', newline='') as csvfile:\n logger.debug('py3: open file for writing')\n writethis = csv.writer(csvfile, delimiter=',')\n writethis.writerow([\"epi_week\",\"disease\",\"no_of_cases\"])\n for i in temp[\"result\"][\"records\"]:\n if i[\"disease\"] in DISEASE_LIST:\n writethis.writerow([i[\"epi_week\"], i[\"disease\"], i[\"no._of_cases\"]])\n logger.info('Finished downloading raw SG data')\n return\n \nif __name__ == '__main__':\n import logging.config\n logging.config.fileConfig('logconf.ini')\n DIRECTORY = '../../../Data/raw/disease_SG'\n OUTFILE = \"../../../Data/raw/disease_SG/weekly-dengue-malaria.csv\"\n download()","sub_path":"src/data/download/SG_disease.py","file_name":"SG_disease.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"138447109","text":"# -*- coding: UTF-8 -*-\nimport re\nimport locale\nimport json\nfrom flask_jwt_extended import ( create_access_token )\n\nfrom .dates import token_expires\n\nLANGUAGE_CODES = [ \"en\", \"ja\", \"vi\" ]\ndef to_locale(language, to_lower=False):\n p = language.find('-')\n if p >= 0:\n if to_lower:\n return language[:p].lower()+'_'+language[p+1:].lower()\n else:\n # Get correct locale for sr-latn\n if len(language[p+1:]) > 2:\n return language[:p].lower()+'_'+language[p+1].upper()+language[p+2:].lower()\n return language[:p].lower()+'_'+language[p+1:].upper()\n else:\n return language.lower()\n\ndef parse_accept_lang_header(lang_string):\n accept_language_re = re.compile(r'''\n ([A-Za-z]{1,8}(?:-[A-Za-z]{1,8})*|\\*) # \"en\", \"en-au\", \"x-y-z\", \"*\"\n (?:\\s*;\\s*q=(0(?:\\.\\d{,3})?|1(?:.0{,3})?))? # Optional \"q=1.00\", \"q=0.8\"\n (?:\\s*,\\s*|$) # Multiple accepts per header.\n ''', re.VERBOSE)\n\n result = []\n pieces = accept_language_re.split(lang_string)\n if pieces[-1]:\n return []\n for i in range(0, len(pieces) - 1, 3):\n first, lang, priority = pieces[i : i + 3]\n if first:\n return []\n priority = priority and float(priority) or 1.0\n result.append((lang, priority))\n result.sort(key=lambda k: k[1], reverse=True)\n return result\n\ndef normalize_language(language):\n return locale.locale_alias.get(to_locale(language, True))\n\ndef is_language_supported(language, supported_languages=None):\n if supported_languages is None:\n supported_languages = LANGUAGE_CODES\n if not language:\n return None\n normalized = normalize_language(language)\n if not normalized:\n return None\n # Remove the default encoding from locale_alias.\n normalized = normalized.split('.')[0]\n for lang in (normalized, normalized.split('_')[0]):\n if lang.lower() in supported_languages:\n return lang\n return None\n\ndef parse_http_accept_language(accept):\n for accept_lang, unused in parse_accept_lang_header(accept):\n if accept_lang == '*':\n break\n\n normalized = locale.locale_alias.get(to_locale(accept_lang, True))\n if not normalized:\n continue\n # Remove the default encoding from locale_alias.\n normalized = normalized.split('.')[0]\n\n for lang_code in (accept_lang, accept_lang.split('-')[0]):\n lang_code = lang_code.lower()\n if lang_code in LANGUAGE_CODES:\n return lang_code\n return None\n\nclass UserAgent():\n def __init__(self, req):\n self.host = req.host\n self.path = req.path\n self.method = req.method\n self.remote_addr = req.remote_addr\n self.user_agent = req.user_agent\n self.cookies = req.cookies\n self.accept_languages = req.accept_languages\n self.username = self.set_username(req)\n self.auth = self.set_auth(req.authorization)\n self.api_key = self.set_api_key(req.form.get('apikey', None))\n self.api_token = self.set_api_bearer(req.headers.get('authorization', None))\n\n def set_username(self, req): \n if req.json is not None:\n return req.json.get('username')\n else:\n return req.form.get('username')\n\n def set_auth(self, auth): \n if auth is not None:\n return auth\n else:\n return None\n\n def set_api_key(self, key):\n if key is not None:\n return key\n else:\n return None\n\n def set_api_bearer(self, bearer):\n if bearer is not None and bearer[:5] != 'token' and bearer[:6] != 'Bearer':\n return bearer.replace('Bearer ', '')\n\n # def set_api_token(self, token):\n # if token is not None:\n # self.api_token = token\n\n def set_session_user(self):\n obj = {}\n obj['username'] = self.username\n obj['api_key'] = self.api_key\n obj['api_token'] = self.api_token\n obj['accept_languages'] = str(self.accept_languages)\n return obj\n\n def to_json(self):\n obj = {}\n obj['username'] = self.username\n obj['auth'] = self.auth\n obj['api_key'] = self.api_key\n obj['api_token'] = self.api_token\n obj['host'] = self.host\n obj['path'] = self.path\n obj['method'] = self.method\n obj['remote_addr'] = self.remote_addr\n obj['user_agent'] = str(self.user_agent)\n obj['cookies'] = self.cookies\n obj['accept_languages'] = str(self.accept_languages)\n return obj","sub_path":"utils/cm/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":4666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"525483387","text":"#CTI-110\r\n#P2T1 - Sales Prediction\r\n#Lucas Porter\r\n#June 8th, 2018\r\n\r\n#Get user input for total sales.\r\ntotal_sales = float(input('What was your annual sales?: '))\r\n\r\n#Profit margin is estimated to be 35 percent total.\r\nprofit = total_sales * .35\r\n\r\n#Adding the profit to total sales for net total.\r\nnet_total = total_sales + profit\r\n\r\n#Displaying calculation of the profit and net total.\r\nprint('Your forecasted profit is', profit)\r\nprint('Your net total is', net_total)\r\n","sub_path":"P2T1_SalesPrediction_PorterLucas.py","file_name":"P2T1_SalesPrediction_PorterLucas.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"543718699","text":"\"\"\"\n下面的文件将会从csv文件中读取读取短信与电话记录\n\"\"\"\nimport csv\n\nwith open('texts.csv', 'r') as f:\n reader = csv.reader(f)\n texts = list(reader)\n\nwith open('calls.csv', 'r') as f:\n reader = csv.reader(f)\n calls = list(reader)\n\n\n\"\"\"\n任务1:\n短信和通话记录中一共有多少电话号码?每个号码只统计一次。\n\"\"\"\n\n\ndef get_diff_phone_num(data, phone_index):\n phones = set()\n for item in data:\n for index in phone_index:\n phones.add(item[index])\n\n return len(phones)\n\n\ntotal = get_diff_phone_num(texts, [0, 1]) + get_diff_phone_num(calls, [0, 1])\n\nprint(\"There are {} different telephone numbers in the records.\".format(total))\n","sub_path":"chaoyang/P1/investigate_texts_and_calls/Task1.py","file_name":"Task1.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"460498021","text":"import numpy as np\nfrom scipy.stats import norm\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n# from matplotlib import rc\n# rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})\n\nnp.random.seed(11)\nnp.set_printoptions(precision=1,linewidth=94,threshold=1000)\n\n# Initialize physical model parameters \nTX_POWER = 1000 # Transmit power of access points in milliwatts\nTX_DIRECTIVITY = 1 # Directivity of transmitting antenna (one for isotropic)\nRX_DIRECTIVITY = 1 # Directivity of recieving antenna (one for isotropic)\nHALL_HEIGHT = 5 # Height of hall in meters\nHALL_LENGTH = 40 # Length of hall in meters\nNUM_ACCESS_POINTS = 5 # Number of access points visible in the hallway\nNUM_LOCATIONS = 20 # Number of locations to distinguish from\nFREQUENCY = 2.4e6 # Frequency of wifi in Hertz\n\nLAMBDA = 3e8/FREQUENCY # Wavelength of wifi in meters\n\n# Initialize probabilistic model parameters\nPOWER_NOISE_STD_DEV = 500 # Standard deviation of normally distributed noise\n\n# Initialize operational model parameters\nPLOT_STEP = 0.01\nPLOT_ALL = True\nTEST_LOCATION = 24.1 # np.random.uniform(0,HALL_LENGTH)\n\n# Generate vector for access point locations\naccessPoints = np.sort(np.round(10*HALL_LENGTH*np.random.rand(NUM_ACCESS_POINTS))/10)\nprint(\"Access Point Locations: \", accessPoints,sep='')\nprint(\"Standard Deviation of Noise: \", POWER_NOISE_STD_DEV, \" milliwatts\",sep='')\n# hall = np.linspace(0,HALL_LENGTH,NUM_LOCATIONS)\n\n# Function to generate data at a given location using the Friis equation with Rayleigh-distributed noise\ndef generateSignal(location, accessPointLocations):\n d = np.sqrt(np.power(accessPointLocations-location,2) + np.power(HALL_HEIGHT, 2))\n noise = np.random.normal(0,POWER_NOISE_STD_DEV)\n # E_field = np.sqrt(TX_POWER*TX_DIRECTIVITY*RX_DIRECTIVITY/2)*(LAMBDA/(4*np.pi*d))\n signalPowerVector = TX_POWER*TX_DIRECTIVITY*RX_DIRECTIVITY*np.power(LAMBDA/(4*np.pi*d),2) + noise\n # print(signalPowerVector)\n # randVect = np.random.rand(NUM_ACCESS_POINTS)\n # print(randVect)\n # print(signalPowerVector*(1*(np.random.rand(NUM_ACCESS_POINTS) <= 0.6)))\n for i in range(NUM_ACCESS_POINTS):\n if (np.random.rand() <= dropOutProbability(d[i])):\n signalPowerVector[i] = 0\n print(\"Signal received: \", signalPowerVector, sep='')\n return abs(signalPowerVector) # 10*np.log10(signalPower)\n\n\ndef dropOutProbability(distance):\n prob = np.power(distance/15,8)\n if prob > 1:\n prob = 1\n return prob\n\n# Function to get the probabilty of seeing a certain signal strength at a location\ndef signalProbability(receivedSignal, location, accessPointLocations, accessPointLocationNumber):\n d = np.sqrt(np.power(accessPointLocations[accessPointLocationNumber]-location,2) + np.power(HALL_HEIGHT, 2))\n if (receivedSignal != 0):\n signalPower = TX_POWER*TX_DIRECTIVITY*RX_DIRECTIVITY*np.power(LAMBDA/(4*np.pi*d),2)\n powerDifference = -abs(receivedSignal - signalPower)\n prob = norm.pdf(powerDifference,scale=POWER_NOISE_STD_DEV)\n prob = prob*(1-dropOutProbability(d))\n else:\n prob = dropOutProbability(d)\n return prob\n\n\n# Function to generate probability distribution given data from sensor\ndef locationProbability(receivedSignalVector, accessPointLocations, plotDistribution=False, plotAll=False):\n hallwayPoints = np.arange(0, HALL_LENGTH, PLOT_STEP)\n probabilityMatrix = np.zeros((len(hallwayPoints),NUM_ACCESS_POINTS))\n for i in range(len(hallwayPoints)):\n for j in range(NUM_ACCESS_POINTS):\n probabilityMatrix[i][j] = signalProbability(receivedSignalVector[j],hallwayPoints[i],accessPointLocations,j)\n probabilityDistribution = np.prod(probabilityMatrix,axis=1)\n probabilityDistribution = probabilityDistribution/(PLOT_STEP*np.sum(probabilityDistribution))\n if (plotDistribution):\n plt.plot(hallwayPoints,probabilityDistribution,label='Probability',color='red')\n plt.axvline(x=TEST_LOCATION,color='k',linestyle='--',label='True Location')\n if (plotAll):\n for i in range(NUM_ACCESS_POINTS):\n line, = plt.plot(hallwayPoints,probabilityMatrix[:,i]/(PLOT_STEP*np.sum(probabilityMatrix[:,i])),label=('Access Point ' + str(i)))\n plt.plot(accessPointLocations[i], max(probabilityDistribution), '.', color=line.get_color())\n else:\n plt.plot(accessPoints,np.ones(NUM_ACCESS_POINTS)*max(distribution),'.',label='Access Points')\n plt.title('Probability Distribution Across the Hallway with Power Noise StdDev = ' + str(POWER_NOISE_STD_DEV) + ' mW')\n plt.xlabel('Hallway Position (m)')\n plt.ylabel('Probability Density')\n plt.legend(loc='lower left', shadow=True)\n return probabilityDistribution\n\n\n\nprint(\"Test Location: \", TEST_LOCATION, sep='')\ndistribution = locationProbability(generateSignal(TEST_LOCATION,accessPoints),accessPoints,plotDistribution=True,plotAll=PLOT_ALL)\n\nplt.show()\n","sub_path":"Trevin/Models/InterpolationModelPowerNoiseWithDropouts.py","file_name":"InterpolationModelPowerNoiseWithDropouts.py","file_ext":"py","file_size_in_byte":5010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"84"} +{"seq_id":"377427744","text":"from flask import Flask, jsonify\nfrom .history import history as hist\nfrom .api_funcs import *\n\n\ndef create_app():\n app = Flask(__name__)\n\n source_message = 'Please select either USGS or EMSC as source'\n\n @app.route('/')\n def home():\n return jsonify({'status_code': 200,\n 'message': 'success, the flask API is running'})\n\n @app.route('/lastQuake//')\n @app.route('/lastQuake///')\n @app.route('/lastQuake///')\n def lastQuake(source, mag=5.5):\n CONN = connect()\n # sanitize inputs\n if mag < 0 or mag > 11:\n return jsonify({'status_code': 400, 'message':\n 'please enter a magnitude between 0 and 11'})\n # check to make sure that source is valid\n if source.upper() not in ['USGS', 'EMSC']:\n return jsonify({'status_code': 400,\n 'message': source_message})\n curs = CONN.cursor()\n response = curs.execute(f'''\n SELECT * FROM {source}\n WHERE Magnitude >= {mag}\n ORDER BY Time Desc\n limit 1;\n ''')\n quake = curs.fetchone()\n curs.close()\n CONN.commit()\n CONN.close()\n num_quakes = 1 if quake is not None else 0\n response = prep_response(quake, source) if quake is not None \\\n else f'No quakes of magnitude {mag} or higher in {source.upper()}'\n return jsonify({'status_code': 200, 'message': response, 'num_quakes': num_quakes})\n\n @app.route('/last//