')[0]\n reportDateList = reportDateStr.split(' ') \n lastReportDate = reportDateList[0]\n seasonsNCurrentyear = len(netProfit_List)\n netProfitCurrentYear = float(netProfit_List[0])\n else:\n netProfitEachStock = float(netProfit_List[0]) - float(netProfit_List[4 - seasonsNCurrentyear]) + netProfitCurrentYear\n except Exception as e:\n errorCode.add(code)\n continue\n df = df.append(pd.DataFrame([[code, lastReportDate, netProfitEachStock]], columns=dfCols),ignore_index=True)\nprint(errorCode)\nprint(df.to_csv(dirStock+'/FinancialIndex.csv'))\n\n\n\n\n\n\n\n\n","sub_path":"machine_learning/stock/backup/Save_FinancialIndex.py","file_name":"Save_FinancialIndex.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"58012198","text":"\"\"\"Collapse fastq files into unique reads for subsequent alignment.\n\nThis helps manage complexity on highly redundant datasets.\n\"\"\"\nimport subprocess\n\nfrom bcbio.utils import (memoize_outfile, tmpfile)\n\n@memoize_outfile(\"-unique.txt\")\ndef uniquify_bioplayground(in_fastq, config, out_file):\n \"\"\"Uniquify fastq file using Brent Pedersen's C++ fastq program.\n\n https://github.com/brentp/bio-playground/tree/master/reads-utils\n \"\"\"\n cl = [config[\"program\"][\"uniquify\"], \"filter\",\n \"--n\", str(config[\"algorithm\"][\"allowed_ns\"]),\n \"--unique\", in_fastq]\n with open(out_file, \"w\") as out_handle:\n subprocess.check_call(cl, stdout=out_handle)\n return out_file\n","sub_path":"jl_hiv/bcbio/fastq/unique.py","file_name":"unique.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"420383359","text":"\nimport sys\nfrom rot13 import rot13\n\ndef test_rot13_file_read_completely_into_memory():\t\n\tr = []\n\twith open(\"rotfile.txt\", \"r\") as f:\n\t\tdata = f.read()\n\t\tfor x in data:\n\t\t\tif x == '\\n':\n\t\t\t\tr += \"\\n\"\n\t\t\telse:\n\t\t\t\tr += rot13(x)\n\treturn str(\"\".join(r))\t\t\n\t\nexpected = \"NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm\\nGur Dhvpx Oebja Sbk Whzcf Bire Gur Ynml Qbt\\nYn Encvqn Mbeen Pnsr Oevapn Rapvzn qry Creeb Sybwb\\n\"\n\nassert test_rot13_file_read_completely_into_memory() == expected\n\n# result = test_rot13_file_read_completely_into_memory()\n# print(result == expected)\n","sub_path":"test_rot13_file_read_completely_into_memory.py","file_name":"test_rot13_file_read_completely_into_memory.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"192314223","text":"# Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя:\n# имя, фамилия, год рождения, город проживания, email, телефон.\n# Функция должна принимать параметры как именованные аргументы.\n# Реализовать вывод данных о пользователе одной строкой\n\ndef private_def ():\n list_1 = list(input('Введите через пробел имя, фамилию, год рождения, город проживания, почту, телефон: ').split())\n first_name = list_1[0]\n second_name = list_1[1]\n birth = list_1[2]\n town = list_1[3]\n mail = list_1[4]\n number = list_1[5]\n return first_name, second_name, birth, town, mail, number\n\nfirst_name_val, second_name_val, birth_val, town_val, mail_val, number_val = private_def()\nprint(first_name_val, second_name_val, birth_val, town_val, mail_val, number_val)","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"11663967","text":"import cv2\nimport os\nfrom config import *\n\ndef draw_points(lands, img, img_name, save_dir):\n for i in range(0, len(lands), 2):\n point = (lands[i], lands[i+1])\n cv2.circle(img, point, 1, (255, 0, 0))\n result_name = \"result_\"+img_name\n print(result_name)\n save_path = os.path.join(save_dir, result_name)\n print(save_path)\n cv2.imwrite(save_path, img)\n print('done')\n\n\nif __name__ == '__main__':\n\n read_from_file = False\n img_path = './test_images/webwxgetmsgimg.png'\n image_txt = \"./image_names.txt\"\n image_dir = \"./data/images/\"\n resize_save_dir = \"./results/\"\n\n if read_from_file == True:\n with open(image_txt, 'r') as fin:\n for line in fin:\n line = line.strip.split(\" \")\n image_name = line[0]\n land_marks = line[-1]\n img_path = os.path.join(image_dir, image_name)\n img = cv2.imread(img_path)\n img_resize = cv2.resize(img, args.height, args.width)\n draw_points(land_marks, img_resize, image_name)\n\n else:\n img = cv2.imread(img_path)\n img = cv2.resize(img, (300, 300), interpolation=cv2.INTER_AREA)\n #lands = [47, 30, 65, 31, 58, 38, 46, 43, 64, 43]\n #location :(140.268341,202.364410,161.242096,261.564728),\n #[Point(144, 100), Point(173, 100), Point(158, 112), Point(144, 119), Point(173, 117)]\n #Point(113, 151), Point(131, 151), Point(124, 169), Point(115, 179), Point(131, 179)]\n\n lands = [113,151,131,151,124,169,115,179,131,179]\n\n lands = [int(i) for i in lands]\n print('lands', lands)\n image_name = img_path.split(\"/\")[-1]\n print(type(image_name))\n draw_points(lands, img, image_name, resize_save_dir)\n\n","sub_path":"landmark/draw_points.py","file_name":"draw_points.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"163037838","text":"import os\nimport sys\nimport argparse\nimport glob\n\ndef _check_and_get_args(args=None):\n parser = argparse.ArgumentParser(description='Histograms generator')\n parser.add_argument('-ET', '--encryptiontype', help='encryption type (EC/AES)', default='EC', required=True, type=_restricted_encryption_types)\n results = parser.parse_args(args)\n return results.encryptiontype\n\ndef _restricted_encryption_types(enc_type):\n if not (enc_type == 'AES' or enc_type == 'CE'):\n raise argparse.ArgumentTypeError(\"Chosen encryption type is correct.\")\n return enc_type\n\n# -------------------------------------------------------\n\nif not \"MSC_HOME\" in os.environ:\n print(\"Environment variables like $MSC_HOME are not set.\")\n exit(1)\n\nencryption_type = _check_and_get_args(sys.argv[1:]) # AES/CE\n\nos.system(f\"rm -rf {encryption_type}\")\nos.system(f\"mkdir {encryption_type}\")\nos.system(f\"mkdir {encryption_type}/test_images\")\n\nsample_paths = os.environ['MSC_SAMPLES'].replace('\\n', '').split(',')\n\nfor sample_path in sample_paths:\n#01 kluczkluczkluczkluczkluczkluczkl\n#02 abcdefghijklmnopqrstuwxyz1234567\n#03 syf1W7dTap3NxJlNy1b09sotPn4DxSzH\n\n#04 U9Dm6dPvda7HDvxwqeS5B5qzFrJySOXN\n#05 jpDwN5bYOos8UXH45JqkkteY37f8xdMu\n#06 8iEr95Odq4rFYB6OomAgHRwK3zowbFqI\n#07 G7WKTR67SSEGL4jDgg8H230wJs5hl9xm\n#08 UDvFCd3ySr0INlJw2odpAfpEaSzycW7s\n#09 HZ3csaIJS5cgeSx5kOLrsQi1B9C0BxGL\n#10 gWt7kvXsM0zsPFdnWANiTRm0ehK7Ofm8\n#11 2D7dS5AacFUacFuI1ZuHs9c4NseELNWm\n#12 8CiP9eDBjPkcPJuUfWdtf4VTf3NcDxdm\n#13 4aAhuKrXnmDRjUCy2CEc37pBlJRlqf3j\n#14 7anDe0VfGSpisz3CnRaITIBWUnOvxNgh\n#15 MsLqyR4Pd41x5vNj0RSAhYXAAqPttkby\n#16 XtACMWr0fWw808mpN35JtZUXEZsO4NUp\n#17 BhTAZkIZt6uDmvoivyOizMRum9W357Be\n#18 tyLkLSHyCMgWq2jVry8VT45Y922UeZXs\n#19 s9iMBD3Rhor9FCVhEeeHPRVo61GRrvMa\n#20 4L62RKcuF8OLC3XlpPzFVE4YEqTtkKgo\n os.system(f\"{encryption_type}.py --source {sample_path} --destination {encryption_type}/test_images --key syf1W7dTap3NxJlNy1b09sotPn4DxSzH\")\n\nencrypted_images = glob.glob(f\"{encryption_type}/test_images/*.png\")\n\nfor encrypted_image in encrypted_images:\n os.system(f\"python ./sp800_22_tests/sp800_22_tests.py {encrypted_image} > {encryption_type}/{os.path.basename(encrypted_image)}.txt\")\n\n\n\n\n\n","sub_path":"research_programs/NIST/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"294123890","text":"#Data Structures: The Stack\r\n\r\nclass Stack:\r\n \r\n #constructor\r\n def __init__(self):\r\n self.items = []\r\n\r\n def push(self, item):\r\n self.items.append(item)\r\n\r\n def pop(self):\r\n return self.items.pop()\r\n\r\n def size(self):\r\n return len(self.items)\r\n\r\n def peek(self):\r\n return self.items[len(self.items) - 1]\r\n\r\n def isEmpty(self):\r\n return len(self.items)==0\r\n\r\ndef main():\r\n #create empty stack\r\n someStack = Stack()\r\n someStack.push(\"Mary\")\r\n someStack.push(\"Bill\")\r\n someStack.push(\"Joe\")\r\n\r\n print('The stack has ', someStack.size(), 'items')\r\n \r\n for i in range(someStack.size()):\r\n print(someStack.pop())\r\n\r\n print('The stack has ', someStack.size(), 'items')\r\n\r\ndef parenthesesCheck(someString):\r\n parentheses = Stack()\r\n balanced = True\r\n index = 0\r\n\r\n while index < len(someString) and balanced:\r\n if someString[index] == '(':\r\n parentheses.push(someString[index])\r\n else:\r\n if parentheses.isEmpty():\r\n balanced = False\r\n else:\r\n parentheses.pop()\r\n index = index + 1\r\n\r\n if balanced and parentheses.isEmpty():\r\n return True\r\n else:\r\n return False\r\n\r\nparenthesesCheck('((())())))))')\r\n\r\ndef removeValues(someString):\r\n s = ''\r\n for i in range(len(someString)):\r\n if someString[i] == '(' or someString[i] == ')':\r\n s = s + someString[i]\r\n\r\n return s\r\n\r\nprint(parenthesesCheck(removeValues('(6+9+(((5+8)-3)')))\r\nprint(parenthesesCheck(\"(((())\"))\r\nprint(parenthesesCheck(\"()\"))\r\n","sub_path":"Lecture 9-20-18.py","file_name":"Lecture 9-20-18.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"456054954","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#------------------------------------------------------------------------------\n__author__ = 'Patrice Carbonneau'\n__contact__ = 'patrice.carbonneau@durham.ac.uk'\n__copyright__ = '(c) Patrice Carbonneau'\n__license__ = 'MIT'\n\n\n'''\n\nThis script will attempt to train a fuzzy classifier with endmembers infered from manual digitisation.\nIt is assumed that the image interpretation process will lead the user to digitise pure classes.\nThe pure class rasters are then transformed to categorical (1-hot encoding) which in effect means\nthat the digitised class pixels will be assigned a pure membership.\n\nThis script will use tis information in a DNN. The script will only train and save the model.\nUse UAV2SEN_GetErrorsDNN to estiate associated errors.\n\n\n\n'''\n###############################################################################\n\"\"\" Libraries\"\"\"\n\nfrom tensorflow.keras import regularizers\nfrom tensorflow.keras import optimizers\nimport numpy as np\nimport pandas as pd\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, BatchNormalization\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom skimage.transform import downscale_local_mean, resize\nfrom skimage import io\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\nimport matplotlib.patches as mpatches\nimport os\n\n\n\n\n##########################################################################################\n\"\"\"User data input. Use the site template and list training and validation choices\"\"\"\n#########################################################################################\n'''Folder Settgings'''\nMainData = 'EMPTY' #main data output from UAV2SEN_MakeCrispTensor.py. no extensions, will be fleshed out below\nSiteList = 'EMPTY'#this has the lists of sites with name, month, year and 1s and 0s to identify training and validation sites\nDataFolder = 'EMPTY' #location of processed tif files\nModelName = 'EMPTY' #Name and location of the final model to be saved in DataFolder. Add .h5 extension\n\n'''Model Features and Labels'''\nUAVtrain = False #if true use the UAV class data to train the model, if false use desk-based data for training\nMajType= 'Pure' #Majority type. only used if UAVtrain or valid is true. The options are RelMaj (relative majority class), Maj (majority) and Pure (95% unanimous).\nFeatureSet = ['B2','B3','B4','B5','B6','B7','B8','B9','B11','B12'] # pick predictor bands from: ['B1','B2','B3','B4','B5','B6','B7','B8','B9','B10','B11','B12']\n\n'''CNN parameters'''\nTrainingEpochs = 200#Use model tuning to adjust this and prevent overfitting\nsize=3#size of the tensor tiles\nKernelSize=3 # size of the convolution kernels\nLearningRate = 0.0005\nChatty = 1 # set the verbosity of the model training. \nNAF = 'relu' #NN activation function\nModelTuning = False #Plot the history of the training losses. Increase the TrainingEpochs if doing this.\n\n'''Validation Settings'''\nUAVvalid = True #if true use the UAV class data to validate. If false, use desk-based polygons\nShowValidation = False #if true will show predicted class rasters for validation images from the site list\n\n\n\n\n\n\n#################################################################################\n'''Function definitions'''\ndef slide_raster_to_tiles(im, size):\n h=im.shape[0]\n w=im.shape[1]\n di=im.shape[2]\n TileTensor = np.zeros(((h-size)*(w-size), size,size,di))\n\n \n B=0\n for y in range(0, h-size):\n for x in range(0, w-size):\n\n TileTensor[B,:,:,:] = im[y:y+size,x:x+size,:]\n B+=1\n\n return TileTensor\n######################################################################################\n \n '''Check that the specified folders and files exist before processing starts'''\nif not(os.path.isfile(MainData+'_fuzzy_'+str(size)+'_T.npy')):\n raise Exception('Main data file does not exist')\nelif not(os.path.isfile(SiteList)):\n raise Exception('Site list csv file does not exist')\nelif not(os.path.isdir(DataFolder)):\n raise Exception('Data folder with pre-processed data not defined')\n\n\n\n'''Load the tensors and filter out the required training and validation data.'''\nTensorFileName = MainData+'_crisp_'+str(size)+'_T.npy'\nLabelFileName = MainData+'_crisp_'+str(size)+'_L.csv'\n\nSiteDF = pd.read_csv(SiteList)\nMasterTensor = np.load(TensorFileName)\nMasterLabelDF=pd.read_csv(LabelFileName)\n\n#Select the features in the tensor\n\nValid=np.zeros(12)\nfor n in range(1,13):\n if ('B'+str(n)) in FeatureSet:\n Valid[n-1]=1\n \nMasterTensor = np.compress(Valid, MasterTensor, axis=3)\n\n\n#Start the filter process to isolate training and validation data\nTrainingSites = SiteDF[SiteDF.Training == 1]\nValidationSites = SiteDF[SiteDF.Validation == 1]\nTrainingSites.index = range(0,len(TrainingSites.Year))\nValidationSites.index = range(0,len(ValidationSites.Year))\n#initialise the training and validation DFs to the master\nTrainingDF = MasterLabelDF\nTrainingTensor = MasterTensor\nValidationDF = MasterLabelDF\nValidationTensor = MasterTensor\n\n#isolate the sites, months and year and isolate the associated tensor values\nMasterValid = (np.zeros(len(MasterLabelDF.index)))==1\nfor s in range(len(TrainingSites.Site)):\n Valid = (TrainingDF.Site == TrainingSites.Abbrev[s])&(TrainingDF.Year==TrainingSites.Year[s])&(TrainingDF.Month==TrainingSites.Month[s])\n MasterValid = MasterValid | Valid\n \nTrainingDF = TrainingDF.loc[MasterValid]\nTrainingTensor=np.compress(MasterValid,TrainingTensor, axis=0)#will delete where valid is false\n\nMasterValid = (np.zeros(len(MasterLabelDF.index)))==1\nfor s in range(len(ValidationSites.Site)):\n Valid = (ValidationDF.Site == ValidationSites.Abbrev[s])&(ValidationDF.Year==ValidationSites.Year[s])&(ValidationDF.Month==ValidationSites.Month[s])\n MasterValid = MasterValid | Valid\n \nValidationDF = ValidationDF.loc[MasterValid]\nValidationTensor = np.compress(MasterValid,ValidationTensor, axis=0)#will delete where valid is false \n\n \nMajType=MajType+'Class'\n\n\n#select desk-based or UAV-based for training and validation, if using UAV data, select the majority type\nif UAVtrain & UAVvalid:\n TrainLabels= TrainingDF[MajType]\n ValidationLabels = ValidationDF[MajType]\n TrainingTensor = np.compress(TrainLabels>0, TrainingTensor, axis=0)\n ValidationTensor = np.compress(ValidationLabels>0,ValidationTensor, axis=0)\n TrainLabels=TrainLabels.loc[TrainLabels>0]\n ValidationLabels=ValidationLabels.loc[ValidationLabels>0]\n \n \nelif UAVtrain and ~(UAVvalid):\n TrainLabels= TrainingDF[MajType]\n ValidationLabels = ValidationDF.PolyClass\n TrainingTensor = np.compress(TrainLabels>0, TrainingTensor, axis=0)\n ValidationTensor = np.compress(ValidationLabels>0,ValidationTensor, axis=0)\n TrainLabels=TrainLabels.loc[TrainLabels>0]\n ValidationLabels=ValidationLabels.loc[ValidationLabels>0]\n \nelif ~(UAVtrain) & UAVvalid:\n TrainLabels= TrainingDF.PolyClass\n ValidationLabels = ValidationDF[MajType]\n TrainingTensor = np.compress(TrainLabels>0, TrainingTensor, axis=0)\n ValidationTensor = np.compress(ValidationLabels>0,ValidationTensor, axis=0)\n TrainLabels=TrainLabels.loc[TrainLabels>0]\n ValidationLabels=ValidationLabels.loc[ValidationLabels>0]\n \n#\nelse:\n TrainLabels= TrainingDF.PolyClass\n ValidationLabels = ValidationDF.PolyClass\n TrainingTensor = np.compress(TrainLabels>0, TrainingTensor, axis=0)\n ValidationTensor = np.compress(ValidationLabels>0,ValidationTensor, axis=0)\n TrainLabels=TrainLabels.loc[TrainLabels>0]\n ValidationLabels=ValidationLabels.loc[ValidationLabels>0]\n \n#Select the central pixel in each tensor tile and make a table for non-convolutional NN classification\nTrainingFeatures = np.squeeze(TrainingTensor[:,size//2,size//2,:])\nValidationFeatures = np.squeeze(ValidationTensor[:,size//2, size//2,:]) \n \n#check for empty dataframes and raise an error if found\n\nif (len(TrainingDF.index)==0):\n raise Exception('There is an empty dataframe for training')\n \nif (len(ValidationDF.index)==0):\n raise Exception('There is an empty dataframe for validation')\n \n#Check that tensor lengths match label lengths\n\nif (len(TrainLabels.index)) != TrainingTensor.shape[0]:\n raise Exception('Sample number mismatch for TRAINING tensor and labels')\n \nif (len(ValidationLabels.index)) != ValidationTensor.shape[0]:\n raise Exception('Sample number mismatch for VALIDATION tensor and labels')\n \n \n\n \n\n\n\n\n\n##############################################################################\n\"\"\"Instantiate the Neural Network pixel-based classifier\"\"\" \nNdims = TrainingFeatures.shape[1] # Feature Dimensions. \nNClasses = len(np.unique(TrainLabels)) #The number of classes in the data. This MUST be the same as the classes used to retrain the model\n\n\n \t# create model\n \nEstimator = Sequential()\nEstimator.add(Dense(64, kernel_regularizer= regularizers.l2(0.001),input_dim=Ndims, kernel_initializer='normal', activation=NAF))\nEstimator.add(BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001, center=True, scale=True, beta_initializer='zeros', gamma_initializer='ones', moving_mean_initializer='zeros', moving_variance_initializer='ones', beta_regularizer=None, gamma_regularizer=None, beta_constraint=None, gamma_constraint=None))\nEstimator.add(Dense(32, kernel_regularizer= regularizers.l2(0.001), kernel_initializer='normal', activation=NAF))\nEstimator.add(Dense(16, kernel_regularizer= regularizers.l2(0.001), kernel_initializer='normal', activation=NAF))\nEstimator.add(Dense(NClasses+1, kernel_initializer='normal', activation='linear')) \n\n\n\n#Tune an optimiser\nOptim = optimizers.Adam(lr=LearningRate, beta_1=0.9, beta_2=0.999, decay=0.0, amsgrad=True)\n\n# Compile model\nEstimator.compile(loss='mean_squared_error', optimizer=Optim, metrics = ['accuracy'])\nEstimator.summary()\n \n###############################################################################\n\"\"\"Data Splitting\"\"\"\nTrainLabels1Hot = to_categorical(TrainLabels)\nValidationLabels1Hot = to_categorical(ValidationLabels)\nX_train, X_test, y_train, y_test = train_test_split(TrainingFeatures, TrainLabels1Hot, test_size=0.2, random_state=42)\n\n\n\n\"\"\"Data Fitting\"\"\"\nprint('Fitting CNN Classifier on ' + str(len(X_train)) + ' pixels')\nEstimator.fit(X_train, y_train, batch_size=1000, epochs=TrainingEpochs, verbose=Chatty)\n\n\n\n'''Save model'''\nModelName=os.path.join(DataFolder,ModelName+'.h5')\nEstimator.save(ModelName,save_format='h5')\n","sub_path":"code/UAV2SEN_CrispendMemberDNN.py","file_name":"UAV2SEN_CrispendMemberDNN.py","file_ext":"py","file_size_in_byte":10621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"392899700","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n Carga la configuración de Domus.\n Busca el fichero domus.conf en la misma ruta que domus.py.\n De no existir el archivo .conf, hay un archivo de ejemplo.\n\"\"\"\n\nimport configparser\nimport os\nimport __main__\n\n\ndef print_error():\n print(\"\\n\\tNo se encuentra el archivo domus.conf\")\n print(\"\\tPor favor, configure la aplicación antes de iniciar.\")\n # print(\"Exception Config.py\")\n raise SystemExit(1)\n\ntry:\n config = configparser.ConfigParser()\n # config.read('/home/pi/Proyectos/domus/app/domus.conf')\n path = os.path.join(os.path.abspath(os.path.dirname(__main__.__file__)),\n 'domus.conf')\n dataset = config.read(path)\n\nexcept:\n print_error()\n\nelse:\n # Separamos secciones de la configuración\n # para cargarlo individualmente en sus respectivos módulos\n if not len(dataset) > 0:\n print_error()\n\n config_logger = config['Logger']\n config_db = config['Database']\n config_telegram = config['Telegram']\n","sub_path":"app/core/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"474903817","text":"#===============================================================================\n# Copyright 2012 Jake Ross\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#============= enthought library imports =======================\nfrom traits.api import HasTraits, Property, Instance, on_trait_change, Any, \\\n cached_property, Int, Button, Event, DelegatesTo\nfrom traitsui.api import View, Item, HGroup, Group, TabularEditor\nfrom traitsui.tabular_adapter import TabularAdapter\n#============= standard library imports ========================\n# import numpy as np\nfrom numpy import Inf, array, random\nimport re\n#============= local library imports ==========================\nfrom src.database.isotope_analysis.summary import Summary\nfrom src.graph.graph import Graph\nfrom src.database.orms.isotope_orm import proc_SelectedHistoriesTable\nfrom pyface.timer.do_later import do_later\nfrom src.constants import PLUSMINUS\nimport time\n\n\nclass HistoryView(HasTraits):\n summary = Any\n apply = Button\n applied_history = Event\n\n selected_history = Any\n\n def _apply_fired(self):\n summary = self.summary\n dbhist = summary.selected_history.history\n record = summary.record\n selhistory = record.selected_histories\n if not selhistory:\n selhistory = proc_SelectedHistoriesTable(analysis=record)\n\n setattr(selhistory, summary.apply_name, dbhist)\n self.summary.oselected_history = summary.selected_history\n self.applied_history = summary.selected_history\n\n def traits_view(self):\n v = View(Group(\n Item('object.summary.histories', show_label=False,\n editor=TabularEditor(\n adapter=HistoryTabularAdapter(),\n editable=False,\n operations=[],\n auto_update=True,\n horizontal_lines=True,\n selected='object.selected_history')),\n Item('apply',\n enabled_when='summary.selected_history!=summary.oselected_history',\n show_label=False),\n show_border=True,\n label='histories',\n )\n )\n return v\n\nclass HistoryTabularAdapter(TabularAdapter):\n columns = [('User', 'user'), ('Date', 'create_date')]\n\n user_text = Property\n user_width = Int(50)\n create_date_width = Int(120)\n\n def get_font(self, obj, trait, row):\n import wx\n s = 9\n f = wx.FONTFAMILY_DEFAULT\n st = wx.FONTSTYLE_NORMAL\n# w = wx.FONTWEIGHT_BOLD\n w = wx.FONTWEIGHT_NORMAL\n name = 'Bitstream Vera Sans Mono'\n return wx.Font(s, f, st, w, False, name)\n\n def _get_user_text(self):\n u = self.item.user\n return u if u is not None else '---'\n\nclass History(HasTraits):\n history = Any\n\n @cached_property\n def _get_user(self):\n return self.summary.user\n\n @cached_property\n def _get_create_date(self):\n return self.summary.create_date\n\n def __getattr__(self, attr):\n return getattr(self.history, attr)\n\nclass HistorySummary(Summary):\n histories = Property\n graph = Instance(Graph)\n history_view = Instance(HistoryView)\n selected_history = DelegatesTo('history_view')\n history_name = ''\n def _graph_default(self):\n g = Graph(container_dict=dict(padding=5, stack_order='top_to_bottom'))\n g.width = self.record.item_width * 0.73\n return g\n\n def _history_view_default(self):\n return HistoryView(summary=self)\n\n def refresh(self):\n hist = None\n if self.histories:\n selh = self.record._dbrecord.selected_histories\n hist = getattr(selh, self.apply_name)\n\n sh = next((hi for hi in self.histories if hi.history == hist), None)\n def up():\n self.oselected_history = sh\n self.selected_history = None\n self.selected_history = sh\n\n super(HistorySummary, self).build_summary(history=hist)\n do_later(up)\n\n def _get_isotope_keys(self, history, name):\n isokeys = sorted([bi.isotope for bi in getattr(history, name)\n# if bi.use_set\n ],\n key=lambda x:re.sub('\\D', '', x),\n reverse=True)\n return isokeys\n\n @on_trait_change('selected_history')\n def _update_summary(self):\n if self.selected_history:\n self._build_summary()\n\n @cached_property\n def _get_histories(self):\n hn = self.history_name\n dbr = self.record._dbrecord\n return [History(history=hii) for hii in getattr(dbr, '{}_histories'.format(hn))]\n\n def _build_summary(self, history=None):\n if self.histories:\n if history is None:\n if self.selected_history:\n history = self.selected_history\n\n if history:\n self._build_graph(history)\n\n def _build_graph(self, hi):\n hn = self.history_name\n dbr = self.record\n#\n g = self.graph\n g.clear()\n# self.graph = g\n isokeys = self._get_isotope_keys(hi, hn)\n xma = -Inf\n xmi = Inf\n\n for i, iso in enumerate(isokeys):\n bi = next((bii for bii in getattr(hi, hn)\n if bii.isotope == iso), None)\n\n g.new_plot(padding=[50, 5, 30, 5],\n title=iso\n\n )\n if bi.use_set:\n# xs = [dbr.make_timestamp(str(bs.analysis.rundate),\n# str(bs.analysis.runtime)) for bs in bi.sets]\n xs = [time.mktime(bs.analysis.analysis_timestamp.timetuple()) for bs in bi.sets ]\n xs = array(xs)\n if xs.shape[0]:\n xs = xs - min(xs)\n ys = random.random(xs.shape[0])\n g.new_series(xs, ys, type='scatter')\n xma = max(xma, max(xs))\n xmi = min(xmi, min(xs))\n else:\n uv = bi.user_value\n ue = bi.user_error\n g.set_plot_title('{} {:0.5f} {}{:0.6f}'.format(iso, uv, PLUSMINUS, ue), plotid=i)\n\n kw = dict(plotid=i, color=(1, 0, 0))\n g.add_horizontal_rule(uv, line_style='solid',\n **kw)\n kw = dict(plotid=i, color=(0, 0, 0))\n g.add_horizontal_rule(uv + ue, **kw)\n g.add_horizontal_rule(uv - ue, **kw)\n g.set_y_limits(min=uv - ue,\n max=uv + ue, pad='0.1', plotid=i)\n\n\n def traits_view(self):\n v = View(HGroup(\n Item('history_view', style='custom',\n show_label=False,\n width=0.27),\n Item('graph', show_label=False,\n style='custom',\n width=0.73\n )\n )\n )\n\n return v\n#============= EOF =============================================\n","sub_path":"src/database/isotope_analysis/history_summary.py","file_name":"history_summary.py","file_ext":"py","file_size_in_byte":7941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"602907552","text":"\"\"\"adding new kmeans parameters\n\nRevision ID: 5bf9db6d7909\nRevises: a13c4b5cc25f\nCreate Date: 2020-10-15 10:01:50.734058\n\n\"\"\"\nfrom alembic import context, op\nfrom sqlalchemy import String, Integer, Text\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.sql import table, column\nimport json\n\n# revision identifiers, used by Alembic.\nrevision = '5bf9db6d7909'\ndown_revision = 'a13c4b5cc25f'\nbranch_labels = None\ndepends_on = None\n\nOFFSET_FIELD = 582\nFORM_KMEANS = 27\nFORM_KMODES = 152\n\n\ndef _insert_operation_form_field():\n tb = table(\n 'operation_form_field',\n column('id', Integer),\n column('name', String),\n column('type', String),\n column('required', Integer),\n column('order', Integer),\n column('default', Text),\n column('suggested_widget', String),\n column('values_url', String),\n column('values', String),\n column('scope', String),\n column('form_id', Integer),\n column('enable_conditions', String),\n )\n data = [\n [OFFSET_FIELD, 'distance', 'TEXT', 0, 9, 'euclidean',\n \"dropdown\", None, json.dumps([\n {'key': 'euclidean', 'value': 'Euclidean'},\n {'key': 'cosine', 'value': 'Cosine'},\n ]), \"EXECUTION\", FORM_KMEANS, None],\n\n [OFFSET_FIELD+1, 'fragmentation', 'INTEGER', 0, 9, None, 'checkbox',\n None, None, 'EXECUTION', FORM_KMODES, None],\n ]\n columns = [c.name for c in tb.columns]\n rows = [dict(list(zip(columns, row))) for row in data]\n op.bulk_insert(tb, rows)\n\n\ndef _insert_operation_form_field_translation():\n tb = table(\n 'operation_form_field_translation',\n column('id', Integer),\n column('locale', String),\n column('label', String),\n column('help', String), )\n\n columns = [c.name for c in tb.columns]\n data = [\n [OFFSET_FIELD, \"en\", \"Distance Measure\", \"The distance measure\"],\n [OFFSET_FIELD, \"pt\", \"Medida de distância\", \"A medida de distância\"],\n\n [OFFSET_FIELD+1, \"en\", \"Reduce fragmentation\",\n \"If enabled, it will reduce the parallelization in favor of the \"\n \"ability to handle small databases.\"],\n [OFFSET_FIELD+1, \"pt\", \"Reduzir a fragmentação\",\n \"Se ativado, irá reduzir a paralelização em favor da capacidade de \"\n \"lidar com pequenas bases\"],\n ]\n rows = [dict(list(zip(columns, row))) for row in data]\n op.bulk_insert(tb, rows)\n\n\nall_commands = [\n\n (_insert_operation_form_field, \"\"\"DELETE FROM operation_form_field\n WHERE id BETWEEN {} AND {}\"\"\".format(OFFSET_FIELD, OFFSET_FIELD+1)),\n\n (_insert_operation_form_field_translation,\n 'DELETE FROM operation_form_field_translation WHERE id BETWEEN {} AND {}'\n .format(OFFSET_FIELD, OFFSET_FIELD+1)),\n]\n\n\ndef upgrade():\n ctx = context.get_context()\n session = sessionmaker(bind=ctx.bind)()\n connection = session.connection()\n\n try:\n for cmd in all_commands:\n if isinstance(cmd[0], str):\n connection.execute(cmd[0])\n elif isinstance(cmd[0], list):\n for row in cmd[0]:\n connection.execute(row)\n else:\n cmd[0]()\n except:\n session.rollback()\n raise\n session.commit()\n\n\ndef downgrade():\n ctx = context.get_context()\n session = sessionmaker(bind=ctx.bind)()\n connection = session.connection()\n\n try:\n connection.execute('SET FOREIGN_KEY_CHECKS=0;')\n for cmd in reversed(all_commands):\n if isinstance(cmd[1], str):\n connection.execute(cmd[1])\n elif isinstance(cmd[1], list):\n for row in cmd[1]:\n connection.execute(row)\n else:\n cmd[1]()\n connection.execute('SET FOREIGN_KEY_CHECKS=1;')\n except:\n session.rollback()\n raise\n session.commit()\n","sub_path":"migrations/versions/5bf9db6d7909_adding_new_kmeans_parameters.py","file_name":"5bf9db6d7909_adding_new_kmeans_parameters.py","file_ext":"py","file_size_in_byte":3982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"502638201","text":"from django.shortcuts import render\nfrom django.shortcuts import redirect\nfrom .models import Quotes\nfrom .form import Quotes_form\nfrom django.contrib.auth.models import User\nfrom django.http import Http404\n\n# Create your views here.\ndef home(request):\n \"\"\"\n return views at / url\n \"\"\"\n if not request.user.is_authenticated():\n return redirect('/login')\n quotes = Quotes.objects.all()\n user = request.user\n return render(request, \"home.html\", {\"quotes\": quotes, \"user\": user})\n\ndef user_profile(request, username):\n \"\"\"\n views for user profile\n \"\"\"\n try:\n user = User.objects.get(username= username).username\n except User.DoesNotExist:\n raise Http404\n return render(request, \"user_profile.html\", {\"username\" : user})\n\ndef add_quote(request):\n if not request.user.is_authenticated():\n return redirect('/login')\n\n form_class = Quotes_form\n if request.method == 'POST':\n form = form_class(data=request.POST)\n if form.is_valid():\n quote = form.cleaned_data['quotes']\n author = form.cleaned_data['author']\n user = request.user\n obj = Quotes.objects.create(quotes=quote, author=author, user=user)\n return redirect('home')\n else:\n form = form_class()\n return render(request, 'add_quote.html',\n {'form':form,\n\n })","sub_path":"project/QuoteApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"496383363","text":"import sys\nprint(\"RISC-V 32I simulator\")\npipelining=int(input(\"Pipelining knob, 1 for pipelined, 0 for non pipelined: \"))\nif pipelining not in [0,1]:\n print(\"Wrong knob\")\n sys.exit()\n\nif pipelining==0:\n import main_non_pipelined\nelse:\n forwarding=int(input(\"Data Forwarding knob, 1 for ON, 0 for OFF: \"))\n if forwarding not in [0,1]:\n print(\"Wrong knob\")\n sys.exit()\n if forwarding==1:\n import main_forwarding\n else:\n import main_stall\n\n\n","sub_path":"src/not_stable/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"521812781","text":"from trees.automorphismsCounter import countTreeAutomorphismsRS\nfrom utilities.basicgraphs import *\nfrom utilities.graphIO import loadgraph\nfrom utilities.graphUtil import isTree\nfrom week1.colorRefinement import getAllIsomorphisms\nfrom week2.coloring import *\n\n\ndef buildColoringCombinationFromGraphs(g1: graph, g2: graph):\n \"\"\"\n This script needs a coloring from week1 to work!!!\n :param g1: graph1, with defined colornums\n :param g2: graph2, with defined colornums\n :return: ColoringCombination with of the 2 graphs\n \"\"\"\n a1 = dict()\n a2 = dict()\n for v in g1.V():\n a1[v] = v.colornum\n\n for v in g2.V():\n a2[v] = v.colornum\n return ColoringCombination(a1, a2, True)\n\n\ndef areIsomorph(g1: graph, g2: graph, aut):\n stack = [buildColoringCombinationFromGraphs(g1, g2)]\n oldColoring = buildColoringCombinationFromGraphs(g1, g2)\n # BCCEverydayLowPricingHighService\n automorphisms = 0\n while len(stack) != 0:\n cc = stack[-1]\n stack = stack[:-1]\n\n if cc.bijection:\n # gevonden |:D\n if aut:\n automorphisms += 1\n else:\n return True\n elif cc.equal:\n # Wel equal, maar geen bijection. Dubbele kleuren dus. Tijd om verder te zoeken\n newCCs = cc.buildNewColoringCombinations()\n for newCC in newCCs:\n newCC.refineColors(g1, g2)\n # reset the colors\n oldColoring.applyToGraphs(g1, g2)\n stack += newCCs\n else:\n # tja, als ze niet equal zijn hoeft er eigenlijk niet heel veel te gebreuren\n pass\n # als ze ooit wel isomorf waren , dan waren we nooit hier uitgekomen\n return automorphisms\n\n\ndef refineFurther(groups, aut):\n newGroups = []\n automorphisms = dict()\n graphs = len([g for group in groups for g in group])\n counter = 1\n for group in groups:\n for g in group:\n print()\n print(\"Checking graph %i (%i/%i)\"%(counter - 1, counter, graphs))\n counter += 1\n placed = False\n for newGroup in newGroups:\n if newGroup[0] in group:\n out = areIsomorph(g, newGroup[0], False)\n if out:\n newGroup.append(g)\n placed = True\n break\n if not placed:\n newGroups.append([g])\n print(\"New group made...\")\n if aut:\n print(\"Counting automorphisms...\")\n if isTree(g):\n print(\"Tree detected: using optimalized algorithm...\")\n automorphisms[g] = countTreeAutomorphismsRS(g)\n else:\n automorphisms[g] = areIsomorph(g, disjointUnionMulti([g], True), True)\n return newGroups, automorphisms\n\n\ndef output(gl, isomorphisms, automorphisms):\n str1 = \"Sets of isomorphic graphs: \"\n print(\"\\n\\n\")\n if automorphisms:\n print(str1, \" Automorphisms:\")\n else:\n print(str1)\n for group in isomorphisms:\n str2 = str([gl.index(g) for g in group])\n if automorphisms:\n print(str2, \" \" * (len(str1) - len(str2)), automorphisms[group[0]])\n else:\n print(str2)\n\n\ndef getIsomorphismGroups(graphList, aut = False):\n \"\"\"[gl.index(g) for g in group]\n The full algorithm that converts a list of graphs to a list of groups of isomorphic graphs\n The outcome contains all elements of the input, in isomorphic groups. Every graph in a group is isomorphic with\n every other graph in the groups.\n :param graphList: A list of graphs\n :return: A list containing smaller list. The smaller lists are groups of isomorphic graphs.\n \"\"\"\n groups, G = getAllIsomorphisms(graphList)\n further, automorphisms = refineFurther(groups, aut)\n output(graphList, further, automorphisms)\n return further\n\nif __name__ == \"__main__\":\n gl = loadgraph(\"./../data/bigtrees1.grl\", readlist=True)\n # gl = [[disjointUnionMulti([createCycleGraph(1), createCycleGraph(1)]), createCycleGraph(2), createCycleGraph(2)]]\n getIsomorphismGroups(gl[0], True)\n","sub_path":"week2/gerbenBetterRefinement.py","file_name":"gerbenBetterRefinement.py","file_ext":"py","file_size_in_byte":4225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"526649448","text":"import unittest\n\nfrom src.sc.pwr.inz.memory.SensoryBufferMemory.Observation import Observation\nfrom src.sc.pwr.inz.memory.LongTermMemory.semantic.language.components.State import State\nfrom src.sc.pwr.inz.memory.LongTermMemory.semantic.language.components.Trait import Trait\nfrom src.sc.pwr.inz.memory.LongTermMemory.semantic.identifiers.QRCode import QRCode\n\n\nclass ObservationsTest(unittest.TestCase):\n\n def setUp(self):\n self.ident1 = QRCode(\"1\")\n self.ident2 = QRCode(\"2\")\n self.ident3 = QRCode(\"-231\")\n\n self.traits = [Trait(\"Obly\"),Trait(\"Krasny\"), Trait(\"Sowiecki\")]\n self.traits2 = [Trait(\"Barowalny\"), Trait(\"Konieczny\"), Trait(\"Bolszoj\")]\n\n self.s1 = State.IS\n self.s2 = State.IS_NOT\n self.s3 = State.MAYHAPS\n\n self.o1 = Observation(self.ident1, [(self.traits[0], self.s1), (self.traits2[2], self.s1), (self.traits[1],\n self.s2)])\n self.o2 = Observation(self.ident2, [(self.traits[1], self.s3), (self.traits2[1], self.s2), (self.traits[1],\n self.s2)], 1)\n self.o3 = Observation(self.ident3, [(self.traits[2], self.s1), (self.traits2[0], self.s3), (self.traits[2],\n self.s1)])\n\n def test_str(self):\n print(self.o2)\n self.assertEqual(str(self.o2), \"{QRCode{id=2} ['Krasny might_be ', 'Konieczny is_not ',\"\n \" 'Krasny is_not '] observed: 1}\")\n\n def test_get_identifier(self):\n self.assertEqual(self.o1.get_identifier(), self.ident1)\n self.assertEqual(self.o2.get_identifier(), self.ident2)\n self.assertEqual(self.o3.get_identifier(), self.ident3)\n\n def test_get_observed(self):\n self.assertEqual(self.o1.get_observed(), [(self.traits[0], self.s1), (self.traits2[2], self.s1), (self.traits[1]\n , self.s2)])\n self.assertEqual(self.o2.get_observed(), [(self.traits[1], self.s3), (self.traits2[1], self.s2), (self.traits[1],\n self.s2)])\n\n def test_get_timestamp(self):\n self.assertEqual(self.o2.get_episode(), 1)\n\n def test_eq(self):\n self.assertEqual(self.o1, self.o1)\n self.assertNotEqual(self.o1, self.o2)\n self.assertEqual(self.o2, self.o2)\n\n def tearDown(self):\n self.traits2 = None\n self.traits = None\n self.ident1 = None\n self.ident2 = None\n self.ident3 = None\n self.o1 = None\n self.o2 = None\n self.o3 = None\n self.s1 = None\n self.s2 = None\n self.s3 = None\n","sub_path":"tests/sc/pwr/inz/memory/SensoryBufferMemory/Observation.py","file_name":"Observation.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"334378307","text":"first_name = 'Monty'\nlast_name = 'Python'\nfull_name = first_name + ' ' + last_name\nprint(first_name, last_name)\n\n# Describe the sketch comedy group\nname = \"Monty Python\"\ndescription = 'sketch comedy group'\nyear = 1969\n\n# Introduce them\nsentence = name + ' is a ' + description + ' formed in ' + str(1969)\nprint(sentence)\n","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"110165780","text":"#相同的`con_deal_id`,`con_shop_id`,`dt`求和并且一些文字信息使用的是\n\nimport sqlalchemy\nimport sql_name\nimport datetime\nimport pymysql\nfrom sqlalchemy.dialects.mysql import DATE\nimport arg_del\nimport pandas as pd\nimport numpy as np\n#每周六运行\n\nstart_time,end_time,fdatabase,tdatabase=arg_del.get_attr()\nstart_time,end_time,fdatabase,tdatabase=arg_del.set_attr_def_value(start_time,end_time,fdatabase,tdatabase)\nprint('start_time=%s***********************,end_time=%s*****************'%(start_time,end_time))\nfor now_time in arg_del.week_alter(start_time,end_time):\n day={}\n day['start_time']=now_time.strftime('%Y-%m-%d')\n day['end_time']=(now_time+datetime.timedelta(7)).strftime('%Y-%m-%d')\n print('************************day=%s*************************' % day['start_time'])\n localhost_conn = pymysql.connect(host=fdatabase['ip'], user=fdatabase['user'], passwd=fdatabase['password'],\n db='o2o', charset='utf8',\n connect_timeout=7200 * 3, cursorclass=pymysql.cursors.DictCursor)\n localhost_cur = localhost_conn.cursor()\n localhost_cur.execute(sql_name.sql_source_meituan_and_dianping %day)\n\n datas=localhost_cur.fetchall()\n localhost_cur.close()\n localhost_conn.close()\n datas=pd.DataFrame(datas)\n datas.drop(['index','check_url'], axis=1, inplace=True)\n datas.rename(columns={'ccc.check_url':'check_url'},inplace=True)\n datas=datas.groupby(['deal_id','platform'],as_index=False).fillna(method='ffill')\n datas = datas.groupby(['deal_id','platform'],as_index=False).fillna(method='bfill')\n datas['sales']=datas['sales'].astype(float)\n datas['sales_meitun']=datas['sales_meitun'].astype(float)\n datas['sales']=datas['sales']+datas['sales_meitun']\n datas['pv']=datas['pv'].astype(float)\n datas['pv_meitun']=datas['pv_meitun'].astype(float)\n datas['pv'] = datas['pv'] + datas['pv_meitun']\n datas['today_hits']=datas['today_hits'].astype(float)\n datas['today_hits_meitun']=datas['today_hits_meitun'].astype(float)\n datas['today_hits'] = datas['today_hits'] + datas['today_hits_meitun']\n datas['hits']=datas['hits'].astype(float)\n datas['hits_meitun']=datas['hits_meitun'].astype(float)\n datas['hits'] = datas['hits'] + datas['hits_meitun']\n datas['click_count']=datas['click_count'].astype(float)\n datas['click_count_meitun']=datas['click_count_meitun'].astype(float)\n datas['hits'] = datas['hits'] + datas['hits_meitun']\n\n datas['start_time']=pd.to_datetime(datas['start_time'])\n datas['start_time_meitun'] = pd.to_datetime(datas['start_time_meitun'])\n\n #pandas 不能直接比较两列。\n\n datas['start_time'] = datas[['start_time', 'start_time_meitun']].max(axis=1)\n datas['shop_num']=datas['shop_num'].astype(float)\n datas['shop_num_meitun'] = datas['shop_num_meitun'].astype(float)\n datas['shop_num'] = datas[['shop_num','shop_num_meitun']].max(axis=1)\n # print(datas[datas['con_deal_id'] == '27253461'][['deal_id', 'shop_id', 'platform', 'dt', 'sales','pv']])\n conn = sqlalchemy.create_engine('mysql+pymysql://%(user)s:%(password)s@%(ip)s:%(port)s/o2o?charset=utf8' %tdatabase,\n connect_args={'charset': 'utf8'})\n datas = datas.reset_index()\n datas.drop(['index','click_count_meitun','start_time_meitun','hits_meitun','sales_meitun','shop_num_meitun','today_hits_meitun','pv_meitun'],\n axis=1, inplace=True)\n datas['platform']='美团+点评'\n datas.to_sql('tuangou_pet_source_data', conn, if_exists='append')","sub_path":"pet_hostipal/source_from_meituan_and_dianping.py","file_name":"source_from_meituan_and_dianping.py","file_ext":"py","file_size_in_byte":3587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"308026835","text":"import contextlib\nimport wave\nimport numpy as np\n\ndef read_wave(path):\n \"\"\"Reads a .wav file.\n Takes the path, and returns (PCM audio data, sample rate).\n \"\"\"\n with contextlib.closing(wave.open(path, 'rb')) as wf:\n num_channels = wf.getnchannels()\n assert num_channels == 1\n sample_width = wf.getsampwidth()\n assert sample_width == 2\n sample_rate = wf.getframerate()\n assert sample_rate in (8000, 16000, 32000, 48000)\n pcm_data = wf.readframes(wf.getnframes())\n return pcm_data, sample_rate\n\nclass Frame(object):\n \"\"\"Represents a \"frame\" of audio data.\"\"\"\n def __init__(self, bytes_data, timestamp, duration):\n self.bytes_data = bytes_data\n self.timestamp = timestamp\n self.duration = duration\n\ndef frame_generator(frame_duration_ms, audio, sample_rate):\n \"\"\"Generates audio frames from PCM audio data.\n Takes the desired frame duration in milliseconds, the PCM data, and\n the sample rate.\n for f in frame_generator, yields a Frame of the requested duration.\n \"\"\"\n n = int(sample_rate * (frame_duration_ms / 1000.0) * 2)\n offset = 0\n timestamp = 0.0\n duration = (float(n) / sample_rate) / 2.0\n while offset + n < len(audio):\n yield Frame(audio[offset:offset + n], timestamp, duration)\n timestamp += duration\n offset += n\n\ndef pcm_to_numpy(pcm):\n return np.frombuffer(pcm, dtype=np.int16) / 2 ** 15\n\ndef numpy_to_pcm(arr):\n return (arr * (2**15)).astype(np.int16).tobytes()","sub_path":"wav_utils.py","file_name":"wav_utils.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"91883803","text":"#!/usr/bin/env python3\n\nimport os\nimport zlib\nfrom struct import pack, unpack\n\n\nclass FileCountError(Exception):\n\tpass\n\n\nclass ChecksumError(Exception):\n\tpass\n\n\nclass Codec(object):\n\t\"\"\"\\\n\tMain codec for DRP.\n\t\"\"\"\n\tdef __init__(self, ifname='', ofname='', is_bin=True):\n\t\tself.ifname = ifname\n\t\t#Currently automatic ofname doesn't work due to cli.py\n\t\tif ofname == \"\":\n\t\t\tself.ofname = os.path.splittext(ifname)[0]+\".xml\"\n\t\telse:\n\t\t\tself.ofname = ofname\n\t\tself.is_bin = is_bin\n\t\tself.iofunc = (self.encode, self.decode)[self.is_bin]\n\n\tdef run(self):\n\t\t\"\"\"\\\n\t\tRun the codec and write the output file.\n\t\t\"\"\"\n\t\twith open(self.ifname, 'rb') as f:\n\t\t\tself.iofunc(f)\n\n\tdef encode(self, f):\n\t\t\"\"\"\\\n\t\tEncode DRP: Boilderplate header and XML compression\n\t\t\"\"\"\n\t\tif os.path.basename(self.ofname) == \"musicInfo.drp\":\n\t\t\ttype = 0\n\t\telif os.path.basename(self.ofname) == \"katsu_theme.drp\":\n\t\t\ttype = 1\n\t\telse:\n\t\t\tprint(\"Please name your output file correctly. It should be musicInfo.drp or katsu_theme.drp.\")\n\t\t\tsys.exit()\n\t\t\n\t\trxml_data = f.read()\n\t\tbxml_data = zlib.compress(rxml_data)\n\t\tbxmls = (len(bxml_data) + 12) if type == 0 else (len(bxml_data) + 8) # 12 for Taiko 3, 4 for Taiko 1.. And 8 for katsu_theme\n\t\tchecksum = len(rxml_data)\n\t\t#Margin is different for katsu\n\t\tunknown_margin = (0x20000001, 0x0310, 0x00010001, 0) if type == 0 else (0x20000001, 0x01B0, 0x00010001, 0)\n\t\tquadup = lambda x: (x, x, x, x)\n\t\talign = lambda x: x * b'\\x00'\n\n\t\twith open(self.ofname, 'wb') as of:\n\t\t\tunknown, filecount = 2, 1\n\t\t\tof.seek(0x14)\n\t\t\tof.write(pack('>HH', unknown, filecount))\n\t\t\tof.seek(0x60)\n\t\t\t# Notice: the original musicInfo.drp stores the filename\n\t\t\t# `musicinfo_db`, which might be game-specific\n\t\t\tif type == 0:\n\t\t\t\tof.write(bytes(\"musicinfo_db\".encode('ascii')))\n\t\t\tif type == 1:\n\t\t\t\tof.write(bytes(\"katsu_theme_db\".encode('ascii')))\n\t\t\t\n\t\t\tof.seek(0xa0) #Jump to A0 (Where the unknown string is written and the rest of it)\n\t\t\tof.write(pack('>9I',\n\t\t\t\t*unknown_margin,\n\t\t\t\t*quadup(bxmls), #???\n\t\t\t\tchecksum))\n\t\t\tof.write(bxml_data)\n\n\t\t\tremain = of.tell() % 0x10\n\t\t\tif remain: of.write(align(0x10 - remain))\n\t\t\t\t\n\tdef decode(self, f):\n\t\t\"\"\"\\\n\t\tDecode DRP: Decompress XML data\n\t\t\"\"\"\n\t\tf.seek(0x14)\n\t\tunknown, filecount = unpack('>HH', f.read(4))\n\n\t\tif filecount != 1:\n\t\t\t#TODO...\n\t\t\tprint('Not a single XML compressed file, internal names will be used instead.')\n\n\t\tf.seek(0x60)\n\t\tfor i in range(filecount):\n\t\t\tfname = f.read(0x40).split(b'\\x00')[0].decode(\"utf-8\")\n\t\t\tprint(fname)\n\t\t\t#No idea what this line is.\n\t\t\tf.read(0x10)\n\t\t\t# bxmls: binary XML size (zlib compressed), rxmls: Raw XML size\n\t\t\t# the 4 bxmls are duplicate, and rxmls is for checksum\n\t\t\tbxmls, bxmls2, bxmls3, bxmls4, rxmls = unpack('>5I', f.read(4 * 5))\n\t\t\tbxml_data = f.read(bxmls - 4) # rxmls is an unsigned integer\n\n\t\t\tif bxmls > 80:\n\t\t\t\tbxml_data = zlib.decompress(bxml_data) # no Unix EOF (\\n)\n\n\t\t\tif len(bxml_data) != rxmls:\n\t\t\t\traise ChecksumError('Checksum failed, file might be broken')\n\n\t\t\tif filecount == 1:\n\t\t\t\twith open(self.ofname, 'wb') as of:\n\t\t\t\t\tof.write(bxml_data)\n\t\t\telse:\n\t\t\t\twith open(fname+\".xml\", 'wb') as of:\n\t\t\t\t\tof.write(bxml_data)\n","sub_path":"s0ngbrew/codec.py","file_name":"codec.py","file_ext":"py","file_size_in_byte":3129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"585349692","text":"from FactorLib.data_source.base_data_source_h5 import data_source\n\n\ndef get_risky_stocks(start, end, **kwargs):\n dates = data_source.trade_calendar.get_trade_days(start, end, retstr=None)\n subscore = data_source.load_factor('sub_score_of_risky_stocks', '/indexes/').iloc[:, 0].unstack().\\\n reindex(dates, method='nearest')\n totalscore = data_source.load_factor('total_score_of_risky_stocks', '/indexes/').iloc[:, 0].unstack().\\\n reindex(dates, method='nearest')\n totalscorev2 = data_source.load_factor('total_score_of_risky_stocks_v2', '/indexes/').iloc[:, 0].unstack().\\\n reindex(dates, method='nearest')\n subscore, totalscore = subscore.align(totalscore, fill_value=0)\n risky_stocks = ((subscore + totalscore)>=1).stack().to_frame('risky_stocks').astype('int')\n risky_stocks.index.names = ['date', 'IDs']\n kwargs['data_source'].h5DB.save_factor(risky_stocks, '/indexes/')\n kwargs['data_source'].h5DB.save_factor(\n subscore.stack().to_frame('risky_stocks_subscore').rename_axis(['date', 'IDs']), '/indexes/')\n kwargs['data_source'].h5DB.save_factor(\n totalscorev2.stack().to_frame('risky_stocks_totalscore').rename_axis(['date', 'IDs']), '/indexes/')\n\nif __name__ == '__main__':\n get_risky_stocks('20180528', '20180606', data_source=data_source)\n","sub_path":"FactorLib/data_source/update_data/other_factors/gtja_risky_stocks.py","file_name":"gtja_risky_stocks.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"237910477","text":"import os\nimport my_directory\n\nclass url_find():\n\n\tdef __init__(self,file_py,main_url,query,att_url='',complete_url='',query_url=''):\n\t\tself.file_py = file_py\n\t\tself.main_url = main_url\n\t\tself.query = query\n\t\tself.att_url = att_url\n\t\tself.me = my_directory.dir_location()\n\t\tself.query_url = query_url\n\n\t\tytb_query = '''https://www.youtube.com/results?search_query='''\n\t\tquery_splited = query.split(' ')\n\n\t\tquery_builted = ''\n\t\tx = 0\n\n\t\tfor x in range(0,len(query_splited)-1):\n\t\t\tprint(len(query_splited))\n\t\t\tquery_builted = query_builted + query_splited[x] + '+'\n\t\ttry:\n\t\t\tquery_builted = query_builted + query_splited[x+1]\n\t\texcept:\n\t\t\tpass\n\t\t\n\t\tytb_query = ytb_query + query_builted\n\t\tprint(ytb_query)\n\t\tself.query_url = ytb_query\n\t\n\tdef get_complete_url(self):\n\t\tos_command = \"scrapy runspider \" + str(self.file_py) + ''' -a url=\"%s\"''' % self.query_url\n\t\ta = os.popen(os_command).read().split(\"\\n\")[0]\n\t\tfor x in range(0,10):\n\t\t\tprint(a)\n\t\tcomplete_url = self.main_url + a\n\t\treturn complete_url\n'''\n#Test\nget_url = url_find('yt_url_spider_v2.py','youtube.com','windows error song').get_complete_url()\nprint(get_url)\n'''","sub_path":"text_to_url.py","file_name":"text_to_url.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"604481868","text":"#!/usr/bin/env python\n#!/bin/env python\n# $Id: adprocess.py,v 1.12 2001/08/24 18:26:15 bsmith Exp $\n#\n# change python to whatever is needed on your system to invoke python\n#\n# Reads classes.data and prints the Matlab classes using Matlab 7.6 class definitions\n#\n# Crude as all hack!\n#\n# Calling sequence:\n# matlab.py\n##\nimport os\nimport re\nfrom exceptions import *\nimport sys\nfrom string import *\nimport pickle\n\n\ndef main(args):\n file = open('classes.data')\n enums = pickle.load(file)\n senums = pickle.load(file)\n structs = pickle.load(file)\n aliases = pickle.load(file)\n classes = pickle.load(file)\n outfile = open('petsc.hh','w')\n\n def ClassToPointer(a):\n if a in classes: return a+\"*\"\n else: return a\n\n for i in aliases:\n outfile.write(\"typedef \"+aliases[i]+\" \"+i+\"; \\n\")\n outfile.write(\"\\n\")\n\n skeys = senums.keys()\n skeys.sort()\n for i in skeys:\n outfile.write(\"#define \"+i+\" char*\\n\")\n outfile.write(\"\\n\")\n\n skeys = enums.keys()\n skeys.sort()\n for i in skeys:\n outfile.write(\"enum \"+i+\"\\n\")\n outfile.write(\"{\\n\")\n cnt = 0\n for j in enums[i]:\n outfile.write(\" \"+j)\n cnt = cnt + 1\n if not cnt == len(enums[i]): outfile.write(\",\")\n outfile.write(\"\\n\")\n outfile.write(\"};\\n\")\n outfile.write(\"\\n\")\n\n skeys = classes.keys()\n skeys.sort()\n for i in skeys:\n outfile.write(\"class \"+i+\";\\n\")\n outfile.write(\"\\n\")\n\n skeys = structs.keys()\n skeys.sort()\n for i in skeys:\n outfile.write(\"struct \"+i+\"\\n\")\n outfile.write(\"{\\n\")\n for j in structs[i]:\n l = j[:j.find(\" \")]\n if l in classes: j = l+\"* \"+j[j.find(\" \"):]\n outfile.write(\" \"+ClassToPointer(j)+\";\\n\")\n outfile.write(\"};\\n\")\n outfile.write(\"\\n\")\n\n if not os.path.isdir('matlab'): os.mkdir('matlab')\n skeys = classes.keys()\n skeys.sort()\n for i in skeys:\n # writes the C version of each method and function\n # these are all included in the .mex file and selected via dlsym()\n fd = open('matlab/'+i+'Createmex.c','w')\n fd.write('#include \"petscts.h\"\\n')\n fd.write('#include \"mex.h\"\\n')\n fd.write('void mexFunction'+i+'(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])\\n{\\n')\n fd.write(' plhs[0] = mxCreateNumericMatrix(1,1,mxINT32_CLASS,mxREAL);')\n fd.write(' '+i+'Create(PETSC_COMM_WORLD,('+i+'*)mxGetPr(plhs[0]));')\n fd.write(' return;\\n}\\n')\n fd.close()\n\n sskeys = classes[i].keys()\n sskeys.sort()\n # write the .m definitions of the class constructors????????\n for j in sskeys:\n if len(classes[i][j]) < 1 or not classes[i][j][0] == i and not j == 'Create':\n fd = open('matlab/'+i+j+'.m','w')\n fd.write('function '+i+j+'(')\n cnt = 0\n for k in classes[i][j]:\n fd.write('i'+str(cnt))\n if cnt < len(classes[i][j])-1: fd.write(\",\")\n cnt = cnt + 1\n fd.write(')\\n')\n fd.write(\"PetscMex('mexFunction\"+i+j+\"'\")\n if classes[i][j]: fd.write(\",\")\n cnt = 0\n for k in classes[i][j]:\n if k in classes:\n fd.write('i'+str(cnt)+'.Id')\n else:\n fd.write('i'+str(cnt))\n if cnt < len(classes[i][j])-1: fd.write(\",\")\n cnt = cnt + 1\n fd.write(');\\n')\n fd.close()\n buildmex(i,j,classes)\n # write the .m definitions of the class methods\n fd = open('matlab/'+i+'.m','w')\n fd.write('classdef '+i+'\\n')\n fd.write(' properties\\n')\n fd.write(' Id\\n')\n fd.write(' end\\n')\n fd.write(' methods\\n')\n # constructor\n fd.write(' function obj = '+j+'()\\n')\n fd.write(\" obj.Id = PetscMex('mexFunction\"+i+\"');\\n\")\n fd.write(\" end\\n\")\n\n for j in sskeys:\n if len(classes[i][j]) > 0 and classes[i][j][0] == i and not j == 'Destroy' and not j == 'Create':\n fd.write(' function '+j+'(')\n cnt = 0\n for k in classes[i][j]:\n fd.write('i'+str(cnt))\n if cnt < len(classes[i][j])-1: fd.write(\",\")\n cnt = cnt + 1\n fd.write(')\\n')\n fd.write(\"PetscMex('mexFunction\"+i+j+\"'\")\n if classes[i][j]: fd.write(\",\")\n cnt = 0\n for k in classes[i][j]:\n if k in classes:\n fd.write('i'+str(cnt)+'.Id')\n else:\n fd.write('i'+str(cnt))\n if cnt < len(classes[i][j])-1: fd.write(\",\")\n cnt = cnt + 1\n fd.write(');\\n')\n fd.write(' end\\n')\n buildmex(i,j,classes)\n fd.write(' end\\n')\n fd.write('end\\n')\n fd.close()\n\n fd = open('matlab/makefile','w')\n fd.write('LOCDIR = 0\\n')\n fd.write('include ${PETSC_DIR}/lib/petsc/conf/base\\n')\n fd.write('include ${PETSC_DIR}/lib/petsc/conf/test\\n')\n fd.write(\"mexs:\\n\\t${MATLAB_MEX} -output PetscMex *.c -g CC=${CC} CFLAGS='${COPTFLAGS} ${CFLAGS} ${CCPPFLAGS}' ${PETSC_TS_LIB}\\n\")\n fd.close()\n\n # universal Matlab mex function called by all functions/methods\n fd = open('matlab/PetscMex.c','w')\n fd.write('#include \"mex.h\"\\n')\n fd.write('#include \"petscsys.h\"\\n')\n fd.write('#include \"petscfix.h\"\\n')\n fd.write('#if defined(PETSC_HAVE_PWD_H)\\n')\n fd.write('#include \\n')\n fd.write('#endif\\n')\n fd.write('#include \\n')\n fd.write('#include \\n')\n fd.write('#include \\n')\n fd.write('#if defined(PETSC_HAVE_UNISTD_H)\\n')\n fd.write('#include \\n')\n fd.write('#endif\\n')\n fd.write('#if defined(PETSC_HAVE_STDLIB_H)\\n')\n fd.write('#include \\n')\n fd.write('#endif\\n')\n fd.write('#if defined(PETSC_HAVE_SYS_UTSNAME_H)\\n')\n fd.write('#include \\n')\n fd.write('#endif\\n')\n fd.write('#if defined(PETSC_HAVE_WINDOWS_H)\\n')\n fd.write('#include \\n')\n fd.write('#endif\\n')\n fd.write('#include \\n')\n fd.write('#include \\n')\n fd.write('#if defined(PETSC_HAVE_SYS_SYSTEMINFO_H)\\n')\n fd.write('#include \\n')\n fd.write('#endif\\n')\n fd.write('#if defined(PETSC_HAVE_DLFCN_H)\\n')\n fd.write('#include \\n')\n fd.write('#endif\\n')\n\n fd.write('void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])\\n{\\n')\n fd.write(' void (*f)(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]);\\n')\n fd.write(' void *handle;\\n')\n fd.write(' char buffer[256];\\n\\n')\n\n fd.write('#if defined(PETSC_HAVE_LOADLIBRARY)\\n')\n fd.write(' handle = LoadLibrary(0);\\n')\n fd.write('#elif defined(PETSC_HAVE_RTLD_GLOBAL)\\n')\n fd.write(' handle = dlopen(0,RTLD_LAZY | RTLD_GLOBAL);\\n')\n fd.write('#else\\n')\n fd.write(' handle = dlopen(0,RTLD_LAZY);\\n')\n fd.write('#endif\\n\\n')\n\n fd.write(' if (!mxIsChar(prhs[0])) return;\\n')\n fd.write(' mxGetNChars(prhs[0], buffer, 256);\\n\\n')\n\n fd.write('#if defined(PETSC_HAVE_GETPROCADDRESS)\\n')\n fd.write(' f = (void (*)(int,mxArray *[],int,const mxArray *[]))GetProcAddress((HMODULE)handle,buffer);\\n')\n fd.write('#else\\n')\n fd.write(' f = (void (*)(int,mxArray *[],int,const mxArray *[]))dlsym(handle,buffer);\\n')\n fd.write('#endif\\n\\n')\n\n fd.write(' (*f)(nlhs,plhs,nrhs-1,prhs+1);\\n')\n fd.write(' return;\\n}\\n')\n fd.close()\n\n\ndef buildmex(i,j,classes):\n fd = open('matlab/'+i+j+'mex.c','w')\n fd.write('#include \"petscts.h\"\\n')\n fd.write('#include \"mex.h\"\\n')\n fd.write('void mexFunction'+i+j+'(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])\\n{\\n')\n\n cnt = 0\n for k in classes[i][j]:\n if k in classes:\n fd.write(' '+k+' i'+str(cnt)+' = ('+k+') (int) mxGetScalar(prhs['+str(cnt)+']);\\n')\n elif k in ['PetscInt','PetscScalar']:\n fd.write(' '+k+' i'+str(cnt)+' = ('+k+') mxGetScalar(prhs['+str(cnt)+']);\\n')\n elif k in ['char*']:\n fd.write(' char i'+str(cnt)+'[256]; mxGetNChars(prhs['+str(cnt)+'], i'+str(cnt)+', 256);\\n')\n elif k.endswith('Type'):\n fd.write(' const char i'+str(cnt)+'[256]; mxGetNChars(prhs['+str(cnt)+'], (char*)i'+str(cnt)+', 256);\\n')\n else:\n fd.write(' '+k+' i'+str(cnt)+' = ('+k+') 0;\\n')\n pass\n cnt = cnt + 1\n fd.write(' '+i+j+'(')\n cnt = 0\n for k in classes[i][j]:\n fd.write('i'+str(cnt))\n if cnt < len(classes[i][j])-1: fd.write(\",\")\n cnt = cnt + 1\n fd.write(');\\n')\n fd.write(' return;\\n}\\n')\n\n#\n# The classes in this file can also be used in other python-programs by using 'import'\n#\nif __name__ == '__main__':\n main(sys.argv[1:])\n\n","sub_path":"lib/petsc/bin/maint/generators/matlab.py","file_name":"matlab.py","file_ext":"py","file_size_in_byte":8371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"225553992","text":"\"\"\"\nImplementation of double transformer\n\"\"\"\nimport torch\n\nfrom onmt.decoders import TransformerDecoder\nfrom onmt.encoders import TransformerEncoder\nfrom onmt.encoders.encoder import EncoderBase\n\nfrom torch import Tensor\nimport torch.nn.functional as f\n\nfrom datetime import datetime\nimport torch.nn as nn\n\nfrom onmt.encoders.encoder import EncoderBase\n\n\n\nclass DoubleTransformerEncoder(EncoderBase):\n \"\"\"The Transformer encoder from \"Attention is All You Need\"\n :cite:`DBLP:journals/corr/VaswaniSPUJGKP17`\n\n .. mermaid::\n\n graph BT\n A[input]\n B[multi-head self-attn]\n C[feed forward]\n O[output]\n A --> B\n B --> C\n C --> O\n\n Args:\n num_layers (int): number of encoder layers\n d_model (int): size of the model\n heads (int): number of heads\n d_ff (int): size of the inner FF layer\n dropout (float): dropout parameters\n embeddings (onmt.modules.Embeddings):\n embeddings to use, should have positional encodings\n\n Returns:\n (torch.FloatTensor, torch.FloatTensor):\n\n * embeddings ``(src_len, batch_size, model_dim)``\n * memory_bank ``(src_len, batch_size, model_dim)``\n \"\"\"\n\n def __init__(self, opt, embeddings, tg_embeddings=None):\n super(DoubleTransformerEncoder, self).__init__()\n self.first_encoder = TransformerEncoder.from_opt(opt, embeddings, 0)\n self.decoder = TransformerDecoder.from_opt(opt, tg_embeddings)\n self.second_encoder = TransformerEncoder.from_opt(opt, tg_embeddings)\n self.bptt = False\n self.counter = 0\n\n @classmethod\n def from_opt(cls, opt, embeddings, tg_embeddings=None):\n \"\"\"Alternate constructor.\"\"\"\n return cls(opt, embeddings, tg_embeddings)\n\n\n def forward(self, src, lengths=None, dec_in=None, bptt=False):\n \"\"\"See :func:`EncoderBase.forward()`\"\"\"\n enc_state, memory_bank, lengths = self.first_encoder(src, lengths)\n if self.bptt is False:\n self.decoder.init_state(src, memory_bank, enc_state)\n\n dec_out1, attns = self.decoder(dec_in, memory_bank,\n memory_lengths=lengths,\n with_align=False)\n\n weights = self.decoder.embeddings.word_lut.weight # we need to multiply by the embeddings to C\n\n # multiply by weights(t) - to vocab dimensions\n dec_out = torch.tensordot(dec_out1, weights.t(), ([2], [0]))\n # gumbel softmax - choose the words we want from the vocab\n dec_out = nn.functional.gumbel_softmax(dec_out, tau=0.01, hard=True, dim=2)\n # multiply by weights back to embeddings dimensions\n dec_out = torch.tensordot(dec_out, weights, ([2], [0]))\n\n # lengths2 = (torch.ones(dec_out.shape[1]) * dec_out.shape[0]).long().to('cuda')\n # only 1 size batch\n lengths2 = torch.tensor([dec_out.shape[0]]).to('cuda')\n\n enc_state2, memory_bank2, lengths2 = self.second_encoder(dec_out, lengths2)\n\n return enc_state2, memory_bank2, lengths2, dec_out, dec_out1, attns\n\n def update_dropout(self, dropout, attention_dropout):\n self.embeddings.update_dropout(dropout)\n for layer in self.transformer:\n layer.update_dropout(dropout, attention_dropout)\n","sub_path":"onmt/encoders/double_transformer.py","file_name":"double_transformer.py","file_ext":"py","file_size_in_byte":3311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"629413011","text":"\ninfile = open('MoveOriginal.txt', 'r')\noutfile = open('out2.txt', 'w')\n\nlines = infile.read().split('\\n')\n\nx = 0\nmvs = 0\n\nwhile x < len(lines):\n\tname = lines[x + 2].split('.')[0]\n\tnewn = 'moves_all[' + str(mvs) + ']'\n\tfor i in range(13):\n\t\toutfile.write(lines[x].replace(name, newn) + '\\n')\n\t\tx += 1\n\tmvs += 1","sub_path":"python_code_conversion/MoveCnvrt.py","file_name":"MoveCnvrt.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"47548508","text":"# coding: UTF-8\n# convert markdown to html\n# in order to get module attributes(argv)\nimport sys\n# markdown\n#import markdown\nimport gfm\n\n# get command line args\nargs = sys.argv\n\nfile_name = args[1]\nprint(\"file_name : \"+file_name)\n\n# markdown file の読み込み\nf = open(file_name, 'r', encoding='utf-8')\ntext_md = f.read()\nf.close()\n\nprint(\"************ markdown **************\")\nprint(text_md)\n\n# markdown file -> html file\n#md = markdown.Markdown()\n#html = md.convert(text_md)\nhtml = gfm.markdown(text_md)\n\nprint(\"************ html **************\")\nprint(html)\n","sub_path":"src/convert-markdown/convert_markdown_html.py","file_name":"convert_markdown_html.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"483818247","text":"#!usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n\r\n'''\r\nCreated on 2018-1-12\r\n\r\n@author: suning\r\n'''\r\nimport sys\r\nimport os\r\nbasepath = os.path.dirname(os.path.abspath(sys.argv[0]))+\"/../../\"\r\nsys.path.append(basepath)\r\n\r\nimport suning.api as api\r\n\r\na=api.ReceiveinfoModifyRequest()\r\n\r\na.setDomainInfo(\"openpre.cnsuning.com\",\"80\")\r\na.setAppInfo(\"a13b8bd0efb06a770c57d1c370ce8ee7\", \"f08ce9836c4bcfc708194594081f6690\")\r\n# 如果使用oauth认证方式,那么调用下面方法来添加accessToken\r\n#a.setAccessToken(\"4caf7fa30dd8\")\r\na.cityName='南京市'\r\na.customerName='张三'\r\na.detailAddress='苏宁大道1号'\r\na.districtName='玄武区'\r\na.mobilePhoneNum='1110002222'\r\na.orderCode='101030001'\r\na.phoneNum='02566996699'\r\na.provinceName='江苏省'\r\na.supplierCode='10001373'\r\na.townCode='0250101'\r\na.townName='仙鹤门街道'\r\na.userName='aa@163.com'\r\n\r\ntry:\r\n f = a.getResponse()\r\n print(f)\r\nexcept Exception as e:\r\n print(e)","sub_path":"test/selfmarket/ReceiveinfoModifyTest.py","file_name":"ReceiveinfoModifyTest.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"148525561","text":"import numpy as np\nimport logging\nimport json\nimport pyperclip\nfrom time import time, perf_counter\n\nfrom qcodes import VisaInstrument\nfrom qcodes.instrument.parameter import Parameter\nfrom qcodes.utils import validators as vals\nfrom time import sleep\n\n\nlogger = logging.getLogger(__name__)\ncmdbase = \"TERM LF\\nFLSH\\nFLOQ\\n\"\n\n\nclass SIM928(Parameter):\n \"\"\"\n This is the parameter class for the SIM928 rechargeable isolated voltage source module\n\n Args:\n channel (int): SIM900 channel for the SIM928 module\n\n name (Optional[str]): Module name (default 'channel_{channel}')\n\n max_voltage (Optional[float]): Maximum voltage (default 20)\n \"\"\"\n\n def __init__(\n self,\n channel,\n name=None,\n max_voltage=20,\n step=0.001,\n inter_delay=0.035,\n t_recheck_cycles=3600,\n **kwargs\n ):\n if not name:\n name = \"channel_{}\".format(channel)\n\n self.t_last_cycle_check = None\n self.t_recheck_cycles = t_recheck_cycles\n self._latest_charge_cycles = None\n\n self.send_cmd = cmdbase + \"SNDT {:d} ,\".format(channel)\n\n super().__init__(\n name=name,\n unit=\"V\",\n get_cmd=self.get_voltage,\n set_cmd=self.send_cmd + '\"VOLT {:.4f}\"',\n step=step,\n inter_delay=inter_delay,\n vals=vals.Numbers(-max_voltage, max_voltage),\n **kwargs\n )\n self.channel = channel\n\n self._meta_attrs.extend([\"reset\", \"charge_cycles\"])\n\n @property\n def charge_cycles(self):\n if (\n self.t_last_cycle_check is None\n or time() - self.t_last_cycle_check < self.t_recheck_cycles\n ):\n\n self._instrument.write(self.send_cmd + '\"BIDN? CYCLES\"')\n sleep(0.08)\n return_str = self._instrument.ask(\"GETN?{:d},100\".format(self.channel))\n\n try:\n self._latest_charge_cycles = int(return_str.rstrip()[5:])\n except Exception:\n logger.warning(\"Return string not understood: \" + return_str)\n self._latest_charge_cycles = -1\n\n self.t_last_cycle_check = time()\n\n return self._latest_charge_cycles\n\n def get_voltage(self):\n \"\"\"\n Retrieves the DAC voltage.\n Note that there is a small delay, since two commands must be sent.\n\n Returns:\n Channel voltage\n \"\"\"\n # Two commands must be sent to the instrument to retrieve the channel voltage\n self._instrument.write(self.send_cmd + '\"VOLT?\"')\n # A small wait is needed before the actual voltage can be retrieved\n sleep(0.035)\n return_str = self._instrument.ask(\"GETN?{:d},100\".format(self.channel))\n for k in range(5):\n if return_str == \"#3000\\n\":\n logger.warning(\n \"Received return string {}, \"\n \"resetting SIM {}\".format(return_str, self.name)\n )\n self._instrument.reset_slot(self.channel)\n sleep(1)\n self._instrument.write(self.send_cmd + '\"VOLT?\"')\n sleep(1)\n return_str = self._instrument.ask(\"GETN?{:d},100\".format(self.channel))\n else:\n break\n return float(return_str[5:-3])\n\n\nclass SIM900(VisaInstrument):\n \"\"\"\n This is the qcodes driver for the Stanford Research SIM900.\n It is currently only programmed for DAC voltage sources.\n\n Args:\n name (str): name of the instrument.\n address (str): The GPIB address of the instrument.\n min_delay (float): Minimum delay between successive visa commands.\n The SIM900 is known to cause issues if there is no delay between\n successive commands.\n \"\"\"\n\n # Dictionary containing current module classes\n modules = {\"SIM928\": SIM928}\n\n def __init__(self, name, address, min_delay=0.03, **kwargs):\n super().__init__(name, address, **kwargs)\n\n # The SIM900 has eight channels\n self.number_of_channels = 8\n\n # Dictionary with (channel, module) elements\n self._modules = {}\n\n self._last_visa_command = None\n self.min_delay = min_delay\n\n # Start with empty list of channels. These are\n self.add_parameter(\n \"channels\",\n initial_value={},\n set_cmd=None,\n vals=vals.Anything(),\n snapshot_value=False,\n )\n\n def define_slot(self, channel, name=None, module=\"SIM928\", **kwargs):\n \"\"\"\n Define a module for a SIM900 slot.\n Args:\n channel (int): The SIM900 slot channel for the module\n name (Optional[str]): Module name (default 'channel_{channel}')\n module (Optional[str]): Module type (default 'SIM928)\n **kwargs: Module-specific kwargs, and StandardParameter kwargs\n\n Returns:\n None\n \"\"\"\n assert isinstance(channel, int), \"Channel {} must be an integer\".format(channel)\n assert (\n channel not in self.channels().keys()\n ), \"Channel {} already exists\".format(channel)\n assert module in self.modules.keys(), \"Module {} is not programmed\".format(\n module\n )\n\n parameter = self.add_parameter(\n name=name, channel=channel, parameter_class=self.modules[module], **kwargs\n )\n\n # Add\n channels = self.channels()\n channels[channel] = name\n self.channels(channels)\n\n return parameter\n\n def reset_slot(self, channel):\n self.write(cmdbase + \"SRST {}\".format(channel))\n\n def write(self, cmd: str) -> None:\n # Add a delay to ensure commands aren't sent too rapidly\n if self._last_visa_command is not None:\n dt = perf_counter() - self._last_visa_command\n if dt < self.min_delay:\n sleep(self.min_delay - dt)\n\n super().write(cmd)\n self._last_visa_command = perf_counter()\n\n def ask(self, cmd: str) -> str:\n # Add a delay to ensure commands aren't sent too rapidly\n if self._last_visa_command is not None:\n dt = perf_counter() - self._last_visa_command\n if dt < self.min_delay:\n sleep(self.min_delay - dt)\n\n result = super().ask(cmd)\n\n self._last_visa_command = perf_counter()\n\n return result\n\nvoltage_parameters = []\n\n\ndef get_voltages(copy=True):\n \"\"\" Get scaled parameter voltages as dict \"\"\"\n voltage_dict = {param.name: param() for param in voltage_parameters}\n if copy:\n voltage_json = json.dumps(voltage_dict)\n pyperclip.copy(voltage_json)\n return voltage_dict\n\n\ndef ramp_voltages(target_voltage=None, gate_names=None, delay=0.03, **kwargs):\n \"\"\"\n Ramp multiple gates in multiple steps.\n\n Note that voltage_parameters must contain the parameters to be varied\n\n Usage:\n ramp_voltages(target_voltage)\n Ramp voltages of all gates to target_voltage\n ramp_voltages(target_voltage, channels)\n Ramp voltages of gates with names in channels to target_voltage\n ramp_voltages(gate1=val1, gate2=val2, ...)\n Ramp voltage of gate1 to val1, gate2 to val2, etc.\n delay: Optional sleep after changing voltage in each gate\n\n Args:\n target_voltage (int): target voltage (can be omitted)\n gate_names (str list): Names of gates to be ramped (can be omitted)\n use_scaled: Use scaled SIM parameter (SIM900_scaled_parameters)\n **kwargs:\n\n Returns:\n None\n \"\"\"\n parameters = {param.name: param for param in voltage_parameters}\n\n if target_voltage is not None:\n if isinstance(target_voltage, dict):\n # Accidentally passed kwargs dict without splat\n kwargs = target_voltage\n else:\n if gate_names is None:\n gate_names = parameters.keys()\n target_voltages = {gate_name: target_voltage for gate_name in gate_names}\n elif kwargs:\n gate_names = kwargs.keys()\n target_voltages = {gate_name: val for gate_name, val in kwargs.items()}\n\n initial_voltages = {}\n for gate_name in gate_names:\n initial_voltages[gate_name] = parameters[gate_name]()\n\n if delay is not None:\n sleep(delay)\n\n for ratio in np.linspace(0, 1, 11):\n for gate_name in gate_names:\n voltage = (1 - ratio) * initial_voltages[\n gate_name\n ] + ratio * target_voltages[gate_name]\n parameters[gate_name](voltage)\n\n if delay is not None:\n sleep(delay)\n","sub_path":"qcodes/instrument_drivers/stanford_research/SIM900.py","file_name":"SIM900.py","file_ext":"py","file_size_in_byte":8666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"353386202","text":"import turtle\nfrom canvasvg import *\n\ndef LerArquivoTxt():\n f = open('Regras.txt', 'r')\n txt = f.read()\n return txt\n\ntxt = LerArquivoTxt()\ntxt = txt.split('\\n')\nvariaveis = txt[0]\nconstantes = txt[1]\naxioma = txt[2]\nangulo = float(txt[3])\nanguloInicial = float(txt[4])\nnumeroDeExecucoes = int(txt[5])\nregrasTxt = list()\nregras = list()\n\nfor i in range (6, len(txt)):\n regrasTxt.append(txt[i])\nfor i in regrasTxt:\n regra = list()\n regra.append(i.split('->')[0].strip())\n regra.append(i.split('->')[1].strip())\n regras.append(regra)\nregrasDict = dict(regras)\n \nprint(axioma)\npalavraAtual = axioma\nfor i in range (numeroDeExecucoes):\n novaPalavra = ''\n for j in palavraAtual:\n if j in regrasDict:\n novaPalavra += regrasDict[j]\n else:\n novaPalavra += j\n #print(novaPalavra)\n palavraAtual = novaPalavra\n\nposicoes = list()\nangulos = list()\npen = turtle.Pen()\npen.setheading(anguloInicial)\npen._tracer(25.0)\nscreen = turtle.Screen()\nscreen.screensize(10000,10000)\nfor i in palavraAtual:\n if i == 'F':\n pen.forward(5)\n elif i == '+':\n pen.left(angulo)\n elif i == '-':\n pen.right(angulo)\n if i == '[':\n posicoes.append(pen.position())\n angulos.append(pen.heading())\n\n if i == ']':\n pen.penup()\n pen.setpos(posicoes.pop())\n pen.setheading(angulos.pop())\n pen.pendown()\nts = turtle.getscreen().getcanvas()\ncanvasvg.saveall('lsystem.svg', ts)","sub_path":"l-systems.py","file_name":"l-systems.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"403071667","text":"import tensorflow as tf\nimport numpy as np\n\nx_data = np.array([[2, 3], [4, 3], [6, 4], [8, 6], [10, 7], [12, 8], [14, 9]])\n# 속성 데이터\ny_data = np.array([0, 0, 0, 1, 1, 1, 1]).reshape(7, 1)\n# class 데이터\n\nnew_x = np.array([7, 6.]).reshape(1, 2)\n\n# reshape 후 [[0], [0], [0], [1], [1], [1], [1]] 로 변경\n\nX = tf.placeholder(tf.float64, shape = [None, 2])\nY = tf.placeholder(tf.float64, shape = [None, 1])\n\n# a, b 임의로 정함\na = tf.Variable(tf.random_uniform([2, 1], dtype = tf.float64))\nb = tf.Variable(tf.random_uniform([1], dtype=tf.float64))\n\n# sigmoid 함수\ny = tf.sigmoid(tf.matmul(X, a)+b)\n\n# 오차 구하는 함수\nloss = -tf.reduce_mean(Y*tf.log(y)+(1-Y)*tf.log(1-y))\n\nlearning_rate =0.1\n\ngradient_descent = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)\n\n# predicted = tf.cast(y>0.5, dtype = tf.float64) # 0.5 초과일 경우 1, 아니면 0\n# accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype= tf.float64))\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n\n for i in range(300001):\n a_, b_, loss_, _ = sess.run([a, b, loss, gradient_descent], feed_dict={X:x_data, Y:y_data})\n if(i+1) % 300 ==0:\n print(\"step=%d, a1=%.4f, a2=%.4f, b=%.4f, loss=%.4f\" % (i+1, a_[0], a_[1], b_, loss_))\n\n new_y = sess.run(y, feed_dict={X: new_x})\n\n# epoch: 300000, loss: 0.0007\nprint(\"합격 가능성: %6.2f %%\" %(new_y*100))","sub_path":"모두의 딥러닝_ 길벗/0502_Multi-Logistic-Regression.py","file_name":"0502_Multi-Logistic-Regression.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"54889150","text":"from policy import PolicyPage\nimport policy, loc\n\nPERMISSION_FULL = 'Full access'\nPERMISSION_LIST = 'List device content only'\nPERMISSION_READ = 'Read'\nPERMISSION_MODIFY = 'Modify'\nPERMISSION_READ_AND_EXECUTE = 'Read and execute'\n\n_USB_PERMISSION_V2L = {'0': PERMISSION_FULL,\n '2': PERMISSION_LIST,\n '4': PERMISSION_READ,\n '5': PERMISSION_MODIFY,\n '6': PERMISSION_READ_AND_EXECUTE}\n_USB_PERMISSION_L2V = dict([(item[1], item[0]) for item in _USB_PERMISSION_V2L.items()])\n\n_APPROVED_LIST_DELETE_ = \"xpath=(//*[@id='approved_list']//a)[%i]\"\n\nclass PolicyWinDeviceControlPage(PolicyPage):\n\n _tab_section = (policy.TAB_WINDOWS, policy.SEC_WIN_DC)\n _save_button_loc = loc.policy.win_dc_save_button\n\n def is_device_control_enabled(self):\n return self._driver.is_checked(loc.policy.win_dc_enabled_checkbox)\n\n def set_device_control_enabled(self, enabled):\n sel = self._driver\n\n check = sel.check if enabled else sel.uncheck\n check(loc.policy.win_dc_enabled_checkbox)\n return self\n\n def is_usb_autorun_disabled(self):\n return self._driver.is_checked(loc.policy.win_dc_disable_autorun_checkbox)\n\n def set_usb_autorun_disabled(self, disabled):\n sel = self._driver\n\n check = sel.check if disabled else sel.uncheck\n check(loc.policy.win_dc_disable_autorun_checkbox)\n return self\n\n def show_usb_permission_tip(self):\n sel = self._driver\n\n tip = loc.policy.win_dc_usb_permission_tip\n sel.mouse_over(tip)\n sel.mouse_move_at(tip, \"1,1\")\n return self\n\n def hide_usb_permission_tip(self):\n self._driver.mouse_out(loc.policy.win_dc_usb_permission_tip)\n return self\n\n def get_usb_permission(self):\n sel = self._driver\n\n value = sel.get_selected_value(loc.policy.win_dc_usb_permission_list)\n return _USB_PERMISSION_V2L[value]\n\n def set_usb_permission(self, permission, reverse=False):\n sel = self._driver\n if reverse:\n options = _USB_PERMISSION_L2V.keys()\n index = options.index(permission)\n permission = options[0 if index else 1]\n value = _USB_PERMISSION_L2V[permission]\n sel.select(loc.policy.win_dc_usb_permission_list, 'value=%s' % value)\n return self\n\n def expand_permission_list(self):\n sel = self._driver\n sel.get_eval(\"list = window.document.getElementById('%s'); list.size = list.length\" %\n loc.policy.win_dc_usb_permission_list_id)\n return self\n\n def collapse_permission_list(self):\n sel = self._driver\n sel.get_eval(\"list = window.document.getElementById('%s'); list.removeAttribute('size')\" %\n loc.policy.win_dc_usb_permission_list_id)\n return self\n\n def set_exceptions_to_be_added(self, exceptions):\n sel = self._driver\n\n field = loc.policy.win_dc_exception_input\n sel.focus(field)\n sel.type(field, exceptions)\n sel.fire_event(field, 'blur')\n return self\n\n def get_exceptions_to_be_added(self):\n return self._driver.get_value(loc.policy.win_dc_exception_input)\n\n def add_to_approved_list(self):\n self._driver.click(loc.policy.win_dc_exception_add_button)\n return self\n\n def is_exceptions_error_message_displayed(self):\n return self._driver.is_visible(loc.policy.win_dc_exception_errmsg)\n\n def get_exceptions_error_message(self):\n return self._driver.get_text(loc.policy.win_dc_exception_errmsg)\n\n def get_approved_list(self):\n sel = self._driver\n count = self._get_approved_list_count()\n\n # row 1 is the header\n loc_table = loc.policy.win_dc_approved_table\n return [sel.get_table(loc_table + '.%i.0' % row) for row in range(1, count + 1)]\n\n def _get_approved_list_count(self):\n sel = self._driver\n return sel.get_xpath_count(\"//tr[starts-with(@id, 'approved_list_')]\")\n\n def clear_approved_list(self):\n sel = self._driver\n\n for _ in range(self._get_approved_list_count()):\n sel.click(_APPROVED_LIST_DELETE_ % 1)\n return self\n\n def remove_approved_exception(self, exception):\n sel = self._driver\n\n exceptions = self.get_approved_list()\n index = exceptions.index(exception) + 1 # XPath is 1-based\n sel.click(_APPROVED_LIST_DELETE_ % index)\n return self\n\n def click_help(self):\n sel = self._driver\n\n sel.click(loc.policy.win_dc_help_icon)\n return self\n\n def click_more_details(self):\n sel = self._driver\n\n sel.check(loc.policy.win_dc_more_details)\n return self\n","sub_path":"lib/tm/wfbssweb/policy_win_dc.py","file_name":"policy_win_dc.py","file_ext":"py","file_size_in_byte":4733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"652086101","text":"import arcade\n\nUPDATES_PER_FRAME = 7\n\n# Constants used to track if the player is facing left or right\nRIGHT_FACING = 0\nLEFT_FACING = 1\n\n# Game specific animation details\nANIMATION_TUPLES = {\n \"kingkrool\": [(\"idle\", 4), (\"walk\", 8), (\"attack\", 4)],\n}\nANIMATION_DEFAULT = [(\"idle\", 1)]\n\n\ndef load_texture_pair(filename):\n \"\"\" Load a texture pair, with the second being a mirror image. \"\"\"\n return [\n arcade.load_texture(filename),\n arcade.load_texture(filename, flipped_horizontally=True),\n ]\n\n\nclass AnimatedSprite(arcade.Sprite):\n def __init__(self, sprite_name, scale=1):\n \"\"\" sprite_name folder containing sprite, e.g. kingkrool \"\"\"\n super().__init__(scale=scale)\n animation_name_frames_tuples = ANIMATION_TUPLES.get(\n sprite_name, ANIMATION_DEFAULT\n )\n self.sprite_name = sprite_name\n\n # Default to face-right\n self.character_face_direction = RIGHT_FACING\n\n # Used for flipping between image sequences\n self.current_animation_name = \"idle\"\n self.current_frame = 0\n self.loop = True\n\n # Load textures\n self.animation_name_texture_pairs = {}\n for animation_name, frames in animation_name_frames_tuples:\n self.animation_name_texture_pairs[animation_name] = []\n animation_textures = self.animation_name_texture_pairs[animation_name]\n for i in range(frames):\n animation_textures.append(\n load_texture_pair(\n f\"images/npcs/{sprite_name}/{animation_name}{i}.png\"\n )\n )\n self.texture = self.get_current_animation()[0][self.character_face_direction]\n\n def update(self):\n super().update()\n # Figure out if we need to flip face left or right\n if self.change_x < 0 and self.character_face_direction == RIGHT_FACING:\n self.character_face_direction = LEFT_FACING\n elif self.change_x > 0 and self.character_face_direction == LEFT_FACING:\n self.character_face_direction = RIGHT_FACING\n\n # Animation\n self.current_frame += 1\n current_animation = self.get_current_animation()\n if self.current_frame // UPDATES_PER_FRAME >= len(current_animation):\n self.current_frame = 0\n if not self.loop:\n self.set_animation(\"idle\")\n self.texture = current_animation[self.current_frame // UPDATES_PER_FRAME][\n self.character_face_direction\n ]\n\n def get_current_animation(self):\n return self.animation_name_texture_pairs[self.current_animation_name]\n\n def get_current_animation_total_frames(self):\n return len(self.get_current_animation()) * UPDATES_PER_FRAME\n\n def set_animation(self, animation_name, loop=True):\n if not self.has_animation(animation_name):\n print(f\"Animation {animation_name} not in sprite {self.sprite_name}\")\n return\n if self.current_animation_name == animation_name:\n print(f\"Animation {animation_name} already active\")\n self.current_animation_name = animation_name\n self.current_frame = 0\n self.loop = loop\n\n def has_animation(self, animation_name):\n return animation_name in self.animation_name_texture_pairs\n","sub_path":"abbot/ui/animated_sprite.py","file_name":"animated_sprite.py","file_ext":"py","file_size_in_byte":3314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"178125311","text":"#!/usr/bin/env python3\n\nimport socket\nimport argparse\nimport sys\nimport select\n\ndef main():\n parser = argparse.ArgumentParser(description='ncd-server client')\n\n parser.add_argument('ip', nargs='?', default='localhost', help='ncd-server ip address')\n parser.add_argument('port', nargs='?', default=5123, type=int, help='ncd-server port')\n\n args = parser.parse_args()\n\n (family, type, proto, canonname, sockaddr) = socket.getaddrinfo(args.ip, args.port)[0];\n\n sock = socket.socket(family, type, proto)\n\n try:\n sock.connect(sockaddr)\n\n for line in sys.stdin:\n if not line:\n break\n\n if line == 'exit\\n' or line == 'quit\\n' or line == 'q\\n':\n break\n\n sock.send(bytes(line, 'utf-8'))\n response = sock.recv(4096)\n if not response:\n print(\"Connection closed.\")\n break\n print(response.decode('utf-8'), end='', flush=True)\n except KeyboardInterrupt:\n sys.exit(130)\n except ConnectionRefusedError:\n print(\"Connection refused.\")\n except ConnectionResetError:\n print(\"Connction closed.\")\n\n \n\n sock.close()\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"632074113","text":"import kivy\nimport socket\n\nfrom kivy.app import App\nfrom kivy.uix.button import Button\nfrom kivy.uix.gridlayout import GridLayout\n\nred = [1,0,0,1]\ngreen = [0,1,0,1]\nblue = [0,0,1,1]\npurple = [1,0,1,1]\n\n\nHOST = '192.168.0.109' # The server's hostname or IP address\nPORT = 23 # The port used by the server\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect((HOST, PORT))\n s.sendall(b'Hello, world')\n data = s.recv(1024)\n\nprint('Received', repr(data))\n\n\nclass MainApp(App):\n\n def build(self):\n\n # this code writing sucks but as mentioned i am way too lazy to write clean code.\n\n button_lightON = Button(text=\"Light ON\",background_color=red)\n \n button_lightON.bind(on_press=self.sendLightON)\n \n\n layout.add_widget(button_lightON)\n \n\n return layout\n\n def sendLightON(self,instance):\n print(\"light on\")\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect((HOST, PORT))\n s.sendall(b'lightON')\n\n \n class Devices(App):\n def __init__(self, name ):\n self.name = name\n\n def build(self):\n layout = GridLayout(cols=1)\n\n\n\n\nif __name__ == '__main__':\n app = MainApp()\n app.run()","sub_path":"ti_IOT/testing/testingmulticlass.py","file_name":"testingmulticlass.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"15942073","text":"from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import generics\nfrom . import views as v3\nfrom aliss.models import Category, ServiceArea, Organisation, Service, Postcode\nfrom collections import OrderedDict\nfrom copy import deepcopy\nfrom django.shortcuts import get_object_or_404\nfrom aliss.search import return_feature\n\nfrom .serializers import (\n v4SearchSerializer,\n SearchInputSerializer,\n v4CategorySerializer,\n v4ServiceAreaSerializer,\n v4OrganisationDetailSerializer,\n v4ServiceSerializer,\n PostcodeLocationSerializer,\n PostcodeLocationSearchSerializer,\n ServiceAreaSpatialSearchSerializer,\n ServiceAreaFullSpatialDataSetSearchSerializer\n)\n\nclass APIv4():\n META = {\n 'licence': 'https://creativecommons.org/licenses/by/4.0/',\n 'attribution': [{\n 'text': 'Contains National Statistics data © Crown copyright and database right 2018',\n 'url': 'http://geoportal.statistics.gov.uk/datasets/local-authority-districts-december-2016-generalised-clipped-boundaries-in-the-uk/'\n },{\n 'text': 'Contains information from the Scottish Charity Register supplied by the Office of the Scottish Charity Regulator and licensed under the Open Government Licence v2.0',\n 'url': 'https://www.oscr.org.uk/about-charities/search-the-register/charity-register-download'\n },{\n 'text': 'Contains National Records of Scotland data licensed under the Open Government Licence v3.0',\n 'url': 'https://www.nrscotland.gov.uk/statistics-and-data/geography/nrs-postcode-extract'\n },{\n 'text': 'Contains contributions from ALISS users',\n 'url': 'https://www.aliss.org/terms-and-conditions'\n }]\n }\n\nclass ImportView(v3.ImportView):\n serializer_class = v4SearchSerializer\n\n def get_serializer_context(self):\n return {'request': self.request}\n\n \n def get(self, request, *args, **kwargs):\n queryset = self.get_queryset()\n res = queryset.query({ \"match_all\":{}}).execute()\n total = res.hits.total\n request._mutable = True\n request.query_params._mutable = True\n\n if 'format' not in request.query_params:\n request.query_params['format'] = 'json'\n \n if 'page_size' not in request.query_params:\n request.query_params['page_size'] = total\n \n if 'page' not in request.query_params:\n request.query_params['page'] = 1\n \n response = self.list(request, *args, **kwargs)\n data = OrderedDict({'meta': APIv4.META}) \n data['count'] = response.data['count']\n data['next'] = response.data['next']\n data['previous'] = response.data['previous']\n data['data'] = response.data['results']\n return Response(data)\n\nclass SearchView(v3.SearchView):\n serializer_class = v4SearchSerializer\n\n def get_serializer_context(self):\n return {'request': self.request}\n\n def get(self, request, *args, **kwargs):\n response = self.list(request, *args, **kwargs)\n data = OrderedDict({'meta': APIv4.META})\n data['count'] = response.data['count']\n data['next'] = response.data['next']\n data['previous'] = response.data['previous']\n data['data'] = response.data['results']\n return Response(data)\n\n\nclass ServiceAreaListView(v3.ServiceAreaListView):\n def list(self, request):\n queryset = self.get_queryset()\n serializer = v4ServiceAreaSerializer(queryset, many=True)\n data = OrderedDict()\n data['meta'] = deepcopy(APIv4.META)\n data['meta']['attribution'].pop()\n data['meta']['attribution'].pop()\n data['data'] = serializer.data\n return Response(data)\n\n\nclass CategoryListView(v3.CategoryListView):\n\n def get_queryset(self):\n return Category.objects.filter(parent=None)\n\n def list(self, request):\n queryset = self.get_queryset()\n serializer = v4CategorySerializer(queryset, many=True)\n data = OrderedDict()\n data['meta'] = deepcopy(APIv4.META)\n data['meta']['attribution'] = []\n data['data'] = serializer.data\n return Response(data)\n\n\nclass OrganisationDetailView(v3.TrackUsageMixin, APIView):\n\n def get(self, request, pk=None, slug=None):\n if pk==None:\n organisation = get_object_or_404(Organisation, slug=slug)\n else:\n organisation = get_object_or_404(Organisation, pk=pk)\n context = { 'request': request }\n data = OrderedDict({'meta': APIv4.META})\n data['data'] = v4OrganisationDetailSerializer(organisation, many=False, context=context).data\n return Response(data)\n\n\nclass ServiceDetailView(v3.TrackUsageMixin, APIView):\n\n def get(self, request, pk=None, slug=None):\n if pk==None:\n service = get_object_or_404(Service, slug=slug)\n else:\n service = get_object_or_404(Service, pk=pk)\n context = { 'request': request }\n data = OrderedDict({'meta': APIv4.META})\n data['data'] = v4ServiceSerializer(service, many=False, context=context).data\n return Response(data)\n\n\nclass PostcodeLocationData(generics.ListAPIView):\n serializer_class = PostcodeLocationSerializer\n\n def get_queryset(self, *args, **kwargs):\n queryset = Postcode.objects.exclude(place_name=None)\n return queryset\n\n def list(self, request, *args, **kwargs):\n input_serializer = PostcodeLocationSearchSerializer(data=request.query_params)\n input_serializer.is_valid(raise_exception=True)\n self.input_data = input_serializer.validated_data\n return super(PostcodeLocationData, self).list(request, *args, **kwargs)\n\n def filter_queryset(self, queryset):\n query = self.input_data.get('q', None)\n if query and len(query) > 2:\n queryset = queryset.filter(place_name__istartswith = query)\n return queryset\n else:\n return None\n\n\nclass ServiceAreaSpatialData(APIView):\n # serializer_class = ServiceAreaSpatialSerializer\n\n def get(self, request, *args, **kwargs):\n input_serializer = ServiceAreaSpatialSearchSerializer(data=request.query_params)\n input_serializer.is_valid(raise_exception=True)\n input_data = input_serializer.validated_data\n service_id = input_data.get('service_id')\n service_area_objs = Service.objects.get(pk=service_id).service_areas.all()\n service_area_features = []\n for service_area_obj in service_area_objs:\n type = service_area_obj.type\n code = service_area_obj.code\n returned = []\n if type == 0:\n if code == \"XS\":\n returned.append(return_feature(type, \"S92000003\"))\n else:\n uk_codes = [\"S92000003\", \"E92000001\", \"W92000004\", \"N92000002\"]\n for uk_code in uk_codes:\n returned.append(return_feature(type, uk_code))\n else:\n returned.append(return_feature(type, code))\n\n service_area_features += returned\n queryset = list(service_area_features)\n return Response(queryset)\n\nclass ServiceAreaFullSpatialDataSet(APIView):\n def get(self, request, *args, **kwargs):\n\n dataset_name_keys = {\n 0: \"ctry17nm\",\n 2: \"lad18nm\",\n 3: \"HBName\",\n 4: \"HIAName\",\n }\n\n input_serializer = ServiceAreaFullSpatialDataSetSearchSerializer(data=request.query_params)\n input_serializer.is_valid(raise_exception=True)\n input_data = input_serializer.validated_data\n area_type = input_data.get('type')\n service_area_features = return_feature(area_type, 0, True)\n queryset = list(service_area_features)\n result = {\"name_key\": dataset_name_keys.get(area_type), \"data\": queryset}\n return Response(result)\n","sub_path":"aliss/api/v4_views.py","file_name":"v4_views.py","file_ext":"py","file_size_in_byte":7980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"458277837","text":"# Kenny Yip and Rafael Trinidad worked on this script\n\nfrom fractions import Fraction\ndef sublistRegulation(input, output_frame_count) -> list:\n assert isinstance(input, list)\n assert isinstance(output_frame_count, int)\n assert all(isinstance(x, float) or isinstance(x, int) for x in input)\n\n slopes = []\n offsets = []\n i = 0\n for _ in input:\n offsets.append(input[i])\n\n if i == len(input) - 1:\n slopes.append(0)\n else:\n slopes.append(input[i+1] - input[i])\n\n i += 1\n\n iterpolated_list = []\n step_count = Fraction(len(input)-1, output_frame_count-1)\n pointer = 0\n while pointer <= len(input)-1:\n current_index = int(pointer // 1)\n current_value = slopes[current_index] * (pointer-current_index) + offsets[current_index]\n iterpolated_list.append(current_value)\n pointer += step_count\n\n return iterpolated_list\n\ndef regulation(input_frames, output_frame_count) -> list:\n assert isinstance(input_frames, list)\n assert isinstance(output_frame_count, int)\n coordinates_per_frame = len(input_frames[0])\n assert all(len(x) == coordinates_per_frame for x in input_frames)\n master_list = []\n slices = []\n\n for s in range(coordinates_per_frame):\n sliced = []\n for i in range(0, len(input_frames)):\n sliced.append(input_frames[i][s])\n slices.append(sublistRegulation(sliced, output_frame_count))\n\n for j in range(output_frame_count):\n newFrames = []\n for t in range(coordinates_per_frame):\n newFrames.append(slices[t][j])\n master_list.append(newFrames)\n\n return master_list\n\nprint(\"OUTPUT: \", regulation([(1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,8)],5))\n","sub_path":"scripts/regulation_python.py","file_name":"regulation_python.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"445821072","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport json\nimport inspect\nimport logging\nimport itertools\n\nfrom django.utils.datastructures import MultiValueDictKeyError\nfrom django.views.generic import View\nfrom django.http.response import JsonResponse, HttpResponseBadRequest, HttpResponse\nfrom pyparsing import ParseException\nimport docutils\nimport docutils.core\n\nfrom django.views.decorators.cache import cache_page\n\nfrom hub.odhql import parser\nfrom hub.odhql.parser import OdhQLParser\nfrom hub.odhql.functions.core import OdhQLFunction\n\nlogger = logging.getLogger(__name__)\n\n\nclass ParseView(View):\n def post(self, request):\n try:\n body = json.loads(request.body, encoding=request.encoding)\n params = body['params']\n\n statement = params['query']\n logger.debug('Validating ODHQL query \"%s\"', statement)\n\n query = OdhQLParser().parse(statement)\n query = itertools.chain(*[q.data_sources for q in query.queries]) if \\\n isinstance(query, parser.Union) else query.data_sources\n\n data_sources = {'tables': [{'name': table.name, 'alias': table.alias} for table in query]}\n except ParseException as e:\n return JsonResponse({'error': e.message,\n 'type': 'parse',\n 'line': e.line,\n 'lineno': e.lineno,\n 'col': e.col},\n status=HttpResponseBadRequest.status_code)\n except MultiValueDictKeyError:\n return JsonResponse({'error': 'Es wurde keine ODHQL Abfrage angegeben.',\n 'type': 'execution'},\n status=HttpResponseBadRequest.status_code)\n\n return JsonResponse(data_sources)\n\n\nclass DocumentationView(View):\n def get(self, request):\n doc = \"\"\"\n OpenDataHub Query Language (ODHQL)\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n .. contents:: Inhalt\n :backlinks: top\n\n {}\n {}\n \"\"\"\n doc = inspect.cleandoc(doc).format(OdhQLParser.gen_doc(), OdhQLFunction.gen_all_docs())\n html = docutils.core.publish_parts(doc, writer_name='html', settings_overrides={'syntax_highlight': 'short'})[\n 'html_body']\n html = html.replace('href=\"#', '= UPDATE_TIME:\n # 将 item_all.column_id,item_all.item_id存入 item_need列表中。\n item_need['column_id'] = item_all.column_id\n item_need['item_id'] = item_all.item_id\n # 将 item_need,存入,items_need集合中。\n items_need.append(item_need)\n return items_need\n\n # update_item_name,需要传入参数,column_id,item_name\n def update_item_name(self, column_id, item_name):\n # 获取monitor表中 column_id.\n update_item = self.session.query(Monitor).get(column_id)\n update_item.item_name = item_name\n self.session.commit()\n\n def update_item_price(self, column_id, item_price):\n # 获取当前时间\n time_now = datetime.datetime.now()\n update_item = self.session.query(Monitor).get(column_id)\n\n if update_item.item_price and update_item.item_price != item_price: # if new price\n update_item.last_price = update_item.item_price\n update_item.discount = round(float(item_price) / float(update_item.last_price), 2) # round(,2) set to 0.01\n update_item.item_price = item_price\n update_item.update_time = time_now\n self.session.commit()\n\n def update_item_subtitle(self, column_id, subtitle):\n update_item = self.session.query(Monitor).get(column_id)\n update_item.subtitle = subtitle\n self.session.commit()\n\n def update_item_plus_price(self, column_id, plus_price):\n update_item = self.session.query(Monitor).get(column_id)\n update_item.plus_price = plus_price\n self.session.commit()\n\n def update_item_max_price(self, column_id, highest_price):\n update_item = self.session.query(Monitor).get(column_id)\n update_item.highest_price = highest_price\n self.session.commit()\n\n def update_item_min_price(self, column_id, lowest_price):\n update_item = self.session.query(Monitor).get(column_id)\n update_item.lowest_price = lowest_price\n self.session.commit()\n\n def update_status(self, column_id):\n update_item = self.session.query(Monitor).get(column_id)\n update_item.status = 0\n self.session.commit()\n\n def check_item_need_to_remind(self):\n # items_alert = {column_id, item_id, user_price, item_price, name, email}\n items_alert = []\n items = self.session.query(Monitor).all()\n for item in items:\n item_alert = {}\n if item.status == 1 and item.user_price:\n if float(item.user_price) > float(item.item_price):\n user = self.session.query(User).filter_by(column_id=item.user_id)\n item_alert['email'] = user[0].email\n item_alert['name'] = item.item_name\n item_alert['item_price'] = item.item_price\n item_alert['user_price'] = item.user_price\n item_alert['item_id'] = item.item_id\n item_alert['column_id'] = item.column_id\n items_alert.append(item_alert)\n return items_alert\n'''\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO)\n sql = Sql()\n\n # add user named 'test'\n # sql.write_file('test', '1712340552')\n print(type(sql.get_file_path()))\n\n\n # add test item\n # item_id, user_price, user_id\n # sql.write_item(['100005857580', '2000', '1'])\n # sql.write_item(['7437690', '200', '2'])\n\n # read all items needed update\n # print(sql.read_all_not_updated_item())\n","sub_path":"con_sql.py","file_name":"con_sql.py","file_ext":"py","file_size_in_byte":6211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"559813488","text":"import pickle\n\ndef checkRange():\n\n try:\n file = open('crawler_results/result.txt', 'rb')\n except:\n return 0\n\n try:\n objs = []\n while True:\n try:\n o = pickle.load(file)\n except EOFError:\n break\n objs.append(o)\n result = 0\n except:\n file.close()\n return 1\n\n try:\n for inner_list in objs:\n for elem in inner_list:\n aux = elem['range']\n result = max(aux, result)\n return result\n except:\n file.close()\n return 1\n\n#print('check_range_says:', checkRange()) just for debug\n","sub_path":"Crawler-Model/checkRange.py","file_name":"checkRange.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"301303911","text":"import matplotlib.pyplot as plt\r\nimport sys\r\nfrom matplotlib import dates\r\n\r\nimport numpy as np\r\n\r\nimport datetime\r\nfilename = sys.argv[1]\r\nwith open(filename, 'r') as f:\r\n\tlines = f.readlines()\r\nlines = lines[5:]\r\nt1 = np.zeros(len(lines))\r\nt2 = np.zeros(len(lines))\r\nt3 = np.zeros(len(lines))\r\ntime = np.zeros(len(lines))\r\nfor i, line in enumerate(lines):\r\n\ttime[i] = int(line.split()[0])\r\n\tt1[i] = float(line.split()[1])\r\n\tt2[i] = float(line.split()[2])\r\n\tt3[i] = float(line.split()[3])\r\n\r\n\r\n\r\nfig = plt.figure()\r\nax = fig.add_subplot(111)\r\nsecs = dates.epoch2num(time)\r\nplt.plot_date(secs, t1, 'r.', label='Ambient')\r\nplt.plot_date(secs, t2, 'b.', label='Plate')\r\nplt.plot_date(secs, t3, 'g.', label='Sample')\r\n\r\ndate_fmt = '%m/%d\\n%H:%M'\r\n# Use a DateFormatter to set the data to the correct format.\r\ndate_formatter = dates.DateFormatter(date_fmt)\r\nax.xaxis.set_major_formatter(date_formatter)\r\n\r\n# Sets the tick labels diagonal so they fit easier.\r\n#fig.autofmt_xdate()\r\n\r\nplt.xlabel('Time')\r\nplt.ylabel('Temperature (deg C)')\r\nplt.legend(loc='best')\r\n\r\nplt.show()\r\n","sub_path":"logging/misc/fit_temp.py","file_name":"fit_temp.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"112127096","text":"from threading import Thread\nfrom time import sleep\na=range(1000,2000)\ndef go():\n for i in range(0,250):\n a[i]=i\n sleep(0.005)\ndef to():\n for i in range(250,500):\n a[i]=i\n sleep(0.005)\nthreads=[]\nfor t in [go,to]:\n threads.append(Thread(target=t))\n threads[-1].start()\nfor tr in threads:\n tr.join()\nprint(a)","sub_path":"timediff/2f.py","file_name":"2f.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"590603895","text":"#!/usr/bin/env python\nimport rospy\nfrom sensor_msgs.msg import JointState\nfrom rns_msgs.msg import JointCmd\nimport math\n\n\nfromIncToRadFor10664 = 4096/(2*math.pi)\nfromIncToRadFor12 = (1024*180)/(300*math.pi)\ncmdPub = rospy.Publisher('cmd_joints',JointCmd,queue_size = 10)\n\ndef PublishCmdCallback(msgPos):\n global fromIncToRadFor10664, fromIncToRadFor12, cmdPub\n jointcmd = JointCmd()\n for i in range(len(msgPos.name)):\n jointcmd.channel = int(msgPos.name[i])\n if (int(msgPos.name[i]) == 0 or int(msgPos.name[i]) == 1 or int(msgPos.name[i]) == 2 or int(msgPos.name[i]) == 6 or int(msgPos.name[i]) == 7 or int(msgPos.name[i]) == 8):\n jointcmd.cmd = int(msgPos.position[i])\n else:\n jointcmd.cmd = int(msgPos.position[i])\n cmdPub.publish(jointcmd)\n \n\nif __name__ == '__main__':\n rospy.init_node('publish_cmd_in_rad_node',anonymous=True)\n rospy.Subscriber(\"/arm/cmd_arm_in_pos\", JointState, PublishCmdCallback)\n rospy.spin()\n","sub_path":"bs_arm_controll/src/publishCmdInPos.py","file_name":"publishCmdInPos.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"593166222","text":"# Program to accept comma seperated values and store them in list and tuple\r\n# First we take it as string and then make them numbers and store them in list itself.\r\nstr=input(\"Enter numbers which are seperated with comma:\")\r\ncount=0;c=0\r\na=[]\r\nfor i in str:\r\n if i==',':\r\n a.append(int(str[c:count]))\r\n c=count+1\r\n count=count+1\r\na.append(int(str[c:count]))\r\nprint(a)\r\nprint(tuple(a))\r\n","sub_path":"coding_assignment_module1/first.py","file_name":"first.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"124380285","text":"import json\nimport requests\nfrom flask import Flask, render_template, request\nfrom flask_ask import Ask, statement, question\nfrom proto_time_db import start, stop\nfrom proto_eremote import temp_on, temp_off,hum_on, hum_off\nfrom tinydb import TinyDB,Query\n\ndb = TinyDB(\"db.json\")\nsensor = Query()\n\napp = Flask(__name__)\nask = Ask(app, '/')\n\n@app.route(\"/temp\", methods=['POST'])\ndef temp():\n temp = request.data.decode()\n db.update({\"value\":temp},sensor.key == \"temp\")\n return temp\n\n@app.route(\"/hum\", methods=['POST'])\ndef hum():\n hum = request.data.decode()\n db.update({\"value\":hum},sensor.key == \"hum\")\n return hum\n\n@ask.launch\ndef launched():\n text = \"はいプロトです。本を読む時は、読書をはじめるよって言ってね。\"\n return question(text)\n\n@ask.intent('readingStart')\ndef readingStart():\n start()\n t = float(db.search(sensor.key == \"temp\")[0][\"value\"])\n h = int(db.search(sensor.key == \"hum\")[0][\"value\"])\n print(\"temp:\" + str(t),\"hum:\" + str(h))\n if t < 20 and h < 60 :\n text = \"ちょっと寒いですね、暖房を点けますか?\"\n return question(\"読書をはじめます。\" + text)\n else:\n text = \"お部屋の温度はちょうどいいですね。\"\n return statement(\"読書をはじめます。\" + text)\n\n@ask.intent('readingEnd')\ndef readingEnd():\n r = stop()\n p1 = db.search(sensor.key == \"temp_power\")[0][\"value\"]\n p2 = db.search(sensor.key == \"hum_power\")[0][\"value\"]\n if p1 == 1:\n text = \"暖房を消しますか?\"\n return question('読書の時間は' + str(r) + 'でした。' + text)\n else:\n return statement('読書の時間は' + str(r) + 'でした。お疲れさまでした。')\n\n@ask.intent('onIntent')\ndef on():\n temp_on()\n db.update({\"value\":1},sensor.key == \"temp_power\")\n\n h = int(db.search(sensor.key == \"hum\")[0][\"value\"])\n if h < 60:\n hum_on()\n db.update({\"value\":1},sensor.key == \"hum_power\")\n else:\n pass\n return statement('暖房を入れました。快適に読書を楽しんでね。')\n\n@ask.intent('offIntent')\ndef off():\n temp_off()\n db.update({\"value\":0},sensor.key == \"temp_power\")\n\n p2 = db.search(sensor.key == \"hum_power\")[0][\"value\"]\n if p2 == 1:\n hum_off()\n db.update({\"value\":0},sensor.key == \"hum_power\")\n else:\n pass\n return statement('暖房を消しました。お疲れさまでした。')\n\n@ask.session_ended\ndef session_ended():\n return \"{}\", 200\n\nif __name__ == \"__main__\":\n app.run(host=\"127.0.0.1\", port=5000)\n","sub_path":"Chapter5/AmazonEcho_room/proto_a_room.py","file_name":"proto_a_room.py","file_ext":"py","file_size_in_byte":2596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"455347605","text":"from threading import *\nimport time\nclass Apple(Thread):\n def run(self):\n for x in range(10):\n time.sleep(1)\n print('Apple says Hi!')\nclass Orange(Thread):\n def run(self):\n for x in range(10):\n time.sleep(1)\n print('Orange says Hello!')\napple_obj = Apple()\norange_obj = Orange()\nstart_time = time.perf_counter()\napple_obj.start()\ntime.sleep(0.1)\norange_obj.start()\napple_obj.join()\norange_obj.join()\nend_time = time.perf_counter()\nprint(f'Processed in {round(end_time-start_time)} seconds')","sub_path":"PythonBasics/multifun.py","file_name":"multifun.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"413009918","text":"# -*- coding: utf-8 -*-\n\nfrom qgis.PyQt.QtWidgets import QTreeWidget, QAbstractItemView, QMessageBox, QTreeWidgetItemIterator\nfrom qgis.PyQt.QtCore import Qt, QByteArray, QDataStream, QIODevice\nfrom qgis.core import Qgis, QgsMessageLog\n\nfrom geobretagne.gui.tree_items import TreeWidgetItem\nfrom geobretagne.utils.plugin_globals import PluginGlobals\n\n\nclass TreeWidget(QTreeWidget):\n \"\"\"\n The tree widget used in the dock\n \"\"\"\n\n def __init__(self):\n objectName = 'TreeWidget'\n\n super(TreeWidget, self).__init__()\n\n # Selection\n self.setSelectionMode(QAbstractItemView.SingleSelection)\n\n # Columns and headers\n self.setColumnCount(1)\n self.setHeaderLabel('')\n self.setHeaderHidden(True)\n\n # Events\n self.itemDoubleClicked.connect(self.tree_item_double_clicked)\n\n # Context menu\n self.setContextMenuPolicy(Qt.CustomContextMenu)\n self.customContextMenuRequested.connect(self.open_menu)\n\n # Enable drag of tree items\n self.setDragEnabled(True)\n self.setAcceptDrops(True)\n\n def set_tree_content(self, resources_tree):\n \"\"\"\n Creates the items of the tree widget\n \"\"\"\n\n def create_subitem(subtree, parent_item=self):\n \"\"\"\n \"\"\"\n subitem = TreeWidgetItem(parent_item, subtree)\n if subtree.children is not None and len(subtree.children) > 0:\n for child in subtree.children:\n create_subitem(child, subitem)\n\n self.clear()\n\n if resources_tree is None:\n QgsMessageLog.logMessage(u\"Faute de fichier de configuration valide, aucune ressource ne peut être chargée \"\n u\"dans le panneau.\", level=Qgis.Warning)\n elif resources_tree.children is not None and len(resources_tree.children) > 0:\n for child in resources_tree.children:\n create_subitem(child, self)\n\n \n def show_parents(self, item):\n # check if item has parent\n if item.parent():\n # show parent\n parent = item.parent()\n parent.setHidden(False)\n # next parent of parent\n self.show_parents(parent)\n\n def show_children(self, item):\n # check if item has children\n if item.childCount() > 0:\n # show all children\n for child_index in range(0, item.childCount()):\n child = item.child(child_index)\n child.setHidden(False)\n # next children of children\n self.show_children(child)\n \n def filter_by_text(self, searchtext):\n # no text filter\n if searchtext == '':\n # folds all folders\n self.collapseAll()\n # show all items\n it = QTreeWidgetItemIterator(self)\n while it.value():\n item = it.value()\n item.setHidden(False)\n it += 1\n # text filter\n\n # if no filter is set, folds all items\n else:\n # hide all items\n it = QTreeWidgetItemIterator(self)\n while it.value():\n item = it.value()\n item.setHidden(True)\n it += 1\n # iterate through all items\n it = QTreeWidgetItemIterator(self)\n while it.value():\n item = it.value()\n # if text is found in item\n if searchtext.lower() in item.text(0).lower():\n # make this item visible\n item.setHidden(False)\n # make its parent visibles\n self.show_parents(item)\n # make its children visible\n self.show_children(item)\n it += 1\n # unfold all folders\n self.expandAll()\n\n def update_visibility_of_tree_items(self):\n \"\"\"\n Update the visibility of tree items:\n - visibility of empty groups\n - visibility of items with status = warn\n \"\"\"\n hide_items_with_warn_status = PluginGlobals.instance().HIDE_RESOURCES_WITH_WARN_STATUS\n hide_empty_groups = PluginGlobals.instance().HIDE_EMPTY_GROUPS\n\n def update_visibility_of_subitems(item, hide_empty_groups, hide_items_with_warn_status):\n\n if hasattr(item, \"item_data\") and item.item_data.status == PluginGlobals.instance().NODE_STATUS_WARN:\n item.setHidden(hide_items_with_warn_status)\n\n child_count = item.childCount()\n if child_count > 0:\n for i in range(child_count):\n sub_item = item.child(i)\n if sub_item.is_an_empty_group():\n sub_item.setHidden(hide_empty_groups)\n\n update_visibility_of_subitems(sub_item, hide_empty_groups, hide_items_with_warn_status)\n\n update_visibility_of_subitems(self.invisibleRootItem(), hide_empty_groups, hide_items_with_warn_status)\n\n def tree_item_double_clicked(self, item, column):\n \"\"\"\n Handles double clic on an item\n \"\"\"\n item.run_default_action()\n\n def open_menu(self, position):\n \"\"\"\n Handles context menu in the tree\n \"\"\"\n selected_item = self.currentItem()\n menu = selected_item.create_menu()\n menu.exec_(self.viewport().mapToGlobal(position))\n\n # Constant and methods used for drag and drop of tree items onto the map\n\n QGIS_URI_MIME = \"application/x-vnd.qgis.qgis.uri\"\n\n def mimeTypes(self):\n \"\"\"\n \"\"\"\n return [self.QGIS_URI_MIME]\n\n def mimeData(self, items):\n \"\"\"\n \"\"\"\n mime_data = QTreeWidget.mimeData(self, items)\n encoded_data = QByteArray()\n stream = QDataStream(encoded_data, QIODevice.WriteOnly)\n\n for item in items:\n layer_mime_data = item.item_data.layer_mime_data()\n stream.writeQString(layer_mime_data)\n\n mime_data.setData(self.QGIS_URI_MIME, encoded_data)\n return mime_data\n\n def dropMimeData(self, parent, index, data, action):\n \"\"\"\n \"\"\"\n if action == Qt.IgnoreAction:\n return True\n\n return False\n","sub_path":"geobretagne/gui/tree_widget.py","file_name":"tree_widget.py","file_ext":"py","file_size_in_byte":6271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"28815761","text":"#!/bin/python3\n\nimport shutil # for copyfile\nimport os # for getfiles and check size\nimport sys # for cli arguments\n\n#logscript.py mylog.txt 10 5\n\nif(len(sys.argv) < 4):\n print(\"You lose arguments? try again\")\n exit(1)\n\nfile_name = sys.argv[1]\nlimit_size = int(sys.argv[2])\nlogsnumber = int(sys.argv[3])\n\nif(os.path.isfile(file_name) == True):\n logfile_size = os.stat(file_name).st_size\n logfile_size = logfile_size / 1024\n\n if(logfile_size >= limit_size):\n if(logsnumber > 0 ):\n for current_file_num in range(logsnumber, 1, -1):\n src = file_name +\"_\" + str(current_file_num-1)\n dst = file_name +\"_\" + str(current_file_num)\n if(os.path.isfile(src) == True):\n shutil.copy(src, dst)\n print(\"Copied: \" + src + \" to \" + dst)\n shutil.copyfile(file_name, file_name + \"_1\")\n print(\" Copied: \" + file_name + \" to\" + file_name + \"_1\")\n myfile = open(file_name, 'w')\n myfile.close()\n\n\n\n\n\n\n\n","sub_path":"logscript.py","file_name":"logscript.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"590921096","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 \n\nclass Student(object):\n def __init__(self,name):\n self.name = name\n def __str__(self):\n return 'Student object(name: %s)' % self.name\n __repr__ = __str__#str返回用户看到的字符串,repr返回开发者看到的字符串\n\ns = Student('Michael')\nprint(s)\n\nclass Fib(object):\n '''\n def __init__(self):\n self.a = 0\n self.b = 1\n def __iter__(self):\n return self\n def __next__(self):\n self.a,self.b = self.b,self.a+self.b\n if self.a> 10000:\n raise StopIteration\n return self.a\n \n '''\n def __getitem__(self,n):\n if isinstance(n,int):\n a,b = 1,1\n for x in range(n):\n a,b = b, a+b\n return a\n if isinstance(n,slice):\n start = n.start\n stop = n.stop\n if start is None:\n start = 0\n L = []#Fib是不能切片的,如果一定要切必须要搞一个L[]来切\n a,b =1,1\n for x in range(stop):\n if x>=start:\n L.append(a)\n a,b = b, a+b\n return L\nf = Fib()\nprint(f[10])\nprint(f[10:20])\n\nclass Student(object):\n\tdef __init__(self):\n\t\tself.name = 'Michael'\n#让调用不存在的属性时\t,会调用__getattr__方法,动态返回一个属性或者方法\t\n\tdef __getattr__(self,attr):\n\t\tif attr == 'score':\n\t\t\treturn 99\n\t\tif attr == 'age':\n\t\t\treturn lambda x:2018 - x\n\t\traise AttributeError( '\\'Student\\' no such attribute.')\n\t\t\n\tdef __call__(self):#直接调用实例,没有任何参数传入\n\t\treturn('Hello')\n\t\t\ns = Student()#有了__call__方法的类就是一个可以调用的对象\nprint(s.name)\nprint(s.age(1996))\nprint(s())\n\nprint(callable(Student()))\n\nclass Chain(object):\n\tdef __init__(self, path = ''):\n\t\tself._path = path\n\tdef __getattr__(self,path):\n\t\treturn Chain('%s/%s' %(self._path,path))\n\tdef __str__(self):\n\t\treturn self._path\n\t\t\n\t__repr__ = __str__\n\t\t\nprint(Chain().status.user.timeline.list)\t\t","sub_path":"Python/work/21___str__.py","file_name":"21___str__.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"411982832","text":"import numpy as np\nfrom scipy import fftpack\nimport matplotlib.pyplot as plt\nfrom matplotlib.pylab import mpl\n\nmpl.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文\nmpl.rcParams['axes.unicode_minus'] = False # 显示负号\n\n\"\"\"\n1111111111111111111111111111111\n\"\"\"\n# 采样点选择1400个,因为设置的信号频率分量最高为600赫兹,\n# 根据采样定理知采样频率要大于信号频率2倍,所以这里设置采样频率为1400赫兹(即一秒内有1400个采样点,一样意思的)\nx = np.linspace(0, 1, 1400)\n\n# 设置需要采样的信号,频率分量有200,400和600\ny = 7 * np.sin(2 * np.pi * 200 * x) + 5 * np.sin(2 * np.pi * 400 * x) + 3 * np.sin(2 * np.pi * 600 * x)\n\nplt.figure()\nplt.plot(x, y)\nplt.title('原始波形')\n\nplt.figure()\nn = 50\nplt.plot(x[0:n], y[0:n])\nplt.title('原始部分波形(前50组样本)')\nplt.show()\n\n\"\"\"\n22222222222222222222222222\n\"\"\"\n\nfft_y = fftpack.fft(y)\nprint(len(fft_y))\nprint(fft_y[0:5])\n\n\"\"\"\n33333333333333333333333333333\n\"\"\"\nN = 1400\nx = np.arange(N) # 频率个数\n\nabs_y = np.abs(fft_y) # 取复数的绝对值,即复数的模(双边频谱)\nangle_y = np.angle(fft_y) # 取复数的角度\n\nplt.figure()\nplt.plot(x, abs_y)\nplt.title('双边振幅谱(未归一化)')\n\nplt.figure()\nplt.plot(x, angle_y)\nplt.title('双边相位谱(未归一化)')\nplt.show()\n\n\"\"\"\n444444444444444444444444444\n\"\"\"\nnormalization_y = abs_y / N # 归一化处理(双边频谱)\nplt.figure()\nplt.plot(x, normalization_y, 'g')\nplt.title('双边频谱(归一化)', fontsize=9, color='green')\nplt.show()\n\n\"\"\"\n55555555555555555555555555555\n\"\"\"\n\nhalf_x = x[range(int(N / 2))] # 取一半区间\nnormalization_half_y = normalization_y[range(int(N / 2))] # 由于对称性,只取一半区间(单边频谱)\nplt.figure()\nplt.plot(half_x, normalization_half_y, 'b')\nplt.title('单边频谱(归一化)', fontsize=9, color='blue')\nplt.show()\n","sub_path":"fourier/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"497491910","text":"from django.conf.urls import url\n\nfrom . import views\n\napp_name = 'image_match'\n\nurlpatterns = [\n url(r'^',views.home,name='home'),\n url(r'^thanks/$',views.thanks,name='thanks')\n # url(r'^$','image_match.views.ImageCreateView',name='home')\n ]","sub_path":"image_match/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"524297126","text":"# -*- coding: utf-8 -*-\n\"\"\"Cisco Identity Services Engine ACISettings API wrapper.\n\nCopyright (c) 2021 Cisco and/or its affiliates.\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\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom builtins import *\n\nfrom past.builtins import basestring\n\nfrom ...pagination import get_next_page\nfrom ...restsession import RestSession\nfrom ...utils import (\n apply_path_params,\n check_type,\n dict_from_items_with_values,\n dict_of_str,\n)\n\n\nclass AciSettings(object):\n \"\"\"Identity Services Engine ACISettings API (version: 3.1.0).\n\n Wraps the Identity Services Engine ACISettings\n API and exposes the API as native Python\n methods that return native Python objects.\n\n | ACI Settings API allows the client to get and update the ACI Settings. In addition, testing the ACI Domain Manager connection is also possible using the TestACIConnection.\n\n **Revision History**\n\n +----------------+----------------------+-----------------------+---------------------------+\n | **Revision #** | **Resource Version** | **Cisco ISE Version** | **Description** |\n +----------------+----------------------+-----------------------+---------------------------+\n | 0 | 1.0 | 3.0 | Initial Cisco ISE Version |\n +----------------+----------------------+-----------------------+---------------------------+\n\n |\n\n **Resource Definition**\n\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | **Attribute** | **Type** | **Required** | **Description** | **Default Values** | **Example Values** |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | name | String | Yes | Resource Name | | AciSettings |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | id | String | No | Resource UUID value | | 29fb45ab-6a8e-4658-8a28-02521c258178 |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | description | String | No | | | Aci Settings |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | enableAci | Boolean | Yes | Enable ACI Integration | false | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | isAci50 | Boolean | Yes | Enable 5.0 ACI Version | false | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | ipAddressHostName | String | No | ACI Cluster IP Address / Host name | | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | adminName | String | No | ACI Cluster Admin name | | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | adminPassword | String | No | ACI Cluster Admin password | | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | tenantName | String | No | ACI Cluster Tenant name | ISE | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | l3RouteNetwork | String | No | ACI Cluster L3 Route network name | L3_ROUTE | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | suffixToEpg | String | No | Name Conversion - EPG suffix | SGT | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | suffixToSgt | String | No | Name Conversion - SGT suffix | EPG | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | allSxpDomain | Boolean | No | SXP Propagation to all the SXP domains | false | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | specificSxpDomain | Boolean | No | SXP Propagation to specific SXP domains | true | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | specifixSxpDomainList | List | No | Specific SXP domains list | [default] | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | isAci51 | Boolean | Yes | Enable 5.1 ACI Version | false | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | aciipaddress | String | No | ACI Domain manager Ip Address | | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | aciuserName | String | No | ACI Domain manager Username | | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | acipassword | String | No | ACI Domain manager Password | | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | enableDataPlane | Boolean | No | Enable data plane | false | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | untaggedPacketIepgName | String | No | Untagged IEPG packets name | untagged | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | defaultSgtName | String | No | Default SGT name | Unknown | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | enableElementsLimit | Boolean | No | Enable Elements Limit | false | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | maxNumIepgFromAci | Integer | No | Max number of IEPGs | 1000 | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n | maxNumSgtToAci | Integer | No | Max number of SGTs | 500 | |\n +------------------------+----------+--------------+-----------------------------------------+--------------------+--------------------------------------+\n\n \"\"\"\n\n def __init__(self, session, object_factory, request_validator):\n \"\"\"Initialize a new AciSettings\n object with the provided RestSession.\n\n Args:\n session(RestSession): The RESTful session object to be used for\n API calls to the Identity Services Engine service.\n\n Raises:\n TypeError: If the parameter types are incorrect.\n\n \"\"\"\n check_type(session, RestSession)\n\n super(AciSettings, self).__init__()\n\n self._session = session\n self._object_factory = object_factory\n self._request_validator = request_validator\n\n def get_aci_settings(self,\n headers=None,\n **query_parameters):\n \"\"\"This API allows the client to get ACI Settings.\n\n Args:\n headers(dict): Dictionary of HTTP Headers to send with the Request\n .\n **query_parameters: Additional query parameters (provides\n support for parameters that may be added in the future).\n\n Returns:\n\n RestResponse: REST response with following properties:\n\n - headers(MyDict): response headers.\n - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation\n or the bracket notation.\n - content(bytes): representation of the request's response\n - text(str): representation of the request's response\n\n Raises:\n TypeError: If the parameter types are incorrect.\n MalformedRequest: If the request body created is invalid.\n ApiError: If the Identity Services Engine cloud returns an error.\n \"\"\"\n check_type(headers, dict)\n\n if headers is not None:\n if 'Content-Type' in headers:\n check_type(headers.get('Content-Type'),\n basestring, may_be_none=False)\n if 'Accept' in headers:\n check_type(headers.get('Accept'),\n basestring, may_be_none=False)\n if 'ERS-Media-Type' in headers:\n check_type(headers.get('ERS-Media-Type'),\n basestring)\n if 'X-CSRF-Token' in headers:\n check_type(headers.get('X-CSRF-Token'),\n basestring)\n\n with_custom_headers = False\n _headers = self._session.headers or {}\n if headers:\n _headers.update(dict_of_str(headers))\n with_custom_headers = True\n\n _params = {\n }\n _params.update(query_parameters)\n _params = dict_from_items_with_values(_params)\n\n path_params = {\n }\n\n e_url = ('/ers/config/acisettings')\n endpoint_full_url = apply_path_params(e_url, path_params)\n if with_custom_headers:\n _api_response = self._session.get(endpoint_full_url, params=_params,\n headers=_headers)\n else:\n _api_response = self._session.get(endpoint_full_url, params=_params)\n\n return self._object_factory('bpm_ea5c865993b56f48f7f43475294a20c_v3_1_0', _api_response)\n\n def get_all(self,\n headers=None,\n **query_parameters):\n \"\"\"Alias for `get_aci_settings <#ciscoisesdk.\n api.v3_1_0.aci_settings.\n AciSettings.get_aci_settings>`_\n \"\"\"\n return self.get_aci_settings(\n headers=headers,\n **query_parameters\n )\n\n def test_aci_connectivity(self,\n headers=None,\n **query_parameters):\n \"\"\"This API allows the client to test ACI Domain Manager\n connection.\n\n Args:\n headers(dict): Dictionary of HTTP Headers to send with the Request\n .\n **query_parameters: Additional query parameters (provides\n support for parameters that may be added in the future).\n\n Returns:\n\n RestResponse: REST response with following properties:\n\n - headers(MyDict): response headers.\n - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation\n or the bracket notation.\n - content(bytes): representation of the request's response\n - text(str): representation of the request's response\n\n Raises:\n TypeError: If the parameter types are incorrect.\n MalformedRequest: If the request body created is invalid.\n ApiError: If the Identity Services Engine cloud returns an error.\n \"\"\"\n check_type(headers, dict)\n\n if headers is not None:\n if 'Content-Type' in headers:\n check_type(headers.get('Content-Type'),\n basestring, may_be_none=False)\n if 'Accept' in headers:\n check_type(headers.get('Accept'),\n basestring, may_be_none=False)\n if 'ERS-Media-Type' in headers:\n check_type(headers.get('ERS-Media-Type'),\n basestring)\n if 'X-CSRF-Token' in headers:\n check_type(headers.get('X-CSRF-Token'),\n basestring)\n\n with_custom_headers = False\n _headers = self._session.headers or {}\n if headers:\n _headers.update(dict_of_str(headers))\n with_custom_headers = True\n\n _params = {\n }\n _params.update(query_parameters)\n _params = dict_from_items_with_values(_params)\n\n path_params = {\n }\n\n e_url = ('/ers/config/acisettings/testACIConnectivity')\n endpoint_full_url = apply_path_params(e_url, path_params)\n\n if with_custom_headers:\n _api_response = self._session.put(endpoint_full_url, params=_params,\n headers=_headers)\n else:\n _api_response = self._session.put(endpoint_full_url, params=_params)\n\n return self._object_factory('bpm_b155c91eec153338302d492db1afb80_v3_1_0', _api_response)\n\n def update_aci_settings_by_id(self,\n id,\n aci50=None,\n aci51=None,\n aciipaddress=None,\n acipassword=None,\n aciuser_name=None,\n admin_name=None,\n admin_password=None,\n all_sxp_domain=None,\n default_sgt_name=None,\n enable_aci=None,\n enable_data_plane=None,\n enable_elements_limit=None,\n ip_address_host_name=None,\n l3_route_network=None,\n max_num_iepg_from_aci=None,\n max_num_sgt_to_aci=None,\n specific_sxp_domain=None,\n specifix_sxp_domain_list=None,\n suffix_to_epg=None,\n suffix_to_sgt=None,\n tenant_name=None,\n untagged_packet_iepg_name=None,\n headers=None,\n payload=None,\n active_validation=True,\n **query_parameters):\n \"\"\"This API allows the client to update ACI settings.\n\n Args:\n aci50(boolean): Enable 5.0 ACI Version, property of the\n request body.\n aci51(boolean): Enable 5.1 ACI Version, property of the\n request body.\n aciipaddress(string): ACI Domain manager Ip Address.,\n property of the request body.\n acipassword(string): ACI Domain manager Password.,\n property of the request body.\n aciuser_name(string): ACI Domain manager Username.,\n property of the request body.\n admin_name(string): ACI Cluster Admin name, property of\n the request body.\n admin_password(string): ACI Cluster Admin password,\n property of the request body.\n all_sxp_domain(boolean): allSxpDomain, property of the\n request body.\n default_sgt_name(string): defaultSgtName, property of\n the request body.\n enable_aci(boolean): Enable ACI Integration, property of\n the request body.\n enable_data_plane(boolean): enableDataPlane, property of\n the request body.\n enable_elements_limit(boolean): enableElementsLimit,\n property of the request body.\n id(string): Resource UUID value, property of the request\n body.\n ip_address_host_name(string): ACI Cluster IP Address /\n Host name, property of the request body.\n l3_route_network(string): l3RouteNetwork, property of\n the request body.\n max_num_iepg_from_aci(integer): maxNumIepgFromAci,\n property of the request body.\n max_num_sgt_to_aci(integer): maxNumSgtToAci, property of\n the request body.\n specific_sxp_domain(boolean): specificSxpDomain,\n property of the request body.\n specifix_sxp_domain_list(list): specifixSxpDomainList,\n property of the request body (list of\n strings).\n suffix_to_epg(string): suffixToEpg, property of the\n request body.\n suffix_to_sgt(string): suffixToSgt, property of the\n request body.\n tenant_name(string): tenantName, property of the request\n body.\n untagged_packet_iepg_name(string):\n untaggedPacketIepgName, property of the\n request body.\n id(basestring): id path parameter.\n headers(dict): Dictionary of HTTP Headers to send with the Request\n .\n payload(dict): A JSON serializable Python object to send in the\n body of the Request.\n active_validation(bool): Enable/Disable payload validation.\n Defaults to True.\n **query_parameters: Additional query parameters (provides\n support for parameters that may be added in the future).\n\n Returns:\n\n RestResponse: REST response with following properties:\n\n - headers(MyDict): response headers.\n - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation\n or the bracket notation.\n - content(bytes): representation of the request's response\n - text(str): representation of the request's response\n\n Raises:\n TypeError: If the parameter types are incorrect.\n MalformedRequest: If the request body created is invalid.\n ApiError: If the Identity Services Engine cloud returns an error.\n \"\"\"\n check_type(headers, dict)\n\n if headers is not None:\n if 'Content-Type' in headers:\n check_type(headers.get('Content-Type'),\n basestring, may_be_none=False)\n if 'Accept' in headers:\n check_type(headers.get('Accept'),\n basestring, may_be_none=False)\n if 'ERS-Media-Type' in headers:\n check_type(headers.get('ERS-Media-Type'),\n basestring)\n if 'X-CSRF-Token' in headers:\n check_type(headers.get('X-CSRF-Token'),\n basestring)\n\n with_custom_headers = False\n _headers = self._session.headers or {}\n if headers:\n _headers.update(dict_of_str(headers))\n with_custom_headers = True\n is_xml_payload = 'application/xml' in _headers.get('Content-Type', [])\n if active_validation and is_xml_payload:\n check_type(payload, basestring)\n if active_validation and not is_xml_payload:\n check_type(payload, dict)\n check_type(id, basestring,\n may_be_none=False)\n\n _params = {\n }\n _params.update(query_parameters)\n _params = dict_from_items_with_values(_params)\n\n path_params = {\n 'id': id,\n }\n if is_xml_payload:\n _payload = payload\n else:\n _tmp_payload = {\n 'id':\n id,\n 'enableAci':\n enable_aci,\n 'ipAddressHostName':\n ip_address_host_name,\n 'adminName':\n admin_name,\n 'adminPassword':\n admin_password,\n 'aciipaddress':\n aciipaddress,\n 'aciuserName':\n aciuser_name,\n 'acipassword':\n acipassword,\n 'tenantName':\n tenant_name,\n 'l3RouteNetwork':\n l3_route_network,\n 'suffixToEpg':\n suffix_to_epg,\n 'suffixToSgt':\n suffix_to_sgt,\n 'allSxpDomain':\n all_sxp_domain,\n 'specificSxpDomain':\n specific_sxp_domain,\n 'specifixSxpDomainList':\n specifix_sxp_domain_list,\n 'enableDataPlane':\n enable_data_plane,\n 'untaggedPacketIepgName':\n untagged_packet_iepg_name,\n 'defaultSgtName':\n default_sgt_name,\n 'enableElementsLimit':\n enable_elements_limit,\n 'maxNumIepgFromAci':\n max_num_iepg_from_aci,\n 'maxNumSgtToAci':\n max_num_sgt_to_aci,\n 'aci50':\n aci50,\n 'aci51':\n aci51,\n }\n _payload = {\n 'AciSettings': dict_from_items_with_values(_tmp_payload)\n }\n _payload.update(payload or {})\n _payload = dict_from_items_with_values(_payload)\n if active_validation and not is_xml_payload:\n self._request_validator('jsd_cea2e785ee57908a9ee3b118e49cfa_v3_1_0')\\\n .validate(_payload)\n\n e_url = ('/ers/config/acisettings/{id}')\n endpoint_full_url = apply_path_params(e_url, path_params)\n\n request_params = {'data': _payload} if is_xml_payload else {'json': _payload}\n if with_custom_headers:\n _api_response = self._session.put(endpoint_full_url, params=_params,\n headers=_headers,\n **request_params)\n\n else:\n _api_response = self._session.put(endpoint_full_url, params=_params,\n **request_params)\n\n return self._object_factory('bpm_cea2e785ee57908a9ee3b118e49cfa_v3_1_0', _api_response)\n\n def update_by_id(self,\n id,\n aci50=None,\n aci51=None,\n aciipaddress=None,\n acipassword=None,\n aciuser_name=None,\n admin_name=None,\n admin_password=None,\n all_sxp_domain=None,\n default_sgt_name=None,\n enable_aci=None,\n enable_data_plane=None,\n enable_elements_limit=None,\n ip_address_host_name=None,\n l3_route_network=None,\n max_num_iepg_from_aci=None,\n max_num_sgt_to_aci=None,\n specific_sxp_domain=None,\n specifix_sxp_domain_list=None,\n suffix_to_epg=None,\n suffix_to_sgt=None,\n tenant_name=None,\n untagged_packet_iepg_name=None,\n headers=None,\n payload=None,\n active_validation=True,\n **query_parameters):\n \"\"\"Alias for `update_aci_settings_by_id <#ciscoisesdk.\n api.v3_1_0.aci_settings.\n AciSettings.update_aci_settings_by_id>`_\n \"\"\"\n return self.update_aci_settings_by_id(\n id=id,\n aci50=aci50,\n aci51=aci51,\n aciipaddress=aciipaddress,\n acipassword=acipassword,\n aciuser_name=aciuser_name,\n admin_name=admin_name,\n admin_password=admin_password,\n all_sxp_domain=all_sxp_domain,\n default_sgt_name=default_sgt_name,\n enable_aci=enable_aci,\n enable_data_plane=enable_data_plane,\n enable_elements_limit=enable_elements_limit,\n ip_address_host_name=ip_address_host_name,\n l3_route_network=l3_route_network,\n max_num_iepg_from_aci=max_num_iepg_from_aci,\n max_num_sgt_to_aci=max_num_sgt_to_aci,\n specific_sxp_domain=specific_sxp_domain,\n specifix_sxp_domain_list=specifix_sxp_domain_list,\n suffix_to_epg=suffix_to_epg,\n suffix_to_sgt=suffix_to_sgt,\n tenant_name=tenant_name,\n untagged_packet_iepg_name=untagged_packet_iepg_name,\n payload=payload,\n active_validation=active_validation,\n headers=headers,\n **query_parameters\n )\n\n def get_version(self,\n headers=None,\n **query_parameters):\n \"\"\"This API helps to retrieve the version information related to\n the Cisco ACI settings.\n\n Args:\n headers(dict): Dictionary of HTTP Headers to send with the Request\n .\n **query_parameters: Additional query parameters (provides\n support for parameters that may be added in the future).\n\n Returns:\n\n RestResponse: REST response with following properties:\n\n - headers(MyDict): response headers.\n - response(MyDict): response body as a MyDict object. Access the object's properties by using the dot notation\n or the bracket notation.\n - content(bytes): representation of the request's response\n - text(str): representation of the request's response\n\n Raises:\n TypeError: If the parameter types are incorrect.\n MalformedRequest: If the request body created is invalid.\n ApiError: If the Identity Services Engine cloud returns an error.\n \"\"\"\n check_type(headers, dict)\n\n if headers is not None:\n if 'Content-Type' in headers:\n check_type(headers.get('Content-Type'),\n basestring, may_be_none=False)\n if 'Accept' in headers:\n check_type(headers.get('Accept'),\n basestring, may_be_none=False)\n\n with_custom_headers = False\n _headers = self._session.headers or {}\n if headers:\n _headers.update(dict_of_str(headers))\n with_custom_headers = True\n\n _params = {\n }\n _params.update(query_parameters)\n _params = dict_from_items_with_values(_params)\n\n path_params = {\n }\n\n e_url = ('/ers/config/acisettings/versioninfo')\n endpoint_full_url = apply_path_params(e_url, path_params)\n if with_custom_headers:\n _api_response = self._session.get(endpoint_full_url, params=_params,\n headers=_headers)\n else:\n _api_response = self._session.get(endpoint_full_url, params=_params)\n\n return self._object_factory('bpm_ea47f65521bcf0ab949b5d72b5_v3_1_0', _api_response)\n","sub_path":"ciscoisesdk/api/v3_1_0/aci_settings.py","file_name":"aci_settings.py","file_ext":"py","file_size_in_byte":31358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"488970123","text":"import turtle\r\nimport time\r\nimport sys\r\n\r\n'''\r\nTugas UTS Instrumentasi Sistem Robotika\r\nMahatma Ageng Wisesa \r\n17/411372/TK/45857\r\n'''\r\nwin = turtle.Screen()\r\nwin.bgcolor('#ffffff')\r\nwin.setup(620,620)\r\n\r\ngrid = 21 # grid pixels \r\n\r\nclass wall(turtle.Turtle):\r\n def __init__(self):\r\n turtle.Turtle.__init__(self)\r\n self.shape('square') \r\n self.color('#636363') \r\n self.penup() \r\n self.speed(0)\r\n\r\nclass objective(turtle.Turtle):\r\n def __init__(self):\r\n turtle.Turtle.__init__(self)\r\n self.shape('square')\r\n self.color('yellow')\r\n self.penup()\r\n self.speed(0)\r\n\r\nclass robot(turtle.Turtle):\r\n def __init__(self):\r\n turtle.Turtle.__init__(self)\r\n self.shape('arrow')\r\n self.shapesize(0.4, 0.4, 0.4)\r\n self.color('red')\r\n self.setheading(270)\r\n #self.penup()\r\n self.pensize(1)\r\n self.speed(0)\r\n\r\n def go_left(self):\r\n if (self.heading() == 0): # Jika robot ngarah ke timur\r\n x_robot = round(robot.xcor(),0)\r\n y_robot = round(robot.ycor(),0)\r\n\r\n if (x_robot, y_robot) in finish: # Robot jika di titik Finish\r\n print('FINISHED')\r\n stop() # Break loop\r\n\r\n if (x_robot, y_robot+grid) not in walls: # Jika tidak ada tembok di kiri (ada di list tembok)\r\n self.left(90) # Putar ke kiri 90 derajar\r\n self.forward(grid) # Maju sejauh satu langkah\r\n else: # Jika ada tembok di kiri\r\n if(x_robot+grid, y_robot) not in walls: # Jika tidak ada tembok di depan (tidak ada list tembok)\r\n self.forward(grid) # Maju sejauh grid\r\n else: # Jika ada tembok di depan\r\n self.right(90) # Putar ke kanan 90 derajat\r\n\r\n def go_right(self):\r\n if (self.heading() == 180): # Jika robot ngarah ke barat\r\n x_robot = round(robot.xcor(),0)\r\n y_robot = round(robot.ycor(),0)\r\n \r\n if (x_robot, y_robot) in finish: # Robot jika di titik Finish\r\n print('FINISHED')\r\n stop() # Break loop\r\n\r\n if (x_robot, y_robot-grid) not in walls:\r\n self.left(90) # Putar ke kiri 90 derajar\r\n self.forward(grid) # Maju sejauh satu langkah\r\n else: # Jika ada tembok di kiri\r\n if(x_robot-grid, y_robot) not in walls:\r\n self.forward(grid)\r\n else:\r\n self.right(90)\r\n\r\n def go_up(self):\r\n if (self.heading() == 90):\r\n x_robot = round(robot.xcor(),0)\r\n y_robot = round(robot.ycor(),0)\r\n\r\n if (x_robot, y_robot) in finish:\r\n print('FINISHED')\r\n stop()\r\n \r\n if (x_robot-grid, y_robot) not in walls:\r\n self.left(90)\r\n self.forward(grid)\r\n else:\r\n if(x_robot, y_robot+grid) not in walls:\r\n self.forward(grid)\r\n else:\r\n self.right(90)\r\n\r\n def go_down(self):\r\n if (self.heading() == 270):\r\n x_robot = round(robot.xcor(),0)\r\n y_robot = round(robot.ycor(),0)\r\n\r\n if (x_robot, y_robot) in finish:\r\n print('FINISHED')\r\n stop()\r\n\r\n #if (not((x_robot+grid, y_robot) in walls)) and ((x_robot, y_robot-grid) not in walls):\r\n # self.forward(grid)\r\n if (x_robot+grid, y_robot) not in walls and (x_robot, y_robot-grid) not in walls and (x_robot-grid, y_robot) not in walls and (x_robot+grid, y_robot+grid) not in walls:\r\n self.forward(grid) # jika tidak ada tembok di kiri, kanan, dan belakang kiri\r\n else:\r\n if (x_robot+grid, y_robot) not in walls:\r\n self.left(90)\r\n self.forward(grid)\r\n else:\r\n if (x_robot, y_robot-grid) not in walls:\r\n self.forward(grid)\r\n else:\r\n self.right(90)\r\n\r\n# bentuk matrix\r\n\r\nbox = [\r\n\"+++++++++++++++++++++++++++++\",\r\n\"+ + +\",\r\n\"+ + +\",\r\n\"+ + +\",\r\n\"+++++++ + +\",\r\n\"e + ++++ +++++++++\",\r\n\"+ + + +\",\r\n\"+ + + +\",\r\n\"+ + + +\",\r\n\"+ + + +\",\r\n\"+ + ++++++++++++++++\",\r\n\"+ + + + +\",\r\n\"+ + + + +\",\r\n\"++++ + +\",\r\n\"+ + + s +\",\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]\r\n\r\ndef setupWall(box):\r\n for y in range(len(box)): # ekstrak karakter baris Array 'box'\r\n for x in range(len(box[y])): # ekstrak karakter kolom Array 'box'\r\n char = box[y][x] # karakter setiap baris setiap kolom \r\n x_win = -298 + (x*grid) # koordinat x tembok\r\n y_win = 298 - (y*grid) # koordinat y tembok\r\n \r\n if char == \"+\": # jika dalam kolom setap baris ada '+'\r\n wall_set.goto(x_win, y_win) # set tembok ke koordinat sesuai baris\r\n wall_set.stamp() # stamp setiap iterasi objek wall win \r\n walls.append((x_win, y_win)) # masukan koordinat ke list walls\r\n\r\n if char == \"e\": # jika dalam kolom setap baris ada 'e'\r\n objective.goto(x_win, y_win) # set tembok ke koordinat sesuai baris\r\n objective.stamp() # stamp setiap iterasi objek exit ke win \r\n finish.append((x_win, y_win)) # masukan koodinat ke list finish\r\n\r\n if char == \"s\": # jika terdapat karakter 's' set ke koordinat itu\r\n robot.goto(x_win, y_win) \r\n\r\nrun = True\r\n\r\ndef stop():\r\n run = False # break infinite loop jika terpenuhi\r\n win.exitonclick() \r\n sys.exit() \r\n\r\nwall_set = wall()\r\nrobot = robot()\r\nobjective = objective()\r\n\r\nwalls = []\r\nfinish = []\r\n\r\nsetupWall(box)\r\n\r\nwhile run: # infinite loop sampai fungsi stop dieksekusi atau finish tercapai\r\n robot.go_right()\r\n robot.go_down()\r\n robot.go_left()\r\n robot.go_up()\r\n\r\n time.sleep(0.03)","sub_path":"UTS_Robotika(Final)_45857.py","file_name":"UTS_Robotika(Final)_45857.py","file_ext":"py","file_size_in_byte":7568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"4834627","text":"# -*- coding: utf-8 -*-\n# Copyright 2020 Google LLC\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 proto # type: ignore\n\nfrom google.cloud.servicedirectory_v1beta1.types import endpoint\n\n\n__protobuf__ = proto.module(\n package='google.cloud.servicedirectory.v1beta1',\n manifest={\n 'Service',\n },\n)\n\n\nclass Service(proto.Message):\n r\"\"\"An individual service. A service contains a name and optional\n metadata. A service must exist before\n [endpoints][google.cloud.servicedirectory.v1beta1.Endpoint] can be\n added to it.\n\n Attributes:\n name (str):\n Immutable. The resource name for the service in the format\n 'projects/*/locations/*/namespaces/*/services/*'.\n metadata (Sequence[google.cloud.servicedirectory_v1beta1.types.Service.MetadataEntry]):\n Optional. Metadata for the service. This data\n can be consumed by service clients. The entire\n metadata dictionary may contain up to 2000\n characters, spread across all key-value pairs.\n Metadata that goes beyond any these limits will\n be rejected.\n endpoints (Sequence[google.cloud.servicedirectory_v1beta1.types.Endpoint]):\n Output only. Endpoints associated with this\n service. Returned on LookupService.Resolve.\n Control plane clients should use\n RegistrationService.ListEndpoints.\n \"\"\"\n\n name = proto.Field(\n proto.STRING,\n number=1,\n )\n metadata = proto.MapField(\n proto.STRING,\n proto.STRING,\n number=2,\n )\n endpoints = proto.RepeatedField(\n proto.MESSAGE,\n number=3,\n message=endpoint.Endpoint,\n )\n\n\n__all__ = tuple(sorted(__protobuf__.manifest))\n","sub_path":"google/cloud/servicedirectory/v1beta1/servicedirectory-v1beta1-py/google/cloud/servicedirectory_v1beta1/types/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"367906051","text":"#recursion lecture- factorial\n\n#What's the base case? n == 1\n#Reduction of problem = n*(n-1)!\n#Remember the weird idea of function calling itself\n\ndef fact(n):\n if n == 1:\n return 1 #Base case\n else:\n return n*fact(n-1)\n\n\n\n\n#\n#Below is the non recursive way\ndef factorial(n):\n\n '''\n n is the (input) number. The function takes the number and multiplies it\n as n decreases\n\n '''\n inside = []\n for i in range(1, n + 1):\n inside.append(i)\n product = 1\n for a in inside:\n product *= a\n return product\n\n\n\n#\n# print(factorial(int(input())))\n","sub_path":"Intro to CS/lectures/lect6.py","file_name":"lect6.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"326172423","text":"\nimport FWCore.ParameterSet.Config as cms\nprocess = cms.Process( \"Alignment\" )\n\nfrom Alignment.KalmanAlignmentAlgorithm.KalmanAlignmentAlgorithm_Commons import loadKAACommons\nloadKAACommons( cms, process )\n\n# message logger\nprocess.MessageLogger = cms.Service( \"MessageLogger\",\n\n categories = cms.untracked.vstring( \"Alignment\", \"AlignmentIORootBase\" ),\n\n statistics = cms.untracked.vstring( \"alignmentISN\" ),\n destinations = cms.untracked.vstring( \"alignmentISN\" ),\n\n alignment = cms.untracked.PSet(\n noLineBreaks = cms.untracked.bool( True ),\n threshold = cms.untracked.string( \"INFO\" ),\n\n INFO = cms.untracked.PSet( limit = cms.untracked.int32(0) ),\n DEBUG = cms.untracked.PSet( limit = cms.untracked.int32(0) ),\n WARNING = cms.untracked.PSet( limit = cms.untracked.int32(0) ),\n ERROR = cms.untracked.PSet( limit = cms.untracked.int32(0) ),\n\n TrackProducer = cms.untracked.PSet( limit = cms.untracked.int32(-1) ),\n Alignment = cms.untracked.PSet( limit = cms.untracked.int32(-1) ),\n AlignmentIORootBase = cms.untracked.PSet( limit = cms.untracked.int32(-1) )\n )\n)\n\nprocess.AlignmentProducer.doMisalignmentScenario = cms.bool( False )\n\nprocess.AlignmentProducer.ParameterBuilder = cms.PSet(\n parameterTypes = cms.vstring( \"Selector,RigidBody\" ),\n Selector = cms.PSet(\n alignParams = cms.vstring(\n \"PixelHalfBarrels,111001\", \n \"PXEndCaps,111001\", \n \"TIBLayersLayers12,111001\", \n \"TIBLayersLayers34,110001\", \n \"TIDLayers,111001\", \n \"TOBHalfBarrels,111111\", \n \"TECLayers,001000\"\n )\n )\n)\n\nprocess.AlignmentProducer.ParameterStore.UseExtendedCorrelations = cms.untracked.bool( False )\n\nprocess.DualTrajectoryFactory.UseHitWithoutDet = cms.bool( False )\n\nprocess.AlignmentProducer.algoConfig.AlgorithmConfig = cms.PSet(\n debug = cms.untracked.bool( True ),\n src = cms.string( \"\" ),\n bsSrc = cms.string( \"\" ),\n Fitter = cms.string( \"KFFittingSmoother\" ),\n Propagator = cms.string( \"AnalyticalPropagator\" ),\n TTRHBuilder = cms.string( \"WithoutRefit\" ),\n\n Setups = cms.vstring( \"FullTracking\" ),\n\n FullTracking = cms.PSet(\n AlignmentUpdator = cms.PSet( process.SingleTrajectoryUpdatorForStrips ),\n MetricsUpdator = cms.PSet( process.DummyMetricsUpdator ),\n TrajectoryFactory = cms.PSet( process.DualTrajectoryFactory ),\n\n Tracking = cms.vint32( 1, 2, 3, 4, 5,6 ),\n External = cms.vint32(),\n\n PropagationDirection = cms.untracked.string( \"alongMomentum\" ),\n SortingDirection = cms.untracked.string( \"SortUpsideDown\" ),\n MinTrackingHits = cms.untracked.uint32(8)\n )\n)\n\nprocess.AlignmentProducer.algoConfig.ParameterConfig = cms.PSet(\n ApplyRandomStartValues = cms.untracked.bool( False ),\n UpdateGraphs = cms.untracked.int32(1000),\n\n InitializationSelector = cms.vstring( \"OuterTrackerDets\", \"FixedAlignables\", \"FreeAlignables\" ),\n\n OuterTrackerDets = cms.PSet(\n AlignableSelection = cms.vstring( \"TOBDets\", \"TECDets\" ),\n\n ApplyParametersFromFile = cms.untracked.bool(True),\n FileName = cms.untracked.string( \"MSSDIR/outer-tracker-dets.root\" )\n ),\n \n FixedAlignables = cms.PSet(\n AlignableSelection = cms.vstring( \"TOBHalfBarrels\" ),\n\n XShiftsStartError = cms.untracked.double(1e-10),\n YShiftsStartError = cms.untracked.double(1e-10),\n ZShiftsStartError = cms.untracked.double(1e-10),\n XRotationsStartError = cms.untracked.double(1e-12),\n YRotationsStartError = cms.untracked.double(1e-12),\n ZRotationsStartError = cms.untracked.double(1e-12)\n ),\n\n FreeAlignables = cms.PSet(\n AlignableSelection = cms.vstring( \"PixelHalfBarrels\", \"PXEndCaps\", \"TIBLayers\", \"TIDLayers\", \"TECLayers\" ),\n \n XShiftsStartError = cms.untracked.double(0.0002),\n YShiftsStartError = cms.untracked.double(0.0002),\n ZShiftsStartError = cms.untracked.double(0.0002),\n XRotationsStartError = cms.untracked.double(1e-08),\n YRotationsStartError = cms.untracked.double(1e-08),\n ZRotationsStartError = cms.untracked.double(1e-08)\n )\n)\n\nprocess.AlignmentProducer.algoConfig.OutputFile = \"kaaOutputISN.root\"\nprocess.AlignmentProducer.algoConfig.TimingLogFile = \"kaaTimingISN.root\"\nprocess.AlignmentProducer.algoConfig.DataCollector.FileName = \"kaaDebugISN.root\"\n\nprocess.AlignmentProducer.algoConfig.MergeResults = cms.bool( False )\nprocess.AlignmentProducer.algoConfig.Merger.InputMergeFileNames = cms.vstring()\n\n# apply alignment and calibration constants from database\nprocess.load( \"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\" )\nprocess.GlobalTag.globaltag = \"STARTUP_V5::All\"\n\n# track selection\nprocess.AlignmentTrackSelector.src = \"ALCARECOTkAlCosmicsCTF\"\nprocess.AlignmentTrackSelector.ptMin = 1.0\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )\n\nprocess.source = cms.Source( \"PoolSource\",\n skipEvents = cms.untracked.uint32(0),\n fileNames = cms.untracked.vstring()\n)\n","sub_path":"Alignment/KalmanAlignmentAlgorithm/test/template.inner_tracker_layers_cfg.py","file_name":"template.inner_tracker_layers_cfg.py","file_ext":"py","file_size_in_byte":5104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"92397512","text":"class Solution:\n\tdef groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n\t\td ={}\n\t\tfor str in strs:\n\t\t\tFV = self.getFV(str)\n\t\t\td[FV] = d.get(FV, []) + [str]\n\t\treturn [d[key] for key in d]\n\t\n\tdef getFV(self, str):\n\t\tFV = [0 for _ in range(26)]\n\t\tfor c in str:\n\t\t\tFV[ord(c) - ord('a')] += 1\n\t\treturn tuple(FV)\n","sub_path":"hash-table/group-anagrams.py","file_name":"group-anagrams.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"142341006","text":"import numpy as np\nimport Neural.NeuralNetwork as nN\n\n\ndef main():\n\n np.random.seed(0)\n\n nn_configuration = []\n\n layer_config_a = [(2, 1), (4, 2), (4, 1)]\n layer_config_b = [(4, 1), (1, 4), (1, 1)]\n\n nn_configuration.append(layer_config_a)\n nn_configuration.append(layer_config_b)\n\n nn = nN.NeuralNetwork(nn_configuration)\n\n input_filename = \"data/input\"\n output_filename = \"data/output\"\n input_data = np.fromfile(input_filename, dtype=np.dtype('f8'), sep=' ').reshape(2, 4)\n output_data = np.fromfile(output_filename, dtype=np.dtype('f8'), sep=' ').reshape(1, 4)\n\n nn.optimize(input_data, output_data, True)\n\n for i in range(4):\n d = output_data[:, i].reshape(1, 1)\n print(d)\n\n for i in range(4):\n x = input_data[:, i].reshape(2, 1)\n y = nn.feed_forward(x)\n print(y)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"21271587","text":"# Copyright 2015 Metaswitch Networks\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\"\"\"\nUsage:\n calicoctl checksystem [--fix]\n\nDescription:\n Check for incompatibilities between calico and the host system\n\nOptions:\n --fix Allow calicoctl to attempt to correct any issues detected on the host\n\"\"\"\nimport sys\nimport re\nimport sh\n\nimport docker\nfrom requests import ConnectionError\n\nfrom utils import DOCKER_VERSION\nfrom utils import enforce_root\nfrom utils import sysctl\nfrom connectors import docker_client\n\ndef checksystem(arguments):\n \"\"\"\n Main dispatcher for checksystem commands. Calls the corresponding helper\n function. checksystem only has one main function, so we call that function\n directly.\n\n :param arguments: A dictionary of arguments already processed through\n this file's docstring with docopt\n :return: None\n \"\"\"\n check_system(fix=arguments[\"--fix\"], quit_if_error=True)\n\n\ndef check_system(fix=False, quit_if_error=False):\n \"\"\"\n Checks that the system is setup correctly. fix==True, this command will\n attempt to fix any issues it encounters. If any fixes fail, it will\n exit(1). Fix will automatically be set to True if the user specifies --fix\n at the command line.\n\n :param fix: if True, try to fix any system dependency issues that are\n detected.\n :param quit_if_error: if True, quit with error code 1 if any issues are\n detected, or if any fixes are unsuccesful.\n :return: True if all system dependencies are in the proper state, False if\n they are not. This function will sys.exit(1) instead of returning false if\n quit_if_error == True\n \"\"\"\n # modprobe and sysctl require root privileges.\n enforce_root()\n\n system_ok = (_check_kernel_modules(fix) and\n _check_ip_forwarding(fix) and\n _check_docker_version())\n\n if quit_if_error and not system_ok:\n sys.exit(1)\n\n return system_ok\n\n\ndef module_loaded(module):\n \"\"\"\n Checks if the specified kernel-module has been loaded.\n :param module: Name of the module to check\n :return: True if the module is loaded, False if not.\n \"\"\"\n return any(s.startswith(module) for s in open(\"/proc/modules\").readlines())\n\n\ndef normalize_version(version):\n \"\"\"\n This function convers a string representation of a version into\n a list of integer values.\n e.g.: \"1.5.10\" => [1, 5, 10]\n http://stackoverflow.com/questions/1714027/version-number-comparison\n \"\"\"\n return [int(x) for x in re.sub(r'(\\.0+)*$', '', version).split(\".\")]\n\n\ndef _check_kernel_modules(fix):\n \"\"\"\n Check system kernel modules\n :param fix: if True, try to fix any system dependency issues that are\n detected.\n :return: True if kernel modules are ok.\n \"\"\"\n modprobe = sh.Command._create('modprobe')\n ip6tables = sh.Command._create('ip6tables')\n system_ok = True\n try:\n ip6tables(\"-L\")\n except:\n if fix:\n try:\n modprobe('ip6_tables')\n except sh.ErrorReturnCode:\n print >> sys.stderr, \"ERROR: Could not enable ip6_tables.\"\n system_ok = False\n else:\n print >> sys.stderr, \"WARNING: Unable to detect the ip6_tables \" \\\n \"module. Load with `modprobe ip6_tables`\"\n system_ok = False\n\n for module in [\"xt_set\", \"ipip\"]:\n if not module_loaded(module):\n if fix:\n try:\n modprobe(module)\n except sh.ErrorReturnCode:\n print >> sys.stderr, \"ERROR: Could not enable %s.\" % module\n system_ok = False\n else:\n print >> sys.stderr, \"WARNING: Unable to detect the %s \" \\\n \"module. Load with `modprobe %s`\" % \\\n (module, module)\n system_ok = False\n return system_ok\n\n\ndef _check_ip_forwarding(fix):\n \"\"\"\n Check IP forwarding is enabled.\n :param fix: if True, try to fix any system dependency issues that are\n detected.\n :return: True if IP forwarding is ok.\n \"\"\"\n system_ok = True\n # Enable IP forwarding since all compute hosts are vRouters.\n # IPv4 forwarding should be enabled already by docker.\n if \"1\" not in sysctl(\"net.ipv4.ip_forward\"):\n if fix:\n if \"1\" not in sysctl(\"-w\", \"net.ipv4.ip_forward=1\"):\n print >> sys.stderr, \"ERROR: Could not enable ipv4 forwarding.\"\n system_ok = False\n else:\n print >> sys.stderr, \"WARNING: ipv4 forwarding is not enabled.\"\n system_ok = False\n\n if \"1\" not in sysctl(\"net.ipv6.conf.all.forwarding\"):\n if fix:\n if \"1\" not in sysctl(\"-w\", \"net.ipv6.conf.all.forwarding=1\"):\n print >> sys.stderr, \"ERROR: Could not enable ipv6 forwarding.\"\n system_ok = False\n else:\n print >> sys.stderr, \"WARNING: ipv6 forwarding is not enabled.\"\n system_ok = False\n return system_ok\n\n\ndef _check_docker_version():\n \"\"\"\n Check the Docker version is supported.\n\n :return: True if Docker version is OK.\n \"\"\"\n system_ok = True\n # Check docker version compatability\n try:\n info = docker_client.version()\n except ConnectionError:\n print >> sys.stderr, \"ERROR: Docker daemon not running.\"\n system_ok = False\n except docker.errors.APIError:\n print >> sys.stderr, \"ERROR: Docker server must support Docker \" \\\n \"Remote API v%s or greater.\" % DOCKER_VERSION\n system_ok = False\n else:\n api_version = normalize_version(info['ApiVersion'])\n # Check that API Version is above the minimum supported version\n if cmp(api_version, normalize_version(DOCKER_VERSION)) < 0:\n print >> sys.stderr, \"ERROR: Docker server must support Docker \" \\\n \"Remote API v%s or greater.\" % DOCKER_VERSION\n system_ok = False\n\n return system_ok\n","sub_path":"calico_containers/calico_ctl/checksystem.py","file_name":"checksystem.py","file_ext":"py","file_size_in_byte":6546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"441836309","text":"\"\"\" Business logic for reading comments in a competition's Reddit thread, parsing submissions,\nscoring users, and posting the results. \"\"\"\n\nimport re\nfrom time import sleep\n\nfrom app.persistence.comp_manager import get_active_competition, get_competition, save_competition,\\\n get_all_comp_events_for_comp\nfrom app.persistence.user_manager import get_username_id_map\nfrom app.persistence.events_manager import get_events_name_id_mapping\nfrom app.persistence.user_results_manager import get_blacklisted_entries_for_comp\nfrom app.util.reddit_util import get_submission_with_id, submit_competition_post,\\\nget_permalink_for_comp_thread, update_results_thread\nfrom app.util.times_util import convert_seconds_to_friendly_time\n\n# -------------------------------------------------------------------------------------------------\n\n# It's actually 40k characters, but let's bump it back a smidge to have a little breathing room\nMAX_REDDIT_THREAD_LENGTH = 39500\n\n# -------------------------------------------------------------------------------------------------\n\ndef filter_no_author(entries):\n \"\"\" Returns a filtered list of competition entries (which here are PRAW Comments) which do not\n contain any author=None. \"\"\"\n\n return [e for e in entries if e.author is not None]\n\n\ndef filter_entries_with_no_events(entries, event_names):\n \"\"\" Returns a filtered list of competition entries (which here are PRAW Comments) which do\n not mention any events from the competition. \"\"\"\n\n return [e for e in entries if find_events(e, event_names)]\n\n\ndef filter_entries_that_are_wip(entries):\n \"\"\" Returns a filtered list of competition entries (which here are PRAW Comments) which have any\n of the work-in-progress magic phrases. \"\"\"\n\n return [e for e in entries if (\"WIP\" not in e.body) and (\"FORMATTINGADVICE\" not in e.body)]\n\n\ndef filter_blacklisted_competitor_events(competitors, comp_id):\n \"\"\" Removes events from the provided list of Competitors which correspond to blacklisted\n UserEventResults for this competition. \"\"\"\n\n # This a set() that contains tuples of (user_id, event_id)\n blacklisted_results_set = get_blacklisted_entries_for_comp(comp_id)\n\n # These are maps of event name to event id, and username to user id\n # Since the entries being passed in only have event names and usernames, we need an efficient\n # way to map them IDs so we can check the blacklist set\n username_id_map = get_username_id_map()\n eventname_id_map = get_events_name_id_mapping()\n\n # Iterate over entries and compare user_id and event_id combo to stuff in this set\n for competitor in competitors:\n user_id = username_id_map.get(competitor.raw_name, None)\n if not user_id:\n continue\n\n indices_to_remove = list()\n for i, event in enumerate(competitor.events):\n\n # if the script parses something wrong and the event key isn't in here, just skip to the next event\n try:\n event_id = eventname_id_map[event]\n except KeyError:\n continue\n\n if (user_id, event_id) in blacklisted_results_set:\n indices_to_remove.append(i)\n\n if indices_to_remove:\n # reverse, so we can remove elements from competitor.events and competitor.times in\n # the reversed order. For example if the indices are [5, 2, 1], we can remove\n # competitor.events[5] and the elements at 2 and 1 are still in the same place.\n # Not true if we remove 1, 2, and 5 in that order\n indices_to_remove.reverse()\n\n # remove the events and times at the indices we remembered earlier\n for i in indices_to_remove:\n del competitor.events[i]\n del competitor.times[i]\n\n # rebuilds the event-to-time mapping we use below in the scoring\n competitor.rebuild_event_time_map()\n\n# -------------------------------------------------------------------------------------------------\n\ndef score_previous_competition(is_rerun=False, comp_id=None):\n \"\"\" Score the previous competition and post the results. \"\"\"\n\n # Get the reddit thread ID and the competition model for the competition to be scored\n if comp_id:\n competition_being_scored = get_competition(comp_id)\n else:\n competition_being_scored = get_active_competition()\n\n submission_id = competition_being_scored.reddit_thread_id\n\n # Build a list of event names that were in this competition\n event_names = [comp_event.Event.name for comp_event in get_all_comp_events_for_comp(competition_being_scored.id)]\n\n # Get the PRAW Submission object and make sure we have all the top-level comments\n submission = get_submission_with_id(submission_id)\n try_count = 0\n while try_count < 10:\n try_count += 1\n try:\n submission.comments.replace_more()\n break\n except:\n sleep(5)\n entries = submission.comments\n\n # Filter out all the entry comments we don't want\n entries = filter_no_author(entries)\n entries = filter_entries_with_no_events(entries, event_names)\n entries = filter_entries_that_are_wip(entries)\n\n # Create a competitor record for each entry\n competitors = [Competitor(entry) for entry in entries]\n\n # Creating a competitor record automatically removes any broken times/events\n # Filter out any competitors without any events left\n competitors = [c for c in competitors if c.events]\n\n # Remove duplicate users\n competitors = list(set(competitors))\n\n # Filter out events for competitors if their UserEventResults for this comp, user, and event is blacklisted\n filter_blacklisted_competitor_events(competitors, competition_being_scored.id)\n\n # Build up a dictionary of event name to participant list\n # Participant list contains tuple of (username, event result), sorted by event result\n comp_event_results = dict()\n for event_name in event_names:\n participating_users = list()\n for competitor in competitors:\n if event_name in competitor.events:\n time = competitor.event_time_map[event_name]\n participating_users.append((competitor.name, float(time), competitor))\n if not participating_users:\n continue\n participating_users.sort(key=lambda x: x[1])\n num_event_participants = len(participating_users)\n for i, record in enumerate(participating_users):\n record[2].points += (num_event_participants - (i+1) + 1)\n comp_event_results[event_name] = participating_users\n\n # TODO: comment more thoroughly below\n\n permalink = get_permalink_for_comp_thread(submission_id)\n comp_title = competition_being_scored.title\n post_body = 'Results for [{}]({})'.format(comp_title, permalink)\n event_chunks = list()\n\n for event_name in event_names:\n event_chunk_txt = ''\n if not event_name in comp_event_results.keys():\n continue\n participants = comp_event_results[event_name]\n if not participants:\n continue\n event_chunk_txt += '\\n\\n**{}**\\n\\n'.format(event_name)\n for participant in participants:\n time = participant[1]\n if event_name != 'FMC':\n time = convert_seconds_to_friendly_time(time)\n event_chunk_txt += '1. {}: {}\\n\\n'.format(participant[0], time)\n event_chunks.append([event_name, event_chunk_txt])\n\n overall_txt = ''\n overall_txt += '---\\n\\n**Total points this week**'\n overall_txt += '\\n\\nEach event gives `# of participants - place + 1` points\\n\\n'\n competitors.sort(key=lambda c: c.points, reverse=True)\n for competitor in competitors:\n overall_txt += '1. {}: {}\\n\\n'.format(competitor.name, competitor.points)\n\n skipped_event_names = list()\n while event_chunks:\n chunk = event_chunks.pop(0)\n if len(post_body) + len(overall_txt) + len(chunk[1]) < MAX_REDDIT_THREAD_LENGTH:\n post_body += chunk[1]\n else:\n skipped_event_names.append(chunk[0])\n\n if skipped_event_names:\n post_body += '\\n\\n**Note: Results for the following events were not included here, '\n post_body += \"to allow this post to fit within Reddit's maximum post length:**\\n\\n\"\n for name in skipped_event_names:\n post_body += '1. {}\\n\\n'.format(name)\n\n post_body += overall_txt\n\n title = 'Results for {}'.format(competition_being_scored.title)\n\n if not is_rerun:\n new_post_id = submit_competition_post(title, post_body)\n competition_being_scored.result_thread_id = new_post_id\n save_competition(competition_being_scored)\n else:\n results_thread_id = competition_being_scored.result_thread_id\n update_results_thread(post_body, results_thread_id)\n\n\ndef find_events(comment, events):\n \"\"\" Returns a list of events that are present in this comment. \"\"\"\n return [e for e in events if '{}:'.format(e) in comment.body]\n\n# -------------------------------------------------------------------------------------------------\n\nclass Competitor:\n \"\"\" Encapsulates a Competitor (who posts a Reddit comment to the competition thread), and the\n information relating to their submission (times, events participated in, etc). \"\"\"\n\n def __init__(self, entry):\n parse_results = parse(entry.body)\n self.events = parse_results[1]\n self.times = parse_results[0]\n self.name = '/u/{}'.format(entry.author.name)\n self.raw_name = entry.author.name\n self.points = 0\n self.fix_times()\n self.rebuild_event_time_map()\n\n def rebuild_event_time_map(self):\n \"\"\" Rebuilds the event_time_map if any entries from events and times were removed\n due to blacklist filtering. \"\"\"\n self.event_time_map = dict(zip(self.events, self.times))\n\n def fix_times(self):\n \"\"\" Remove the entries in the events and times lists where the entry is 'Error' \"\"\"\n while 'Error' in self.times:\n self.events.pop(self.times.index('Error'))\n self.times.pop(self.times.index(\"Error\"))\n\n def __eq__(self, other):\n if isinstance(other, self.__class__):\n return self.name == other.name\n else:\n return False\n\n def __hash__(self):\n return hash(self.name)\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n# -------------------------------------------------------------------------------------------------\n# This is pretty awful below, but it's functional so let's mess with it as little as possible!\n# Just minor tweaks to improve readibility\n# -------------------------------------------------------------------------------------------------\n\ndef parse(post):\n \"\"\" Parse a comment body to extract the user's submitted times and events information. \"\"\"\n\n # As as long as a line of text \"fits\" this pattern, we will get a successful match.\n # Otherwise we get 'None'.\n matcher = re.compile('^(.+?)\\\\:\\\\s*([^\\\\s]+).*')\n\n # Create a second matcher to find \"empty\" results.\n # ONLY apply it if the first rule didn't match. (see below)\n dnf_matcher = re.compile('^([^\\\\:\\\\s]+)\\\\s*\\\\:.*')\n\n times = list()\n events = list()\n raw_times = list()\n\n # Split our post into individual lines, and process them\n for line in post.splitlines():\n # Now replace any * characters with nothing.\n content = re.sub ('\\\\*','',line)\n\n # Use our matchers to see if the current line matches our pattern(s).\n result = matcher.match(content)\n dnf_result = dnf_matcher.match(content)\n\n average = ''\n if result is not None:\n # We have gotten a puzzle name and an average.\n if result.group(1).lower() == \"mirror blocks\":\n events.append(\"3x3 Mirror Blocks/Bump\")\n elif result.group(1).lower() == \"3x3 mirror blocks/bump\":\n events.append(\"3x3 Mirror Blocks/Bump\")\n elif result.group(1).lower() == \"3x3 relay\":\n events.append(\"3x3 Relay of 3\")\n elif result.group(1).lower() == \"relay of 3\":\n events.append(\"3x3 Relay of 3\")\n elif result.group(1).lower() == \"5x5x5\":\n events.append(\"5x5\")\n elif result.group(1).lower() == \"6x6x6\":\n events.append(\"6x6\")\n elif result.group(1).lower() == \"7x7x7\":\n events.append(\"7x7\")\n elif result.group(1).lower() == \"4x4oh\":\n events.append(\"4x4 OH\")\n elif result.group(1).lower() == \"pyra\":\n events.append(\"Pyraminx\")\n elif result.group(1).lower() == \"blind\":\n events.append(\"3BLD\")\n elif result.group(1).lower() == \"4x4oh\":\n events.append(\"4x4 OH\")\n elif result.group(1).lower() == \"f2l\":\n events.append(\"F2L\")\n elif result.group(1).lower() == \"bld\":\n events.append(\"3BLD\")\n elif result.group(1).lower() == \"pll time attack\":\n events.append(\"PLL Time Attack\")\n elif result.group(1).lower() == \"3x3 mirror blocks/bump\":\n events.append(\"3x3 Mirror Blocks/Bump\")\n elif result.group(1).lower() == \"3x3 mirror blocks\":\n events.append(\"3x3 Mirror Blocks/Bump\")\n elif result.group(1).lower() == \"mirror blocks/bump\":\n events.append(\"3x3 Mirror Blocks/Bump\")\n elif result.group(1).lower() == \"3x3 with feet\":\n events.append(\"3x3 With Feet\")\n elif result.group(1).lower() == \"3x3 oh\":\n events.append(\"3x3OH\")\n elif result.group(1).lower() == \"oll\":\n events.append(\"OH OLL\")\n else:\n events.append(result.group(1))\n\n average = result.group(2) #The second group was average.\n if \":\" in average:\n try:\n mins = (int)(average[0: average.index(\":\")])\n secs = (int)(average[average.index(\":\") + 1: average.index(\".\")])\n dec = (int)(average[average.index(\".\") + 1: average.index(\".\") + 3])\n\n secs += mins * 60\n if dec < 10:\n average = str(secs) + \".0\" + str(dec)\n else:\n average = str(secs) + \".\" + str(dec)\n except ValueError:\n average = \"Error\"\n\n try:\n float(re.sub('[* ()=/]', '', average).strip())\n times.append(re.sub('[* ()=/]', '', average).strip())\n except:\n times.append(\"Error\")\n\n elif dnf_result is not None:\n # We have a puzzle name, but no average.\n events.append(dnf_result.group(1))\n times.append(\"Error\")\n\n else:\n # If a line didn't match any of the two rules, skip it.\n continue\n return [times, events, raw_times]\n","sub_path":"app/util/score_comp.py","file_name":"score_comp.py","file_ext":"py","file_size_in_byte":15055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"253152141","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport asyncio\nimport random\n\nimport aiohttp\nfrom lxml import etree\n\nfrom data import agents\nimport setting\nimport logging\n\nclass BaseSpider():\n\n def __init__(self):\n self.urls = []\n self.next= None\n self.loop = asyncio.get_event_loop()\n self.idle = 5\n\n def run(self):\n logging.debug(\"Running spider [%s] now!\" % (type(self).__name__))\n results = []\n tasks = [self._feth(results, u) for u in self.urls]\n self.loop.run_until_complete(asyncio.gather(*tasks))\n\n while self.next:\n next_url = self.next\n self.next = None\n self.loop.run_until_complete(self._feth(results, next_url))\n\n return results\n\n def _headers(self):\n number = random.randint(0, len(agents)-1)\n return {'user-agent': agents[number]}\n\n async def _feth(self, results, url):\n logging.debug(\"Fetching page [%s] by spider [%s].\" % (url, type(self).__name__))\n try:\n html = None\n async with aiohttp.ClientSession() as session:\n async with session.get(url, headers=self._headers(), proxy=setting.spider_proxy) as response:\n html = await response.text()\n\n self._parse(results, html)\n\n except Exception as e:\n logging.error(\"Fetch page error:%s by spider [%s]\" % (e, type(self).__name__))\n\n def _parse(self, results, text):\n pass\n","sub_path":"src/spiders/baseSpider.py","file_name":"baseSpider.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"398957745","text":"import tkinter\nimport tkinter.ttk\n\n\nclass VerticalScrolledFrame(tkinter.Frame):\n \"\"\"A pure Tkinter scrollable frame that actually works!\n * Use the 'interior' attribute to place widgets inside the scrollable frame\n * Construct and pack/place/grid normally\n * This frame only allows vertical scrolling\n \"\"\"\n\n def __init__(self, parent, *args, **kw):\n tkinter.Frame.__init__(self, parent, *args, **kw)\n\n # create a canvas object and a vertical scrollbar for scrolling it\n vscrollbar = tkinter.Scrollbar(self, orient=tkinter.VERTICAL)\n vscrollbar.pack(fill=tkinter.Y, side=tkinter.RIGHT, expand=tkinter.FALSE)\n canvas = tkinter.Canvas(self, bd=0, highlightthickness=0,\n yscrollcommand=vscrollbar.set)\n canvas.pack(side=tkinter.LEFT, fill=tkinter.BOTH, expand=tkinter.TRUE)\n vscrollbar.config(command=canvas.yview)\n\n # reset the view\n canvas.xview_moveto(0)\n canvas.yview_moveto(0)\n\n # create a frame inside the canvas which will be scrolled with it\n self.interior = interior = tkinter.Frame(canvas)\n interior_id = canvas.create_window(0, 0, window=interior,\n anchor=tkinter.NW)\n\n # track changes to the canvas and frame width and sync them,\n # also updating the scrollbar\n def _configure_interior(event):\n # update the scrollbars to match the size of the inner frame\n size = (interior.winfo_reqwidth(), interior.winfo_reqheight())\n canvas.config(scrollregion=\"0 0 %s %s\" % size)\n if interior.winfo_reqwidth() != canvas.winfo_width():\n # update the canvas's width to fit the inner frame\n canvas.config(width=interior.winfo_reqwidth())\n\n interior.bind('', _configure_interior)\n\n def _configure_canvas(event):\n if interior.winfo_reqwidth() != canvas.winfo_width():\n # update the inner frame's width to fill the canvas\n canvas.itemconfigure(interior_id, width=canvas.winfo_width())\n\n canvas.bind('', _configure_canvas)\n\n\nclass GuiEscolhaQuesito:\n def __init__(self, master):\n\n self.master = master\n master.title(\"Escolha de quesitação\")\n\n # gives weight to the cells in the grid\n rows = 0\n while rows < 50:\n master.rowconfigure(rows, weight=1)\n master.columnconfigure(rows, weight=1)\n rows += 1\n\n # Defines and places the notebook widget\n nb = tkinter.ttk.Notebook(master)\n nb.grid(row=1, column=0, columnspan=50, rowspan=49, sticky='NESW')\n\n # Adds tab 1 of the notebook\n page1 = tkinter.ttk.Frame(nb)\n nb.add(page1, text='Escolha de quesito')\n\n # Monta lista de quesitos\n q = 0\n var_quesito = tkinter.IntVar()\n var_quesito = 0\n tkinter.Label(page1, text=\"%similar.\").grid(row=0, column=1, sticky=tkinter.W)\n tkinter.Label(page1, text=\"Quesito\").grid(row=0, column=2, sticky=tkinter.W)\n\n for quesito in lista_quesitos:\n # Incluir variavel na lista\n # var.append(tkinter.IntVar())\n # Monta checkbox\n # tkinter.Checkbutton(page1, text=quesito, variable=var[q]).grid(row=q, sticky=tkinter.W)\n linha = q + 1\n tkinter.Label(page1, text=\"0.95\").grid(row=linha, column=1)\n tkinter.Radiobutton(page1, text=quesito, variable=var_quesito, value=q).grid(row=linha, column=2,\n sticky=tkinter.W)\n #\n q = q + 1\n\n # Adds tab 2 of the notebook\n page2 = tkinter.ttk.Frame(nb)\n\n\n\n txt_frm = tkinter.Frame(page2, width=300, height=300)\n txt_frm.pack(fill=\"both\", expand=True)\n # ensure a consistent GUI size\n txt_frm.grid_propagate(False)\n # implement stretchability\n txt_frm.grid_rowconfigure(0, weight=1)\n txt_frm.grid_columnconfigure(0, weight=1)\n\n # create a Text widget\n self.txt = tkinter.Text(txt_frm, borderwidth=3, relief=\"sunken\")\n self.txt.config(font=(\"consolas\", 12), undo=True, wrap='word')\n self.txt.grid(row=0, column=0, sticky=\"nsew\", padx=2, pady=2)\n\n # create a Scrollbar and associate it with txt\n scrollb = tkinter.Scrollbar(txt_frm, command=self.txt.yview)\n scrollb.grid(row=0, column=1, sticky='nsew')\n self.txt['yscrollcommand'] = scrollb.set\n\n #\n self.txt.insert(tkinter.END, texto)\n\n\n nb.add(page2, text='Solicitação de exame')\n\n # Tab para teste\n\n page3 = VerticalScrolledFrame(nb)\n nb.add(page3, text='Teste')\n\n frm_int = tkinter.Frame(page3, width=300, height=300)\n frm_int.pack(fill=\"both\", expand=True)\n # ensure a consistent GUI size\n frm_int.grid_propagate(False)\n # implement stretchability\n frm_int.grid_rowconfigure(0, weight=1)\n frm_int.grid_columnconfigure(0, weight=1)\n\n quesito = lista_quesitos[1]\n\n for q in range(100):\n # listNodes.insert(tkinter.END, quesito)\n linha = q + 1\n # tkinter.Label(page3, text=\"0.95\").grid(row=linha, column=1)\n # tkinter.Radiobutton(page3, text=quesito, variable=var_quesito, value=q).grid(row=linha, column=2, sticky=tkinter.W)\n tkinter.Label(frm_int, text=\"0.95\").pack()\n tkinter.Radiobutton(frm_int, text=quesito, variable=var_quesito, value=q).pack()\n\n\n # tkinter.Label(window, text=\"Bottom label\").pack()\n\n\n #\n # self.label = tkinter.Label(master, text=\"This is our first GUI!\")\n # self.label.pack()\n\n\n\n #\n # self.greet_button = tkinter.Button(master, text=\"Greet\", command=self.greet)\n # self.greet_button.pack()\n #\n # self.close_button = tkinter.Button(master, text=\"Close\", command=master.quit)\n # self.close_button.pack()\n\n def greet(self):\n print(\"Greetings!\")\n\n\ndef escolhe_quesito(lista_quesitos, texto):\n root = tkinter.Tk()\n root.title('Notebook Demo')\n root.geometry('600x600')\n\n my_gui = GuiEscolhaQuesito(root)\n root.mainloop()\n\n\nquesito1 = '''NADA IGUAL.'''\n\nquesito2 = '''I. Quais as caracteristicas do aparelho?\nII. Quais as chamadas?\nIII. Qual a agenda?\nIV. Outros dados julgados úteis.'''\n\nquesito3 = '''1. Quais as caracteristicas do aparelho?\n2. Quais as chamadas?\n3. Qual a agenda?\n4. Outros dados julgados úteis.'''\n\nquesito4 = '''1. Quais as caracteristicas do aparelho?\n2. Quais as chamadas?\n3. Qual a agenda?\n4. Qual a número de telefone?\n5. Outros dados julgados úteis.'''\n\nlista_quesitos = [quesito1, quesito2, quesito3, quesito4]\n\ntexto = '''\n Memorando 1234/18\n xxxx\n 1. Quais as caracteristicas do aparelho?\n 2. Quais as chamadas?\n 3. Qual a agenda?\n 4. Outros dados julgados úteis.\n\n Lista de Materiais\n Um celular\n '''\n\nescolhe_quesito(lista_quesitos, texto)\n","sub_path":"teste_notebook_texto_scroll.py","file_name":"teste_notebook_texto_scroll.py","file_ext":"py","file_size_in_byte":7112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"457002104","text":"lines = open('input.txt').readlines()\n\nidList = []\nfor line in lines:\n minRow = 0\n maxRow = 127\n minCol = 0\n maxCol = 7\n for dir in line:\n if dir == 'F':\n maxRow = maxRow - ((maxRow-minRow + 1) / 2)\n elif dir == 'B':\n minRow = minRow + ((maxRow-minRow + 1) / 2)\n elif dir == 'L':\n maxCol = maxCol - ((maxCol-minCol + 1) / 2)\n elif dir == 'R':\n minCol = minCol + ((maxCol-minCol + 1) / 2)\n idList.append(int(maxRow * 8 + maxCol))\n\nidList.sort()\nfor id in range(idList[0], idList[-1]):\n if id not in idList:\n print(id)\n break\n","sub_path":"2020/day05/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"442271478","text":"import itertools\n\nfrom flask import jsonify, url_for, request, Response\nfrom sqlalchemy.exc import IntegrityError\nfrom sqlalchemy.orm.exc import NoResultFound, UnmappedInstanceError\n\nfrom app.application import app, db\nfrom app.models.auth_token import AuthToken\nfrom app.models.location import Location, locations_schema, location_schema\nfrom app.models.stop_point import StopPoint, stop_points_schema, \\\n stop_point_schema\nfrom app.models.user import User, users_schema\nfrom app.utils.utils import has_no_empty_params, Errors, error, \\\n get_timetable_for_stop_point_ref_list_multithreaded\nfrom verbund_soap_client.verbund_soap_client import VDVClient\n\n\n@app.route('/users', methods=['GET'])\ndef get_users():\n all_users = User.query.all()\n result = users_schema.dump(all_users)\n return jsonify(result)\n\n\n@app.route('/proxy/location-information-request', methods=['GET'])\ndef proxy_location_information_request():\n if 'location_name' in request.args:\n locations = VDVClient().location_information_request__location_name(\n request.args['location_name'])\n return jsonify(locations)\n\n@app.route('/locations', methods=['GET'])\ndef get_locations():\n return jsonify(locations_schema.dump(Location.query.all()))\n\n@app.route('/location/slug//timetable', methods=['GET'])\ndef get_timetable_for_location_slug(slug):\n try:\n location = Location.query.filter(Location.slug == slug).one()\n except NoResultFound:\n return error(Errors.OBJECT_NOT_FOUND_ERROR, status_code=404)\n stop_point_refs = [stop_point.ref for stop_point in location.stop_points]\n\n result_lists = list(get_timetable_for_stop_point_ref_list_multithreaded(stop_point_refs))\n result = itertools.chain.from_iterable(result_lists) # todo: have to sort the lists while/after jaining them\n return jsonify(list(result))\n\n\n@app.route('/location', methods=['POST'])\ndef create_location():\n name, slug = request.json['name'], request.json['slug']\n try:\n location = Location(name=name, slug=slug)\n db.session.add(location)\n db.session.commit()\n except IntegrityError:\n return error(Errors.SLUG_ALREADY_EXISTS_ERROR)\n return jsonify(location_schema.dump(location))\n\n\n@app.route('/location/id/', methods=['GET', 'DELETE'])\ndef rud_location(location_id):\n # find location\n location = Location.query.get(location_id)\n if not location:\n return error(Errors.OBJECT_NOT_FOUND_ERROR)\n if request.method == 'DELETE':\n db.session.delete(location)\n db.session.commit()\n return jsonify(location_schema.dump(location))\n\n\n@app.route('/location/id//stopPoint', methods=['POST'])\ndef create_stop_point(location_id):\n name, city, ref = request.json['name'], request.json['city'], request.json[\n 'ref']\n stop_point = StopPoint(name=name, city=city, ref=ref, location_id=location_id)\n db.session.add(stop_point)\n db.session.commit()\n return jsonify(stop_point_schema.dump(stop_point))\n\n\n@app.route('/stopPoint/id/', methods=['GET', 'DELETE'])\ndef rud_stop_point(stop_point_id):\n stop_point = StopPoint.query.get(stop_point_id)\n if not stop_point:\n return error(Errors.OBJECT_NOT_FOUND_ERROR)\n if request.method == 'DELETE':\n db.session.delete(stop_point)\n db.session.commit()\n return jsonify(location_schema.dump(stop_point))\n\n\n@app.route('/location/id//stopPoints', methods=['GET'])\ndef get_stop_points(location_id):\n return jsonify(stop_points_schema.dump(Location.query.get(location_id).stop_points))\n\n\n@app.route('/login', methods=['POST'])\ndef login():\n username, password = request.json['username'], request.json['password']\n\n # find user\n try:\n user = User.query.filter(User.username == username).one()\n except NoResultFound:\n return error(Errors.AUTHENTICATION_ERROR)\n # check password\n if not user.check_password(password):\n return error(Errors.AUTHENTICATION_ERROR)\n # generate password and return\n auth_token = AuthToken(user_id=user.id)\n db.session.add(auth_token)\n db.session.commit()\n\n return jsonify({'token': auth_token.token})\n\n\n@app.route('/')\ndef all_links():\n links = []\n for rule in app.url_map.iter_rules():\n # Filter out rules we can't navigate to in a browser\n # and rules that require parameters\n if \"GET\" in rule.methods and has_no_empty_params(rule):\n url = url_for(rule.endpoint, **(rule.defaults or {}))\n links.append((url, rule.endpoint))\n # links is now a list of url, endpoint tuples\n return jsonify(links)\n","sub_path":"backend/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"191409904","text":"from django.shortcuts import render_to_response ,render,get_object_or_404,redirect\nfrom blog.models import Post,Post2,category,Sub,comment1,comment2\nimport webbrowser\nimport smtplib as p\nfrom django.core.files import File\n\n\ndef index(request):\n\tposts = Post.objects.all()\n\treturn render(request ,'indexx.html',{'posts':posts})\ndef blog(request):\n\tposts = Post.objects.filter(published = True)\n\tposts2 = Post2.objects.filter(published = True)\n\tcategorys = category.objects.all()\n\tnumber = str(Sub.objects.count())\n\treturn render(request , 'blog.html' , {'posts':posts,'posts2':posts2,'category':categorys,'num':number})\ndef view_blog_post(request , slug):\n\tpost = get_object_or_404(Post , slug = slug)\n\tif (request.method == 'POST'):\n\t\tname = request.POST.get('name' , None)\n\t\tif (len(name)!= 0):\n\t\t\temail = request.POST.get('email' , None)\n\t\t\tcmnt = request.POST.get('comment',None)\n\t\t\tc = post.comment1_set.create(name = name , email = email , desc = cmnt)\n\t\t\tc.save()\n\tcomment = comment1.objects.filter(post = post)\n\treturn render(request,'testpost.html',{'post':post,'comment':comment})\n\ndef view_post_2(request , slug):\n\tpost = get_object_or_404(Post2 , slug = slug)\n\tif (request.method == 'POST'):\n\t\tname = request.POST.get('name' , None)\n\t\tif (len(name)!= 0):\n\t\t\temail = request.POST.get('email' , None)\n\t\t\tcmnt = request.POST.get('comment',None)\n\t\t\tc = post.comment1_set.create(name = name , email = email , desc = cmnt)\n\t\t\tc.save()\n\t#comment = post.comment2_set.all()\n\tcomment = comment2.objects.filter(post = post)\n\treturn render_to_response('post.html',{'post':post,'comment':comment})\ndef post(request,slug):\n\tpost = get_object_or_404(Post ,slug=slug)\n\t#comment = post.comment1_set.all()\n\t\n\treturn render(request,'post.html',{'post':post,'comment':comment})\ndef about(request):\n\treturn render(request,'about.html')\ndef sending(request):\n\tif (request.method == 'POST'):\n\t\tname = request.POST.get('name',None)\n\t\tabout = request.POST.get('email',None)\n\t\tdescription = request.POST.get('description',None)\n\t\tmsg =\"\"\"From: From skyteam.work@gmail.com\nTo: %r\nMIME-Version: 1.0\nContent-type: text/html\nSubject: BUG repport about (%a)\n Message : \n%s
\n\n\"\"\"\t% (name,about,description)\t\n\t\tserver = p.SMTP(\"smtp.gmail.com\",587)\n\t\tserver.starttls()\n\t\tserver.login(\"teamsky.work@gmail.com\",\"teamskywork123\")\n\t\tserver.sendmail(\"teamsky.work@gmail.com\",\"sky.red2212@gmail.com\",msg)\n\t\tposts = Post.objects.all()\n\t\treturn render(request ,'indexx.html',{'posts':posts})\ndef send(request):\n\treturn render(request , 'sending.html')\ndef view_category(request,slug):\n\tcategories = get_object_or_404(category ,slug = slug)\n\tcategorys = category.objects.all()\n\tposts = Post.objects.filter(category = categories)\n\tposts2 = Post2.objects.filter(category = categories)\n\tnumber = str(Sub.objects.count())\n\treturn render(request , 'blog.html',{'category':categorys,'posts':posts,'posts2':posts2,'num':number})\ndef subscribe(request):\n\tif (request.method == 'POST'):\n\t\tname = request.POST.get('name',None)\n\t\temail = request.POST.get('email',None)\n\t\tq = Sub(name = name , email=email)\n\t\tq.save()\n\t\tfile = open(\"maillist.txt\",\"a\")\n\t\tfile.write(\"\\n\")\n\t\tfile.write(name)\n\t\tfile.write(\"\\n\")\n\t\tfile.write(email)\n\t\tfile.close()\n\t\treturn redirect('https://skyteam.herokuapp.com')\n\telse:\n\t\treturn redirect('https://www.google.com')\ndef share(request):\n\tmaillist = Sub.objects.all()\n\tabout = \"New post\"\n\turl = \"https://skyteam.herokuapp.com/news\"\n\tserver = p.SMTP(\"smtp.gmail.com\",587)\n\tserver.starttls()\n\tserver.login(\"teamsky.work@gmail.com\",\"teamskywork123\")\n\tfor mail in maillist:\n\t\tmsg =\"\"\"From: From skyteam.work@gmail.com\nTo: %r\nMIME-Version: 1.0\nContent-type: text/html\nSubject: (%a)\n Message : \ncheck our new post in \\n %s
\n\n\"\"\"\t% (mail.name,about,url)\n\t\tserver.sendmail(\"teamsky.work@gmail.com\",mail.email,msg)\n\t\treturn redirect(\"https://skyteam.herokuapp.com\")\ndef news(request):\n\tposts = Post.objects.filter(published = True)[0:3]\n\tposts2 = Post2.objects.filter(published = True)[0:3]\n\tcategorys = category.objects.all()\n\tnumber = str(Sub.objects.count())\n\treturn render(request , 'blog.html' , {'posts':posts,'posts2':posts2,'category':categorys,'num':number})\n# Create your views here.\ndef blog_search(request):\n \tif (request.method == 'GET'):\n \t\tkeyword = request.GET.get('search')\n \t\tposts = Post.objects.filter(title__icontains = keyword)\n \t\tposts2 = Post2.objects.filter(title__icontains=keyword)\n \t\tcategorys = category.objects.all()\n \t\tnumber = str (Sub.objects.count())\n \t\t#import webbrowser\n \t\t#webbrowser.open(\"www.google.com\")\n \t\treturn render(request , 'blog.html' , {'posts':posts,'posts2':posts2,'category':categorys,'num':number})\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"244551776","text":"#!/usr/python3.5\nfrom kivy.app import App\nfrom kivy.uix.widget import Widget\nfrom kivy.uix.button import Button\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.graphics import *\n# codigo ainda com falhas para corrigir\n\ncores_hex = [\n 'FF9E73', 'FF7B40', 'FF4F00', 'BF5D30', 'A63400',\n 'FFD473', 'FFC540', 'FFB100', 'BF9430', 'A67300',\n '67E467', '39E444', '00C90D', '26972D', '008209',\n '64AAD0', '3C9DD0', '086CA2', '235B79', '034569',\n '717DD7', '4B5CD7', '1729B0', '2E3884', '081472',\n '926CD6', '7945D6', '4811AE', '492A82', '2C0571',\n 'FF7673', 'FF4540', 'FF0700', 'BF3330', 'A60400',\n 'FFFFFF', '999999', '000000'\n\n ]\n\ndef hex2rgb (cor):\n cor = cor.lstrip('#')\n return (int(cor[:2], 16)/255., int(cor[2:4], 16)/255., int(cor[:4], 16)/255., 1.)\n\ncores = [hex2rgb(cor) for cor in cores_hex]\n\nclass DesenhoWidget (Widget):\n def on_touch (self, touch):\n with self.canvas:\n Color(*self.cor, mode='rgba')\n touch.ud['line'] = Line(points=(touch.x, touch.y), width=self.brush)\n\n def on_touch_move (self, touch):\n if 'line' in touch.ud:\n touch.ud['line'].points += [touch.x, touch.y]\n\nclass DesenhoApp (App):\n def build(self):\n tela = BoxLayout(orientation='horizontal')\n controles = BoxLayout(orientation='vertical', size_hint=[.1, 1.])\n palheta = GridLayout(cols=2, spacing=0)\n\n def define_cor (instance):\n desenho.cor = list(instance.background_color)\n desenho.cor[-1] = .6\n limpara.color = desenho.cor\n limparb.color = desenho.cor\n\n for cor in cores:\n cw = Button(text=' ', background_color=cor, background_normal='')\n cw.bind(on_press=define_cor)\n palheta.add_widget(cw)\n\n desenho = DesenhoWidget()\n desenho.cor = list(cores[0])\n desenho.cor[-1] = .6\n desenho.brush = 5.\n tela.add_widget(desenho)\n limpara = Button(text='X', background_color=(0., 0., 0., 1.), color=desenho.cor, background_normal='')\n palheta.add_widget(limpara)\n\n limparb = Button(text='X', background_color=(1., 1., 1., 1.), color=desenho.cor, background_normal='')\n palheta.add_widget(limparb)\n controles.add_widget(palheta)\n tela.add_widget(controles)\n\n def limpar1 (obj):\n desenho.canvas.clear()\n limpara.bind(on_release=limpar1)\n\n def limpar2 (obj):\n with desenho.canvas:\n Color(1., 1., 1., 1., mode='rgba')\n Rectangle(pos=desenho.pos, size=desenho.size)\n limparb.bind(on_release=limpar2)\n return tela\n\nif __name__ == '__main__':\n DesenhoApp().run()\n\n","sub_path":"livro/24.01_desenho/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"141167485","text":"from model.Image import Image\n\ndef printScreen(text, x, y, size=50, color=(0, 0, 0)): # retorne une collection d'image avec un texte en entré\n images = []\n lines = text.split('\\n')\n for line in lines:\n image = Image(line, x, y, text=True, size=size, color=color)\n images.append(image)\n y += 50\n return images\n","sub_path":"tools/PRINTscreen.py","file_name":"PRINTscreen.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"76148831","text":"class Solution:\n def isPowerOfThree(self, num):\n if num == 1:\n return True\n if abs(num) < 3 or num % 3 != 0:\n return False\n return self.isPowerOfThree(num//3)\n\ndef main():\n sln = Solution()\n print(sln.isPowerOfThree(9))\n\nif __name__ == '__main__':\n main()\n","sub_path":"Power of Three/Power of Three.py","file_name":"Power of Three.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"217930513","text":"#!/usr/bin/env python2\n\n\ndef parse_command(instr, bot):\n if instr.startswith('action move'):\n time = int(instr.split(' ')[-1])\n x, y = bot.make_move(time)\n return 'place_move %d %d\\n' % (x, y)\n elif instr.startswith('update game field'):\n fstr = instr.split(' ')[-1]\n bot.update_currentboard(fstr)\n elif instr.startswith('update game macroboard'):\n mbstr = instr.split(' ')[-1]\n bot.update_macroboard(mbstr)\n elif instr.startswith('update game move'):\n bot.set_movenumb(int(instr.split(' ')[-1]))\n elif instr.startswith('settings your_botid'):\n myid = int(instr.split(' ')[-1])\n bot.myid(myid)\n bot.myid = myid\n bot.oppid = 1 if myid == 2 else 2\n elif instr.startswith('settings timebank'):\n bot.timebank = int(instr.split(' ')[-1])\n elif instr.startswith('settings time_per_move'):\n bot.time_per_move = int(instr.split(' ')[-1])\n return ''\n\nif __name__ == '__main__':\n import sys\n from scorebot import ScoreBot\n import logging\n import socket\n\n if 'f4hy' in socket.gethostname() or 'fahy' in socket.gethostname():\n logging.basicConfig(format='SCOREBOT %(levelname)s: %(message)s', level=logging.DEBUG)\n root = logging.getLogger()\n errfilename = \"test\"+\".err\"\n errfilehandler = logging.FileHandler(errfilename, delay=True)\n errfilehandler.setLevel(logging.WARNING)\n formatter = logging.Formatter('SCOREBOT %(levelname)s: %(message)s')\n errfilehandler.setFormatter(formatter)\n root.addHandler(errfilehandler)\n logfilename = \"test\"+\".log\"\n logfilehandler = logging.FileHandler(logfilename, delay=True)\n logfilehandler.setLevel(logging.DEBUG)\n formatter = logging.Formatter('SCOREBOT %(levelname)s: %(message)s')\n logfilehandler.setFormatter(formatter)\n root.addHandler(logfilehandler)\n\n logging.info(\"starting logging\")\n\n bot = ScoreBot()\n\n while True:\n try:\n instr = raw_input()\n logging.info(\"instr {}\".format(instr))\n except EOFError as e:\n logging.warn(\"given EOF exiting\")\n sys.stdout.flush()\n exit(-1)\n except Exception as e:\n logging.warn('error reading input {}, {}'.format(e, type(e)))\n sys.stderr.write('error reading input')\n raise e\n outstr = parse_command(instr, bot)\n sys.stdout.write(outstr)\n sys.stdout.flush()\n","sub_path":"scorebot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"250915138","text":"import networkx as nx\nfrom matplotlib import pyplot as plt\nimport os \nG = nx.read_pajek('weighted_hero_network.txt')\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\ndef get_color(arg,name):\n '''\n Determines the color code for the given node\n Inputs:\n arg: (str) \n name: (str)\n Outputs g for green, r for red\n '''\n if name == arg:\n return 'g'\n else:\n return 'r'\n\ndef get_network(arg,conn_num=False):\n '''\n Draws the network\n Inputs:\n arg: (str) name of the character to draw the network for\n Outputs tuple with information about the graph\n '''\n limit = False\n plt.clf()\n arg = arg.upper()\n if arg not in G.nodes():\n return (0,0,0,0)\n else:\n N = G.neighbors(arg)\n N.append(arg)\n H = G.subgraph(N)\n d = nx.degree(H)\n weights = H[arg]\n\n most_apps = sorted([(x,weights[x][0]['weight']) for x in weights], key=lambda i: i[1],reverse=True)\n highest = most_apps[0][1]\n i = 0\n for j in most_apps:\n if j[1] == highest:\n i +=1\n most = [x[0].title() for x in most_apps[:i]]\n\n weights[arg] = {0:{'weight':highest}}\n\n if conn_num and conn_num < len(N):\n limit = True\n lim_N = [x[0] for x in most_apps[:conn_num-1]] + [arg]\n lim_H = G.subgraph(lim_N)\n lim_d = nx.degree(lim_H)\n nx.draw_circular(lim_H,with_labels=True,alpha=0.5,edge_color='0.5',\n nodelist=lim_d.keys(), node_size=[weights[v][0]['weight'] * 5 for v in lim_d.keys()],\n node_color=[get_color(arg,v) for v in lim_d.keys()])\n plt.savefig(os.path.join(BASE_DIR,'ui/static/lim_network.jpg'))\n plt.clf()\n\n nx.draw_circular(H,with_labels=True,alpha=0.5,edge_color='0.5',\n nodelist=d.keys(), node_size=[weights[v][0]['weight'] * 5 for v in d.keys()],\n node_color=[get_color(arg,v) for v in d.keys()])\n plt.savefig(os.path.join(BASE_DIR,'ui/static/network.jpg'))\n plt.clf()\n return (1,most,len(N),limit)\n","sub_path":"ui/grapher.py","file_name":"grapher.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"223851116","text":"def badSolution(N, A):\n result = [0]*N\n for command in A:\n if 1 <= command <= N:\n result[command-1] += 1\n else:\n result[:] = [max(result)]*N\n return result\n\n\ndef solution(N, A):\n result = [0]*N # The list to be returned\n max_counter = 0 # The used value in previous max_counter command\n current_max = 0 # The current maximum value of any counter\n for command in A:\n if 1 <= command <= N:\n # increase(X) command\n if max_counter > result[command-1]:\n # lazy write\n result[command-1] = max_counter\n result[command-1] += 1\n if current_max < result[command-1]:\n current_max = result[command-1]\n else:\n # max_counter command\n # just record the current maximum value for later write\n max_counter = current_max\n for index in range(0, N):\n if result[index] < max_counter:\n # This element has never been used/updated after previous\n # max_counter command\n result[index] = max_counter\n return result\n\n\nprint(solution(5, [3, 4, 4, 6, 1, 4, 4])) # [3, 2, 2, 4, 2]\n","sub_path":"codility/04.04.max-counters.py","file_name":"04.04.max-counters.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"337349760","text":"import collections\n\n\nPoint = collections.namedtuple(\"Point\", \"y x\")\nPoint._delta_udlr = (\n Point(-1, 0),\n Point(1, 0),\n Point(0, -1),\n Point(0, 1)\n)\n\n\ndef _Point____add__(self, other):\n return Point(self.y + other.y,\n self.x + other.x)\n\n\ndef _Point__udlr(self):\n \"\"\"Get the four next points. UDLR means Up, Down, Left and Right.\"\"\"\n return [self + delta for delta in self._delta_udlr]\n\n\nPoint.__add__ = _Point____add__\nPoint.udlr = _Point__udlr\n\n\ndef def_getter(cls, attr_name: str):\n \"\"\"\n Define a getter property of a given class.\n\n e.g.\n In below code, code 1 is same as code 2.\n\n # Code 1\n def_getter(C, '_foo')\n\n # Code 2\n class C:\n @property\n def foo(self):\n return self._foo\n\n \"\"\"\n prop_name = attr_name.lstrip(\"_\")\n\n def getter(self):\n return getattr(self, attr_name)\n\n setattr(cls, prop_name, property(getter))\n","sub_path":"mylib/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"652572886","text":"import bpy\n\n\n__all__ = [\n \"delete_all_data\",\n]\n\n\ndef delete_all_data():\n \"\"\"Delete all collections, mesh and curve objects, meshes, curves, materials.\"\"\"\n for collection in bpy.data.collections:\n bpy.data.collections.remove(collection)\n for obj in bpy.data.objects:\n if obj.type == 'MESH':\n bpy.data.objects.remove(obj)\n elif obj.type == 'CURVE':\n bpy.data.objects.remove(obj)\n for mesh in bpy.data.meshes:\n bpy.data.meshes.remove(mesh)\n for curve in bpy.data.curves:\n bpy.data.curves.remove(curve)\n for material in bpy.data.materials:\n bpy.data.materials.remove(material)\n\n\n# ==============================================================================\n# Main\n# ==============================================================================\n\nif __name__ == '__main__':\n pass\n","sub_path":"src/compas_blender/utilities/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"283527637","text":"from Linux_Helpers.py_ssh import set_content\n\nclass Host:\n def __init__(self,HostName,IP_address,alias=\"\",comment=\"\"):\n self.HostName = HostName\n self.IP_address = IP_address\n self.alias = alias\n self.comment = \"\"\n if len(comment)>0:\n self.comment = '#' + comment\n\ndef add_host(elevated_remoteShell,host):\n line = host.IP_address + \" \" +host.HostName + \" \" + host.alias + \" \" +host.comment\n set_content(elevated_remoteShell,Line=line,FileName='/etc/hosts',Append=True)","sub_path":"Linux_Helpers/etc_hosts.py","file_name":"etc_hosts.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"94962364","text":"from __future__ import annotations\n\nfrom binascii import hexlify\n\nfrom typeddfs.df_typing import DfTyping\n\nfrom sauronlab.calc.waveform_embedding import *\nfrom sauronlab.core.core_imports import *\nfrom sauronlab.model.audio import Waveform\n\n\nclass StimFrame(TypedDf, metaclass=abc.ABCMeta):\n \"\"\"\n A DataFrame where the rows are milliseconds (or 'stimulus frames') and the columns are stimuli.\n A couple of properties:\n - The values are normally 0-255, but for some legacy assays are 0-1.\n - The rows are normally in milliseconds, but for legacy assays are currently every 40ms (25fps).\n - For SauronX assays, values for audio stimuli will have either:\n a) A single nonzero value followed by zeros to indicate that playback of the native audio file length begins there.\n b) More than one nonzero value in a row, indicating that the playback will start at the first nonzero position and end at the last.\n This means that the audio will be repeated and truncated as necessary to fill that number of milliseconds.\n c) A waveform embedded centered around 127.5 with maximum of 255 and minimum of 0.\n This will be used if expand_audio_inplace is called, or Sauronlab is set to store waveforms.\n In the first two cases, the first nonzero value dictates the volume, where 255 is the max volume allowed by SauronX,\n which is in turn determined by the audio card, the amplifier setting, and the settings configured in the Toml\n \"\"\"\n\n @classmethod\n def get_typing(cls) -> DfTyping:\n return DfTyping(_required_columns=[\"ms\"])\n\n def expand_audio_inplace(\n self, waveform_loader: Callable[[StimulusLike], Waveform], is_legacy: bool\n ) -> None:\n \"\"\"\n Replaces position in the stimframes for audio stimuli with values from a waveform.\n Also sets all solenoids and soft solenoids to have intensity 255.\n\n Args:\n waveform_loader: A function mapping stimulus names to Waveform objects.\n The waveforms will be 'standardized' to range from 0 to 255.\n is_legacy:\n\n \"\"\"\n for stim in self.columns:\n stim = Stimuli.fetch(stim)\n orig_stim_name = copy(stim.name)\n kind = ValarTools.stimulus_type(stim).name\n if kind == StimulusType.SOLENOID.name:\n self[stim.name] = 255 * (self[stim.name] > 0)\n if stim.audio_file is not None:\n try:\n self[orig_stim_name] = WaveformEmbedding.expand(\n self[orig_stim_name], stim, waveform_loader(stim.name), is_legacy=is_legacy\n )\n except Exception as e:\n raise AlgorithmError(f\"Failed to expand audio {orig_stim_name}\") from e\n\n def with_at_least(\n self, stim_or_type: Union[str, Stimuli, StimulusType], byteval: int\n ) -> StimFrame:\n \"\"\"\n\n\n Args:\n stim_or_type:\n byteval:\n\n Returns:\n\n \"\"\"\n if byteval < 0 or byteval > 255:\n raise OutOfRangeError(f\"{byteval} is not a byte\", value=byteval)\n real_stim = Stimuli.fetch_or_none(stim_or_type)\n real_type = None if real_stim is not None else StimulusType.of(stim_or_type)\n sel = None\n for stim in self.columns:\n if (\n real_stim is not None\n and Stimuli.fetch(stim) == real_stim\n or real_type is not None\n and (ValarTools.stimulus_type(stim) is StimulusType.of(stim_or_type))\n ):\n if sel is None:\n sel = self[stim] > 0\n else:\n sel |= self[stim] > 0\n return self[sel]\n\n @classmethod\n def _frame_df(cls, battery: Union[Batteries, int, str]) -> pd.DataFrame:\n battery = Batteries.fetch(battery)\n stimuli_in_batteries = (\n Stimuli.select(StimulusFrames, Stimuli, Assays, AssayPositions, Batteries)\n .join(StimulusFrames, join_type=JOIN.LEFT_OUTER)\n .join(Assays)\n .join(AssayPositions)\n .join(Batteries)\n .where(Batteries.id == battery.id)\n )\n df = pd.DataFrame(\n [\n [\n f.name,\n f.default_color,\n f.stimulusframes.assay.name,\n f.stimulusframes.assay.assaypositions.start,\n f.stimulusframes.assay.length,\n f.stimulusframes.assay.assaypositions.start + f.stimulusframes.assay.length,\n hexlify(f.stimulusframes.frames_sha1).decode(\"utf8\"),\n Tools.jvm_sbytes_to_ubytes(f.stimulusframes.frames),\n ]\n for f in stimuli_in_batteries\n ],\n columns=[\n \"stimulus\",\n \"color\",\n \"assay\",\n \"start\",\n \"length\",\n \"end\",\n \"frames_sha1\",\n \"frames\",\n ],\n )\n logger.info(f\"Downloaded battery {battery.name}\")\n if len(df) == 0:\n logger.warning(\"Battery {battery} / {battery.name} has no stimulus frames\")\n return df.sort_values(\"start\")\n\n @classmethod\n def _slice_stim(\n cls, stimframes, name: str, start_ms: Optional[int] = None, end_ms: Optional[int] = None\n ) -> StimFrame:\n stimframes_per_ms = 25 / 1000 if ValarTools.battery_is_legacy(name) else 1\n start_ms = 0 if start_ms is None else start_ms\n end_ms = len(stimframes) / stimframes_per_ms if end_ms is None else end_ms\n # return stimframes[int(np.floor(stimframes_per_ms * start_ms)) : int(np.ceil(stimframes_per_ms * end_ms))]\n return stimframes[int(stimframes_per_ms * start_ms) : int(stimframes_per_ms * end_ms)]\n\n @classmethod\n def _generate_stimframes(\n cls, battery: Batteries, fps_for_sampling: Optional[int] = None\n ) -> pd.DataFrame:\n fdf = StimFrame._frame_df(battery)\n if len(fdf) == 0:\n dct = {\n k: v\n for k, v in zip(\n fdf.columns,\n [\n \"none\",\n \"#ffffff\",\n \"\",\n 0,\n battery.length,\n battery.length,\n \"\",\n np.zeros((battery.length,)),\n ],\n )\n }\n fdf = fdf.append(pd.Series(dct), ignore_index=True)\n the_range = np.arange(fdf.tail(1).end.values) if len(fdf) > 0 else []\n empty_df = pd.DataFrame(index=the_range, columns=set(fdf.stimulus))\n for idx in fdf.index:\n start_index = fdf.start.loc[idx]\n assay_frames = fdf.frames.loc[idx]\n stim_name = fdf.stimulus.loc[idx]\n empty_df.loc[\n start_index : start_index + len(assay_frames) - 1, stim_name\n ] = assay_frames\n stimframes = empty_df.fillna(0)\n stimframes.index.name = \"ms\"\n if fps_for_sampling is not None:\n return stimframes[:: int(1000 / fps_for_sampling)]\n else:\n return stimframes\n\n\nclass BatteryStimFrame(StimFrame):\n \"\"\" \"\"\"\n\n @classmethod\n def of(cls, df, *args, **kwargs) -> BatteryStimFrame:\n if isinstance(df, (Batteries, int, str)):\n battery = Batteries.fetch(df) # type: Batteries\n stimframes = StimFrame._generate_stimframes(battery, None)\n stimframes = StimFrame._slice_stim(\n stimframes, battery.name, kwargs.get(\"start_ms\"), kwargs.get(\"end_ms\")\n )\n return cls._gen_from(battery)(stimframes)\n return super().of(df, *args, **kwargs)\n\n @classmethod\n def battery(cls) -> Batteries:\n raise NotImplementedError()\n\n def slice_ms(\n self,\n battery: Union[Batteries, int, str],\n start_ms: Optional[int] = None,\n end_ms: Optional[int] = None,\n ) -> BatteryStimFrame:\n battery = battery if isinstance(battery, str) else Batteries.fetch(battery).name\n rdf = StimFrame._slice_stim(self, battery, start_ms, end_ms)\n rdf.__class__ = self.__class__\n # noinspection PyTypeChecker\n return rdf\n\n def deltas(self) -> BatteryStimFrame:\n \"\"\"\n Returns a new stimframe with value 1 at the time the stimulus changed and 0 elsewhere.\n Calculates independently per stimulus.\n\n Returns:\n\n \"\"\"\n # noinspection PyTypeChecker,PyUnresolvedReferences\n df = (self.diff() > 0).astype(np.float32).fillna(0)\n return BatteryStimFrame(df)\n\n @classmethod\n def _gen_from(cls, battery: Batteries) -> Type[BatteryStimFrame]:\n class BatteryX(BatteryStimFrame):\n @classmethod\n def battery(cls) -> Batteries:\n return battery\n\n BatteryX.__name__ = f\"Battery{battery.id}StimFrame\"\n return BatteryX\n\n\n__all__ = [\"StimFrame\", \"BatteryStimFrame\"]\n","sub_path":"sauronlab/sauronlab/model/stim_frames.py","file_name":"stim_frames.py","file_ext":"py","file_size_in_byte":9181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"30051206","text":"from element import BasePageElement\nfrom locators import MainPageLocators\n\nclass SearchTextElement(BasePageElement):\n \"\"\"This class gets the search text from the specified locator\"\"\"\n #The locator for search box where search string is entered\n locator = 'q'\n\n\nclass BasePage(object):\n \"\"\"Base class to initialize the base page that will be called from all pages\"\"\"\n\n def __init__(self, driver):\n self.driver = driver\n\n\n","sub_path":"libs/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"635143195","text":"# coding: UTF-8\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom util import loss_fn\n\n\nclass Config(object):\n def __init__(self, data_dir):\n self.model_name = 'mmoe'\n self.train_path = data_dir + 'census-income.data.gz'\n self.test_path = data_dir + 'census-income.test.gz'\n self.save_path = './saved_dict/' + self.model_name + '.ckpt'\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n self.require_improvement = 1000\n self.dropout = 0.5\n self.learning_rate = 3e-5\n self.label_columns = ['income_50k', 'marital_stat']\n\n self.label_dict = [2, 2]\n self.num_feature = 0\n self.num_experts = 3\n self.num_tasks = 2\n self.units = 16\n self.hidden_units = 8\n self.embed_size = 300\n self.batch_size = 256\n self.field_size = 0\n self.towers_hidden = 16\n self.SB_hidden = 1024\n self.SB_output = 512\n self.num_epochs = 100\n self.loss_fn = loss_fn('binary')\n\n\nclass Transform_layer(nn.Module):\n def __init__(self, input_size, output_size, config):\n super(Transform_layer, self).__init__()\n self.alpha = torch.nn.Parameter(torch.rand((1,), device=config.device), requires_grad=True)\n self.beta = 0.9\n self.gamma = -0.1\n self.eplison = 2\n\n w = torch.empty(input_size, config.num_experts,output_size, device=config.device)\n self.u = torch.nn.Parameter(torch.nn.init.uniform_(w, 0, 1),\n requires_grad=True)\n\n w = torch.empty(input_size,config.num_experts, output_size, device=config.device)\n self.w_params = torch.nn.Parameter(torch.nn.init.xavier_normal_(w),\n requires_grad=True)\n\n def forward(self, x):\n self.s = torch.sigmoid(torch.log(self.u) - torch.log(1 - self.u) + torch.log(self.alpha) / self.beta)\n self.s_ = self.s * (self.eplison - self.gamma) + self.gamma\n\n self.z_params = (self.s_ > 0).float() * self.s_\n self.z_params = (self.z_params > 1).float() + (self.z_params <= 1).float() * self.z_params\n\n output = self.z_params * self.w_params\n output = torch.einsum('ab,bnc -> anc', x, output)\n return output\n\nclass high_layers(nn.Module):\n\n def __init__(self,input_size,output_size,config):\n super(high_layers,self).__init__()\n self.alpha = torch.nn.Parameter(torch.rand((1,), device=config.device), requires_grad=True)\n self.beta = 0.9\n self.gamma = -0.1\n self.eplison = 2\n\n w = torch.empty(input_size, output_size, device=config.device)\n self.u = torch.nn.Parameter(torch.nn.init.uniform_(w, 0, 1),\n requires_grad=True)\n\n w = torch.empty(input_size, output_size, device=config.device)\n self.w_params = torch.nn.Parameter(torch.nn.init.xavier_normal_(w),\n requires_grad=True)\n def forward(self,x):\n self.s = torch.sigmoid(torch.log(self.u) - torch.log(1 - self.u) + torch.log(self.alpha) / self.beta)\n self.s_ = self.s * (self.eplison - self.gamma) + self.gamma\n\n self.z_params = (self.s_ > 0).float() * self.s_\n self.z_params = (self.z_params > 1).float() + (self.z_params <= 1).float() * self.z_params\n\n output = self.z_params * self.w_params\n output = torch.einsum('anc,cd -> and', x, output)\n return output\n\n\nclass Tower(nn.Module):\n def __init__(self, input_size, output_size, hidden_size=16):\n super(Tower, self).__init__()\n self.fc1 = nn.Linear(input_size, hidden_size)\n self.fc2 = nn.Linear(hidden_size, output_size)\n self.relu = nn.ReLU()\n self.dropout = nn.Dropout(0.4)\n\n def forward(self, x):\n out = self.fc1(x)\n out = self.relu(out)\n out = self.dropout(out)\n out = self.fc2(out)\n\n out = torch.sigmoid(out)\n return out\n\n\nclass Model(nn.Module):\n def __init__(self, config):\n super(Model, self).__init__()\n\n # accept_unit = config.field_size*config.embed_size\n accept_unit = config.num_feature\n self.trans1 = Transform_layer(accept_unit, config.SB_hidden, config)\n self.trans2 = high_layers(config.SB_hidden,config.SB_output,config)\n\n self.fc_experts = nn.Linear(config.num_experts,1)\n self.relu = nn.ReLU()\n\n self.towers = nn.ModuleList([Tower(config.SB_output, 1, config.towers_hidden) for i in range(config.num_tasks)])\n\n self.lamdba = 1e-4\n\n # self.embedding_layer = nn.Embedding(config.num_feature,config.embed_size)\n\n def forward(self, x):\n output = self.trans1(x)\n output = self.trans2(output)\n output = output.transpose(2,1)\n output = self.fc_experts(output)\n output = torch.squeeze(output)\n output = self.relu(output)\n\n final_outputs = [tower(output) for tower in self.towers]\n\n s1 = self.trans1.s_\n s2 = self.trans2.s_\n\n\n s1_prob = 1 - ((s1 < 0).sum(dim=-1) / s1.size(1))\n s2_prob = 1 - ((s2 < 0).sum(dim=-1) / s2.size(1))\n\n regul = self.lamdba * (s1_prob.sum() + s2_prob.sum())\n # regul = 0\n return final_outputs, regul\n\n","sub_path":"Models/snr_trans.py","file_name":"snr_trans.py","file_ext":"py","file_size_in_byte":5294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"247621875","text":"from cv2 import cv2\n\n# Load the eye cascade\neyes_cascade_path = \"../haarcascades/haarcascade_eye.xml\"\n\n# Load the face cascade\neyes_cascade = cv2.CascadeClassifier(eyes_cascade_path)\nface_cascade_path = \"../haarcascades/haarcascade_frontalface_default.xml\"\nface_cascade = cv2.CascadeClassifier(face_cascade_path)\n\nimage_path = r\"../assets/img.png\"\nimage = cv2.imread(image_path)\nimage = cv2.resize(image, (512, 512))\n\n# Convert image to gray\nimage_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\nimage_gray = cv2.equalizeHist(image_gray)\n\n# Detect faces in the image\nfaces = face_cascade.detectMultiScale(image_gray)\n\n# Draw ellipse for each face in the image\nfor (x, y, w, h) in faces:\n # Draw ellipse around the face\n center = (x + w // 2, y + h // 2)\n image = cv2.ellipse(image, center, (w // 2, h // 2), 0, 0, 360, (255, 0, 255), 4)\n\n # Crop face from the image and use it for eye detection\n faceROI = image_gray[y:y + h // 2, x:x + w]\n\n # Detect eyes for each face\n eyes = eyes_cascade.detectMultiScale(faceROI)\n for (x2, y2, w2, h2) in eyes:\n eye_center = (x + x2 + w2 // 2, y + y2 + h2 // 2)\n radius = int(round((w2 + h2) * 0.25))\n # Draw circle around the eye\n frame = cv2.circle(image, eye_center, radius, (255, 0, 0), 4)\n\ncv2.imshow('Capture - Face detection', image)\ncv2.waitKey(0)\n","sub_path":"feature-detection/eyes-detection.py","file_name":"eyes-detection.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"254190601","text":"'''\r\nCreated on Sep 10, 2015\r\n\r\n@author: scale 87762\r\n'''\r\n'''\r\nGiven A list of mix datatypes give you th sum of all\r\nints in the list.\r\n\r\nCreate a new list with all of the strings only\r\n'''\r\n\r\n\r\n\r\nmyList = [\"apple\", \"banana\", 2, 3]\r\n\r\n","sub_path":"PythonLabs/ExtraCredit.py","file_name":"ExtraCredit.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"228179312","text":"def readfile(path):\n import numpy as np\n f = open(path, 'r')\n return np.loadtxt(f)\n\nif __name__ == \"__main__\":\n import sys \n sys.path.insert(0, \"/home/akke/Physicum/dyna/project/trim/\")\n from trim import removeFirst\n path = sys.argv[1]\n N = int(sys.argv[2])\n resPath = \"results/\" + path + \"/\"\n axes = ['X','Y','Z']\n colors = ['r','b','g','m','k']\n \n data = readfile(resPath + \"int.out\")\n removeFirst(data,N)\n\n from matplotlib import pyplot as pl\n \n pl.figure(0);\n for i in range(int(N)):\n X = data[:,1+3*i]\n Y = data[:,2+3*i]\n\n pl.plot(X,Y,'.')\n \n pl.savefig(resPath + \"orbitplot.pdf\")\n pl.show()\n","sub_path":"plot/plotxy.py","file_name":"plotxy.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"511238699","text":"import paddle.fluid as fluid\r\nimport numpy as np\r\nfrom paddle.fluid.layer_helper import LayerHelper\r\nfrom paddle.fluid.dygraph import Conv2D, Pool2D, BatchNorm, Linear, InstanceNorm, PRelu, SpectralNorm\r\nfrom paddle.fluid.dygraph import Sequential\r\n\r\n\r\nclass ResnetGenerator(fluid.dygraph.Layer):\r\n def __init__(self, input_nc, output_nc, ngf=64, n_blocks=6, img_size=256, light=False):\r\n assert(n_blocks >= 0)\r\n super(ResnetGenerator, self).__init__()\r\n self.input_nc = input_nc\r\n self.output_nc = output_nc\r\n self.ngf = ngf\r\n self.n_blocks = n_blocks\r\n self.img_size = img_size\r\n self.light = light\r\n\r\n DownBlock = []\r\n # 先通过一个卷积核尺寸为7的卷积层,图片大小不变,通道数变为64\r\n DownBlock += [ReflectionPad2d(3),\r\n Conv2D(input_nc, ngf, filter_size=7, stride=1, padding=0, bias_attr=False),\r\n InstanceNorm(ngf),\r\n PRelu(mode=\"all\")]\r\n\r\n # Down-Sampling --> 下采样模块\r\n n_downsampling = 2\r\n # 两层下采样,img_size缩小4倍(64),通道数扩大4倍(256)\r\n for i in range(n_downsampling):\r\n mult = 2**i\r\n DownBlock += [ReflectionPad2d(1),\r\n Conv2D(ngf * mult, ngf * mult * 2, filter_size=3, stride=2, padding=0, bias_attr=False),\r\n InstanceNorm(ngf * mult * 2),\r\n PRelu(mode=\"all\")]\r\n\r\n # Down-Sampling Bottleneck --> 编码器中的残差模块\r\n mult = 2**n_downsampling\r\n # 6个残差块,尺寸和通道数都不变\r\n for i in range(n_blocks):\r\n DownBlock += [ResnetBlock(ngf * mult, use_bias=False)]\r\n\r\n # Class Activation Map --> 产生类别激活图\r\n # 接着global average pooling后的全连接层\r\n self.gap_fc = Linear(ngf * mult, 1, bias_attr=False)\r\n # 接着global max pooling后的全连接层\r\n self.gmp_fc = Linear(ngf * mult, 1, bias_attr=False)\r\n #下面1x1卷积和激活函数,是为了得到两个pooling合并后的特征图\r\n self.conv1x1 = Conv2D(ngf * mult * 2, ngf * mult, filter_size=1, stride=1, bias_attr=True, act='relu')\r\n # self.relu = nn.ReLU(True)\r\n\r\n # Gamma, Beta block --> 生成自适应 L-B Normalization(AdaILN)中的Gamma, Beta\r\n # 确定轻量级,FC使用的是两个256 --> 256的全连接层\r\n if self.light:\r\n FC = [Linear(ngf * mult, ngf * mult, bias_attr=False, act='relu'),\r\n # nn.ReLU(True),\r\n Linear(ngf * mult, ngf * mult, bias_attr=False, act='relu'),\r\n # nn.ReLU(True)\r\n ]\r\n else:\r\n # 不是轻量级,则下面的1024x1024 --> 256的全连接层和一个256 --> 256的全连接层\r\n FC = [Linear(img_size // mult * img_size // mult * ngf * mult, ngf * mult, bias_attr=False, act='relu'),\r\n # nn.ReLU(True),\r\n Linear(ngf * mult, ngf * mult, bias_attr=False, act='relu'),\r\n # nn.ReLU(True)\r\n ]\r\n # AdaILN中的Gamma, Beta\r\n self.gamma = Linear(ngf * mult, ngf * mult, bias_attr=False)\r\n self.beta = Linear(ngf * mult, ngf * mult, bias_attr=False)\r\n\r\n # Up-Sampling Bottleneck --> 解码器中的自适应残差模块\r\n for i in range(n_blocks):\r\n setattr(self, 'UpBlock1_' + str(i+1), ResnetAdaILNBlock(ngf * mult, use_bias=False))\r\n\r\n # Up-Sampling --> 解码器中的上采样模块\r\n UpBlock2 = []\r\n # 上采样与编码器的下采样对应\r\n for i in range(n_downsampling):\r\n mult = 2**(n_downsampling - i)\r\n UpBlock2 += [Upsample(),\r\n ReflectionPad2d(1),\r\n Conv2D(ngf * mult, int(ngf * mult / 2), filter_size=3, stride=1, padding=0, bias_attr=False, act='relu'),\r\n ILN(int(ngf * mult / 2)), # 注:只有自适应残差块使用AdaILN\r\n # nn.ReLU(True)\r\n ]\r\n # 最后一层卷积层,与最开始的卷积层对应\r\n UpBlock2 += [ReflectionPad2d(3),\r\n Conv2D(ngf, output_nc, filter_size=7, stride=1, padding=0, bias_attr=False, act='tanh'),\r\n # nn.Tanh()\r\n ]\r\n\r\n self.DownBlock = Sequential(*DownBlock) # 编码器整个模块\r\n self.FC = Sequential(*FC) # 生成gamma,beta的全连接层模块\r\n self.UpBlock2 = Sequential(*UpBlock2) # 只包含上采样后的模块,不包含残差块\r\n\r\n def forward(self, input):\r\n x = self.DownBlock(input)\r\n # 得到编码器的输出,对应途中encoder feature map\r\n # torch.Size([1, 256, 64, 64])\r\n # gap torch.Size([1, 256, 1, 1])\r\n\r\n gap = Pool2D(pool_size=x.shape[-1],pool_stride=x.shape[-1],pool_type='avg')(x) #全局平均池化\r\n gap = fluid.layers.reshape(gap, shape=[x.shape[0], -1]) #torch.Size([1, 1])\r\n gap_logit = self.gap_fc(gap) #gap的预测\r\n gap_weight = list(self.gap_fc.parameters())[0] #self.gap_fc的权重参数 torch.Size([1, 256])\r\n gap_weight = fluid.layers.unsqueeze(input=gap_weight, axes=[0])\r\n gap_weight = fluid.layers.unsqueeze(input=gap_weight, axes=[3])\r\n gap = x * gap_weight #得到全局平均池化加持权重的特征图 torch.Size([1, 256, 64, 64])\r\n\r\n gmp = Pool2D(pool_size=x.shape[-1],pool_stride=x.shape[-1],pool_type='max')(x)\r\n gmp = fluid.layers.reshape(gmp, shape=[x.shape[0], -1])\r\n gmp_logit = self.gmp_fc(gmp)\r\n gmp_weight = list(self.gmp_fc.parameters())[0]\r\n gmp_weight = fluid.layers.unsqueeze(input=gmp_weight, axes=[0])\r\n gmp_weight = fluid.layers.unsqueeze(input=gmp_weight, axes=[3]) \r\n gmp = x * gmp_weight #torch.Size([1, 256, 64, 64])\r\n\r\n cam_logit = fluid.layers.concat([gap_logit, gmp_logit], 1) #结合gap和gmp的cam_logit预测\r\n x = fluid.layers.concat([gap, gmp], 1) #torch.Size([1, 512, 64, 64]) \r\n x = self.conv1x1(x) #接入一个卷积层,通道数512转换为256 torch.Size([1, 256, 64, 64])\r\n #x = self.relu(self.conv1x1(x))\r\n #torch.Size([1, 256, 64, 64])\r\n\r\n # heatmap = torch.sum(x, dim=1, keepdim=True)\r\n heatmap = fluid.layers.reduce_sum(x, dim=1, keep_dim=True) #得到注意力热力图\r\n #heatmap torch.Size([1, 1, 64, 64])\r\n\r\n if self.light:\r\n #轻量级则先经过一个gap\r\n x_ = fluid.layers.adaptive_pool2d(x, 1,pool_type='avg')\r\n x_ = fluid.layers.reshape(x_, shape=[x.shape[0], -1])\r\n x_ = self.FC(x_)\r\n else:\r\n x_=fluid.layers.reshape(x, shape=[x.shape[0], -1])\r\n x_ = self.FC(x_)\r\n gamma, beta = self.gamma(x_), self.beta(x_) #得到自适应gamma和beta\r\n # gamma torch.Size([1, 256]) beta torch.Size([1, 256])\r\n\r\n for i in range(self.n_blocks):\r\n # 将自适应gamma和beta送入到AdaILN\r\n x = getattr(self, 'UpBlock1_' + str(i+1))(x, gamma, beta)\r\n out = self.UpBlock2(x) #通过上采样后的模块,得到生成结果\r\n #out torch.Size([1, 3, 256, 256]) cam_logit torch.Size([1, 2]) heatmap torch.Size([1, 1, 64, 64])\r\n\r\n return out, cam_logit, heatmap #模型输出为生成结果,cam预测以及热力图\r\n\r\n\r\nclass ResnetBlock(fluid.dygraph.Layer):\r\n def __init__(self, dim, use_bias):\r\n super(ResnetBlock, self).__init__()\r\n conv_block = []\r\n conv_block += [ReflectionPad2d(1),\r\n Conv2D(dim, dim, filter_size=3, stride=1, padding=0, bias_attr=use_bias),\r\n InstanceNorm(dim),\r\n PRelu(mode=\"all\")]\r\n\r\n conv_block += [ReflectionPad2d(1),\r\n Conv2D(dim, dim, filter_size=3, stride=1, padding=0, bias_attr=use_bias),\r\n InstanceNorm(dim)]\r\n\r\n self.conv_block = Sequential(*conv_block)\r\n\r\n def forward(self, x):\r\n out = x + self.conv_block(x)\r\n return out\r\n\r\n\r\nclass ResnetAdaILNBlock(fluid.dygraph.Layer):\r\n def __init__(self, dim, use_bias):\r\n super(ResnetAdaILNBlock, self).__init__()\r\n self.pad1 = ReflectionPad2d(1)\r\n self.conv1 = Conv2D(dim, dim, filter_size=3, stride=1, padding=0, bias_attr=use_bias)\r\n self.norm1 = adaILN(dim)\r\n # self.relu1 = nn.ReLU(True)\r\n\r\n self.pad2 = ReflectionPad2d(1)\r\n self.conv2 = Conv2D(dim, dim, filter_size=3, stride=1, padding=0, bias_attr=use_bias)\r\n self.norm2 = adaILN(dim)\r\n\r\n def forward(self, x, gamma, beta):\r\n out = self.pad1(x)\r\n out = self.conv1(out)\r\n out = self.norm1(out, gamma, beta)\r\n out = fluid.layers.relu(out)\r\n # out = self.relu1(out)\r\n out = self.pad2(out)\r\n out = self.conv2(out)\r\n out = self.norm2(out, gamma, beta)\r\n\r\n return out + x\r\n\r\n# Adaptive Layer-Instance Normalization代码\r\nclass adaILN(fluid.dygraph.Layer):\r\n def __init__(self, num_features, eps=1e-5):\r\n super(adaILN, self).__init__()\r\n self.eps = eps\r\n # adaILN的参数p,通过这个参数来动态调整LN和IN的占比\r\n self.rho = fluid.layers.fill_constant(shape=[1, num_features, 1, 1], value=0.9, dtype='float32')\r\n\r\n def forward(self, input, gamma, beta):\r\n # torch.Size([1, 256, 64, 64])\r\n ninput = input.numpy()\r\n # 先求两种规范化的值\r\n in_mean, in_var = np.mean(ninput, axis=(2, 3), keepdims=True), np.var(ninput, axis=(2, 3), keepdims=True)\r\n out_in = (ninput - in_mean) / np.sqrt(in_var + self.eps)\r\n ln_mean, ln_var = np.mean(ninput, axis=(1, 2, 3), keepdims=True), np.var(ninput, axis=(1, 2, 3), keepdims=True)\r\n out_ln = (ninput - ln_mean) / np.sqrt(ln_var + self.eps)\r\n out_in = fluid.dygraph.base.to_variable(out_in)\r\n out_ln = fluid.dygraph.base.to_variable(out_ln)\r\n ninput = fluid.dygraph.base.to_variable(ninput)\r\n #out = fluid.dygraph.base.to_variable(out)\r\n # 合并两种规范化(IN, LN)\r\n out = self.rho * out_in + (1-self.rho) * out_ln\r\n # 扩张得到结果\r\n gamma = fluid.layers.unsqueeze(input=gamma, axes=[2])\r\n gamma = fluid.layers.unsqueeze(input=gamma, axes=[3]) \r\n beta = fluid.layers.unsqueeze(input=beta, axes=[2])\r\n beta = fluid.layers.unsqueeze(input=beta, axes=[3]) \r\n out = out * gamma + beta\r\n # out torch.Size([1, 256, 64, 64])\r\n\r\n return out\r\n\r\n\r\nclass ILN(fluid.dygraph.Layer):\r\n def __init__(self, num_features, eps=1e-5):\r\n super(ILN, self).__init__()\r\n self.eps = eps\r\n self.rho = fluid.layers.fill_constant(shape=[1, num_features, 1, 1], value=0.0, dtype='float32')\r\n self.gamma = fluid.layers.fill_constant(shape=[1, num_features, 1, 1], value=1.0, dtype='float32')\r\n self.beta = fluid.layers.fill_constant(shape=[1, num_features, 1, 1], value=0.0, dtype='float32')\r\n\r\n def forward(self, input):\r\n #torch.Size([1, 128, 128, 128])\r\n ninput = input.numpy()\r\n\r\n in_mean, in_var=np.mean(ninput, axis=(2, 3), keepdims=True), np.var(ninput, axis=(2, 3), keepdims=True)\r\n out_in = (ninput - in_mean) / np.sqrt(in_var + self.eps)\r\n ln_mean, ln_var = np.mean(ninput, axis=(1, 2, 3), keepdims=True), np.var(ninput, axis=(1, 2, 3), keepdims=True)\r\n out_ln = (ninput - ln_mean) / np.sqrt(ln_var + self.eps)\r\n out_in = fluid.dygraph.base.to_variable(out_in)\r\n out_ln = fluid.dygraph.base.to_variable(out_ln)\r\n ninput = fluid.dygraph.base.to_variable(ninput) \r\n out = self.rho * out_in + (1-self.rho) * out_ln\r\n out = out * self.gamma + self.beta\r\n # out torch.Size([1, 128, 128, 128])\r\n\r\n return out\r\n\r\n\r\nclass Discriminator(fluid.dygraph.Layer):\r\n def __init__(self, input_nc, ndf=64, n_layers=5):\r\n super(Discriminator, self).__init__()\r\n # 第一层下采样, 尺寸减半(128),通道数为64\r\n model = [ReflectionPad2d(1),\r\n Spectralnorm(Conv2D(input_nc, ndf, filter_size=4, stride=2, padding=1, bias_attr=True, act='leaky_relu')),\r\n # nn.LeakyReLU(0.2, True)\r\n ]\r\n # 第二,三层下采样,尺寸再缩4倍(32),通道数为256\r\n for i in range(1, n_layers - 2):\r\n mult = 2 ** (i - 1)\r\n model += [ReflectionPad2d(1),\r\n Spectralnorm(Conv2D(ndf * mult, ndf * mult * 2, filter_size=4, stride=2, padding=0, bias_attr=True, act='leaky_relu')),\r\n # nn.LeakyReLU(0.2, True)\r\n ]\r\n # 尺寸不变(32),通道数为512\r\n mult = 2 ** (n_layers - 2 - 1)\r\n model += [ReflectionPad2d(1),\r\n Spectralnorm(Conv2D(ndf * mult, ndf * mult * 2, filter_size=4, stride=1, padding=0, bias_attr=True, act='leaky_relu')),\r\n # nn.LeakyReLU(0.2, True)\r\n ]\r\n\r\n # Class Activation Map\r\n mult = 2 ** (n_layers - 2)\r\n self.gap_fc = Spectralnorm(Linear(ndf * mult, 1, bias_attr=False))\r\n self.gmp_fc = Spectralnorm(Linear(ndf * mult, 1, bias_attr=False))\r\n self.conv1x1 = Conv2D(ndf * mult * 2, ndf * mult, filter_size=1, stride=1, bias_attr=True)\r\n # self.leaky_relu = nn.LeakyReLU(0.2, True)\r\n\r\n self.pad = ReflectionPad2d(1)\r\n self.conv = Spectralnorm(Conv2D(ndf * mult, 1, filter_size=4, stride=1, padding=0, bias_attr=False))\r\n\r\n self.model = Sequential(*model)\r\n\r\n def forward(self, input):\r\n x = self.model(input) #[1, 2048, 2, 2]\r\n\r\n gap = Pool2D(pool_size=x.shape[-1],pool_stride=x.shape[-1],pool_type='avg')(x) #[1, 2048, 1, 1]\r\n gap = fluid.layers.reshape(gap, shape=[x.shape[0], -1]) \r\n gap_logit = self.gap_fc(gap) #torch.Size([1, 1])\r\n gap_weight = list(self.gap_fc.parameters())[0]\r\n gap_weight = fluid.layers.unsqueeze(input=gap_weight, axes=[0])\r\n gap_weight = fluid.layers.unsqueeze(input=gap_weight, axes=[3]) \r\n gap = x * gap_weight #[1, 2048, 2, 2]\r\n\r\n gmp = Pool2D(pool_size=x.shape[-1],pool_stride=x.shape[-1],pool_type='max')(x)\r\n gmp = fluid.layers.reshape(gmp, shape=[x.shape[0], -1]) \r\n gmp_logit = self.gmp_fc(gmp)\r\n gmp_weight = list(self.gmp_fc.parameters())[0]\r\n gmp_weight = fluid.layers.unsqueeze(input=gmp_weight, axes=[0])\r\n gmp_weight = fluid.layers.unsqueeze(input=gmp_weight, axes=[3]) \r\n gmp = x * gmp_weight\r\n\r\n cam_logit = fluid.layers.concat([gap_logit, gmp_logit], 1)\r\n x = fluid.layers.concat([gap, gmp], 1)\r\n x = fluid.layers.leaky_relu(self.conv1x1(x))\r\n\r\n heatmap = fluid.layers.reduce_sum(x, dim=1, keep_dim=True)\r\n\r\n x = self.pad(x)\r\n out = self.conv(x)\r\n\r\n return out, cam_logit, heatmap\r\n\r\n\r\nclass RhoClipper(object):\r\n\r\n def __init__(self, min, max):\r\n self.clip_min = min\r\n self.clip_max = max\r\n assert min < max\r\n\r\n def __call__(self, module):\r\n\r\n if hasattr(module, 'rho'):\r\n w = module.rho.data\r\n w = w.clamp(self.clip_min, self.clip_max)\r\n module.rho.data = w\r\n\r\n\r\nclass ReflectionPad2d(fluid.dygraph.Layer):\r\n def __init__(self, size):\r\n super(ReflectionPad2d, self).__init__()\r\n self.size = size\r\n \r\n def forward(self, x):\r\n return fluid.layers.pad2d(x, [self.size] * 4, mode='reflect')\r\n\r\n\r\n# 定义上采样模块\r\nclass Upsample(fluid.dygraph.Layer):\r\n def __init__(self, scale=2):\r\n super(Upsample, self).__init__()\r\n self.scale = scale\r\n\r\n def forward(self, inputs):\r\n # get dynamic upsample output shape\r\n shape_nchw = fluid.layers.shape(inputs)\r\n shape_hw = fluid.layers.slice(shape_nchw, axes=[0], starts=[2], ends=[4])\r\n shape_hw.stop_gradient = True\r\n in_shape = fluid.layers.cast(shape_hw, dtype='int32')\r\n out_shape = in_shape * self.scale\r\n out_shape.stop_gradient = True\r\n\r\n # reisze by actual_shape\r\n out = fluid.layers.resize_nearest(\r\n input=inputs, scale=self.scale, actual_shape=out_shape)\r\n return out\r\n\r\n\r\nclass Spectralnorm(fluid.dygraph.Layer):\r\n def __init__(self,\r\n layer,\r\n dim=0,\r\n power_iters=1,\r\n eps=1e-12,\r\n dtype='float32'):\r\n super(Spectralnorm, self).__init__()\r\n self.spectral_norm = SpectralNorm(layer.weight.shape, dim, power_iters, eps, dtype)\r\n self.dim = dim\r\n self.power_iters = power_iters\r\n self.eps = eps\r\n self.layer = layer\r\n weight = layer._parameters['weight']\r\n del layer._parameters['weight']\r\n self.weight_orig = self.create_parameter(weight.shape, dtype=weight.dtype)\r\n self.weight_orig.set_value(weight)\r\n\r\n def forward(self, x):\r\n weight = self.spectral_norm(self.weight_orig)\r\n self.layer.weight = weight\r\n out = self.layer(x)\r\n \r\n return out\r\n\r\n \r\nclass BCEWithLogitsLoss():\r\n def __init__(self, weight=None, reduction='mean'):\r\n self.weight = weight\r\n self.reduction = 'mean'\r\n\r\n def __call__(self, x, label):\r\n out = fluid.layers.sigmoid_cross_entropy_with_logits(x, label)\r\n if self.reduction == 'sum':\r\n return fluid.layers.reduce_sum(out)\r\n elif self.reduction == 'mean':\r\n return fluid.layers.reduce_mean(out)\r\n else:\r\n return out","sub_path":"networks.py","file_name":"networks.py","file_ext":"py","file_size_in_byte":17728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"420573472","text":"'''\n Copyright (c) 2016-2017 Wind River Systems, 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 http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software distributed\n under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES\n OR CONDITIONS OF ANY KIND, either express or implied.\n'''\n\n\"\"\"\nThis module contains the Relay class which is a secure way to pipe data to a\nlocal socket connection. This is useful for Telnet which is not secure by\ndefault.\n\"\"\"\n\nimport logging\nimport random\nimport select\nimport socket\nimport ssl\nimport threading\nimport time\nimport sys\n# -------------------------------------------------------------------\n# Note: when using a proxy server, the socket class is overlayed with\n# pysocks class. Keep around a local copy so that local socket\n# connections don't use the proxy\n# -------------------------------------------------------------------\nnon_proxy_socket = None\n\n# yocto supports websockets, not websocket, so check for that\ntry:\n import websocket\nexcept ImportError:\n import websockets as websocket\n\nCONNECT_MSG = \"CONNECTED-129812\"\n\nclass Relay(object):\n \"\"\"\n Class for establishing a secure pipe between a cloud based websocket and a\n local socket. This is useful for things like Telnet which are not secure to\n use remotely.\n \"\"\"\n\n def __init__(self, wsock_host, sock_host, sock_port, secure=True,\n log=None, local_socket=None, reconnect=False):\n \"\"\"\n Initialize a relay object for piping data between a websocket and a\n local socket\n \"\"\"\n\n self.wsock_host = wsock_host\n self.sock_host = sock_host\n self.sock_port = sock_port\n self.secure = secure\n self.log = log\n self.proxy = None\n self.log_name = \"Relay:{}:{}({:0>5})\".format(self.sock_host,\n self.sock_port,\n random.randint(0,99999))\n self.reconnect = reconnect\n if self.log is None:\n self.logger = logging.getLogger(self.log_name)\n log_handler = logging.StreamHandler()\n #log_formatter = logging.Formatter(constants.LOG_FORMAT, datefmt=constants.LOG_TIME_FORMAT)\n #log_handler.setFormatter(log_formatter)\n self.logger.addHandler(log_handler)\n self.logger.setLevel(logging.DEBUG)\n self.log = self.logger.log\n\n self.running = False\n self.thread = None\n self.ws_thread = None\n self.lsock = None\n self.wsock = None\n self.lconnect = 0\n\n def _connect_local(self):\n ret = False\n try:\n # check for proxy. If not proxy, this\n # is None.\n if non_proxy_socket:\n self.lsock = non_proxy_socket(socket.AF_INET,\n socket.SOCK_STREAM)\n else:\n self.lsock = socket.socket(socket.AF_INET,\n socket.SOCK_STREAM)\n\n self.lsock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True)\n self.lsock.connect((self.sock_host,\n self.sock_port))\n self.lsock.setblocking(0)\n except socket.error as err:\n self.running = False\n ret = True\n self.log(logging.ERROR, \"{} Failed to open local socket.\".format(self.log_name))\n self.log(logging.ERROR, \"Reason: {} \".format(str(err)))\n return ret\n\n def _on_local_message(self):\n \"\"\"\n Main loop that pipes all data from one socket to the next. The\n websocket connection is established first and has its own\n callback, so this is where the local socket will be handled.\n \"\"\"\n # ws data must be in binary format. The websocket lib uses\n # this op code\n op_binary = 0x2\n while self.running is True:\n if self.lsock:\n socket_list = [self.lsock]\n read_sockets, write_sockets, _es = select.select(socket_list, [], [], 1)\n if len(read_sockets):\n try:\n data = self.lsock.recv(4096)\n except:\n # during a close a read might return a EBADF,\n # that is ok, pass it don't dump an exception\n pass\n if data:\n self.log(logging.DEBUG, \"_on_local_message: send {} -> ws\".format(len(data)))\n try:\n self.wsock.send(data, opcode=op_binary)\n except websocket.WebSocketConnectionClosedException:\n self.log(logging.ERROR, \"Websocket closed\")\n break\n else:\n self.log(logging.INFO, \"{}: Received NULL from local socket\".format(self.log_name))\n if self.reconnect and self.running:\n self.log(logging.INFO, \"Reconnecting local socket\")\n time.sleep(2)\n self._connect_local()\n else:\n self.running = False\n break\n else:\n time.sleep(1)\n if self.lsock:\n self.lsock.close()\n self.lsock = None\n if self.wsock:\n self.wsock.close()\n self.wsock = None\n self.log(logging.INFO, \"{} - Sockets Closed\".format(self.log_name))\n\n def _on_open(self, ws):\n self.log(logging.INFO, \"_on_open: starting thread loop\")\n self.thread = threading.Thread(target=self._on_local_message)\n self.thread.start()\n\n def _on_message(self, ws, data):\n\n if data:\n if data == CONNECT_MSG:\n # If the local socket has not been established yet,\n # and we have received the connection string, start\n # local socket.\n self._connect_local()\n self.lconnect = 1;\n self.log(logging.DEBUG, \"{} Local socket opened\".format(self.log_name))\n else:\n # send to local socket\n self.log(logging.DEBUG, \"_on_message: send {} -> local socket\".format(len(data)))\n\n # py3 data of type string needs to be byte encoded\n if isinstance(data, str) and sys.version_info[0] > 2:\n data = bytes(data, 'utf-8')\n self.lsock.send(data)\n\n def _on_error(self, ws, exception):\n self.log(logging.ERROR, \"_on_error: exception {}\".format(str(exception)))\n if self.lsock:\n self.lsock.close()\n if self.wsock:\n self.wsock.close()\n self.stop()\n\n def _on_close(self, ws):\n self.log(logging.INFO,\"_on_close: websocket closed\")\n if self.lsock:\n self.lsock.close()\n self.running = False\n\n def start(self):\n \"\"\"\n Establish the websocket connection and start the main loop\n \"\"\"\n\n if not self.running:\n self.running = True\n sslopt = {}\n if not self.secure:\n sslopt[\"cert_reqs\"] = ssl.CERT_NONE\n self.wsock = websocket.WebSocketApp(\n self.wsock_host,\n on_message=self._on_message,\n on_error=self._on_error,\n on_close=self._on_close,\n on_open=self._on_open)\n kwargs = {'sslopt': sslopt}\n if self.proxy:\n self.log(logging.DEBUG, \"start:self.proxy={} \".format(self.proxy)),\n kwargs['http_proxy_host'] = self.proxy.host\n kwargs['http_proxy_port'] = self.proxy.port\n self.ws_thread = threading.Thread(target=self.wsock.run_forever, kwargs=kwargs)\n self.ws_thread.start()\n else:\n raise RuntimeError(\"{} - Already running!\".format(self.log_name))\n\n def stop(self):\n \"\"\"\n Stop piping data between the two connections and stop the loop thread\n \"\"\"\n\n self.log(logging.INFO, \"{} Stopping\".format(self.log_name))\n self.running = False\n self.reconnect = False\n if self.thread:\n self.thread.join()\n self.thread = None\n if self.ws_thread:\n self.ws_thread.join()\n self.ws_thread = None\n\n\nrelays = []\n\ndef create_relay(url, host, port, secure=True, log_func=None, local_socket=None,\n reconnect=False, proxy=None):\n global relays, non_proxy_socket\n\n non_proxy_socket = local_socket\n newrelay = Relay(url, host, port, secure=secure, log=log_func, reconnect=reconnect)\n if proxy:\n newrelay.proxy = proxy\n newrelay.start()\n relays.append(newrelay)\n\ndef stop_relays():\n global relays\n\n threads = []\n while relays:\n relay = relays.pop()\n thread = threading.Thread(target=relay.stop)\n thread.start()\n threads.append(thread)\n\n for thread in threads:\n thread.join()\n\n","sub_path":"device_cloud/relay.py","file_name":"relay.py","file_ext":"py","file_size_in_byte":9344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"534411492","text":"import os, sys\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\nimport numpy as np\nfrom flagelsum.regstokes.simulate import simulate_rotating_helical_tube_ftd\n\ndef generate_figure_2_data(o):\n \"\"\"\n Generate and save the data necessary to reproduce Figure 2.\n \"\"\"\n pitches = np.arange(2, 21)\n axial_length = 20\n tube_radius = 1/16\n data = np.empty([3, len(pitches)])\n for i in range(len(pitches)):\n (f, t, d) = simulate_rotating_helical_tube_ftd(\n pitch=pitches[i],\n axial_length=axial_length,\n tube_radius=tube_radius,\n gmres_tol=1e-4\n )\n data[0, i] = f\n data[1, i] = t\n data[2, i] = d\n np.save(o, data)\n\nif __name__ == \"__main__\":\n generate_figure_2_data('out/fig2_data.npy')\n","sub_path":"bin/generate_figure_2_data.py","file_name":"generate_figure_2_data.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"15756790","text":"from neuron import h\n\nclass PoissonSpiker(object):\n \"\"\"NetStim Object with variable lambda\"\"\"\n def __init__(self):\n self.soma = h.Section(name='soma', cell=self)\n self.syn_ = h.Exp2Syn(self.soma(0.5))\n self.stim = h.NetStim()\n self.stim.start = 0\n\n self.netcon = h.NetCon(self.stim, self.syn_)\n\n self.stim.interval = 10\n self.stim.number = 1e9\n self.stim.noise = 1\n\n def update_lambda(self, value):\n self.stim.interval = value","sub_path":"Version-2-0/src/PoissonSpiker.py","file_name":"PoissonSpiker.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"591566122","text":"# Author: PythonSalad\n# Date: 2013-06-09\n# Python Version: 2.7.3\n\n\"\"\" File contains the main game object, the core of the tdb game. \"\"\"\n\nimport pygame\nfrom config import GlobalConfig as GC\n\nclass Game:\n \"\"\" Contains the main game loop, StateGroups and all global game configs.\n Has functionality for loading and unloading StateGroups.\n \"\"\"\n def __init__(self, title = 'Game', frequency = 150):\n pygame.init()\n \n self._title = title\n\n # Default frequency of 150Hz (for game loop)\n self._frequency = frequency\n self._delta = 1000 // self._frequency\n\n self._ticks = pygame.time.get_ticks()\n self._is_active = True\n\n # Initialise display\n self._init_display()\n\n def _init_display(self):\n # Save current screen resolution\n self._initial_resolution = (\n pygame.display.Info().current_w,\n pygame.display.Info().current_h,\n )\n\n # Get resolution from config\n resolution = (\n GC().get_config('display', 'width'),\n GC().get_config('display', 'height'),\n )\n\n # Get flags from config\n flags = 0\n if GC().get_config('display', 'fullscreen'):\n flags = pygame.FULLSCREEN | pygame.HWSURFACE\n\n # Create the screen\n self.screen = pygame.display.set_mode(resolution, flags, 0)\n pygame.display.set_caption(self._title)\n\n def run(self):\n \"\"\" The main game loop. At intervals given by self._delta, flush\n the event queue and dispatch all messages to the active StateGroup.\n This function utilises wait, sleeping the main thread when\n all events are handled to avoid resource hogging.\n \"\"\"\n while self._is_active:\n ticks = pygame.time.get_ticks() - self._ticks\n if ticks < self._delta:\n pygame.time.wait(self._delta - ticks)\n self._ticks = pygame.time.get_ticks()\n\n def set_frequency(self, frequency):\n \"\"\" Set the game loop frequency and update self._delta \"\"\"\n self._frequency = frequency\n self._delta = 1000 // frequency\n\n def get_frequency(self):\n \"\"\" Get the game loop frequency. \"\"\"\n return self._frequency\n\n def __del__(self):\n \"\"\" Restore system to as it was before the game was launched. \"\"\"\n # Restore system resolution\n pygame.display.set_mode(self._initial_resolution)\n","sub_path":"tdb/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"148400364","text":"from multiprocessing import Queue\nfrom itertools import izip\n\nfrom traits.api import (\n HasTraits, Bool, Int, String, Set, Tuple, Dict, Instance, Range, Event,\n List, DelegatesTo, on_trait_change\n)\n\nfrom gambolputty.core import line_to_melody, choose_transition\nfrom gambolputty.model import (\n Phrase, Point, PhraseNode, Voice, Track, Transition\n)\nfrom gambolputty.exceptions import (\n GambolputtyException, NoPhraseSelected, NoVoiceSelected\n)\n\n\nclass PlayerBackend(HasTraits):\n \"\"\"\n Abstract base class for player backends.\n \"\"\"\n\n device = Int(-1)\n \"\"\"The number of the MIDI output device.\"\"\"\n\n devices = List(Int)\n \"\"\"Available MIDI output devices.\"\"\"\n\n def time(self):\n \"\"\"\n @return: the current MIDI time\n \"\"\"\n raise NotImplementedError\n\n def refresh_devices(self):\n device = self.device\n self.device = -1\n self.devices = list(self.init_devices())\n if device in self.devices:\n self.device = device\n\n def init_devices(self):\n \"\"\"\n @return: a sequence of output device numbers\n \"\"\"\n raise NotImplementedError\n\n def get_device_title(self, device_id):\n \"\"\"\n @return: the title of the given device number.\n \"\"\"\n raise NotImplementedError\n\n def get_device(self, device_title):\n \"\"\"\n @return: the device number for the given title.\n \"\"\"\n raise NotImplementedError\n\n def program_change(self, channel, program, time):\n \"\"\"\n Sends a MIDI ProgramChange event to the MIDI output device.\n \"\"\"\n raise NotImplementedError\n\n def noteon(self, channel, note, volume, time):\n \"\"\"\n Sends a MIDI NoteOn event to the MIDI output device.\n \"\"\"\n raise NotImplementedError\n\n def noteoff(self, channel, note, time):\n \"\"\"\n Sends a MIDI NoteOff event to the MIDI output device.\n \"\"\"\n raise NotImplementedError\n\n def all_notes_off(self, channel):\n \"\"\"\n Sends a MIDI NoteOff event for all notes to the MIDI output device.\n \"\"\"\n raise NotImplementedError\n\n\nclass NoDeviceSelected(GambolputtyException):\n title = \"No output device selected\"\n\n def __init__(self):\n super(NoDeviceSelected, self).__init__(\n \"Please select a MIDI output device\"\n )\n\n\nclass PyGamePlayerBackend(PlayerBackend):\n\n def __init__(self):\n from pygame import midi\n self.midi = midi\n self.midi.init()\n self.output = None\n super(PyGamePlayerBackend, self).__init__()\n\n def time(self):\n return self.midi.time()\n\n def init_devices(self):\n #if self.output is not None:\n # self.output = None\n self.midi.quit()\n self.midi.init()\n for i in range(self.midi.get_count()):\n interf, name, inp, outp, opened = self.midi.get_device_info(i)\n if outp != 1:\n continue\n yield i\n\n def get_device_title(self, device_id):\n if device_id < 0:\n return ''\n interf, name, inp, outp, opened = self.midi.get_device_info(device_id)\n return \"%d: %s\" % (device_id, name)\n\n def get_device(self, device_title):\n if not device_title:\n return -1\n return int(device_title.split(':')[0])\n\n @on_trait_change('device')\n def _device_changed(self):\n # Calling Output.close() here results in 'Bad Pointer' error,\n # for it is called automatically when dereferencing.\n # (see http://comments.gmane.org/gmane.comp.python.pygame/22027)\n if self.device < 0:\n self.output = None\n return\n self.output = self.midi.Output(self.device)\n\n def program_change(self, channel, program, time):\n if self.output is None:\n raise NoDeviceSelected()\n self.output.write([[[0xc0+channel, program, 0], time]])\n\n def noteon(self, channel, note, volume, time):\n if self.output is None:\n raise NoDeviceSelected()\n self.output.write([[[0x90+channel, note, volume], time]])\n\n def noteoff(self, channel, note, time):\n if self.output is None:\n raise NoDeviceSelected()\n self.output.write([[[0x80+channel, note, 0], time]])\n\n def all_notes_off(self, channel):\n if self.output is None:\n raise NoDeviceSelected()\n self.output.write([[[0xb0+channel, 123, 0], self.time()]])\n\n\nclass PortMidiPlayerBackend(PlayerBackend):\n\n def __init__(self):\n import pypm\n self.pypm = pypm\n pypm.Initialize()\n self.output = None\n super(PortMidiPlayerBackend, self).__init__()\n\n def time(self):\n return self.pypm.Time()\n\n def init_devices(self):\n self.device = -1\n if self.output is not None:\n self.output = None\n self.pypm.Terminate()\n self.pypm.Initialize()\n for i in range(self.pypm.CountDevices()):\n interf, name, inp, outp, opened = self.pypm.GetDeviceInfo(i)\n if outp != 1:\n continue\n yield i\n\n def get_device_title(self, device_id):\n if device_id < 0:\n return ''\n interf, name, inp, outp, opened = self.pypm.GetDeviceInfo(device_id)\n return \"%d: %s\" % (device_id, name)\n\n def get_device(self, device_title):\n if not device_title:\n return -1\n return int(device_title.split(':')[0])\n\n @on_trait_change('device')\n def _device_changed(self):\n self.output = self.pypm.Output(self.device, 0)\n\n def program_change(self, channel, program, time):\n if self.output is None:\n raise NoDeviceSelected()\n self.output.Write([[[0xc0+channel, program, 0], time]])\n\n def noteon(self, channel, note, volume, time):\n if self.output is None:\n raise NoDeviceSelected()\n self.output.Write([[[0x90+channel, note, volume], time]])\n\n def noteoff(self, channel, note, time):\n if self.output is None:\n raise NoDeviceSelected()\n self.output.Write([[[0x80+channel, note, 0], time]])\n\n def all_notes_off(self, channel):\n if self.output is None:\n raise NoDeviceSelected()\n self.output.Write([[[0xb0+channel, 123, 0], self.pypm.Time()]])\n\n\nclass Player(HasTraits):\n \"\"\"\n Abstract base class for players.\n \"\"\"\n\n playing = Bool(False)\n \"\"\"True if the player is currently playing back.\"\"\"\n\n def __init__(self, backend, **kwargs):\n \"\"\"\n Initializes the player.\n\n @param backend: the L{PlayerBackend}\n \"\"\"\n self.play_iter = None\n self.backend = backend\n super(Player, self).__init__(**kwargs)\n\n def tick(self):\n \"\"\"Ticks the player's iterator.\"\"\"\n if self.play_iter is None:\n return False\n try:\n self.play_iter.next()\n except StopIteration:\n self.play_iter = None\n self.playing = False\n return False\n except:\n self.play_iter = None\n self.playing = False\n raise\n else:\n return True\n\n def play(self):\n \"\"\"\n Starts the player by initializing L{Player.play_iter} with the\n generator function L{Player.iter()}.\n \"\"\"\n self.play_iter = self.iter()\n self.playing = True\n\n def stop(self):\n \"\"\"\n Stops the player.\n \"\"\"\n self.playing = False\n\n def iter(self):\n raise NotImplementedError\n\n\nclass PhrasePlayer(Player):\n \"\"\"\n Player for playing back a L{Phrase}.\n \"\"\"\n\n phrase = Instance(Phrase)\n \"\"\"The phrase to be played back.\"\"\"\n\n voice = Instance(Voice)\n \"\"\"The voice to use.\"\"\"\n\n tempo = Int(120)\n \"\"\"The tempo in beats per minute.\"\"\"\n\n transpose = Int(0)\n \"\"\"The number of half steps to add to every note.\"\"\"\n\n loop = Bool(False)\n \"\"\"Whether to loop playback.\"\"\"\n\n current_point = Instance(Point)\n \"\"\"The currently played back L{Point}.\"\"\"\n\n time = Int(-1)\n \"\"\"The current MIDI time.\"\"\"\n\n def stop(self):\n super(PhrasePlayer, self).stop()\n self.current_point = None\n\n def tick(self):\n result = super(PhrasePlayer, self).tick()\n if not result:\n self.time = -1\n return result\n\n def iter(self):\n if self.phrase is None:\n raise NoPhraseSelected\n if self.voice is None:\n raise NoVoiceSelected\n backend = self.backend\n try:\n while True:\n phrase = self.phrase\n if phrase is None or len(phrase.points) <= 1:\n yield None\n continue\n melody = line_to_melody(\n (p.pos for p in phrase.points),\n phrase.steps, phrase.transpose + self.transpose,\n )\n measure_len = (60.0/(float(self.tempo)/4.0))*1000\n point = None\n if self.time < 0:\n self.time = backend.time()\n voice = self.voice\n for point, (note, length) in izip(phrase.points[1:], melody):\n if not voice.mute:\n if point.type != 'Rest':\n backend.noteon(\n voice.channel,\n note,\n voice.volume,\n self.time,\n )\n self.current_point = point\n else:\n self.current_point = None\n note_len = int(measure_len*length)\n note_time = self.time + note_len\n try:\n while backend.time() < note_time:\n yield None\n self.time = note_time\n finally:\n backend.noteoff(\n voice.channel, note, self.time\n )\n if not self.playing:\n break\n if not self.loop or not self.playing:\n break\n finally:\n self.current_point = None\n self.playing = False\n\n @on_trait_change('voice.instrument, voice.channel')\n def _voice_changed(self):\n self.backend.program_change(\n self.voice.channel,\n self.voice.instrument,\n self.backend.time(),\n )\n\n\nclass VoicePlayer(Player):\n \"\"\"\n Player for playing back a L{Voice}.\n \"\"\"\n\n track = Instance(Track)\n \"\"\"The L{track} the voice belongs to.\"\"\"\n\n voice = Instance(Voice)\n \"\"\"The played back L{Voice}.\"\"\"\n\n _current_node = Instance(PhraseNode)\n \"\"\"\n The L{PhraseNode} currently played back. This is only to be used\n internally in the player module and you should not bind any trait\n notification handlers to this, for this will hurt performance in that\n transitions between nodes will sound sloppy.\n Use L{VoicePlayer.current_node} instead.\n \"\"\"\n\n current_node = Instance(PhraseNode)\n \"\"\"\n The L{PhraseNode} to be displayed by viewers etc.\n This is set to L{VoicePlayer._current_node} just after the first note of\n the new node is beginning to play, to give notification handlers some\n time to do their (usually slow) GUI updates.\n \"\"\"\n\n phrase_player = Instance(PhrasePlayer)\n \"\"\"\n The L{PhrasePlayer} used to play back phrases.\n \"\"\"\n\n time = DelegatesTo('phrase_player')\n\n def _phrase_player_default(self):\n return PhrasePlayer(self.backend, voice=self.voice)\n\n def stop(self):\n super(VoicePlayer, self).stop()\n self.phrase_player.stop()\n\n def iter(self):\n phrase_player = self.phrase_player\n # Start with the voice's start node. This will also set the phrase\n # player's phrase to the node's phrase.\n self._current_node = self.voice.start_node\n phrase_player.play()\n while True:\n # Wait until there is a phrase to be played back\n if phrase_player.phrase is None:\n yield None\n # Exit the loop if the voice player has been stopped\n if not self.playing:\n break\n continue\n try:\n yield phrase_player.play_iter.next()\n except StopIteration:\n # The phrase player has finished its phrase or was stopped.\n\n # Exit the loop if the voice player has been stopped.\n if not self.playing:\n break\n\n # Choose the next phrase transition.\n transition = choose_transition(\n *self.track.get_voice_transition_weights(\n self._current_node, 'Phrase', self.voice\n )\n )\n if transition is None:\n # If there is no transition for the current voice,\n # try to get a transition for all voices.\n transition = choose_transition(\n *self.track.get_voice_transition_weights(\n self._current_node, 'Phrase', None\n )\n )\n if transition is None:\n next_node = None\n else:\n # Set the node to be played back next. This will also set\n # the phrase player's phrase to the new node's phrase.\n next_node = transition.target_node\n self._current_node = next_node\n phrase_player.play()\n if next_node is None or next_node.phrase is None:\n # If there is no phrase to be played, update the\n # externally visible node attribute immediately for we\n # don't have a chance to do so later on (the else-branch\n # below will not be reached in this case).\n self.current_node = next_node\n else:\n # Check if the node has been changed, so we can now tell\n # observers to do their stuff while the first note of the\n # new node is already being played.\n if self.current_node is not self._current_node:\n self.current_node = self._current_node\n phrase_player.current_point = None\n self._current_node = None\n self.current_node = None\n self.time = -1\n\n @on_trait_change('_current_node.transpose')\n def _transpost_changed(self):\n if self._current_node is not None:\n self.phrase_player.transpose = self._current_node.transpose\n\n @on_trait_change('_current_node.phrase')\n def _phrase_changed(self):\n if self._current_node is None:\n self.phrase_player.phrase = None\n else:\n self.phrase_player.phrase = self._current_node.phrase\n\n @on_trait_change('voice')\n def _voice_changed(self):\n self.phrase_player.voice = self.voice\n\n @on_trait_change('playing')\n def _playing_changed(self):\n self.phrase_player.playing = self.playing\n\n @on_trait_change('track.tempo')\n def _tempo_changed(self):\n self.phrase_player.tempo = self.track.tempo\n\n\nclass TrackPlayer(Player):\n \"\"\"\n Player to play back a L{Track}.\n \"\"\"\n\n track = Instance(Track)\n \"\"\"The played back L{Track}.\"\"\"\n\n voice_players = Dict(Voice, VoicePlayer)\n \"\"\"The players for playing back the L{Voice}s of the L{Track}.\"\"\"\n\n def stop(self):\n super(TrackPlayer, self).stop()\n for voice_player in self.voice_players.itervalues():\n voice_player.stop()\n\n def iter(self):\n self.voice_players = {}\n time = self.backend.time()\n for voice in self.track.voices:\n voice_player = VoicePlayer(\n self.backend, voice=voice, track=self.track, time=time,\n )\n voice_player.play()\n self.voice_players[voice] = voice_player\n stopped_voices = set()\n while self.voice_players:\n for voice, voice_player in self.voice_players.iteritems():\n try:\n yield voice_player.play_iter.next()\n except StopIteration:\n stopped_voices.add(voice)\n if stopped_voices:\n for voice in stopped_voices:\n del self.voice_players[voice]\n stopped_voices.clear()\n\n @on_trait_change('playing')\n def _playing_changed(self):\n for voice_player in self.voice_players.itervalues():\n voice_player.playing = self.playing\n\n @on_trait_change('voice_players:_current_node')\n def _on_node_change(self, voice_player, name, old, new):\n if old is None or new is None:\n # only trigger other voices when moving to a different node\n return\n node = voice_player._current_node\n voice_players = self.voice_players\n for voice, weight_sum, transition_weights in (\n self.track.get_transition_weights(node, 'Trigger')\n ):\n if voice is voice_player.voice:\n # Do not let voices trigger themselves.\n continue\n transition = choose_transition(weight_sum, transition_weights)\n target_voice_player = voice_players[voice]\n if node is transition.target_node:\n target_voice_player._current_node = None\n target_voice_player._current_node = transition.target_node\n target_voice_player.time = voice_player.time\n target_voice_player.phrase_player.play()\n\n","sub_path":"src/gambolputty/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":17803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"199624595","text":"\"\"\"\n Copyright (c) 2018 Intel Corporation\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 http://www.apache.org/licenses/LICENSE-2.0\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 os.path as osp\n\nimport cv2 as cv\nfrom tqdm import tqdm\nfrom torch.utils.data import Dataset\n\nfrom utils.face_align import FivePointsAligner\n\n\nclass MSCeleb1M(Dataset):\n \"\"\"MSCeleb1M Dataset compatible with PyTorch DataLoader.\"\"\"\n def __init__(self, images_root_path, image_list_path, transform=None):\n self.image_list_path = image_list_path\n self.images_root_path = images_root_path\n self.identities = {}\n\n assert osp.isfile(image_list_path)\n self.have_landmarks = True\n\n self.all_samples_info = self._read_samples_info()\n self.samples_info = self.all_samples_info\n self.transform = transform\n\n def _read_samples_info(self):\n \"\"\"Reads annotation of the dataset\"\"\"\n samples = []\n\n with open(self.image_list_path, 'r') as f:\n images_file_lines = f.readlines()\n last_class_id = -1\n\n for i in tqdm(range(len(images_file_lines))):\n line = images_file_lines[i]\n terms = line.split('|')\n if len(terms) < 3:\n continue # FD has failed on this imsage\n path, landmarks, bbox = terms\n image_id, _ = path.split('/')\n\n if image_id in self.identities:\n self.identities[image_id].append(len(samples))\n else:\n last_class_id += 1\n self.identities[image_id] = [len(samples)]\n\n bbox = [max(int(coord), 0) for coord in bbox.strip().split(' ')]\n landmarks = [float(coord) for coord in landmarks.strip().split(' ')]\n assert len(bbox) == 4\n assert len(landmarks) == 10\n samples.append((osp.join(self.images_root_path, path).strip(),\n last_class_id, image_id, bbox, landmarks))\n\n return samples\n\n def get_weights(self):\n \"\"\"Computes weights of the each identity in dataset according to frequency of it's occurance\"\"\"\n weights = [0.]*len(self.all_samples_info)\n for i, sample in enumerate(self.all_samples_info):\n weights[i] = float(len(self.all_samples_info)) / len(self.identities[sample[2]])\n return weights\n\n def get_num_classes(self):\n \"\"\"Returns total number of identities\"\"\"\n return len(self.identities)\n\n def __len__(self):\n \"\"\"Returns total number of samples\"\"\"\n return len(self.samples_info)\n\n def __getitem__(self, idx):\n \"\"\"Returns sample (image, class id, image id) by index\"\"\"\n img = cv.imread(self.samples_info[idx][0], cv.IMREAD_COLOR)\n bbox = self.samples_info[idx][-2]\n landmarks = self.samples_info[idx][-1]\n\n img = img[bbox[1]:bbox[1] + bbox[3], bbox[0]:bbox[0] + bbox[2]]\n img = FivePointsAligner.align(img, landmarks, d_size=(200, 200), normalized=True, show=False)\n\n if self.transform:\n img = self.transform(img)\n\n return {'img': img, 'label': self.samples_info[idx][1], 'instance': self.samples_info[idx][2]}\n","sub_path":"datasets/ms_celeb1m.py","file_name":"ms_celeb1m.py","file_ext":"py","file_size_in_byte":3652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"595219402","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2016-05-18 14:43:49\n# @Author : moling (365024424@qq.com)\n# @Link : #\nimport os\nfrom datetime import datetime\nfrom fabric.api import *\n\n_REMOTE_BASE_DIR = '/home/ubuntu/mblog'\n_TAR_FILE = 'dist-mblog.tar.gz'\n_REMOTE_TMP_TAR = '/tmp/%s' % _TAR_FILE\n\nenv.hosts = ['119.29.191.109']\nenv.user = 'ubuntu'\nenv.password = '******'\nenv.key_filename = 'D:\\\\tk'\n\n\ndef _now():\n return datetime.now().strftime('%y-%m-%d_%H:%M:%S')\n\n\ndef build():\n includes = ['app', 'config', '*.py']\n excludes = ['__pycache__', '*.pyc', '*.pyo', 'orm_test.*']\n local('rm -f dist/%s' % _TAR_FILE)\n with lcd(os.path.join(os.path.abspath('.'), 'www')):\n cmd = ['tar', '--dereference', '-czvf', '../dist/%s' % _TAR_FILE]\n cmd.extend(['--exclude=\\'%s\\'' % ex for ex in excludes])\n cmd.extend(includes)\n local(' '.join(cmd))\n\n\ndef deploy():\n newdir = 'www-%s' % _now()\n sudo('rm -f %s' % _REMOTE_TMP_TAR)\n put('dist/%s' % _TAR_FILE, _REMOTE_TMP_TAR)\n with cd(_REMOTE_BASE_DIR):\n sudo('mkdir %s' % newdir)\n with cd('%s/%s' % (_REMOTE_BASE_DIR, newdir)):\n sudo('tar -xzvf %s' % _REMOTE_TMP_TAR)\n with cd(_REMOTE_BASE_DIR):\n sudo('rm -f www')\n sudo('ln -s %s www' % newdir)\n sudo('chown www-data:www-data www')\n sudo('chown -R www-data:www-data %s' % newdir)\n with settings(warn_only=True):\n sudo('supervisorctl restart mblog')\n sudo('service nginx restart')\n\n\ndef go():\n build()\n deploy()\n","sub_path":"fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"160878384","text":"import os\nfrom utils import config, DashDebug\nimport dash\nimport dash_bootstrap_components as dbc\n\nflask_options = config.get('flask')\n\nDASH_DEBUG = 'DASH_DEBUG' in os.environ\n\n_app_create = DashDebug if DASH_DEBUG else dash.Dash\n\napp = _app_create(__name__,\n suppress_callback_exceptions=True,\n external_stylesheets=[\n dbc.themes.BOOTSTRAP,\n 'https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css'\n ])\n\napp.scripts.config.serve_locally = True\napp.css.config.serve_locally = True\napp.server.config['SECRET_KEY'] = flask_options.secret_key\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"601552113","text":"\"\"\"Create a game where the computer picks a random word and\nthe player has to guess that word. The computer tells the\nplayer how many letters are in the word. Then the player gets\nfive chances to ask if a letter is in the word. The computer can\nonly respond with “yes” or “no”. Then, the player must guess\nthe word.\"\"\"\nimport random\n\nwords = ('Lenny','Pekka','Cardinal','Text','Right','Answer','Birthplace','Garage','Dude', 'Hello', 'Dog', 'Cat')\nword = random.choice(words)\nprint ('Words length is '+str(len(word))+' letters.')\n","sub_path":"word_guess_game.py","file_name":"word_guess_game.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"207199359","text":"# global\nimport ivy\nimport math\nimport numpy as np\n\n\ndef sinusoid_positional_encoding(x, embedding_length=10):\n \"\"\"\n Perform sinusoid positional encoding of the inputs.\n\n :param x: input array to encode *[batch_shape, dim]*\n :type x: array\n :param embedding_length: Length of the embedding. Default is 10.\n :type embedding_length: int, optional\n :return: The new positionally encoded array *[batch_shape, dim+dim*2*embedding_length]*\n \"\"\"\n rets = [x]\n for i in range(embedding_length):\n for fn in [ivy.sin, ivy.cos]:\n rets.append(fn(2.**i * x))\n return ivy.concatenate(rets, -1)\n\n\n# noinspection PyUnresolvedReferences\ndef sampled_volume_density_to_occupancy_probability(density, inter_sample_distance):\n \"\"\"\n Compute probability of occupancy, given sampled volume densities and their associated inter-sample distances\n\n :param density: The sampled density values *[batch_shape]*\n :type density: array\n :param inter_sample_distance: The inter-sample distances *[batch_shape]*\n :type inter_sample_distance: array\n :return: The occupancy probabilities *[batch_shape]*\n \"\"\"\n return 1 - ivy.exp(-density*inter_sample_distance)\n\n\ndef ray_termination_probabilities(density, inter_sample_distance):\n \"\"\"\n Compute probability of occupancy, given sampled volume densities and their associated inter-sample distances\n\n :param density: The sampled density values *[batch_shape,num_samples_per_ray]*\n :type density: array\n :param inter_sample_distance: The inter-sample distances *[batch_shape,num_samples_per_ray]*\n :type inter_sample_distance: array\n :return: The occupancy probabilities *[batch_shape]*\n \"\"\"\n\n # BS x NSPR\n occ_prob = sampled_volume_density_to_occupancy_probability(density, inter_sample_distance)\n return occ_prob * ivy.cumprod(1. - occ_prob + 1e-10, -1, exclusive=True)\n\n\n# noinspection PyUnresolvedReferences\ndef stratified_sample(starts, ends, num_samples, batch_shape=None):\n \"\"\"\n Perform stratified sampling, between start and end arrays. This operation divides the range into equidistant bins,\n and uniformly samples value within the ranges for each of these bins.\n\n :param starts: Start values *[batch_shape]*\n :type starts: array\n :param ends: End values *[batch_shape]*\n :type ends: array\n :param num_samples: The number of samples to generate between starts and ends\n :type num_samples: int\n :param batch_shape: Shape of batch, Inferred from inputs if None.\n :type batch_shape: sequence of ints, optional\n :return: The stratified samples, with each randomly placed in uniformly spaced bins *[batch_shape,num_samples]*\n \"\"\"\n\n # shapes\n if batch_shape is None:\n batch_shape = starts.shape\n\n # shapes as lists\n batch_shape = list(batch_shape)\n\n # BS\n bin_sizes = (ends - starts)/num_samples\n\n # BS x NS\n linspace_vals = ivy.linspace(starts, ends - bin_sizes, num_samples)\n\n # BS x NS\n random_uniform = ivy.random_uniform(shape=batch_shape + [num_samples], dev_str=ivy.dev_str(starts))\n\n # BS x NS\n random_offsets = random_uniform * ivy.expand_dims(bin_sizes, -1)\n\n # BS x NS\n return linspace_vals + random_offsets\n\n\n# noinspection PyUnresolvedReferences\ndef render_rays_via_termination_probabilities(ray_term_probs, features, render_variance=False):\n \"\"\"\n Render features onto the image plane, given rays sampled at radial depths with readings of\n feature values and densities at these sample points.\n\n :param ray_term_probs: The ray termination probabilities *[batch_shape,num_samples_per_ray]*\n :type ray_term_probs: array\n :param features: Feature values at the sample points *[batch_shape,num_samples_per_ray,feat_dim]*\n :type features: array\n :param render_variance: Whether to also render the feature variance. Default is False.\n :type render_variance: bool, optional\n :return: The feature renderings along the rays, computed via the termination probabilities *[batch_shape,feat_dim]*\n \"\"\"\n\n # BS x NSPR\n rendering = ivy.reduce_sum(ivy.expand_dims(ray_term_probs, -1) * features, -2)\n if not render_variance:\n return rendering\n var = ivy.reduce_sum(ray_term_probs*(ivy.expand_dims(rendering, -2) - features)**2, -2)\n return rendering, var\n\n\ndef render_implicit_features_and_depth(network_fn, rays_o, rays_d, near, far, samples_per_ray, render_variance=False,\n batch_size_per_query=512*64, inter_feat_fn=None, v=None):\n \"\"\"\n Render an rgb-d image, given an implicit rgb and density function conditioned on xyz data.\n\n :param network_fn: the implicit function.\n :type network_fn: callable\n :param rays_o: The camera center *[batch_shape,3]*\n :type rays_o: array\n :param rays_d: The rays in world space *[batch_shape,ray_batch_shape,3]*\n :type rays_d: array\n :param near: The near clipping plane values *[batch_shape,ray_batch_shape]*\n :type near: array\n :param far: The far clipping plane values *[batch_shape,ray_batch_shape]*\n :type far: array\n :param samples_per_ray: The number of stratified samples to use along each ray\n :type samples_per_ray: int\n :param render_variance: Whether to also render the feature variance. Default is False.\n :type render_variance: bool, optional\n :param batch_size_per_query: The maximum batch size for querying the implicit network. Default is 1024.\n :type batch_size_per_query: int, optional\n :param inter_feat_fn: Function to extract interpolated features from world-coords *[batch_shape,ray_batch_shape,3]*\n :type inter_feat_fn: callable, optional\n :param v: The container of trainable variables for the implicit model. default is to use internal variables.\n :type v: ivy Container of variables\n :return: The rendered feature *[batch_shape,ray_batch_shape,feat]* and depth *[batch_shape,ray_batch_shape,1]* values\n \"\"\"\n\n # shapes\n batch_shape = list(near.shape)\n flat_batch_size = np.prod(batch_shape)\n num_sections = math.ceil(flat_batch_size*samples_per_ray/batch_size_per_query)\n\n # Compute 3D query points\n\n # BS x SPR x 1\n z_vals = ivy.expand_dims(stratified_sample(near, far, samples_per_ray), -1)\n\n # BS x 1 x 3\n rays_d = ivy.expand_dims(rays_d, -2)\n rays_o = ivy.broadcast_to(rays_o, rays_d.shape)\n\n # BS x SPR x 3\n pts = rays_o + rays_d * z_vals\n\n # (BSxSPR) x 3\n pts_flat = ivy.reshape(pts, (flat_batch_size*samples_per_ray, 3))\n\n # batch\n # ToDo: use a more general batchify function, from ivy core\n\n # num_sections size list of BSPQ x 3\n pts_split = [pts_flat[i*batch_size_per_query:min((i+1)*batch_size_per_query, flat_batch_size*samples_per_ray)]\n for i in range(num_sections)]\n if inter_feat_fn is not None:\n # (BSxSPR) x IF\n features = ivy.reshape(inter_feat_fn(pts), (flat_batch_size*samples_per_ray, -1))\n # num_sections size list of BSPQ x IF\n feats_split =\\\n [features[i * batch_size_per_query:min((i + 1) * batch_size_per_query, flat_batch_size*samples_per_ray)]\n for i in range(num_sections)]\n else:\n feats_split = [None]*num_sections\n\n # Run network\n\n # num_sections size list of tuple of (BSPQ x OF, BSPQ)\n feats_n_densities = [network_fn(pt, f, v=v) for pt, f in zip(pts_split, feats_split)]\n\n # BS x SPR x OF\n feat = ivy.reshape(ivy.concatenate([item[0] for item in feats_n_densities], 0),\n batch_shape + [samples_per_ray, -1])\n\n # FBS x SPR\n densities = ivy.reshape(ivy.concatenate([item[1] for item in feats_n_densities], 0),\n batch_shape + [samples_per_ray])\n\n # BS x (SPR+1)\n z_vals_w_terminal = ivy.concatenate((z_vals[..., 0], ivy.ones_like(z_vals[..., -1:, 0])*1e10), -1)\n\n # BS x SPR\n depth_diffs = z_vals_w_terminal[..., 1:] - z_vals_w_terminal[..., :-1]\n ray_term_probs = ray_termination_probabilities(densities, depth_diffs)\n\n # BS x OF\n feat = ivy.clip(render_rays_via_termination_probabilities(ray_term_probs, feat, render_variance), 0., 1.)\n\n # BS x 1\n depth = render_rays_via_termination_probabilities(ray_term_probs, z_vals, render_variance)\n if render_variance:\n # BS x OF, BS x OF, BS x 1, BS x 1\n return feat[0], feat[1], depth[0], depth[1]\n # BS x OF, BS x 1\n return feat, depth\n","sub_path":"ivy_vision/implicit.py","file_name":"implicit.py","file_ext":"py","file_size_in_byte":8401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"585688131","text":"#!/usr/bin/env python\n# coding: utf8\n\"\"\"\nTango device server for setting up pyFAI azimuthal integrator in a LImA ProcessLib.\n\nDestination path:\nLima/tango/plugins/DistortionCorrection \n\"\"\"\n__author__ = \"Jérôme Kieffer\"\n__contact__ = \"Jerome.Kieffer@ESRF.eu\"\n__license__ = \"GPLv3+\"\n__copyright__ = \"European Synchrotron Radiation Facility, Grenoble, France\"\n__date__ = \"25/02/2013\"\n__status__ = \"beta\"\n__docformat__ = 'restructuredtext'\n\nimport os\nimport sys\nimport threading\nimport logging\nlogger = logging.getLogger(\"lima.tango.pyfai\")\n# set loglevel at least at INFO\nif logger.getEffectiveLevel() > logging.INFO:\n logger.setLevel(logging.INFO)\nimport pyFAI, pyFAI._distortion\ntry:\n from pyFAI.fastcrc import crc32\nexcept ImportError:\n from zlib import crc32\n\nimport fabio\ntry:\n import pyopencl\n import pyFAI.ocl_azim_lut\nexcept ImportError:\n pyopencl = None\n logger.warning(\"Unable to import pyopencl, will use OpenMP (if available)\")\nimport PyTango\nfrom os.path import dirname\ncwd = dirname(dirname(dirname(os.path.abspath(__file__))))\nsys.path.append(os.path.join(cwd, \"build\", \"lib.linux-x86_64-2.6\"))\nimport numpy\nfrom Lima import Core\nfrom Utils import BasePostProcess\n\nclass PyFAISink(Core.Processlib.SinkTaskBase):\n \"\"\"\n This is a processlib Sink: it takes an image as input and writes a file to disk but returns nothing\n \"\"\"\n def __init__(self, splinefile=None, darkfile=None, flatfile=None, extraheader=None):\n \"\"\"\n @param splinefile: File with the description of the distortion as a cubic spline\n @param darkfile: image with the dark current\n @param flatfile: image with the flat field correction \n @param extraheader: dictionary with additional static header for EDF files \n \"\"\"\n Core.Processlib.SinkTaskBase.__init__(self)\n\n self._sem = threading.Semaphore()\n if extraheader:\n self.header = extraheader\n else:\n self.header = {}\n self.splinefile = self.dis = self.det = self.ocl_integrator = None\n self.darkfile = self.darkcurrent = self.darkcurrent_crc = None\n self.flatfile = self.flatfield = self.flatfield_crc = None\n self.setSplineFile(splinefile)\n self.setDarkcurrentFile(darkfile)\n self.setFlatfieldFile(flatfile)\n\n def process(self, data) :\n \"\"\"\n Process a frame\n @param data: a LImA frame with member .buffer (a numpy array) and .frameNumber (an int)\n \"\"\"\n ctControl = _control_ref()\n saving = ctControl.saving()\n sav_parms = saving.getParameters()\n directory = sav_parms.directory\n prefix = sav_parms.prefix\n nextNumber = sav_parms.nextNumber\n indexFormat = sav_parms.indexFormat\n output = os.path.join(directory, prefix + indexFormat % (nextNumber + data.frameNumber) + \".cor.edf\")\n header = self.header.copy()\n header[\"index\"] = nextNumber + data.frameNumber\n if pyopencl and self.ocl_integrator:\n out = self.ocl_integrator.integrate(data.buffer, dark=self.darkcurrent, flat=self.flatfield,\n dark_checksum=self.darkcurrent_crc, flat_checksum=self.flatfield_crc)[1]\n else:\n data = numpy.ascontiguousarray(data.buffer, dtype=numpy.float32)\n if self.darkcurrent is not None:\n data -= self.darkcurrent\n if self.flatfield is not None:\n data /= self.flatfield\n if self.dis:\n out = self.dis.correct(data)\n else:\n out = data\n edf = fabio.edfimage.edfimage(data=out, header=header)\n edf.write(output)\n\n\n\n def setDarkcurrentFile(self, imagefile):\n \"\"\"\n @param imagefile: filename with the path to the dark image\n \"\"\"\n with self._sem:\n if imagefile:\n self.darkfile = imagefile\n try:\n self.darkcurrent = numpy.ascontiguousarray(fabio.open(imagefile).data, numpy.float32)\n except Exception as error:\n logger.warning(\"setDarkcurrentFile: Unable to read file %s: %s\" % (imagefile, error))\n else:\n self.darkcurrent_crc = crc32(self.darkcurrent)\n self.header[\"darkcurrent\"] = imagefile\n else:\n self.darkfile = self.darkcurrent = self.darkcurrent_crc = None\n self.header[\"darkcurrent\"] = \"None\"\n\n def setFlatfieldFile(self, imagefile):\n \"\"\"\n @param imagefile: filename with the path to the flatfield image\n \"\"\"\n with self._sem:\n if imagefile:\n self.flatfile = imagefile\n try:\n self.flatfield = numpy.ascontiguousarray(fabio.open(imagefile).data, numpy.float32)\n except Exception as error:\n logger.warning(\"setFlatfieldFile: Unable to read file %s: %s\" % (imagefile, error))\n else:\n self.flatfield_crc = crc32(self.flatfield)\n self.header[\"flatfield\"] = imagefile\n else:\n self.flatfile = self.flatfield = self.flatfield_crc = None\n self.header[\"flatfield\"] = \"None\"\n\n def setSplineFile(self, splineFile):\n \"\"\"\n @param imagefile: filename with the path to the spline distortion file\n \"\"\"\n with self._sem:\n if not splineFile or not os.path.exists(str(splineFile)):\n self.splinefile = None\n self.det = None\n self.dis = None\n self.header[\"splinefile\"] = \"None\"\n else:\n logger.info(\"start config ...\")\n self.det = pyFAI.detectors.FReLoN(splineFile)\n self.dis = pyFAI._distortion.Distortion(self.det)\n self.reset()\n self.header[\"splinefile\"] = splineFile\n\n def calc_LUT(self):\n \"\"\"\n This is the \"slow\" calculation of the Look-up table that can be spown in another thread \n (especially to avoid Tango from timing out) \n \"\"\"\n with self._sem:\n if self.dis:\n self.dis.calc_LUT_size()\n self.dis.calc_LUT()\n if pyopencl:\n self.ocl_integrator = pyFAI.ocl_azim_lut.OCL_LUT_Integrator(self.dis.LUT, self.dis.shape[0] * self.dis.shape[1])\n else:\n self.splinefile = None\n self.det = None\n self.dis = None\n self.header[\"splinefile\"] = \"None\"\n\n def reset(self):\n \"\"\"\n Recalculate the lookup table in another thread\n \"\"\"\n threading.Thread(target=self.calc_LUT, name=\"calc_LUT\").start()\n\n\nclass DistortionCorrectionDeviceServer(BasePostProcess) :\n \"\"\"\n Tango device server exposed to configure the LImA plugin\n \"\"\"\n DISTORTION_TASK_NAME = 'DistortionCorrectionTask'\n Core.DEB_CLASS(Core.DebModApplication, 'DistortionCorrection')\n def __init__(self, cl, name):\n self.__Task = None\n self.get_device_properties(self.get_device_class())\n BasePostProcess.__init__(self, cl, name)\n DistortionCorrectionDeviceServer.init_device(self)\n\n self.__spline_filename = None\n self.__darkcurrent_filename = None\n self.__flatfield_filename = None\n self.__pyFAISink = None\n\n def set_state(self, state) :\n \"\"\"\n Switch on or off the LImA plugin\n \"\"\"\n if(state == PyTango.DevState.OFF) :\n if (self.__Task):\n self.__Task = None\n ctControl = _control_ref()\n extOpt = ctControl.externalOperation()\n extOpt.delOp(self.DISTORTION_TASK_NAME)\n elif(state == PyTango.DevState.ON) :\n if not self.__Task:\n try:\n ctControl = _control_ref()\n extOpt = ctControl.externalOperation()\n self.__Task = extOpt.addOp(Core.USER_SINK_TASK,\n self.DISTORTION_TASK_NAME,\n self._runLevel)\n if not self.__pyFAISink:\n self.__pyFAISink = PyFAISink(splinefile=self.__spline_filename,\n darkfile=self.__darkcurrent_filename,\n flatfile=self.__flatfield_filename)\n self.__Task.setSinkTask(self.__pyFAISink)\n except:\n import traceback\n traceback.print_exc()\n return\n PyTango.Device_4Impl.set_state(self, state)\n\n def setDarkcurrentFile(self, filepath):\n \"\"\"\n @param imagefile: filename with the path to the dark image\n \"\"\"\n\n self.__darkcurrent_filename = filepath\n if(self.__pyFAISink) :\n self.__pyFAISink.setBackgroundFile(filepath)\n\n def setFlatfieldImage(self, filepath):\n \"\"\"\n @param filepath: filename with the path to the flatfield image\n \"\"\"\n self.__flatfield_filename = filepath\n if(self.__pyFAISink) :\n self.__pyFAISink.setFlatfieldFile(filepath)\n\n def setSplineFile(self, filepath):\n \"\"\"\n @param filepath: filename with the path to the spline distortion file\n \"\"\"\n\n self.__spline_filename = filepath\n if(self.__pyFAISink) :\n self.__pyFAISink.setSplineFile(filepath)\n\n def Reset(self) :\n \"\"\"\n Force the reinitialization\n \"\"\"\n self.__pyFAISink = PyFAISink(splinefile=self.__spline_filename,\n darkfile=self.__darkcurrent_filename,\n flatfile=self.__flatfield_filename)\n self.__Task.setSinkTask(self.__pyFAISink)\n\n\nclass DistortionCorrectionDeviceServerClass(PyTango.DeviceClass) :\n # Class Properties\n class_property_list = {\n }\n\n\n # Device Properties\n device_property_list = {\n }\n\n\n # Command definitions\n cmd_list = {\n 'setDarkcurrentFile':\n [[PyTango.DevString, \"Full path of darkcurrent image file\"],\n [PyTango.DevVoid, \"\"]],\n\n 'setFlatfieldImage':\n [[PyTango.DevString, \"Full path of flatfield image file\"],\n [PyTango.DevVoid, \"\"]],\n\n 'setSplineFile':\n [[PyTango.DevString, \"Full path of spline distortion file\"],\n [PyTango.DevVoid, \"\"]],\n\n 'Start':\n [[PyTango.DevVoid, \"\"],\n [PyTango.DevVoid, \"\"]],\n 'Stop':\n [[PyTango.DevVoid, \"\"],\n [PyTango.DevVoid, \"\"]],\n 'Reset':\n [[PyTango.DevVoid, \"\"],\n [PyTango.DevVoid, \"\"]],\n }\n\n\n # Attribute definitions\n attr_list = {\n 'RunLevel':\n [[PyTango.DevLong,\n PyTango.SCALAR,\n PyTango.READ_WRITE]],\n# 'delete_dark_after_read':\n# [[PyTango.DevBoolean,\n# PyTango.SCALAR,\n# PyTango.READ_WRITE]],\n }\n#------------------------------------------------------------------\n# AzimuthalIntegratorDeviceServerClass Constructor\n#------------------------------------------------------------------\n def __init__(self, name):\n PyTango.DeviceClass.__init__(self, name)\n self.set_type(name)\n\n_control_ref = None\ndef set_control_ref(control_class_ref):\n global _control_ref\n _control_ref = control_class_ref\n\ndef get_tango_specific_class_n_device() :\n return DistortionCorrectionDeviceServerClass, DistortionCorrectionDeviceServer\n","sub_path":"plugins/Lima/DistortionCorrection.py","file_name":"DistortionCorrection.py","file_ext":"py","file_size_in_byte":11688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"238055413","text":"import datetime, os\nimport pymysql.cursors\n\nclass Importer():\n '''\n\n '''\n\n def __init__(self):\n # Connect to the database\n self.connection = pymysql.connect(host='localhost',\n user=os.environ['MYSQL_USER'],\n password=os.environ['MYSQL_USER_PASSWD'],\n #db='xbrl',\n db='xbrl-django',\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor)\n\n def table_clear(self):\n with self.connection.cursor() as cusor:\n sql = \"DELETE from reports_company\"\n cusor.execute(sql)\n sql = \"DELETE from reports_report\"\n cusor.execute(sql)\n self.connection.commit()\n\n\n def import_dei_to_mysql(self, jpcrp):\n with self.connection.cursor() as cursor:\n sql = \"REPLACE into reports_company ( edinet_code, \\\n company_name, \\\n english_company_name, \\\n security_code) VALUES(%s,%s,%s,%s)\"\n cursor.execute(sql, (jpcrp.dei.edinet_code,\n jpcrp.dei.company_name,\n jpcrp.dei.english_company_name,\n jpcrp.dei.security_code))\n self.connection.commit()\n\n def count_company(self):\n with self.connection.cursor() as cusor:\n sql = \"select count(*) from reports_company\"\n cusor.execute(sql)\n result = cusor.fetchone()\n count = result['count(*)']\n return count\n\n def import_report_to_mysql(self, jpcrp):\n with self.connection.cursor() as cursor:\n sql = \"REPLACE into reports_report (\\\n edinet_code,\\\n year,\\\n per,\\\n roe,\\\n eps,\\\n equity_to_asset_ratio,\\\n pay_out_ratio,\\\n net_sales,\\\n net_assets,\\\n total_assets,\\\n liabilities,\\\n operating_revenue,\\\n ordinary_revenue,\\\n profit_before_tax,\\\n owners_equity_per_share,\\\n cash_and_cash_equivalents,\\\n cash_flow_from_operating,\\\n cash_flow_from_investing,\\\n cash_flow_from_financing,\\\n type_of_current_period,\\\n accounting_standard,\\\n whether_consolidated_financial_statements,\\\n current_fiscal_year_start_date,\\\n current_fiscal_year_end_date)\\\n VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,\\\n %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,\\\n %s,%s,%s,%s)\"\n\n cursor.execute(sql,(\n jpcrp.dei.edinet_code,\n jpcrp.get_current_fiscal_year(),\n jpcrp.per,\n jpcrp.roe,\n jpcrp.eps,\n jpcrp.equity_to_asset_ratio,\n jpcrp.pay_out_ratio,\n jpcrp.net_sales,\n jpcrp.net_assets,\n jpcrp.total_assets,\n jpcrp.liabilities,\n jpcrp.operating_revenue,\n jpcrp.ordinary_revenue,\n jpcrp.profit_before_tax,\n jpcrp.owners_equity_per_share,\n jpcrp.cash_and_cash_equivalents,\n jpcrp.cash_flow_from_operating,\n jpcrp.cash_flow_from_investing,\n jpcrp.cash_flow_from_financing,\n jpcrp.dei.type_of_current_period,\n jpcrp.dei.accounting_standard,\n jpcrp.dei.whether_consolidated_financial_statements,\n jpcrp.get_current_fiscal_year_start_date(),\n jpcrp.get_current_fiscal_year_end_date(),\n\n ))\n self.connection.commit()\n\n def count_report(self):\n with self.connection.cursor() as cusor:\n sql = \"select count(*) from reports_report\"\n cusor.execute(sql)\n result = cusor.fetchone()\n count = result['count(*)']\n return count\n","sub_path":"edinetxbrl/importer.py","file_name":"importer.py","file_ext":"py","file_size_in_byte":4152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"225995932","text":"\"\"\"\nTests for db/sqlite_db.py\n\"\"\"\nfrom . import *\n\nimport sqlite3\n\nimport db.sqlite_db as _\n\n\nclass TestModuleSqliteDb(TestModule):\n def test_all_statement(self):\n expected = [\"Database\", \"Connection\"]\n self.assertAllSpecifiedProperly(expected, _.__all__)\n\n\nclass TestDatabase(unittest.TestCase):\n def test_init(self):\n db = _.Database(':memory:')\n self.assertIsInstance(db, _.Database)\n\n def test_repr(self):\n path = 'foo'\n db = _.Database(path)\n expected = [\"Database(\" + q + path + q + \")\" for q in (\"'\", '\"')]\n self.assertIn(repr(db), expected)\n\n def test_path(self):\n path = ':memory:'\n db = _.Database(path)\n self.assertEqual(path, db.path)\n\n def test_connect(self):\n db = _.Database(':memory:')\n with db.connect() as c:\n self.assertIsInstance(c, _.Connection)\n self.assertIsInstance(c, sqlite3.Connection)\n\n\ndef iter_cocktails_ingredients(foo, bar):\n index = 0\n for i in foo:\n for j in bar:\n if j[0] <= i[0]:\n index += 1\n yield(index, i[0], j[0], i[0] + j[0])\n\n\nclass TestConnection(unittest.TestCase):\n insert_cocktail = \"INSERT INTO cocktails VALUES (?, ?, ?)\"\n insert_ingredient = \"INSERT INTO ingredients VALUES (?, ?)\"\n insert_cocktail_ingredient = \"\"\"\n INSERT INTO cocktails_ingredients VALUES (?, ?, ?, ?)\n \"\"\"\n\n cocktails = [(i, 'name' + str(i), 'image' + str(i)) for i in range(10)]\n ingredients = [(i, 'ing' + str(i)) for i in range(10)]\n cocktails_ingredients = list(\n iter_cocktails_ingredients(cocktails, ingredients))\n\n def test_inheritance(self):\n with _.Connection(':memory:') as c:\n self.assertIsInstance(c, _.Connection)\n self.assertIsInstance(c, sqlite3.Connection)\n\n def test_fk_support(self):\n with _.Connection(':memory:') as c:\n fk = c.execute(\"PRAGMA foreign_keys\").fetchone()[0]\n self.assertTrue(fk)\n\n def test_create_tables_if_needed(self):\n tables = \"cocktails ingredients cocktails_ingredients\".split()\n query = \"SELECT name FROM sqlite_master WHERE type='table'\"\n with _.Connection(':memory:') as c:\n c.create_tables_if_needed()\n\n existing_tables_count = 0\n for row in c.execute(query):\n # Check that all expected tables exist\n self.assertIn(row[0], tables)\n existing_tables_count += 1\n # Check that extra tables don't exist\n self.assertEqual(existing_tables_count, len(tables))\n\n def test_select_all_cocktails(self):\n with _.Connection(':memory:') as c:\n args = c, 'cocktails', self.insert_cocktail, self.cocktails\n self._test_select_all_foo(*args)\n\n def test_select_cocktail(self):\n with _.Connection(':memory:') as c:\n args = c, 'cocktail', self.insert_cocktail, self.cocktails\n self._test_select_foo(*args)\n\n def test_select_cocktail_type_checking(self):\n with _.Connection(':memory:') as c:\n with self.assertRaises(TypeError):\n c.select_cocktail('165')\n\n def test_select_all_ingredients(self):\n with _.Connection(':memory:') as c:\n args = c, 'ingredients', self.insert_ingredient, self.ingredients\n self._test_select_all_foo(*args)\n\n def test_select_ingredient(self):\n with _.Connection(':memory:') as c:\n args = c, 'ingredient', self.insert_ingredient, self.ingredients\n self._test_select_foo(*args)\n\n def test_select_ingredient_type_checking(self):\n with _.Connection(':memory:') as c:\n with self.assertRaises(TypeError):\n c.select_ingredient('165')\n\n def test_select_all_cocktails_ingredients(self):\n with _.Connection(':memory:') as c:\n self._test_select_all_foo(\n c,\n 'cocktails_ingredients',\n self.insert_cocktail_ingredient,\n self.cocktails_ingredients\n )\n\n def test_select_cocktail_ingredient(self):\n with _.Connection(':memory:') as c:\n self._test_select_foo(\n c,\n 'cocktail_ingredient',\n self.insert_cocktail_ingredient,\n self.cocktails_ingredients\n )\n\n def test_select_cocktail_ingredient_type_checking(self):\n with _.Connection(':memory:') as c:\n with self.assertRaises(TypeError):\n c.select_cocktail_ingredient('165')\n\n def test_select_ingredients_of_cocktail(self):\n with _.Connection(':memory:') as c:\n c.create_tables_if_needed()\n self._fill_table(c, self.insert_cocktail, self.cocktails)\n self._fill_table(c, self.insert_ingredient, self.ingredients)\n self._fill_table(\n c, self.insert_cocktail_ingredient, self.cocktails_ingredients)\n\n for cocktail in self.cocktails:\n identifier = cocktail[0]\n result = c.select_ingredients_of_cocktail(identifier)\n expected = []\n for ci in self.cocktails_ingredients:\n if ci[1] == identifier:\n ing_id = ci[2]\n part = ci[3]\n for i in self.ingredients:\n if i[0] == ing_id:\n name = i[1]\n row = ing_id, name, part\n expected.append(row)\n self.assertEqual(expected, list(result))\n\n def test_select_ingredients_of_cocktail_type_checking(self):\n with _.Connection(':memory:') as c:\n with self.assertRaises(TypeError):\n c.select_ingredients_of_cocktail('165')\n\n def test_insert_cocktail(self):\n with _.Connection(':memory:') as connection:\n self._test_insert_foo(\n connection,\n 'cocktails',\n self.insert_cocktail,\n self.cocktails,\n )\n\n def test_insert_ingredient(self):\n with _.Connection(':memory:') as connection:\n self._test_insert_foo(\n connection,\n 'ingredients',\n self.insert_ingredient,\n self.ingredients,\n )\n\n def _iter_select_all(self, connection, select_postfix):\n select = getattr(connection, 'select_all_' + select_postfix)\n yield from select()\n\n def _test_insert_foo(self, connection, select_postfix, insert_sql, items):\n connection.create_tables_if_needed()\n\n for item in items:\n cursor = connection.execute(insert_sql, item)\n self.assertEqual(item[0], cursor.lastrowid)\n\n fiends_count = None\n select = self._iter_select_all(connection, select_postfix)\n for expected_row, got_row in zip(items, select):\n if fiends_count is None: # set up once\n fiends_count = len(expected_row)\n\n for i in range(fiends_count):\n self.assertEqual(expected_row[i], got_row[i])\n\n def _fill_table(self, connection, insert_sql, items):\n for item in items:\n connection.execute(insert_sql, item)\n\n def _test_select_all_foo(self, connection, select_postfix, insert_sql,\n items):\n connection.create_tables_if_needed()\n self._fill_table(connection, insert_sql, items)\n\n fiends_count = None\n select = self._iter_select_all(connection, select_postfix)\n for expected_row, got_row in zip(items, select):\n if fiends_count is None: # set up once\n fiends_count = len(expected_row)\n\n for i in range(fiends_count):\n self.assertEqual(expected_row[i], got_row[i])\n\n def _get_select_one_func(self, connection, select_postfix):\n return getattr(connection, 'select_' + select_postfix)\n\n def _test_select_foo(self, connection, select_postfix, insert_sql, items):\n connection.create_tables_if_needed()\n self._fill_table(connection, insert_sql, items)\n\n select = self._get_select_one_func(connection, select_postfix)\n for item in items:\n identifier = item[0]\n row = select(identifier).fetchone()\n self.assertEqual(item, row)\n","sub_path":"tests/test_db_sqlite_db.py","file_name":"test_db_sqlite_db.py","file_ext":"py","file_size_in_byte":8426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"183479477","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Author: Longgeek \n\nimport simplejson as json\n\nfrom fuerte.api.v1.utils import pack_requests\nfrom fuerte.api.v1.config import URL\nfrom fuerte.api.v1.config import HEADERS\n\n\ndef execute(cid, cmds, wait=False):\n \"\"\"在容器中执行命令\n\n :param str cid: The container uuid\n :param list cmds: List of commands to execute\n :param bool wait:\n wait is True 命令将在前台执行,会等待命令执行完成\n wait is False 命令将在后台执行,不等待命令执行完成\n \"\"\"\n\n if type(cmds) != list:\n return (-1, \"cmds needs to be a list type parameter\", \"\")\n\n if wait:\n results = []\n params = {\n \"AttachStdin\": False,\n \"AttachStdout\": True,\n \"AttachStderr\": True,\n \"Tty\": False,\n }\n for c in cmds:\n params[\"Cmd\"] = [\"/bin/sh\", \"-c\", c]\n kwargs = {\n \"url\": URL + \"/containers/%s/exec\" % cid,\n \"headers\": HEADERS,\n \"data\": json.dumps(params)\n }\n r = pack_requests(\"POST\", **kwargs)\n s = r.status_code\n if s != 201:\n return (s, r.text, \"\")\n\n kwargs = {\n \"url\": URL + \"/exec/%s/start\" % r.json()[\"Id\"],\n \"headers\": HEADERS,\n \"data\": json.dumps({\"Tty\": False, \"Detach\": False})\n }\n r = pack_requests(\"POST\", **kwargs)\n s = r.status_code\n results.append(r.text)\n if s != 200:\n return (s, r.text, \"\")\n return (0, \"\", results)\n else:\n params = {\n \"AttachStdout\": False,\n \"AttachStderr\": False,\n \"Tty\": True,\n }\n for c in cmds:\n params[\"Cmd\"] = [\"/bin/sh\", \"-c\", c]\n kwargs = {\n \"url\": URL + \"/containers/%s/exec\" % cid,\n \"headers\": HEADERS,\n \"data\": json.dumps(params)\n }\n r = pack_requests(\"POST\", **kwargs)\n s = r.status_code\n if s != 201:\n return (s, r.text, \"\")\n\n kwargs = {\n \"url\": URL + \"/exec/%s/start\" % r.json()[\"Id\"],\n \"headers\": HEADERS,\n \"data\": json.dumps({\"Tty\": True, \"Detach\": True})\n }\n r = pack_requests(\"POST\", **kwargs)\n s = r.status_code\n if s != 200:\n return (s, r.text, \"\")\n return (0, \"\", \"\")\n","sub_path":"fuerte/api/v1/actions/container/execute.py","file_name":"execute.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"350315424","text":"# Update e Delete de dados \n# Importando modulos necessarios \n\nimport sqlite3 as sql \nimport os \nimport random as rdm\nimport time \nimport datetime as dtm\nimport matplotlib.pyplot as plt\n\n\n# Variaveis Globais \nnomeDB = '/home/ludmylla/Documents/PythonFundamentos/MeusCodigos/cap06/dsaUpdat.db'\nnomeTab = 'CasaNova'\nprodutos = ['fogão', 'geladeira', 'mesa', 'sofa', 'cadeira']\n\n# Validando se ja existe o banco de dados \nif os.path.exists(nomeDB):\n os.remove(nomeDB)\nelse:\n None\n\n# Criando conexão e cursor\ncon = sql.connect(nomeDB)\nc = con.cursor()\n\n# Criando funções para manipulação de dados\ndef criando_tabela(nomeTab):\n c.execute('CREATE TABLE IF NOT EXISTS nomeTab (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,'\\\n 'date TEXT, '\\\n 'prod_name TEXT,'\\\n 'valor REAL)')\n\ndef inserir_dados(nomeTab, produtos):\n c.execute(\"INSERT INTO nomeTab (date,prod_name,valor) VALUES (?, ?, ?)\", (dtm.datetime.now(),produtos,rdm.randrange(50,200)))\n con.commit()\n\ndef lendo_todos_dados(nomeTab):\n c.execute(\"SELECT * FROM nomeTab\")\n for linha in c.fetchall():\n print(linha)\n\ndef lendo_coluna(nomeTab):\n c.execute(\"SELECT * FROM nomeTab\")\n for i in c.fetchall():\n print(i[3])\n\ndef atualizando_doc(nomeTab):\n c.execute(\"UPDATE nomeTab SET valor = 70.00 WHERE valor = 80.00\")\n con.commit()\n\ndef delete_doc(nomeTab):\n c.execute(\"DELETE FROM nomeTab WHERE valor = 70.00\")\n con.commit()\n\n# Função para criação de grafico\ndef criando_graficos(nomeTab):\n c.execute(\"SELECT id, valor FROM nomeTab\")\n ids = []\n valores = []\n dados = c.fetchall()\n for i in dados:\n ids.append(i[0])\n valores.append(i[1])\n plt.bar(ids,valores)\n plt.show()\n\n# Executando as funções \ncriando_tabela(nomeTab)\nfor prod in produtos :\n inserir_dados(nomeTab,prod)\n time.sleep(1)\nlendo_todos_dados(nomeTab)\nlendo_coluna(nomeTab)\natualizando_doc(nomeTab)\ndelete_doc(nomeTab)\ncriando_graficos(nomeTab)","sub_path":"MeusCodigos/cap06/cap06-05.py","file_name":"cap06-05.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"567465705","text":"class Node:\r\n def __init__(self):\r\n self.next = [None] * 26\r\n self.wordEnd = False\r\n\r\n\r\ndef insertNode(head, word):\r\n temp = head\r\n\r\n for c in word:\r\n index = ord(c) - ord('a')\r\n if not temp.next[index]:\r\n temp.next[index] = Node()\r\n temp = temp.next[index]\r\n temp.wordEnd = True\r\n\r\ndef searchSentence(head, sentence):\r\n n = len(sentence)\r\n visited = [False] * (n + 1)\r\n visited[0] = True\r\n\r\n for i in range(n):\r\n if visited[i]:\r\n temp = head\r\n for j in range(i, n):\r\n if not temp:\r\n break\r\n index = ord(sentence[j]) - ord('a')\r\n temp = temp.next[index]\r\n if temp and temp.wordEnd:\r\n visited[j + 1] = True\r\n \r\n return visited[n]\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n wordList = [\"self\", \"th\", \"is\", \"famous\", \"word\", \"break\", \"b\", \"r\", \"e\", \"a\", \"k\", \"br\", \"bre\", \"brea\", \"ak\", \"prob\", \"lem\"]\r\n sentence = \"wordbreakproblem\"\r\n\r\n head = Node()\r\n for word in wordList:\r\n insertNode(head, word)\r\n \r\n print(searchSentence(head, sentence))","sub_path":"python/DP/WordBreakTrie.py","file_name":"WordBreakTrie.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"3503411","text":"# Copyright (c) 2020 SMHI, Swedish Meteorological and Hydrological Institute.\n# License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit).\n\"\"\"\nCreated on 2020-04-07 15:41\n\n@author: a002028\n\"\"\"\nimport json\nimport numpy as np\nfrom sirena import utils\n\n\nclass JSONreader(dict):\n \"\"\"Read json files.\n\n - Import json\n - Export to json\n - Find dictionary within json file based on a specific key\n - Add elements to dictionary\n - Fill up json/dictionary structure with relevant/desired information\n \"\"\"\n\n def load_json(self, config_files=None, return_dict=False):\n \"\"\"Load json file.\n\n Array will be either a list of dictionaries or one single dictionary\n depending on what the json file includes.\n \"\"\"\n if not isinstance(config_files, (list, np.ndarray)):\n config_files = [config_files]\n\n for config_file in config_files:\n with open(config_file, 'r') as fd:\n self = utils.recursive_dict_update(self, json.load(fd))\n\n if return_dict:\n return self\n","sub_path":"sirena/readers/json_reader.py","file_name":"json_reader.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"473952378","text":"import tweepy # for tweeting\nimport secrets # shhhh\nfrom book_manager import BookManager # for getting sentences out of our book file\nimport random\n\ndef get_next_chunk():\n # open text file\n book = BookManager()\n first_sentence = book.first_sentence()\n # tweet the whole sentence if it's short enough\n if len(first_sentence) <= 140:\n chunk = first_sentence\n # otherwise just print the first 140 characters\n else:\n chunk = first_sentence[0:140]\n\n # delete what we just tweeted from the text file\n book.delete_message(chunk)\n #chunk = 'https://unsplash.it/200/300/?random'\n return chunk\n\ndef tweet(message):\n auth = tweepy.OAuthHandler(secrets.consumer_key, secrets.consumer_secret)\n auth.set_access_token(secrets.access_token, secrets.access_token_secret)\n api = tweepy.API(auth)\n auth.secure = True\n\n print(\"Posting message {}\".format(message))\n api.update_status(status=message)\n\ndef retweet():\n auth = tweepy.OAuthHandler(secrets.consumer_key, secrets.consumer_secret)\n auth.set_access_token(secrets.access_token, secrets.access_token_secret)\n api = tweepy.API(auth)\n auth.secure = True\n try:\n searchQuery = 'alice in wonderland' # this is what we're searching for\n tweetsPerQry = 1 # this is the max the API permits\n #new_tweet = api.search(q=searchQuery, count=tweetsPerQry) #its a list\n for tweet in tweepy.Cursor(api.search,q=searchQuery,result_type=\"recent\",include_entities=True).items(tweetsPerQry):\n print(\"Posting RT {}\".format(tweet.text))\n api.retweet(tweet.id)\n except tweepy.TweepError as e:\n print(\"TweepError. Posting a message from the book...\")\n tweet(get_next_chunk())\n\nif __name__ == '__main__':\n if random.randint(0,1) == 0:\n tweet(get_next_chunk())\n else:\n retweet()\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"277868873","text":"# -*- coding: utf-8 -*- #\n# Copyright 2018 Google Inc. All Rights Reserved.\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\"\"\"Tests of the peering module.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.api_lib.services import exceptions\nfrom googlecloudsdk.api_lib.services import peering\nfrom tests.lib.apitools import http_error\nfrom tests.lib.surface.services import unit_test_base\n\n\nclass PeeringTest(unit_test_base.SNUnitTestBase):\n \"\"\"Unit tests for peering module.\"\"\"\n\n OPERATION_NAME = 'operations/abc.0000000000'\n NETWORK = 'hello'\n RANGES = ['10.0.1.0/30', '10.0.3.0/30']\n\n def testCreateConnection_Success(self):\n \"\"\"Test CreateConnection returns operation when successful.\"\"\"\n want = self.services_messages.Operation(\n name=self.OPERATION_NAME, done=False)\n self.ExpectCreateConnection(self.NETWORK, self.RANGES, self.OPERATION_NAME)\n\n got = peering.CreateConnection(self.PROJECT_NUMBER, self.service,\n self.NETWORK, self.RANGES)\n\n self.assertEqual(got, want)\n\n def testCreateConnection_PermissionDenied(self):\n \"\"\"Test CreateConnection raises correctly when server returns 403 error.\"\"\"\n server_error = http_error.MakeDetailedHttpError(code=403, message='Error!')\n self.ExpectCreateConnection(\n self.NETWORK, self.RANGES, None, error=server_error)\n\n with self.assertRaisesRegex(\n exceptions.CreateConnectionsPermissionDeniedException, r'Error!'):\n peering.CreateConnection(self.PROJECT_NUMBER, self.service, self.NETWORK,\n self.RANGES)\n\n def testGetOperation_Success(self):\n \"\"\"Test GetOperation returns operation when successful.\"\"\"\n want = self.services_messages.Operation(name=self.OPERATION_NAME, done=True)\n self.ExpectOperation(self.OPERATION_NAME, 0)\n\n got = peering.GetOperation(self.OPERATION_NAME)\n\n self.assertEqual(got, want)\n\n def testGetOperation_PermissionDenied(self):\n \"\"\"Test GetOperation returns operation when server returns 403 error.\"\"\"\n server_error = http_error.MakeDetailedHttpError(code=403, message='Error!')\n self.ExpectOperation(self.OPERATION_NAME, 0, error=server_error)\n\n with self.assertRaisesRegex(exceptions.OperationErrorException, r'Error!'):\n peering.GetOperation(self.OPERATION_NAME)\n\n def testWaitOperation_Success(self):\n \"\"\"Test WaitOperation returns operation when successful.\"\"\"\n want = self.services_messages.Operation(name=self.OPERATION_NAME, done=True)\n self.ExpectOperation(self.OPERATION_NAME, 3)\n\n got = peering.WaitOperation(self.OPERATION_NAME)\n\n self.assertEqual(got, want)\n\n def testListConnections_Success(self):\n \"\"\"Test ListConnection returns connections when successful.\"\"\"\n want = [\n self.services_messages.Connection(\n network='projects/%s/global/networks/%s' % (self.PROJECT_NUMBER,\n self.NETWORK),\n peering='servicenetworking-googleapis-com',\n reservedPeeringRanges=['google1', 'google2'])\n ]\n self.ExpectListConnections(self.NETWORK, want)\n\n got = peering.ListConnections(self.PROJECT_NUMBER, self.service,\n self.NETWORK)\n\n self.assertEqual(got, want)\n\n def testListConnections_PermissionDenied(self):\n \"\"\"Test ListConnection raises correctly when server returns 403 error.\"\"\"\n server_error = http_error.MakeDetailedHttpError(code=403, message='Error!')\n self.ExpectListConnections(self.NETWORK, None, error=server_error)\n\n with self.assertRaisesRegex(\n exceptions.ListConnectionsPermissionDeniedException, r'Error!'):\n peering.ListConnections(self.PROJECT_NUMBER, self.service, self.NETWORK)\n","sub_path":"google-cloud-sdk/lib/tests/unit/api_lib/services/peering_test.py","file_name":"peering_test.py","file_ext":"py","file_size_in_byte":4302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"289715679","text":"import getopt\nimport secrets\nimport sys\n\nimport ckanapi\n\nckan = ckanapi.RemoteCKAN(secrets.ckan_url, apikey=secrets.ckan_api_key)\n\n\ndef get_opts():\n # Get the arguments from the command-line except the filename\n argv = sys.argv[1:]\n try:\n # Define the getopt parameters\n opts, args = getopt.getopt(argv, 'p:n:d:u:f:', ['package_id', 'name','description', 'url', 'file'])\n # Check if the options' length is 4 (can be enhanced)\n if len(opts) != 5:\n print('usage: ckan_upload.py -p -n -d -u -f ')\n else:\n # Iterate the options and get the corresponding values\n for opt, arg in opts:\n print(opt, arg)\n pid = opts[0][1]\n name = opts[1][1]\n desc = opts[2][1]\n url = opts[3][1]\n file = opts[4][1]\n # print(pid)\n return pid, name, desc, url, file\n except getopt.GetoptError:\n # Print something useful\n print('usage: ckan_upload.py -p -n -d -u -f ')\n sys.exit(2)\n\n\ndef upload_file(package_id, name, description, url, file_to_upload):\n ckan.action.resource_create(package_id=package_id,\n name=name, # added\n description=description,\n url=url,\n upload=open(file_to_upload))\n\n\ndef main():\n pid, name, desc, url, file = get_opts()\n upload_file(pid, name, desc, url, file)\n\nmain()\n","sub_path":"ckanuploader.py","file_name":"ckanuploader.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"20017100","text":"import cv2\nimport csv\n\nif __name__ == \"__main__\":\n\t# Loading the cascade XML file using CascadeClassifier method. \n\tface_cascades = cv2.CascadeClassifier(\"xml-files/haarcascade_frontalface_alt.xml\")\n\n\timg = cv2.imread(\"images/image-group-1.jpg\")\n\timg = cv2.resize(img, None, fx=0.1, fy=0.1, interpolation = cv2.INTER_CUBIC)\n\n\t# For storing x, y pixels of the face in any given image\n\tfaces = face_cascades.detectMultiScale(img, scaleFactor=1.05, minNeighbors=5)\n\n\tfor x, y, w, h in faces:\n\t\t# To draw rectamgle, args: img, (starting point corner), (end point corner), (color), width)\n\t\timg = cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)\n\n\tcv2.imshow(\"Output\", img)\n\tcv2.waitKey(0)\n\n","sub_path":"image-face-detection.py","file_name":"image-face-detection.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"364920898","text":"import numpy as np\nimport os\nfrom PIL import Image\nimport tqdm\nfrom src.utils import data_utils, misc\nfrom src import dataset\nfrom multiprocessing import Pool\nimport pickle\nimport argparse\n\nimport torch\n\nfrom src import data_fitter\nfrom src.utils import train_utils, config, data_utils\nfrom src import dataset, data_fitter, bern_gp_rloss_explorer, beta_gp_rloss_explorer, betaab_gp_rloss_explorer, simple_explorer\n\nROOT_DIR = os.path.expanduser(\"~/datasets/cocostuff\")\nCACHE_DIR = \"data/cocos3_10k\"\npreds_dir = os.path.expanduser(\"~/repos/deeplab-pytorch/data/features/cocostuff164k_on_cocostuff10k/deeplabv2_resnet101_msc\")\nprimary_label_strs = [\"bird\", \"cat\", \"dog\", \"horse\", \"sheep\", \"cow\", \"elephant\", \"bear\", \"zebra\", \"giraffe\"]\nscene_label_hierarchy = {\n \"water-other\": [\"sea\", \"river\"],\n \"ground-other\": [\"ground-other\", \"playingfield\", \"platform\", \"railroad\", \"pavement\", \"road\", \"gravel\", \"mud\", \"dirt\", \"snow\", \"sand\", \"solid-other\", \"hill\", \"mountain\", \"stone\", \"rock\", \"wood\", \"plant-other\", \"straw\", \"moss\", \"branch\", \"flower\", \"leaves\", \"bush\", \"tree\", \"grass\"],\n \"sky-other\": [\"sky-other\", \"clouds\"], \n \"structural-other\": [\"structural-other\", \"cage\", \"fence\", \"railing\", \"net\", \"building-other\", \"house\", \"roof\", \"tent\", \"skyscraper\", \"bridge\"], \n \"furniture-other\": [\"furniture-other\", \"stairs\", \"light\", \"counter\", \"mirror-stuff\", \"cupboard\", \"shelf\", \"cabinet\", \"table\", \"desk-stuff\", \"door-stuff\", \"window-other\", \"window-blind\", \"metal\", \"plastic\", \"cardboard\", \"paper\", \"floor-other\", \"floor-stone\", \"floor-marble\", \"floor-wood\", \"floor-tile\", \"carpet\", \"ceiling-other\", \"ceiling-tile\", \"wall-other\", \"wall-concrete\", \"wall-stone\", \"wall-brick\", \"wall-concrete\", \"wall-tile\", \"wall-panel\"],\n}\n# scene_label_strs = [\"sea\", \"fog\", \"ground-other\", \"railroad\", \"road\", \"snow\", \"sand\", \"hill\", \"wood\", \"tree\", \"bush\", \"grass\", \"railing\", \"fence\", \"bridge\", \"house\", \"sky-other\", \"textile-other\", \"furniture-other\", \"window-other\", \"floor-other\", \"wall-other\", \"plastic\"]\ndev = config.device\n\n\"\"\"\nLabeled ai: 0 acc: 0.7360\nLabeled ai: 1 acc: 0.9420\nLabeled ai: 2 acc: 0.8520\nLabeled ai: 3 acc: 0.9140\nLabeled ai: 4 acc: 0.7720\nLabeled ai: 5 acc: 0.7800\n\"\"\"\ngen_params = {\n 'animal': np.arange(10), \n 'water': np.arange(2), \n 'ground': np.arange(2), \n 'sky': np.arange(2),\n 'building': np.arange(2),\n 'furniture': np.arange(2),\n}\n\nD = np.meshgrid(*[np.arange(len(gen_params[key])) for key in gen_params])\nattr_dim = len(gen_params)\nfor _ in range(attr_dim):\n D[_] = np.reshape(D[_], -1)\n# -1 x attr_dim\nD = np.stack(D, axis=1)\nprint (\"Arms shape: \", np.shape(D), D[0], D[-1])\n\n\ndef get_labels():\n labels_strs = []\n # The checkpoint from: https://github.com/kazuto1011/deeplab-pytorch does not use unlabeled label\n # so are the annotations images of cocos.\n with open(os.path.join(ROOT_DIR, \"labels.txt\")) as f:\n for line in f:\n line = line.strip()\n flds = line.split()\n if flds[1] == \"unlabeled\":\n continue\n labels_strs.append(flds[1])\n \n primary_label_map = dict([(labels_strs.index(_pl), pi) for pi, _pl in enumerate(primary_label_strs)])\n scene_label_map = dict([(labels_strs.index(_sl), si) for si, _sl in enumerate(scene_label_hierarchy)])\n fine_to_coarse_scene_index = {}\n for k in scene_label_hierarchy:\n for fine_label in scene_label_hierarchy[k]:\n fine_index = labels_strs.index(fine_label)\n coarse_index = labels_strs.index(k)\n fine_to_coarse_scene_index[fine_index] = coarse_index\n# scene_label_map = dict([(sl, si) for si, sl in enumerate(range(92, 183))])\n \n print (fine_to_coarse_scene_index)\n return primary_label_map, scene_label_map, fine_to_coarse_scene_index\n\ndef _get_ids():\n train_ids = [fname[:-4] for fname in os.listdir(preds_dir + \"/train2017/logit/\") if fname.endswith(\".npy\")]\n val_ids = [fname[:-4] for fname in os.listdir(preds_dir + \"/val2017/logit/\") if fname.endswith(\".npy\")]\n return train_ids, val_ids\n\n\ndef _filter_fn(obj):\n fname, _id = obj\n img = Image.open(fname)\n img = np.array(img)\n labels = np.unique(img)\n _pls = [label for label in labels if label in primary_label_map]\n if len(_pls) == 1:\n return (_id, True)\n return (_id, False)\n\n\ndef filter_ids_with_single_object(ids, train=True):\n good_ids = []\n \n fnames = []\n for _id in ids:\n fname = _id + \".png\"\n fname = ROOT_DIR + \"/dataset/annotations/\" + (\"train2017\" if train else \"val2017\") + \"/\" + fname\n fnames.append((fname, _id))\n\n with Pool(20) as p:\n all_ids = list(tqdm.tqdm(p.imap(_filter_fn, fnames), total=len(ids)))\n good_ids = [_id for _id, _good in all_ids if _good]\n return good_ids\n \n\ndef fetch_preds(id_train_pair):\n _id, train = id_train_pair\n primary_labels = np.array([_pl for _pl in primary_label_map])\n scene_labels = np.array([_sl for _sl in scene_label_map])\n \n fldr = \"train2017\" if train else \"val2017\"\n pred_fname = preds_dir + \"/\" + fldr + \"/logit/\" + _id + \".npy\"\n assert os.path.exists(pred_fname)\n\n logits = np.load(pred_fname)\n preds = np.argmax(logits, axis=0)\n pls = [primary_label_map[_pl] for _pl in np.unique(preds) if _pl in primary_labels]\n random_pick = 0\n # this could happen\n if len(pls) > 1:\n scores = [len(np.where(preds==_pl)[0]) for _pl in pls]\n # retain the label with the highest prevalence\n good_pl_idx = np.argmax(scores)\n pl = pls[good_pl_idx]\n elif len(pls) == 0:\n primary_preds = np.argmax(logits[primary_labels, :, :], axis=0)\n pls = np.unique(primary_preds)\n scores = [len(np.where(primary_preds==_pl)[0]) for _pl in pls]\n good_pl_idx = np.argmax(scores)\n pl = pls[good_pl_idx]\n random_pick = 1\n elif len(pls) == 1:\n pl = pls[0]\n probs = torch.softmax(torch.tensor(logits), dim=0)\n primary_prob_cumsum = torch.mean(probs[primary_labels, :, :], dim=[1, 2]).numpy()\n\n z = np.zeros(len(scene_label_map))\n scene_probs = np.zeros([len(scene_label_map), 2])\n scene_coarse_preds = [fine_to_coarse_scene_index[_pl] for _pl in preds.flatten() if _pl in fine_to_coarse_scene_index]\n for fine_index, coarse_index in fine_to_coarse_scene_index.items():\n _cl = scene_label_map[coarse_index]\n scene_probs[_cl, 1] += torch.mean(probs[fine_index, :, :]).numpy()\n scene_probs[_cl, 0] += torch.mean(1 - probs[fine_index, :, :]).numpy()\n scene_coarse_labels = np.unique(scene_coarse_preds)\n scores = [len(np.where(scene_coarse_preds==_pl)[0]) for _pl in scene_coarse_labels]\n for si in np.argsort(-np.array(scores)):\n support = scores[si]\n _pl = scene_coarse_labels[si]\n z[scene_label_map[_pl]] = 1\n \n return {\"id\": _id, \"pl\": pl, \"sl\": z, \n \"random_pick\": random_pick, \n \"primary_logits\": primary_prob_cumsum,\n \"scene_logits\": scene_probs}\n\n\ndef predictions(ids, train=True):\n all_pl, all_sl = [], []\n logits_pl, logits_sl = [], []\n with Pool(5) as p:\n objs = list(tqdm.tqdm(p.imap(fetch_preds, zip(ids, [train]*len(ids))), total=len(ids)))\n id_to_obj_map = dict([(obj[\"id\"], obj) for obj in objs])\n num_random = 0\n for _id in ids:\n obj = id_to_obj_map[_id]\n pl, z = obj[\"pl\"], obj[\"sl\"]\n all_pl.append(pl)\n all_sl.append(z) \n logits_pl.append(obj[\"primary_logits\"])\n logits_sl.append(obj[\"scene_logits\"])\n num_random += obj[\"random_pick\"]\n \n print (\"Randomly picked examples: %d\" % num_random)\n return all_pl, all_sl, logits_pl, logits_sl\n\n\ndef fetch_gt(id_train_pair):\n _id, train = id_train_pair\n fldr = \"train2017\" if train else \"val2017\"\n fname = _id + \".png\"\n fname = ROOT_DIR + \"/dataset/annotations/\" + fldr + \"/\" + fname\n img = Image.open(fname)\n img = np.array(img)\n gt_labels = np.unique(img)\n pls = [primary_label_map[_pl] for _pl in gt_labels if _pl in primary_label_map]\n assert len(pls) == 1, \"Found two primary labels for id: %s, labels: %s\" % (_id, pls)\n pl = pls[0]\n gt_labels = [fine_to_coarse_scene_index[_label] for _label in gt_labels if _label in fine_to_coarse_scene_index]\n sls = [scene_label_map[_label] for _label in gt_labels if _label in scene_label_map]\n scores = [len(np.where(img==_label)[0]) for _label in gt_labels if _label in scene_label_map]\n z = np.zeros(len(scene_label_map))\n for si in np.argsort(-np.array(scores)):\n sl = sls[si]\n z[sl] = 1\n return {\"id\": _id, \"pl\": pl, \"sl\": z}\n\n\ndef ground_truth(ids, train=True):\n all_pl, all_sl = [], []\n with Pool(20) as p:\n gts = list(tqdm.tqdm(p.imap(fetch_gt, zip(ids, [train]*len(ids))), total=len(ids)))\n id_to_gt_map = dict([(_gt[\"id\"], _gt) for _gt in gts])\n for _id in ids:\n gt_obj = id_to_gt_map[_id]\n pl, z = gt_obj[\"pl\"], gt_obj[\"sl\"]\n all_pl.append(pl)\n all_sl.append(z)\n return all_pl, all_sl\n\n\nclass COCOSDataset(dataset.Dataset):\n def __init__(self, pred_pls, pred_sls, gt_pls, gt_sls, seed): \n assert len(pred_pls) == len(pred_sls)\n assert len(gt_pls) == len(gt_sls)\n assert len(pred_pls) == len(gt_pls)\n \n self.seed = seed\n LABELED_DATA_SIZE = 500\n self._arms = D\n #a small subset of labeled\n np.random.seed(0)\n idxs = np.random.permutation(np.arange(len(pred_pls)))\n all_labeled_idxs, unlabeled_idxs = idxs[:3*LABELED_DATA_SIZE], idxs[3*LABELED_DATA_SIZE:]\n np.random.seed(self.seed)\n labeled_idxs = np.random.choice(all_labeled_idxs, LABELED_DATA_SIZE)\n \n self.arm_hash_to_index = {}\n self.arm_to_idxs = {}\n seen_hashes = set()\n # Make arms from what is seen\n for arm in self._arms:\n arm_hash = self.hash_arm(arm)\n if arm_hash not in seen_hashes:\n self.arm_hash_to_index[arm_hash] = len(seen_hashes)\n seen_hashes.add(arm_hash)\n \n assert len(np.shape(self._arms)) == 2, \"Unexpected shape of arms: %s\" % np.shape(self._arms)\n \n arm_indices = []\n for idx in range(len(pred_pls)):\n arm = np.concatenate([[gt_pls[idx]], gt_sls[idx]]).astype(np.int32)\n arm_hash = self.hash_arm(arm)\n arm_index = self.arm_hash_to_index[arm_hash]\n arm_indices.append(arm_index)\n arm_indices = np.array(arm_indices)\n \n # this should only keep track of unlabeled indices\n for ui, idx in enumerate(unlabeled_idxs):\n arm = np.concatenate([[gt_pls[idx]], gt_sls[idx]]).astype(np.int32)\n arm_hash = self.hash_arm(arm)\n arm_index = self.arm_hash_to_index[arm_hash]\n x_indices = self.arm_to_idxs.get(arm_index, [])\n x_indices.append(ui) \n self.arm_to_idxs[arm_index] = x_indices\n \n num_empty = 0\n for ai in range(len(self.arms)):\n if ai not in self.arm_to_idxs:\n num_empty += 1\n print (\"Found %d/%d empty arms\" % (num_empty, len(self.arms)))\n \n print (\"Found %d unique arms and %0.2f average number of examples per arm\" % (len(self._arms), np.mean([len(self.arm_to_idxs.get(ai, [])) for ai in range(len(self._arms))])))\n self.labeled_data = (labeled_idxs, gt_pls[labeled_idxs], arm_indices[labeled_idxs])\n self.U = (unlabeled_idxs, gt_pls[unlabeled_idxs], arm_indices[unlabeled_idxs])\n \n assert len(self.arm_hash_to_index) == len(self._arms)\n\n @property\n def arms(self):\n return self._arms\n \n @property\n def num_arms(self):\n return len(self.arms)\n \n def sample(self, num_sample):\n idxs = np.random.choice(len(self), num_sample)\n x, y, arm_ids = self.U[0][idxs], self.U[1][idxs], self.U[2][idxs]\n return x, y, arm_ids\n \n def sample_arm(self, arm_index, num_sample):\n \"\"\"\n Sample randomly from arm (integer index) \n :return: np.array of x, y \n \"\"\"\n # allowing repeats\n idxs = np.random.choice(self.arm_to_idxs[arm_index], num_sample)\n x, y, arm_ids = self.U[0][idxs], self.U[1][idxs], self.U[2][idxs]\n return x, y\n \n def full_labeled_data(self):\n return self.labeled_data\n \n def full_data_arm(self, arm_index):\n idxs = self.arm_to_idxs[arm_index]\n x, y = self.U[0][idxs], self.U[1][idxs]\n return x, y\n \n def full_data(self):\n return self.U\n \n def num_attrs(self):\n return np.shape(self.arms)[-1]\n\n def __len__(self):\n return len(self.U[0])\n \n @staticmethod\n def hash_arm(arm):\n return \"::\".join(map(str, arm))\n \n def hash_to_arm_index(self, hashed_arm: str):\n # this can happen here since self.arms do not span the universe \n if hashed_arm not in self.arm_hash_to_index:\n return None\n return self.arm_hash_to_index[hashed_arm]\n\n \nclass JointModelFromCache():\n def __init__(self, logits_per_attr):\n \"\"\"\n Logits should be of shape: [len(full_data) x num_labels_for_this_attr]_{num_attr}\n \"\"\"\n self.logits = logits_per_attr\n \n def logit_per_attr(self, np_x, debug=False):\n return [self.logits[ai][np_x] for ai in range(len(self.logits))]\n\n\ndef check(gt_pls, gt_sls):\n arm_hash_to_index = {}\n arms = []\n for si in range(len(gt_pls)):\n arm = np.concatenate([[gt_pls[si]], gt_sls[si]]).astype(np.int32)\n arm_hash = COCOSDataset.hash_arm(arm)\n\n if arm_hash not in arm_hash_to_index:\n arms.append(arm)\n x_indices = arm_hash_to_index.get(arm_hash, [])\n x_indices.append(si)\n arm_hash_to_index[arm_hash] = x_indices\n \n print (\"Found %d unique arms and %0.2f average number of examples per arm\" % (len(arm_hash_to_index), np.mean([len(arm_hash_to_index[_h]) for _h in arm_hash_to_index])))\n \n\ndef _one_hot(preds, depth, on=1, off=0):\n z = np.ones([len(preds), depth])*off\n z[np.arange(len(preds)), preds.astype(np.int64)] = on\n return z\n\n\ndef evaluate(preds, gt):\n corr, num = {}, {}\n for i in range(len(preds)):\n _corr = (preds[i] == gt[i])\n _l = gt[i]\n corr[_l] = corr.get(_l, 0) +_corr\n num[_l] = num.get(_l, 0) + 1\n\n for k in corr:\n print (\"Key: %s Acc: %0.4f num: %d\" % (str(k), corr[k]/num[k], num[k]))\n\n\ndef evaluate_sls(pred_sls, gt_sls):\n num_sls = len(pred_sls[0])\n corr = np.zeros(num_sls)\n for i in range(len(pred_sls)):\n corr += (pred_sls[i] == gt_sls[i]).astype(np.float32)\n\n print (\"Per scene label acc:\")\n print (corr/len(pred_sls))\n\n\ndef prepare(seed):\n gt_pls, gt_sls, (pred_pls, plogits), (pred_sls, slogits) = parse_preds_gts()\n check(gt_pls, gt_sls)\n # num_examples x num_labels\n plogits = np.array(plogits)\n # num_examples x num_attrs x 2\n slogits = np.array(slogits)\n print (\"Shape of p: %s, scene: %s\" % (plogits.shape, slogits.shape))\n \n cocos_dataset = COCOSDataset(pred_pls, pred_sls, gt_pls, gt_sls, seed)\n num_sl_attrs = pred_sls.shape[-1]\n \n models = [dataset.ModelFromCache(_one_hot(pred_pls, len(primary_label_map), on=1, off=-1))] + [dataset.ModelFromCache(_one_hot(pred_sls[:, si], 2, on=1, off=-1)) for si in range(num_sl_attrs)]\n joint_model = JointModelFromCache([_one_hot(pred_pls, len(primary_label_map), on=1, off=-1)] + [_one_hot(pred_sls[:, si], 2, on=1, off=-1) for si in range(num_sl_attrs)])\n\n# models = [dataset.ModelFromCache(plogits)] + [dataset.ModelFromCache(slogits[:, si, :]) for si in range(num_sl_attrs)]\n# joint_model = JointModelFromCache([plogits] + [slogits[:, si, :] for si in range(num_sl_attrs)])\n \n config = data_fitter.Config()\n config.CALIBRATION_TOL = 1e-3\n config.CALIBRATION_TOPK = 5\n \n cocos_fitter = data_fitter.Fitter(cocos_dataset, models=models, device=dev, cache_dir=CACHE_DIR, joint_model=joint_model, config=config)\n cocos_fitter.set_primary_task_index(0)\n \n in_features = 1 + gt_sls.shape[-1]\n kernel_embedding_model = torch.nn.Sequential(\n torch.nn.Linear(in_features, 20),\n torch.nn.ReLU(),\n torch.nn.Linear(20, 20)\n )\n cocos_fitter.set_deep_kernel(kernel_embedding_model, 20)\n \n if not os.path.exists(cocos_fitter.model_name):\n cocos_fitter.fit(use_edge_potentials=True)\n if not os.path.exists(cocos_fitter.model_name_no_edge_potential):\n cocos_fitter.fit(use_edge_potentials=False)\n \n return cocos_dataset, cocos_fitter\n \ndef parse_preds_gts():\n train_ids = data_utils.cache(\n lambda: filter_ids_with_single_object(train_ids, train=True),\n CACHE_DIR + \"/train_ids.pkl\"\n )\n print (\"Found %d good ones in train\" % len(train_ids))\n \n val_ids = data_utils.cache(\n lambda: filter_ids_with_single_object(val_ids, train=False),\n CACHE_DIR + \"/val_ids.pkl\"\n )\n print (\"Found %d good ones in val\" % len(val_ids))\n \n train_pls, train_sls, train_plogits, train_slogits = data_utils.cache(\n lambda: predictions(train_ids, train=True),\n CACHE_DIR + \"/train_preds.pkl\"\n )\n val_pls, val_sls, val_plogits, val_slogits = data_utils.cache(\n lambda: predictions(val_ids, train=False),\n CACHE_DIR + \"/val_preds.pkl\"\n )\n pred_pls, pred_sls = train_pls + val_pls, train_sls + val_sls\n plogits, slogits = train_plogits + val_plogits, train_slogits + val_slogits\n \n train_pls2, train_sls2 = data_utils.cache(\n lambda: ground_truth(train_ids, train=True),\n CACHE_DIR + \"/train_gt.pkl\"\n )\n val_pls2, val_sls2 = data_utils.cache(\n lambda: ground_truth(val_ids, train=False),\n CACHE_DIR + \"/val_gt.pkl\"\n )\n gt_pls, gt_sls = train_pls2 + val_pls2, train_sls2 + val_sls2\n \n# evaluate(pred_pls, gt_pls)\n evaluate_sls(pred_sls, gt_sls)\n return np.array(gt_pls), np.array(gt_sls), (np.array(pred_pls), plogits), (np.array(pred_sls), slogits)\n\n\nprimary_label_map, scene_label_map, fine_to_coarse_scene_index = get_labels()\nif __name__ == '__main__':\n parser = misc.get_arg_parser()\n \n args = parser.parse_args()\n \n cocos_dataset, cocos_data_fitter = prepare(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n \n _args = [cocos_dataset, cocos_data_fitter, cocos_data_fitter.cache_dir, dev]\n _kwargs = {'explore_strategy': args.et, 'seed': args.seed, \"sample_type\": args.sample_type}\n if args.explorer == \"bern_gp_rloss\":\n _kwargs['width'] = args.width\n if args.ablation:\n bern_gp_rloss_explorer.estimation_ablation(_args, _kwargs)\n else:\n explorer = bern_gp_rloss_explorer.BernGPExplorer(*_args, **_kwargs)\n elif args.explorer == 'beta_gp_rloss':\n misc.populate_params(_kwargs, args)\n # _kwargs[\"sample_type\"] = \"correctednoep\"\n if args.ablation:\n if args.alpha_beta:\n betaab_gp_rloss_explorer.estimation_ablation(_args, _kwargs)\n else:\n beta_gp_rloss_explorer.estimation_ablation(_args, _kwargs)\n else:\n explorer = beta_gp_rloss_explorer.BetaGPExplorer(*_args, **_kwargs)\n elif args.explorer == 'simple':\n if args.ablation:\n simple_explorer.estimation_ablation(_args, _kwargs)\n else:\n explorer = simple_explorer.SimpleExplorer(*_args, **_kwargs)\n \n if not args.ablation:\n explorer.explore_and_fit(budget=2000)","sub_path":"cocos3_10k.py","file_name":"cocos3_10k.py","file_ext":"py","file_size_in_byte":19666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"513711522","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 15 08:27:27 2015\n\n@author: jack.gang\n\"\"\"\n\nimport time\nfrom EulerFunctions import isPrime\n\ndef nthPrime(n):\n number = 2\n count = 0\n while True:\n if isPrime(number):\n count = count + 1\n if count == n:\n return number\n number = number + 1 \n\nstart = time.time()\n\nanswer = nthPrime(10001)\n\nelapsed = time.time() - start\n\nprint(\"{} found in {} seconds\".format(answer,elapsed))","sub_path":"007 - 10001st prime.py","file_name":"007 - 10001st prime.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"262402921","text":"\n\n#calss header\nclass _CRAZED():\n\tdef __init__(self,): \n\t\tself.name = \"CRAZED\"\n\t\tself.definitions = [u'behaving in a wild or strange way, especially because of strong emotions or extreme pain: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_crazed.py","file_name":"_crazed.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"5359790","text":"import os\r\nfrom email.parser import Parser\r\nclass TestingCorpus:\r\n '''Class of methods for test handling.'''\r\n def __init__(self, corpus_dir):\r\n self.corpus_dir = corpus_dir\r\n self.file_names_list = self.list_file_names()\r\n self.pos_tag = 'SPAM'\r\n self.neg_tag = 'OK'\r\n \r\n def list_file_names(self):\r\n '''Returns a list of files in the directory (ignores special files beginning with \"!\").'''\r\n file_list = []\r\n for fname in os.listdir(self.corpus_dir):\r\n if not fname.startswith('!'):\r\n file_list.append(fname)\r\n return file_list\r\n \r\n def file_as_lower_string(self,fname):\r\n '''Returns the required file as a string converted to lower chars.'''\r\n return self.file_as_string(fname).lower()\r\n \r\n def file_as_string(self, fname):\r\n '''Returns the required file as a string. Necessary for file_as_lower_string().'''\r\n file_path = os.path.join(self.corpus_dir, fname)\r\n with open(file_path, 'r', encoding='utf-8') as file:\r\n file_string = file.read()\r\n return file_string\r\n \r\n def parse_email(self, fname):\r\n '''Used for get important parts of the mail.'''\r\n parser = Parser()\r\n email = parser.parsestr(self.file_as_lower_string(fname))\r\n sender = self.get_sender(email)\r\n subject = self.get_subject(email)\r\n return (sender, subject)\r\n \r\n def get_sender(self, email):\r\n '''Returns the sender's address. Necessary for parse_email().'''\r\n sender = email['from']\r\n if sender == None:\r\n return 'none'\r\n if \"<\" in sender:\r\n strip_chars = ''\r\n for char in sender:\r\n if char == '<':\r\n break\r\n else:\r\n strip_chars += char\r\n sender = sender.lstrip(strip_chars)\r\n return sender.strip().strip('<>')\r\n \r\n def get_subject(self, email):\r\n '''Returns the subject. Necessary for parse_email().'''\r\n subject = email['subject']\r\n if subject == None:\r\n return 'none'\r\n return subject\r\n \r\n","sub_path":"RPH/SPAM/testingcorpus.py","file_name":"testingcorpus.py","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"426155161","text":"# -*- coding:utf-8 -*-\n\n\"\"\"\nOKEx Future Asset Server.\n\nAuthor: HuangTao\nDate: 2019/01/20\nEmail: huangtao@ifclover.com\n\"\"\"\n\nfrom quant.utils import tools\nfrom quant.utils import logger\nfrom quant.event import EventAsset\nfrom quant.tasks import LoopRunTask\nfrom quant.platform.okex_future import OKExFutureRestAPI\n\n\nclass OKExFutureAsset:\n \"\"\" OKEx Future Asset Server.\n\n Attributes:\n kwargs:\n platform: Exchange platform name, must be `okex_future`.\n host: Exchange HTTP host address, default is \"https://www.okex.com\".\n account: Account name. e.g. test@gmail.com.\n access_key: Account's ACCESS KEY.\n secret_key: Account's SECRETE KEY.\n passphrase: API KEY Passphrase.\n update_interval: Interval time(second) for fetching asset information via HTTP, default is 10s.\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"Initialize object.\"\"\"\n self._platform = kwargs[\"platform\"]\n self._host = kwargs.get(\"host\", \"https://www.okex.com\")\n self._account = kwargs[\"account\"]\n self._access_key = kwargs[\"access_key\"]\n self._secret_key = kwargs[\"secret_key\"]\n self._passphrase = kwargs[\"passphrase\"]\n self._update_interval = kwargs.get(\"update_interval\", 10)\n\n self._assets = {} # All currencies\n\n # Create a REST API client.\n self._rest_api = OKExFutureRestAPI(self._host, self._access_key, self._secret_key, self._passphrase)\n\n # Register a loop run task to fetching asset information.\n LoopRunTask.register(self.check_asset_update, self._update_interval)\n\n async def check_asset_update(self, *args, **kwargs):\n \"\"\"Fetch asset information.\"\"\"\n result, error = await self._rest_api.get_user_account()\n if error:\n logger.warn(\"platform:\", self._platform, \"account:\", self._account, \"get asset info failed!\", caller=self)\n return\n\n assets = {}\n for name, item in result[\"info\"].items():\n symbol = name.upper()\n total = float(item[\"equity\"])\n locked = float(item[\"margin\"])\n if total > 0:\n assets[symbol] = {\n \"total\": \"%.8f\" % total,\n \"free\": \"%.8f\" % (total - locked),\n \"locked\": \"%.8f\" % locked\n }\n\n if assets == self._assets:\n update = False\n else:\n update = True\n self._assets = assets\n\n # Publish AssetEvent.\n timestamp = tools.get_cur_timestamp_ms()\n EventAsset(self._platform, self._account, self._assets, timestamp, update).publish()\n logger.info(\"platform:\", self._platform, \"account:\", self._account, \"asset:\", self._assets, caller=self)\n","sub_path":"src/assets/okex_future.py","file_name":"okex_future.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"90044889","text":" \n\n# Program extracting first column \nimport xlrd \nimport xlwt\nimport xlsxwriter \nloc = (\"C:/Users/ARUNBABU/Desktop/Mashupstack/Python/parvathy.xlsx\") \n \nwb = xlrd.open_workbook(loc) \nsheet = wb.sheet_by_index(0) \nsheet.cell_value(0, 0) \n \nfor i in range(sheet.nrows):\n\tlist1 = sheet.cell_value(i, 0)\n\tprint(list1) \n\nrow = 0\ncolumn = 0\n \n# Workbook() takes one, non-optional, argument \n# which is the filename that we want to create. \nworkbook = xlsxwriter.Workbook('hello2.xlsx') \n \n# The workbook object is then used to add new \n# worksheet via the add_worksheet() method. \nworksheet = workbook.add_worksheet() \n \n# Use the worksheet object to write \n# data via the write() method. \n\n\nfor item in list1 : \n \n # write operation perform \n worksheet.write(row,column,item) \n \n # incrementing the value of row by one \n # with each iteratons. \n row += 1\n \nworkbook.close() \n\n \n\n","sub_path":"Python/pgm1.py","file_name":"pgm1.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"318253621","text":"import pygame\nfrom pygame.sprite import Sprite\n\nclass Alien(Sprite):\n\n\tdef __init__(self, game):\n\t\tsuper().__init__()\n\t\tself.screen = game.screen\n\t\tself.settings = game.game_setting\n\t\tself.image = pygame .image.load(\"img/NYA.PNG\")\n\t\tself.rect = self.image.get_rect()\n\n\t\tself.rect.x = self.rect.width\n\t\tself.rect.y = self.rect.height\n\n\t\tself.y = float(self.rect.y)\n\n\n\tdef update(self):\n\n\n\t\tself.y -= self.settings.alien_speed * self.settings.alien_army_direction\n\t\tself.rect.y = self.y\n\n\tdef _check_edges(self):\n\t\tscreen_rect = self.screen.get_rect()\n\t\tif (self.rect.bottom >= screen_rect.bottom) or (self.rect.top <= screen_rect.top):\n\t\t\treturn True","sub_path":"Game/alien.py","file_name":"alien.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"498660791","text":"\"\"\" given an array. waf w\n\"\"\"\n\nimport sys\nsys.path.append('..')\n\nfrom Sorting.sorttest import test\nimport random\n\n\ndef dutchflag(nums, low, high):\n i, j = low, high\n \n while i < j:\n while nums[i]%2 == 0 and i < j:\n i +=1\n while nums[j]%2 == 1 and i< j:\n j -=1\n \n nums[i], nums[j] = nums[j], nums[i]\n \n \nif __name__ == \"__main__\":\n res = []\n for x in xrange(10000):\n size = random.randint(2,50)\n nums = [random.randint(0,1) for _ in xrange(size)]\n dutchflag(nums, 0, len(nums)-1)\n res.append(test(nums))\n \n print(\"%s Pass.\"%(res.count(True)))\n print(\"%s Fail.\"%(res.count(False)))\n\n\n\n","sub_path":"Searching/dutch_flag.py","file_name":"dutch_flag.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"376455939","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/1/27 下午2:22\n# @Author : wudizhangzhi\n\"\"\"Hupu.\n Proudly presented by Hupu JRs.\n\nUsage:\n hupu [-m MODE] [-a APIVERSION] [-d DATATYPE] [-u USERNAME] [-p PASSWORD]\n hupu -h | --help\n hupu -v | --version\n\nTips:\n Please hit Ctrl-C on the keyborad when you want to interrupt the game live.\n\nOptions:\n -u USERNAME --username=USERNAME Input username.\n -p PASSWORD --password=PASSWORD Input password.\n -a APIVERSION --apiversion=APIVERSION Api version.[default: 7.1.15]\n -m MODE --mode=MODE Run mode.Available: live news teamranks...[default: live]\n -d DATATYPE --datatype=DATATYPE Player data type.Available: regular, injury, daily[default:regular]\n -h --help Show this help message and exit.\n -v --version Show version.\n\"\"\"\nfrom __future__ import print_function\n# python2 curses addstr乱码问题\nimport locale\n\nlocale.setlocale(locale.LC_ALL, '')\nimport sys\nimport curses\nimport colored\nimport docopt\nimport traceback\n\nfrom hupu.api.live import LiveMinxin\nfrom hupu.api.login import LoginMixin\nfrom hupu.api.news import NewsMixin\nfrom hupu.api.datas import DatasMixin\nfrom hupu.utils import colored_text, SYSTEM\nfrom hupu.api import logger\nfrom hupu.menus.HupuMenu import HupuMenu\nfrom hupu.version import version\n\n# if SYSTEM.lower() == 'windows':\n# # TODO debug window\n# reload(sys)\n# sys.setdefaultencoding('utf-8')\n# sys.stdout.encoding = 'cp65001'\n\nlog = logger.getLogger(__name__)\n\nMODE_LIST = ['live', 'news', 'teamranks', 'playerdata']\n\n\nclass HupuApp(LiveMinxin, NewsMixin, LoginMixin, DatasMixin):\n def run(self):\n # 判断参数, 执行哪一种场景\n # 默认进入比赛文字直播模式\n mode = self._kwargs.get('mode', 'live')\n mode = mode.lower()\n assert mode in MODE_LIST, AttributeError('Expected mode are {}, got {}.'.format(', '.join(MODE_LIST), mode))\n try:\n hupumenu = HupuMenu(self)\n items = []\n if mode == 'live': # 文字直播模式\n items = self.getGames()\n\n elif mode == 'news': # 新闻模式\n items = self.getNews()\n hupumenu.body_title = '新闻:'\n\n elif mode == 'teamranks': # 球队数据模式\n items = self.getDatas()\n hupumenu.body_title = '球队数据:'\n\n elif mode == 'playerdata': # 球队数据模式\n datatype = self._kwargs.get('datatype', '').lower()\n if not datatype or datatype not in ['regular', 'injury', 'daily']:\n datatype = 'regular'\n items = self.getPlayerDataInGenernal(datatype)\n hupumenu.body_title = '球员数据:'\n\n if not items:\n raise Exception('没有数据!')\n hupumenu.set_items(items)\n hupumenu.mode = mode\n\n hupumenu.draw()\n hupumenu.listen()\n\n except curses.error as e:\n curses.endwin()\n log.error(e)\n print(colored_text('窗口太小, 请调整窗口大小!', colored.fg(\"red\") + colored.attr(\"bold\")))\n except Exception as e:\n log.error(traceback.format_exc())\n if not curses.isendwin():\n curses.endwin()\n print(e)\n\n\ndef start():\n arguments = docopt.docopt(__doc__, version='Hupu {}'.format(version))\n # 处理参数\n arguments = {k.replace('--', ''): v for k, v in arguments.items()}\n hupulive = HupuApp(**arguments)\n hupulive.run()\n","sub_path":"hupu/hupuapp.py","file_name":"hupuapp.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"72229156","text":"#\n# Modified standard toolbar for image manipulation tasks and image WM awareness\n#\n# Copied from:\n# matplotlib.backend_bases.NavigationToolbar2\n# matplotlib.backends.backend_tkagg.NavigationToolbar2TkAgg\n#\n# If one can live with the dual function pan/zoom, it should be possible to subclass this.\n#\n\n\nimport matplotlib\nimport matplotlib.cbook as cbook\nfrom matplotlib.figure import Figure\nfrom matplotlib.widgets import SubplotTool\nimport matplotlib.backends.windowing as windowing\nfrom matplotlib.backends.backend_tkagg import ToolTip, FigureCanvasTkAgg, FigureManagerTkAgg\n\nimport numpy as np\n\nimport six\nimport Tkinter as Tk\n\nimport WM\n\nimport os.path\nrcParams = matplotlib.rcParams\n\nclass Cursors:\n # this class is only used as a simple namespace\n HAND, POINTER, SELECT_REGION, MOVE = list(range(4))\ncursors = Cursors()\n\ncursord = {\n \"none\" : \"arrow\",\n \"slice\" : \"fleur\",\n \"bvalue\" : \"fleur\",\n \"pan\" : \"hand2\",\n \"crosshair\": \"tcross\",\n \"ZOOM\": \"tcross\",\n }\n\nclass NavigationToolbar2(object):\n \"\"\"\n Base class for the navigation cursor, version 2\n\n backends must implement a canvas that handles connections for\n 'button_press_event' and 'button_release_event'. See\n :meth:`FigureCanvasBase.mpl_connect` for more information\n\n\n They must also define\n\n :meth:`save_figure`\n save the current figure\n\n :meth:`set_cursor`\n if you want the pointer icon to change\n\n :meth:`_init_toolbar`\n create your toolbar widget\n\n :meth:`draw_rubberband` (optional)\n draw the zoom to rect \"rubberband\" rectangle\n\n :meth:`press` (optional)\n whenever a mouse button is pressed, you'll be notified with\n the event\n\n :meth:`release` (optional)\n whenever a mouse button is released, you'll be notified with\n the event\n\n :meth:`dynamic_update` (optional)\n dynamically update the window while navigating\n\n :meth:`set_message` (optional)\n display message\n\n :meth:`set_history_buttons` (optional)\n you can change the history back / forward buttons to\n indicate disabled / enabled state.\n\n That's it, we'll do the rest!\n \"\"\"\n\n # list of toolitems to add to the toolbar, format is:\n # (\n # text, # the text of the button (often not visible to users)\n # tooltip_text, # the tooltip shown on hover (where possible)\n # image_file, # name of the image for the button (without the extension)\n # name_of_method, # name of the method in NavigationToolbar2 to call\n # )\n toolitems = (\n ('Sources', 'Select sources', 'move', 'wm_sources'),\n ('View', 'Select view', 'move', 'wm_view'),\n ('Source', 'Select source', 'move', 'source'),\n ('Axis', 'Toggle Axis', 'move', 'axis'),\n ('Crosshair', 'Show a point in space', 'move', 'crosshair'),\n ('B-value', 'Pan through b-values', 'move', 'bvalue'),\n ('Slice', 'Pan through slices', 'move', 'slice'),\n ('Home', 'Reset original view', 'home', 'home'),\n ('Back', 'Back to previous view', 'back', 'back'),\n ('Forward', 'Forward to next view', 'forward', 'forward'),\n (None, None, None, None),\n ('Pan', 'Pan axes with left mouse, zoom with right', 'move', 'pan'),\n ('Zoom', 'Zoom to rectangle', 'zoom_to_rect', 'zoom'),\n (None, None, None, None),\n ('Subplots', 'Configure subplots', 'subplots', 'configure_subplots'),\n ('Save', 'Save the figure', 'filesave', 'save_figure'),\n #('Debug', 'bind debug info here', 'filesave', 'debug'),\n )\n\n def __init__(self, canvas, Winst):\n self.canvas = canvas\n self.Winst = Winst\n canvas.toolbar = self\n # a dict from axes index to a list of view limits\n self._views = cbook.Stack()\n self._views2 = cbook.Stack()\n self._positions = cbook.Stack() # stack of subplot positions\n\n\n self._idPress = None\n self._idRelease = None\n self._idDrag = self.canvas.mpl_connect(\n 'motion_notify_event', self.mouse_move)\n self._ids_zoom = [] # Zoom equivalent for drag ID (mouse move, key press, key release)\n\n self._last_axis = None # Axis where the button was pressed\n self._xypress = None # Press info for the zoom rectangle\n\n self._active = None # ID string denoting active mode\n self._button_pressed = None # Save the mouse button pressed at canvas\n self._zoom_mode = None # Key pressed in zoom mode, to limit to y/x zooming\n\n self._lastCursor = None # GUI mouse cursor\n self.mode = '' # GUI status message\n self._init_toolbar()\n\n\n\n # a mode string for the status bar\n self.set_history_buttons()\n\n # ACTIVATION FUNCTIONS\n # General activation function called from the GUI\n def activate(self, mode_id, *args):\n \"\"\" General activation function for toolbar button press.\n Set the active mode and connect corresponding callbacks.\n \"\"\"\n\n if self._active == mode_id:\n self._active = None\n else:\n self._active = mode_id\n if self._idPress is not None:\n self._idPress = self.canvas.mpl_disconnect(self._idPress)\n self.mode = ''\n\n if self._idRelease is not None:\n self._idRelease = self.canvas.mpl_disconnect(self._idRelease)\n self.mode = ''\n\n if self._active:\n self._idPress = self.canvas.mpl_connect('button_press_event',\n getattr(self, 'press_' + mode_id))\n self._idRelease = self.canvas.mpl_connect('button_release_event',\n getattr(self, 'release_' + mode_id))\n self.mode = mode_id\n self.canvas.widgetlock(self)\n else:\n self.canvas.widgetlock.release(self)\n\n for a in self.canvas.figure.get_axes():\n a.set_navigate_mode(self._active)\n\n self.set_message(self.mode)\n # just get rid of these altogether\n def pan(self, *args): self.activate('pan')\n def slice(self, *args): self.activate('slice')\n def crosshair(self, *args): self.activate('crosshair')\n def bvalue(self, *args): self.activate('bvalue')\n def axis(self, *args): self.activate('axis')\n def wm_sources(self, *args): self.activate('sources')\n def wm_view(self, *args): self.activate('view')\n def source(self, *args): self.activate('source')\n\n\n # CANVAS MOUSE PRESS\n # Called when mouse button is pressed\n def press(self, event): pass\n # General function to call when a mouse press occurs in canvas\n def press_canvas(self, mode_string, event, implements = (1,)):\n\n if event.button in implements:\n self._button_pressed = event.button\n else:\n self._button_pressed = None\n return\n\n # push the current view to define home if stack is empty\n if self._views.empty():\n self.push_current()\n\n x, y = event.x, event.y\n for i, a in enumerate(self.canvas.figure.get_axes()):\n if x is not None and y is not None and a.in_axes(event) and a.get_navigate() and a.can_pan():\n\n self._last_axis = a\n self.canvas.mpl_disconnect(self._idDrag)\n # Can replaced by a subclass like structure\n a2 = self.Winst.get_adapter(a)\n if self._button_pressed == 1:\n getattr(a2, 'start_'+self._active)(x, y, event.button)\n self._idDrag = self.canvas.mpl_connect('motion_notify_event', getattr(self,'drag_'+self._active))\n elif self._button_pressed == 3:\n #TODO: seperate zoom/pan into two buttons to get rid of the first if\n if self._active == 'pan':\n getattr(a2, 'start_'+self._active)(x, y, event.button)\n self._idDrag = self.canvas.mpl_connect('motion_notify_event', getattr(self,'drag_'+self._active))\n else:\n getattr(self, self._active+'_menu')(event)\n\n\n self.press(event)\n # Connect to drag_mode\n def press_pan(self, event): self.press_canvas('pan', event, implements = (1,3))\n def press_slice(self, event): self.press_canvas('slice', event, implements = (1,))\n def press_crosshair(self, event): self.press_canvas('crosshair', event, implements = (1,))\n def press_bvalue(self, event): self.press_canvas('bvalue', event, implements = (1,))\n # Call mode_menu\n def press_axis(self, event): self.press_canvas('axis', event, implements = (3,))\n def press_sources(self, event): self.press_canvas('sources', event, implements = (3,))\n def press_view(self, event): self.press_canvas('view', event, implements = (3,))\n def press_source(self, event): self.press_canvas('source', event, implements = (3,))\n\n\n # CANVAS MOUSE DRAG\n # General function to call when a mouse drag occurs in canvas\n def drag_canvas(self, event):\n a = self._last_axis\n a2 = self.Winst.get_adapter(a)\n getattr(a2, 'drag_'+self._active)(event)\n self.display_message(event)\n self.dynamic_update()\n # When the tool is not active\n def mouse_move(self, event):\n if not event.inaxes or not self._active:\n if self._lastCursor != \"none\":\n self.set_cursor(\"none\")\n self._lastCursor = \"none\"\n else:\n if self._lastCursor != self._active:\n if cursord.has_key(self._active):\n self.set_cursor(self._active)\n else:\n self.set_cursor(\"none\")\n self._lastCursor = self._active\n self.display_message(event)\n\n def display_message(self, event):\n if event.inaxes and event.inaxes.get_navigate():\n try:\n a2 = self.Winst.get_adapter(event.inaxes)\n if self._active in ('crosshair', None):\n s = a2.get_display_str(event.xdata, event.ydata)\n elif self._active in ('slice','bvalue','pan'):\n s = a2.get_display_minor_str(event.xdata, event.ydata)\n else:\n s = event.inaxes.format_coord(event.xdata, event.ydata)\n except (ValueError, OverflowError):\n pass\n else:\n if len(self.mode):\n self.set_message('%s, %s' % (self.mode, s))\n else:\n self.set_message(s)\n else:\n self.set_message(self.mode)\n\n\n # Drag functions\n def drag_pan(self, event): self.drag_canvas(event)\n def drag_slice(self, event): self.drag_canvas(event)\n def drag_bvalue(self, event): self.drag_canvas(event)\n def drag_crosshair(self, event): self.drag_canvas(event)\n # Menu functions, overwritten in GUI's subclass\n def axis_menu(self, event): pass\n def sources_menu(self, event): pass\n def view_menu(self, event): pass\n def source_menu(self, event): pass\n\n\n # CANVAS MOUSE RELEASE\n # Called when mouse button is released\n def release(self, event): pass\n # General function to call when a mouse release occurs in canvas\n def release_canvas(self, event):\n if self._button_pressed is None:\n return\n self.canvas.mpl_disconnect(self._idDrag)\n self._idDrag = self.canvas.mpl_connect('motion_notify_event', self.mouse_move)\n\n if not self._last_axis:\n return\n a = self._last_axis\n a2 = self.Winst.get_adapter(a)\n # Menus do not implement this\n if hasattr(a2,'end_'+self._active):\n getattr(a2, 'end_'+self._active)()\n\n self._button_pressed = None\n self._last_axis = None\n\n self.push_current()\n self.release(event)\n self.draw()\n # just get rid of these altogether\n def release_pan(self, event): self.release_canvas(event)\n def release_slice(self, event): self.release_canvas(event)\n def release_crosshair(self, event): self.release_canvas(event)\n def release_bvalue(self, event): self.release_canvas(event)\n def release_axis(self, event): self.release_canvas(event)\n def release_sources(self, event): self.release_canvas(event)\n def release_view(self, event): self.release_canvas(event)\n def release_source(self, event): self.release_canvas(event)\n\n def get_method(self, a, f):\n if hasattr(a,f): return getattr(a, f)\n else:\n a2 = self.Winst.get_adapter(a)\n if hasattr(a2,f): return getattr(a2, f)\n else: return None\n\n # The black sheep\n def zoom(self, *args):\n \"\"\"Activate zoom to rect mode\"\"\"\n if self._active == 'ZOOM':\n self._active = None\n else:\n self._active = 'ZOOM'\n\n if self._idPress is not None:\n self._idPress = self.canvas.mpl_disconnect(self._idPress)\n self.mode = ''\n\n if self._idRelease is not None:\n self._idRelease = self.canvas.mpl_disconnect(self._idRelease)\n self.mode = ''\n\n if self._active:\n self._idPress = self.canvas.mpl_connect('button_press_event',\n self.press_zoom)\n self._idRelease = self.canvas.mpl_connect('button_release_event',\n self.release_zoom)\n self.mode = 'zoom rect'\n self.canvas.widgetlock(self)\n else:\n self.canvas.widgetlock.release(self)\n\n for a in self.canvas.figure.get_axes():\n a.set_navigate_mode(self._active)\n\n self.set_message(self.mode)\n def press_zoom(self, event):\n \"\"\"the press mouse button in zoom to rect mode callback\"\"\"\n # If we're already in the middle of a zoom, pressing another\n # button works to \"cancel\"\n if self._ids_zoom != []:\n for zoom_id in self._ids_zoom:\n self.canvas.mpl_disconnect(zoom_id)\n self.release(event)\n self.draw()\n self._xypress = None\n self._button_pressed = None\n self._ids_zoom = []\n return\n\n if event.button == 1:\n self._button_pressed = 1\n elif event.button == 3:\n self._button_pressed = 3\n else:\n self._button_pressed = None\n return\n\n x, y = event.x, event.y\n\n # push the current view to define home if stack is empty\n if self._views.empty():\n self.push_current()\n\n self._xypress = []\n for i, a in enumerate(self.canvas.figure.get_axes()):\n if (x is not None and y is not None and a.in_axes(event) and\n a.get_navigate() and a.can_zoom()):\n self._xypress.append((x, y, a, i, a.viewLim.frozen(),\n a.transData.frozen()))\n\n id1 = self.canvas.mpl_connect('motion_notify_event', self.drag_zoom)\n id2 = self.canvas.mpl_connect('key_press_event',\n self._switch_on_zoom_mode)\n id3 = self.canvas.mpl_connect('key_release_event',\n self._switch_off_zoom_mode)\n\n self._ids_zoom = id1, id2, id3\n self._zoom_mode = event.key\n\n self.press(event)\n def drag_zoom(self, event):\n \"\"\"the drag callback in zoom mode\"\"\"\n\n if self._xypress:\n x, y = event.x, event.y\n lastx, lasty, a, ind, lim, trans = self._xypress[0]\n\n # adjust x, last, y, last\n x1, y1, x2, y2 = a.bbox.extents\n x, lastx = max(min(x, lastx), x1), min(max(x, lastx), x2)\n y, lasty = max(min(y, lasty), y1), min(max(y, lasty), y2)\n\n if self._zoom_mode == \"x\":\n x1, y1, x2, y2 = a.bbox.extents\n y, lasty = y1, y2\n elif self._zoom_mode == \"y\":\n x1, y1, x2, y2 = a.bbox.extents\n x, lastx = x1, x2\n\n self.draw_rubberband(event, x, y, lastx, lasty)\n def release_zoom(self, event):\n \"\"\"the release mouse button callback in zoom to rect mode\"\"\"\n for zoom_id in self._ids_zoom:\n self.canvas.mpl_disconnect(zoom_id)\n self._ids_zoom = []\n\n if not self._xypress:\n return\n\n last_a = []\n\n for cur_xypress in self._xypress:\n x, y = event.x, event.y\n lastx, lasty, a, ind, lim, trans = cur_xypress\n # ignore singular clicks - 5 pixels is a threshold\n if abs(x - lastx) < 5 or abs(y - lasty) < 5:\n self._xypress = None\n self.release(event)\n self.draw()\n return\n\n x0, y0, x1, y1 = lim.extents\n\n # zoom to rect\n inverse = a.transData.inverted()\n lastx, lasty = inverse.transform_point((lastx, lasty))\n x, y = inverse.transform_point((x, y))\n Xmin, Xmax = a.get_xlim()\n Ymin, Ymax = a.get_ylim()\n\n # detect twinx,y axes and avoid double zooming\n twinx, twiny = False, False\n if last_a:\n for la in last_a:\n if a.get_shared_x_axes().joined(a, la):\n twinx = True\n if a.get_shared_y_axes().joined(a, la):\n twiny = True\n last_a.append(a)\n\n if twinx:\n x0, x1 = Xmin, Xmax\n else:\n if Xmin < Xmax:\n if x < lastx:\n x0, x1 = x, lastx\n else:\n x0, x1 = lastx, x\n if x0 < Xmin:\n x0 = Xmin\n if x1 > Xmax:\n x1 = Xmax\n else:\n if x > lastx:\n x0, x1 = x, lastx\n else:\n x0, x1 = lastx, x\n if x0 > Xmin:\n x0 = Xmin\n if x1 < Xmax:\n x1 = Xmax\n\n if twiny:\n y0, y1 = Ymin, Ymax\n else:\n if Ymin < Ymax:\n if y < lasty:\n y0, y1 = y, lasty\n else:\n y0, y1 = lasty, y\n if y0 < Ymin:\n y0 = Ymin\n if y1 > Ymax:\n y1 = Ymax\n else:\n if y > lasty:\n y0, y1 = y, lasty\n else:\n y0, y1 = lasty, y\n if y0 > Ymin:\n y0 = Ymin\n if y1 < Ymax:\n y1 = Ymax\n\n if self._button_pressed == 1:\n if self._zoom_mode == \"x\":\n a.set_xlim((x0, x1))\n elif self._zoom_mode == \"y\":\n a.set_ylim((y0, y1))\n else:\n a.set_xlim((x0, x1))\n a.set_ylim((y0, y1))\n elif self._button_pressed == 3:\n if a.get_xscale() == 'log':\n alpha = np.log(Xmax / Xmin) / np.log(x1 / x0)\n rx1 = pow(Xmin / x0, alpha) * Xmin\n rx2 = pow(Xmax / x0, alpha) * Xmin\n else:\n alpha = (Xmax - Xmin) / (x1 - x0)\n rx1 = alpha * (Xmin - x0) + Xmin\n rx2 = alpha * (Xmax - x0) + Xmin\n if a.get_yscale() == 'log':\n alpha = np.log(Ymax / Ymin) / np.log(y1 / y0)\n ry1 = pow(Ymin / y0, alpha) * Ymin\n ry2 = pow(Ymax / y0, alpha) * Ymin\n else:\n alpha = (Ymax - Ymin) / (y1 - y0)\n ry1 = alpha * (Ymin - y0) + Ymin\n ry2 = alpha * (Ymax - y0) + Ymin\n\n if self._zoom_mode == \"x\":\n a.set_xlim((rx1, rx2))\n elif self._zoom_mode == \"y\":\n a.set_ylim((ry1, ry2))\n else:\n a.set_xlim((rx1, rx2))\n a.set_ylim((ry1, ry2))\n\n self.draw()\n self._xypress = None\n self._button_pressed = None\n\n self._zoom_mode = None\n\n self.push_current()\n self.release(event)\n def _switch_on_zoom_mode(self, event):\n self._zoom_mode = event.key\n self.mouse_move(event)\n def _switch_off_zoom_mode(self, event):\n self._zoom_mode = None\n self.mouse_move(event)\n\n\n # GUI\n def _init_toolbar(self):\n \"\"\"\n This is where you actually build the GUI widgets (called by\n __init__). The icons ``home.xpm``, ``back.xpm``, ``forward.xpm``,\n ``hand.xpm``, ``zoom_to_rect.xpm`` and ``filesave.xpm`` are standard\n across backends (there are ppm versions in CVS also).\n\n You just need to set the callbacks\n\n home : self.home\n back : self.back\n forward : self.forward\n hand : self.pan\n zoom_to_rect : self.zoom\n filesave : self.save_figure\n\n You only need to define the last one - the others are in the base\n class implementation.\n\n \"\"\"\n raise NotImplementedError\n def set_message(self, s): pass\n def draw_rubberband(self, event, x0, y0, x1, y1): pass\n def save_figure(self, *args): raise NotImplementedError\n def set_cursor(self, cursor): pass\n def set_history_buttons(self): pass\n # Draw the canvas when idle\n def dynamic_update(self): pass\n\n\n # Undo/Redo\n def back(self, *args):\n \"\"\"move back up the view lim stack\"\"\"\n self._views2.back()\n self._views.back()\n self._positions.back()\n self.set_history_buttons()\n self._update_view()\n def forward(self, *args):\n \"\"\"Move forward in the view lim stack\"\"\"\n self._views2.forward()\n self._views.forward()\n self._positions.forward()\n self.set_history_buttons()\n self._update_view()\n def home(self, *args):\n \"\"\"Restore the original view\"\"\"\n self._views2.home()\n self._views.home()\n self._positions.home()\n self.set_history_buttons()\n self._update_view()\n def push_current(self):\n \"\"\"push the current view limits and position onto the stack\"\"\"\n vws = []\n lims = []\n pos = []\n for a in self.canvas.figure.get_axes():\n a2 = self.Winst.get_adapter(a)\n vws.append(a2.view_to_tuple())\n xmin, xmax = a.get_xlim()\n ymin, ymax = a.get_ylim()\n lims.append((xmin, xmax, ymin, ymax))\n # Store both the original and modified positions\n pos.append((\n a.get_position(True).frozen(),\n a.get_position().frozen()))\n self._views2.push(vws)\n self._views.push(lims)\n self._positions.push(pos)\n self.set_history_buttons()\n # Reset the stack\n def update(self):\n self._views2.clear()\n self._views.clear()\n self._positions.clear()\n self.set_history_buttons()\n # Set the view from current stack position\n def _update_view(self):\n wvs = self._views2()\n if wvs is None:\n return\n lims = self._views()\n if lims is None:\n return\n pos = self._positions()\n if pos is None:\n return\n for i, a in enumerate(self.canvas.figure.get_axes()):\n a2 = self.Winst.get_adapter(a)\n a2.view_from_tuple(wvs[i])\n xmin, xmax, ymin, ymax = lims[i]\n a.set_xlim((xmin, xmax))\n a.set_ylim((ymin, ymax))\n # Restore both the original and modified positions\n a.set_position(pos[i][0], 'original')\n a.set_position(pos[i][1], 'active')\n\n self.canvas.draw_idle()\n\n\n def debug(self, *args):\n self.Winst.print_debug()\n\n #TODO: in this case can just replace calls here with self.canvas.draw_idle()\n def draw(self):\n \"\"\"Redraw the canvases, update the locators\"\"\"\n for a in self.canvas.figure.get_axes():\n xaxis = getattr(a, 'xaxis', None)\n yaxis = getattr(a, 'yaxis', None)\n locators = []\n if xaxis is not None:\n locators.append(xaxis.get_major_locator())\n locators.append(xaxis.get_minor_locator())\n if yaxis is not None:\n locators.append(yaxis.get_major_locator())\n locators.append(yaxis.get_minor_locator())\n\n for loc in locators:\n loc.refresh()\n self.canvas.draw_idle()\n\n\n\n\nclass NavigationToolbar2TkAgg(NavigationToolbar2, Tk.Frame):\n \"\"\"\n Public attributes\n\n canvas - the FigureCanvas (gtk.DrawingArea)\n win - the gtk.Window\n \"\"\"\n def __init__(self, canvas, window, Winst):\n self.canvas = canvas\n self.window = window\n self._idle = True\n #Tk.Frame.__init__(self, master=self.canvas._tkcanvas)\n NavigationToolbar2.__init__(self, canvas, Winst)\n\n def destroy(self, *args):\n del self.message\n Tk.Frame.destroy(self, *args)\n\n def set_message(self, s):\n self.message.set(s)\n\n def draw_rubberband(self, event, x0, y0, x1, y1):\n height = self.canvas.figure.bbox.height\n y0 = height-y0\n y1 = height-y1\n try: self.lastrect\n except AttributeError: pass\n else: self.canvas._tkcanvas.delete(self.lastrect)\n self.lastrect = self.canvas._tkcanvas.create_rectangle(x0, y0, x1, y1)\n\n #self.canvas.draw()\n\n def release(self, event):\n try: self.lastrect\n except AttributeError: pass\n else:\n self.canvas._tkcanvas.delete(self.lastrect)\n del self.lastrect\n\n def set_cursor(self, cursor):\n self.window.configure(cursor=cursord[cursor])\n #self.window.configure(cursor=\"tcross\")\n\n def _Button(self, text, file, command, extension='.ppm'):\n img_file = os.path.join(rcParams['datapath'], 'images', file + extension)\n im = Tk.PhotoImage(master=self, file=img_file)\n b = Tk.Button(\n master=self, text=text, padx=2, pady=2, image=im, command=command)\n b._ntimage = im\n b.pack(side=Tk.LEFT)\n return b\n\n def _init_toolbar(self):\n xmin, xmax = self.canvas.figure.bbox.intervalx\n height, width = 50, xmax-xmin\n Tk.Frame.__init__(self, master=self.window,\n width=int(width), height=int(height),\n borderwidth=2)\n\n self.update() # Make axes menu\n\n for text, tooltip_text, image_file, callback in self.toolitems:\n if text is None:\n # spacer, unhandled in Tk\n pass\n else:\n button = self._Button(text=text, file=image_file,\n command=getattr(self, callback))\n if tooltip_text is not None:\n ToolTip.createToolTip(button, tooltip_text)\n\n self.message = Tk.StringVar(master=self)\n self._message_label = Tk.Label(master=self, textvariable=self.message)\n self._message_label.pack(side=Tk.RIGHT)\n self.pack(side=Tk.BOTTOM, fill=Tk.X)\n\n\n def configure_subplots(self):\n toolfig = Figure(figsize=(6,3))\n window = Tk.Tk()\n canvas = FigureCanvasTkAgg(toolfig, master=window)\n toolfig.subplots_adjust(top=0.9)\n tool = SubplotTool(self.canvas.figure, toolfig)\n canvas.show()\n canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)\n\n def save_figure(self, *args):\n import tkFileDialog\n import tkMessageBox\n filetypes = self.canvas.get_supported_filetypes().copy()\n default_filetype = self.canvas.get_default_filetype()\n\n # Tk doesn't provide a way to choose a default filetype,\n # so we just have to put it first\n default_filetype_name = filetypes[default_filetype]\n del filetypes[default_filetype]\n\n sorted_filetypes = list(six.iteritems(filetypes))\n sorted_filetypes.sort()\n sorted_filetypes.insert(0, (default_filetype, default_filetype_name))\n\n tk_filetypes = [\n (name, '*.%s' % ext) for (ext, name) in sorted_filetypes]\n\n # adding a default extension seems to break the\n # asksaveasfilename dialog when you choose various save types\n # from the dropdown. Passing in the empty string seems to\n # work - JDH!\n #defaultextension = self.canvas.get_default_filetype()\n defaultextension = ''\n initialdir = rcParams.get('savefig.directory', '')\n initialdir = os.path.expanduser(initialdir)\n initialfile = self.canvas.get_default_filename()\n fname = tkFileDialog.asksaveasfilename(\n master=self.window,\n title='Save the figure',\n filetypes=tk_filetypes,\n defaultextension=defaultextension,\n initialdir=initialdir,\n initialfile=initialfile,\n )\n\n if fname == \"\" or fname == ():\n return\n else:\n if initialdir == '':\n # explicitly missing key or empty str signals to use cwd\n rcParams['savefig.directory'] = initialdir\n else:\n # save dir for next time\n rcParams['savefig.directory'] = os.path.dirname(six.text_type(fname))\n try:\n # This method will handle the delegation to the correct type\n self.canvas.print_figure(fname)\n except Exception as e:\n tkMessageBox.showerror(\"Error saving file\", str(e))\n\n def set_active(self, ind):\n self._ind = ind\n self._active = [ self._axes[i] for i in self._ind ]\n\n def update(self):\n _focus = windowing.FocusManager()\n self._axes = self.canvas.figure.axes\n naxes = len(self._axes)\n #if not hasattr(self, \"omenu\"):\n # self.set_active(range(naxes))\n # self.omenu = AxisMenu(master=self, naxes=naxes)\n #else:\n # self.omenu.adjust(naxes)\n NavigationToolbar2.update(self)\n\n def dynamic_update(self):\n 'update drawing area only if idle'\n # legacy method; new method is canvas.draw_idle\n self.canvas.draw_idle()\n\n def axis_menu(self, event):\n \"\"\"Show a popup menu to choose the axis\"\"\"\n pmenu = Tk.Menu(self)\n\n x = event.guiEvent.x_root\n y = event.guiEvent.y_root\n\n a = self._last_axis\n a2 = self.Winst.get_adapter(a)\n\n for i in range(3):\n axes_string = WM.MINOR_AXES[i][0]+WM.MINOR_AXES[i][1]\n # Calling the redraw is necessary *immediately*,\n # a bug with with internal state variables or event handling..?\n def f (i=i):\n a2.change_projection(i)\n self.dynamic_update()\n pmenu.add_command(label=axes_string, compound=Tk.LEFT, command=f)\n\n pmenu.tk_popup(int(x),int(y),0)\n\n def sources_menu(self, event):\n \"\"\"Show a popup menu to choose the WM sources\"\"\"\n select_sources_menu = Tk.Menu(self)\n\n x = event.guiEvent.x_root\n y = event.guiEvent.y_root\n\n source_menu = []\n for i in range(len(self.Winst.sources)):\n source_menu.append(Tk.Menu(self, tearoff=0))\n select_sources_menu.add_cascade(label=str(i), menu=source_menu[-1])\n for j in range(len(self.Winst.all_sources)):\n def f (i=i,j=j):\n self.Winst.change_source(i,j)\n self.canvas.draw_idle()\n source_menu[-1].add_radiobutton(label=str(j)+\" (\"+str(self.Winst.all_sources[j])+\")\", command=f )\n\n select_sources_menu.tk_popup(int(x),int(y),0)\n\n def view_menu(self, event):\n \"\"\"Show a popup menu to choose the WM view\"\"\"\n smenu = Tk.Menu(self)\n\n x = event.guiEvent.x_root\n y = event.guiEvent.y_root\n\n a = self._last_axis\n a2 = self.Winst.get_adapter(a)\n\n wm_views = WM.TEMPLATES.keys()\n for i,wm_view in zip(range(len(wm_views)),wm_views):\n def f (wm_view=wm_view,a=a):\n self.Winst.change_template(wm_view, a)\n self.canvas.draw()\n smenu.add_command(label=wm_view, compound=Tk.LEFT, command=f)\n\n smenu.tk_popup(int(x),int(y),0)\n\n def source_menu(self, event):\n \"\"\"Show a popup menu to choose the view's image source\"\"\"\n smenu = Tk.Menu(self)\n\n x = event.guiEvent.x_root\n y = event.guiEvent.y_root\n\n a = self._last_axis\n a2 = self.Winst.get_adapter(a)\n\n sources = self.Winst.get_sources()\n for i,source in zip(range(len(sources)),sources):\n def f (i=i):\n a2.change_source(i)\n self.canvas.draw()\n smenu.add_command(label=str(i)+\" (\"+str(source)+\")\", compound=Tk.LEFT, command=f)\n\n smenu.tk_popup(int(x),int(y),0)\n\n\nFigureCanvas = FigureCanvasTkAgg\nFigureManager = FigureManagerTkAgg","sub_path":"custom_toolbar.py","file_name":"custom_toolbar.py","file_ext":"py","file_size_in_byte":33336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"555430122","text":"import random\nimport time\n\nfrom app.effects import Effect, StateEffect\nfrom app.lib.misc import map_to_range\n\nfrom . import BasicDMX\n\n\nclass DeadCoastingStateEffect(StateEffect):\n FUNCTIONS = ['speed', 'dim']\n\n def __init__(self, speed=5, dim=20, delay=2, dim_duration=1, move_duration=8, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.speed = speed\n self.dim = dim\n self.delay = delay\n self.dim_duration = dim_duration\n self.move_duration = move_duration\n\n def applicable(self, light, data):\n return (data.get('dead_for') or 0) > self.delay\n\n def apply(self, light, data):\n light.auto_state['speed'] = self.speed\n light.add_effect('dim', Effect(light.auto_state['dim'], self.dim, self.dim_duration), overwrite=True)\n\n def run(self, light, data):\n light.add_effect('pan', Effect(random.randint(0, 255), None, 8))\n light.add_effect('tilt', Effect(random.randint(0, 255), None, 8))\n if hasattr(light, '_get_dead_coasting_effects'):\n for k, e in light._get_dead_coasting_effects().items():\n light.add_effect(k, e)\n\n\nclass IdleCoastingStateEffect(StateEffect):\n FUNCTIONS = ['speed']\n\n def __init__(self, speed=31, delay=2, move_duration=5, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.speed = speed\n self.delay = delay\n self.move_duration = move_duration\n\n def applicable(self, light, data):\n idle_pan_tilt = time.time() - max(light.last_function['pan'], light.last_function['tilt']) >= self.delay\n return data.get('audio_v_sum') and idle_pan_tilt\n\n def apply(self, light, data):\n light.auto_state['speed'] = self.speed\n\n def run(self, light, data):\n light.add_effect('pan', Effect(random.randint(0, 255), None, self.move_duration))\n light.add_effect('tilt', Effect(random.randint(0, 255), None, self.move_duration))\n\n\nclass IdleFadeoutStateEffect(StateEffect):\n FUNCTIONS = ['dim']\n\n def __init__(self, delay=0.25, dim_duration=0.5, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.delay = delay\n self.dim_duration = dim_duration\n # self.applied = None\n\n def applicable(self, light, data):\n # if self.applied and time.time() - self.applied > self.dim_duration:\n # return False\n return (data.get('idle_for') or 0) > self.delay\n\n def apply(self, light, data):\n light.add_effect('dim', Effect(light.auto_state['dim'], 0, self.dim_duration), overwrite=True)\n # self.applied = time.time()\n\n # def unapply(self, light, data):\n # super().unapply(light, data)\n # self.applied = None\n\n\nclass MovingHeadMixin:\n \"\"\"\\\n Basic moving head light.\n \"\"\"\n\n # Probably should adjust these per light\n SPEEDS = {\n 'pan': (25, 1),\n 'tilt': (10, 0.5),\n }\n\n def _get_dead_coasting_effects(self):\n return {}\n\n def get_state_effects(self):\n return [DeadCoastingStateEffect(), IdleCoastingStateEffect(), IdleFadeoutStateEffect()]\n\n\nclass TomshineMovingHead6in1(MovingHeadMixin, BasicDMX):\n FUNCTIONS = {\n 'pan': 1,\n 'pan_fine': 2,\n 'tilt': 3,\n 'tilt_fine': 4,\n 'speed': 5,\n 'dim': 6,\n 'strobe': 7,\n 'red': 8,\n 'green': 9,\n 'blue': 10,\n 'white': 11,\n 'amber': 12,\n 'uv': 13,\n 'mode': 14,\n 'motor_sens': 15,\n 'effect': 16,\n 'led_sens': 17,\n 'reset': 18,\n }\n\n RATES = {\n 'pan': 0.75,\n 'tilt': 0.75,\n 'color': 0.125,\n 'strobe': 10,\n 'dim': 0.125,\n }\n\n INITIALIZE = {\n 'dim': 255,\n # 'dim': 80,\n 'speed': 255,\n # 'uv': 255,\n }\n\n INVERT = ['speed']\n CLEAR_EFFECTS_ON_NEW_STATE = ['pan', 'tilt', 'speed', 'dim', 'uv', 'white', 'amber']\n RESET_ON_NEW_STATE = ['speed', 'dim']\n MULTI_PROP_MAP = {'color': ['red', 'green', 'blue']}\n\n def _get_dead_coasting_effects(self):\n return {\n 'color': Effect(\n (self.auto_state['red'], self.auto_state['green'], self.auto_state['blue'],),\n self.map_color(None, 1, 0),\n 2\n )\n }\n\n def _map_pan_tilt(self, function, value, threshold):\n if value < threshold:\n return\n cur_value = self.auto_state[function]\n distance = int(map_to_range(value, threshold) * (max(cur_value, 255 - cur_value)))\n choices = [\n min(cur_value + distance, 255),\n max(cur_value - distance, 0),\n ]\n return random.choice(choices)\n\n def map_pan(self, trigger, value, threshold):\n return self._map_pan_tilt('pan', value, threshold)\n\n def map_tilt(self, trigger, value, threshold):\n return self._map_pan_tilt('tilt', value, threshold)\n\n def map_color(self, trigger, value, threshold):\n if trigger == 'frequency_all':\n if not isinstance(value[0], list):\n # Raw bins\n bins_per = int(len(value) / 3)\n temp_value = []\n for offset in (0, bins_per, bins_per * 2):\n bucket = []\n for idx in range(offset, offset + bins_per):\n bucket.append(value[idx])\n value = temp_value\n\n out = []\n colors = ('red', 'green', 'blue')\n for color, bins in zip(colors, value[:3]):\n newvalue = max(bins)\n if newvalue > threshold:\n out.append(int(newvalue * 255))\n else:\n out.append(0)\n if sum(out):\n # Try to create an effect to fade to the next color, always return something if there's data\n curr = (self.auto_state['red'], self.auto_state['green'], self.auto_state['blue'])\n self.add_effect('color', Effect(curr, out, 0.25))\n # return curr\n return None\n\n if value < threshold:\n return\n\n if trigger == 'pitch':\n return int((value / 128) * 255), 0, 0\n\n old_rgb = [self.auto_state[k] for k in ('red', 'green', 'blue')]\n diff = 0\n while diff < 0.25:\n rgb = [random.randint(0, 256) for _ in range(3)]\n diff = sum((abs(rgb[i] - old_rgb[i]) / 256 for i in range(3))) / 3\n return rgb\n\n # def map_color(self, trigger, value, threshold):\n # if value >= threshold:\n # half_color = random.random() > 0.75\n # if half_color:\n # return random.randint(57, 127)\n # return random.randint(0, 56)\n\n # def map_gobo(self, trigger, value, threshold):\n # if value >= threshold:\n # dither = random.random() > 0.75\n # if dither:\n # return random.randint(64, 127)\n # return random.randint(0, 63)\n\n def map_strobe(self, trigger, value, threshold):\n return None\n # should set a high threshold for this\n if value > threshold and self.last_function['strobe'] + self.RATES.get('strobe', 0) < time.time():\n # TODO: might need a different value for some lights\n self.add_effect('strobe', Effect(255, 255, 1, 0))\n # Because this is not applied normally...\n self.last_function['strobe'] = time.time()\n\n # 'dim': 6,\n # 'red': 8,\n # 'green': 9,\n # 'blue': 10,\n # 'white': 11,\n # 'amber': 12,\n # 'uv': 13,\n","sub_path":"server/app/outputs/dmxfixtures/movinghead.py","file_name":"movinghead.py","file_ext":"py","file_size_in_byte":7541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"392648280","text":"# Instructions to run file\n# 1) Open terminal and go to the directory in which this file exists\n# 2) In the terminal, type: set FLASK_APP=hello.py\n# 3) In the terminal, type: flask run\n\nfrom flask import Flask, Response, request, jsonify\nfrom flask_cors import CORS\n\napp = Flask(__name__)\nCORS(app)\n\n@app.route('/', methods=['POST', 'GET'])\ndef hello_world():\n # return 'Hello, World!'\n return jsonify({\"data\": \"Hello World\"})\n\n@app.route('/analyze', methods=['POST', 'GET'])\ndef second():\n param = request.args.get('values')\n param = int(param)\n val = param + 20\n\n return jsonify({\"data\": val})\n\n\n\n\n","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"379420393","text":"import boto3\nfrom base64 import b64decode\nfrom urllib.parse import parse_qs\n\n# Replace your email address here\nsend_to = 'your_email_address_here'\n\ndef lambda_handler(event, context):\n # We receive our data through POST requests. API gateway\n # sends the POST data as a Base64 encoded string in\n # event['body'], so we must decode it.\n data = parse_qs(b64decode(event['body']).decode())\n\n subject = 'You got a message from %s' % data['email'][0]\n text = '\\n'.join([\n 'Name: %s' % data['name'][0],\n 'Email: %s' % data['email'][0],\n 'Message %s' % data['message'][0]\n ])\n\n # Send an email through SES with the SendEmail API\n client = boto3.client('ses', region_name='us-east-1')\n client.send_email(\n Source=send_to,\n Destination={'ToAddresses': [send_to]},\n Message={\n 'Subject': {'Data': subject},\n 'Body': {'Text': {'Data': text}}\n },\n ReplyToAddresses=[data['email'][0]]\n )\n\n # This is the response that'll be sent out through the\n # API gateway to the browser.\n return {\n 'statusCode': 200,\n 'headers': {\n 'Access-Control-Allow-Origin': '*'\n },\n 'body': '\"Success\"' # jquery expects a JSON response\n }\n","sub_path":"lamda-script.py","file_name":"lamda-script.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"137253291","text":"import csv\nimport cv2\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Flatten, Dense, Lambda, Cropping2D, Activation, Convolution2D\n\n\nlines = []\nwith open('driving_log.csv') as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n lines.append(line)\n\nimages = []\nimagesCenter = []\nimagesLeft = []\nimagesRight = []\nmeasurements = []\ncorrection = 0.002\nfor line in lines:\n source_pathCenter = line[0]\n source_pathLeft = line[1]\n source_pathRight = line[2]\n \n filenameCenter = source_pathCenter.split('/')[-1] \n filenameLeft = source_pathLeft.split('/')[-1] \n filenameRight = source_pathRight.split('/')[-1] \n \n imagesCenter = cv2.imread(filenameCenter)\n imagesLeft = cv2.imread(filenameLeft)\n imagesRight = cv2.imread(filenameRight)\n \n \n images.append(imagesCenter)\n images.append(imagesLeft)\n images.append(imagesRight)\n \n measurement = float(line[3])\n measurements.append(measurement)\n measurements.append(measurement+correction)\n measurements.append(measurement-correction)\n \nX_train = np.array(images)\nY_train = np.array(measurements)\n\n\n#Build the NN\nmodel = Sequential()\nmodel.add(Lambda(lambda x:x /255.0 - 0.5, input_shape = (160, 320, 3)))\nmodel.add(Cropping2D(cropping = ((70,25), (0,0))))\nmodel.add(Convolution2D(24,5,5, subsample = (2,2), border_mode = \"valid\", init = 'he_normal'))\nmodel.add(Activation('relu'))\nmodel.add(Convolution2D(36,5,5, subsample = (2,2), border_mode = \"valid\", init = 'he_normal'))\nmodel.add(Activation('relu'))\nmodel.add(Convolution2D(48,5,5, subsample = (2,2), border_mode = \"valid\", init = 'he_normal'))\nmodel.add(Activation('relu'))\nmodel.add(Convolution2D(64,3,3, subsample = (1,1), border_mode = \"valid\", init = 'he_normal'))\nmodel.add(Activation('relu'))\nmodel.add(Convolution2D(64,3,3, subsample = (1,1), border_mode = \"valid\", init = 'he_normal'))\nmodel.add(Activation('relu'))\nmodel.add(Flatten())\nmodel.add(Dense(1164, init = 'he_normal'))\nmodel.add(Activation('relu'))\nmodel.add(Dense(100, init = 'he_normal'))\nmodel.add(Activation('relu'))\nmodel.add(Dense(50, init = 'he_normal'))\nmodel.add(Activation('relu'))\nmodel.add(Dense(10, init = 'he_normal'))\nmodel.add(Activation('relu'))\nmodel.add(Dense(1, init = 'he_normal'))\nmodel.compile(loss = 'mse', optimizer ='adam')\n\nmodel.fit(X_train, Y_train, validation_split = 0.2, shuffle = True, nb_epoch = 5)\nmodel.save('model.h5')","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"52361119","text":"class RomanNumeralConverter(object):\n\tglobal append_numerals #don't know why this is necessary but it only works when this is here\n\n\tdef __init__(self):\n\t\tself.arabics = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]\n\t\tself.romans = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']\n\t\tself.roman = ''\n\t\t\n\tdef convert(self, arabic):\n\t\tfor i in range(0, len(self.arabics)):\n\t\t\tarabic = append_numerals(self, arabic, self.arabics[i], self.romans[i])\n\n\t\treturn self.roman\n\n\tdef append_numerals(self, current_value, arabic_number, roman_letters):\n\t\twhile (current_value >= arabic_number):\n\t\t\tself.roman += roman_letters\n\t\t\tcurrent_value -= arabic_number\n\n\t\treturn current_value","sub_path":"src/rn.py","file_name":"rn.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"101075881","text":"import numpy as np\n\ndef save_do_dipha(img_data, filename):\n \n \"\"\"\n save matrix data to dipha format \n img_data: numpy array\n filename: path to output file\n \"\"\"\n #import numpy as np\n num = np.array(8067171840).astype('int64') #magic dipha number\n fid = np.array(1).astype('int64') #another magic dipha number\n numel= np.array(img_data.size).astype('int64') #number of elements in array\n dim = np.array(len(img_data.shape)).astype('int64') # dimension of numpy array\n imshape = np.array(img_data.shape).astype('int64') # shape of numpy array\n data = img_data.reshape(-1, order = 'F').astype('float64') #data in x-fastest order\n \n with open(filename, 'wb') as f:\n num.tofile(f)\n fid.tofile(f)\n numel.tofile(f)\n dim.tofile(f)\n imshape.tofile(f)\n data.tofile(f)\n f.close()\n print('Image was saved to dipha compatible format with name '+filename)\n return 0\n\ndef read_PD_dipha(dgmfile):\n \"\"\"\n load dipha persistence diagram to numpy arrays\n dgmfile: dipha file with PD\n \"\"\"\n import numpy as np\n fd = open(dgmfile,'rb') \n dipha_identifier, dgm_identifier = np.fromfile(fd, dtype = 'int', count = 2)\n fd.seek(16)\n num_pairs = np.fromfile(fd, dtype = 'int', count = 1).astype('int')\n fd.seek(24)\n dt = np.dtype(\"i8, f8, f8\")\n whole_array = np.fromfile(fd, dtype = dt, count = num_pairs[0])\n fd.close()\n dims,birth,death = zip(*whole_array)\n dims = np.array(dims)\n birth = np.array(birth)\n death = np.array(death)\n return (dims,birth,death)\ndef run_dipha(dipha_img_path, dipha_dir):\n import numpy as np\n import subprocess\n dipha_res = subprocess.run(['mpiexec',\n '-n',\n '4',\n dipha_dir,\n dipha_img_path,\n dipha_img_path + '.dgm'])\n print(dipha_res)\n return 0 \n ","sub_path":"dipha_utils.py","file_name":"dipha_utils.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"225116083","text":"\"\"\" Finviz View \"\"\"\n__docformat__ = \"numpy\"\n\n\nimport io\nimport logging\n\nfrom PIL import Image\n\nfrom openbb_terminal import OpenBBFigure\nfrom openbb_terminal.decorators import log_start_end\nfrom openbb_terminal.stocks.technical_analysis import finviz_model\n\nlogger = logging.getLogger(__name__)\n\n\n@log_start_end(log=logger)\ndef view(symbol: str, external_axes: bool = False):\n \"\"\"View finviz image for ticker\n\n Parameters\n ----------\n symbol: str\n Stock ticker symbol\n external_axes: bool, optional\n Whether to return the figure object or not, by default False\n \"\"\"\n\n image_data = finviz_model.get_finviz_image(symbol)\n dataBytesIO = io.BytesIO(image_data)\n im = Image.open(dataBytesIO)\n fig = OpenBBFigure()\n fig.add_layout_image(\n dict(\n source=im,\n xref=\"x\",\n yref=\"y\",\n x=0,\n y=1,\n sizex=im.width,\n sizey=im.height,\n sizing=\"stretch\",\n )\n )\n fig.update_xaxes(visible=False, range=[0, im.width])\n fig.update_yaxes(visible=False, range=[im.height, 0], scaleanchor=\"y\")\n fig.update_layout(height=im.height, width=im.width)\n\n return fig.show(external=external_axes)\n","sub_path":"openbb_terminal/stocks/technical_analysis/finviz_view.py","file_name":"finviz_view.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"153222048","text":"\"\"\"\nтестовая версия клиента, подвергается частым изменениям\nобкатываются возможности ввода своих данных и p2p-соединения с изменением настроек подключения\n\nреализуется возможность работы со специальными командами программы(выход,отключение,посыл спец сообщений)\n\"\"\"\n\nimport socket\nimport time\n\ndef test_message(mes):\n if mes[0] == '/':\n if mes[1:] == 'stop':\n sock.close()\n print('Connection closed')\n elif mes[1:] == 'reconnect':\n sock.connect((ip_con, 9090))\n print('Reconnected to ',ip_con)\n elif mes[1:] == 'help':\n print('In development')\n else:\n print('Unknow kommand! Enter /help for instructions and ABOUT')\n else:\n return mes\n\n\nsock = socket.socket()\nip_con = input('Which server you want connect? Enter 0 (null) if you want connect to LOCALHOST')\nif ip_con[0] == '0':\n ip_con = 'localhost'\n\nsock.connect((ip_con, 9090))\nprint(\"Press ENTER to send message\")\n\nwhile True:\n stock = input()\n test_message(stock)\n s_data = stock.encode()\n sock.send(s_data)\n data = sock.recv(16384)\n udata = data.decode(\"utf-8\")\n print (udata,time.strftime('%H.%M.%S %d/%m/%y'))","sub_path":"chat-clientCOPY.py","file_name":"chat-clientCOPY.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"330230647","text":"import time\nimport subprocess\nimport shlex\nimport string\nimport random\nfrom uuid import uuid1\nimport os\nimport pyqrcode\nimport config\nimport hashlib\n\nstring_pool = string.ascii_letters + string.digits\ngen_random_text = lambda s: ''.join(map(lambda _: random.choice(string_pool), range(s)))\n\n\ndef timestamp():\n return int(time.time())\n\n\ndef run_command(cmd):\n args = shlex.split(cmd)\n subprocess.call(args)\n\n\ndef generate_uuid():\n return str(uuid1())\n\n\ndef gen_identity():\n if config.get_uuid() == \"\":\n uuid = generate_uuid()\n psw = gen_random_text(6)\n config.set_uuid_psw(uuid, psw)\n qrimg = os.path.join(config.PROJECT_DIR, config.get_identity_path())\n if not os.path.isfile(qrimg):\n gen_identity_img(qrimg)\n\n\ndef regen_identity():\n uuid = config.get_uuid()\n if uuid == \"\":\n uuid = generate_uuid()\n psw = gen_random_text(6)\n config.set_uuid_psw(uuid, psw)\n gen_identity_img()\n\n\ndef gen_identity_img(qrimg):\n\n json_str = str({'UUID': config.get_uuid(), 'PSW': config.get_psw()})\n qr = pyqrcode.create(json_str)\n qr.png(qrimg, scale=5)\n\n\ndef psw_salt(uuid, psw):\n md5 = hashlib.md5()\n pwbytes = (uuid+psw).encode('utf-8')\n md5.update(pwbytes)\n return md5.hexdigest()\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"40823571","text":"from flask import Flask, render_template, request, send_file\nfrom werkzeug.utils import secure_filename\nimport pandas as pd\nfrom geopy.geocoders import ArcGIS\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return render_template(\"index.html\")\n\n\n@app.route('/', methods=['POST'])\ndef success():\n global ufile\n global df\n if request.method == 'POST':\n ufile = request.files['file']\n if ufile.filename.lower().endswith('.csv'):\n df = pd.read_csv(ufile, encoding = \"ISO-8859-1\")\n if 'Address' in df.columns or 'address' in df.columns:\n if 'address' in df.columns and 'Address' not in df.columns:\n address = 'address'\n else:\n address = 'Address'\n df['Latitude'] = df[address].apply(ArcGIS().geocode).apply(\n lambda x: x.latitude if x != None else None)\n df['Longitude'] = df[address].apply(ArcGIS().geocode).apply(\n lambda x: x.longitude if x != None else None)\n return render_template(\"index.html\",\n tables=[\n df.to_html(classes='data',\n index=False,\n header=\"true\")\n ],\n btn=\"download.html\")\n else:\n return render_template(\"index.html\", wrong_file=\"wrong_file.html\")\n else:\n return render_template(\"index.html\", wrong_file=\"wrong_file.html\")\n\n@app.route('/download')\ndef download():\n df.to_csv(secure_filename(\"uploaded_\" + ufile.filename), index=False)\n return send_file(\"uploaded_\" + ufile.filename, attachment_filename=\"yourfile.csv\", as_attachment=True)\n\nif __name__ == \"__main__\":\n app.debug = True\n app.run(port=5001)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"308149368","text":"import unittest\nfrom polyhedral_analysis.coordination_polyhedron import CoordinationPolyhedron\nfrom polyhedral_analysis.atom import Atom\nfrom pymatgen.analysis.chemenv.coordination_environments.coordination_geometry_finder import AbstractGeometry\nfrom unittest.mock import Mock, MagicMock, patch, PropertyMock\nimport copy\nimport numpy as np\nfrom pymatgen.core.sites import Site\n\ndef mock_atom_lt( self, other ):\n return self.index < other.index\n\ndef mock_atom_eq( self, other ):\n return self.index == other.index\n\nclass TestCoordinationPolyhedronInit( unittest.TestCase ):\n\n def test_coordination_polyhedron_is_initialised( self ):\n mock_central_atom = Mock( spec=Atom )\n mock_central_atom.in_polyhedra = []\n mock_central_atom.index = 10\n mock_central_atom.label = 'Li'\n mock_vertices = [ Mock( spec=Atom ) for i in range(6) ]\n for i, v in enumerate( mock_vertices, 1 ):\n v.neighbours = None\n v.__lt__ = mock_atom_lt\n v.index = i\n v.in_polyhedra = []\n with patch( 'polyhedral_analysis.coordination_polyhedron.CoordinationPolyhedron.construct_edge_graph' ) as mock_construct_edge_graph:\n mock_construct_edge_graph.return_value = { 0: [ 1, 2, 3, 4 ],\n 1: [ 0, 2, 3, 5 ],\n 2: [ 0, 1, 3, 5 ],\n 3: [ 0, 2, 4, 5 ],\n 4: [ 0, 1, 3, 5 ],\n 5: [ 1, 2, 3, 4 ] }\n with patch( 'polyhedral_analysis.coordination_polyhedron.CoordinationPolyhedron.construct_abstract_geometry' ) as mock_construct_abstract_geometry:\n mock_construct_abstract_geometry.return_value = Mock( spec=AbstractGeometry )\n CoordinationPolyhedron( central_atom=mock_central_atom, \n vertices=mock_vertices )\n\nclass TestCoordinationPolyhedron( unittest.TestCase ):\n\n def setUp( self ):\n mock_central_atom = Mock( spec=Atom )\n mock_central_atom.in_polyhedra = []\n mock_central_atom.index = 0\n mock_central_atom.label = 'A'\n mock_central_atom.__eq__ = mock_atom_eq\n mock_vertices = [ Mock( spec=Atom ) for i in range(6) ]\n for i, v in enumerate( mock_vertices, 1 ):\n v.neighbours = None\n v.index = i\n v.__lt__ = mock_atom_lt\n v.__eq__ = mock_atom_eq\n v.in_polyhedra =[] \n with patch( 'polyhedral_analysis.coordination_polyhedron.CoordinationPolyhedron.construct_edge_graph' ) as mock_construct_edge_graph:\n mock_construct_edge_graph.return_value = { 0: [ 1, 2, 3, 4 ],\n 1: [ 0, 2, 3, 5 ],\n 2: [ 0, 1, 3, 5 ],\n 3: [ 0, 2, 4, 5 ],\n 4: [ 0, 1, 3, 5 ],\n 5: [ 1, 2, 3, 4 ] }\n with patch( 'polyhedral_analysis.coordination_polyhedron.CoordinationPolyhedron.construct_abstract_geometry' ) as mock_construct_abstract_geometry:\n mock_construct_abstract_geometry.return_value = Mock( spec=AbstractGeometry )\n self.coordination_polyhedron = CoordinationPolyhedron( \n central_atom=mock_central_atom,\n vertices=mock_vertices )\n\n def test_equal_members( self ):\n other_coordination_polyhedron = copy.deepcopy( self.coordination_polyhedron )\n other_coordination_polyhedron.vertices[0].neighbours = { 0: [ 1, 2, 3 ] }\n other_coordination_polyhedron.vertices[4].neighbours = { 4: [ 1, 3, 5 ] }\n self.assertTrue( self.coordination_polyhedron.equal_members(\n other_coordination_polyhedron ) )\n\n def test_vertex_vectors( self ):\n vectors = [ np.array( [ 1.0, 0.0, 0.0 ] ),\n np.array( [ 0.0, 1.0, 2.0 ] ) ]\n self.coordination_polyhedron.abstract_geometry.points_wocs_ctwocc.return_value = vectors\n returned_vectors = self.coordination_polyhedron.vertex_vectors\n for v1, v2 in zip( vectors, returned_vectors ):\n np.testing.assert_equal( v1, v2 )\n\n def test_angles( self ):\n vertex_vectors = np.array( [ [ 1.0, 0.0, 0.0 ],\n [ 0.0, 1.0, 0.0 ],\n [ 0.0, -1.0, 0.0 ] ] )\n with patch( 'polyhedral_analysis.coordination_polyhedron.CoordinationPolyhedron.vertex_vectors', new_callable=PropertyMock ) as mock_vertex_vectors:\n mock_vertex_vectors.return_value = vertex_vectors\n angles = self.coordination_polyhedron.angles()\n np.testing.assert_equal( angles, [ 90.0, 90.0, 180.0 ] )\n\n def test_vertex_distances( self ):\n mock_vertex_distances = [ 2.0, 1.0, 1.0, 1.0, 1.0, 1.5 ]\n self.coordination_polyhedron.central_atom.site = Mock( spec=Site )\n self.coordination_polyhedron.central_atom.site.distance = \\\n Mock( side_effect=mock_vertex_distances )\n for v in self.coordination_polyhedron.vertices:\n v.site = Mock( spec=Site )\n vertex_distances = self.coordination_polyhedron.vertex_distances()\n np.testing.assert_equal( vertex_distances, mock_vertex_distances )\n \n def test_vertex_distances_with_vertex_labels( self ):\n mock_vertex_distances = [ 2.0, 1.0, 1.0, 1.0, 1.0, 1.5 ]\n mock_labels = [ 'O', 'O', 'F', 'F', 'F', 'F' ]\n self.coordination_polyhedron.central_atom.site = Mock( spec=Site )\n self.coordination_polyhedron.central_atom.site.distance = \\\n Mock( side_effect=mock_vertex_distances )\n for v, mock_label in zip( self.coordination_polyhedron.vertices, mock_labels ):\n v.site = Mock( spec=Site )\n v.label = mock_label\n vertex_distances = self.coordination_polyhedron.vertex_distances( vertex_labels=True )\n np.testing.assert_equal( vertex_distances, \n list( zip( mock_vertex_distances, mock_labels ) ) )\n \nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"tests/test_coordination_polyhedron.py","file_name":"test_coordination_polyhedron.py","file_ext":"py","file_size_in_byte":6409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"246414218","text":"#!/usr/bin/python3\n\"\"\"\n Prints count of all searched for words in hot post titles.\n\"\"\"\n\n\nimport requests\n\n\ndef count_words(subreddit, word_list, hot_list=[], aft=None):\n \"\"\"\n Counts words in all hot post titles\n \"\"\"\n\n dic = {}\n for x in word_list:\n dic[x] = 0\n\n head = {\n 'User-Agent': 'Totally human'\n }\n\n response = requests.get('https://www.reddit.com/r/{}/hot.json?after={}'\n .format(subreddit, aft), headers=head)\n\n if (not response.status_code == 200 or\n not response.json().get('data').get('children')):\n return None\n\n aft = response.json().get('data').get('after')\n hot_list += [x.get('data').get('title') for x in\n [y for y in response.json().get('data').get('children')]]\n if aft:\n count_words(subreddit, word_list, hot_list, aft)\n else:\n for title in hot_list:\n for key in dic:\n dic[key] += title.lower().split(' ').count(key.lower())\n sort = [(v, k) for k, v in dic.items()]\n sort.sort(reverse=True)\n for v, k in sort:\n if v:\n print('{}: {}'.format(k, v))\n","sub_path":"0x16-api_advanced/100-count.py","file_name":"100-count.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"334504266","text":"\"\"\" A command that implements auto-completion of names in the search box. \"\"\"\n\n\nfrom traits.api import HasTraits\n\n\n# We get a new instance of each command every time, so we can't keep instance\n# state. I tried this as class state but it just looks uglier ;^)\n# The index of the next candidate.\ncandidate_index = 0\n\n# The candidate names.\ncandidate_names = []\n\n\nclass AbstractAutoComplete(HasTraits):\n \"\"\" The base class for the auto-complete commands.\n\n Do not use this command directly - use the derived classes.\n\n \"\"\"\n\n #### 'AutoComplete' *class* protocol #######################################\n\n # Gives the 'direction' of the auto-completion. Must be either 'next' or\n # 'previous' (and is set appropriately in the derived classes). We would\n # like this to be Enum('next', 'previous') maybe, but we can't have class\n # traits.\n direction = None\n\n #### 'object' protocol #####################################################\n\n def __call__(self, window):\n red = window.red\n \n global candidate_names, candidate_index\n\n # If we are NOT currently in auto-complete mode then we need to generate\n # a list of candidate names.\n if not self._in_auto_complete_mode(red):\n candidate_names = self._get_candidate_names(red)\n candidate_index = -1\n \n if len(candidate_names) > 0:\n if self.direction == 'next':\n candidate_index += 1\n if candidate_index > len(candidate_names) - 1:\n candidate_index = 0\n\n else:\n candidate_index -= 1\n if candidate_index < 0:\n candidate_index = len(candidate_names) - 1\n\n red.name = candidate_names[candidate_index]\n red.set_insertion_point_end()\n\n return\n\n #### Private protocol ######################################################\n\n def _get_candidate_names(self, red):\n \"\"\" Get the candidate names at the start of auto-complete mode. \"\"\"\n\n parent_name, filter = self._get_parent_name_and_filter(red.name)\n parent = red.lookup(parent_name)\n\n candidate_names = (\n self._get_filtered_child_names(parent, filter)\n\n if parent is not None else []\n )\n\n return candidate_names\n \n def _get_filtered_child_names(self, node, filter):\n \"\"\" Get the filtered child names of the given node. \"\"\"\n\n if filter is not None:\n candidate_names = [\n child.dotted_name for child in node.children\n\n if child.name.startswith(filter)\n ]\n\n else:\n candidate_names = [\n child.dotted_name for child in node.children\n ]\n\n return sorted(candidate_names)\n\n def _get_parent_name_and_filter(self, name):\n \"\"\" Get the parent name and the filter from the given name. \"\"\"\n\n # If the name ends with a period then we use *all* of the name before\n # the period as the name of the parent namespace node, and there is\n # no filter.\n if name.endswith('.'):\n parent_name = name[:-1]\n filter = None\n \n # Otherwise, we use all but the last portion of the name as the name\n # of the parent namespace node, and the rest as the filter.\n else:\n atoms = name.split('.')\n if len(atoms) == 1:\n parent_name = ''\n \n else:\n parent_name = '.'.join(atoms[:-1])\n\n filter = atoms[-1]\n\n return parent_name, filter\n\n def _in_auto_complete_mode(self, red):\n \"\"\" Return True if we are in auto-complete mode. \"\"\"\n \n command_history = red.command_history\n\n in_auto_complete_mode = (\n len(command_history) > 0\n and isinstance(command_history[-1], AbstractAutoComplete)\n )\n \n return in_auto_complete_mode\n\n\nclass AutoCompleteNext(AbstractAutoComplete):\n \"\"\" Auto-complete to the next candidate name. \"\"\"\n\n direction = 'next'\n\n\nclass AutoCompletePrevious(AbstractAutoComplete):\n \"\"\" Auto-complete to the previous candidate name. \"\"\"\n\n direction = 'previous'\n \n#### EOF #######################################################################\n","sub_path":"source/pgv/red/ui/commands/auto_complete.py","file_name":"auto_complete.py","file_ext":"py","file_size_in_byte":4355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"587865452","text":"# Utility functions used for HA4\n\nimport numpy as np\nimport os\nimport sys\nimport math\n\n\ndef preprocess(input_folder: str):\n \"\"\"\n Preprocess the original sign language dataset, and save the altered data to new files\n \"\"\"\n X_raw = np.load(open(input_folder+ '/X.npy', 'rb'))\n Y_raw = np.load(open(input_folder+ '/y.npy', 'rb'))\n print('X_raw shape: {}'.format(X_raw.shape))\n print('Y_raw shape: {}'.format(Y_raw.shape))\n\n # Add a channel dimension to X_raw\n X_raw = np.expand_dims(X_raw, axis=3)\n\n # Examination \n Y_integer = np.argmax(Y_raw, axis=1).reshape((-1, 1))\n print(Y_integer.shape)\n # print(Y_integer[:10,:])\n classes = np.unique(Y_integer)\n print('All classes:', classes)\n\n # Randomly sample 80% as training data, and the rest 20% as testing data\n np.random.seed(1)\n train_indices = np.array([])\n for c in classes:\n x_ind = np.where(Y_integer == c)[0]\n np.random.shuffle(x_ind)\n train_indices = np.append(train_indices, x_ind[:int(.8 * len(x_ind))])\n print(x_ind[0])\n print(train_indices.shape)\n train_indices = train_indices.astype(int)\n print(train_indices[:10])\n\n X_train = X_raw[train_indices, :]\n Y_train = Y_raw[train_indices, :]\n X_test = X_raw[[i for i in range(X_raw.shape[0]) if i not in train_indices], :]\n Y_test = Y_raw[[i for i in range(X_raw.shape[0]) if i not in train_indices], :]\n print('X_train shape:', X_train.shape)\n print('Y_train shape:', Y_train.shape)\n print('X_test shape:', X_test.shape)\n print('Y_test shape:', Y_test.shape)\n\n # Save to file\n np.save(open('X_train.npy', 'wb'), X_train)\n np.save(open('Y_train.npy', 'wb'), Y_train)\n np.save(open('X_test.npy', 'wb'), X_test)\n np.save(open('Y_test.npy', 'wb'), Y_test)\n\n\ndef load_data():\n data_files = ['X_train.npy', 'Y_train.npy', 'X_test.npy', 'Y_test.npy']\n for df in data_files:\n if not os.path.exists(df):\n sys.stderr.write('Make sure that {} is in the current directory'.format(df))\n sys.stderr.flush()\n sys.exit(1)\n\n X_train = np.load(open('X_train.npy', 'rb'))\n Y_train = np.load(open('Y_train.npy', 'rb'))\n X_test = np.load(open('X_test.npy', 'rb'))\n Y_test = np.load(open('Y_test.npy', 'rb'))\n\n return X_train, Y_train, X_test, Y_test\n\n\ndef generate_minibatch(X, Y, mini_batch_size = 64, seed = 0):\n \"\"\"\n Creates a list of random minibatches from (X, Y)\n \n Arguments:\n X -- input data, of shape (num_examples, input size)\n Y -- true \"label\" vector of shape (num_examples, num_classes)\n seed -- this is only for the purpose of grading \n \n Returns:\n mini_batches -- list of (mini_batch_X, mini_batch_Y)\n \"\"\"\n \n m = X.shape[0] # number of training examples\n mini_batches = []\n np.random.seed(seed)\n \n # Step 1: Shuffle (X, Y)\n permutation = list(np.random.permutation(m))\n shuffled_X = X[permutation, :]\n shuffled_Y = Y[permutation, :]\n\n # Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.\n num_complete_minibatches = math.floor(m/mini_batch_size) # number of mini batches of size mini_batch_size in your partitionning\n for k in range(num_complete_minibatches):\n mini_batch_X = shuffled_X[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]\n mini_batch_Y = shuffled_Y[k * mini_batch_size : k * mini_batch_size + mini_batch_size, :]\n mini_batch = (mini_batch_X, mini_batch_Y)\n mini_batches.append(mini_batch)\n \n # Handling the end case (last mini-batch < mini_batch_size)\n if m % mini_batch_size != 0:\n mini_batch_X = shuffled_X[num_complete_minibatches * mini_batch_size :, :]\n mini_batch_Y = shuffled_Y[num_complete_minibatches * mini_batch_size :, :]\n mini_batch = (mini_batch_X, mini_batch_Y)\n mini_batches.append(mini_batch)\n \n return mini_batches\n\n\ndef softmax(x):\n e_x = np.exp(x - np.max(x))\n return e_x / e_x.sum(axis=0)\n\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\n\ndef main():\n preprocess('../ha3/Sign-language-digits-dataset 2')\n return\n\nif __name__ == '__main__':\n main()","sub_path":"CS 596/hw5/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"371432855","text":"n = int(input())\n\ndef check(n):\n ans = \"2\"\n count = 0\n i = 3\n while (count+1 < n):\n checkSNT = 0;\n for x in range(1, i + 1):\n if i % x == 0:\n checkSNT += 1\n if checkSNT == 2:\n ans += \", \" + str(i)\n count += 1\n i += 1\n return ans\n\nprint(check(n))\n","sub_path":".idea/Workshop01/Bai07.py","file_name":"Bai07.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"218321162","text":"# -------------- Timers ---------------------------\nfrom datetime import datetime, timedelta\nfrom json import dumps\nfrom unittest import TestCase\nimport dateutil\nfrom bson import ObjectId\nfrom goalboost.model.timer_models import TimerEntity, TimerDAO\nfrom goalboost.model.legacy_timer_models import LegacyTimer\nfrom test.common.test_helper import TestHelper, TestObjects\n\nclass TestTimerEntity(TestCase):\n\n def test_can_save_and_load_timer(self):\n user = TestObjects().get_test_user()\n t = TimerEntity(id=TestObjects().get_any_id(), notes=\"Saved from unit test\", user=user )\n t.save()\n t2 = TimerEntity.objects(id = t.id).first()\n assert(t.__repr__() == t2.__repr__())\n t.delete()\n\n def test_eval_ok(self):\n user = TestObjects().get_test_user()\n t1 = TimerEntity(id=ObjectId(b\"Timer1Timer2\"), notes=\"I want a shrubbery\", user=user)\n # print(t1.__repr__())\n t2 = eval(t1.__repr__())\n # Note this part works partly because compare is brain-dead, compares id only and only works for non-null id\n # But that may be what we need for MongoEngine purposes, so don't override\n assert(t1 == t2)\n # A better check\n assert(t1.__repr__() == t2.__repr__())\n # print(t1.to_json())\n\n def test_user_not_updated_on_save(self):\n user = TestObjects().get_test_user()\n t1 = TimerEntity(id=ObjectId(b\"Timer1Timer3\"), notes=\"I want a shrubbery\", user=user)\n t1.save()\n t1.user.password = \"foo\"\n t1.save()\n # TODO ETC...\n t1.delete()\n\n\n# This tests the new refactored TimerDAO that takes a TimerEntity\nclass TestTimerDAO(TestCase):\n def test_save_timer(self):\n dao = TimerDAO()\n t1 = TimerEntity(notes=\"My Test LegacyTimer Running!\", user=TestObjects().get_test_user(), running=True)\n dao.put(t1)\n assert(t1.id is not None)\n\n# Derive from object temporarily to disable\nclass TestTimerLegacy(TestCase):\n def test_can_create_with_utc_now(self):\n #userId = \"561dcd3c8c57cf2c17b7f4f9\"\n my_notes = \"I want to know how long this took, but my code is brain dead so far. Woe is me.\"\n timer = LegacyTimer(notes=my_notes)\n assert(my_notes == timer.notes)\n timer.save()\n\n def test_can_start_and_stop(self):\n notes = \"Testing start and stop\"\n t = LegacyTimer(notes=notes)\n t.start()\n t.stop()\n\n\n def test_can_create_with_explicit_start(self):\n my_notes = \"I am another timer\"\n timer = LegacyTimer(notes=my_notes, startTime=datetime(2007, 12, 5, 0, 0))\n assert(my_notes == timer.notes)\n assert(timer.startTime == timer.lastRestart)\n\n # timers created this way display an ugly ui bug -- so there's a bug either in the GUI or here or both.\n # Entered as\n # https://github.com/CodeSolid/Goalboost/issues/12\n def test_can_create_without_datastore(self):\n pass\n # Uncomment the following to see (and delete \"pass\" of course).\n # my_notes = \"We don't need no steenkin datastore.\"\n # timer = LegacyTimer(id=\"56259a278c57cf02f9692ccc\", userId = \"561dcd3c8c57cf2c17b7f4f9\", notes=my_notes)\n #\n # # This will be a bug that will appear in the UI -- no entry in the entries array is created for today!\n # # timer = LegacyTimer(id=\"56259a278c57cf02f9692ccc\", userId = \"561dcd3c8c57cf2c17b7f4f9\", notes=my_notes, startTime=datetime(2007, 12, 5, 0, 0))\n # timer.save()\n # timer2 = LegacyTimer.objects(id=\"56259a278c57cf02f9692ccc\").first()\n # assert(timer2.notes == timer.notes)\n # assert(my_notes == timer.notes)\n # assert(timer.startTime == timer.lastRestart)\n\n # Don't run in debugger, a breakpoint in right place will throw off elapsed calculation.\n # Otherwise elapsed converts to int, which shaves off any \"running time\" error\n def test_elapsed_time_correct(self):\n now = datetime.utcnow()\n tenSecondsAgo = now - timedelta(seconds=10)\n # LegacyTimer must be running or elapsed time will be zero\n timer = LegacyTimer(startTime = tenSecondsAgo, running=True)\n timer.set_seconds_today(20)\n elapsed = timer.current_elapsed()\n total = timer.total_elapsed()\n assert(elapsed == 10)\n assert(total == 30)\n\n def test_to_api_dict_correct(self):\n start_time = dateutil.parser.parse('2008-09-03T20:00:00.000000Z')\n # LegacyTimer must be running or elapsed time will be zero\n timer = LegacyTimer(startTime = start_time, running=True, id=ObjectId(\"56259a278c57cf02f9692b31\"))\n d = timer.to_api_dict()\n json = dumps(d)\n assert('\"notes\": null' in json)\n assert('\"id\": \"56259a278c57cf02f9692b31\"' in json)\n assert('\"entries\": []' in json)\n #assert('\"seconds\": 20' in json)\n timer.notes = \"Testing the JSON!\"\n timer.set_seconds_today(99)\n d = timer.to_api_dict()\n json = dumps(d)\n assert('\"notes\": \"Testing the JSON!\"' in json)\n assert('\"seconds\": 99' in json)\n\n def test_can_load_from_api_dict(self):\n start_time = dateutil.parser.parse('2008-09-03T20:00:00.000000Z')\n # LegacyTimer must be running or elapsed time will be zero\n timer = LegacyTimer(startTime = start_time, running=True, id=ObjectId(\"56259a278c57cf02f9692b31\"))\n timer.set_seconds_today(99)\n d = timer.to_api_dict()\n t2 = LegacyTimer.load_from_dict(d)\n assert(timer.notes == t2.notes)\n assert(timer.id == t2.id)\n assert(timer.entries[0].dateRecorded == t2.entries[0].dateRecorded)\n assert(len(timer.entries) == len(t2.entries))\n assert(timer.entries[0].seconds == t2.entries[0].seconds)\n d[\"notes\"] = \"Testing\"\n t2 = LegacyTimer.load_from_dict(d)\n assert(t2.notes == \"Testing\")\n","sub_path":"test/unit/model/test_timer_model.py","file_name":"test_timer_model.py","file_ext":"py","file_size_in_byte":5860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"421202110","text":"\"\"\"\nhttps://leetcode.com/problems/single-row-keyboard/\n\"\"\"\nclass Solution:\n def calculateTime(self, keyboard: str, word: str) -> int:\n ref = {}\n for i, ch in enumerate(keyboard):\n ref[ch] = i\n curr_pos, ans = 0, 0\n for ch in word:\n ans += abs(ref[ch] - curr_pos)\n curr_pos = ref[ch]\n return ans\n\nsol = Solution()\nassert sol.calculateTime('abcdefghijklmnopqrstuvwxyz', 'cba') == 4\nassert sol.calculateTime('pqrstuvwxyzabcdefghijklmno', 'leetcode') == 73\n","sub_path":"1165_SingleRowKeyboard.py","file_name":"1165_SingleRowKeyboard.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"124990788","text":"#coding:utf-8\nimport sys,os\nsys.path.append(os.pardir)\nfrom datetime import datetime\nimport unittest\nfrom todoItem import ToDoItem\n\nclass TestToDoItem(unittest.TestCase):\n\t\t\t\tdef setUp(self):\n\t\t\t\t\t\t\t\tself.testItem1=ToDoItem('','',datetime.now())\n\t\t\t\t\t\t\t\tself.testItem2=ToDoItem('test','test description',datetime.strptime('2014/9/20 12:30:00','%Y/%m/%d %H:%M:%S'))\n\t\t\t\t\t\t\t\t\n\t\t\t\tdef tearDown(self):\n\t\t\t\t\t\t\t\tpass\n\t\t\t\tdef testNewInstance(self):\n\t\t\t\t\t\t\t\tself.assertNotEqual(self.testItem1,None)\n\t\t\t\tdef testToDoItemFinish(self):\n\t\t\t\t\t\t\t\tself.testItem2.finish()\n\t\t\t\t\t\t\t\tfinished_date=self.testItem2.finished_date\n\t\t\t\t\t\t\t\tself.assertEqual(self.testItem2.finished,True)\n\t\t\t\t\t\t\t\tself.assertEqual(finished_date.strftime('%Y/%m/%d %H:%M'),datetime.now().strftime('%Y/%m/%d %H:%M'))\nif __name__=='__main__':\n\t\t\t\tsuite=unittest.TestLoader().loadTestsFromTestCase(TestToDoItem)\n\t\t\t\tunittest.TextTestRunner(verbosity=2).run(suite)\n","sub_path":"test/testToDoItem.py","file_name":"testToDoItem.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"288959452","text":"from tv_show_folder_rename_sonarr.logger import Logger\nfrom tv_show_folder_rename_sonarr.config import GuiConfig\nfrom tv_show_folder_rename_sonarr.cli_helpers import read_args\nfrom tv_show_folder_rename_sonarr.rename_shows import run_rename\nfrom pathlib import Path\nimport argparse\n\n\ndef run_cli():\n \"\"\"\n Runs the cli interface. Requires that the script was called with proper arguments. Accesses sys.argv for arguments.\n Starts worker script after parsing inputs.\n :return: None\n \"\"\"\n cli_default_config = Path('config.yml')\n cli_config = GuiConfig(cli_default_config)\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-c\", \"--config\", help=\"specify configuration file to load\", default=None)\n parser.add_argument(\"-l\", \"--log\", help=\"Specify log file.\", default=None, )\n parser.add_argument(\"-u\", \"--url\", help=\"Specify the Sonarr API url.\", default=None, )\n parser.add_argument(\"-k\", \"--key\", help=\"Specify the Sonarr API key\", default=None, )\n parser.add_argument(\"--char\", help=\"replacement char for space\", default=None, )\n parser.add_argument(\"-n\", \"--new\", help=\"new library root path\", default=None, )\n\n parser.add_argument(\"-p\", \"--preview\", help=\"Switch use if you want to preview the changes\",\n default=False, action='store_true')\n parser.add_argument(\"--replace_space\", help=\"Switch use if you want to replace the space char in the folder name\",\n default=False, action='store_true')\n parser.add_argument(\"--replace_root\", help=\"Switch use if you want to change the root folder of your library\",\n default=False, action='store_true')\n parser.add_argument(\"--use_language_in_path\", help=\"Switch use if you want to use the language of a show in the library path\",\n default=False, action='store_true')\n\n args = parser.parse_args()\n cli_config = read_args(args, cli_config)\n cli_config.logger = Logger(log_file=Path(cli_config.get('log_file')))\n run_rename(cli_config)\n","sub_path":"tv_show_folder_rename_sonarr/run_cli.py","file_name":"run_cli.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"599329199","text":"#!/usr/bin/env python3\n\nfrom RSA_Class import RSA\n\nrsa1 = RSA()\nrsa2 = RSA()\n\nq = rsa1.find_prime_smaller_than_k(10000)\nalpha = rsa1.find_prime_smaller_than_k(100)\n\nprint(q, alpha)\n\nrsa1.set_q(q)\nrsa1.set_alpha(alpha)\nrsa2.set_q(q)\nrsa2.set_alpha(alpha)\n\ncipher_key_1 = rsa1.gen_pv_key()\ncipher_key_2 = rsa2.gen_pv_key()\nshared_key_1 = rsa1.gen_shared_key(cipher_key_2)\nshared_key_2 = rsa2.gen_shared_key(cipher_key_1)\nprint(shared_key_1, shared_key_2)\n","sub_path":"Coding_Part/RSA_local_test_main.py","file_name":"RSA_local_test_main.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"294442440","text":"\"\"\"\nУрок 3\nЗадание 4\nОпределить, какое число в массиве встречается чаще всего\n\"\"\"\n\nimport random\n\n\ndef func_rec(max_i, *args):\n \"\"\"\n Функция возвращает индекс списка элемент которого чаще всего\n встречается в этом списке, сделано через рекурсию с уменьшением\n длины передаваемого списка\n :param max_i: индекс\n :param args: список\n :return: индекс числа вхождение кото��ого наибольшее в списке\n \"\"\"\n my_list_in = list (*args)\n if len (my_list_in) == 0:\n return max_i\n if my_list_in.count (max_i) < my_list_in.count ([-1]):\n max_i = my_list_in.pop ()\n else:\n my_list_in.pop ()\n func_rec (max_i, my_list_in)\n\n\nif __name__ == '__main__':\n my_list = [random.randint (0, 100) for number in range (100)]\n print (my_list)\n INDEX_MAX_REC = func_rec (0)\n print (f'Число {my_list[INDEX_MAX_REC]} встречается чаще '\n f'всего = {my_list.count (INDEX_MAX_REC)} раз(-а)')\n","sub_path":"three_task4.py","file_name":"three_task4.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"225362437","text":"from copy import copy\nimport asyncio\nimport inspect\nimport collections\nimport discord\nimport datetime\nimport re\n\nfrom redbot.core import Config, checks, commands\nfrom redbot.core.i18n import Translator\nfrom redbot.core.utils.predicates import MessagePredicate\n\n_ = Translator(\"Warnings\", __file__)\n\n\nasync def warning_points_add_check(\n config: Config, ctx: commands.Context, user: discord.Member, points: int\n):\n \"\"\"Handles any action that needs to be taken or not based on the points\"\"\"\n guild = ctx.guild\n guild_settings = config.guild(guild)\n act = {}\n async with guild_settings.actions() as registered_actions:\n for a in registered_actions:\n # Actions are sorted in decreasing order of points.\n # The first action we find where the user is above the threshold will be the\n # highest action we can take.\n if points >= a[\"points\"]:\n act = a\n break\n if act and act[\"exceed_command\"] is not None: # some action needs to be taken\n await create_and_invoke_context(ctx, act[\"exceed_command\"], user)\n\n\nasync def warning_points_remove_check(\n config: Config, ctx: commands.Context, user: discord.Member, points: int\n):\n guild = ctx.guild\n guild_settings = config.guild(guild)\n act = {}\n async with guild_settings.actions() as registered_actions:\n for a in registered_actions:\n if points >= a[\"points\"]:\n act = a\n else:\n break\n if act and act[\"drop_command\"] is not None: # some action needs to be taken\n await create_and_invoke_context(ctx, act[\"drop_command\"], user)\n\n\nasync def create_and_invoke_context(\n realctx: commands.Context, command_str: str, user: discord.Member\n):\n m = copy(realctx.message)\n m.content = command_str.format(user=user.mention, prefix=realctx.prefix)\n fctx = await realctx.bot.get_context(m, cls=commands.Context)\n try:\n await realctx.bot.invoke(fctx)\n except (commands.CheckFailure, commands.CommandOnCooldown):\n await fctx.reinvoke()\n\n\ndef get_command_from_input(bot, userinput: str):\n com = None\n orig = userinput\n while com is None:\n com = bot.get_command(userinput)\n if com is None:\n userinput = \" \".join(userinput.split(\" \")[:-1])\n if len(userinput) == 0:\n break\n if com is None:\n return None, _(\"I could not find a command from that input!\")\n\n check_str = inspect.getsource(checks.is_owner)\n if any(inspect.getsource(x) in check_str for x in com.checks):\n # command the user specified has the is_owner check\n return (\n None,\n _(\"That command requires bot owner. I can't allow you to use that for an action\"),\n )\n return \"{prefix}\" + orig, None\n\n\nasync def get_command_for_exceeded_points(ctx: commands.Context):\n \"\"\"Gets the command to be executed when the user is at or exceeding\n the points threshold for the action\"\"\"\n await ctx.send(\n _(\n \"Enter the command to be run when the user **exceeds the points for \"\n \"this action to occur.**\\n**If you do not wish to have a command run, enter** \"\n \"`none`.\\n\\nEnter it exactly as you would if you were \"\n \"actually trying to run the command, except don't put a prefix and \"\n \"use `{user}` in place of any user/member arguments\\n\\n\"\n \"WARNING: The command entered will be run without regard to checks or cooldowns. \"\n \"Commands requiring bot owner are not allowed for security reasons.\\n\\n\"\n \"Please wait 15 seconds before entering your response.\"\n )\n )\n await asyncio.sleep(15)\n\n await ctx.send(_(\"You may enter your response now.\"))\n\n try:\n msg = await ctx.bot.wait_for(\n \"message\", check=MessagePredicate.same_context(ctx), timeout=30\n )\n except asyncio.TimeoutError:\n return None\n else:\n if msg.content == \"none\":\n return None\n\n command, m = get_command_from_input(ctx.bot, msg.content)\n if command is None:\n await ctx.send(m)\n return None\n\n return command\n\n\nasync def get_command_for_dropping_points(ctx: commands.Context):\n \"\"\"\n Gets the command to be executed when the user drops below the points\n threshold\n\n This is intended to be used for reversal of the action that was executed\n when the user exceeded the threshold\n \"\"\"\n await ctx.send(\n _(\n \"Enter the command to be run when the user **returns to a value below \"\n \"the points for this action to occur.** Please note that this is \"\n \"intended to be used for reversal of the action taken when the user \"\n \"exceeded the action's point value.\\n**If you do not wish to have a command run \"\n \"on dropping points, enter** `none`.\\n\\nEnter it exactly as you would \"\n \"if you were actually trying to run the command, except don't put a prefix \"\n \"and use `{user}` in place of any user/member arguments\\n\\n\"\n \"WARNING: The command entered will be run without regard to checks or cooldowns. \"\n \"Commands requiring bot owner are not allowed for security reasons.\\n\\n\"\n \"Please wait 15 seconds before entering your response.\"\n )\n )\n await asyncio.sleep(15)\n\n await ctx.send(_(\"You may enter your response now.\"))\n\n try:\n msg = await ctx.bot.wait_for(\n \"message\", check=MessagePredicate.same_context(ctx), timeout=30\n )\n except asyncio.TimeoutError:\n return None\n else:\n if msg.content == \"none\":\n return None\n command, m = get_command_from_input(ctx.bot, msg.content)\n if command is None:\n await ctx.send(m)\n return None\n\n return command\n\n\nasync def EmbedPaginateWarnsList(\n self,\n ctx,\n items: list,\n items_per_page: int = 15,\n title=discord.Embed.Empty,\n desc=discord.Embed.Empty,\n author=discord.Embed.Empty,\n author_url=discord.Embed.Empty,\n author_icon_url=discord.Embed.Empty,\n thumbnail=discord.Embed.Empty,\n):\n maxPage = len(items) // items_per_page + (len(items) % items_per_page > 0)\n pages = [items[i * items_per_page : (i + 1) * items_per_page] for i in range(maxPage)]\n count = 0\n for page in pages:\n count += 1\n # print(f\"Page {count} : {page}\")\n\n async def showPage(page):\n em = discord.Embed(title=title, description=desc, color=0x3DF270)\n em.set_author(name=author, url=author_url, icon_url=author_icon_url)\n em.set_thumbnail(url=thumbnail)\n count = (page - 1) * items_per_page\n total = len(items)\n for warning in pages[page - 1]:\n id = warning.get(\"id\", \"None\")\n count += 1\n num_points = warning[\"points\"]\n time = datetime.datetime.fromtimestamp(warning[\"time\"]).strftime(\n \"%m/%d/%y @ %I:%M %p UTC\"\n )\n unwarn = (\n datetime.datetime.fromtimestamp(warning[\"unwarn\"]).strftime(\n \"%m/%d/%y @ %I:%M %p UTC\"\n )\n if warning.get(\"unwarn\")\n else None\n )\n mod = ctx.guild.get_member(warning[\"mod\"])\n if mod is None:\n mod = discord.utils.get(self.bot.get_all_members(), id=warning[\"mod\"])\n if mod is None:\n mod = await self.bot.get_user_info(warning[\"mod\"])\n em.add_field(\n name=f\"{count} of {total} | {num_points} point warning | Warning ID (*{id}*)\",\n value=f\"Issued by {mod.mention}\",\n inline=False,\n )\n em.add_field(\n name=f\"Issued on {time}\",\n value=f'Reason : {warning[\"description\"]}'\n + (f\"\\nUnwarning: {unwarn}\" if unwarn else \"\")\n + \"\\n------------------------------------------------------------------------------\",\n inline=False,\n )\n em.set_footer(\n text=f\"Page {currentPage} out of {maxPage}\",\n icon_url=\"https://www.clipartmax.com/png/middle/171-1715896_paper-book-icon-textbook-icon.png\",\n )\n return em\n\n firstRun = True\n while True:\n if firstRun:\n firstRun = False\n currentPage = 1\n em = await showPage(currentPage)\n msg = await ctx.send(embed=em)\n\n if maxPage == 1 and currentPage == 1:\n toReact = [\"✅\"]\n elif currentPage == 1:\n toReact = [\"⏩\", \"✅\"]\n elif currentPage == maxPage:\n toReact = [\"⏪\", \"✅\"]\n elif currentPage > 1 and currentPage < maxPage:\n toReact = [\"⏪\", \"⏩\", \"✅\"]\n\n for reaction in toReact:\n await msg.add_reaction(reaction)\n\n def checkReaction(reaction, user):\n return user == ctx.message.author and str(reaction.emoji).startswith(\n (\"⏪\", \"⏩\", \"✅\")\n ) # and reaction.message == msg\n\n try:\n result, user = await self.bot.wait_for(\n \"reaction_add\", timeout=120, check=checkReaction\n )\n except asyncio.TimeoutError:\n em.set_footer(\n text=f\"Page {currentPage} out of {maxPage}. Timeout. Please reinvoke the command to change pages.\",\n icon_url=\"https://www.clipartmax.com/png/middle/171-1715896_paper-book-icon-textbook-icon.png\",\n )\n try:\n await msg.edit(embed=em)\n await msg.clear_reactions()\n except (discord.NotFound, discord.Forbidden):\n pass\n break\n else:\n try:\n if \"⏪\" in str(result.emoji):\n # print('Previous Page')\n currentPage -= 1\n em = await showPage(currentPage)\n await msg.edit(embed=em)\n await msg.clear_reactions()\n elif \"⏩\" in str(result.emoji):\n # print('Next Page')\n currentPage += 1\n em = await showPage(currentPage)\n await msg.edit(embed=em)\n await msg.clear_reactions()\n elif \"✅\" in str(result.emoji):\n # print('Close List')\n await msg.delete()\n await ctx.message.delete()\n break\n except (discord.NotFound, discord.Forbidden):\n pass\n\n\nclass Time(commands.Converter):\n TIME_AMNT_REGEX = re.compile(\"([1-9][0-9]*)([a-z]+)\", re.IGNORECASE)\n TIME_QUANTITIES = collections.OrderedDict(\n [\n (\"seconds\", 1),\n (\"minutes\", 60),\n (\"hours\", 3600),\n (\"days\", 86400),\n (\"weeks\", 604800),\n (\"months\", 2.628e6),\n (\"years\", 3.154e7),\n ]\n ) # (amount in seconds, max amount)\n\n def get_seconds(self, time):\n \"\"\"Returns the amount of converted time or None if invalid\"\"\"\n seconds = 0\n for time_match in self.TIME_AMNT_REGEX.finditer(time):\n time_amnt = int(time_match.group(1))\n time_abbrev = time_match.group(2)\n time_quantity = discord.utils.find(\n lambda t: t[0].startswith(time_abbrev), self.TIME_QUANTITIES.items()\n )\n if time_quantity is not None:\n seconds += time_amnt * time_quantity[1]\n return None if seconds == 0 else seconds\n\n async def convert(self, ctx, arg):\n result = None\n seconds = self.get_seconds(arg)\n result = seconds\n if result is None:\n raise commands.BadArgument('Unable to parse Time \"{}\" '.format(arg))\n return result\n\n @classmethod\n async def fromString(cls, arg):\n result = None\n seconds = cls.get_seconds(cls, arg)\n result = seconds\n if result is None:\n raise commands.BadArgument('Unable to parse Time \"{}\" '.format(arg))\n return result\n","sub_path":"warnings/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":12138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"71864876","text":"import logging\nimport sqlite3\n\nimport discord\nfrom discord.ext import commands\n\nfrom .extensions import INIT_EXTENSIONS\nfrom .helpers.database import init_db\nfrom .settings import DEBUG, COMMAND_PREFIX, TOKEN\n\nlog = logging.getLogger(__name__)\n\nbot = commands.Bot(command_prefix=COMMAND_PREFIX)\n\n# Load extensions\nlog.debug(\"Loading default extensions...\")\nif DEBUG is True:\n log.info(\"=== DEBUG MODE ENABLED ===\")\n # Add debug-specific code/extensions here\n\nfor ext in INIT_EXTENSIONS:\n log.debug(f\"Loading {ext}...\")\n bot.load_extension(ext)\n\nlog.debug(\"Default extensions loaded.\")\n\n# Initialize Database\ninit_db()\n\n\n@bot.event\nasync def on_ready():\n \"\"\"\n Execute on bot initialization with the Discord API. This may happen more than once.\n \"\"\"\n log.info(f\"Started as {bot.user}\")\n\n\n@bot.command()\n@commands.is_owner()\nasync def reload(ctx: commands.context):\n \"\"\"\n Reload default extensions (cogs)\n\n :param ctx: Discord Context\n \"\"\"\n async with ctx.channel.typing():\n log.info(\"Reloading Extensions...\")\n\n msg = await ctx.send(\n embed=discord.Embed(\n title=\"Reloading extensions...\", color=discord.Color.orange()\n )\n )\n\n for extension in INIT_EXTENSIONS:\n from discord.ext.commands import (\n ExtensionNotLoaded,\n ExtensionNotFound,\n ExtensionFailed,\n )\n\n try:\n bot.reload_extension(extension)\n except (\n ExtensionNotLoaded,\n ExtensionNotFound,\n ExtensionFailed,\n ) as e:\n log.exception(e)\n await ctx.send(\n embed=discord.Embed(\n title=f\"Module {extension} failed to reload\",\n color=discord.Color.red(),\n )\n )\n log.debug(f\"{extension} reloaded\")\n\n try:\n log.info(\"Re-initializing database\")\n init_db()\n except sqlite3.OperationalError:\n await ctx.send(\n embed=discord.Embed(\n title=f\"Database failed to re-initialize (i.e. upgrade)\",\n color=discord.Color.red(),\n )\n )\n\n await msg.delete()\n await ctx.send(\n embed=discord.Embed(title=\"Reload Successful\", color=discord.Color.green())\n )\n log.info(\"Reloading complete.\")\n\n\nbot.run(TOKEN)\n","sub_path":"bot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"642284192","text":"n=int(input())\nm=list(map(int, input().split()))\ndp=[1]\nfor i in range(1,n):\n mi = 0\n for j in range(i):\n if m[i] < m[j] and dp[j] > mi:\n mi = dp[j]\n dp.append(mi + 1)\n\nprint(max(dp))\n","sub_path":"src/11722.py","file_name":"11722.py","file_ext":"py","file_size_in_byte":211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"399040773","text":"import pymongo\n\nmyclient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n\nmydb = myclient[\"Case-Base\"]\n\nmycol = mydb[\"cases\"]\n\nmydict = { \"classification\": \"1\", \"cancer\": \"1\" }\n\nx = mycol.insert_one(mydict)\n\nprint(myclient.list_database_names())","sub_path":"CBR/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"640551460","text":"#_*_ encoding: utf-8 _*_\nfrom django.shortcuts import render\nfrom django.template.loader import get_template\nfrom django.http import HttpResponse\nfrom datetime import datetime\n\n# Create your views here.\ndef index(request, tvno='0'):\n\ttv_list = [{'name':'CCTV News', 'tvcode':'yPhFG2I0dE0'},\n\t\t\t{'name':'CCTV中文国际', 'tvcode':'E1DTZBy4xr4'},]\n\n\ttemplate = get_template('index.html')\n\tnow = datetime.now()\n\thour = now.timetuple().tm_hour\n\ttvno = tvno\n\ttv = tv_list[int(tvno)]\n\thtml = template.render(locals())\n\n\treturn HttpResponse(html)\n\ndef engtv(request, tvno='0'):\n\ttv_list = [{'name':'SkyNews', 'tvcode':'y60wDzZt8yg'},\n\t\t\t{'name':'Euro News', 'tvcode':'mWdKb7255Bs'},\n\t\t\t{'name':'India News', 'tvcode':'oMncjfIE-ZU'},\n\t\t\t{'name':'CCTV', 'tvcode':'wuzZYzSoEEU'},]\n\n\ttemplate = get_template('engtv.html')\n\tnow = datetime.now()\n\ttvno = tvno\n\ttv = tv_list[int(tvno)]\n\thtml = template.render(locals())\n\n\treturn HttpResponse(html)\n\n","sub_path":"django/djangoStudy/mtv/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"288631901","text":"from entity import Entity\nfrom util import *\nfrom components import *\nfrom pyglet.window import key\n\nclass Limb(Entity):\n \"\"\"\n A limb of an Actor\n Contains a mesh and a collision component\n \"\"\"\n def __init__(self, eman, mesh):\n super().__init__(eman)\n\n self.addComponent(mesh)\n self.addComponent(CollisionComponent(\"limb\", [\"weapon\",\"ground\"], useAABB=False, AABB=None, collidable=True))\n self.addComponent(SVAComponent())\n\n\nclass Actor(Entity):\n \"\"\"\n An Actor is an player controlled entity.\n Actors the following Limbs:\n Head\n L Arm\n R Arm\n L Leg\n R Leg\n Body\n\n \"\"\"\n def __init__(self, eman):\n super().__init__(eman)\n # Head\n self.head = Limb(eman,\n MeshComponent(shape=Rectangle(10, 30, Vector(50,130, 0), CENTER, [Color(255,255,255)*4], None)))\n # Body\n self.body = Limb(eman,\n MeshComponent(shape=Rectangle(30, 50, Vector(40,100, 0), TOPLEFT, [Color(255,255,0)*4], None)))\n # Arms\n self.larm = Limb(eman,\n MeshComponent(shape=Rectangle(20, 30, Vector(40,100, 0), TOPRIGHT, [Color(255,0,0)*4], None)))\n self.rarm = Limb(eman,\n MeshComponent(shape=Rectangle(20, 30, Vector(70, 100, 0), TOPLEFT, [Color(255,0,255)*4], None)))\n # Legs\n self.lleg = Limb(eman,\n MeshComponent(shape=Rectangle(20, 50, Vector(30, 50, 0), TOPLEFT, [Color(128,0,255)*4], None)))\n self.rleg = Limb(eman,\n MeshComponent(shape=Rectangle(20, 50, Vector(60, 50, 0), TOPLEFT, [Color(255,0,128)*4], None)))\n\n self.addComponent(KeyHoldComponent({Key(key.Q, 0): [\n\"\"\"\nowner.larm.getSingleComponentByType(SVAComponent).OMEGA = Vector(0,0,3)\n\"\"\",\n\"\"\"\nowner.larm.getSingleComponentByType(SVAComponent).OMEGA = Vector(0,0,0)\n\"\"\"\n]}))\n self.addComponent(KeyHoldComponent({Key(key.W, 0): [\n\"\"\"\nowner.rarm.getSingleComponentByType(SVAComponent).OMEGA = Vector(0,0,3)\n\"\"\",\n\"\"\"\nowner.rarm.getSingleComponentByType(SVAComponent).OMEGA = Vector(0,0,0)\n\"\"\"\n]}))\n self.addComponent(KeyHoldComponent({Key(key.A, 0): [\n\"\"\"\nowner.lleg.getSingleComponentByType(SVAComponent).OMEGA = Vector(0,0,3)\n\"\"\",\n\"\"\"\nowner.lleg.getSingleComponentByType(SVAComponent).OMEGA = Vector(0,0,0)\n\"\"\"\n]}))\n self.addComponent(KeyHoldComponent({Key(key.S, 0): [\n\"\"\"\nowner.rleg.getSingleComponentByType(SVAComponent).OMEGA = Vector(0,0,3)\n\"\"\",\n\"\"\"\nowner.rleg.getSingleComponentByType(SVAComponent).OMEGA = Vector(0,0,0)\n\"\"\"\n]}))\n\n def addSVAComponent(self,\n position=Vector(0,0,0), velocity=Vector(0,0,0), acceleration=Vector(0,0,0),\n a_position=Vector(0,0,0), a_velocity=Vector(0,0,0), a_acceleration=Vector(0,0,0),\n bounded=True):\n self.addComponent(SVAComponent(position, velocity, acceleration, a_position, a_velocity, a_acceleration, bounded))\n\n def interact(self, other):\n pass\n","sub_path":"source/entities/actor.py","file_name":"actor.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"510908711","text":"import asyncio\nimport json\nimport re\nimport sys\nfrom os.path import dirname, join\nfrom typing import Any, Coroutine, Dict, List, cast\nfrom unittest import TestCase\nfrom unittest.mock import patch\n\nfrom hubitatmaker.hub import Hub, InvalidConfig\n\nwith open(join(dirname(__file__), \"hub_edit.html\")) as f:\n hub_edit_page = f.read()\n\nwith open(join(dirname(__file__), \"devices.json\")) as f:\n devices = f.read()\n\nwith open(join(dirname(__file__), \"device_details.json\")) as f:\n device_details = json.loads(f.read())\n\nwith open(join(dirname(__file__), \"events.json\")) as f:\n events = json.loads(f.read())\n\n\ndef run(cr: Coroutine) -> Any:\n return asyncio.get_event_loop().run_until_complete(cr)\n\n\nclass FakeResponse:\n def __init__(self, status=200, text: str = \"\"):\n self.status = status\n self._text = text\n\n async def json(self):\n return json.loads(self._text)\n\n async def text(self):\n return self._text\n\n\nclass FakeServer:\n url = \"http://localhost:9999\"\n\n\nrequests: List[Dict[str, Any]] = []\n\n\nclass fake_request:\n def __init__(self, method: str, url: str, **kwargs: Any):\n data = kwargs\n\n if url.endswith(\"/hub/edit\"):\n self.response = FakeResponse(text=hub_edit_page)\n elif url.endswith(\"/devices\"):\n self.response = FakeResponse(text=devices)\n else:\n dev_match = re.match(\".*/devices/(\\\\d+)$\", url)\n if dev_match:\n dev_id = dev_match.group(1)\n self.response = FakeResponse(\n text=json.dumps(device_details.get(dev_id, {}))\n )\n else:\n self.response = FakeResponse(text=\"{}\")\n\n requests.append({\"method\": method, \"url\": url, \"data\": kwargs})\n\n async def __aenter__(self):\n return self.response\n\n async def __aexit__(self, exc_type, exc, tb):\n pass\n\n\ndef fake_get_mac_address(**kwargs: str):\n return \"aa:bb:cc:dd:ee:ff\"\n\n\nclass TestHub(TestCase):\n def setUp(self):\n requests = []\n\n def test_hub_checks_arguments(self) -> None:\n \"\"\"The hub should check for its required inputs.\"\"\"\n self.assertRaises(InvalidConfig, Hub, \"\", \"1234\", \"token\")\n self.assertRaises(InvalidConfig, Hub, \"1.2.3.4\", \"\", \"token\")\n self.assertRaises(InvalidConfig, Hub, \"1.2.3.4\", \"1234\", \"\")\n Hub(\"1.2.3.4\", \"1234\", \"token\")\n\n @patch(\"getmac.get_mac_address\", new=fake_get_mac_address)\n def test_initial_values(self) -> None:\n \"\"\"Hub properties should have expected initial values.\"\"\"\n hub = Hub(\"1.2.3.4\", \"1234\", \"token\")\n self.assertEqual(list(hub.devices), [])\n self.assertEqual(hub.mac, \"aa:bb:cc:dd:ee:ff\")\n\n @patch(\"aiohttp.request\", new=fake_request)\n @patch(\"getmac.get_mac_address\", new=fake_get_mac_address)\n @patch(\"hubitatmaker.server.Server\")\n def test_start_server(self, MockServer) -> None:\n \"\"\"Hub should start a server when asked to.\"\"\"\n hub = Hub(\"1.2.3.4\", \"1234\", \"token\", True)\n run(hub.start())\n self.assertTrue(MockServer.called)\n\n @patch(\"aiohttp.request\", new=fake_request)\n @patch(\"getmac.get_mac_address\", new=fake_get_mac_address)\n @patch(\"hubitatmaker.server.Server\")\n def test_start(self, MockServer) -> None:\n \"\"\"start() should request data from the Hubitat hub.\"\"\"\n hub = Hub(\"1.2.3.4\", \"1234\", \"token\")\n run(hub.start())\n # 33 requests - 1 to get device list, 32 to update devices\n self.assertEqual(len(requests), 33)\n self.assertRegex(requests[1][\"url\"], \"devices$\")\n self.assertRegex(requests[2][\"url\"], \"devices/\\d+$\")\n self.assertRegex(requests[-1][\"url\"], \"devices/\\d+$\")\n\n @patch(\"aiohttp.request\", new=fake_request)\n @patch(\"getmac.get_mac_address\", new=fake_get_mac_address)\n @patch(\"hubitatmaker.server.Server\")\n def test_stop_server(self, MockServer) -> None:\n \"\"\"Hub should stop a server when stopped.\"\"\"\n hub = Hub(\"1.2.3.4\", \"1234\", \"token\", True)\n run(hub.start())\n self.assertTrue(MockServer.return_value.start.called)\n hub.stop()\n self.assertTrue(MockServer.return_value.stop.called)\n\n @patch(\"aiohttp.request\", new=fake_request)\n @patch(\"getmac.get_mac_address\", new=fake_get_mac_address)\n @patch(\"hubitatmaker.server.Server\")\n def test_devices_loaded(self, MockServer) -> None:\n \"\"\"Started hub should have parsed device info.\"\"\"\n hub = Hub(\"1.2.3.4\", \"1234\", \"token\")\n run(hub.start())\n self.assertEqual(len(hub.devices), 9)\n\n @patch(\"aiohttp.request\", new=fake_request)\n @patch(\"getmac.get_mac_address\", new=fake_get_mac_address)\n @patch(\"hubitatmaker.server.Server\")\n def test_process_event(self, MockServer) -> None:\n \"\"\"Started hub should process a device event.\"\"\"\n hub = Hub(\"1.2.3.4\", \"1234\", \"token\")\n run(hub.start())\n device = hub.devices[\"176\"]\n attr = device.attributes[\"switch\"]\n self.assertEqual(attr.value, \"off\")\n\n hub.process_event(events[0])\n\n attr = device.attributes[\"switch\"]\n self.assertEqual(attr.value, \"on\")\n","sub_path":"hubitatmaker/tests/test_hub.py","file_name":"test_hub.py","file_ext":"py","file_size_in_byte":5163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"370534503","text":"import uuid\nimport route as r\nimport validate as vld\nimport voicer as v\nimport file_loger as fl\nimport database_loger as db\n\nFILE_LOG = int(1)\nDB_LOG = int()\n\nPHONE = str()\nPATH = str()\nSTAGE = str()\n\nif __name__ == \"__main__\":\n arguments = r.runRouting()\n\n if vld.validate(arguments):\n PHONE = arguments.phone\n DB_LOG = arguments.database\n PATH = arguments.path\n STAGE = arguments.stage\n\n message = v.readingSound(PATH)\n status, response, duration = v.analyseMessage(message, STAGE)\n logMessage = {\n 'uid': str(uuid.uuid4()),\n 'stage': 'stage №' + str(STAGE),\n 'phone': PHONE,\n 'duration': duration,\n 'status': status\n }\n fl.logInfo(\"{uid} - {stage} - {phone} - {duration} - {status}\".format(**logMessage))\n if(DB_LOG == 1):\n db.logInfo(logMessage)\n r.removeFileByPath(PATH)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"237939351","text":"import functools\nimport json\nimport subprocess\n\nfrom qhub.provider.cloud.commons import filter_by_highest_supported_k8s_version\n\n\n@functools.lru_cache()\ndef projects():\n output = subprocess.check_output([\"gcloud\", \"projects\", \"list\", \"--format=json\"])\n data = json.loads(output.decode(\"utf-8\"))\n return {_[\"name\"]: _[\"projectId\"] for _ in data}\n\n\n@functools.lru_cache()\ndef regions(project):\n output = subprocess.check_output(\n [\"gcloud\", \"compute\", \"regions\", \"list\", \"--project\", project, \"--format=json\"]\n )\n data = json.loads(output.decode(\"utf-8\"))\n return {_[\"description\"]: _[\"name\"] for _ in data}\n\n\n@functools.lru_cache()\ndef zones(project, region):\n output = subprocess.check_output(\n [\"gcloud\", \"compute\", \"zones\", \"list\", \"--project\", project, \"--format=json\"]\n )\n data = json.loads(output.decode(\"utf-8\"))\n return {_[\"description\"]: _[\"name\"] for _ in data if _[\"name\"].startswith(region)}\n\n\n@functools.lru_cache()\ndef kubernetes_versions(region):\n \"\"\"Return list of available kubernetes supported by cloud provider. Sorted from oldest to latest.\"\"\"\n\n output = subprocess.check_output(\n [\n \"gcloud\",\n \"container\",\n \"get-server-config\",\n \"--region\",\n region,\n \"--format=json\",\n ]\n )\n data = json.loads(output.decode(\"utf-8\"))\n supported_kubernetes_versions = sorted([_ for _ in data[\"validMasterVersions\"]])\n return filter_by_highest_supported_k8s_version(supported_kubernetes_versions)\n\n\n@functools.lru_cache()\ndef instances(project):\n output = subprocess.check_output(\n [\n \"gcloud\",\n \"compute\",\n \"machine-types\",\n \"list\",\n \"--project\",\n project,\n \"--format=json\",\n ]\n )\n data = json.loads(output.decode(\"utf-8\"))\n return {_[\"description\"]: _[\"name\"] for _ in data}\n\n\n# Getting pricing data could come from here\n# https://cloudpricingcalculator.appspot.com/static/data/pricelist.json\n","sub_path":"qhub/provider/cloud/google_cloud.py","file_name":"google_cloud.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"416435846","text":"from splinter import Browser\nfrom bs4 import BeautifulSoup as bs\nimport pandas as pd\nimport datetime as dt\nimport time\n# import warnings\n\n# warnings.filterwarnings('ignore')\n\n\n\ndef scrape_all():\n\n # Initiate headless driver for deployment\n executable_path = {'executable_path': 'chromedriver'}\n browser = Browser('chrome', **executable_path)\n \n news_title, news_paragraph = mars_news(browser)\n\n # Run all scraping functions and store in dictionary.\n data = {\n \"news_title\": news_title,\n \"news_paragraph\": news_paragraph,\n \"featured_image\": featured_image(browser),\n \"hemispheres\": hemispheres(browser),\n \"weather\": twitter_weather(browser),\n \"facts\": mars_facts(),\n \"last_modified\": dt.datetime.now()\n }\n\n # Stop webdriver and return data\n browser.quit()\n return data\n\n\ndef mars_news(browser):\n url = \"https://mars.nasa.gov/news/\"\n browser.visit(url)\n #write your code here\n # Optional delay for loading the page\n browser.is_element_present_by_css(\"ul.item_list li.slide\", wait_time=1)\n # HTML Object\n html = browser.html\n # Parse HTML with Beautiful Soup\n soup = bs(html, 'html.parser')\n # Retrieve the latest element that contains news title and news_paragraph\n new_soup = soup.select_one(\"ul.item_list li.slide\")\n news_title = new_soup.find('div', class_='content_title').find('a').text\n news_paragraph = new_soup.find('div', class_='article_teaser_body').text\n \n return news_title, news_paragraph\n\n\ndef featured_image(browser):\n url = \"https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars\"\n browser.visit(url)\n\n # HTML Object \n html_image = browser.html\n\n # Parse HTML with Beautiful Soup\n soup = bs(html_image, \"html.parser\")\n\n # Retrieve background-image url from style tag \n image_url = soup.find('article')['style'].replace('background-image: url(','').replace(');', '')[1:-1]\n\n # Website Url \n main_url = \"https://www.jpl.nasa.gov\"\n\n # Concatenate website url with scrapped route\n image_url = main_url + image_url\n\n return image_url\n\n\ndef hemispheres(browser):\n\n # A way to break up long strings\n url = (\n \"https://astrogeology.usgs.gov/search/\"\n \"results?q=hemisphere+enhanced&k1=target&v1=Mars\"\n )\n\n browser.visit(url)\n\n html = browser.html\n\n # Parse HTML with Beautiful Soup\n soup = bs(html, \"html.parser\")\n\n # Create dictionary to store titles & links to images\n hemisphere_image_urls = []\n\n # Retrieve all elements that contain image information\n results = soup.find(\"div\", class_ = \"result-list\" )\n hemispheres = results.find_all(\"div\", class_=\"item\")\n\n # Iterate through each image\n for hemisphere in hemispheres:\n title = hemisphere.find(\"h3\").text\n title = title.replace(\"Enhanced\", \"\")\n end_link = hemisphere.find(\"a\")[\"href\"]\n image_link = \"https://astrogeology.usgs.gov/\" + end_link \n browser.visit(image_link)\n html = browser.html\n soup = bs(html, \"html.parser\")\n downloads = soup.find(\"div\", class_=\"downloads\")\n image_url = downloads.find(\"a\")[\"href\"]\n hemisphere_image_urls.append({\"title\": title, \"img_url\": image_url})\n\n return hemisphere_image_urls\n\n\ndef twitter_weather(browser):\n url = \"https://twitter.com/marswxreport?lang=en\"\n browser.visit(url)\n\n # wait couple of seconds to load the page. Otherwise search for weather tweets returns null.\n time.sleep(2)\n\n html = browser.html\n soup = bs(html, \"html.parser\")\n\n # Find all elements that contain tweets \n latest_tweets = soup.find_all('div', class_='css-901oao r-hkyrab r-1qd0xha r-a023e6 r-16dba41 r-ad9z0x r-bcqeeo r-bnwqim r-qvutc0')\n # # Retrieve all elements that contain news title in the specified range\n # # Look for entries that display weather related words to exclude non weather related tweets \n\n for tweet in latest_tweets:\n if 'sol' and 'pressure' in tweet.text:\n mars_weather = tweet.text\n break\n else: \n pass\n \n return mars_weather\n\ndef mars_facts():\n try:\n df = pd.read_html(\"http://space-facts.com/mars/\")[0]\n except BaseException:\n return None\n\n df.columns = [\"Description\", \"Value\"]\n # df.set_index(\"description\", inplace=True)\n\n # Add some bootstrap styling to \n return df.to_html(classes=\"table table-striped\", index=False)\n\n\nif __name__ == \"__main__\":\n\n # If running as script, print scraped data\n print(scrape_all())","sub_path":"Mission_to_Mars/app/scrape_mars.py","file_name":"scrape_mars.py","file_ext":"py","file_size_in_byte":4562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"522510901","text":"import discord\r\nfrom discord.ext import commands\r\nfrom discord.ext import tasks\r\nfrom itertools import cycle\r\n\r\nbot = commands.Bot(command_prefix = \".\")\r\nstatus = cycle(['Coding Server with \\'.\\'','by Anonyme#5137'])\r\n\r\n\r\n@bot.event\r\nasync def on_ready():\r\n change_status.start()\r\n print('Mod is ready to be used')\r\n\r\n\r\n\r\n\r\n#Commands to use\r\n@bot.command(aliases=['h','assist','aide'])\r\nasync def command(ctx): \r\n await ctx.send('`Prefix to use` : \\\"**.**\\\"')\r\n await ctx.send('**.clear [amount of message to delete]** \\n*delete specific number of messages*\\n_e.g : **.clear 5**_\\n --------------------')\r\n await ctx.send('**.cls** \\n*clears chosen channel\\'s chat*\\n_e.g : **.cls**_\\n --------------------')\r\n await ctx.send('**.kick [Player Tag]** \\n*Kicks the player from the server*\\n_e.g : **.kick Discord#0000** or **.kick @Discord**_\\n --------------------')\r\n await ctx.send('**.ban [Player Tag]** \\n*Bans the player from the server*\\n_e.g : **.ban Discord#0000** or **.kick @Discord**_\\n --------------------')\r\n await ctx.send('**.unban [Player Tag]** \\n*Unbans the player from the server*\\n_e.g : **.unban** or **Discord#0000**_\\n --------------------')\r\n await ctx.send('**.e** *or* **.event [\"Event\"** + **\"Date/Timing\"**] \\n*Create an event\\'s announcement that contains an Event and its date/timing*\\n_e.g : **.event** or **.e \"Summer Travel to...\" \"17:00 am - Place\"**_\\n___USE QUOTES FOR **\"EVENT\"** and **\"DATE\"**, SEPARATED WITH SPACE___\\n --------------------')\r\n await ctx.send('MORE FEATURES COMMING SOON\\n --------------------')\r\n\r\n\r\n\r\n@tasks.loop(seconds=3)\r\nasync def change_status():\r\n await bot.change_presence(activity=discord.Game(next(status)))\r\n\r\n\r\n#CLEAR + ROLE NEEDED\r\n@bot.command()\r\n@commands.has_any_role('bot','Dad','Admin')\r\nasync def clear(ctx, amount = 5):\r\n await ctx.channel.purge(limit=amount)\r\n\r\n\r\n@clear.error\r\nasync def clear_error(ctx, error):\r\n if isinstance(error, commands.MissingAnyRole):\r\n await ctx.send('You need \\\"**`Dad`**\\\" or \\\"**`bot`**\\\" role or \\\"**`Admin`**\\\" role.')\r\n\r\n \r\n\r\n#CLS + ROLE NEEDED\r\n@bot.command()\r\n@commands.has_any_role('Dad','bot','Admin')\r\nasync def cls(ctx, amount = 999999999999999999999999999999999999999999999999999999999999):\r\n await ctx.channel.purge(limit=amount)\r\n\r\n@cls.error\r\nasync def cls_error(ctx, error):\r\n if isinstance(error, commands.MissingAnyRole):\r\n await ctx.send('You need \\\"**`Dad`**\\\" or \\\"**`bot`**\\\" role or \\\"**`Admin`**\\\" role.') \r\n\r\n\r\n\r\n\r\n\r\n\r\n#REMOVE\r\n@bot.command()\r\n@commands.has_any_role('bot','Dad','Admin')\r\nasync def kick(ctx, member : discord.Member, *, reason = None ):\r\n await member.kick(reason=reason)\r\n await ctx.send(f'{member.mention} was kicked from the server')\r\n\r\n@kick.error\r\nasync def kick_error(ctx, error):\r\n if isinstance(error, commands.MissingAnyRole):\r\n await ctx.send('You need \\\"**`Dad`**\\\" or \\\"**`bot`**\\\" role or \\\"**`Admin`**\\\" role.')\r\n\r\n\r\n#ban\r\n@bot.command()\r\n@commands.has_any_role('bot','Dad','Admin')\r\nasync def ban(ctx, member : discord.Member, *, reason = None ):\r\n await member.ban(reason=reason)\r\n await ctx.send(f'{member.name}#{member.discriminator} was banned from the server')\r\n\r\n@ban.error\r\nasync def ban_error(ctx, error):\r\n if isinstance(error, commands.MissingAnyRole):\r\n await ctx.send('You need \\\"**`Dad`**\\\" or \\\"**`bot`**\\\" role or \\\"**`Admin`**\\\" role.')\r\n\r\n\r\n\r\n#unban\r\n@bot.command(aliases=['uba'])\r\n@commands.has_any_role('bot','Dad','Admin')\r\nasync def unban(ctx, *, member):\r\n banned_users_list = await ctx.guild.bans()\r\n member_name, member_discriminator = member.split(\"#\")\r\n \r\n for ban_entry in banned_users_list:\r\n user = ban_entry.user\r\n\r\n if (user.name, user.discriminator) == (member_name, member_discriminator):\r\n await ctx.guild.unban(user)\r\n await ctx.send(f'{user.mention} was unbanned')\r\n return\r\n\r\n@unban.error\r\nasync def unban_error(ctx, error):\r\n if isinstance(error, commands.MissingAnyRole):\r\n await ctx.send('You need \\\"**`Dad`**\\\" or \\\"**`bot`**\\\" role or \\\"**`Admin`**\\\" role.')\r\n\r\n\r\n#Annonce\r\n@bot.command(aliases=['e', 'event'])\r\n@commands.has_any_role('bot','Dad','Admin')\r\nasync def evenement(ctx, a, b):\r\n await ctx.send('```diff\\n-Announcement:\\n```\\n```ini\\n[Event: {}]\\n```\\n```json\\n\\\"Date: {}\\\"\\n```'.format(a.capitalize(),b.capitalize()))\r\n\r\n@evenement.error\r\nasync def evenement_error(ctx, error):\r\n if isinstance(error, commands.MissingAnyRole):\r\n await ctx.send('You need \\\"**`Dad`**\\\" or \\\"**`bot`**\\\" role or \\\"**`Admin`**\\\" role.')\r\n \r\n \r\n \r\ntoken = 't2NzE4MjczNDU4MTI2OTc5MDgy.Xt5xsw.B4M7uKFMu3j49p3ynqAFw08G3Rg'\r\ntoken_print = ''.join(token[2:])\r\n\r\n\r\nbot.run(token_print)\r\n\r\n","sub_path":"modBot.py","file_name":"modBot.py","file_ext":"py","file_size_in_byte":4800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"343797870","text":"\"\"\"General TensorFlow ops.\"\"\"\n\n# Copyright 2015 Google Inc. All Rights Reserved.\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 tensorflow as tf\nfrom tensorflow.models.rnn import linear\n\n\ndef embedding_lookup(params, ids, name=\"embedding_lookup\"):\n \"\"\"Provides a N dimensional version of tf.embedding_lookup.\n\n Ids are flattened to a 1d tensor before being passed to embedding_lookup\n then, they are unflattend to match the original ids shape plus an extra\n leading dimension of the size of the embeddings.\n\n Args:\n params: List of tensors of size D0 x D1 x ... x Dn-2 x Dn-1.\n ids: N-dimensional tensor of B0 x B1 x .. x Bn-2 x Bn-1.\n Must contain indexes into params.\n name: Optional name for the op.\n\n Returns:\n A tensor of size B0 x B1 x .. x Bn-2 x Bn-1 x D1 x ... x Dn-2 x Dn-1 containing the values from\n the params tensor(s) for indecies in ids.\n\n Raises:\n ValueError: if some parameters are invalid.\n \"\"\"\n with tf.op_scope([params, ids], name, \"embedding_lookup\"):\n params = tf.convert_to_tensor(params)\n ids = tf.convert_to_tensor(ids)\n shape = tf.shape(ids)\n ids_flat = tf.reshape(ids, tf.reduce_prod(shape, keep_dims=True))\n embeds_flat = tf.nn.embedding_lookup(params, ids_flat, name)\n embed_shape = tf.concat(0, [shape, [-1]])\n embeds = tf.reshape(embeds_flat, embed_shape)\n embeds.set_shape(ids.get_shape().concatenate(params.get_shape()[1:]))\n return embeds\n\n\ndef categorical_variable(tensor_in, n_classes, embedding_size, name):\n \"\"\"Creates an embedding for categorical variable with given number of\n classes.\n\n Args:\n tensor_in: Input tensor with class identifier (can be batch or\n N-dimensional).\n n_classes: Number of classes.\n embedding_size: Size of embedding vector to represent each class.\n name: Name of this categorical variable.\n Returns:\n Tensor of input shape, with additional dimension for embedding.\n\n Example:\n Calling categorical_variable([1, 2], 5, 10, \"my_cat\"), will return 2 x 10\n tensor, where each row is representation of the class.\n \"\"\"\n with tf.variable_scope(name):\n embeddings = tf.get_variable(name + \"_embeddings\", [n_classes, embedding_size])\n return embedding_lookup(embeddings, tensor_in)\n\n\ndef mean_squared_error_regressor(tensor_in, labels, weights, biases, name=None):\n \"\"\"Returns prediction and loss for mean squared error regression.\"\"\"\n with tf.op_scope([tensor_in, labels], name, \"mean_squared_error_regressor\"):\n predictions = tf.nn.xw_plus_b(tensor_in, weights, biases)\n diff = predictions - labels\n loss = tf.reduce_mean(tf.mul(diff, diff))\n return predictions, loss\n\n\ndef softmax_classifier(tensor_in, labels, weights, biases, name=None):\n \"\"\"Returns prediction and loss for softmax classifier.\"\"\"\n with tf.op_scope([tensor_in, labels], name, \"softmax_classifier\"):\n logits = tf.nn.xw_plus_b(tensor_in, weights, biases)\n xent = tf.nn.softmax_cross_entropy_with_logits(logits,\n labels,\n name=\"xent_raw\")\n loss = tf.reduce_mean(xent, name=\"xent\")\n predictions = tf.nn.softmax(logits, name=name)\n return predictions, loss\n\n\ndef dnn(tensor_in, hidden_units, activation=tf.nn.relu, keep_prob=None):\n \"\"\"Creates fully connected deep neural network subgraph.\n\n Args:\n tenson_in: tensor or placeholder for input features.\n hidden_units: list of counts of hidden units in each layer.\n activation: activation function between layers.\n keep_proba: if not None, will add a dropout layer with given\n probability. \n\n Returns:\n A tensor which would be a deep neural network.\n \"\"\"\n with tf.variable_scope('dnn'):\n for i, n_units in enumerate(hidden_units):\n with tf.variable_scope('layer%d' % i):\n tensor_in = linear.linear(tensor_in, n_units, True)\n tensor_in = activation(tensor_in)\n if keep_prob:\n tensor_in = tf.nn.dropout(tensor_in, keep_prob)\n return tensor_in\n\n\ndef conv2d(tensor_in, n_filters, filter_shape, strides=None, padding='SAME',\n bias=True):\n \"\"\"Creates 2D convolutional subgraph with bank of filters.\n\n Uses tf.nn.conv2d under the hood.\n Creates a filter bank:\n [filter_shape[0], filter_shape[1], tensor_in[3], n_filters]\n and applies it to the input tensor.\n\n Args:\n tensor_in: input Tensor, 4D shape: \n [batch, in_height, in_width, in_depth].\n n_filters: number of filters in the bank.\n filter_shape: Shape of filters, a list of ints, 1-D of length 2.\n strides: A list of ints, 1-D of length 4. The stride of the sliding\n window for each dimension of input.\n padding: A string: 'SAME' or 'VALID'. The type of padding algorthim to\n use.\n bias: Boolean, if to add bias.\n Returns:\n A Tensor with resuling convolution.\n \"\"\"\n with tf.variable_scope('convolution'):\n if strides is None: strides = [1, 1, 1, 1]\n input_shape = tensor_in.get_shape()\n filter_shape = list(filter_shape) + [input_shape[3], n_filters]\n filters = tf.get_variable('filters', filter_shape, tf.float32)\n output = tf.nn.conv2d(tensor_in, filters, strides, padding)\n if bias:\n bias_var = tf.get_variable('bias', [1, 1, 1, n_filters],\n tf.float32)\n output = output + bias_var\n return output\n\n","sub_path":"skflow/ops.py","file_name":"ops.py","file_ext":"py","file_size_in_byte":6250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"477840961","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport threading\n\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nimport requests\n\n\n# In[ ]:\n\n\n## firebase와의 연동\n\n\n# In[2]:\n\n\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import db\n\n# Fetch the service account key JSON file contents\ncred = credentials.Certificate(open('realace2018-firebase-adminsdk-r7gk1-121be5edaf.json').read())\n\n# Initialize the app with a service account, granting admin privileges\napp=firebase_admin.initialize_app(cred, {\n 'databaseURL': 'https://realace2018.firebaseio.com/'\n})\n\nref=db.reference()\n\n\n# In[ ]:\n\n\n## \n\n\n# In[3]:\n\n\nserviceKey='F%2FxP1NfaTBhw0giVbsH7HTUMMnbJF6p9LhD9p8mJ4HpucMsVcxUzoTw4RxZDFdnRP3NgWj0IwJke%2FOzfe5VxhA%3D%3D'\nnumOfRows=[25, 16, 8, 9, 5, 5, 5, 31, 6, 7, 14, 12, 9, 1, 9, 9, 3]\nsidoName=['서울', '부산', '대구', '인천', '광주', '대전', '울산', '경기', '강원', '충북', '충남', '전북', '전남', '세종', '경북', '경남', '제주']\n\n\n# In[ ]:\n\n\n## firebase저장 함수\n\n\n# In[9]:\n\n\n\ndef func():\n timer=threading.Timer(3600,func)\n \n for number in range(0,17):\n url='http://openapi.airkorea.or.kr/openapi/services/rest/ArpltnInforInqireSvc/getCtprvnMesureSidoLIst?serviceKey='+str(serviceKey)+'&numOfRows='+str(numOfRows[number])+'&pageSize=10&pageNo=1&startPage=1&sidoName='+str(sidoName[number])+'&searchCondition=DAILY'\n html=requests.get(url).text\n soup = BeautifulSoup(html, 'html.parser')\n \n citylist=[]\n pm10list=[]\n timelist=[]\n\n datatime=soup.find_all('datatime')\n cityname=soup.find_all('cityname')\n pm10vale=soup.find_all('pm10value')\n\n for code in datatime:\n timelist.append(code.text)\n for code in cityname:\n citylist.append(code.text)\n for code in pm10vale:\n pm10list.append(code.text)\n \n numb=numOfRows[number]\n \n for num in range(0,numb):\n users_ref= ref.child('pm')\n users_ref.push({'sidoname':sidoName[number],'cityname':citylist[int(num)], 'pm10vale':pm10list[int(num)],'datatime':timelist[int(num)]})\n \n timer.start()\n\nfunc()\n\n","sub_path":"api/APIfirebase.py","file_name":"APIfirebase.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"29760291","text":"from django.urls import path, include\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.home),\n path(\"invite/\", views.invite),\n path(\"discord/\", views.discord),\n path(\"info/maker/\", views.maker),\n path(\"info/bot/\", views.bot),\n path(\"user//\", views.search_user),\n path(\"search/\", views.search),\n]\n","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"240933798","text":"from levels.levels import dummy\nimport serial\nfrom time import sleep\nfrom config import COM, BAUDRATE, TIMEOUT, SINGLE_PRESS_DURATION,\\\n CENTER, HAT_CENTER\n\ncommands = dummy\n\n\ndef SplitHex(num):\n return [(num >> 8), (num & 0xFF)]\n\n\ndef Timeout(time=SINGLE_PRESS_DURATION):\n print(\"timeout for:\", time,\n \"ms\")\n sleep(time/1000)\n\n\ndef Command(lx=CENTER, ly=CENTER, rx=CENTER, ry=CENTER, hat=HAT_CENTER, button=0):\n print(\"sending:\", lx, ly, rx, ry, hat, button)\n button = SplitHex(button)\n return bytearray([lx, ly, rx, ry, hat, button[0], button[1]])\n\n\nprint(\"Connecting...\")\n\nser = serial.Serial(COM, BAUDRATE, timeout=TIMEOUT)\nser.setDTR(False)\nsleep(0.022)\nser.setDTR(True)\n\nindex = 0\ntry:\n while index < len(commands):\n com = commands[index]\n case = com[0]\n if (case == None):\n ser.write(Command())\n Timeout(com[1])\n elif (case == \"GOTO\"):\n index = com[1] - 1\n elif (case == \"COPY\"):\n _tmp = commands[com[1]]\n ser.write(Command(_tmp[0], _tmp[1], _tmp[2],\n _tmp[3], _tmp[4], _tmp[5]))\n Timeout(_tmp[6] if (len(_tmp) == 7) else SINGLE_PRESS_DURATION)\n else:\n ser.write(Command(com[0], com[1], com[2], com[3], com[4], com[5]))\n Timeout(com[6] if (len(com) == 7) else SINGLE_PRESS_DURATION)\n index += 1\n ser.write(Command())\n ser.close()\nexcept KeyboardInterrupt:\n ser.write(Command())\n print(\"Exiting\")\n ser.close()\nexcept:\n raise","sub_path":"python/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"173195296","text":"adjectives = [\n 'adaptable',\n 'adventurous',\n 'admirable',\n 'affable',\n 'altruistic',\n 'amazing',\n 'ambitious',\n 'amiable',\n 'appreciative',\n 'attentive',\n 'authentic',\n 'awesome',\n 'balanced',\n 'bedazzled',\n 'beloved',\n 'bold',\n 'brave',\n 'breathtaking',\n 'bright',\n 'brilliant',\n 'calm',\n 'capable',\n 'caring',\n 'captivating',\n 'charismatic',\n 'classy',\n 'compassionate',\n 'compelling',\n 'considerate',\n 'courageous',\n 'caring',\n 'centered',\n 'charismatic',\n 'charming',\n 'cheerful',\n 'confident',\n 'creative',\n 'curious',\n 'daring',\n 'dashing',\n 'dedicated',\n 'delightful',\n 'dependable',\n 'diligent',\n 'efficient',\n 'empathetic',\n 'encouraging',\n 'electric',\n 'energizing',\n 'engaging',\n 'exuberant',\n 'exceptional',\n 'exquisite',\n 'extraordinary',\n 'fabulous',\n 'fantastic',\n 'fearless',\n 'fierce',\n 'focused',\n 'friendly',\n 'generous',\n 'genuine',\n 'glorious',\n 'graceful',\n 'gregarious',\n 'groovy',\n 'grounded',\n 'giving',\n 'hardworking',\n 'helpful',\n 'honest',\n 'incredible',\n 'insightful',\n 'inventive',\n 'inspiring',\n 'intelligent',\n 'interesting',\n 'jazzy',\n 'joyful',\n 'jubilant',\n 'kind',\n 'lovable',\n 'loving',\n 'loyal',\n 'lively',\n 'magnificent',\n 'marvelous',\n 'mighty',\n 'motivated',\n 'outstanding',\n 'optimistic',\n 'passionate',\n 'perceptive',\n 'phenomenal',\n 'profound',\n 'proactive',\n 'powerful',\n 'purposeful',\n 'radiant',\n 'reflective',\n 'relaxed',\n 'reliable',\n 'remarkable',\n 'resourceful',\n 'respectable',\n 'responsible',\n 'resilient',\n 'sassy',\n 'sincere',\n 'skillful',\n 'soaring',\n 'soothing',\n 'special',\n 'splendid',\n 'stellar',\n 'sublime',\n 'superb',\n 'strong',\n 'stunning',\n 'talented',\n 'terrific',\n 'tenacious',\n 'thoughtful',\n 'thriving',\n 'trusting',\n 'vibrant',\n 'vivacious',\n 'warm',\n 'wise',\n 'witty',\n 'wonderful',\n 'zappy',\n 'zestful'\n]","sub_path":"src/scripts/adj.py","file_name":"adj.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"370891678","text":"import numpy as np\nfrom utils import deg2rad, rad2deg, normalize_angle_deg\nfrom BackUp import BackUp\nimport random\n\n\n\ndef dist_to_rock(Rover):\n idx_in_front = np.where(np.abs(Rover.obs_angles) < deg2rad(2.5))[0]\n\n if not len(idx_in_front):\n print(\"Dist to rock: N/A\")\n return None\n\n min_dist = np.min(Rover.rock_dists[idx_in_front])\n print(\"Dist to rock: %.2f\" % min_dist)\n return min_dist\n\n\n\n\n\n\ndef update_steering(Rover):\n Rover.steer = calc_steering_angle(Rover)\n\n\n\ndef update_throttle(Rover):\n if Rover.objective == 'mapping':\n target_velocity = Rover.max_vel\n throttle = Rover.throttle_set\n else:\n target_velocity = 0.5\n throttle = 0.1\n\n if Rover.vel < target_velocity:\n Rover.throttle = throttle\n else:\n Rover.throttle = 0\n\n\ndef stop_rover(Rover):\n Rover.throttle = 0\n Rover.brake = Rover.brake_set\n Rover.steer = 0\n Rover.mode = 'stop'\n\n\ndef turn_rover(Rover, rate=-15):\n Rover.throttle = 0\n Rover.brake = 0\n Rover.steer = rate # Could be more clever here about which way to turn\n\n\ndef decision_step(Rover):\n if Rover.home_pos is None:\n assert(Rover.pos is not None)\n Rover.home_pos = Rover.pos\n\n\n if Rover.stuck_counter > 100 and not type(Rover.state_machine.current_state()) == type(BackUp) :\n Rover.state_machine.push_front(BackUp(Rover))\n Rover.stuck_counter = 0\n\n Rover.state_machine.run()\n\n if abs(Rover.throttle) > 0:\n if abs(Rover.vel) < 0.2:\n Rover.stuck_counter += 1\n else:\n Rover.stuck_counter = 0\n\n return Rover\n\n","sub_path":"code/decision.py","file_name":"decision.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"276507477","text":"import base64\nimport json\nimport logging\nimport re\nimport socket\nimport time\nfrom telnetlib import Telnet\nfrom threading import Thread\nfrom typing import Optional, Union\n\nfrom paho.mqtt.client import Client, MQTTMessage\nfrom . import bluetooth, utils\nfrom .miio_fix import Device\nfrom .unqlite import Unqlite, SQLite\nfrom .utils import GLOBAL_PROP\n\n_LOGGER = logging.getLogger(__name__)\n\nRE_NWK_KEY = re.compile(r'lumi send-nwk-key (0x.+?) {(.+?)}')\n\n\nclass Gateway3(Thread):\n pair_model = None\n pair_payload = None\n\n def __init__(self, host: str, token: str, config: dict, ble: bool = True,\n zha: bool = False):\n super().__init__(daemon=True)\n\n self.host = host\n self.zha = zha\n\n self.miio = Device(host, token)\n\n self.mqtt = Client()\n self.mqtt.on_connect = self.on_connect\n self.mqtt.on_disconnect = self.on_disconnect\n self.mqtt.on_message = self.on_message\n self.mqtt.connect_async(host)\n\n self.ble = GatewayBLE(self) if ble else None\n\n self.debug = config['debug'] if 'debug' in config else ''\n self.default_devices = config['devices']\n\n self.devices = {}\n self.updates = {}\n self.setups = {}\n\n @property\n def device(self):\n return self.devices['lumi.0']\n\n def add_update(self, did: str, handler):\n \"\"\"Add handler to device update event.\"\"\"\n self.updates.setdefault(did, []).append(handler)\n\n def add_setup(self, domain: str, handler):\n \"\"\"Add hass device setup funcion.\"\"\"\n self.setups[domain] = handler\n\n def run(self):\n \"\"\"Main loop\"\"\"\n while True:\n # if not telnet - enable it\n if not self._check_port(23) and not self._enable_telnet():\n time.sleep(30)\n continue\n\n devices = self._get_devices_v3()\n if devices:\n self.setup_devices(devices)\n break\n\n # start bluetooth read loop\n if self.ble:\n self.ble.start()\n\n while True:\n # if not telnet - enable it\n if not self._check_port(23) and not self._enable_telnet():\n time.sleep(30)\n continue\n\n if not self.zha:\n # if not mqtt - enable it\n if not self._mqtt_connect() and not self._enable_mqtt():\n time.sleep(60)\n continue\n\n self.mqtt.loop_forever()\n\n elif not self._check_port(8888) and not self._enable_zha():\n time.sleep(60)\n continue\n\n else:\n # ZHA works fine, check every 60 seconds\n time.sleep(60)\n\n def _check_port(self, port: int):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n return s.connect_ex((self.host, port)) == 0\n finally:\n s.close()\n\n def _mqtt_connect(self) -> bool:\n try:\n self.mqtt.reconnect()\n return True\n except:\n return False\n\n def _miio_connect(self) -> bool:\n try:\n self.miio.send_handshake()\n return True\n except:\n _LOGGER.debug(f\"{self.host} | Can't send handshake\")\n return False\n\n def _get_devices_v1(self) -> Optional[list]:\n \"\"\"Load devices via miio protocol.\"\"\"\n _LOGGER.debug(f\"{self.host} | Read devices\")\n try:\n devices = {}\n\n # endless loop protection\n for _ in range(16):\n # load only 8 device per part\n part = self.miio.send('get_device_list', retry_count=10)\n if len(part) == 0:\n return []\n\n for item in part:\n devices[item['num']] = {\n 'did': item['did'],\n 'mac': f\"0x{item['did'][5:]}\",\n 'model': item['model'],\n }\n\n if part[0]['total'] == len(devices):\n break\n\n devices = list(devices.values())\n for device in devices:\n desc = utils.get_device(device['model'])\n # skip unknown model\n if desc is None:\n continue\n # get xiaomi param names\n params = [p[1] for p in desc['params'] if p[1] is not None]\n # skip if don't have retain params\n if not params:\n continue\n # load param values\n values = self.miio.send('get_device_prop',\n [device['did']] + params)\n # get hass param names\n params = [p[2] for p in desc['params'] if p[1] is not None]\n\n data = dict(zip(params, values))\n # fix some param values\n for k, v in data.items():\n if k in ('temperature', 'humidity'):\n data[k] = v / 100.0\n elif v in ('on', 'open'):\n data[k] = 1\n elif v in ('off', 'close'):\n data[k] = 0\n\n device['init'] = data\n\n device = self.miio.info()\n devices.append({\n 'did': 'lumi.0',\n 'mac': device.mac_address, # wifi mac!!!\n 'model': device.model\n })\n\n return devices\n\n except Exception as e:\n _LOGGER.exception(f\"{self.host} | Get devices: {e}\")\n return None\n\n def _get_devices_v2(self) -> Optional[list]:\n \"\"\"Load device list via Telnet.\n\n Device desc example:\n mac: '0x158d0002c81234'\n shortId: '0x0691'\n manuCode: '0x115f'\n model: 'lumi.sensor_ht'\n did: 'lumi.158d0002c81234'\n devType: 0\n appVer: 2\n hardVer: 0\n devID: 770\n status: 0\n model_ver: 2\n \"\"\"\n _LOGGER.debug(f\"{self.host} | Read devices\")\n try:\n telnet = Telnet(self.host)\n telnet.read_until(b\"login: \")\n telnet.write(b\"admin\\r\\n\")\n telnet.read_until(b'\\r\\n# ') # skip greeting\n\n telnet.write(b\"cat /data/zigbee/coordinator.info\\r\\n\")\n telnet.read_until(b'\\r\\n') # skip command\n raw = telnet.read_until(b'# ')\n device = json.loads(raw[:-2])\n device.update({\n 'did': 'lumi.0',\n 'model': 'lumi.gateway.mgl03',\n 'host': self.host\n })\n\n devices = [device]\n\n telnet.write(b\"cat /data/zigbee/device.info\\r\\n\")\n telnet.read_until(b'\\r\\n') # skip command\n raw = telnet.read_until(b'# ')\n raw = json.loads(raw[:-2])\n devices += raw['devInfo']\n telnet.close()\n\n return devices\n except Exception as e:\n _LOGGER.exception(f\"Can't read devices: {e}\")\n return None\n\n def _get_devices_v3(self):\n \"\"\"Load device list via Telnet.\"\"\"\n _LOGGER.debug(f\"{self.host} | Read devices\")\n try:\n telnet = Telnet(self.host, timeout=5)\n telnet.read_until(b\"login: \")\n telnet.write(b\"admin\\r\\n\")\n telnet.read_until(b'\\r\\n# ') # skip greeting\n\n # read coordinator info\n telnet.write(b\"cat /data/zigbee/coordinator.info\\r\\n\")\n telnet.read_until(b'\\r\\n') # skip command\n raw = telnet.read_until(b'# ')\n\n device = json.loads(raw[:-2])\n devices = [{\n 'did': 'lumi.0',\n 'model': 'lumi.gateway.mgl03',\n 'mac': device['mac'],\n 'type': 'gateway'\n }]\n\n if self.zha:\n return devices\n\n # https://github.com/AlexxIT/XiaomiGateway3/issues/14\n # fw 1.4.6_0012 and below have one zigbee_gw.db file\n # fw 1.4.6_0030 have many json files in this folder\n telnet.write(b\"cat /data/zigbee_gw/* | base64\\r\\n\")\n telnet.read_until(b'\\r\\n') # skip command\n raw = telnet.read_until(b'# ')\n raw = base64.b64decode(raw)\n if raw.startswith(b'unqlite'):\n db = Unqlite(raw)\n data = db.read_all()\n else:\n raw = re.sub(br'}\\s+{', b',', raw)\n data = json.loads(raw)\n\n # data = {} or data = {'dev_list': 'null'}\n dev_list = json.loads(data.get('dev_list', 'null')) or []\n _LOGGER.debug(f\"{self.host} | Load {len(dev_list)} zigbee devices\")\n\n for did in dev_list:\n model = data[did + '.model']\n desc = utils.get_device(model)\n\n # skip unknown model\n if desc is None:\n _LOGGER.debug(f\"{did} has an unsupported modell: {model}\")\n continue\n\n retain = json.loads(data[did + '.prop'])['props']\n _LOGGER.debug(f\"{self.host} | {did} {model} retain: {retain}\")\n\n params = {\n p[2]: retain.get(p[1])\n for p in desc['params']\n if p[1] is not None\n }\n\n device = {\n 'did': did,\n 'mac': '0x' + data[did + '.mac'],\n 'model': data[did + '.model'],\n 'type': 'zigbee',\n 'zb_ver': data[did + '.version'],\n 'init': utils.fix_xiaomi_props(params),\n 'online': retain.get('alive', 1) == 1\n }\n devices.append(device)\n\n return devices\n\n except (ConnectionRefusedError, socket.timeout):\n return None\n\n except Exception as e:\n _LOGGER.debug(f\"Can't read devices: {e}\")\n return None\n\n def _enable_telnet(self):\n _LOGGER.debug(f\"{self.host} | Try enable telnet\")\n try:\n resp = self.miio.send(\"enable_telnet_service\")\n return resp[0] == 'ok'\n except Exception as e:\n _LOGGER.debug(f\"Can't enable telnet: {e}\")\n return False\n\n def _enable_mqtt(self):\n _LOGGER.debug(f\"{self.host} | Try run public MQTT\")\n try:\n telnet = Telnet(self.host)\n telnet.read_until(b\"login: \")\n telnet.write(b\"admin\\r\\n\")\n telnet.read_until(b\"\\r\\n# \") # skip greeting\n\n # enable public mqtt\n telnet.write(b\"killall mosquitto\\r\\n\")\n telnet.read_until(b\"\\r\\n\") # skip command\n time.sleep(.5) # it's important to wait\n telnet.write(b\"mosquitto -d\\r\\n\")\n telnet.read_until(b\"\\r\\n\") # skip command\n time.sleep(.5) # it's important to wait\n\n # fix CPU 90% full time bug\n telnet.write(b\"killall zigbee_gw\\r\\n\")\n telnet.read_until(b\"\\r\\n\") # skip command\n time.sleep(.5) # it's important to wait\n\n telnet.close()\n return True\n except Exception as e:\n _LOGGER.debug(f\"Can't run MQTT: {e}\")\n return False\n\n def _enable_zha(self):\n _LOGGER.debug(f\"{self.host} | Try enable ZHA\")\n try:\n check_socat = \\\n \"(md5sum /data/socat | grep 92b77e1a93c4f4377b4b751a5390d979)\"\n download_socat = \\\n \"(curl -o /data/socat http://pkg.musl.cc/socat/\" \\\n \"mipsel-linux-musln32/bin/socat && chmod +x /data/socat)\"\n run_socat = \"/data/socat tcp-l:8888,reuseaddr,fork /dev/ttyS2\"\n\n telnet = Telnet(self.host, timeout=5)\n telnet.read_until(b\"login: \")\n telnet.write(b\"admin\\r\\n\")\n telnet.read_until(b\"\\r\\n# \") # skip greeting\n\n # download socat and check md5\n telnet.write(f\"{check_socat} || {download_socat}\\r\\n\".encode())\n raw = telnet.read_until(b\"\\r\\n# \")\n if b\"Received\" in raw:\n _LOGGER.debug(f\"{self.host} | Downloading socat\")\n\n telnet.write(f\"{check_socat} && {run_socat} &\\r\\n\".encode())\n telnet.read_until(b\"\\r\\n# \")\n\n telnet.write(\n b\"killall daemon_app.sh; killall Lumi_Z3GatewayHost_MQTT\\r\\n\")\n telnet.read_until(b\"\\r\\n# \")\n\n telnet.close()\n return True\n\n except Exception as e:\n _LOGGER.debug(f\"Can't enable ZHA: {e}\")\n return False\n\n def on_connect(self, client, userdata, flags, rc):\n _LOGGER.debug(f\"{self.host} | MQTT connected\")\n self.mqtt.subscribe('#')\n\n self.process_gw_message({'online': True})\n\n def on_disconnect(self, client, userdata, rc):\n _LOGGER.debug(f\"{self.host} | MQTT disconnected\")\n # force end mqtt.loop_forever()\n self.mqtt.disconnect()\n\n self.process_gw_message({'online': False})\n\n def on_message(self, client: Client, userdata, msg: MQTTMessage):\n if 'mqtt' in self.debug:\n _LOGGER.debug(f\"[MQ] {msg.topic} {msg.payload.decode()}\")\n\n if msg.topic == 'zigbee/send':\n payload = json.loads(msg.payload)\n self.process_message(payload)\n elif msg.topic.endswith('/heartbeat'):\n payload = json.loads(msg.payload)\n self.process_gw_message(payload)\n elif self.pair_model and msg.topic.endswith('/commands'):\n self.process_pair(msg.payload)\n\n def setup_devices(self, devices: list):\n \"\"\"Add devices to hass.\"\"\"\n for device in devices:\n desc = utils.get_device(device['model'])\n if not desc:\n _LOGGER.debug(f\"Unsupported model: {device}\")\n continue\n\n _LOGGER.debug(f\"{self.host} | Setup Zigbee device {device}\")\n\n device.update(desc)\n\n # update params from config\n default_config = self.default_devices.get(device['mac']) or \\\n self.default_devices.get(device['did'])\n if default_config:\n device.update(default_config)\n\n self.devices[device['did']] = device\n\n for param in device['params']:\n domain = param[3]\n if not domain:\n continue\n\n # wait domain init\n while domain not in self.setups:\n time.sleep(1)\n\n attr = param[2]\n self.setups[domain](self, device, attr)\n\n def setup_mesh_devices(self, devices: list):\n for device in devices:\n desc = bluetooth.get_device(device['model'], 'Mesh')\n device.update(desc)\n\n _LOGGER.debug(f\"{self.host} | Setup Mesh device {device}\")\n\n # update params from config\n default_config = self.default_devices.get(device['did'])\n if default_config:\n device.update(default_config)\n\n device['online'] = False\n\n self.devices[device['did']] = device\n\n # wait domain init\n while 'light' not in self.setups:\n time.sleep(1)\n\n self.setups['light'](self, device, 'light')\n\n def process_message(self, data: dict):\n if data['cmd'] == 'heartbeat':\n # don't know if only one item\n assert len(data['params']) == 1, data\n\n data = data['params'][0]\n pkey = 'res_list'\n elif data['cmd'] == 'report':\n pkey = 'params' if 'params' in data else 'mi_spec'\n elif data['cmd'] in ('write_rsp', 'read_rsp'):\n pkey = 'results'\n else:\n _LOGGER.warning(f\"Unsupported cmd: {data}\")\n return\n\n did = data['did']\n\n # skip without callback\n if did not in self.updates:\n return\n\n device = self.devices[did]\n payload = {}\n\n # convert codes to names\n for param in data[pkey]:\n if param.get('error_code', 0) != 0:\n continue\n\n prop = param['res_name'] if 'res_name' in param else \\\n f\"{param['siid']}.{param['piid']}\"\n\n if prop in GLOBAL_PROP:\n prop = GLOBAL_PROP[prop]\n else:\n prop = next((p[2] for p in device['params']\n if p[0] == prop), prop)\n\n if prop in ('temperature', 'humidity', 'pressure'):\n payload[prop] = param['value'] / 100.0\n elif prop == 'battery' and param['value'] > 1000:\n # xiaomi light sensor\n payload[prop] = round((min(param['value'], 3200) - 2500) / 7)\n elif prop == 'alive':\n # {'res_name':'8.0.2102','value':{'status':'online','time':0}}\n device['online'] = (param['value']['status'] == 'online')\n elif prop == 'angle':\n # xiaomi cube 100 points = 360 degrees\n payload[prop] = param['value'] * 4\n elif prop == 'duration':\n # xiaomi cube\n payload[prop] = param['value'] / 1000.0\n elif prop in ('consumption', 'power'):\n payload[prop] = round(param['value'], 2)\n else:\n payload[prop] = param['value']\n\n _LOGGER.debug(f\"{self.host} | {device['did']} {device['model']} <= \"\n f\"{payload}\")\n\n for handler in self.updates[did]:\n handler(payload)\n\n if 'added_device' in payload:\n # {'did': 'lumi.fff', 'mac': 'fff', 'model': 'lumi.sen_ill.mgl01',\n # 'version': '21', 'zb_ver': '3.0'}\n device = payload['added_device']\n device['mac'] = '0x' + device['mac']\n device['type'] = 'zigbee'\n device['init'] = payload\n self.setup_devices([device])\n\n def process_gw_message(self, payload: json):\n _LOGGER.debug(f\"{self.host} | gateway <= {payload}\")\n\n if 'lumi.0' not in self.updates:\n return\n\n if 'networkUp' in payload:\n payload = {\n 'network_pan_id': payload['networkPanId'],\n 'radio_tx_power': payload['radioTxPower'],\n 'radio_channel': payload['radioChannel'],\n }\n elif 'online' in payload:\n self.device['online'] = payload['online']\n\n for handler in self.updates['lumi.0']:\n handler(payload)\n\n def process_pair(self, raw: bytes):\n # get shortID and eui64 of paired device\n if b'lumi send-nwk-key' in raw:\n # create model response\n payload = f\"0x18010105000042{len(self.pair_model):02x}\" \\\n f\"{self.pair_model.encode().hex()}\"\n m = RE_NWK_KEY.search(raw.decode())\n self.pair_payload = json.dumps({\n 'sourceAddress': m[1],\n 'eui64': '0x' + m[2],\n 'profileId': '0x0104',\n 'clusterId': '0x0000',\n 'sourceEndpoint': '0x01',\n 'destinationEndpoint': '0x01',\n 'APSCounter': '0x01',\n 'APSPlayload': payload\n }, separators=(',', ':'))\n\n # send model response \"from device\"\n elif b'zdo active ' in raw:\n mac = self.device['mac'][2:].upper()\n self.mqtt.publish(f\"gw/{mac}/MessageReceived\", self.pair_payload)\n\n def process_ble_event(self, raw: Union[bytes, str]):\n data = json.loads(raw[10:])['params'] \\\n if isinstance(raw, bytes) else json.loads(raw)\n\n _LOGGER.debug(f\"{self.host} | Process BLE {data}\")\n\n did = data['dev']['did']\n if did not in self.devices:\n mac = data['dev']['mac'].replace(':', '').lower() \\\n if 'mac' in data['dev'] else \\\n 'ble_' + did.replace('blt.3.', '')\n self.devices[did] = device = {\n 'did': did, 'mac': mac, 'init': {}, 'type': 'bluetooth'}\n pdid = data['dev'].get('pdid')\n desc = bluetooth.get_device(pdid, 'BLE')\n device.update(desc)\n\n # update params from config\n default_config = self.default_devices.get(did)\n if default_config:\n device.update(default_config)\n\n else:\n device = self.devices[did]\n\n if isinstance(data['evt'], list):\n # check if only one\n assert len(data['evt']) == 1, data\n payload = bluetooth.parse_xiaomi_ble(data['evt'][0])\n elif isinstance(data['evt'], dict):\n payload = bluetooth.parse_xiaomi_ble(data['evt'])\n else:\n payload = None\n\n if payload is None:\n _LOGGER.debug(f\"Unsupported BLE {data}\")\n return\n\n # init entities if needed\n for k in payload.keys():\n if k in device['init']:\n continue\n\n device['init'][k] = payload[k]\n\n domain = bluetooth.get_ble_domain(k)\n if not domain:\n continue\n\n # wait domain init\n while domain not in self.setups:\n time.sleep(1)\n\n self.setups[domain](self, device, k)\n\n if did in self.updates:\n for handler in self.updates[did]:\n handler(payload)\n\n def process_mesh_data(self, raw: Union[bytes, list]):\n data = json.loads(raw[10:])['params'] \\\n if isinstance(raw, bytes) else raw\n\n _LOGGER.debug(f\"{self.host} | Process Mesh {data}\")\n\n data = bluetooth.parse_xiaomi_mesh(data)\n for did, payload in data.items():\n device = self.devices.get(did)\n if not device:\n _LOGGER.warning(\"Unknown mesh device, reboot Hass may helps\")\n return\n\n if did in self.updates:\n for handler in self.updates[did]:\n handler(payload)\n\n def send(self, device: dict, data: dict):\n # convert hass prop to lumi prop\n params = [{\n 'res_name': next(p[0] for p in device['params'] if p[2] == k),\n 'value': v\n } for k, v in data.items()]\n\n payload = {\n 'cmd': 'write',\n 'did': device['did'],\n 'params': params,\n }\n\n _LOGGER.debug(f\"{self.host} | {device['did']} {device['model']} => \"\n f\"{payload}\")\n\n payload = json.dumps(payload, separators=(',', ':')).encode()\n self.mqtt.publish('zigbee/recv', payload)\n\n def send_telnet(self, *args: str):\n try:\n telnet = Telnet(self.host, timeout=5)\n telnet.read_until(b\"login: \")\n telnet.write(b\"admin\\r\\n\")\n telnet.read_until(b\"\\r\\n# \") # skip greeting\n\n for command in args:\n telnet.write(command.encode() + b'\\r\\n')\n telnet.read_until(b\"\\r\\n\") # skip command\n\n telnet.close()\n\n except Exception as e:\n _LOGGER.exception(f\"Telnet command error: {e}\")\n\n def send_mqtt(self, cmd: str):\n if cmd == 'publishstate':\n mac = self.device['mac'][2:].upper()\n self.mqtt.publish(f\"gw/{mac}/publishstate\")\n\n def send_mesh(self, device: dict, data: dict):\n did = device['did']\n payload = bluetooth.pack_xiaomi_mesh(did, data)\n return self.miio.send('set_properties', payload)\n\n def get_device(self, mac: str) -> Optional[dict]:\n for device in self.devices.values():\n if device.get('mac') == mac:\n return device\n return None\n\n\nclass GatewayBLE(Thread):\n devices_loaded = False\n\n def __init__(self, gw: Gateway3):\n super().__init__(daemon=True)\n self.gw = gw\n\n def run(self):\n _LOGGER.debug(f\"{self.gw.host} | Start BLE \")\n while True:\n try:\n telnet = Telnet(self.gw.host, timeout=5)\n telnet.read_until(b\"login: \")\n telnet.write(b\"admin\\r\\n\")\n telnet.read_until(b\"\\r\\n# \") # skip greeting\n\n if not self.devices_loaded:\n self._get_devices(telnet)\n self.devices_loaded = True\n\n telnet.write(b\"killall silabs_ncp_bt; \"\n b\"silabs_ncp_bt /dev/ttyS1 1\\r\\n\")\n telnet.read_until(b\"\\r\\n\") # skip command\n\n while True:\n raw = telnet.read_until(b\"\\r\\n\")\n\n if 'bluetooth' in self.gw.debug:\n _LOGGER.debug(f\"[BT] {raw}\")\n\n if b'_async.ble_event' in raw:\n self.gw.process_ble_event(raw)\n elif b'properties_changed' in raw:\n self.gw.process_mesh_data(raw)\n\n except (ConnectionRefusedError, ConnectionResetError, EOFError,\n socket.timeout):\n pass\n except Exception as e:\n _LOGGER.exception(f\"Bluetooth loop error: {e}\")\n\n time.sleep(30)\n\n def _get_devices(self, telnet: Telnet):\n # read bluetooth db\n telnet.write(b\"cat /data/miio/mible_local.db | base64\\r\\n\")\n telnet.read_until(b'\\r\\n') # skip command\n raw = telnet.read_until(b'# ')\n raw = base64.b64decode(raw)\n\n db = SQLite(raw)\n tables = db.read_page(0)\n device_page = next(table[3] - 1 for table in tables\n if table[1] == 'mesh_device')\n rows = db.read_page(device_page)\n if not rows:\n return\n\n devices = [{\n 'did': row[0],\n 'mac': row[1].replace(':', ''),\n 'model': row[2],\n 'type': 'bluetooth'\n } for row in rows]\n self.gw.setup_mesh_devices(devices)\n\n\ndef is_gw3(host: str, token: str) -> Optional[str]:\n try:\n device = Device(host, token)\n info = device.info()\n if info.model != 'lumi.gateway.mgl03':\n raise Exception(f\"Wrong device model: {info.model}\")\n except Exception as e:\n return str(e)\n\n return None\n","sub_path":"custom_components/xiaomi_gateway3/gateway3.py","file_name":"gateway3.py","file_ext":"py","file_size_in_byte":26209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"544814477","text":"__author__ = 'jasocarter'\nfrom math import *\n\nclass MyPoint:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def distance(self, other):\n dx = self.x - other.x\n dy = self.y - other.y\n return sqrt(dx * dx + dy * dy)\n\n","sub_path":"INLS_560_Final_Project/MyPoint.py","file_name":"MyPoint.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"297499040","text":"\n\"\"\"Functions for importing and exporting data.\n\"\"\"\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nimport os\nfrom textwrap import dedent\nfrom glob import glob\n\nimport pandas as pd\nimport numpy as np\nimport math\n\ntry:\n import xarray as xr\n has_xarray = True\nexcept ImportError:\n has_xarray = False\n\nclass ImpExper(object):\n ds = None\n\n def __enter__(self):\n if self.ds is not None:\n self.ds = self.ds.__enter__()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if exc_type is None:\n self.finish()\n\n if self.ds is not None:\n self.ds.__exit__(exc_type, exc_val, exc_tb)\n\n def finish(self):\n pass\n\nclass Exporter(ImpExper):\n def remove_static(self, list_name):\n pass\n\n def remove_series(self, list_name, attr):\n pass\n\nclass Importer(ImpExper):\n pass\n\nclass ExporterCSV(Exporter):\n def __init__(self, csv_folder_name, encoding):\n self.csv_folder_name = csv_folder_name\n self.encoding = encoding\n\n #make sure directory exists\n if not os.path.isdir(csv_folder_name):\n logger.warning(\"Directory {} does not exist, creating it\"\n .format(csv_folder_name))\n os.mkdir(csv_folder_name)\n\n def save_attributes(self, attrs):\n name = attrs.pop('name')\n df = pd.DataFrame(attrs, index=pd.Index([name], name='name'))\n fn = os.path.join(self.csv_folder_name, \"network.csv\")\n df.to_csv(fn, encoding=self.encoding)\n\n def save_snapshots(self, snapshots):\n fn = os.path.join(self.csv_folder_name, \"snapshots.csv\")\n snapshots.to_csv(fn, encoding=self.encoding)\n\n def save_investment_periods(self, investment_periods):\n fn = os.path.join(self.csv_folder_name, \"investment_periods.csv\")\n investment_periods.to_csv(fn, encoding=self.encoding)\n\n def save_static(self, list_name, df):\n fn = os.path.join(self.csv_folder_name, list_name + \".csv\")\n df.to_csv(fn, encoding=self.encoding)\n\n def save_series(self, list_name, attr, df):\n fn = os.path.join(self.csv_folder_name, list_name + \"-\" + attr + \".csv\")\n df.to_csv(fn, encoding=self.encoding)\n\n def remove_static(self, list_name):\n fns = glob(os.path.join(self.csv_folder_name, list_name) + \"*.csv\")\n if fns:\n for fn in fns: os.unlink(fn)\n logger.warning(\"Stale csv file(s) {} removed\".format(', '.join(fns)))\n\n def remove_series(self, list_name, attr):\n fn = os.path.join(self.csv_folder_name, list_name + \"-\" + attr + \".csv\")\n if os.path.exists(fn):\n os.unlink(fn)\n\ndef import_from_csv_folder(network, csv_folder_name, encoding=None, skip_time=False):\n \"\"\"\n Import network data from CSVs in a folder.\n The CSVs must follow the standard form, see ``pypsa/examples``.\n Parameters\n ----------\n csv_folder_name : string\n Name of folder\n encoding : str, default None\n Encoding to use for UTF when reading (ex. 'utf-8'). `List of Python standard encodings\n `_\n skip_time : bool, default False\n Skip reading in time dependent attributes\n Examples\n ----------\n >>> network.import_from_csv_folder(csv_folder_name)\n \"\"\"\n\n basename = os.path.basename(csv_folder_name)\n with ImporterCSV(csv_folder_name, encoding=encoding) as importer:\n _import_from_importer(network, importer, basename=basename, skip_time=skip_time)\n\nclass ImporterCSV(Importer):\n\n def __init__(self, csv_folder_name, encoding):\n self.csv_folder_name = csv_folder_name\n self.encoding = encoding\n\n assert os.path.isdir(csv_folder_name), f\"Directory {csv_folder_name} does not exist.\"\n\n def get_attributes(self):\n fn = os.path.join(self.csv_folder_name, \"network.csv\")\n if not os.path.isfile(fn):\n return None\n \n return dict(pd.read_csv(fn, encoding=self.encoding).iloc[0])\n\n def get_snapshots(self):\n fn = os.path.join(self.csv_folder_name, \"snapshots.csv\")\n if not os.path.isfile(fn): return None\n df = pd.read_csv(fn, index_col=0, encoding=self.encoding, parse_dates=True)\n if \"snapshot\" in df:\n df[\"snapshot\"] = pd.to_datetime(df.snapshot)\n return df\n\n def get_investment_periods(self):\n fn = os.path.join(self.csv_folder_name, \"investment_periods.csv\")\n if not os.path.isfile(fn): return None\n return pd.read_csv(fn, index_col=0, encoding=self.encoding)\n\n def get_static(self, list_name):\n fn = os.path.join(self.csv_folder_name, list_name + \".csv\")\n return (pd.read_csv(fn, index_col=0, encoding=self.encoding)\n if os.path.isfile(fn) else None)\n\n def get_series(self, list_name):\n for fn in os.listdir(self.csv_folder_name):\n if fn.startswith(list_name+\"-\") and fn.endswith(\".csv\"):\n attr = fn[len(list_name)+1:-4]\n df = pd.read_csv(os.path.join(self.csv_folder_name, fn),\n index_col=0, encoding=self.encoding, parse_dates=True)\n yield attr, df\n\ndef _import_from_importer(network, importer, basename, skip_time=False):\n \"\"\"\n Import network data from importer.\n Parameters\n ----------\n skip_time : bool\n Skip importing time\n \"\"\"\n\n # If network.csv exists, attributes loaded as dict from csv:\n # name,now,srid,pypsa_version, e.g. AC-DC,now,4326,0.10.0\n\n attrs = importer.get_attributes()\n\n current_pypsa_version = [int(s) for s in network.pypsa_version.split(\".\")]\n pypsa_version = None\n\n if attrs is not None:\n network.name = attrs.pop('name')\n try:\n pypsa_version = [int(s) for s in attrs.pop(\"pypsa_version\").split(\".\")]\n except KeyError:\n pypsa_version = None\n\n for attr, val in attrs.items():\n setattr(network, attr, val)\n\n ##https://docs.python.org/3/tutorial/datastructures.html#comparing-sequences-and-other-types\n if pypsa_version is None or pypsa_version < current_pypsa_version:\n logger.warning(dedent(\"\"\"\n Importing PyPSA from older version of PyPSA than current version {}.\n Please read the release notes at https://pypsa.org/doc/release_notes.html\n carefully to prepare your network for import.\n \"\"\").format(network.pypsa_version))\n\n importer.pypsa_version = pypsa_version\n importer.current_pypsa_version = current_pypsa_version\n\n # if there is snapshots.csv, read in snapshot data\n df = importer.get_snapshots()\n\n if df is not None:\n\n # check if imported snapshots have MultiIndex\n snapshot_levels = set([\"period\", \"snapshot\"]).intersection(df.columns)\n if snapshot_levels:\n df.set_index(sorted(snapshot_levels), inplace=True)\n network.set_snapshots(df.index)\n\n cols = ['objective', 'generators', 'stores']\n if not df.columns.intersection(cols).empty:\n network.snapshot_weightings = df.reindex(index=network.snapshots,\n columns=cols)\n elif \"weightings\" in df.columns:\n network.snapshot_weightings = df[\"weightings\"].reindex(network.snapshots)\n\n network.set_snapshots(df.index)\n\n # read in investment period weightings\n periods = importer.get_investment_periods()\n\n if periods is not None:\n network._investment_periods = periods.index\n\n network._investment_period_weightings = (\n periods.reindex(network.investment_periods))\n\n\n imported_components = []\n\n # now read in other components; make sure buses and carriers come first\n for component in [\"Bus\", \"Carrier\"] + sorted(network.all_components - {\"Bus\", \"Carrier\", \"SubNetwork\"}):\n list_name = network.components[component][\"list_name\"]\n\n df = importer.get_static(list_name)\n if df is None:\n if component == \"Bus\":\n logger.error(\"Error, no buses found\")\n return\n else:\n continue\n\n import_components_from_dataframe(network, df, component)\n\n if not skip_time:\n for attr, df in importer.get_series(list_name):\n df.set_index(network.snapshots, inplace=True)\n import_series_from_dataframe(network, df, component, attr)\n\n logger.debug(getattr(network,list_name))\n\n imported_components.append(list_name)\n\n logger.info(\"Imported network{} has {}\".format(\" \" + basename, \", \".join(imported_components)))\n\ndef export_to_csv_folder(network, csv_folder_name, encoding=None, export_standard_types=False):\n \"\"\"\n Export network and components to a folder of CSVs.\n Both static and series attributes of all components are exported, but only\n if they have non-default values.\n If ``csv_folder_name`` does not already exist, it is created.\n Static attributes are exported in one CSV file per component,\n e.g. ``generators.csv``.\n Series attributes are exported in one CSV file per component per\n attribute, e.g. ``generators-p_set.csv``.\n Parameters\n ----------\n csv_folder_name : string\n Name of folder to which to export.\n encoding : str, default None\n Encoding to use for UTF when reading (ex. 'utf-8'). `List of Python\n standard encodings\n `_\n export_standard_types : boolean, default False\n If True, then standard types are exported too (upon reimporting you\n should then set \"ignore_standard_types\" when initialising the network).\n Examples\n --------\n >>> network.export_to_csv_folder(csv_folder_name)\n \"\"\"\n\n basename = os.path.basename(csv_folder_name)\n with ExporterCSV(csv_folder_name=csv_folder_name, encoding=encoding) as exporter:\n _export_to_exporter(network, exporter, basename=basename,\n export_standard_types=export_standard_types)\n\ndef _export_to_exporter(network, exporter, basename, export_standard_types=False):\n \"\"\"\n Export to exporter.\n Both static and series attributes of components are exported, but only\n if they have non-default values.\n Parameters\n ----------\n exporter : Exporter\n Initialized exporter instance\n basename : str\n Basename, used for logging\n export_standard_types : boolean, default False\n If True, then standard types are exported too (upon reimporting you\n should then set \"ignore_standard_types\" when initialising the netowrk).\n \"\"\"\n\n #exportable component types\n #what about None???? - nan is float?\n allowed_types = (float, int, bool, str) + tuple(np.sctypeDict.values())\n\n #first export network properties\n attrs = dict((attr, getattr(network, attr))\n for attr in dir(network)\n if (not attr.startswith(\"__\") and\n isinstance(getattr(network,attr), allowed_types)))\n exporter.save_attributes(attrs)\n\n #now export snapshots\n if isinstance(network.snapshot_weightings.index, pd.MultiIndex):\n network.snapshot_weightings.index.rename([\"period\", \"snapshot\"], inplace=True)\n else:\n network.snapshot_weightings.index.rename(\"snapshot\", inplace=True)\n snapshots = network.snapshot_weightings.reset_index()\n exporter.save_snapshots(snapshots)\n\n # export investment period weightings\n investment_periods = network.investment_period_weightings\n exporter.save_investment_periods(investment_periods)\n\n exported_components = []\n for component in network.all_components - {\"SubNetwork\"}:\n\n list_name = network.components[component][\"list_name\"]\n attrs = network.components[component][\"attrs\"]\n\n df = network.df(component)\n pnl = network.pnl(component)\n\n if not export_standard_types and component in network.standard_type_components:\n df = df.drop(network.components[component][\"standard_types\"].index)\n\n # first do static attributes\n df.index.name = \"name\"\n if df.empty:\n exporter.remove_static(list_name)\n continue\n\n col_export = []\n for col in df.columns:\n # do not export derived attributes\n if col in [\"sub_network\", \"r_pu\", \"x_pu\", \"g_pu\", \"b_pu\"]:\n continue\n if col in attrs.index and pd.isnull(attrs.at[col, \"default\"]) and pd.isnull(df[col]).all():\n continue\n if (col in attrs.index\n and df[col].dtype == attrs.at[col, 'dtype']\n and (df[col] == attrs.at[col, \"default\"]).all()):\n continue\n\n col_export.append(col)\n\n exporter.save_static(list_name, df[col_export])\n\n #now do varying attributes\n for attr in pnl:\n if attr not in attrs.index:\n col_export = pnl[attr].columns\n else:\n default = attrs.at[attr, \"default\"]\n\n if pd.isnull(default):\n col_export = pnl[attr].columns[(~pd.isnull(pnl[attr])).any()]\n else:\n col_export = pnl[attr].columns[(pnl[attr] != default).any()]\n\n if len(col_export) > 0:\n df = pnl[attr].reset_index()[col_export]\n exporter.save_series(list_name, attr, df)\n else:\n exporter.remove_series(list_name, attr)\n\n exported_components.append(list_name)\n\n logger.info(\"Exported network {} has {}\".format(basename, \", \".join(exported_components)))\n\ndef import_components_from_dataframe(network, dataframe, cls_name):\n \"\"\"\n Import components from a pandas DataFrame.\n If columns are missing then defaults are used.\n If extra columns are added, these are left in the resulting component dataframe.\n Parameters\n ----------\n dataframe : pandas.DataFrame\n A DataFrame whose index is the names of the components and\n whose columns are the non-default attributes.\n cls_name : string\n Name of class of component, e.g. ``\"Line\",\"Bus\",\"Generator\", \"StorageUnit\"``\n Examples\n --------\n >>> import pandas as pd\n >>> buses = ['Berlin', 'Frankfurt', 'Munich', 'Hamburg']\n >>> network.import_components_from_dataframe(\n pd.DataFrame({\"v_nom\" : 380, \"control\" : 'PV'},\n\t\t\tindex=buses),\n\t\t\t\"Bus\")\n >>> network.import_components_from_dataframe(\n pd.DataFrame({\"carrier\" : \"solar\", \"bus\" : buses, \"p_nom_extendable\" : True},\n\t\t\tindex=[b+\" PV\" for b in buses]),\n\t\t\t\"Generator\")\n See Also\n --------\n pypsa.Network.madd\n \"\"\"\n\n attrs = network.components[cls_name][\"attrs\"]\n\n static_attrs = attrs[attrs.static].drop(\"name\")\n non_static_attrs = attrs[~attrs.static]\n\n # Clean dataframe and ensure correct types\n dataframe = pd.DataFrame(dataframe)\n dataframe.index = dataframe.index.astype(str)\n\n for k in static_attrs.index:\n if k not in dataframe.columns:\n dataframe[k] = static_attrs.at[k, \"default\"]\n else:\n if static_attrs.at[k, \"type\"] == 'string':\n dataframe[k] = dataframe[k].replace({np.nan: \"\"})\n\n dataframe[k] = dataframe[k].astype(static_attrs.at[k, \"typ\"])\n\n #check all the buses are well-defined\n for attr in [\"bus\", \"bus0\", \"bus1\"]:\n if attr in dataframe.columns:\n missing = dataframe.index[~dataframe[attr].isin(network.buses.index)]\n if len(missing) > 0:\n logger.warning(\"The following %s have buses which are not defined:\\n%s\",\n cls_name, missing)\n\n non_static_attrs_in_df = non_static_attrs.index.intersection(dataframe.columns)\n old_df = network.df(cls_name)\n new_df = dataframe.drop(non_static_attrs_in_df, axis=1)\n if not old_df.empty:\n new_df = pd.concat((old_df, new_df), sort=False)\n\n if not new_df.index.is_unique:\n logger.error(\"Error, new components for {} are not unique\".format(cls_name))\n return\n\n setattr(network, network.components[cls_name][\"list_name\"], new_df)\n\n #now deal with time-dependent properties\n\n pnl = network.pnl(cls_name)\n\n for k in non_static_attrs_in_df:\n #If reading in outputs, fill the outputs\n pnl[k] = pnl[k].reindex(columns=new_df.index,\n fill_value=non_static_attrs.at[k, \"default\"])\n pnl[k].loc[:,dataframe.index] = dataframe.loc[:,k].values\n\n setattr(network,network.components[cls_name][\"list_name\"]+\"_t\",pnl)\n\ndef import_series_from_dataframe(network, dataframe, cls_name, attr):\n \"\"\"\n Import time series from a pandas DataFrame.\n Parameters\n ----------\n dataframe : pandas.DataFrame\n A DataFrame whose index is ``network.snapshots`` and\n whose columns are a subset of the relevant components.\n cls_name : string\n Name of class of component\n attr : string\n Name of time-varying series attribute\n Examples\n --------\n >>> import numpy as np\n >>> network.set_snapshots(range(10))\n >>> network.import_series_from_dataframe(\n pd.DataFrame(np.random.rand(10,4),\n columns=network.generators.index,\n\t\t\t index=range(10)),\n\t\t\t\"Generator\",\n\t\t\t\"p_max_pu\")\n See Also\n --------\n pypsa.Network.madd()\n \"\"\"\n\n df = network.df(cls_name)\n pnl = network.pnl(cls_name)\n list_name = network.components[cls_name][\"list_name\"]\n\n diff = dataframe.columns.difference(df.index)\n if len(diff) > 0:\n logger.warning(f\"Components {diff} for attribute {attr} of {cls_name} \"\n f\"are not in main components dataframe {list_name}\")\n\n attrs = network.components[cls_name]['attrs']\n expected_attrs = attrs[lambda ds: ds.type.str.contains('series')].index\n if attr not in expected_attrs:\n pnl[attr] = dataframe\n return\n\n attr_series = attrs.loc[attr]\n default = attr_series.default\n columns = dataframe.columns\n\n diff = network.snapshots.difference(dataframe.index)\n if len(diff):\n logger.warning(f\"Snapshots {diff} are missing from {attr} of {cls_name}.\"\n f\" Filling with default value '{default}'\")\n dataframe = dataframe.reindex(network.snapshots, fill_value=default)\n\n if not attr_series.static:\n pnl[attr] = pnl[attr].reindex(columns=df.index.union(columns), fill_value=default)\n else:\n pnl[attr] = pnl[attr].reindex(columns=(pnl[attr].columns.union(columns)))\n\n pnl[attr].loc[network.snapshots, columns] = dataframe.loc[network.snapshots, columns]","sub_path":"pypsa/io TEST.py","file_name":"io TEST.py","file_ext":"py","file_size_in_byte":18693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"593742952","text":"import requests\nfrom cx_Freeze import Executable, setup\n\nbuildOptions = {\n \"packages\": [\"os\", 'requests', 'queue', 'idna', 'gc', 'pysocks'],\n 'includes': ['requests', 'dermod', 'queue', 'idna', 'gc', 'pysocks'],\n \"excludes\": [\"tkinter\"],\n 'include_files': [\"extra/\", (requests.certs.where(), 'cacert.pem')]\n}\n\nsetup(\n name=\"DBooru\",\n version=\"1.0.0\",\n requires=['requests', 'idna', 'gc', 'pysocks'],\n options={\"build_exe\": buildOptions},\n executables=[Executable(\"main.py\"), Executable('webv3.py')]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"451241210","text":"# Copyright 2019-2021 Huawei Technologies Co., Ltd\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\nimport numpy as np\r\nfrom akg.topi.util import get_const_tuple\r\nfrom akg.utils import kernel_exec as utils\r\nfrom akg.ops.nn.ascend import ZerosLike\r\nfrom tests.common.tensorio import compare_tensor\r\nfrom tests.common.base import get_rtol_atol\r\n\r\n\r\ndef zeros_like_run(shape, dtype, attrs):\r\n if 'tuning' in attrs.keys():\r\n t = attrs.get(\"tuning\", False)\r\n kernel_name = attrs.get(\"kernel_name\", False)\r\n mod = utils.op_build_test(ZerosLike, [shape], [dtype], kernel_name=kernel_name, attrs=attrs, tuning=t)\r\n if t:\r\n input, expect, output = gen_data(dtype, shape)\r\n return mod, expect, (input, output)\r\n else:\r\n return mod\r\n else:\r\n mod = utils.op_build_test(ZerosLike, [shape], [dtype], kernel_name='zeros_like', attrs=attrs)\r\n input, expect, output = gen_data(dtype, shape)\r\n output = utils.mod_launch(mod, (input, output), expect=expect)\r\n rtol, atol = get_rtol_atol(\"zeros_like\", dtype)\r\n # compare result\r\n compare_res = compare_tensor(output, expect, rtol=rtol, atol=atol)\r\n return input, output, expect, compare_res\r\n\r\n\r\ndef gen_data(dtype, shape):\r\n input = np.random.uniform(low=-1.0, high=1.0, size=get_const_tuple(shape)).astype(dtype)\r\n expect = np.zeros_like(input)\r\n output = np.full(shape, np.nan, dtype)\r\n return input, expect, output\r\n\r\n","sub_path":"tests/common/test_run/ascend/zeros_like_run.py","file_name":"zeros_like_run.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"38701468","text":"import numpy as np\r\nimport sys\r\n\r\ndef criaMatriz(linhas, colunas):\r\n Matriz = np.zeros((linhas, colunas) , dtype = float)\r\n\r\n for l in range(linhas):\r\n for c in range(colunas):\r\n \r\n while(True):\r\n try:\r\n Matriz[l][c] = float(input(f'Inseir na linha {l+1} coluna{c+1} na matriz:'))\r\n break\r\n except:\r\n print('Dado invalido!! Insire um valor do tipo float')\r\n\r\n \r\n\r\n return Matriz \r\n\r\ndef triangular (matriz):\r\n linhaDoPivo = 0\r\n contador = 0\r\n for i in range(0,len(matriz)):\r\n pivo = matriz[i][i]\r\n\r\n if pivo == 0:\r\n for j in range(1,len(matriz)):\r\n if matriz[j][i] != 0:\r\n linhaDoPivo = j\r\n break \r\n for x in range(0, len(matriz[0])): \r\n aux = matriz[i][x]\r\n matriz[i][x] = matriz[linhaDoPivo][x]\r\n matriz[linhaDoPivo][x] = aux\r\n\r\n for a in range (i+1, len(matriz)):\r\n mIK = (matriz[a][i] / pivo)\r\n for b in range(i+1, len(matriz[0])):\r\n matriz[a][b] = matriz[a][b] - (mIK * matriz[i][b])\r\n matriz[a][i] = 0\r\n print(f'Passos do escalonamento:{contador}\\n{matriz}\\n')\r\n contador += 1 \r\n\r\n return matriz \r\n \r\ndef retroSubstiuicao(matriz):\r\n numeroDeEquacoesInconi = len(matriz)\r\n vetorDeZeros = numeroDeEquacoesInconi * [0]\r\n for i in range(numeroDeEquacoesInconi - 1, -1, -1):\r\n soma = sum([matriz[i][j] * vetorDeZeros[j] for j in range(i+1, numeroDeEquacoesInconi)])\r\n if matriz[i][i] == 0:\r\n print('=*' * 15)\r\n print('\\n Sistema Impossível\\n')\r\n print('=*' * 15)\r\n sys.exit()\r\n vetorDeZeros[i] = (matriz[i][numeroDeEquacoesInconi] - soma) / matriz[i][i]\r\n \r\n\r\n return vetorDeZeros\r\n\r\ndef resolve(A):\r\n print(f'\\nA matriz original é :\\n{A}')\r\n triangular(A)\r\n print(f'\\nA matriz triangular é:\\n{A}\\n')\r\n x = retroSubstiuicao(A)\r\n print(f'Os coeficientes são: {x}')\r\n\r\nentradaLinhas = int(input('\\nInsira a quantidade de linhas:\\n'))\r\nentradaColunas = int(input('\\nInsira a quantidade de colunas:\\n'))\r\nm = criaMatriz(entradaLinhas,entradaColunas)\r\nresolve(m)\r\n","sub_path":"algoritmoGauss/gauss.py","file_name":"gauss.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"610677958","text":"\nfrom flask import Flask, render_template, request\nimport pandas as pd\nimport json\nimport plotly\nimport plotly.express as px\n\nimport csv, re, operator\n# from textblob import TextBlob\n\napp = Flask(__name__)\n\nperson = {\n 'first_name': 'Nohossat',\n 'last_name' : 'TRAORE',\n 'address' : '9 rue Léon Giraud · PARIS · FRANCE',\n 'job': 'Web developer',\n 'tel': '0678282923',\n 'email': 'nohossat.tra@yahoo.com',\n 'description' : 'Suite à une expérience internationale en développement web et dans le domaine des arts, l’impact de l’intelligence artificielle dans nos vies me surprend de jour en jour. \\n Aujourd’hui, je souhaite changer de cap et comprendre les secrets que recèlent nos données. J’aimerais mettre à profit ces découvertes au service des entreprises/associations à dimension sociale.',\n 'social_media' : [\n {\n 'link': 'https://www.facebook.com/nono',\n 'icon' : 'fa-facebook-f'\n },\n {\n 'link': 'https://github.com/nono',\n 'icon' : 'fa-github'\n },\n {\n 'link': 'linkedin.com/in/nono',\n 'icon' : 'fa-linkedin-in'\n },\n {\n 'link': 'https://twitter.com/nono',\n 'icon' : 'fa-twitter'\n }\n ],\n 'img': 'img/img_nono.jpg',\n 'experiences' : [\n {\n 'title' : 'Web Developer',\n 'company': 'AZULIK',\n 'description' : 'Project manager and lead developer for several AZULIK websites.',\n 'timeframe' : 'July 2018 - November 2019'\n },\n {\n 'title' : 'Freelance Web Developer',\n 'company': 'Independant',\n 'description' : 'Create Wordpress websites for small and medium companies. ',\n 'timeframe' : 'February 2017 - Present'\n },\n {\n 'title' : 'Sharepoint Intern',\n 'company': 'ALTEN',\n 'description' : 'Help to manage a 600 Sharepoint sites platform (audit, migration to Sharepoint newer versions)',\n 'timeframe' : 'October 2015 - October 2016'\n }\n ],\n 'education' : [\n {\n 'university': 'Paris Diderot',\n 'degree': 'Projets informatiques et Startégies d\\'entreprise (PISE)',\n 'description' : 'Gestion de projets IT, Audit, Programmation',\n 'mention' : 'Bien',\n 'timeframe' : '2015 - 2016'\n },\n {\n 'university': 'Paris Dauphine',\n 'degree': 'Master en Management global',\n 'description' : 'Fonctions supports (Marketing, Finance, Ressources Humaines, Comptabilité)',\n 'mention' : 'Bien',\n 'timeframe' : '2015'\n },\n {\n 'university': 'Lycée Turgot - Paris Sorbonne',\n 'degree': 'CPGE Economie & Gestion',\n 'description' : 'Préparation au concours de l\\'ENS Cachan, section Economie',\n 'mention' : 'N/A',\n 'timeframe' : '2010 - 2012'\n }\n ],\n 'programming_languages' : {\n 'HMTL' : ['fa-html5', '100'],\n 'CSS' : ['fa-css3-alt', '100'],\n 'SASS' : ['fa-sass', '90'],\n 'JS' : ['fa-js-square', '90'],\n 'Wordpress' : ['fa-wordpress', '80'],\n 'Python': ['fa-python', '70'],\n 'Mongo DB' : ['fa-database', '60'],\n 'MySQL' : ['fa-database', '60'],\n 'NodeJS' : ['fa-node-js', '50']\n },\n 'languages' : {'French' : 'Native', 'English' : 'Professional', 'Spanish' : 'Professional', 'Italian' : 'Limited Working Proficiency'},\n 'interests' : ['Dance', 'Travel', 'Languages']\n}\n\n@app.route('/')\ndef cv(person=person):\n return render_template('index.html', person=person)\n\n\n\n\n@app.route('/callback', methods=['POST', 'GET'])\ndef cb():\n\treturn gm(request.args.get('data'))\n\n@app.route('/chart')\ndef index():\n\treturn render_template('chartsajax.html', graphJSON=gm())\n\ndef gm(country='United Kingdom'):\n\tdf = pd.DataFrame(px.data.gapminder())\n\n\tfig = px.line(df[df['country']==country], x=\"year\", y=\"gdpPercap\")\n\n\tgraphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)\n\treturn graphJSON\n\n\n@app.route('/senti')\ndef main():\n\ttext = \"\"\n\tvalues = {\"positive\": 0, \"negative\": 0, \"neutral\": 0}\n\n\twith open('ask_politics.csv', 'rt') as csvfile:\n\t\treader = csv.DictReader(csvfile, delimiter=',', quotechar='\"')\n\t\tfor idx, row in enumerate(reader):\n\t\t\tif idx > 0 and idx % 2000 == 0:\n\t\t\t\tbreak\n\t\t\tif 'text' in row:\n\t\t\t\tnolinkstext = re.sub(r'''(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))''', '', row['text'], flags=re.MULTILINE)\n\t\t\t\ttext = nolinkstext\n\n\t\t\tblob = TextBlob(text)\n\t\t\tfor sentence in blob.sentences:\n\t\t\t\tsentiment_value = sentence.sentiment.polarity\n\t\t\t\tif sentiment_value >= -0.1 and sentiment_value <= 0.1:\n\t\t\t\t\tvalues['neutral'] += 1\n\t\t\t\telif sentiment_value < 0:\n\t\t\t\t\tvalues['negative'] += 1\n\t\t\t\telif sentiment_value > 0:\n\t\t\t\t\tvalues['positive'] += 1\n\n\tvalues = sorted(values.items(), key=operator.itemgetter(1))\n\ttop_ten = list(reversed(values))\n\tif len(top_ten) >= 11:\n\t\ttop_ten = top_ten[1:11]\n\telse :\n\t\ttop_ten = top_ten[0:len(top_ten)]\n\n\ttop_ten_list_vals = []\n\ttop_ten_list_labels = []\n\tfor language in top_ten:\n\t\ttop_ten_list_vals.append(language[1])\n\t\ttop_ten_list_labels.append(language[0])\n\n\tgraph_values = [{\n\t\t\t\t\t'labels': top_ten_list_labels,\n\t\t\t\t\t'values': top_ten_list_vals,\n\t\t\t\t\t'type': 'pie',\n\t\t\t\t\t'insidetextfont': {'color': '#FFFFFF',\n\t\t\t\t\t\t\t\t\t\t'size': '14',\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t'textfont': {'color': '#FFFFFF',\n\t\t\t\t\t\t\t\t\t\t'size': '14',\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t}]\n\n\tlayout = {'title': '意见挖掘 '}\n\n\treturn render_template('sentiment.html', graph_values=graph_values, layout=layout)\n\n\nif __name__ == '__main__':\n app.run(debug= True,port=5000,threaded=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"82240921","text":"import gdal\nimport numpy as np\n\n# filename= ('/Users/lauro/Documents/PROJECTS/BOLIVIA/Bolivia2/simulazioni/Prova6/Results6b_verbose2_WATERDEPTH_36000.tif');\n\n# readFile(filename):\n\"\"\"def readGeotiff(filename):\n filehandle = gdal.Open(filename)\n band1 = filehandle.GetRasterBand(1)\n scale = band1.GetScale()\n print (scale)\n geotransform = filehandle.GetGeoTransform()\n geoproj = filehandle.GetProjection()\n band1data = band1.ReadAsArray()\n xsize = filehandle.RasterXSize\n ysize = filehandle.RasterYSize\n return band1data, xsize, ysize, geotransform, geoproj\n\"\"\"\n\ndef readGeotiff (filename):\n filehandle = gdal.Open(filename)\n geotransform = filehandle.GetGeoTransform()\n geoproj = filehandle.GetProjection()\n xsize = filehandle.RasterXSize\n ysize = filehandle.RasterYSize\n band_tot = filehandle.RasterCount\n\n if band_tot > 1:\n data3d= np.zeros((ysize,xsize,band_tot))\n\n for i in range (0,band_tot):\n band = filehandle.GetRasterBand(i+1)\n scale = band.GetScale()\n nodata = band.GetNoDataValue()\n dataset = band.ReadAsArray()\n dataset [dataset==nodata]= np.nan\n if band_tot > 1:\n data3d[:,:,i] = dataset\n else:\n data3d = dataset\n\n return data3d, xsize, ysize, geotransform, geoproj\n\n\n\ndef writeGeotiffSingleBand(filename, geotransform, geoprojection, data, nodata=np.nan, BandName= \"\"):\n (x, y) = data.shape\n format = \"GTiff\"\n driver = gdal.GetDriverByName(format)\n # dst_datatype = gdal.GDT_Byte #byte\n dst_datatype = gdal.GDT_Float32\n dst_ds = driver.Create(\n filename, y, x, 1, dst_datatype, options=[\n 'COMPRESS=DEFLATE'])\n # sDATETIME= \"2013:04:30 12:00:00\"#The format is: \"YYYY:MM:DD HH:MM:SS\",\n # with hours like those on a 24-hour clock, and one space character\n # between the date and the time. The length of the string, including the\n # terminating NUL, is 20 bytes.\n #dst_ds.SetMetadata({'TIFFTAG_SOFTWARE': 'Hydra2D'})\n dst_ds.GetRasterBand(1).SetNoDataValue(nodata)\n dst_ds.GetRasterBand(1).WriteArray(data)\n dst_ds.GetRasterBand(1).SetDescription (BandName)\n dst_ds.SetGeoTransform(geotransform)\n dst_ds.SetProjection(geoprojection)\n return 1\n\n\ndef writeGeotiff(filename, geotransform, geoprojection, data, nodata=np.nan, BandNames=None, globalDescr=\"\"):\n\n dim = len(data.shape)\n\n if dim == 2:\n (x, y) = data.shape\n iNbands = 1\n else:\n (x, y, z) = data.shape\n iNbands = z\n\n\n format = \"GTiff\"\n driver = gdal.GetDriverByName(format)\n # dst_datatype = gdal.GDT_Byte #byte\n dst_datatype = gdal.GDT_Float32\n # dst_ds = driver.Create(filename,y,x,1,dst_datatype,options = [\n # 'COMPRESS=DEFLATE', 'PREDICTOR=3' ]) #incompatibility of PREDICTOR con\n # Geoserver 2.2.4 (Bolivia)\n dst_ds = driver.Create(filename, y,x,iNbands, dst_datatype, options=['COMPRESS=DEFLATE'])\n dst_ds.SetDescription(globalDescr)\n dst_ds.SetGeoTransform(geotransform)\n dst_ds.SetProjection(geoprojection)\n # write data\n if iNbands == 1:\n dst_ds.GetRasterBand(1).WriteArray(data[:, :])\n dst_ds.GetRasterBand(1).SetNoDataValue(nodata)\n if BandNames != None:\n dst_ds.GetRasterBand(1).SetDescription (BandNames)\n else:\n for i in range(0, iNbands):\n dst_ds.GetRasterBand(1).SetNoDataValue(nodata)\n dst_ds.GetRasterBand(i + 1).WriteArray(data[:, :, i])\n if BandNames != None:\n dst_ds.GetRasterBand(i + 1).SetDescription (BandNames[i])\n return 1\n\n\ndef writeGeotiffSingleBandByte(filename, geotransform, geoprojection, data, descr = \"\"):\n (x, y) = data.shape\n format = \"GTiff\"\n driver = gdal.GetDriverByName(format)\n # dst_datatype = gdal.GDT_Byte #byte\n dst_datatype = gdal.GDT_Byte\n dst_ds = driver.Create(\n filename, y, x, 1, dst_datatype, options=['COMPRESS=DEFLATE'])\n dst_ds.SetMetadata({'TIFFTAG_IMAGEDESCRIPTION': descr})\n dst_ds.GetRasterBand(1).WriteArray(data)\n dst_ds.SetGeoTransform(geotransform)\n dst_ds.SetProjection(geoprojection)\n return 1","sub_path":"indexes/CDI/geotiff.py","file_name":"geotiff.py","file_ext":"py","file_size_in_byte":4140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"584440933","text":"\"\"\"\nCopyright 2021 BlazeMeter Inc.\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\"\"\"\nimport json\nimport os\nfrom subprocess import PIPE\nfrom bzt import TaurusConfigError, ToolError\nfrom bzt.modules import ScenarioExecutor\nfrom bzt.modules.console import ExecutorWidget\nfrom bzt.modules.aggregator import ResultsReader, ConsolidatingAggregator\nfrom bzt.utils import RequiredTool, CALL_PROBLEMS, FileReader, shutdown_process, get_full_path, is_windows, is_mac, \\\n untar\n\n\nclass VegetaExecutor(ScenarioExecutor):\n def __init__(self):\n super(VegetaExecutor, self).__init__()\n self.output_file = None\n self.log_file = None\n self.script = None\n self.process = None\n self.vegeta = None\n self.kpi_file = None\n self.scenario = None\n\n def prepare(self):\n super(VegetaExecutor, self).prepare()\n self.scenario = self.get_scenario()\n self.install_required_tools()\n\n self.script = self.get_script_path()\n if not self.script:\n requests = self.scenario.get_requests()\n if not requests:\n raise TaurusConfigError(\"Either 'script' or 'scenario' should be present for Vegeta executor\")\n self.script = os.path.join(self.engine.artifacts_dir, \"vegeta.txt\")\n with open(self.script, \"w\") as f:\n i = 0\n for request in requests:\n f.write(\"{} {}\\n\".format(request.method, request.url))\n headers = \"\\n\".join([\"{}: {}\".format(key, value) for key, value in request.headers.items()])\n if headers:\n f.write(\"{}\\n\".format(headers))\n if request.body:\n json_body_file = os.path.join(self.engine.artifacts_dir, \"body-{}.json\".format(i))\n with open(json_body_file, \"w\") as g:\n g.write(json.dumps(request.body))\n f.write(\"@{}\\n\".format(json_body_file))\n f.write(\"\\n\")\n i += 1\n\n self.stdout = open(self.engine.create_artifact(\"Vegeta\", \".out\"), \"w\")\n self.stderr = open(self.engine.create_artifact(\"Vegeta\", \".err\"), \"w\")\n\n self.kpi_file = self.engine.create_artifact(\"kpi\", \".csv\")\n self.reader = VegetaLogReader(self.kpi_file, self.log)\n if isinstance(self.engine.aggregator, ConsolidatingAggregator):\n self.engine.aggregator.add_underling(self.reader)\n\n def startup(self):\n cmdline = [self.vegeta.tool_path, \"attack\", \"-targets\", self.script]\n load = self.get_load()\n\n if load.throughput:\n cmdline += ['-rate', str(load.throughput)]\n\n if load.hold:\n cmdline += ['-duration', str(int(load.hold)) + \"s\"]\n\n if load.concurrency:\n cmdline += ['-max-workers', str(int(load.concurrency))]\n\n if self.scenario and 'timeout' in self.scenario:\n cmdline += ['-timeout', str(int(self.scenario.get('timeout'))) + \"s\"]\n\n user_cmd = self.settings.get(\"cmdline\")\n if user_cmd:\n cmdline += user_cmd.split(\" \")\n\n self.process = self._execute(cmdline, stdout=PIPE, shell=False)\n with open(self.kpi_file, 'wb') as f:\n self._execute([self.vegeta.tool_path, \"encode\", \"-to=csv\"], stdin=self.process.stdout, stdout=f, shell=False)\n\n def get_widget(self):\n if not self.widget:\n label = \"%s\" % self\n self.widget = ExecutorWidget(self, \"Vegeta: \" + label.split('/')[1])\n return self.widget\n\n def check(self):\n retcode = self.process.poll()\n if retcode is not None:\n ToolError(f\"Vegeta tool exited with non-zero code: {retcode}\")\n return True\n return False\n\n def shutdown(self):\n shutdown_process(self.process, self.log)\n\n def post_process(self):\n if self.kpi_file:\n self.engine.existing_artifact(self.kpi_file)\n super(VegetaExecutor, self).post_process()\n\n def install_required_tools(self):\n self.vegeta = self._get_tool(Vegeta, config=self.settings)\n self.vegeta.tool_name = self.vegeta.tool_name.lower()\n if not self.vegeta.check_if_installed():\n self.vegeta.install()\n\n def resource_files(self):\n return [self.get_script_path(required=True)]\n\n\nclass VegetaLogReader(ResultsReader):\n def __init__(self, filename, parent_logger):\n super(VegetaLogReader, self).__init__()\n self.log = parent_logger.getChild(self.__class__.__name__)\n self.file = FileReader(filename=filename, parent_logger=self.log)\n\n def _read(self, last_pass=False):\n lines = self.file.get_lines(size=1024 * 1024, last_pass=last_pass)\n\n for line in lines:\n log_vals = [val.strip() for val in line.split(',')]\n\n _tstamp = int(log_vals[0][:10])\n _url = log_vals[10]\n _concur = 1\n _etime = float(log_vals[2]) / 1000000000.0\n _con_time = 0\n _latency = 0\n _rstatus = log_vals[1]\n _error = log_vals[5] or None\n _bytes = int(log_vals[4])\n\n yield _tstamp, _url, _concur, _etime, _con_time, _latency, _rstatus, _error, '', _bytes\n\n\nclass Vegeta(RequiredTool):\n DOWNLOAD_LINK = \\\n \"https://github.com/tsenart/vegeta/releases/download/v{version}/vegeta_{version}_{platform}_amd64.tar.gz \"\n VERSION = \"12.8.4\"\n LOCAL_PATH = \"~/.bzt/vegeta-taurus/{version}/\"\n\n def __init__(self, config=None, **kwargs):\n settings = config or {}\n version = settings.get(\"version\", self.VERSION)\n self.tool_path = get_full_path(settings.get(\"path\", self.LOCAL_PATH.format(version=version) + 'vegeta'))\n if not is_windows():\n platform = 'darwin' if is_mac() else 'linux'\n download_link = settings.get(\"download-link\", self.DOWNLOAD_LINK).format(version=version, platform=platform)\n else:\n download_link = ''\n super(Vegeta, self).__init__(tool_path=self.tool_path, download_link=download_link, version=version, **kwargs)\n\n def check_if_installed(self):\n self.log.debug('Checking Vegeta Framework: %s' % self.tool_path)\n try:\n out, err = self.call([self.tool_path, '-version'])\n except CALL_PROBLEMS as exc:\n self.log.warning(\"%s check failed: %s\", self.tool_name, exc)\n return False\n\n if err:\n out += err\n self.log.debug(\"Vegeta output: %s\", out)\n return True\n\n def install(self):\n if is_windows():\n raise ToolError(\"Unable to install Vegeta on Windows! Manual installation required.\")\n\n dest = get_full_path(self.tool_path, step_up=1)\n if not os.path.exists(dest):\n os.makedirs(dest)\n\n self.log.info(\"Will install %s into %s\", self.tool_name, dest)\n vegeta_dist = self._download(use_link=True)\n\n self.log.info(\"Untaring %s\", vegeta_dist)\n untar(vegeta_dist, dest, rel_path='vegeta')\n os.remove(vegeta_dist)\n os.chmod(get_full_path(self.tool_path), 0o755)\n self.log.info(\"Installed Vegeta successfully\")\n\n if not self.check_if_installed():\n raise ToolError(\"Unable to run %s after installation!\" % self.tool_name)\n","sub_path":"bzt/modules/vegeta.py","file_name":"vegeta.py","file_ext":"py","file_size_in_byte":7796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"189932280","text":"# -*- mode: python; coding: utf-8 -*-\n# Copyright 2018 the HERA Collaboration\n# Licensed under the 2-clause BSD license.\n\n\"\"\"Some low-level configuration management utility functions.\n\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport os.path\nimport subprocess\nimport six\nfrom astropy.time import Time\nfrom astropy.time import TimeDelta\nimport datetime\n\nfrom . import mc\n\nPAST_DATE = '2000-01-01'\nall_hera_zone_prefixes = ['HH', 'HA', 'HB'] # This is for hookup_cache to get all\ndefault_station_prefixes = ['HH', 'HA', 'HB'] # This is for defaults for sys etc.\n\n\ndef get_cm_repo_git_hash(mc_config_path=None, cm_csv_path=None):\n \"\"\"\n Get the current cm_version for recording with antenna locations.\n \"\"\"\n if cm_csv_path is None:\n cm_csv_path = mc.get_cm_csv_path(mc_config_file=mc_config_path)\n if cm_csv_path is None:\n raise ValueError('No cm_csv_path defined in mc_config file.')\n\n git_hash = subprocess.check_output(['git', '-C', cm_csv_path, 'rev-parse', 'HEAD'],\n stderr=subprocess.STDOUT).strip()\n return git_hash\n\n\ndef log(msg, **kwargs):\n fp = open(mc.cm_log_file, 'a')\n dt = Time.now()\n fp.write('-------------------' + str(dt.datetime) + ' ' + msg\n + '-------------------\\n\\n')\n for key, value in kwargs.items():\n if key == 'args':\n fp.write('--args\\n\\t')\n vargs = vars(value)\n for k, v in vargs.items():\n fp.write(str(k) + ': ' + str(v) + '; ')\n fp.write('\\n\\n')\n elif key == 'data_dict':\n fp.write('--data\\n\\t')\n for k, v in value.items():\n fp.write(' ' + k + ' ')\n for d in v:\n fp.write(str(d) + '; ')\n fp.write('\\n\\n')\n else:\n fp.write('--other\\n\\t')\n fp.write(str(key) + ': ' + str(value) + '\\n\\n')\n fp.close()\n\n\n# #######################################Key stuff\ndef make_part_key(hpn, rev):\n return \":\".join([hpn, rev]).strip()\n\n\ndef split_part_key(key):\n return key.split(':')[0], key.split(':')[1]\n\n\ndef make_connection_key(hpn, rev, port, start_gps):\n return \":\".join([hpn, rev, port, str(start_gps)]).strip()\n\n\ndef split_connection_key(key):\n ks = key.split(':')\n return ks[0], ks[1], ks[2], ks[3]\n\n\ndef stringify(X):\n if X is None:\n return None\n if isinstance(X, six.string_types):\n return X\n if isinstance(X, list):\n return ','.join(X)\n return str(X)\n\n\ndef listify(X):\n if X is None:\n return None\n if isinstance(X, six.string_types) and ',' in X:\n return X.split(',')\n if isinstance(X, list):\n return X\n return [X]\n\n\ndef add_verbosity_args(parser):\n \"\"\"Add a standardized \"--verbosity\" argument to an ArgParser object. Supported\n values are \"l\", \"m\", and \"h\", which presumably stand for \"low\", \"medium\",\n and \"high\".\n\n The function name is plural because it's conceivable that in the future we might\n want to provide multiple arguments related to this general topic.\n\n \"\"\"\n parser.add_argument('-v', '--verbosity', help=\"Verbosity level: 'l', 'm', or 'h'. [l].\",\n choices=['l', 'm', 'h'], default=\"m\")\n\n\n# ##############################################DATE STUFF\ndef add_date_time_args(parser):\n \"\"\"Add standardized \"--date\" and \"--time\" arguments to an ArgParser object.\n Their values should then be converted into a Python DateTime object using\n the function `get_astropytime`.\n\n \"\"\"\n parser.add_argument(\n '--date', help=\"UTC YYYY/MM/DD or '<' or '>' or 'n/a' or 'now' [now]\",\n default='now')\n parser.add_argument(\n '--time', help=\"UTC hh:mm or float (hours), must include --date if use --time\", default=0.0)\n\n\ndef is_active(at_date, start_date, stop_date):\n at_date = get_astropytime(at_date)\n start_date = get_astropytime(start_date)\n stop_date = get_stopdate(stop_date)\n return at_date >= start_date and at_date <= stop_date\n\n\ndef future_date():\n \"\"\"\n Future is defined here, since defining a far FUTURE_DATE typically gives a\n warning about UTC vs UT1 etc\n \"\"\"\n return Time.now() + TimeDelta(300, format='jd')\n\n\ndef get_stopdate(stop_date):\n if stop_date is None:\n return future_date()\n return get_astropytime(stop_date)\n\n\ndef get_time_for_display(display):\n \"\"\"\n Provide a reader-friendly time string for any time parse-able by get_astropytime -\n if that results in None, then the string None is displayed.\n \"\"\"\n d = get_astropytime(display)\n\n if d is None:\n d = 'None'\n elif isinstance(d, Time):\n d = \"{:%Y-%m-%d %H:%M:%S}\".format(d.datetime)\n return d\n\n\ndef get_astropytime(_date, _time=0):\n \"\"\"\n Take in various incarnations of _date/_time and return an astropy.Time object or None.\n No time zone is allowed.\n\n Returns: either astropy Time or None\n\n Parameters:\n -----------\n _date: date in various formats:\n return astropy Time\n astropy Time: just gets returned\n datetime: just gets converted\n int, long, float: interpreted as gps_second\n string: '<' - PAST_DATE\n '>' - future_date()\n 'now' or 'current'\n 'YYYY/M/D' or 'YYYY-M-D'\n return None:\n string: 'none' return None\n None/False: return None\n _time: only used if _date is 'YYYY/M/D'/'YYYY-M-D' string\n float, int: hours in decimal time\n string: HH[:MM[:SS]]\n \"\"\"\n\n if isinstance(_date, Time):\n return _date\n if isinstance(_date, datetime.datetime):\n return Time(_date, format='datetime')\n if _date is None or _date is False:\n return None\n if isinstance(_date, (six.integer_types, float)):\n if int(_date) > 1000000000:\n return Time(_date, format='gps')\n raise ValueError('Invalid format: date as a number should be gps time, not {}.'.format(_date))\n if isinstance(_date, str):\n if _date == '<':\n return Time(PAST_DATE, scale='utc')\n if _date == '>':\n return future_date()\n if _date.lower() == 'now' or _date.lower() == 'current':\n return Time.now()\n if _date.lower() == 'none':\n return None\n _date = _date.replace('/', '-')\n try:\n return_date = Time(_date, scale='utc')\n except ValueError:\n raise ValueError('Invalid format: date should be YYYY/M/D or YYYY-M-D, not {}'.format(_date))\n if isinstance(_time, (float, int)):\n return return_date + TimeDelta(_time * 3600.0, format='sec')\n if isinstance(_time, str):\n add_time = 0.0\n for i, d in enumerate(_time.split(':')):\n if i > 2:\n raise ValueError('Time can only be hours[:minutes[:seconds]], not {}.'.format(_time))\n add_time += (float(d)) * 3600.0 / (60.0**i)\n return return_date + TimeDelta(add_time, format='sec')\n raise ValueError('Invalid format: time should be H[:M[:S]] (ints or floats)')\n\n raise TypeError(\"Not supported: type {}\".format(type(_date)))\n\n\ndef put_keys_in_numerical_order(keys):\n \"\"\"\n Takes a list of hookup keys in the format of prefix+number:revision and puts them in number order.\n Returns the ordered list of keys\n \"\"\"\n keylib = {}\n n = None\n for k in keys:\n colon = k.find(':')\n for i in range(len(k)):\n try:\n n = int(k[i:colon])\n break\n except ValueError:\n continue\n if n is None or n in keylib.keys():\n return keys\n keylib[n] = [k[:i], k[colon:]]\n if not len(keylib.keys()):\n return keys\n keyordered = []\n for n in sorted(keylib.keys()):\n kre = keylib[n][0] + str(n) + keylib[n][1]\n keyordered.append(kre)\n return keyordered\n\n\ndef get_date_from_pair(d1, d2, ret='earliest'):\n \"\"\"\n Returns either the earliest or latest of two dates. This handles either ordering\n and when either or both are None.\n \"\"\"\n if d1 is None and d2 is None:\n return None\n if ret == 'earliest':\n if d1 is None:\n return d2\n elif d2 is None:\n return d1\n else:\n return d1 if d1 < d2 else d2\n elif ret == 'latest':\n if d1 is None:\n return d1\n elif d2 is None:\n return d2\n else:\n return d1 if d1 > d2 else d2\n else:\n raise ValueError(\"Must supply earliest/latest.\")\n\n\ndef query_default(a, args):\n vargs = vars(args)\n default = vargs[a]\n s = '%s [%s]: ' % (a, str(default))\n v = raw_input(s)\n if len(v) == 0:\n v = default\n elif v.lower() == 'none':\n v = None\n return v\n\n\ndef query_yn(s, default='y'):\n if default:\n s += ' [' + default + ']'\n s += ': '\n ans = raw_input(s)\n if len(ans) == 0 and default:\n ans = default.lower()\n elif len(ans) > 0:\n ans = ans.lower()\n else:\n print('No answer provided.')\n ans = query_yn(s)\n return ans[0] == 'y'\n","sub_path":"hera_mc/cm_utils.py","file_name":"cm_utils.py","file_ext":"py","file_size_in_byte":9350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"594022489","text":"import argparse\nimport os\nimport numpy as np\n\nimport sys\n\nsys.path.insert(0, \"../../test_utils\")\nimport result_parser_utils\n\n\nWARMUP_ROUNDS = 2\n\n\ndef get_durations(lines):\n durations = []\n for line in lines:\n if 'duration = ' in line:\n tmp = line.split('duration = ')[1]\n durations.append(float(tmp))\n return durations\n\n\ndef parse_all_ranks(folder_path, with_rank0=True):\n files = os.listdir(folder_path)\n all_rank_durations = []\n for filename in files:\n if 'rank' in filename and (with_rank0 or 'rank_0' not in filename):\n try:\n with open(os.path.join(folder_path, filename)) as f:\n durations = get_durations(f.readlines())\n if not durations:\n raise ValueError(\"Bad file\")\n all_rank_durations.append(durations)\n except Exception:\n print(\"Bad file\", folder_path, filename)\n return None\n\n try:\n return np.max(all_rank_durations, axis=0)\n except Exception as e:\n print(\"Error: empty directory\", folder_path, e)\n return None\n\n\ndef parse_file(task_name, log_dir, foldername):\n path = os.path.join(log_dir, foldername)\n\n if task_name in ('allreduce', 'allgather'):\n return parse_all_ranks(path)\n elif task_name == 'multicast':\n return parse_all_ranks(path, with_rank0=False)\n elif task_name in ('reduce', 'gather', 'subset_reduce'):\n return result_parser_utils.default_parse_file(task_name, log_dir, foldername)\n else:\n raise ValueError('Unknown task', task_name)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Hoplite (C++) benchmark results parser.')\n parser.add_argument('log_dir', metavar='PATH', nargs='?', type=str, default='log',\n help='The logging directory of Gloo benchmarks')\n parser.add_argument('--verbose', action='store_true')\n args = parser.parse_args()\n df = result_parser_utils.parse(args.log_dir, parse_file)\n if args.verbose:\n print(df)\n df.to_csv('hoplite_results.csv', index=False)\n","sub_path":"microbenchmarks/hoplite-cpp/parse_result.py","file_name":"parse_result.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"371113862","text":"\n\ndef rev_arr_without_slice(lst):\n low = 0\n high = len(lst)-1\n for i in range(len(lst)//2):\n lst[low],lst[high] = lst[high], lst[low]\n low+=1\n high-=1\n return lst\n\n\ndef rev_arr(lst):\n return \"PERFECT\" if (lst==lst[::-1]) else \"NOT PERFECT\"\n\nfor _ in range(int(input())):\n n = int(input())\n lst = [int(i) for i in input().split()]\n print(rev_arr_without_slice(lst))","sub_path":"perfect_arr.py","file_name":"perfect_arr.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"477311081","text":"from numpy import *\nimport matplotlib.pyplot as plt\n\ndef convertCoordinate(pX, pY):\n x = pX/631.0\n y = (548.0 - pY)* 0.5 * sqrt(3.0) / 548\n return x, y\ndef coordinates():\n pXY = {'A':[0,548],'B':[315.5,0],'C':[631,548],'D':[16,525],'E':[27,504],'F':[169,540],'G':[173,519],'H':[285,381],'I':[270,540],'J':[354,483],'K':[458,492],'L':[429,202],'M':[317,548],'N':[394,548],'P':[173,548],'Q':[266,548],'DF1':[39, 514],'DF2':[68, 509],'DF3':[100, 513],'DF4':[122, 519],'DF5':[147, 529],'EG1':[45, 503],'EG2':[64, 501],'EG3':[96, 503],'EG4':[129, 508],'EG5':[156, 514],'GH1':[181, 493],'GH2':[195, 468],'GH3':[209, 449],'GH4':[228, 428],'GH5':[260, 398],'GH6':[177,503],'GH7':[180,498],'GH8':[222,435],'GH9':[269,392],'HL1':[293, 365],'HL2':[314, 326],'HL3':[342, 283],'HL4':[381, 239],'HL5':[417, 210],'HL6':[340,286],'HL7':[343,282],'HL8':[307,337],'HL9':[293,367] }\n coors = {}\n for key in pXY.keys():\n pX, pY = pXY.get(key)\n x, y = convertCoordinate(pX, pY)\n coors[key] = [x, y]\n return coors\ndef getLinearInfo(p1, p2):\n coors = coordinates()\n p1 = coors[p1]\n p2 = coors[p2]\n k = (p2[1] - p1[1]) / (p2[0] - p1[0])\n b = p2[1] - k * p2[0]\n return {'k':k,'b':b, 'range':[min([p1[0],p2[0]]), max([p1[0],p2[0]])]}\ndef getCurve(p1, p2, power=2):\n # power是指拟合函数的最高次项,power=3是指拟合三次函数\n coors = coordinates()\n xList = [coors[p1][0], coors[p2][0]]\n yList = [coors[p1][1], coors[p2][1]]\n for key in coors.keys():\n if (p1 in key) and (p2 in key):\n xList.append(coors[key][0])\n yList.append(coors[key][1])\n xArr = array(xList)\n yArr = array(yList)\n tmp = [xArr ** 2, xArr, ones(len(xArr))]\n keys = ['kk','k','b']\n if power > 2:\n for i in range(3, power+1):\n tmp.insert(0, xArr**i)\n keys.insert(0, keys[0] + 'k')\n A = vstack(tmp).T\n res = linalg.lstsq(A, yArr)[0]\n paraDict = {}\n for i in range(len(res)):\n paraDict[keys[i]] = res[i]\n paraDict['range'] = [min(xList), max(xList)]\n return paraDict\ndef borders():\n AB = getLinearInfo('A', 'B')\n BC = getLinearInfo('B', 'C')\n AC = getLinearInfo('A', 'C')\n FG = getLinearInfo('F', 'G')\n FP = getLinearInfo('F', 'P')\n IQ = getLinearInfo('I', 'Q')\n FI = getLinearInfo('F', 'I')\n GI = getLinearInfo('G', 'I')\n IJ = getLinearInfo('I', 'J')\n MJ = getLinearInfo('M', 'J')\n HJ = getLinearInfo('H', 'J')\n HK = getLinearInfo('H', 'K')\n JK = getLinearInfo('J', 'K')\n JM = getLinearInfo('J', 'M')\n NK = getLinearInfo('N', 'K')\n CK = getLinearInfo('C', 'K')\n S_DF = getCurve('D', 'F', 3)\n S_EG = getCurve('E', 'G', 7)\n S_GH = getCurve('G', 'H', 3)\n S_HL = getCurve('H', 'L', 3)\n bordersDict = {'AB':AB, 'BC':BC, 'AC':AC, 'FG':FG, 'FP':FP, 'IQ':IQ, 'FI':FI, 'GI':GI, 'IJ':IJ, 'MJ':MJ, 'HJ':HJ, 'HK':HK, 'JK':JK, 'JM':JM, 'NK':NK, 'CK':CK, 'S_DF':S_DF, 'S_EG':S_EG, 'S_GH':S_GH, 'S_HL':S_HL}\n return bordersDict\ndef blocks():\n coors = coordinates()\n blocksDict = {}\n bordersList = []\n keys = []\n for i in range(11):\n keys.append('block'+str(i + 1))\n for i in range(len(keys)):\n bordersDict = borders()\n # criterion:\n # more: more\n # less: less and equal\n # for block1\n if i == 0:\n AB = bordersDict['AB']\n AB['criterion'] = 'less'\n AB['range'] = [coors['E'][0], coors['B'][0]]\n BC = bordersDict['BC']\n BC['criterion'] = 'less'\n BC['range'] = [coors['B'][0], coors['L'][0]]\n S_EG = bordersDict['S_EG']\n S_EG['criterion'] = 'more'\n S_GH = bordersDict['S_GH']\n S_GH['criterion'] = 'more'\n S_HL = bordersDict['S_HL']\n S_HL['criterion'] = 'more'\n bordersList = [AB, BC, S_EG, S_GH, S_HL]\n # for block2\n elif i == 1:\n BC = bordersDict['BC']\n BC['criterion'] = 'less'\n BC['range'] = [coors['L'][0], coors['C'][0]]\n S_HL = bordersDict['S_HL']\n S_HL['criterion'] = 'less'\n HK = bordersDict['HK']\n HK['criterion'] = 'more'\n CK = bordersDict['CK']\n CK['criterion'] = 'more'\n bordersList = [BC, S_HL, HK, CK]\n # for block3\n elif i == 2:\n S_GH = bordersDict['S_GH']\n S_GH['criterion'] = 'less'\n HJ = bordersDict['HJ']\n HJ['criterion'] = 'less'\n IJ = bordersDict['IJ']\n IJ['criterion'] = 'more'\n GI = bordersDict['GI']\n GI['criterion'] = 'more'\n bordersList = [S_GH, HJ, IJ, GI]\n # for block4\n elif i == 3:\n HJ = bordersDict['HJ']\n HJ['criterion'] = 'more'\n HK = bordersDict['HK']\n HK['criterion'] = 'less'\n JK = bordersDict['JK']\n JK['criterion'] = 'more'\n bordersList = [HJ, HK, JK]\n # for block5\n elif i == 4:\n AC = bordersDict['AC']\n AC['criterion'] = 'more'\n AC['range'] = [coors['N'][0], coors['C'][0]]\n NK = bordersDict['NK']\n NK['criterion'] = 'less'\n CK = bordersDict['CK']\n CK['criterion'] = 'less'\n bordersList = [AC, NK, CK]\n # for block6\n elif i == 5:\n AC = bordersDict['AC']\n AC['criterion'] = 'more'\n AC['range'] = [coors['M'][0], coors['N'][0]]\n JM = bordersDict['JM']\n JM['criterion'] = 'less'\n JK = bordersDict['JK']\n JK['criterion'] = 'less'\n NK = bordersDict['NK']\n NK['criterion'] = 'more'\n bordersList = [AC, JM, JK, NK]\n # for block7\n elif i == 6:\n IQ = bordersDict['IQ']\n IQ['criterion'] = 'less'\n IJ = bordersDict['IJ']\n IJ['criterion'] = 'less'\n JM = bordersDict['JM']\n JM['criterion'] = 'more'\n AC = bordersDict['AC']\n AC['criterion'] = 'more'\n AC['range'] = [coors['Q'][0], coors['M'][0]]\n bordersList = [IQ, IJ, JM, AC]\n # for block8\n elif i == 7:\n AC = bordersDict['AC']\n AC['criterion'] = 'more'\n AC['range'] = [coors['A'][0], coors['P'][0]]\n AB = bordersDict['AB']\n AB['criterion'] = 'less'\n AB['range'] = [coors['A'][0], coors['D'][0]]\n S_DF = bordersDict['S_DF']\n S_DF['criterion'] = 'less'\n FP = bordersDict['FP']\n FP['criterion'] = 'less'\n bordersList = [AC, AB, S_DF, FP]\n # for block9\n elif i == 8:\n FG = bordersDict['FG']\n FG['criterion'] = 'less'\n GI = bordersDict['GI']\n GI['criterion'] = 'less'\n FI = bordersDict['FI']\n FI['criterion'] = 'more'\n bordersList = [FG, GI, FI]\n # for block10\n elif i == 9:\n AB = bordersDict['AB']\n AB['criterion'] = 'less'\n AB['range'] = [coors['D'][0], coors['E'][0]]\n S_EG = bordersDict['S_EG']\n S_EG['criterion'] = 'less'\n FG = bordersDict['FG']\n FG['criterion'] = 'more'\n S_DF = bordersDict['S_DF']\n S_DF['criterion'] = 'more'\n bordersList = [AB, S_EG, FG, S_DF]\n # for block11\n elif i == 10:\n FP = bordersDict['FP']\n FP['criterion'] = 'more'\n FI = bordersDict['FI']\n FI['criterion'] = 'less'\n IQ = bordersDict['IQ']\n IQ['criterion'] = 'more'\n AC = bordersDict['AC']\n AC['criterion'] = 'more'\n AC['range'] = [coors['P'][0], coors['Q'][0]]\n bordersList = [FP, FI, IQ, AC]\n blocksDict[keys[i]] = bordersList\n return blocksDict\ndef decideBlock(x, y):\n blocksDict = blocks()\n keys = []\n for i in range(11):\n keys.append('block'+str(i + 1))\n for key in keys:\n block = blocksDict[key]\n resList = []\n for border in block:\n if (x >= border['range'][0]) and (x <= border['range'][1]):\n # print(border)\n resY = 0.0\n for k in border.keys():\n if 'k' in k:\n resY += border[k] * (x**len(k))\n if 'b' in k:\n resY += border['b']\n if ((border['criterion'] == 'more') and (round(y,6) >= resY)) or ((border['criterion'] == 'less') and (round(y,6) <= resY * 1.00001)):\n resList.append(True)\n else:\n resList.append(False)\n if (False not in resList) and (len(resList) >= 2):\n return keys.index(key) + 1\ndef plotBorders():\n ax = plt.subplot(111)\n bordersDict = borders()\n for key in bordersDict.keys():\n border = bordersDict[key]\n x = arange(0, 1.0, 0.001)\n yList = []\n for e in x:\n y = 0.0\n for a in border.keys():\n if 'k' in a:\n y += border[a] * (e ** len(a))\n if 'b' in a:\n y += border[a]\n yList.append(y)\n yArr = array(yList)\n plt.plot(x, yArr, label=\"Border=%s\" % (key,), linewidth=0.5)\n plt.xlim(0, 1.0)\n plt.ylim(0, 0.866)\n plt.legend()\n leg = plt.legend(loc=2, ncol=2)\n leg.get_frame().set_alpha(0)\n plt.show()\n\n# plotBorders()\n\n# x,y = convertCoordinate(195,543)\n# print('x',x,'y',y)\n\n# x = 0.523317108369\n# y = 0.825638987404\n# res = decideBlock(x,y)\n# borY = sqrt(3) * (1 - x)\n# print('result = ',res,'border = ',borY)\n","sub_path":"python_src/ternaryUtil.py","file_name":"ternaryUtil.py","file_ext":"py","file_size_in_byte":9779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"244637844","text":"# An average Green Fox attendee codes 6 hours daily\n# The semester is 17 weeks long\n#\n# Print how many hours is spent with coding in a semester by an attendee,\n# if the attendee only codes on workdays.\n#\n# Print the percentage of the coding hours in the semester if the average\n# work hours weekly is 52\n\ni = (17*(5*6))\naverage = 17*52\npercentage = i / average *100\nprint(\"An attendee code: \" + str(i) + \" hours in a semester!\")\nstr(i / average *100) + \"%\"\nprint(str(percentage //1) + \"%\")\n","sub_path":"week-02/day-01/coding_hours.py","file_name":"coding_hours.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"592830616","text":"\n\n# TODO: finish this\ndef evaluate_policy(policy, rollouts):\n pass\n\ndef run_policy(policy, rollouts, new_rollouts, proxy_environment, behavior_policy, train_models):\n pass\n\n\n\ndef analyzeRL(args, save_path, true_environment, train_models, learning_algorithm, proxy_environment,\n proxy_chain, reward_classes, state_class, behavior_policy):\n print(\"#######\")\n print(\"Training Options\")\n print(\"#######\")\n # if option_chain is not None: #TODO: implement this\n base_env = proxy_chain[0]\n base_env.set_save(0, args.save_dir, args.save_recycle)\n proxy_environment.initialize(args, proxy_chain, reward_classes, state_class, behavior_policy)\n if args.save_models:\n save_to_pickle(os.path.join(save_path, \"env.pkl\"), proxy_environment)\n behavior_policy.initialize(args, state_class.action_num)\n print(\"loading weights\", args.load_weights)\n if not args.load_weights:\n train_models.initialize(args, len(reward_classes), state_class)\n proxy_environment.set_models(train_models)\n learning_algorithm.initialize(args, train_models)\n state = pytorch_model.wrap(proxy_environment.getState(), cuda = args.cuda)\n hist_state = pytorch_model.wrap(proxy_environment.getHistState(), cuda = args.cuda)\n raw_state = base_env.getState()\n cp_state = proxy_environment.changepoint_state([raw_state])\n # print(\"initial_state (s, hs, rs, cps)\", state, hist_state, raw_state, cp_state)\n # print(cp_state.shape, state.shape, hist_state.shape, state_class.shape)\n rollouts = RolloutOptionStorage(args.num_processes, (state_class.shape,), state_class.action_num, state.shape, hist_state.shape, args.buffer_steps, args.changepoint_queue_len, len(train_models.models), cp_state[0].shape)\n option_actions = {option.name: collections.Counter() for option in train_models.models}\n total_duration = 0\n total_elapsed = 0\n start = time.time()\n fcnt = 0\n final_rewards = list()\n option_counter = collections.Counter()\n option_value = collections.Counter()\n collect_policies = []\n characteristic_policies = []\n for j in range(args.num_iters):\n rollouts.set_parameters(learning_algorithm.current_duration)\n raw_actions = []\n rollouts.cuda()\n for step in range(learning_algorithm.current_duration):\n fcnt += 1\n current_state = proxy_environment.getHistState()\n estate = proxy_environment.getState()\n values, dist_entropy, action_probs, Q_vals = train_models.determine_action(current_state.unsqueeze(0))\n v, ap, qv = train_models.get_action(values, action_probs, Q_vals)\n action = behavior_policy.take_action(ap, qv)\n # print(ap, action)\n cp_state = proxy_environment.changepoint_state([raw_state])\n # print(state, action)\n rollouts.insert(step, state, current_state, action_probs, action, Q_vals, values, train_models.option_index, cp_state[0], pytorch_model.wrap(args.greedy_epsilon, cuda=args.cuda))\n # print(\"step states (cs, s, cps, act)\", current_state, estate, cp_state, action) \n # print(\"step outputs (val, de, ap, qv, v, ap, qv)\", values, dist_entropy, action_probs, Q_vals, v, ap, qv)\n\n state, raw_state, done, action_list = proxy_environment.step(action, model = False)#, render=len(args.record_rollouts) != 0, save_path=args.record_rollouts, itr=fcnt)\n # print(\"step check (al, s)\", action_list, state)\n learning_algorithm.interUpdateModel(step)\n #### logging\n option_actions[train_models.currentName()][int(pytorch_model.unwrap(action.squeeze()))] += 1\n #### logging\n\n if done:\n # print(\"reached end\")\n rollouts.cut_current(step+1)\n # print(step)\n break\n current_state = proxy_environment.getHistState()\n values, dist_entropy, action_probs, Q_vals = train_models.determine_action(current_state.unsqueeze(0))\n v, ap, qv = train_models.get_action(values, action_probs, Q_vals)\n action = behavior_policy.take_action(ap, qv)\n # print(state, action)\n # print(\"step states (cs, s, cps, act)\", current_state, estate, cp_state, action) \n # print(\"step outputs (val, de, ap, qv, v, ap, qv)\", values, dist_entropy, action_probs, Q_vals, v, ap, qv)\n\n cp_state = proxy_environment.changepoint_state([raw_state])\n rollouts.insert(step + 1, state, current_state, action_probs, action, Q_vals, values, train_models.option_index, cp_state, pytorch_model.wrap(args.greedy_epsilon, cuda=args.cuda)) # inserting the last state and unused action\n # print(\"states and actions (es, cs, a, m)\", rollouts.extracted_state, rollouts.current_state, rollouts.actions, rollouts.masks)\n # print(\"actions and Qvals (qv, vp, ap)\", rollouts.Qvals, rollouts.value_preds, rollouts.action_probs)\n\n total_duration += step + 1\n rewards = proxy_environment.computeReward(rollouts, step+1)\n # print(\"rewards\", rewards)\n rollouts.insert_rewards(rewards)\n # print(rollouts.extracted_state)\n # print(rewards)\n rollouts.compute_returns(args, values)\n # print(\"returns and rewards (rew, ret)\", rollouts.rewards, rollouts.returns)\n # print(\"returns and return queue\", rollouts.returns, rollouts.return_queue)\n # print(\"reward check (cs, rw, rol rw, rt\", rollouts.current_state, rewards, rollouts.rewards, rollouts.returns)\n name = train_models.currentName()\n # print(name, rollouts.extracted_state, rollouts.rewards, rollouts.actions)\n\n #### logging\n reward_total = rollouts.rewards.sum(dim=1)[train_models.option_index]\n final_rewards.append(reward_total)\n option_counter[name] += step + 1\n option_value[name] += reward_total.data \n #### logging\n if step != 0:\n value_loss, action_loss, dist_entropy, output_entropy, entropy_loss, action_log_probs = learning_algorithm.step(args, train_models, rollouts)\n else:\n continue\n if args.dist_interval != -1 and j % args.dist_interval == 0:\n learning_algorithm.distibutional_sparcity_step(args, train_models, rollouts)\n if args.greedy_epsilon_decay > 0 and j % args.greedy_epsilon_decay == 0 and j != 0:\n behavior_policy.epsilon = max(args.min_greedy_epsilon, behavior_policy.epsilon * 0.5) # TODO: more advanced greedy epsilon methods\n learning_algorithm.updateModel()\n\n if j % args.save_interval == 0 and args.save_models and args.train: # no point in saving if not training\n print(\"=========SAVING MODELS==========\")\n train_models.save(save_path) # TODO: implement save_options\n\n\n #### logging\n if j % args.log_interval == 0:\n print(\"Qvalue and state\", pytorch_model.unwrap(Q_vals.squeeze()), pytorch_model.unwrap(current_state.squeeze()))\n print(\"probs and state\", pytorch_model.unwrap(action_probs.squeeze()), pytorch_model.unwrap(current_state.squeeze()))\n for name in train_models.names():\n if option_counter[name] > 0:\n print(name, option_value[name] / option_counter[name], [option_actions[name][i]/option_counter[name] for i in range(len(option_actions[name]))])\n if j % (args.log_interval * 20) == 0:\n option_value[name] = 0\n option_counter[name] = 0\n for i in range(len(option_actions[name])):\n option_actions[name][i] = 0\n end = time.time()\n final_rewards = torch.stack(final_rewards)\n el, vl, al = unwrap_or_none(entropy_loss), unwrap_or_none(value_loss), unwrap_or_none(action_loss)\n total_elapsed += total_duration\n log_stats = \"Updates {}, num timesteps {}, FPS {}, mean/median reward {:.1f}/{:.1f}, min/max reward {:.1f}/{:.1f}, entropy {}, value loss {}, policy loss {}\".format(j, total_elapsed,\n int(total_elapsed / (end - start)),\n final_rewards.mean(),\n np.median(final_rewards.cpu()),\n final_rewards.min(),\n final_rewards.max(), el,\n vl, al)\n print(log_stats)\n final_rewards = list()\n total_duration = 0\n #### logging\n","sub_path":"ReinforcementLearning/rl_analysis.py","file_name":"rl_analysis.py","file_ext":"py","file_size_in_byte":8444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"415247438","text":"from fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\nimport uvicorn\n\nfrom app import db, ml, viz\n\ndescription = \"\"\"\nMISSION: Be a one-stop resource for users to receive the most accurate city information.\n\n\nCITYSPIRE APP:\nAn app that analyzes data from cities such as populations, cost of living,\\n\nrental rates, crime rates, park (walk score), and many other social \\n\nand economic factors that are important in deciding where someone would like to live.\\n\nThis app will present such important data in an intuitive and easy to understand interface.\\n\n\nUse data to find a place right for you to live.\n\"\"\"\n\napp = FastAPI(\n title=\"CITYSPIRE API\",\n description=description,\n docs_url=\"/\",\n)\n\napp.include_router(db.router, tags=[\"Database\"])\napp.include_router(ml.router, tags=[\"Machine Learning\"])\napp.include_router(viz.router, tags=[\"Visualization\"])\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n\n@app.on_event(\"startup\")\nasync def startup():\n await db.database.connect()\n\n\n@app.on_event(\"shutdown\")\nasync def shutdown():\n await db.database.disconnect()\n\n\nif __name__ == \"__main__\":\n uvicorn.run(app)\n","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"501342698","text":"\"\"\"Mysql wrappers to execute mysql statements.\nThe default behaviour depends on the configuration module which contains the\ndatabase settings to use.\n\"\"\"\n\nfrom contextlib import contextmanager\nfrom functools import wraps\nimport logging\n\nimport MySQLdb\nfrom helot_common import configuration\n\n\n@contextmanager\ndef db_connection(host=None, user=None, passwd=None, db=None,\n connect_to_db=True):\n \"\"\"Auto closing db connection context manager.\n Yields an active db connection which will be closed automatically.\n :parameter connect_to_db: (boolean) True to connect to the database.\n Otherwise it will no connect to a specific database, something that can be\n useful in the case of a database creation.\n \"\"\"\n params = {\n 'host': host or configuration.mysql.host,\n 'user': user or configuration.mysql.user,\n 'passwd': passwd or configuration.mysql.passwd\n }\n\n if connect_to_db:\n params['db'] = db or configuration.mysql.db\n\n db_conn = MySQLdb.connect(**params)\n yield db_conn\n db_conn.close()\n\n\n@contextmanager\ndef db_cursor(db_conn):\n \"\"\"Auto closing db cursor context manager.\n Yields an live db cursor which will be closed automatically.\n :parameter db_conn: The db connection to use for the creation of the cursor.\n \"\"\"\n cur = db_conn.cursor()\n yield cur\n cur.close()\n\n\n@contextmanager\ndef make_query_executor(*args, **kwargs):\n \"\"\"Context manager providing a function to execute sql queries.\n Yields a query executor function.\n \"\"\"\n with db_connection(*args, **kwargs) as db_conn, db_cursor(db_conn) as cur:\n def execute_query(sql):\n cur.execute(sql)\n col_names = [col_data[0] for col_data in cur.description]\n for row in cur.fetchall():\n row_data = _RawData()\n for i, cell in enumerate(row):\n setattr(row_data, col_names[i], cell)\n yield row_data\n\n yield execute_query\n\n\n@contextmanager\ndef make_non_query_executor(*args, **kwargs):\n \"\"\"Context manager providing a function to execute non query statements.\n Yields a non query executor function.\n :parameter use_db: (boolean) True to connect to the database. Otherwise it\n will no connect to a specific database, something that can be useful in the\n case of a database creation.\n \"\"\"\n with db_connection(*args, **kwargs) as db_conn, db_cursor(db_conn) as cur:\n def execute_non_query(sql):\n try:\n cur.execute(sql)\n db_conn.commit()\n except Exception as ex:\n logging.exception(ex)\n db_conn.rollback()\n\n yield execute_non_query\n\n\nclass _RawData(object):\n \"\"\"Used to create the object to encapsulate the data of retrieved row.\"\"\"\n\n\ndef query_executor_user(function_to_decorate):\n \"\"\"Decorates a function adding an execute query function argument.\n When decorates a function its signature must contain an argument called\n execute_query which will receive a sql executor to use for queries.\n :parameter function_to_decorate: The function to decorate.\n :returns : The decorated function containing the execute_query argument.\n \"\"\"\n\n @wraps(function_to_decorate)\n def decorator(*args, **kargs):\n with make_query_executor() as execute_query:\n kargs['execute_query'] = execute_query\n return function_to_decorate(*args, **kargs)\n\n return decorator\n\n\ndef execute_query(sql, **kwargs):\n \"\"\"Simplest way to execute a query.\n Opens and closes a new connection and cursor every time called.\n :param sql: (str) The sql statement to execute.\n :param kwargs: The connection settings.\n Yields a sequence of rows coming from the execution of the query.\n \"\"\"\n with make_query_executor(**kwargs) as executor:\n for row in executor(sql):\n yield row\n","sub_path":"helot_mysql/wrappers.py","file_name":"wrappers.py","file_ext":"py","file_size_in_byte":3917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"487859311","text":"import pandas as pd\nimport numpy as np\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\nbaby = pd.read_csv('../dataset/day_care_center.csv')\n\nprint(baby.head(4))\n#서울 데이터만 추출\nbaby = baby.loc[baby['city'] == '서울특별시']\n\n#결측치 평균으로 채우기\nbaby['teacher_num'] = baby['teacher_num'].fillna(baby['teacher_num'].mean())\nprint('결측치 확인: ', baby['teacher_num'].isnull().sum())\n\n#구별로 매핑\nbaby['gu_map'] = baby['gu'].map({'용산구': 0, '양천구': 1, '강동구': 2, '관악구': 3, '노원구': 4, '영등포구': 5, '마포구': 6, '서초구': 7, '성동구': 8, '금천구': 9, '도봉구': 10, '동작구': 11, '강서구': 12, '동대문구': 13, '강북구': 14, '서대문구': 15, '광진구': 16, '구로구': 17, '성북구': 18, '강남구': 19, '종로구': 20, '중구': 21, '중랑구': 22, '송파구': 23, '은평구': 24})\n\n\nbaby_type = baby['day_care_type'].unique()\n\nprint(baby_type)\n\n#기관 별로 가중치 입력\nprint('결측치 확인', baby['day_care_type'].isnull().sum())\n\nbaby['baby/teacher point'] = baby['day_care_type'].map({'국공립':0.4, '사회복지법인': 0.3, '직장':0.3, '법인·단체':0.3, '민간':0.2,'협동':0.1, '가정':0.1})\nprint('1결측치 확인', baby['baby/teacher point'].isnull().sum())\n\nprint(baby.head(5))\n\n# 가중치 곱한 값 입력\nbaby['day_care_baby_num'] = round(baby['day_care_baby_num'] * baby['baby/teacher point'], 3)\nbaby['teacher_num'] = round(baby['teacher_num'] * baby['baby/teacher point'], 3)\n\nprint(baby.head(5))\n\n#구별 아이 수와 선생 수 합하기\nbaby_sum = []\nteacher_sum = []\ngu = []\n\nfor i in baby['gu'].unique():\n gu.append(i)\n x = baby.loc[baby['gu'] == i]['day_care_baby_num'].sum()\n y = baby.loc[baby['gu'] == i]['teacher_num'].sum()\n baby_sum.append(x)\n teacher_sum.append(y)\n\nset1 = pd.DataFrame()\nset1['gu'] = gu\nset1['baby_sum'] = baby_sum\nset1['teacher_sum'] = teacher_sum\n\nprint(set1.head(4))\n\nset1['baby/teacher point'] = round(set1['baby_sum'] / set1['teacher_sum'],2)\n\nprint(set1)\n\nset1.to_csv('../dataset/baby_center.csv', header = True, index = False)","sub_path":"preprocessing/day_care_center.py","file_name":"day_care_center.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"108492439","text":"import pytest\nfrom Pages.login_page import Loginpage\nfrom selenium import webdriver\nfrom Utils import utils as utils\nimport allure\n\n\n#@pytest.mark.usefixtures(\"setup\")\nclass TestLogin():\n\n @pytest.fixture(scope=\"class\")\n def setup(self):\n global driver\n driver = webdriver.Chrome(\n executable_path=\"C:\\\\Users\\\\C5261196\\\\Downloads\\\\chromedriver_win32\\\\chromedriver.exe\")\n driver.maximize_window()\n yield\n driver.close()\n\n def test_login_valid(self,setup):\n driver.get(utils.URL)\n login = Loginpage(driver)\n login.enter_email_textbox(utils.USERNAME)\n login.enter_password_textbox(utils.PASSWORD)\n login.click_login_button()\n","sub_path":"PythonWebAutomation-master/Tests/login_test.py","file_name":"login_test.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"475403826","text":"MAX_ITERATIONS = 40\nDEBUG = False\nPRETTY_LOG = True\nUSED_MODELS = ['Baseline', 'SDBN', 'UBM', 'UBM-IA', 'EB_UBM', 'EB_UBM-IA', 'DCM', 'DCM-IA', 'DBN', 'DBN-IA']\nMIN_DOCS_PER_QUERY = 10\nMAX_DOCS_PER_QUERY = 10\nSERP_SIZE = 10\nEXTENDED_LOG_FORMAT = False\n\nTRANSFORM_LOG = False\nQUERY_INDEPENDENT_PAGER = False\n\nTRAIN_FOR_METRIC = False\nPRINT_EBU_STATS = True\n\n","sub_path":"config_sample.py","file_name":"config_sample.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"244528988","text":"def solution(N,A):\n li = {i:0 for i in range(1, N+1)}\n max_sum = 0\n max_num = 0\n for key in A:\n if(key == N+1):\n max_sum += max_num\n li.clear()\n max_num = 0\n else:\n if(li.get(key) is None):\n li[key] = 1\n else:\n \tli[key] += 1\n max_num = max(max_num, li[key])\n answer = [max_sum] * N\n for key, val in li.items():\n answer[key-1] +=val\n return answer","sub_path":"minjoo/Codility/MaxCounters.py","file_name":"MaxCounters.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"465121378","text":"from typing import List\n\n\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n t = 0\n i = 1\n while i < len(nums):\n if nums[i] == nums[i-1]:\n t += 1\n else:\n t = 0\n if t >= 2:\n nums.pop(i)\n t -= 1\n else:\n i += 1\n return len(nums)\n\n\nif __name__ == \"__main__\":\n solu = Solution()\n nums = [1, 1, 1, 2, 2, 3]\n print(solu.removeDuplicates(nums))","sub_path":"remove_duplicates2.py","file_name":"remove_duplicates2.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"446705540","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nt_start = 0.0\nt_final = 5.0\n\n#starting points of numerical calculation:\nt = [0]\nx = [1]\nt_n = 0\n\nstep = 0.1\n\nwhile t_n < t_final:\n x_n = x[-1] + step* x[-1] #calculate new value, with the previous value\n x.append(x_n) #store it in your data list\n t_n += step # increase the time with the step\n t.append(t_n)\n\n#(semi-)anaytic:\nt2 = np.arange(t_start, t_final, 0.001)\nx2 = np.exp(t2)\n\n#plot both in one plot:\nplt.plot(t,x, 'r', label = \"numeric\")\nplt.plot(t2, x2, 'b', label = \"analytic\")\n\nplt.legend()\nplt.xlabel(\"x\")\nplt.ylabel(\"t\")\nplt.title(r\"Euler integration of $e^t$ with a step size of %.2f\" %step)\n\n#saving data to file and save figure:\n\n#file = open(\"Data_EulerInt.txt\", 'w')\n#file.write(\"Euler Integration of exp(t):\\n t \\t f(t)\\n\")\n#for i in range(len(x)):\n\t#file.write(\"%.4f \\t %.4f \\n\" %(t[i], x[i]))\n#file.close() # make sure you close your file!\n\n#plt.savefig(\"EulerIntegration.png\")\nplt.show()\n","sub_path":"EulerIntegration.py","file_name":"EulerIntegration.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"87877803","text":"import discord\nimport asyncio\nimport datetime\nfrom discord.ext import commands\nfrom discord import Embed\nfrom pathlib import Path\nimport sys, traceback\nimport os\ntry:\n import config\nexcept ImportError:\n print(\"Couldn't import config.py\")\n\nbot = commands.Bot(command_prefix=os.getenv('prefix'), description='I ban people who deserves so...')\n\nstartup_extensions = [\"moderation\",\n \"info\"]\n\n@bot.event\nasync def on_ready():\n print(\"[Info] Bot startup done.\")\n channel = bot.get_channel(int(os.getenv('botlog')))\n await channel.send(\"**[Info]** Bot startup done.\")\n print(\"\\n\")\n await bot.change_presence(game=discord.Game(name=\"with the banhammer\"))\n\n@bot.event\nasync def on_command_error(ctx: commands.Context, error):\n if isinstance(error, commands.NoPrivateMessage):\n await ctx.send(\"This command cannot be used in private messages\")\n elif isinstance(error, commands.BotMissingPermissions):\n await ctx.send(embed=Embed(color=discord.Color.red(), description=\"I need the permission `Ban Members` to sync the bans!\"))\n elif isinstance(error, commands.MissingPermissions):\n await ctx.send(embed=Embed(color=discord.Color.red(), description=\"You are missing the permission `Ban Members`!\"))\n elif isinstance(error, commands.CheckFailure):\n return\n elif isinstance(error, commands.CommandOnCooldown):\n return\n elif isinstance(error, commands.MissingRequiredArgument):\n return\n elif isinstance(error, commands.BadArgument):\n return\n elif isinstance(error, commands.CommandNotFound):\n return\n else:\n await ctx.send(\"Something went wrong while executing that command... Sorry!\")\n channel = bot.get_channel(int(os.getenv('botlog')))\n await channel.send(\"**[ERROR]** %s\" % error)\n\n@bot.event\nasync def on_guild_join(guild):\n channel = bot.get_channel(int(os.getenv('botlog')))\n print(\"[Info] Joined a new guild (`%s` - `%s`)\" % (guild.name, guild.id))\n await channel.send(\"**[Info]** Joined a new guild (`%s` - `%s`)\" % (guild.name, guild.id))\n banguild = bot.get_guild(int(os.getenv('banlistguild')))\n ban_list = await banguild.bans()\n for BanEntry in ban_list:\n await guild.ban(BanEntry.user, reason=f\"WatchDog - Global Ban\")\n\n@bot.event\nasync def on_message(message:discord.Message):\n if message.author.bot:\n return\n ctx:commands.Context = await bot.get_context(message)\n if message.content.startswith(os.getenv('prefix')):\n if ctx.command is not None:\n print(\"[Command] %s (%s) just used the %s command in the guild %s (%s)\" % (ctx.author.name, ctx.author.id, ctx.invoked_with, ctx.guild.name, ctx.guild.id))\n channel = bot.get_channel(int(os.getenv('botlog')))\n await channel.send(\"**[Command]** `%s` (%s) used the `%s` command in the guild `%s` (%s), in the channel `%s` (%s)\" % (ctx.author.name, ctx.author.id, ctx.invoked_with, ctx.guild.name, ctx.guild.id, ctx.channel.name, ctx.channel.id))\n await bot.invoke(ctx)\n else:\n return\n\nif __name__ == '__main__':\n for extension in startup_extensions:\n try:\n bot.load_extension(f\"cogs.{extension}\")\n except Exception as e:\n print(f\"[ERROR] Failed to load extention {extension}.\", e)\n\nbot.run(os.getenv('token'))\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"342208856","text":"import json\n\nwith open(\"itemprices.json\") as json_file:\n menu_card = json.load(json_file)\n\ndef calculate_order_total(order):\n global menu_card\n order_list = list(order)\n total = sum([menu_card[item] for item in order_list])\n print(f\"Your order total is {total}\")\n\nmenu = '''\n====== MENU for today: =======\n 1. \"Chicken Strips\": 280,\n 2. \"French Fries\": 140,\n 3. \"Hamburger\": 160,\n 4. \"Hotdog\": 120,\n 5. \"Large Drink\": 100,\n 6. \"Medium Drink\": 75,\n 7. \"Milk Shake\": 85,\n 8. \"Salad\": 125,\n 9. \"Small Drink\": 60\n'''\ndef take_orders():\n take = True\n while take:\n print(menu)\n order = input(\"Please entre your order\")\n calculate_order_total(order)\n repeat = input(\"Do you want to place another order ? Y/N\")\n if repeat == 'n' or repeat =='N':\n take = False\n\nif __name__ == \"__main__\":\n take_orders()","sub_path":"menucalculator/menucalculator.py","file_name":"menucalculator.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"317593339","text":"from __future__ import division\nfrom builtins import str\nfrom builtins import range\nfrom builtins import object\nfrom past.utils import old_div\nimport copy\nimport datetime\nimport random\nfrom contextlib import contextmanager\n\nimport pytest\nimport pytest_twisted\nimport pytz\nfrom mock import MagicMock, Mock, PropertyMock, call, patch\nfrom twisted.internet import defer\nfrom twisted.internet.task import Clock\n\nfrom cardinal import util\nfrom cardinal.bot import CardinalBot, user_info\nfrom cardinal.unittest_util import get_mock_db\nfrom plugins.ticker import plugin\nfrom plugins.ticker.plugin import (\n TickerPlugin,\n colorize,\n get_delta,\n)\n\n\ndef get_fake_now(market_is_open=True):\n tz = pytz.timezone('America/New_York')\n fake_now = datetime.datetime.now(tz)\n if market_is_open:\n # Ensure it is open\n fake_now = fake_now.replace(hour=10)\n while fake_now.weekday() >= 5:\n fake_now = fake_now - datetime.timedelta(days=1)\n else:\n # Ensure it is closed\n fake_now = fake_now.replace(hour=18)\n\n return fake_now\n\n\n@contextmanager\ndef mock_api(response,\n fake_now=None,\n raise_times=0,\n throttle_times=0):\n fake_now = fake_now or get_fake_now()\n responses = copy.deepcopy(response) \\\n if isinstance(response, list) else \\\n [copy.deepcopy(response)]\n\n response_mock = MagicMock()\n type(response_mock).status_code = PropertyMock(return_value=200)\n\n # hack since nonlocal doesn't exist in py2\n context = {'raise_times': raise_times, 'throttle_times': throttle_times}\n\n def mock_deferToThread(*args, **kwargs):\n if context['raise_times'] > 0:\n context['raise_times'] -= 1\n raise Exception('mock exception')\n\n elif context['throttle_times'] > 0:\n context['throttle_times'] -= 1\n response_mock.json.return_value = make_throttle_response()\n\n else:\n response_mock.json.return_value = responses.pop(0)\n\n return response_mock\n\n with patch.object(plugin, 'deferToThread') as mock_defer, \\\n patch.object(plugin, 'est_now', return_value=fake_now):\n mock_defer.side_effect = mock_deferToThread\n\n yield mock_defer\n\n\ndef make_throttle_response():\n return {\n \"Note\": \"Thank you for using Alpha Vantage! Our standard API call \"\n \"frequency is 5 calls per minute and 500 calls per day. \"\n \"Please visit https://www.alphavantage.co/premium/ if you \"\n \"would like to target a higher API call frequency.\"\n }\n\n\ndef make_global_quote_response(symbol,\n open_=None,\n close=None,\n previous_close=None,\n latest_trading_day=None,\n ):\n if latest_trading_day is None:\n latest_trading_day = datetime.datetime.today()\n\n open_ = open_ or \\\n random.randrange(95, 105) + random.random()\n high = random.randrange(106, 110) + random.random()\n low = random.randrange(90, 94) + random.random()\n close = close or \\\n random.randrange(95, 105) + random.random()\n previous_close = previous_close or \\\n random.randrange(95, 105) + random.random()\n volume = random.randrange(100000, 999999)\n\n change = close - previous_close\n change_percent = old_div(1.0 * close, previous_close) * 100 - 100\n\n return {\n \"Global Quote\": {\n \"01. symbol\": symbol.upper(),\n \"02. open\": \"{:.4f}\".format(open_),\n \"03. high\": \"{:.4f}\".format(high),\n \"04. low\": \"{:.4f}\".format(low),\n \"05. price\": \"{:.4f}\".format(close),\n \"06. volume\": \"{}\".format(volume),\n \"07. latest trading day\": latest_trading_day.strftime('%Y-%m-%d'),\n \"08. previous close\": \"{:.4f}\".format(previous_close),\n \"09. change\": \"{:.4f}\".format(change),\n \"10. change percent\": \"{:.4f}%\".format(change_percent),\n },\n }\n\n\ndef make_time_series_daily_response(symbol,\n last_open=None,\n last_close=None,\n previous_close=None,\n start=None):\n \"\"\"Mock response for TIME_SERIES_DAILY API\"\"\"\n\n last_market_day = start or datetime.datetime.today()\n while last_market_day.weekday() >= 5:\n last_market_day = last_market_day - datetime.timedelta(days=1)\n\n previous_market_day = last_market_day - datetime.timedelta(days=1)\n while previous_market_day.weekday() >= 5:\n previous_market_day = previous_market_day - datetime.timedelta(days=1)\n\n def make_random_response():\n open_ = random.randrange(95, 105) + random.random()\n high = random.randrange(106, 110) + random.random()\n low = random.randrange(90, 94) + random.random()\n close = random.randrange(95, 105) + random.random()\n volume = random.randrange(100000, 999999)\n return {\n \"1. open\": \"{:.4f}\".format(open_),\n \"2. high\": \"{:.4f}\".format(high),\n \"3. low\": \"{:.4f}\".format(low),\n \"4. close\": \"{:.4f}\".format(close),\n \"5. volume\": \"{}\".format(volume)\n }\n\n time_series_daily = {}\n market_day = last_market_day # this changes each iteration\n for days in range(0, 60):\n # don't add data for weekends\n if market_day.weekday() < 5:\n response = make_random_response()\n\n # Override last open / last close for testing\n if market_day == last_market_day:\n if last_open:\n response[\"1. open\"] = \"{:.4f}\".format(last_open)\n if last_close:\n response[\"4. close\"] = \"{:.4f}\".format(last_close)\n if market_day == previous_market_day and previous_close:\n response[\"4. close\"] = \"{:.4f}\".format(previous_close)\n\n time_series_daily[market_day.strftime(\"%Y-%m-%d\")] = response\n market_day = market_day - datetime.timedelta(days=1)\n\n compact = True\n return {\n \"Meta Data\": {\n \"1. Information\": \"Daily Prices (open, high, low, close) and \"\n \"Volumes\",\n \"2. Symbol\": symbol,\n \"3. Last Refreshed\": datetime.datetime.now().strftime(\"%Y-%m-%d\"),\n \"4. Output Size\": \"Compact\" if compact else \"Full size\",\n \"5. Time Zone\": \"US/Eastern\"\n },\n \"Time Series (Daily)\": time_series_daily,\n }\n\n\ndef test_get_delta():\n assert get_delta(105, 100) == 5.0\n assert get_delta(95, 100) == -5.0\n assert get_delta(100, 100) == 0\n\n\ndef test_colorize():\n assert colorize(-0.151) == '\\x0304-0.15%\\x03'\n assert colorize(-0.1) == '\\x0304-0.10%\\x03'\n assert colorize(0) == '\\x03040.00%\\x03'\n assert colorize(0.1) == '\\x03090.10%\\x03'\n assert colorize(0.159) == '\\x03090.16%\\x03'\n\n\nclass TestTickerPlugin(object):\n @pytest.fixture(autouse=True)\n def setup_method_fixture(self, request, tmpdir):\n self.api_key = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n self.channel = '#test'\n self.channels = [self.channel]\n self.stocks = {\n 'INX': 'S&P 500',\n 'DJI': 'Dow',\n 'VEU': 'Foreign',\n 'AGG': 'US Bond',\n }\n self.relay_bots = [\n {\"nick\": \"relay.bot\", \"user\": \"relay\", \"vhost\": \"relay\"},\n ]\n\n d = tmpdir.mkdir('storage')\n\n get_db, self.db = get_mock_db()\n self.mock_cardinal = Mock(spec=CardinalBot)\n self.mock_cardinal.network = self.network = 'irc.darkscience.net'\n self.mock_cardinal.storage_path = str(d.dirpath())\n self.mock_cardinal.get_db.side_effect = get_db\n\n self.plugin = TickerPlugin(self.mock_cardinal, {\n 'api_key': self.api_key,\n 'channels': self.channels,\n 'stocks': self.stocks,\n 'relay_bots': self.relay_bots,\n })\n\n def test_config_defaults(self):\n plugin = TickerPlugin(self.mock_cardinal, {\n 'api_key': self.api_key,\n })\n assert plugin.config['api_key'] == self.api_key\n assert plugin.config['channels'] == []\n assert plugin.config['stocks'] == {}\n assert plugin.config['relay_bots'] == []\n\n def test_missing_api_key(self):\n with pytest.raises(KeyError):\n TickerPlugin(self.mock_cardinal, {})\n\n def test_missing_stocks(self):\n with pytest.raises(ValueError):\n TickerPlugin(self.mock_cardinal, {\n 'api_key': self.api_key,\n 'stocks': {\n 'a': 'a',\n 'b': 'b',\n 'c': 'c',\n 'd': 'd',\n 'e': 'e',\n 'f': 'f',\n },\n })\n\n @defer.inlineCallbacks\n def test_send_ticker(self):\n responses = [\n make_global_quote_response('DJI',\n previous_close=100,\n close=200),\n make_global_quote_response('AGG',\n previous_close=100,\n close=150.50),\n make_global_quote_response('VEU',\n previous_close=100,\n close=105),\n make_global_quote_response('INX',\n previous_close=100,\n close=50),\n ]\n\n with mock_api(responses, fake_now=get_fake_now(market_is_open=True)):\n yield self.plugin.send_ticker()\n\n self.mock_cardinal.sendMsg.assert_called_once_with(\n self.channel,\n 'Dow (\\x02DJI\\x02): \\x0309100.00%\\x03 | '\n 'Foreign (\\x02VEU\\x02): \\x03095.00%\\x03 | '\n 'S&P 500 (\\x02INX\\x02): \\x0304-50.00%\\x03 | '\n 'US Bond (\\x02AGG\\x02): \\x030950.50%\\x03'\n )\n\n @pytest.mark.parametrize(\"dt,should_send_ticker,should_do_predictions\", [\n (datetime.datetime(2020, 3, 21, 16, 0, 0), # Saturday 4pm\n False,\n False,),\n (datetime.datetime(2020, 3, 22, 16, 0, 0), # Sunday 4pm\n False,\n False,),\n (datetime.datetime(2020, 3, 23, 15, 45, 45), # Monday 3:45pm\n True,\n False,),\n (datetime.datetime(2020, 3, 23, 16, 0, 30), # Monday 4pm\n True,\n True,),\n (datetime.datetime(2020, 3, 23, 16, 15, 0), # Monday 4:15pm\n False,\n False,),\n (datetime.datetime(2020, 3, 27, 9, 15, 0), # Friday 9:15am\n False,\n False,),\n (datetime.datetime(2020, 3, 27, 9, 30, 15), # Friday 9:30am\n True,\n True,),\n (datetime.datetime(2020, 3, 27, 9, 45, 15), # Friday 9:45am\n True,\n False,),\n ])\n @patch.object(plugin.TickerPlugin, 'do_predictions')\n @patch.object(plugin.TickerPlugin, 'send_ticker')\n @patch.object(util, 'sleep')\n @patch.object(plugin, 'est_now')\n @pytest_twisted.inlineCallbacks\n def test_tick(self,\n est_now,\n sleep,\n send_ticker,\n do_predictions,\n dt,\n should_send_ticker,\n should_do_predictions):\n est_now.return_value = dt\n\n yield self.plugin.tick()\n\n if should_send_ticker:\n send_ticker.assert_called_once_with()\n else:\n assert send_ticker.mock_calls == []\n\n if should_do_predictions:\n sleep.assert_called_once_with(60)\n do_predictions.assert_called_once_with()\n else:\n assert sleep.mock_calls == []\n assert do_predictions.mock_calls == []\n\n @pytest.mark.parametrize(\"market_is_open\", [True, False])\n @patch.object(util, 'reactor', new_callable=Clock)\n @pytest_twisted.inlineCallbacks\n def test_do_predictions(self, mock_reactor, market_is_open):\n symbol = 'INX'\n base = 100.0\n\n user1 = 'user1'\n user2 = 'user2'\n prediction1 = 105.0\n prediction2 = 96.0\n\n actual = 95.0\n\n yield self.plugin.save_prediction(\n symbol,\n user1,\n base,\n prediction1,\n )\n yield self.plugin.save_prediction(\n symbol,\n user2,\n base,\n prediction2,\n )\n\n assert len(self.db['predictions']) == 1\n assert len(self.db['predictions'][symbol]) == 2\n\n response = make_global_quote_response(symbol, close=actual)\n\n with mock_api(response, fake_now=get_fake_now(market_is_open)):\n d = self.plugin.do_predictions()\n mock_reactor.advance(15)\n\n yield d\n\n assert len(self.mock_cardinal.sendMsg.mock_calls) == 3\n self.mock_cardinal.sendMsg.assert_called_with(\n self.channel,\n '{} had the closest guess for \\x02{}\\x02 out of {} predictions '\n 'with a prediction of {} (\\x0304{:.2f}%\\x03) '\n 'compared to the actual {} of {} (\\x0304{:.2f}%\\x03).'.format(\n user2,\n symbol,\n 2,\n prediction2,\n -4,\n 'open' if market_is_open else 'close',\n actual,\n -5))\n\n @patch.object(plugin, 'est_now')\n def test_send_prediction(self, mock_now):\n prediction = 105\n actual = 110\n base = 100\n nick = \"nick\"\n symbol = \"INX\"\n\n # Set the datetime to a known value so the message can be tested\n tz = pytz.timezone('America/New_York')\n mock_now.return_value = tz.localize(\n datetime.datetime(2020, 3, 20, 10, 50, 0, 0))\n\n prediction_ = {'when': '2020-03-20 10:50:00 EDT',\n 'prediction': prediction,\n 'base': base,\n }\n self.plugin.send_prediction(nick, symbol, prediction_, actual)\n\n message = (\"Prediction by nick for \\x02INX\\02: 105 (\\x03095.00%\\x03). \"\n \"Actual value at open: 110 (\\x030910.00%\\x03). \"\n \"Prediction set at 2020-03-20 10:50:00 EDT.\")\n self.mock_cardinal.sendMsg.assert_called_once_with('#test', message)\n\n @pytest.mark.skip(reason=\"Not written yet\")\n def test_check(self):\n pass\n\n @pytest.mark.parametrize(\"symbol,input_msg,output_msg,market_is_open\", [\n (\"INX\",\n \"!predict INX +5%\",\n \"Prediction by nick for \\x02INX\\x02 at market close: 105.00 (\\x03095.00%\\x03) \",\n True,\n ),\n (\"INX\",\n \"!predict INX -5%\",\n \"Prediction by nick for \\x02INX\\x02 at market close: 95.00 (\\x0304-5.00%\\x03) \",\n True,\n ),\n (\"INX\",\n \"!predict INX -5%\",\n \"Prediction by nick for \\x02INX\\x02 at market open: 95.00 (\\x0304-5.00%\\x03) \",\n False,\n ),\n # testing a few more formats of stock symbols\n (\"^RUT\",\n \"!predict ^RUT -5%\",\n \"Prediction by nick for \\x02^RUT\\x02 at market open: 95.00 (\\x0304-5.00%\\x03) \",\n False,\n ),\n (\"REE.MC\",\n \"!predict REE.MC -5%\",\n \"Prediction by nick for \\x02REE.MC\\x02 at market open: 95.00 (\\x0304-5.00%\\x03) \",\n False,\n ),\n (\"LON:HDLV\",\n \"!predict LON:HDLV -5%\",\n \"Prediction by nick for \\x02LON:HDLV\\x02 at market open: 95.00 (\\x0304-5.00%\\x03) \",\n False,\n ),\n ])\n @pytest_twisted.inlineCallbacks\n def test_predict(self,\n symbol,\n input_msg,\n output_msg,\n market_is_open):\n channel = \"#finance\"\n\n fake_now = get_fake_now(market_is_open=market_is_open)\n\n kwargs = {'previous_close': 100} if market_is_open else {'close': 100}\n response = make_global_quote_response(symbol, **kwargs)\n\n with mock_api(response, fake_now=fake_now):\n yield self.plugin.predict(self.mock_cardinal,\n user_info(\"nick\", \"user\", \"vhost\"),\n channel,\n input_msg)\n\n assert symbol in self.db['predictions']\n assert len(self.db['predictions'][symbol]) == 1\n\n self.mock_cardinal.sendMsg.assert_called_once_with(\n channel,\n output_msg)\n\n @pytest.mark.parametrize(\"message_pairs\", [\n ((\"!predict INX +5%\",\n \"Prediction by nick for \\x02INX\\x02 at market close: 105.00 (\\x03095.00%\\x03) \",\n ),\n (\"!predict INX -5%\",\n \"Prediction by nick for \\x02INX\\x02 at market close: 95.00 (\\x0304-5.00%\\x03) \"\n \"(replaces old prediction of 105.00 (\\x03095.00%\\x03) set at {})\"\n ),\n )\n ])\n @pytest_twisted.inlineCallbacks\n def test_predict_replace(self, message_pairs):\n channel = \"#finance\"\n symbol = 'INX'\n\n response = make_global_quote_response(symbol, previous_close=100)\n\n fake_now = get_fake_now()\n for input_msg, output_msg in message_pairs:\n with mock_api(response, fake_now):\n yield self.plugin.predict(self.mock_cardinal,\n user_info(\"nick\", \"user\", \"vhost\"),\n channel,\n input_msg)\n\n assert symbol in self.db['predictions']\n assert len(self.db['predictions'][symbol]) == 1\n\n self.mock_cardinal.sendMsg.assert_called_with(\n channel,\n output_msg.format(fake_now.strftime('%Y-%m-%d %H:%M:%S %Z'))\n if '{}' in output_msg else\n output_msg)\n\n @pytest.mark.parametrize(\"input_msg,output_msg\", [\n (\" !predict INX +5%\",\n \"Prediction by nick for \\x02INX\\x02 at market close: 105.00 (\\x03095.00%\\x03) \",\n ),\n (\" !predict INX -5%\",\n \"Prediction by nick for \\x02INX\\x02 at market close: 95.00 (\\x0304-5.00%\\x03) \",\n ),\n ])\n @pytest_twisted.inlineCallbacks\n def test_predict_relay_bot(self, input_msg, output_msg):\n symbol = 'INX'\n channel = \"#finance\"\n\n response = make_global_quote_response(symbol, previous_close=100)\n with mock_api(response):\n yield self.plugin.predict(self.mock_cardinal,\n user_info(\"relay.bot\", \"relay\", \"relay\"),\n channel,\n input_msg)\n\n assert symbol in self.db['predictions']\n assert len(self.db['predictions'][symbol]) == 1\n\n self.mock_cardinal.sendMsg.assert_called_once_with(\n channel,\n output_msg)\n\n @pytest.mark.parametrize(\"input_msg\", [\n \" !predict INX +5%\",\n \" !predict INX -5%\",\n ])\n @pytest_twisted.inlineCallbacks\n def test_predict_not_relay_bot(self, input_msg):\n channel = \"#finance\"\n\n yield self.plugin.predict(self.mock_cardinal,\n user_info(\"nick\", \"user\", \"vhost\"),\n channel,\n input_msg)\n\n assert len(self.db['predictions']) == 0\n assert self.mock_cardinal.sendMsg.mock_calls == []\n\n @pytest.mark.parametrize(\"user,message,value,expected\", [\n (\n user_info(\"whoami\", None, None),\n \"!predict INX 5%\",\n 100,\n (\"whoami\", \"INX\", 105, 100),\n ),\n (\n user_info(\"whoami\", None, None),\n \"!predict INX +5%\",\n 100,\n (\"whoami\", \"INX\", 105, 100),\n ),\n (\n user_info(\"whoami\", None, None),\n \"!predict INX -5%\",\n 100,\n (\"whoami\", \"INX\", 95, 100),\n ),\n (\n user_info(\"not.a.relay.bot\", None, None),\n \" !predict INX -5%\",\n 100,\n None,\n ),\n (\n user_info(\"relay.bot\", \"relay\", \"relay\"),\n \" !predict INX -5%\",\n 100,\n (\"whoami\", \"INX\", 95, 100),\n ),\n ])\n @pytest_twisted.inlineCallbacks\n def test_parse_prediction_open(\n self,\n user,\n message,\n value,\n expected,\n ):\n symbol = 'INX'\n\n response = make_global_quote_response(symbol, previous_close=value)\n with mock_api(response):\n result = yield self.plugin.parse_prediction(user, message)\n\n assert result == expected\n\n @pytest.mark.parametrize(\"user,message,value,expected\", [\n (\n user_info(\"whoami\", None, None),\n \"!predict INX 5%\",\n 100,\n (\"whoami\", \"INX\", 105, 100),\n ),\n (\n user_info(\"whoami\", None, None),\n \"!predict INX +5%\",\n 100,\n (\"whoami\", \"INX\", 105, 100),\n ),\n (\n user_info(\"whoami\", None, None),\n \"!predict INX -5%\",\n 100,\n (\"whoami\", \"INX\", 95, 100),\n ),\n (\n user_info(\"not.a.relay.bot\", None, None),\n \" !predict INX -5%\",\n 100,\n None,\n ),\n (\n user_info(\"relay.bot\", \"relay\", \"relay\"),\n \" !predict INX -5%\",\n 100,\n (\"whoami\", \"INX\", 95, 100),\n ),\n ])\n @pytest_twisted.inlineCallbacks\n def test_parse_prediction_close(\n self,\n user,\n message,\n value,\n expected,\n ):\n symbol = 'INX'\n\n response = make_global_quote_response(symbol, close=value)\n with mock_api(response, fake_now=get_fake_now(market_is_open=False)):\n result = yield self.plugin.parse_prediction(user, message)\n\n assert result == expected\n\n @patch.object(plugin, 'est_now')\n def test_save_prediction(self, mock_now):\n symbol = 'INX'\n nick = 'whoami'\n base = 100\n prediction = 105\n\n tz = pytz.timezone('America/New_York')\n mock_now.return_value = tz.localize(datetime.datetime(\n 2020,\n 3,\n 23,\n 12,\n 0,\n 0,\n ))\n self.plugin.save_prediction(\n symbol,\n nick,\n base,\n prediction,\n )\n\n assert symbol in self.db['predictions']\n assert nick in self.db['predictions'][symbol]\n actual = self.db['predictions'][symbol][nick]\n assert actual == {\n 'when': '2020-03-23 12:00:00 EDT',\n 'base': base,\n 'prediction': prediction,\n }\n\n @defer.inlineCallbacks\n def test_get_quote(self):\n symbol = 'INX'\n response = make_global_quote_response(symbol)\n r = response[\"Global Quote\"]\n\n expected = {\n 'symbol': symbol,\n 'open': float(r['02. open']),\n 'high': float(r['03. high']),\n 'low': float(r['04. low']),\n 'price': float(r['05. price']),\n 'volume': int(r['06. volume']),\n 'latest trading day': datetime.datetime.today().replace(\n hour=0, minute=0, second=0, microsecond=0),\n 'previous close': float(r['08. previous close']),\n 'change': float(r['09. change']),\n 'change percent': float(r['10. change percent'][:-1]),\n }\n\n with mock_api(response):\n result = yield self.plugin.get_quote(symbol)\n\n assert result == expected\n\n @defer.inlineCallbacks\n def test_get_daily(self):\n symbol = 'INX'\n last_open = 100.0\n last_close = 101.0\n previous_close = 102.0\n\n response = make_global_quote_response(symbol,\n open_=last_open,\n close=last_close,\n previous_close=previous_close,\n )\n\n expected = {\n 'symbol': symbol,\n 'close': last_close,\n 'open': last_open,\n 'previous close': previous_close,\n # this one is calculated by our make response function so it\n # doesn't really test anything anymore\n 'change': float(\n '{:.4f}'.format(get_delta(last_close, previous_close))),\n }\n\n with mock_api(response):\n result = yield self.plugin.get_daily(symbol)\n assert result == expected\n\n @defer.inlineCallbacks\n def test_get_time_series_daily(self):\n symbol = 'INX'\n\n response = make_time_series_daily_response(symbol)\n with mock_api(response):\n result = yield self.plugin.get_time_series_daily(symbol)\n\n for date in response['Time Series (Daily)']:\n assert date in result\n # verify prefix is stripped and values are floats\n for key in ('open', 'high', 'low', 'close', 'volume'):\n assert key in result[date]\n assert isinstance(result[date][key], float)\n\n @defer.inlineCallbacks\n def test_get_time_series_daily_bad_format(self):\n symbol = 'INX'\n\n response = {}\n with mock_api(response):\n with pytest.raises(KeyError):\n yield self.plugin.get_time_series_daily(symbol)\n\n @defer.inlineCallbacks\n def test_make_av_request(self):\n # Verify that this returns the response unmodified, and that it\n # properly calculates params\n function = 'TIME_SERIES_DAILY'\n symbol = 'INX'\n outputsize = 'compact'\n\n response = make_time_series_daily_response(symbol)\n with mock_api(response) as defer_mock:\n result = yield self.plugin.make_av_request(\n function,\n params={\n 'symbol': symbol,\n 'outputsize': outputsize,\n })\n\n assert result == response\n\n defer_mock.assert_called_once_with(\n plugin.requests.get,\n plugin.AV_API_URL,\n params={\n 'apikey': self.api_key,\n 'function': function,\n 'symbol': symbol,\n 'outputsize': outputsize,\n 'datatype': 'json',\n })\n\n @defer.inlineCallbacks\n def test_make_av_request_no_params(self):\n # This one is mostly just for coverage\n function = 'TIME_SERIES_DAILY'\n symbol = 'INX'\n\n response = make_time_series_daily_response(symbol)\n with mock_api(response) as defer_mock:\n result = yield self.plugin.make_av_request(function)\n\n assert result == response\n\n defer_mock.assert_called_once_with(\n plugin.requests.get,\n plugin.AV_API_URL,\n params={\n 'apikey': self.api_key,\n 'function': function,\n 'datatype': 'json',\n })\n\n @patch.object(util, 'reactor', new_callable=Clock)\n @defer.inlineCallbacks\n def test_make_av_request_retry_when_throttled(self, mock_reactor):\n # Verify that this returns the response unmodified, and that it\n # properly calculates params\n function = 'TIME_SERIES_DAILY'\n symbol = 'INX'\n outputsize = 'compact'\n\n response = make_time_series_daily_response(symbol)\n throttle_times = plugin.MAX_RETRIES - 1\n with mock_api(response, throttle_times=throttle_times) as defer_mock:\n d = self.plugin.make_av_request(\n function,\n params={\n 'symbol': symbol,\n 'outputsize': outputsize,\n })\n\n # loop through retries\n for _ in range(throttle_times):\n mock_reactor.advance(plugin.RETRY_WAIT)\n\n result = yield d\n\n assert result == response\n\n defer_mock.assert_has_calls([call(\n plugin.requests.get,\n plugin.AV_API_URL,\n params={\n 'apikey': self.api_key,\n 'function': function,\n 'symbol': symbol,\n 'outputsize': outputsize,\n 'datatype': 'json',\n })] * (throttle_times + 1))\n\n @patch.object(util, 'reactor', new_callable=Clock)\n @defer.inlineCallbacks\n def test_make_av_request_retry_on_exception(self, mock_reactor):\n # Verify that this returns the response unmodified, and that it\n # properly calculates params\n function = 'TIME_SERIES_DAILY'\n symbol = 'INX'\n outputsize = 'compact'\n\n response = make_time_series_daily_response(symbol)\n raise_times = plugin.MAX_RETRIES - 1\n with mock_api(response, raise_times=raise_times) as defer_mock:\n d = self.plugin.make_av_request(\n function,\n params={\n 'symbol': symbol,\n 'outputsize': outputsize,\n })\n\n # loop through retries\n for _ in range(raise_times):\n mock_reactor.advance(plugin.RETRY_WAIT)\n\n result = yield d\n\n assert result == response\n\n defer_mock.assert_has_calls([call(\n plugin.requests.get,\n plugin.AV_API_URL,\n params={\n 'apikey': self.api_key,\n 'function': function,\n 'symbol': symbol,\n 'outputsize': outputsize,\n 'datatype': 'json',\n })] * (raise_times + 1))\n\n @patch.object(util, 'reactor', new_callable=Clock)\n @defer.inlineCallbacks\n def test_make_av_request_give_up_after_max_retries(self, mock_reactor):\n # Verify that this returns the response unmodified, and that it\n # properly calculates params\n function = 'TIME_SERIES_DAILY'\n symbol = 'INX'\n outputsize = 'compact'\n\n response = make_time_series_daily_response(symbol)\n raise_times = plugin.MAX_RETRIES\n with mock_api(response, raise_times=raise_times) as defer_mock:\n d = self.plugin.make_av_request(\n function,\n params={\n 'symbol': symbol,\n 'outputsize': outputsize,\n })\n\n # loop through retries\n for _ in range(raise_times):\n mock_reactor.advance(plugin.RETRY_WAIT)\n\n with pytest.raises(Exception):\n yield d\n\n defer_mock.assert_has_calls([call(\n plugin.requests.get,\n plugin.AV_API_URL,\n params={\n 'apikey': self.api_key,\n 'function': function,\n 'symbol': symbol,\n 'outputsize': outputsize,\n 'datatype': 'json',\n })] * (raise_times))\n\n @patch.object(plugin, 'est_now')\n def test_market_is_open(self, mock_now):\n tz = pytz.timezone('America/New_York')\n\n # Nothing special about this time - it's a Thursday 7:49pm\n mock_now.return_value = tz.localize(datetime.datetime(\n 2020,\n 3,\n 19,\n 19,\n 49,\n 55,\n 0,\n ))\n assert plugin.market_is_open() is False\n\n # The market was open earlier though\n mock_now.return_value = tz.localize(datetime.datetime(\n 2020,\n 3,\n 19,\n 13,\n 49,\n 55,\n 0,\n ))\n assert plugin.market_is_open() is True\n\n # But not before 9:30am\n mock_now.return_value = tz.localize(datetime.datetime(\n 2020,\n 3,\n 19,\n 9,\n 29,\n 59,\n 0,\n ))\n assert plugin.market_is_open() is False\n\n # Or this weekend\n mock_now.return_value = tz.localize(datetime.datetime(\n 2020,\n 3,\n 14,\n 13,\n 49,\n 55,\n 0,\n ))\n assert plugin.market_is_open() is False\n","sub_path":"plugins/ticker/test_plugin.py","file_name":"test_plugin.py","file_ext":"py","file_size_in_byte":32360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"501893989","text":"from os import path\nfrom setuptools import setup\n\nHERE = path.abspath(path.dirname(__file__))\n\n# Get the long description from the README file\nwith open(path.join(HERE, 'README.md'), encoding='utf-8') as fp:\n long_description = fp.read()\n\n# Get the list of required packages\nwith open(path.join(HERE, 'requirements.txt'), encoding='utf-8') as fp:\n requirements = [req.rstrip() for req in fp.readlines()]\n\nsetup(\n name=\"imageai\",\n version='2.0.1',\n description='A flexible Computer Vision and Deep Learning library for applications and systems.',\n url=\"https://moses.specpal.science\",\n author='Moses Olafenwa and John Olafenwa',\n author_email='guymodscientist@gmail.com',\n license='MIT',\n packages=['imageai'],\n\n long_description=long_description,\n long_description_content_type='text/markdown',\n\n install_requires=requirements,\n\n zip_safe=False,\n\n # Classifiers help users find your project by categorizing it.\n # For a list of valid classifiers, see https://pypi.org/classifiers/\n classifiers=[ # Optional\n # How mature is this project? Common values are\n # 3 - Alpha ; 4 - Beta ; 5 - Production/Stable\n 'Development Status :: 5 - Production/Stable',\n 'License :: OSI Approved :: MIT License',\n\n # Indicate who your project is intended for\n 'Intended Audience :: Developers',\n 'Topic :: Scientific/Engineering :: Artificial Intelligence',\n 'Topic :: Scientific/Engineering :: Image Recognition',\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 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n ],\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"629242202","text":"# -*- coding: utf-8 -*-\nimport dataiku\nfrom dataiku.customrecipe import *\nimport pandas as pd, numpy as np\nfrom dataiku import pandasutils as pdu\nfrom google.cloud import translate\n\n#Get config\ncredential = get_input_names_for_role('folder_of_credentials')[0]\ncredential = dataiku.Folder(str(credential))\ncredentials_path = credential.get_path()+credential.list_paths_in_partition()[0]\ntranslate_client = translate.Client.from_service_account_json(credentials_path)\n\ncolumn_to_translate = get_recipe_config()[\"column_to_translate\"]\ntarget = get_recipe_config()[\"target_language\"]\ninput_data_path=get_input_names_for_role('dataset_to_translate')[0]\noutput_data_path = get_output_names_for_role('dataset_translated')[0]\n\n####################\n# INIT GOOGLE CLIENT\n####################\n# The target language\n\ndef translate_from_google(row,column_to_translate):\n text = row[column_to_translate]\n translation = translate_client.translate(\n text,\n target_language=target)\n row[column_to_translate+'_translated_'+target] = translation['translatedText'] \n row[column_to_translate+'_detectedSourceLanguage'] = translation['detectedSourceLanguage'] \n return row\n\n####################\n# MANIPULATE DATA\n####################\n\ninput_data= dataiku.Dataset(input_data_path)\ninput_data_df = input_data.get_dataframe()\n\ninput_data_df[column_to_translate+'_translated_'+target]=''\ninput_data_df[column_to_translate+'_detectedSourceLanguage']=''\n\ninput_data_df= input_data_df.apply(translate_from_google, column_to_translate=column_to_translate, axis=1)\ninput_data_translated_df = input_data_df\n\noutput_translated = dataiku.Dataset(output_data_path)\noutput_translated.write_with_schema(input_data_translated_df)","sub_path":"google-translate-plugin/custom-recipes/google-translate-plugin-python/recipe.py","file_name":"recipe.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"505061410","text":"from wxpy import *\nbot = Bot(cache_path=True)\nmy_friend = bot.friends().search('好友昵称')[10] #定位好友\nmy_friend.send('Hello!') #发送“Hello!”测试一下对接是否成功。\ngroup = bot.groups().search('群名')[10] #定位群\n\n#接入图灵api:需要去下述网址申请:\ntuling = Tuling(api_key='9d1d9486f8ca4663bc508afc9799f05e')\n\n# 使用图灵机器人自动与指定好友聊天\n@bot.register(my_friend)\ndef reply_my_friend(msg):\n tuling.do_reply(msg)\n","sub_path":"WechatRobot/tuling/wx7_tuling.py","file_name":"wx7_tuling.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"521177120","text":"#!/usr/bin/python\r\n\r\n#coding=utf-8\r\n\r\n\r\nimport cgitb\r\ncgitb.enable()\r\n\r\nimport cgi\r\nform = cgi.FieldStorage()\r\n\r\n\"\"\"\r\nexecfile('product_functions.py');\r\nform=CgiForm();\r\nform.fromUrl('http://localhost/cgi-bin/cgi_main.py?workspace=food-groceries');\r\nform.fromUrl('http://localhost/cgi-bin/cgi_main.py?workspace=blog-electronics');\r\nform.fromUrl('http://localhost/cgi-bin/cgi_main.py');\r\nform.fromUrl('http://localhost/cgi-bin/cgi_main.py?topic_id=92b93920d6a4007084b0ef87fc8d44a7%2D0');\r\n\r\n\"\"\"\r\nworkspace=form.getvalue('workspace');\r\nif workspace==None: workspace=\"\";\r\n\r\n\r\nimport os; \r\nPATH_CGI_DIR=os.getcwd()+\"/\";\r\nif PATH_CGI_DIR.find('cgi-bin/')<0: PATH_CGI_DIR+=\"cgi-bin/\";\r\n\r\nexecfile(PATH_CGI_DIR+\"load_data.py\");\r\n\r\n\r\nimport time;\r\nfrom datetime import datetime;\r\nworkspaces=[('blog-electronics','Home Electronics'), \r\n\t\t\t('food-groceries', 'Food & Groceries'), \r\n\t\t\t('health-vitamin', 'Health & Vitamins'),\r\n\t\t\t('music-blog', 'Book/Music/Video'),\r\n\t\t\t('health-beauty', 'Health & Beauty'),\r\n\t\t\t];\r\n\r\ntitle=\"Trending Topics\"\r\n\r\n\r\ntopic_id=form.getvalue('topic_id'); \r\nshow_multiple_stories=False;\r\n\r\nnextPageUrl='';\r\nif workspace:\r\n\tnextPageUrl+='workspace='+workspace;\r\n\r\ncurPage=1;\r\ntry:\r\n\tcurPage=int(form.getvalue('page'));\r\nexcept:\r\n\tpass;\r\n\r\nperPage=50; #the max number of entries per page.\r\nmaxCount=0; #the max number of entries in solr, in order to do the pagination.\r\ntotalPage=0; #total page.\r\npageStartDate='';\r\npageEndDate='';\r\n\r\nentries=[];\r\ntop_products=defaultdict(list); \r\nif topic_id: \r\n\t# ------------ show one topics ------------\r\n\tp,s=solr_query_var({'id':topic_id, }, perpage=50, page=0, to_print=0);\r\n\tif p:\r\n\t\tworkspace=p[0]['category'].split('__')[0];\r\n\t\tcategory_id=p[0]['category'];\r\n\t\tprodname=p[0]['name'];\r\n\t\tfor p1 in p: \r\n\t\t\tentries.append(decode_post_data(p1['data_t']));\r\n\t\t\tentries[-1]['id']=p1['id'];\r\n\t\t\tif 'date_dt' in p1.keys(): \r\n\t\t\t\tentries[-1]['date_dt']=strptime(p1['date_dt'], '%Y-%m-%dT%H:%M:%SZ');\r\n\t\t\telse: #for old data without date_dt, use updated date\r\n\t\t\t\tentries[-1]['date_dt']=entries[-1]['date'];\r\n\t\tif show_multiple_stories: \r\n\t\t\tp,s=solr_query_var({'category':category_id, 'name':prodname}, perpage=50, page=0, to_print=0);\r\n\t\t\tfor p1 in p: \r\n\t\t\t\tentries.append(decode_post_data(p1['data_t']));\r\n\t\t\t\tentries[-1]['id']=p1['id'];\r\nelse:\r\n\t# ------------ list all topics ------------\r\n\tfor w,n in workspaces: \r\n\t\tif not workspace or workspace == w: \r\n\t\t\tp,s=solr_query_var({'category':w+'__top_products', }, perpage=50, page=curPage-1, to_print=0, params='sort=date_dt+desc');\r\n\t\t\tif len(p):\r\n\t\t\t\tpageStartDate=p[0]['date_s'];\r\n\t\t\t\tpageEndDate=p[-1]['date_s'];\r\n\t\t\tif int(s['response']['numFound']) > maxCount:\r\n\t\t\t\tmaxCount = int(s['response']['numFound']);\r\n\t\t\tfor p1 in p: \r\n\t\t\t\ttop_products[w].append(decode_post_data(p1['data_t']));\r\n\t\t\t\ttop_products[w][-1]['id']=p1['id'];\r\n\t\t\t\tif 'date_dt' in p1.keys(): \r\n\t\t\t\t\ttop_products[w][-1]['date_dt']=strptime(p1['date_dt'], '%Y-%m-%dT%H:%M:%SZ');\r\n\t\t\t\telse: #for old data without date_dt, use updated date\r\n\t\t\t\t\ttop_products[w][-1]['date_dt']=top_products[w][-1]['date'];\r\n\t#\r\n\tblack_list=['doubleclick.net', 'logo', '/ad/', '125x125'];\r\n\timg_min_size=200;\r\n\tadded_entries=[];\r\n\tfor w,n in workspaces:\r\n\t\tfor t in top_products[w]:\r\n\t\t\tif t['product'].lower() not in added_entries and ( \\\r\n\t\t\t\t\t(t['type_image']['imgwidth'] and int(t['type_image']['imgwidth'])>=img_min_size and t['type_image']['imgheight'] and int(t['type_image']['imgheight'])>=img_min_size) \\\r\n\t\t\t\t\tor w in ['music-blog', 'helium-entertainment', ]): \r\n\t\t\t\tif not sum([t['type_image']['img'].find(k)>=0 for k in black_list]) and t['type_image']['img'][-4:].lower() not in ['.gif',]:\r\n\t\t\t\t\tadded_entries.append(t['product'].lower()); \r\n\t\t\t\t\tentries.append(t); \r\n\r\nentries=sorted([k for k in entries if k['date_dt'] and isinstance(k['date_dt'],datetime) ], key=lambda k: k['date_dt'], reverse=True);\r\n#entries=sorted(entries, key=lambda k: k['date_dt'], reverse=True);\r\n\r\n\r\n\r\n# ------------ html page head -----------------\r\nprint(\"content-type: text/html\\n\\n\"); \r\n\r\nprint(\"\"\"\r\n\r\n\r\n\r\n\t \r\n\t \r\n\t\r\n\t \r\n\t\t\r\n\t\"\"\"+title+\"\"\" \r\n\t\r\n\t \r\n\t \r\n\r\n\t\r\n\t\r\n \t\r\n\t\r\n \r\n\r\n\r\n\t\r\n\t\r\n\r\n\r\n\t\t \r\n\t\r\n\"\"\");\r\n\r\n# ----------------------pagination area--------------------------------\r\nif topic_id:\r\n\tpass;\r\nelse:\r\n\tif(curPage<=0):\r\n\t\tcurPage=1;\r\n\t\t\r\n\tif maxCount % perPage==0:\r\n\t\ttotalPage = maxCount/perPage;\r\n\telse:\r\n\t\ttotalPage = maxCount/perPage + 1;\r\n\t\t\r\n\tif curPage>totalPage:\r\n\t\tcurPage=totalPage;\r\n\t\t\r\n\ttsp = time.strptime(pageStartDate, '%Y-%m-%d')\r\n\tdate_object=datetime(tsp[0],tsp[1],tsp[2]);\r\n\tprint(\"\"\"\r\n\t\r\n\t\"\"\");\r\n#----------------end of pagination-------------------------------------------\r\n\t\r\n\t\r\n\r\n# ------------ page content -----------------\r\n\r\nprint(\"\"\"\r\n\t\t
\r\n\t\t\t
\r\n\t\t\t
\r\n\t\"\"\");\r\n\r\nif topic_id: \r\n\t# ------------ show one topics ------------\r\n\tsummarizer=text_summarizer();\r\n\tshown_articles=[];\r\n\tfor i, entry in enumerate(entries): \r\n\t\tnew_articles=[headline['article']['id'] for headline in entry['headlines'][0:2] if headline['article']['id'] not in shown_articles];\r\n\t\tif not new_articles: continue; \r\n\t\tshown_articles+=new_articles;\r\n\t\t#\r\n\t\tprint('
'); \r\n\t\tprint(\"\"\"
\");\r\n\t\t#\r\n\t\t# --- show some headline titles ---\r\n\t\thtml=\"\"\"
\r\n\t\t\t%(date)s \r\n\t\t\t\"\"\"%{'date':entry['date_dt'].strftime('%Y-%m-%d') };\r\n\t\tfor headline in entry['headlines'][0:2]: \r\n\t\t\tarticle=headline['article'];\r\n\t\t\tsentences=[];\r\n\t\t\tif headline['r'] and 'isentence0' in headline['r'][0].keys(): \r\n\t\t\t\tfor r in headline['r']: r['isentence']=r['isentence0']; \r\n\t\t\t\tblog_text2=[];\r\n\t\t\t\tpost,s=solr_query_var({'id':article['id']}); \r\n\t\t\t\tif post: \r\n\t\t\t\t\tpost_data1=decode_post_data(post[0]['data_t']); \r\n\t\t\t\t\tblog_text2=[' '+' '.join([p[0] for p in pos])+' ' for pos in post_data1['blog_pos']];\r\n\t\t\t\tsentences=summarizer.get_ranked_article_sentences(blog_text2, headline['r'], 100);\r\n\t\t\t#\r\n\t\t\thtml+=\"\"\"
\r\n\t\t\t\t\t\t\t
%(story)s \r\n\t\t\t\t\t
\r\n\t\t\t\t\t\t—
%(title)s : \r\n\t\t\t\t\t\t
%(source)s \r\n\t\t\t\t\t\t
%(date)s \r\n\t\t\t\t\t
\r\n\t\t\t\t\t
\r\n\t\t\t\t\t\"\"\"%{\r\n\t\t\t\t'story': '
'.join(sentences[0:2]),\r\n\t\t\t\t'source': article['source'],\r\n\t\t\t\t'title': escape_html(article['title']), \r\n\t\t\t\t'url': article['url'], \r\n\t\t\t\t'date': article['date'].strftime(\"%Y-%m-%d\")\r\n\t\t\t\t};\r\n\t\thtml+=\"
\";\r\n\t\tprint(html);\r\n\t\t#\r\n\t\tprint(\"
\");\r\n\t#\r\nelse: #no topic_id, list trending topics\r\n\t# ------------ list trending topics ------------\r\n\tfor i, entry in enumerate(entries): \r\n\t\tif i%4==0: \r\n\t\t\tif i==0: \r\n\t\t\t\tprint('
'); \r\n\t\t\telse:\r\n\t\t\t\tprint('
');\r\n\t\tprint(\"\"\"
\r\n\t\t\t
\r\n\t\t\t \r\n\t\t\t\t\"\"\"+escape_html(entry['product'])+\"\"\" \r\n\t\t\t
\r\n\t\t\t\r\n\t\t\t\"\"\");\r\n\t\tif 'type_image' in entry.keys() and entry['type_image']['img']: \r\n\t\t\tprint(\"
\"); \r\n\t\telse:\r\n\t\t\twords=entry['summary'].split(); \r\n\t\t\tif len(words)>7: words=words[:7]+['...']; \r\n\t\t\tprint(\"
%s \"%' '.join(words)); \r\n\t\tprint(\"\"\"\r\n\t\t\t
\r\n\t\t\t \r\n\t\t\t\"\"\");\r\n\t\t#product recommendation\r\n\t\tif 'prod_tags' in entry.keys() and entry['prod_tags']:\r\n\t\t\tif i%4==3:\r\n\t\t\t\tprint('
');\r\n\t\t\telse:\r\n\t\t\t\tprint('
');\r\n\t\t\tF_name, F_subcat, F_url, F_img, F_price, F_price0, F_seller=range(7);\r\n\t\t\tprint('
');\r\n\t\t\tfor tag in entry['prod_tags'][:4]:\r\n\t\t\t\tif tag['products']:\r\n\t\t\t\t\tprint(' %(price)s ' %{\r\n\t\t\t\t\t\t\t\t'url': tag['products'][0][F_url], \r\n\t\t\t\t\t\t\t\t'name': tag['products'][0][F_name], \r\n\t\t\t\t\t\t\t\t'price': tag['products'][0][F_price], \r\n\t\t\t\t\t\t\t\t'img': tag['products'][0][F_img],\r\n\t\t\t\t\t\t\t} );\r\n\t\t\tprint('
');\r\n\t\t\tprint('
'); \r\n\t\tprint(\"\"\"\r\n\t\t\t
\r\n\t\t\t\"\"\");\r\n\t#\r\n\tprint('
');\r\n\r\nprint(\"\"\"
\r\n\t
\r\n\t
\r\n\t
\r\n\t
\r\n\t\"\"\");\r\n\t\r\n\r\n# ------------ page bottom -----------------\r\n\r\nprint(\"\"\"\r\n\t
\r\n\t\r\n\t\r\n\t\"\"\"); \r\n\r\n","sub_path":"cgi-bin/cgi_main.py","file_name":"cgi_main.py","file_ext":"py","file_size_in_byte":13658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"455128340","text":"from functools import partial\nimport numpy as np\nimport collections\nfrom scipy.stats import binom_test\nimport copy\nimport math\nimport os\n\nimport ray\nfrom ray import tune\nfrom ray.tune.logger import pretty_print\nfrom ray.rllib.agents.trainer import with_common_config\nfrom ray.rllib.execution.rollout_ops import ParallelRollouts, ConcatBatches\nfrom ray.rllib.execution.train_ops import TrainOneStep\nfrom ray.rllib.execution.metric_ops import StandardMetricsReporting\nfrom ray.rllib.agents.trainer_template import build_trainer\nfrom ray.rllib.optimizers import SyncSamplesOptimizer\nfrom ray.rllib.rollout import DefaultMapping\nfrom ray.rllib.agents.callbacks import DefaultCallbacks\nfrom ray.rllib.evaluation.worker_set import WorkerSet\nfrom ray.rllib.evaluation.metrics import collect_episodes\nfrom ray.rllib.env import MultiAgentEnv\nfrom ray.rllib.utils.space_utils import flatten_to_single_ndarray\nfrom ray.tune.registry import get_trainable_cls\n\nfrom RLC.capture_chess_rllib.policies import PolicyGradient, PolicyRandom\nfrom RLC.capture_chess_rllib.environment import CaptureChessEnv\nfrom RLC.utils import dotdict\n\n# Define a trainer using our own defined policy.\n# The trainer will run multiple workers and update the policy given by the ruling underneath.\n# (this is the standard PG as implemented in RLLib)\n# Evaluation of a policy can be done with the function rollout in rollout.py.\n# https://github.com/ray-project/ray/blob/master/rllib/examples/rollout_worker_custom_workflow.py\n\n\ndef execution_plan(workers, config):\n # enable with \"use_exec_api\": True.\n # Collects experiences in parallel from multiple RolloutWorker actors.\n rollouts = ParallelRollouts(workers, mode=\"bulk_sync\")\n\n # Combine experiences batches until we hit `train_batch_size` in size.\n # Then, train the policy on those experiences and update the workers.\n train_op = rollouts \\\n .combine(ConcatBatches(\n min_batch_size=config[\"train_batch_size\"])) \\\n .for_each(TrainOneStep(workers))\n\n # Add on the standard episode reward, etc. metrics reporting. This returns\n # a LocalIterator[metrics_dict] representing metrics for each train step.\n return StandardMetricsReporting(train_op, workers, config)\n\n\nclass MyCallbacks(DefaultCallbacks):\n def on_episode_end(self, worker, base_env,\n policies, episode,\n **kwargs):\n episode.custom_metrics[\"winner\"] = base_env.get_unwrapped()[\n 0].determine_winner()\n\n\n# Because we need to set the setting to True on default, we will override the parameters.\nDEFAULT_CONFIG = with_common_config({\n # No remote workers by default.\n \"num_workers\": 0,\n # Learning rate.\n \"lr\": 0.0004,\n # Use the execution plan API instead of policy optimizers.\n \"use_exec_api\": True,\n \"callbacks\": MyCallbacks,\n})\n\n# Define the trainer.\n# From the _setup() function in trainer.py, we can see how the env is setup.\n# The main function is _train() in trainer_template.py.\n# Here we can see how the execution_plan or other training is called.\nPGTrainer = build_trainer(\n name=\"PolicyGradientTrainer\",\n default_config=DEFAULT_CONFIG,\n default_policy=PolicyGradient,\n execution_plan=execution_plan,\n)\n\n\nclass InfoNumberRounds():\n def __init__(self, min_, max_, step):\n self.min = min_\n self.max = max_\n self.step = step\n\n\ndef self_play_workflow(config):\n \"\"\"\n Expects in config:\n checkpoint\n checkpoint to load from (None if new)\n trainer\n trainer to use\n model\n model to use in learning\n percentage_equal: float\n The maximal allowed percentage that equal opponents get game results. (see binomial test)\n lr_schedule: List of lr\n Learning rates to use. Will use first to last and update each time the model gets worse.\n training_rounds\n Rounds of training\n evaluation_rounds\n Rounds of evaluation\n\n 1. Generate a large batch of self-play games.\n 2. Train.\n 3. Test the updated bot against the previous version.\n 4. If the bot is measurably stronger, switch to this new version.\n 5. If the bot is about the same strength, generate more games and train again.\n 6. If the bot gets significantly weaker, adjust the optimizer settings and retrain.\n \"\"\"\n ##########################################\n # Set config of trainer and evaluators\n ##########################################\n check_dir = 'logs'\n log_file = 'logs/logs.txt'\n if os.path.exists(log_file):\n os.remove(log_file)\n\n if config.get(\"evaluation_num_episodes\", None) is None:\n config[\"evaluation_num_episodes\"] = 1\n trainer_fn = get_trainable_cls(config[\"trainer\"])\n lr_idx = 0\n\n def select_policy_train(agent_id):\n if agent_id == \"player1\":\n return np.random.choice([\"learning_white\", \"previous_white\", \"random\"], 1,\n p=[.6, .3, .1])[0]\n else:\n return np.random.choice([\"learning_black\", \"previous_black\", \"random\"], 1,\n p=[.6, .3, .1])[0]\n\n def select_policy_eval(learning_player, agent_id):\n if learning_player == \"player1\":\n if agent_id == \"player1\":\n return \"learning_white\"\n else:\n return \"previous_black\"\n else:\n if agent_id == \"player2\":\n return \"learning_black\"\n else:\n return \"previous_white\"\n\n trainer_config = copy.deepcopy(config)\n # remove self-play parameters\n trainer_config.pop(\"trainer\")\n trainer_config.pop(\"percentage_equal\")\n trainer_config.pop(\"model\")\n trainer_config.pop(\"training_rounds\")\n trainer_config.pop(\"evaluation_rounds\")\n trainer_config.pop(\"checkpoint\", None)\n trainer_config.pop(\"lr_schedule\", None)\n trainer_config.pop(\"evaluation_interval\", None)\n\n trainer_config[\"lr\"] = config[\"lr_schedule\"][lr_idx]\n trainer_config[\"multiagent\"] = {\n \"policies_to_train\": [\"learning_white\", \"learning_black\"],\n \"policies\": {\n \"random\": (PolicyRandom, config[\"env\"].observation_space, config[\"env\"].action_space,\n {}),\n \"learning_white\": (None, config[\"env\"].observation_space, config[\"env\"].action_space,\n {\n \"model\": config[\"model\"]\n }),\n \"learning_black\": (None, config[\"env\"].observation_space, config[\"env\"].action_space,\n {\n \"model\": config[\"model\"]\n }),\n \"previous_white\": (None, config[\"env\"].observation_space, config[\"env\"].action_space,\n {\n \"model\": config[\"model\"]\n }),\n \"previous_black\": (None, config[\"env\"].observation_space, config[\"env\"].action_space,\n {\n \"model\": config[\"model\"]\n }),\n },\n \"policy_mapping_fn\": select_policy_train,\n }\n trainer_config[\"train_batch_size\"] = 2 * config[\"train_batch_size\"]\n\n eval_config_player1 = copy.deepcopy(trainer_config)\n eval_config_player1[\"multiagent\"][\"policy_mapping_fn\"] = partial(\n select_policy_eval, \"player1\")\n eval_config_player1[\"multiagent\"][\"policies_to_train\"] = []\n\n eval_config_player2 = copy.deepcopy(trainer_config)\n eval_config_player2[\"multiagent\"][\"policy_mapping_fn\"] = partial(\n select_policy_eval, \"player2\")\n eval_config_player2[\"multiagent\"][\"policies_to_train\"] = []\n\n ##########################################\n # Run train / evaluation rounds\n ##########################################\n\n def update_for_next_loop(total_rounds, rounds, reset=False):\n done = False\n if reset:\n next_num_rounds = rounds.min\n else:\n if (total_rounds >= rounds.max):\n done = True\n next_num_rounds = rounds.step\n\n return done, next_num_rounds\n\n ray.init()\n\n trainer = trainer_fn(\n env=trainer_config[\"env\"], config=trainer_config)\n evaluator_player1 = trainer_fn(\n env=eval_config_player1[\"env\"], config=eval_config_player1)\n evaluator_player2 = trainer_fn(\n env=eval_config_player1[\"env\"], config=eval_config_player2)\n\n total_rounds_training = 0\n done, training_rounds = update_for_next_loop(\n total_rounds_training, config[\"training_rounds\"], True)\n prev_it_state = config.get(\"checkpoint\", None)\n prev_state = prev_it_state\n while not done:\n ##########################################\n # Train\n ##########################################\n try:\n if prev_it_state is not None:\n trainer.restore(prev_it_state)\n for _ in range(training_rounds):\n trainer.train()\n state = trainer.save(check_dir)\n # trainer.stop()\n\n total_rounds_training += training_rounds\n except Exception:\n trainer.stop()\n with open(log_file, 'a') as f:\n f.write(\"Model failed, updating optimizer\\n\")\n lr_idx += 1\n if lr_idx < len(config[\"lr_schedule\"]):\n trainer_config[\"lr\"] = config[\"lr_schedule\"][lr_idx]\n trainer = trainer_fn(\n env=trainer_config[\"env\"], config=trainer_config)\n total_rounds_training = 0\n done, training_rounds = update_for_next_loop(\n total_rounds_training, config[\"training_rounds\"], True)\n prev_it_state = prev_state\n else:\n done = True\n continue # try again.\n\n ##########################################\n # Evaluate\n ##########################################\n try:\n total_eval_rounds = 0\n comparison_wrt_equal = 1\n eval_results1 = []\n eval_results2 = []\n # maximal evaluation rounds determined by training, does not make sense to evaluate more than training rounds.\n eval_info = InfoNumberRounds(config[\"evaluation_rounds\"].min, min(\n config[\"evaluation_rounds\"].max, total_rounds_training), config[\"evaluation_rounds\"].step)\n done_eval, eval_rounds = update_for_next_loop(\n total_eval_rounds, eval_info, True)\n while not done_eval:\n num_episodes = eval_rounds * config[\"evaluation_num_episodes\"]\n\n evaluator_player1.restore(state)\n eval_results1.extend(own_evaluation(\n evaluator_player1, eval_rounds))\n num_pos = sum(x == 1 for x in eval_results1)\n num_neg = sum(x == -1 for x in eval_results1)\n comparison_wrt_equal1 = binom_test(\n num_pos, num_pos + num_neg, 0.5)\n with open(log_file, 'a') as f:\n f.write(\n f'results1: trained agent wins: {num_pos} previous agent wins: {num_neg} remises: {sum(x == 0 for x in eval_results1)} \\n')\n f.write(\n f'chance result for equal opponents: {comparison_wrt_equal1} \\n')\n\n evaluator_player2.restore(state)\n eval_results2.extend(own_evaluation(\n evaluator_player2, eval_rounds))\n num_pos = sum(x == 1 for x in eval_results2)\n num_neg = sum(x == -1 for x in eval_results2)\n comparison_wrt_equal2 = binom_test(\n num_neg, num_pos + num_neg, 0.5)\n with open(log_file, 'a') as f:\n f.write(\n f'results2: trained agent wins: {num_neg} previous agent wins: {num_pos} remises: {sum(x == 0 for x in eval_results2)} \\n')\n f.write(\n f'chance result for equal opponents: {comparison_wrt_equal2} \\n')\n\n total_eval_rounds += eval_rounds\n\n done_eval, eval_rounds = update_for_next_loop(\n total_eval_rounds, eval_info)\n if config[\"percentage_equal\"] > comparison_wrt_equal1 or config[\"percentage_equal\"] > comparison_wrt_equal2:\n # one of players improved\n done_eval = True\n except Exception:\n with open(log_file, 'a') as f:\n f.write(\"Model failed, need to update optimizer\\n\")\n # trigger update optimizer\n comparison_wrt_equal1 = 0\n comparison_wrt_equal2 = 0\n eval_results1 = [-1]\n eval_results2 = [1]\n\n ##########################################\n # Update policy\n ##########################################\n\n if config[\"percentage_equal\"] > comparison_wrt_equal1 or config[\"percentage_equal\"] > comparison_wrt_equal2:\n # results differ enough\n if sum(x == 1 for x in eval_results1) > sum(x == -1 for x in eval_results1) and sum(x == -1 for x in eval_results2) > sum(x == 1 for x in eval_results2):\n with open(log_file, 'a') as f:\n f.write(\"Model improved\\n\")\n total_rounds_training = 0\n done, training_rounds = update_for_next_loop(\n total_rounds_training, config[\"training_rounds\"], True)\n # reupdate previous\n key_previous_val_learning_white = {}\n for (k, v), (k2, v2) in zip(trainer.get_policy(\"previous_white\").get_weights().items(),\n trainer.get_policy(\"learning_white\").get_weights().items()):\n key_previous_val_learning_white[k] = v2\n key_previous_val_learning_black = {}\n for (k, v), (k2, v2) in zip(trainer.get_policy(\"previous_black\").get_weights().items(),\n trainer.get_policy(\"learning_black\").get_weights().items()):\n key_previous_val_learning_black[k] = v2\n # set weights\n trainer.set_weights({\"previous_white\": key_previous_val_learning_white,\n \"previous_black\": key_previous_val_learning_black,\n # no change\n \"learning_white\": trainer.get_policy(\"learning_white\").get_weights(),\n \"learning_black\": trainer.get_policy(\"learning_black\").get_weights(),\n })\n if prev_state is not None:\n trainer.delete_checkpoint(prev_state)\n trainer.delete_checkpoint(state)\n\n prev_it_state = trainer.save(check_dir)\n prev_state = prev_it_state\n elif sum(x == 1 for x in eval_results1) < sum(x == -1 for x in eval_results1) and sum(x == -1 for x in eval_results2) < sum(x == 1 for x in eval_results2):\n with open(log_file, 'a') as f:\n f.write(\"Model got worse, updating optimizer\\n\")\n trainer.stop()\n lr_idx += 1\n if lr_idx < len(config[\"lr_schedule\"]):\n trainer_config[\"lr\"] = config[\"lr_schedule\"][lr_idx]\n trainer = trainer_fn(\n env=trainer_config[\"env\"], config=trainer_config)\n total_rounds_training = 0\n done, training_rounds = update_for_next_loop(\n total_rounds_training, config[\"training_rounds\"], True)\n prev_it_state = prev_state\n else:\n done = True\n else:\n with open(log_file, 'a') as f:\n f.write(\n \"One player improved one got worse, trying more learning iterations.\\n\")\n done, training_rounds = update_for_next_loop(\n total_rounds_training, config[\"training_rounds\"])\n prev_it_state = state\n else:\n with open(log_file, 'a') as f:\n f.write(\"Unable to evaluate, trying more learning iterations.\\n\")\n done, training_rounds = update_for_next_loop(\n total_rounds_training, config[\"training_rounds\"])\n prev_it_state = state\n\n trainer.restore(prev_it_state)\n trainer.save()\n print(\"Checkpoint and trainer saved at: \", trainer.logdir)\n with open(log_file, 'a') as f:\n f.write(f'Checkpoint and trainer saved at: {trainer.logdir} \\n')\n\n\ndef own_rollout(agent,\n num_episodes):\n results = []\n if hasattr(agent, \"workers\") and isinstance(agent.workers, WorkerSet):\n env = agent.workers.local_worker().env\n multiagent = isinstance(env, MultiAgentEnv)\n if agent.workers.local_worker().multiagent:\n policy_agent_mapping = agent.config[\"multiagent\"][\n \"policy_mapping_fn\"]\n\n policy_map = agent.workers.local_worker().policy_map\n state_init = {p: m.get_initial_state() for p, m in policy_map.items()}\n else:\n raise NotImplementedError(\"Multi-Agent only\")\n\n action_init = {\n p: flatten_to_single_ndarray(m.action_space.sample())\n for p, m in policy_map.items()\n }\n\n episodes = 0\n while episodes < num_episodes:\n mapping_cache = {} # in case policy_agent_mapping is stochastic\n obs = env.reset()\n prev_actions = DefaultMapping(\n lambda agent_id: action_init[mapping_cache[agent_id]])\n prev_rewards = collections.defaultdict(lambda: 0.)\n done = False\n while not done and (episodes < num_episodes):\n action_dict = {}\n for agent_id, a_obs in obs.items():\n if a_obs is not None:\n policy_id = mapping_cache.setdefault(\n agent_id, policy_agent_mapping(agent_id))\n\n a_action = agent.compute_action(\n a_obs,\n prev_action=prev_actions[agent_id],\n prev_reward=prev_rewards[agent_id],\n policy_id=policy_id)\n a_action = flatten_to_single_ndarray(a_action)\n action_dict[agent_id] = a_action\n prev_actions[agent_id] = a_action\n\n action = action_dict\n next_obs, reward, done, info = env.step(action)\n done = done[\"__all__\"]\n\n # update\n for agent_id, r in reward.items():\n prev_rewards[agent_id] = r\n obs = next_obs\n\n if done:\n episodes += 1\n # specific function for alternate game.\n results.append(env.determine_winner())\n\n return results\n\n\ndef own_evaluation(agent, num_rounds):\n results = []\n num_episodes = num_rounds * agent.config[\"evaluation_num_episodes\"]\n if agent.config[\"num_workers\"] == 0:\n for _ in range(num_episodes):\n agent.evaluation_workers.local_worker().sample()\n else:\n while len(results) < num_episodes:\n # Calling .sample() runs exactly one episode per worker due to how the\n # eval workers are configured.\n ray.get([\n w.sample.remote()\n for w in agent.workers.remote_workers()\n ])\n\n episodes, _ = collect_episodes(None,\n agent.workers.remote_workers(),\n [])\n\n for episode in episodes:\n for key, winner in episode.custom_metrics.copy().items():\n results.append(winner)\n\n return results[:num_episodes]\n","sub_path":"RLC/capture_chess_rllib/game_internal.py","file_name":"game_internal.py","file_ext":"py","file_size_in_byte":19784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"376053311","text":"from typing import List\nfrom collections import Counter\n\nclass Solution:\n # https://leetcode.com/problems/permutations-ii/solution/\n # Backtracking with Groups of Numbers\n def permuteUnique(self, nums: List[int]) -> List[List[int]]:\n ans = []\n self.helper(nums, [], Counter(nums), ans)\n return ans\n\n def helper(self, nums, element, counter, ans):\n if len(element) == len(nums):\n ans.append(element[::])\n return\n for num in counter:\n if counter[num] > 0:\n counter[num] -= 1\n element.append(num)\n self.helper(nums, element, counter, ans)\n element.pop()\n counter[num] += 1\n\n def permuteUnique2(self, nums: List[int]) -> List[List[int]]:\n results = []\n\n def backtrack(comb, counter):\n if len(comb) == len(nums):\n # make a deep copy of the resulting permutation,\n # since the permutation would be backtracked later.\n results.append(list(comb))\n return\n\n for num in counter:\n if counter[num] > 0:\n # add this number into the current combination\n comb.append(num)\n counter[num] -= 1\n # continue the exploration\n backtrack(comb, counter)\n # revert the choice for the next exploration\n comb.pop()\n counter[num] += 1\n\n backtrack([], Counter(nums))\n\n return results\n\n\nif __name__ == '__main__':\n solution = Solution()\n n = [1, 2, 1]\n result = solution.permuteUnique(n)\n print(result)\n\n result = solution.permuteUnique2(n)\n print(result)","sub_path":"Backtracking/47-PermutationsII.py","file_name":"47-PermutationsII.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"580329585","text":"\nimport requests\nimport json\n# requestlist = requests.get('https://github.com/PyCQA/bandit')\n\n# GET /repos/:owner/:repo/pulls\n\n\n\n# GET /repos/????/????/pulls\n\n# owner = \n# repo = \n\nrequestdata = requests.get('https://api.github.com/repos/PyCQA/bandit/pulls?state=open')\n\njsondata = (requestdata.text)\n\n#print(jsondata)\n\nloadeddata = json.loads(jsondata)\n\n\nfor id in loadeddata:\n print(id['title'])\n print(id['created_at']+' '+id['user']['login'])\n print(id['url'])\n print()\n","sub_path":"HackerRank Java/src/PullRequestList.py","file_name":"PullRequestList.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"327578316","text":"import tweepy \r\nimport yfinance as yf \r\nimport os \r\n \r\n# Authenticate to Twitter \r\n# Use real key values instead of placeholders \r\napi_key = \"your_api_key\" \r\napi_secret_key =\"your_api_secret_key\" \r\naccess_token = \"your_access_token\" \r\naccess_token_secret= \"your_secret_access_token\" \r\n \r\n# Call the variables using tweepy \r\nauth = tweepy.OAuthHandler(api_key, api_secret_key) \r\nauth.set_access_token(access_token, access_token_secret) \r\n \r\n# Retrieve the stock data \r\napi = tweepy.API(auth) \r\ndata = yf.download(tickers='JW-A', period='1D', interval='1D') \r\n \r\nrow = data.iloc[0] \r\nstatus = \"The open price of Wiley's stock is %s. The close price of Wiley's stock is %s. Volume recorded is %s.\" %(str(round(row['Open'], 2)),str(round(row['Close'], 2)),str(int(row['Volume']))) \r\napi.update_status(status) ","sub_path":"post_stock.py","file_name":"post_stock.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"527418575","text":"import numpy as np\nimport pandas as pd\nimport time\nimport os\nimport torch\nfrom torch import autograd\nimport torchvision\nfrom torchvision import transforms\nimport torchvision.datasets as dsets\nfrom torch.autograd import Variable\nimport matplotlib.pyplot as plt\nfrom torchvision.utils import save_image\nfrom dcgan_network import Generator, Discriminator\nimport pdb\n\n\n# parameters\nimage_size = 64\nbatch_size = 128\ndata_dir = \"generative-dog-images/data/\"\noutput_dir = \"output/\"\n\nG_input_dim = 100\nG_output_dim = 3\nG_num_filters = [1024, 512, 256, 128]\nD_input_dim = 3\nD_output_dim = 1\nD_num_filters = [128, 256, 512, 1024]\n\nlearning_rate = 1e-4\nG_beta_1, G_beta_2 = 0.5, 0.999\nD_beta_1, D_beta_2 = 0.5, 0.999\nlambda_gp = 10\nuse_Adam = True\ncuda_ = True if torch.cuda.is_available() else False\nclip_value = 0.01\nn_critic = 5\nnum_epochs = 800\nsample_interval = 100\n\nTensor = torch.cuda.FloatTensor if cuda_ else torch.FloatTensor\n\n\n# write results\ndef write_out_result(generator, noise, epoch_nums, iteration_nums,\n save=False, save_dir='dogs_results/', show=False, fig_size=(5, 5)):\n generator.eval()\n noise = Variable(noise.cuda(), volatile=True)\n # pdb.set_trace()\n gen_img = denormalization(generator(noise))\n generator.train()\n\n n_rows = np.sqrt(noise.size()[0]).astype(np.int32)\n n_cols = (noise.size()[0]//n_rows).astype(np.int32)\n fig, axes = plt.subplots(nrows=n_rows, ncols=n_cols, figsize=fig_size)\n for ax, img in zip(axes.flatten(), gen_img):\n ax.axis('off')\n ax.set_adjustable('box-forced')\n # intensity rescale\n img = (((img - img.min()) * 255) / (img.max() - img.min())).cpu().data.numpy().transpose(1, 2, 0).astype(np.uint8)\n ax.imshow(img, cmap=None, aspect='equal')\n plt.subplots_adjust(wspace=0.0, hspace=0.0)\n title = 'Epoch {0}'.format(epoch_nums + 1)\n fig.text(0.5, 0.04, title, ha='center')\n\n # save figure\n if save:\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n save_filename = save_dir + 'dogs_wgangp_epoch_{:d}_iteration_{:d}'.format((epoch_nums+1),\n (iteration_nums+1)) + '.png'\n plt.savefig(save_filename)\n\n if show:\n plt.show()\n else:\n plt.close()\n\n\ndef denormalization(in_img):\n out_img = (in_img+1.0)/2.0\n return out_img.clamp(min=0.0, max=1.0)\n\n\n# Calculates the gradient penalty loss for wgan-gp\ndef compute_gradient_penalty(D, real_samples, fake_samples):\n # random weights term for interpolation between real and fake samples\n alpha = Tensor(np.random.random((real_samples.size(0), 1, 1, 1)))\n # get random interpolation between real and fake samples\n interpolations = (alpha*real_samples + (1-alpha)*fake_samples)\n interpolations.requires_grad = True\n # pdb.set_trace()\n D_interpolations = D(interpolations)\n D_interpolations = D_interpolations.view(-1, 1)\n fake = Variable(Tensor(real_samples.shape[0], 1).fill_(1.0), requires_grad=False)\n if cuda_:\n fake.cuda()\n gradients = autograd.grad(outputs=D_interpolations, inputs=interpolations, grad_outputs=fake,\n create_graph=True, retain_graph=True, only_inputs=True)[0]\n else:\n gradients = autograd.grad(outputs=D_interpolations, inputs=interpolations, grad_outputs=fake,\n create_graph=True, retain_graph=True, only_inputs=True)[0]\n gradient_penalty = ((gradients.view(gradients.size()[0], -1).norm(2, 1) - 1) ** 2).mean()\n return gradient_penalty\n\n\n# dog data set\ntransform = transforms.Compose([transforms.Resize(64),\n transforms.CenterCrop(64),\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))])\n\ndogs_data = dsets.ImageFolder(root=data_dir,\n transform=transform)\ndata_loader = torch.utils.data.DataLoader(dataset=dogs_data,\n batch_size=batch_size,\n shuffle=True)\n# pdb.set_trace()\n# Models\nG = Generator(G_input_dim, G_num_filters, G_output_dim)\nG.weights_init(mean=0.0, std=0.02)\nD = Discriminator(D_input_dim, D_num_filters, D_output_dim)\nD.weights_init(mean=0.0, std=0.02)\nif cuda_:\n G.cuda()\n D.cuda()\n\n# optimizers\nif use_Adam:\n G_optimizer = torch.optim.Adam(G.parameters(), lr=learning_rate, betas=(G_beta_1, G_beta_2))\n D_optimizer = torch.optim.Adam(D.parameters(), lr=learning_rate, betas=(D_beta_1, D_beta_2))\nelse:\n G_optimizer = torch.optim.RMSprop(G.parameters(), lr=learning_rate)\n D_optimizer = torch.optim.RMSprop(D.parameters(), lr=learning_rate)\n\n# training process\nnum_rows, num_cols = 10, 10\nnum_test_samples = num_cols*num_rows\nfixed_noise = torch.randn(num_test_samples, G_input_dim).view(-1, G_input_dim, 1, 1)\n\nfor epoch in range(num_epochs):\n G_losses, D_losses = [], []\n G.train()\n n_iter = 0\n for batch_ndx, (real_images, _) in enumerate(data_loader):\n print(batch_ndx)\n # configure input\n mini_batch = real_images.size()[0]\n\n # sample noise as the generator input\n z_ = torch.randn(mini_batch, G_input_dim).view(-1, G_input_dim, 1, 1)\n if cuda_:\n real_images = real_images.cuda()\n z_ = z_.cuda()\n z_ = Variable(z_)\n D_optimizer.zero_grad()\n\n D_real = D(real_images)\n D_real_loss = -torch.mean(D_real)\n\n fake_images = G(z_).squeeze().detach()\n D_fake = D(fake_images)\n D_fake_loss = torch.mean(D_fake)\n\n # gradient penalty\n gradient_penalty = compute_gradient_penalty(D=D, real_samples=real_images, fake_samples=fake_images)\n D_loss = D_real_loss + D_fake_loss + lambda_gp*gradient_penalty\n D_loss.backward()\n D_optimizer.step()\n\n # train the generator every n_critic iterations\n if (batch_ndx+1) % n_critic == 0:\n G_optimizer.zero_grad()\n gen_imgs = G(z_)\n G_loss = -torch.mean(D(gen_imgs))\n G_loss.backward()\n G_optimizer.step()\n G_losses.append(G_loss.item())\n D_losses.append(D_loss.item())\n\n if (batch_ndx + 1) % sample_interval == 0:\n print(\"[Epoch %d/%d] [Batch %d/%d] [D loss: %f] [G loss: %f]\"\n % (epoch + 1, num_epochs, batch_ndx + 1 % len(data_loader), len(data_loader), D_loss.item(),\n G_loss.item()))\n if not os.path.exists(\"images/\"):\n os.makedirs(\"images/\")\n save_image(gen_imgs.data[:sample_interval], \"images/%d_%d.png\" % (epoch + 1, n_iter),\n nrow=np.int8(np.sqrt(sample_interval)), normalize=True)\n # pdb.set_trace()\n write_out_result(generator=G, noise=fixed_noise, epoch_nums=epoch, iteration_nums=n_iter,\n save=True, save_dir=output_dir, show=False, fig_size=(num_rows, num_cols))\n n_iter += 1\n\n\nif not os.path.exists('output_images/'):\n os.mkdir('output_images/')\nimage_batch_size = 200\nnum_images = 10000\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\npdb.set_trace()\nfor i_batch in range(0, num_images, image_batch_size):\n gen_z = torch.randn(image_batch_size, G_input_dim, device=device).view(-1, G_input_dim, 1, 1)\n if cuda_:\n gen_z.cuda()\n gen_z = Variable(gen_z)\n gen_images = G(gen_z)\n images = gen_images.to(\"cpu\").clone().detach()\n images = images.numpy()\n for i_image in range(gen_images.size(0)):\n save_image(gen_images[i_image, :, :, :], os.path.join('output_images/', f'image_{i_batch+i_image:05d}.png'))\n\n\nimport shutil\nshutil.make_archive('images', 'zip', 'output_images/')\n\n\n","sub_path":"Generative-Dog-Images/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"302667074","text":"import time\nfrom part2.spiders import scrape, check_domains\nfrom scrapy.crawler import CrawlerProcess, CrawlerRunner\n\n'''\n https://github.com/scrapy/scrapy/issues/990\n\n'''\ndef main():\n process = CrawlerProcess({\n 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',\n 'FEED_FORMAT': 'json',\n 'FEED_URI': 'healthy_domain_resps.json'\n })\n\n start_time = time.time()\n process.crawl(scrape.ScrapeDomains)\n #process.crawl(check_domains.CheckDomains)\n process.start()\n print('The script took {0} second !'.format(time.time() - start_time))\n\n # https://doc.scrapy.org/en/latest/topics/practices.html -- explains the differences with CrawlerProcess and runner\n # runner = CrawlerRunner({\n # 'FEED_FORMAT': 'json',\n # 'FEED_URI': 'result.json',\n # })\n # runner.crawl(scrape.ScrapeDomains)\n #\n # d = runner.join()\n # d.addBoth(lambda _: reactor.stop())\n # reactor.run()\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"run_spyder.py","file_name":"run_spyder.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"62581812","text":"#!/usr/bin/python3\nimport struct\nimport sys\nimport pprint\nimport zlib\nfrom .resource import ResourceID, ResourceFilter\nfrom collections import namedtuple\n\nclass FormatException(Exception):\n pass\n\n# TODO: also store a reference to the DBPF that this entry is from\nclass IndexEntry(namedtuple(\"IndexEntry\", 'id offset size size_decompressed compression')):\n @property\n def deleted(self):\n return self.compression[0] == 0xFFE0\n\nfoo = [None]\nclass DBPFFile:\n \"\"\"A Sims4 DBPF file. This is the format in Sims4 packages, worlds, etc\"\"\"\n _CONST_TYPE = 1\n _CONST_GROUP = 2\n _CONST_INSTAMCE_EX = 4\n \n def __init__(self, name, prescan_index=True):\n self.file = open(name, \"rb\")\n self._index_cache = None\n self._read_header()\n if prescan_index:\n self._index_cache = list(self.scan_index(full_entries=True))\n def _read_header(self):\n\n self.file.seek(0)\n buf = self.file.read(96)\n\n if buf[0:4] != b\"DBPF\":\n raise FormatException(\"Wrong magic\")\n self.file_version = struct.unpack_from(\"=II\", buf, 4)\n if self.file_version != (2,1):\n raise FormatException(\"Don't know how to handle anything other than DBPF v2.1\")\n\n # TODO: check the accuracy of this; it's based on code I had\n # lying around for Sims3 DBPF files\n self._index_count, self._index_size, self._index_vsn, self._index_off = struct.unpack_from(\"=I4xI12xII\", buf, 36)\n\n def _get_dword(self, dword=struct.Struct(\"=I\")):\n \"\"\"This is only ever intended to be called with no arguments; the\n dword kwarg is a function static\"\"\"\n return dword.unpack(self.file.read(4))[0]\n def scan_index(self, filter=None, full_entries=False):\n \"\"\"Iterate over the items that match a filter\"\"\"\n if full_entries:\n xform = lambda x: x\n else:\n xform = lambda x: x.id\n if self._index_cache is not None:\n if filter is None:\n for x in self._index_cache:\n yield xform(x)\n else:\n for x in self._index_cache:\n if filter.match(x.id):\n yield xform(x)\n return\n if self._index_off == 0:\n if self._index_count == 0:\n # Empty DBPF file.\n return\n else:\n raise FormatException(\"Missing index\")\n self.file.seek(self._index_off)\n flags = self._get_dword()\n\n if flags & self._CONST_TYPE:\n entry_type = self._get_dword()\n if flags & self._CONST_GROUP:\n entry_group = self._get_dword()\n if flags & self._CONST_INSTAMCE_EX:\n entry_instance_ex = self._get_dword()\n\n for n in range(self._index_count):\n if not flags & self._CONST_TYPE:\n entry_type = self._get_dword()\n if not flags & self._CONST_GROUP:\n entry_group = self._get_dword()\n if not flags & self._CONST_INSTAMCE_EX:\n entry_instance_ex = self._get_dword()\n entry_instance = self._get_dword()\n entry_offset = self._get_dword()\n entry_size = self._get_dword()\n entry_size_decompressed = self._get_dword()\n if entry_size & 0x80000000:\n entry_compressed = struct.unpack(\"=HH\", self.file.read(4))\n else:\n entry_compressed = (0,1)\n entry_size = entry_size & 0x7FFFFFFF\n rid = ResourceID(entry_group, (entry_instance_ex << 32) | entry_instance, entry_type)\n if filter is None or filter.match(rid):\n # The process of reading the index may be interleaved\n # with reading the contents of the file. This way, we\n # don't lose the file pointer\n cur_pos = self.file.tell()\n if full_entries:\n yield IndexEntry(rid, entry_offset, entry_size,\n entry_size_decompressed, entry_compressed)\n else:\n yield rid\n self.file.seek(cur_pos)\n\n \n def __getitem__(self, item):\n if isinstance(item, int):\n item = self._index_cache[item]\n elif not isinstance(item, IndexEntry):\n # It must be a filter\n itemlist = self.scan_index(item, full_entries=True)\n try:\n item = next(itemlist)\n except StopIteration:\n raise KeyError(\"No item found\")\n try:\n next(itemlist)\n except StopIteration:\n pass\n else:\n raise KeyError(\"More than one item found\")\n # At this point, we know that the item is an IndexEntry;\n # hopefully it is one that refers to this file ;-)\n self.file.seek(item.offset)\n ibuf = self.file.read(item.size)\n\n if item.compression[0] == 0:\n return ibuf # uncompressed\n elif item.compression[0] == 0xFFFE:\n # BUG: I'm guessing \"streamable compression\" is the same\n # as RefPack, with a limited buffer size. This may or may\n # not be true, and even if it is, I'd need to know the\n # size of the buffer to do anything sensible.\n return decodeRefPack(ibuf)\n elif item.compression[0] == 0xFFFF:\n return decodeRefPack(ibuf)\n elif item.deleted:\n raise KeyError(\"Deleted file\")\n elif item.compression[0] == 0x5A42:\n # BUG: Not sure if the gzip header is needed. If it is,\n # change -15 in the next line to 15\n return zlib.decompress(ibuf, 15, item.size_decompressed)\n\ndef decodeRefPack(ibuf):\n \"\"\"Decode the DBPF compression. ibuf must quack like a bytes\"\"\"\n # Based on http://simswiki.info/wiki.php?title=Sims_3:DBPF/Compression\n # Sims4 compression has the first two bytes swapped\n \n iptr = optr = 0\n flags = ibuf[0]\n if ibuf[1] != 0xFB:\n raise FormatException(\"Invalid compressed data\")\n iptr = 2\n osize = 0 # output size\n for _ in range(4 if flags & 0x80 else 3):\n osize = (osize << 8) | ibuf[iptr]\n iptr += 1\n\n obuf = bytearray(osize)\n while iptr < len(ibuf):\n numPlaintext = numToCopy = copyOffset = 0\n # Copyoffset is 0-indexed back from obuf[optr]\n # I.e., copyoffset=0 ==> copying starts at obuf[optr-1]\n \n # Read a control code\n cc0 = ibuf[iptr]; iptr+=1\n if cc0 <= 0x7F:\n cc1 = ibuf[iptr]; iptr+=1\n cc = (cc0,cc1)\n numPlaintext = cc0 & 0x03\n numToCopy = ((cc0 & 0x1C) >> 2) + 3\n copyOffset = ((cc0 & 0x60) << 3) + cc1\n elif cc0 <= 0xBF:\n cc1 = ibuf[iptr]; iptr+=1\n cc2 = ibuf[iptr]; iptr+=1\n cc = (cc0,cc1,cc2)\n numPlaintext = (cc1 & 0xC0) >> 6\n numToCopy = (cc0 & 0x3F) + 4\n copyOffset = ((cc1 & 0x3F) << 8) + cc2\n elif cc0 <= 0xDF:\n cc1 = ibuf[iptr]; iptr+=1\n cc2 = ibuf[iptr]; iptr+=1\n cc3 = ibuf[iptr]; iptr+=1\n cc = (cc0,cc1,cc2,cc3)\n numPlaintext = cc0 & 0x03\n numToCopy = ((cc0 & 0x0C) << 6) + cc3 + 5\n copyOffset = ((cc0 & 0x10) << 12) + (cc1 << 8) + cc2\n elif cc0 <= 0xFB:\n cc = (cc0,)\n numPlaintext = ((cc0 & 0x1F) << 2) + 4\n numToCopy = 0\n else:\n cc = (cc0,)\n numPlaintext = cc0 & 3\n numToCopy = 0\n\n # Copy from source\n obuf[optr:optr+numPlaintext] = ibuf[iptr:iptr+numPlaintext]\n iptr += numPlaintext\n optr += numPlaintext\n\n # Copy from output\n for _ in range(numToCopy):\n obuf[optr] = obuf[optr - 1 - copyOffset]\n optr += 1\n # Done decompressing\n return bytes(obuf)\n\n \n","sub_path":"lib/s4py/dbpf.py","file_name":"dbpf.py","file_ext":"py","file_size_in_byte":7957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"412222894","text":"import numpy as np\nimport torch.nn as nn\n\nfrom params import FEATURE_VALUE2ID, FEATURE_NUMBER\nfrom data.data_parser import Parser\nfrom data.data_splitter import Splitter\n\n\nclass DataGenerator(object):\n def __init__(self, splitter: Splitter, sample_space: int):\n self.label_size = splitter.get_label_size()\n self.data = splitter.load()\n self.name = splitter.name\n self.total_batch = 0\n self.sample_space = sample_space\n\n def generate(self, batch_size: int, mode: str):\n data = self.data[mode]\n np.random.shuffle(data)\n\n total_batch = (len(data) - 1) // batch_size + 1\n for batch_id in range(total_batch):\n begin = batch_id * batch_size\n end = (batch_id + 1) * batch_size\n batch_data = data[begin: end]\n\n batch_input, batch_label = [], []\n for per_data in batch_data:\n features = np.array(Parser.parse_train_file(per_data['path'])[::self.sample_space])\n # for col in range(features.shape[1]):\n # for row in range(features.shape[0]):\n # features[row, col] = FEATURE_VALUE2ID[col][features[row, col]]\n batch_input.append(features)\n batch_label.append(per_data['label'])\n yield np.array(batch_input), np.array(batch_label)\n\n def get_label_size(self) -> int:\n return self.label_size\n\n def get_total_batch(self, batch_size: int, mode: str) -> int:\n return (len(self.data[mode]) - 1) // batch_size + 1\n\n\nif __name__ == '__main__':\n splitter = Splitter(\n label_list=[0, 2, 7, 17],\n is_slice_data=False,\n is_create_negative_sample=True\n )\n splitter.split()\n generator = DataGenerator(splitter, 10)\n for idx, data in enumerate(generator.generate(batch_size=20)):\n print(idx, data[0].shape, data[1].shape)\n","sub_path":"data/data_generator.py","file_name":"data_generator.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"161837038","text":"#!/usr/bin/env python\n# cording: utf-8\n\n#\n# Copyright (c) 2017, Hiroki Urase\n# All rights reserved.\n#\n\n#!/usr/bin/env python\nimport rospy\nimport tf2_ros\nimport tf2_geometry_msgs\nfrom nav_msgs.msg import Odometry\nfrom geometry_msgs.msg import PoseStamped\n\nclass utm_simple_goal:\n\tdef __init__(self,utm_odom_topic):\n\t\tself.utm_odom = rospy.Subscriber(utm_odom_topic, Odometry, self.callback)\n\t\tself.goalpub = rospy.Publisher('move_base_simple/goal', PoseStamped, queue_size=50)\t\t\n\t\tself.goal = PoseStamped()\n\t\tself.odom_pose = PoseStamped()\n\t\tself.odom_pose_flag = False\n\t\t#tf2 setup\n\t\tself.tfBuffer = tf2_ros.Buffer()\n\t\tself.tfListener = tf2_ros.TransformListener(self.tfBuffer)\n\n\tdef callback(self,odom):\n\t\tself.odom_pose_flag = True\n\t\tself.odom_pose.header = odom.header\n\t\tself.odom_pose.pose = odom.pose.pose\n\n\tdef publish(self):\n\t\tif self.odom_pose_flag == True:\n\t\t\tself.odom_pose_flag = False\n\t\t\tself.goal.header.frame_id = self.odom_pose.header.frame_id\n\t\t\tself.goal = tf2_geometry_msgs.do_transform_pose(self.odom_pose, self.trans)\n\t\t\tself.goal.header.stamp = rospy.Time()\n\t\t\tself.goal.pose.orientation.x = 0\n\t\t\tself.goal.pose.orientation.y = 0\n\t\t\tself.goal.pose.orientation.z = 0.12\n\t\t\tself.goal.pose.orientation.w = 0.99\n\t\t\tself.goalpub.publish(self.goal)\n\t\telse:\n\t\t\trospy.loginfo(\"it has not get goal odom topic\")\n\n\tdef set_transform(self):\n\t\tself.trans = self.tfBuffer.lookup_transform('map','utm', rospy.Time())\n\t\t\n\n\ndef main():\n\trospy.init_node('utm_simple_goal', anonymous=True)\n\n\t#Get Parameters\n\tutm_odom_topic = rospy.get_param('~utm_odom_topic', \"odom/goal\")\n\n\tsimple_goal = utm_simple_goal(utm_odom_topic)\n\trate = rospy.Rate(1)\n\n\twhile not rospy.is_shutdown():\n\t\ttry:\n\t\t\ttry:\n\t\t\t\tsimple_goal.set_transform()\n\t\t\texcept (tf2_ros.LookupException, tf2_ros.ConnectivityException, tf2_ros.ExtrapolationException):\n\t\t\t\trate.sleep()\n\t\t\t\tcontinue\n\t\t\tsimple_goal.publish()\n\t\texcept rospy.ROSInterruptException:\n\t\t\tbreak\n\n \nif __name__ == '__main__':\n main()\n","sub_path":"cloud_links/utm_simple_goal/script/utm_simple_goal.py","file_name":"utm_simple_goal.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"277964083","text":"from django.forms import ModelForm, Textarea\nfrom csm.models import Issue, UserOnProject, Label, Comment, Commit\nfrom django.db.models import Q\nfrom django.forms.extras.widgets import SelectDateWidget\n\n\n\n\nclass IssueCreateForm(ModelForm):\n\n def __init__(self,issue,*args,**kwargs):\n super (IssueCreateForm,self ).__init__(*args,**kwargs) # populates the post\n self.fields['assigned_users'].queryset = UserOnProject.objects.filter(project_id = issue.project_id)\n self.fields['labels'].queryset = Label.objects.filter(Q(project_id = issue.project_id) | Q(project_id = None))\n\n class Meta:\n model = Issue\n fields = ['title', 'description', 'assigned_users', 'labels', 'date_end']\n widgets = {\n 'description': Textarea(attrs={'cols': 50, 'rows': 10}),\n 'date_end' : SelectDateWidget()\n }\n\n\nclass IssueEditForm(ModelForm):\n\n def __init__(self,issue,*args,**kwargs):\n super (IssueEditForm,self ).__init__(*args,**kwargs) # populates the post\n self.fields['assigned_users'].queryset = UserOnProject.objects.filter(project_id = issue.project_id)\n self.fields['labels'].queryset = Label.objects.filter(Q(project_id = issue.project_id) | Q(project_id = None))\n\n class Meta:\n model = Issue\n fields = ['title', 'description', 'assigned_users', 'opened', 'completed', 'labels', 'date_end']\n widgets = {\n 'description': Textarea(attrs={'cols': 50, 'rows': 10}),\n 'date_end' : SelectDateWidget()\n }\n\n\nclass CommentForm(ModelForm):\n\n class Meta:\n model = Comment\n fields = ['body']\n widgets = {\n 'body': Textarea(attrs={'cols': 50, 'rows': 10}),\n }\n\n\nclass CommitForm(ModelForm):\n\n class Meta:\n model = Commit\n fields = ['link']\n ","sub_path":"CSMProject/csm/forms/issue_forms.py","file_name":"issue_forms.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"379219377","text":"from django import template\n\nregister = template.Library()\n\n@register.filter\ndef obj_rev_msg_flg(key, val):\n '''目標・振り返り作成のメッセージを出すか判定する'''\n if val == \"1\":\n # 目標:目標入力済\n # 振り返り:目標入力済&振り返り入力済\n return False\n else:\n # 目標:未入力\n # 振り返り:目標入力済&振り返り未入力\n if key[:1] == \"T\" and key[2:] == \"R\":\n # 対象が今年・月・週・日かつ振り返りの場合はメッセージを出さない\n return False\n else:\n return True\n\n\n@register.filter\ndef create_obj_rev_msg(key):\n '''目標・振り返り作成のメッセージを作成する'''\n kind_dic = {\"Y\":\"年\",\"M\":\"月\",\"W\":\"週\",\"D\":\"日\"}\n or_dic = {\"O\":\"目標\",\"R\":\"振返り\"}\n prev_this_dic = {\"T\":\"今\",\"P\":\"前\"}\n return \"%s%sの%sが未作成です。\" % (prev_this_dic[key[:1]], kind_dic[key[1:2]], or_dic[key[2:]])\n\n@register.filter\ndef create_obj_rev_link(key, target_date):\n '''目標・振り返り作成のリンクを作成する'''\n return \"/objectives/objrev/%s/%s\" % (key, target_date)\n\n@register.filter\ndef get_checkbox(key):\n if key == \"1\":\n return \"fas fa-check-circle\"\n else:\n return \"far fa-circle\"\n\n@register.filter\ndef get_btn_class(key):\n if key == \"1\":\n return \"btn btn-success\"\n else:\n return \"btn btn-outline-secondary\"","sub_path":"templatetags/cmn_filter.py","file_name":"cmn_filter.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"412088389","text":"\n# -*- coding: cp936 -*-\n##tcp响应服务器,当与客户端建立连接后,服务器显示客户端ip和端口,同时将接收的客户端信息和'I get it!'传给客户端,此时等待输入一个新的信息传给客户端。\n\nimport socket,traceback\nhost='0.0.0.0'\nport=12345\ns=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\ns.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)\ns.bind((host,port))\ns.listen(1)\nwhile 1:\n try:\n clientsock,clientaddr=s.accept()\n except KeyboardInterrupt:\n raise\n except:\n traceback.print_exc()\n continue\n try:\n print(\"连接来自:\",clientsock.getpeername())\n while 1:\n data=clientsock.recv(4096).decode()\n if not len(data):\n break\n print(clientsock.getpeername()[0]+':'+str(data))\n clientsock.sendall(data.encode())\n clientsock.sendall((\"\\nI get it!\\n\").encode())\n t=input('input the word:')\n clientsock.sendall(t.encode())\n except (KeyboardInterrupt,SystemExit):\n raise\n except:\n traceback.print_exc()\n try:\n clientsock.close()\n except KeyboardInterrupt:\n raise\n except:\n traceback.print_exc()\n\n","sub_path":"network/example1/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"497137892","text":"\"\"\" iframe-eventsource transport \"\"\"\nimport asyncio\nfrom aiohttp import web, hdrs\nfrom sockjs.protocol import STATE_CLOSING, close_frame\nfrom sockjs.exceptions import SessionIsAcquired\n\nfrom .utils import session_cookie\nfrom .xhrstreaming import StreamingTransport\n\n\nclass EventsourceTransport(StreamingTransport):\n\n @asyncio.coroutine\n def send_blob(self, blob):\n blob = b''.join((b'data: ', blob, b'\\r\\n\\r\\n'))\n yield from self.response.write(blob)\n\n self.size += len(blob)\n if self.size > self.maxsize:\n yield from self.manager.release(self.session)\n self.waiter.set_result(True)\n\n def process(self):\n headers = list(\n ((hdrs.CONTENT_TYPE, 'text/event-stream; charset=UTF-8'),\n (hdrs.CACHE_CONTROL,\n 'no-store, no-cache, must-revalidate, max-age=0')) +\n session_cookie(self.request))\n\n # open sequence (sockjs protocol)\n resp = self.response = web.StreamResponse(headers=headers)\n resp.start(self.request)\n resp.write(b'\\r\\n')\n\n # get session\n session = self.session\n\n # session was interrupted\n if session.interrupted:\n self.send_blob(close_frame(1002, b\"Connection interrupted\"))\n\n # session is closed\n elif session.state == STATE_CLOSING:\n yield from self.session._remote_closed()\n self.send_blob(close_frame(3000, b'Go away!'))\n\n else:\n # acquire session\n try:\n yield from self.manager.acquire(self.session, self)\n except SessionIsAcquired:\n yield from self.send_blob(\n close_frame(2010, b\"Another connection still open\"))\n else:\n yield from self.waiter\n\n return resp\n","sub_path":"sockjs/transports/eventsource.py","file_name":"eventsource.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"321859277","text":"from perceptron import Perceptron\nimport numpy as np\nfrom utils import gens\nfrom time import gmtime, strftime\nfrom os import getcwd\n\ndef build_adjacency_list (shape):\n adj_list = [[] for node_id in xrange(sum(shape))]\n \n if len(shape) == 1: return adj_list\n \n node_start = 0\n for size_cur, size_next in zip(shape[:-1], shape[1:]):\n node_finish = node_start + size_cur\n for node_id in xrange(node_start, node_finish):\n adj_list[node_id] = range(node_finish, node_finish+size_next)\n node_start = node_finish\n return adj_list\n\ndef build_reverse_adjacency_list (shape):\n r_adj_list = [[] for node_id in xrange(sum(shape))]\n if len(shape) == 1: return r_adj_list\n \n node_start = sum(shape)-1\n \n r_shape = shape[::-1]\n for size_prev, size_cur in zip(r_shape[1:], r_shape[:-1]):\n node_finish = node_start - size_cur\n for node_id in range(node_start, node_finish, -1):\n r_adj_list[node_id] = range(node_finish-size_prev + 1, node_finish+1)\n node_start = node_finish\n return r_adj_list\n\nclass NeuralNetwork (object):\n \n def __init__ (self, number_of_inputs, shape, filename = None):\n\n \n self.shape = shape\n \n self.num_inputs = number_of_inputs\n \n self.node_list = [Perceptron(node_id, size) for node_id, size in gens.id_inputs(number_of_inputs, shape)]\n \n self.adj_list = build_adjacency_list(shape)\n self.r_adj_list = build_reverse_adjacency_list(shape)\n \n self.node_output = [None for node_id in self.node_list]\n \n self.input_ids = [node_id for node_id in gens.id_empty(self.r_adj_list)]\n self.output_ids = [node_id for node_id in gens.id_empty(self.adj_list)]\n \n if filename is None:\n time_str = strftime(\"%H-%M-%S_%d-%b-%Y\", gmtime())\n #self.f = open(getcwd()+'/'+time_str+'.csv', 'w') # self enforcing csv convention\n else: self.f = open(filename + '.csv', 'w')\n \n def feed_forward (self, X):\n for node_id, edges in enumerate(self.r_adj_list):\n if len(edges) == 0: input_value = X\n else: input_value = [self.node_output[edge_id] for edge_id in edges]\n \n self.node_output[node_id] = self.node_list[node_id].output(input_value)\n \n def output (self, X):\n self.feed_forward(X)\n return np.array([self.node_output[node_id] for node_id in self.output_ids])\n","sub_path":"src/nn/neural_network.py","file_name":"neural_network.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"612865451","text":"\nfrom spa.serverside import CSocketProServer\nimport sys\nfrom ctypes import *\nfrom sys import platform as os\n\n_ussLib_ = None\n_IsWin_ = (os == \"win32\")\nif _IsWin_:\n _ussLib_ = WinDLL('ustreamfile.dll')\nelse:\n _ussLib_ = CDLL('libustreamfile.so')\n\n# void WINAPI SetRootDirectory(const wchar_t *pathRoot);\nSetRootDirectory = _ussLib_.SetRootDirectory\nSetRootDirectory.argtypes = [c_wchar_p]\nSetRootDirectory.restype = None\n\nwith CSocketProServer() as server:\n handle = CSocketProServer.DllManager.AddALibrary('ustreamfile')\n if handle:\n SetRootDirectory('C:\\\\boost_1_60_0\\\\stage\\\\lib64')\n ok = server.Run(20901)\n if not ok:\n print('Error message = ' + CSocketProServer.ErrorMessage)\n print('Read a line to shutdown the application ......')\n line = sys.stdin.readline()\n","sub_path":"tutorials/python/remote_file/rf_server/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"25184733","text":"import pygame\nheight = 800\nwidth = 600\ndisplay = pygame.display.set_mode((height, width)) #design game window\n\t\t#r g b\nblack = (0, 0, 0)\nred = (255, 0, 0)\ngreen = (0, 255, 0)\nblue = (0, 0, 255)\nwhite = (255, 255, 255)\ngrey = (122, 122, 122)\n\nx = height / 2\nx_speed = 0\ny = width / 2\ny_speed = 0\nsize = 20\ngame_on = True\n#gameloop\nwhile game_on:\n\tfor event in pygame.event.get():\n\t\t# print(event)\n\t\tif event.type == pygame.QUIT:\n\t\t\tpygame.quit()\n\t\t\tquit()\n\t\tif event.type == pygame.KEYDOWN:\n\t\t\tif event.key == pygame.K_RIGHT:\n\t\t\t\tx_speed = size\n\n\t\t\tif event.key == pygame.K_LEFT:\n\t\t\t\tx_speed = -size\t\n\n\t\t\tif event.key == pygame.K_UP:\n\t\t\t\ty_speed = -size\n\n\t\t\tif event.key == pygame.K_DOWN:\n\t\t\t\ty_speed = size\n\n\tx += x_speed\n\ty += y_speeḍ\n\tdisplay.fill(black)\n\tdisplay.fill(red, rect=[x, y, size, size])\n\tpygame.display.update()\n\tpygame.time.Clock().tick(40)\n\n","sub_path":"tut3.py","file_name":"tut3.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"495158551","text":"from selenium import webdriver\nfrom requests import post, get\nfrom time import sleep\nfrom sys import stdout\nfrom json import loads\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport time\nfrom email.mime.text import MIMEText\nimport smtplib\n\ncredit_list = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7,\n 1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.9,\n 2, 2.4, 2.5, 2.6, 3, 3.5, 4, 4.4, 4.5,\n 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9, 9.5,\n 10, 11, 11.5, 12, 14.5, 15, 17.5]\n\nfail_num = 0\nsuccess_num = 0\nfail_list = []\ncourse_info_list = []\ncourse_id = ''\ncourse_name = ''\ncourse_timeout = 0\n\nheader = {\n 'Accept': 'application/json, text/javascript, */*; q=0.01',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n 'Connection': 'keep-alive',\n 'Content-Length': '57',\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'Host': 'study.foton.com.cn',\n 'Origin': 'http://study.foton.com.cn',\n 'Referer': 'http://study.foton.com.cn/els/flash/elnFlvPlayer.swf?v=4.0.2',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36',\n 'X-Requested-With': 'XMLHttpRequest'}\n\ndata_single = {\n 'courseId': 'PTC035903',\n 'playTime': '9999'\n}\n\ndata_double = {\n 'courseId': ' ',\n 'scoId': ' ',\n 'progress_measure': '100',\n 'session_time': '60:01',\n 'location': '3601'\n}\n\nselect_video_data = {\n 'courseId': '',\n 'scoId': '',\n 'firstLoad': 'true',\n 'Location': '0',\n 'elsSign': ''\n}\n\ncookie = {}\n\ntemplate_url = \"http://study.foton.com.cn/els/html/coursestudyrecord/coursestudyrecord.studyCheck.do?courseId={}&scoId={}\"\nprogress_url = \"http://study.foton.com.cn/els/html/courseStudyItem/courseStudyItem.saveProgress.do\"\nprecent_url = \"http://study.foton.com.cn/els/html/courseStudyItem/courseStudyItem.saveCoursePrecent.do\"\ntemplate_watch_url = \"http://study.foton.com.cn/els/html/courseStudyItem/courseStudyItem.learn.do?courseId={}&vb_server=&willGoStep=COURSE_COURSE_STUDY\"\ntemplate_play_url = \"http://study.foton.com.cn/els/html/studyCourse/studyCourse.enterCourse.do?courseId={}&studyType=STUDY\"\n\n# 保存视频播放进度\nsave_progress_api = \"http://study.foton.com.cn/els/html/courseStudyItem/courseStudyItem.saveProgress.do\"\n# 同步刷新记录\nupdate_time_api = \"http://study.foton.com.cn/els/html/courseStudyItem/courseStudyItem.updateTimestepByUserTimmer.do\"\n# 获取课程包含的小节信息\nload_course_api = \"http://study.foton.com.cn/els/html/courseStudyItem/courseStudyItem.loadCourseItemTree.do\"\n# 选课接口,包含location信息\nselect_resource_api = \"http://study.foton.com.cn/els/html/courseStudyItem/courseStudyItem.selectResource.do?vbox_server=&fromNetWorkSetting=false\"\n# 确认选课接口\nstudy_check_api_tmp = \"http://study.foton.com.cn/els/html/coursestudyrecord/coursestudyrecord.studyCheck.do?courseId={}&scoId={}\"\n# 查看小节学习进度\nscols_complate_api_tmp = \"http://study.foton.com.cn/els/html/courseStudyItem/courseStudyItem.scoIsComplate.do?courseId={}&processType=THREESCREEN\"\n# sever酱推送接口\nnotification_api_tmp = 'https://api.telegram.org/bot{}/sendMessage?chat_id={}&parse_mode=Markdown&text='\n\n\ndef push_notification(ntfc):\n try:\n get(notification_api+\"福田大学云学习进度提示:\\n\"+ntfc)\n except:\n print(\"推送到TG时出错\")\n\n\ndef show_time():\n print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))\n\n\ndef open_broswer():\n driver.implicitly_wait(20)\n driver.get(\"http://study.foton.com.cn\")\n\n\ndef login():\n print(\"登录中...\")\n sleep(10)\n usrname = driver.find_element_by_id('loginName')\n usrname.click()\n usrname.send_keys(username)\n\n passwd = driver.find_element_by_id('password')\n passwd.click()\n passwd.send_keys(password)\n\n sleep(2)\n\n ele = driver.find_element_by_class_name('login_Btn')\n ele.click()\n\n\ndef login_ok():\n if driver.current_url == \"http://study.foton.com.cn/os/html/index.init.do\":\n # 登录成功\n return True\n else:\n return False\n\n\ndef load_course():\n global select_credit\n with open('./course_data.txt', 'r', encoding='utf-8') as f:\n line = f.readline()\n line = f.readline()\n while line:\n line_list = line.strip().split(',')\n credit = line_list[-2]\n if credit == select_credit:\n course_info_list.append(line)\n line = f.readline()\n\n\ndef select_video(course_id, video_id):\n select_video_data['courseId'] = course_id\n select_video_data['scoId'] = video_id\n select_video_data['elsSign'] = cookie['eln_session_id']\n study_check_api = study_check_api_tmp.format(course_id, video_id)\n sleep(5)\n try:\n post(select_resource_api, headers=header, cookies=cookie, data=select_video_data, timeout=(15, 15))\n post(study_check_api, headers=header, cookies=cookie, data={'elsSign': cookie['eln_session_id']}, timeout=(15, 15))\n except:\n pass\n\n\ndef get_completed_video_list(course_id):\n \"\"\"\n 获取已经完成的视频列表\n \"\"\"\n completed_list = []\n scols_complate_api = scols_complate_api_tmp.format(course_id)\n try:\n cmpls = post(scols_complate_api, headers=header, cookies=cookie,\n data={'elsSign': cookie['eln_session_id']}, timeout=(15, 15))\n except:\n print(\"获取视频完成列表出错\")\n else:\n if len(cmpls.text) != 0:\n completed_list = loads(cmpls.text)\n return completed_list\n\n\ndef course_finished(completed_list, vid_list):\n \"\"\"\n 判断课程是否学习完毕\n \"\"\"\n if len(completed_list) == len(vid_list):\n return True\n else:\n return False\n\n\ndef video_finished(course_id, video_id, course_name, video_name):\n \"\"\"\n 判断视频是否播放完毕\n \"\"\"\n data_double['courseId'] = course_id\n data_double['scoId'] = video_id\n completed_list = get_completed_video_list(course_id)\n\n # print(course_id)\n # print(video_id)\n # print(completed_list)\n\n if video_id in completed_list:\n return True\n try:\n r = post(save_progress_api, headers=header, cookies=cookie, data=data_double, timeout=(15, 15))\n except:\n print(\"获取视频播放进度时出错\")\n else:\n r_data = r.text\n\n print(r.text)\n\n if len(r_data) != 0:\n\n # print(r_data)\n\n try:\n r_dict = loads(r_data)\n except:\n print(\"HTTP Status 500 服务器内部错误\")\n else:\n if 'completed' in r_dict:\n if r_dict['completed'] == 'true':\n return True\n else:\n show_time()\n print(\"{}视频播放进度{}%,{}课程学习进度{}%\".format(video_name, r_dict['completeRate'],\n course_name, r_dict['courseProgress']))\n progress = \"{} 视频播放进度{}%,{} 课程学习进度{}%\".format(video_name, r_dict['completeRate'],\n course_name, r_dict['courseProgress'])\n push_notification(progress)\n return False\n else:\n return False\n else:\n return False\n\n\ndef pre_test():\n sleep(15)\n form = driver.find_element_by_id(\"coursePretestForm\")\n sleep(5)\n try:\n h2 = form.find_element_by_tag_name(\"h2\")\n except:\n form_choice = driver.find_element_by_class_name(\"form_choice\")\n # choice_type_list = form_choice.find_elements_by_class_name(\"choice_type\")\n # for choice_type in choice_type_list:\n # if choice_type.text == \"判断题\":\n # 判断题/选择题(单选,多选)都只需要循环点question-item的第一个选项就行了\n question_item_list = form_choice.find_elements_by_class_name(\"question-item\")\n for question_item in question_item_list:\n p_list = question_item.find_elements_by_tag_name(\"p\")\n span = p_list[1].find_element_by_tag_name(\"span\")\n button = span.find_element_by_tag_name(\"input\")\n button.click()\n sleep(1)\n from_confirm = driver.find_element_by_class_name(\"from_confirm\")\n submit_button = from_confirm.find_element_by_id(\"coursePretestSubmit\")\n submit_button.click()\n sleep(5)\n next_step = driver.find_element_by_id(\"upCoursePretestGoNextBtn\")\n next_step.click()\n sleep(5)\n learn()\n else:\n if h2.text == \"(无试题)\":\n button = driver.find_element_by_class_name(\"from_confirm\").find_element_by_tag_name(\"button\")\n button.click()\n sleep(5)\n learn()\n\n\ndef is_finished():\n global success_num\n sleep(15)\n try:\n # 通过课程进度判断课程是否学习完成,span.text == '100'说明已经学完了\n # span = driver.find_element_by_id(\"studyProgress\")\n span = WebDriverWait(driver, 3, 0.5).until(\n EC.presence_of_element_located((By.ID, 'studyProgress')))\n except:\n try:\n # 通过是否显示课程评估页面判断课程是否学习完成\n # h1 = driver.find_element_by_class_name(\"main_title\")\n h1 = WebDriverWait(driver, 3, 0.5).until(\n EC.presence_of_element_located((By.CLASS_NAME, 'main_title')))\n except:\n # 不显示课程评估,没学完,开始学习\n learn()\n else:\n span = h1.find_element_by_tag_name('span')\n if span.text == \"课程评估\":\n success_num += 1\n print(\"恭喜你!课程《{}》 已经完成学习,已成功学习 {} 门\".format(course_name, success_num))\n info = \"《{}》课程全部视频学习完毕.学习成功{}门.共{}门.学习进度{}\".format(course_name, success_num,\n len(course_info_list),\n str(round((success_num+fail_num) / len(course_info_list),\n 4) * 100) + \"%\")\n push_notification(info)\n elif span.text == \"课前测试\":\n pre_test()\n elif span.text == \"课后测试\":\n success_num += 1\n print(\"恭喜你!课程《{}》 已经完成学习,已成功学习 {} 门\".format(course_name, success_num))\n info = \"《{}》���程全部视频学习完毕.学习成功{}门.共{}门.学习进度{}\".format(course_name, success_num,\n len(course_info_list),\n str(round((success_num+fail_num) / len(course_info_list),\n 4) * 100) + \"%\")\n push_notification(info)\n\n else:\n if span.text == '100':\n success_num += 1\n print(\"恭喜你!课程《{}》 已经完成学习,已成功学习 {} 门\".format(course_name, success_num))\n info = \"《{}》课程全部视频学习完毕.学习成功{}门.共{}门.学习进度{}\".format(course_name, success_num,\n len(course_info_list),\n str(round((success_num+fail_num) / len(course_info_list),\n 4) * 100) + \"%\")\n push_notification(info)\n else:\n # 开始学习\n learn()\n\n\ndef get_cookie():\n cookie_list = driver.get_cookies()\n for single_cookie in cookie_list:\n cookie[single_cookie['name']] = single_cookie['value']\n\n\ndef learn():\n global success_num\n global fail_num\n global course_timeout\n sleep(15)\n play_button = WebDriverWait(driver, 15, 0.5).until(\n EC.presence_of_element_located((By.ID, 'courseRp_sel')))\n play_button.click()\n sleep(5)\n get_cookie()\n data_single['courseId'] = course_id\n data_double['courseId'] = course_id\n\n try:\n # ele存在说明是双分屏或者三分屏\n # ele = driver.find_element_by_id('vodtree')\n ele = WebDriverWait(driver, 3, 0.5).until(\n EC.presence_of_element_located((By.ID, 'vodtree')))\n except:\n # ele不存在说明是单分屏\n sleep(0.1)\n try:\n r = post(precent_url, headers=header, cookies=cookie, data=data_single, timeout=(15, 15))\n except:\n fail_num += 1\n print(\"课程《{}》学习失败,已学习失败{}门课程\".format(course_name, fail_num))\n fail_list.append(course_name)\n else:\n r_data = r.text\n if len(r_data) != 0:\n r_dict = loads(r_data)\n if 'completed' in r_dict:\n if r_dict['completed'] == 'true':\n success_num += 1\n print(\"恭喜你!课程《{}》 已经完成学习,已成功学习 {} 门\".format(course_name, success_num))\n info = \"《{}》课程全部视频学习完毕.学习成功{}门.共{}门.学习进度{}\".format(course_name, success_num,\n len(course_info_list),\n str(round(\n (success_num+fail_num) / len(course_info_list),\n 4) * 100) + \"%\")\n push_notification(info)\n else:\n fail_num += 1\n print(\"课程《{}》学习失败,已学习失败{}门课程\".format(course_name, fail_num))\n fail_list.append(course_name)\n else:\n # 双/三分屏\n completed_video_list = get_completed_video_list(course_id)\n vid_list = []\n title_list = []\n\n div_list = ele.find_elements_by_tag_name('div')\n for div in div_list[1:]:\n try:\n a = div.find_element_by_tag_name('a')\n except:\n pass\n else:\n video_id = a.get_attribute('data-id')\n vid_list.append(video_id)\n video_title = a.get_attribute('title')\n title_list.append(video_title)\n print(\"正在爬取 {} 视频数据...\".format(video_title))\n stdout.flush()\n\n print(\"课程《{}》所有视频数据爬取完成!开始学习\".format(course_name))\n if course_finished(completed_video_list, vid_list):\n show_time()\n print(\"《{}》课程全部视频学习完毕\".format(course_name))\n success_num += 1\n info = \"《{}》课程全部视频学习完毕.学习成功{}门.共{}门.学习进度{}\".format(course_name, success_num, len(course_info_list),\n str(round((success_num+fail_num) / len(course_info_list),\n 4) * 100) + \"%\")\n push_notification(info)\n else:\n for index, vid in enumerate(vid_list):\n t = 0\n sleep(1)\n video_title = title_list[index]\n data_double['scoId'] = vid\n video_url = template_url.format(course_id, vid)\n print(\"开始学习 {} 视频\".format(video_title))\n select_video(course_id, vid)\n while True:\n if video_finished(course_id, vid, course_name, video_title):\n show_time()\n print(\"{} 视频学习完毕\".format(video_title))\n sleep(1)\n break\n else:\n post(update_time_api, headers=header, cookies=cookie,\n data={'elsSign': cookie['eln_session_id']}, timeout=(15, 15))\n sleep(180)\n t += 1\n if t > 30:\n print(\"{} 视频学习超时\".format(video_title))\n course_timeout = 1\n break\n completed_video_list = get_completed_video_list(course_id)\n if course_finished(completed_video_list, vid_list):\n show_time()\n success_num += 1\n print(\"《{}》课程全部视频学习完毕\".format(course_name))\n info = \"《{}》课程全部视频学习完毕.学习成功{}门.共{}门.学习进度{}\".format(course_name, success_num, len(course_info_list),\n str(round((success_num+fail_num) / len(course_info_list),\n 4) * 100) + \"%\")\n '''\n msg = MIMEText(info, 'plain', 'utf-8')\n server.sendmail(from_addr, [to_addr], msg.as_string())\n '''\n push_notification(info)\n sleep(1)\n elif course_timeout == 1:\n show_time()\n fail_num += 1\n fail_list.append(course_name)\n course_timeout = 0\n print(\"《{}》课程学习超时\".format(course_name))\n info = \"《{}》课程学习超时\".format(course_name)\n push_notification(info)\n\n\ndef end_study():\n print(\"本次学习结束,共{}门课程\".format(len(course_info_list)))\n print(\"学习成功{}门,学习失败{}门\".format(success_num, fail_num))\n end_info = \"本次学习结束,共{}门课程.学习成功{}门,学习失败{}门,请检查学习失败的课程是否已经完成选课,未进行选课的课程无法学习。\"\\\n .format(len(course_info_list), success_num, fail_num)\n if fail_num > 0:\n print(\"学习失败的课程有{}\".format(fail_list))\n print(\"请检查学习失败的课程是否已经完成选课,未进行选课的课程无法学习。\")\n push_notification(end_info)\n\n\nif __name__ == \"__main__\":\n print(\"课程学分:\" + str(credit_list))\n select_credit = input(\"请输入要学习的课程的学分:\")\n if float(select_credit) not in credit_list:\n print(\"输入错误。告辞\")\n exit(0)\n else:\n print(\"正在打开浏览器...\")\n load_course()\n # driver = webdriver.Firefox()\n options = webdriver.FirefoxOptions()\n options.add_argument('-headless')\n driver = webdriver.Firefox(options=options)\n open_broswer()\n username = input(\"请输入用户名:\")\n password = input(\"请输入密码:\")\n bot_token = input(\"请输入TelegramBotToken: \")\n bot_chatID = input(\"请输入chat_id: \")\n notification_api = notification_api_tmp.format(bot_token, bot_chatID)\n login()\n while not login_ok():\n driver.refresh()\n sleep(2)\n login()\n print(\"登录成功\")\n for c, course_info in enumerate(course_info_list):\n course_line_list = course_info.strip().split(',')\n course_id = course_line_list[-3]\n course_name = course_line_list[-4]\n play_url = template_play_url.format(course_id)\n driver.switch_to.window(driver.window_handles[0])\n driver.get(play_url)\n if c % 100 == 0:\n get_cookie()\n sleep(1)\n print(\"开始学习《{}》:\".format(course_name))\n try:\n is_finished()\n except:\n fail_num += 1\n fail_list.append(course_name)\n print(\"{} 学习失败,请检查《{}》是否已选课!\".format(course_name, course_name))\n info = \"{} 学习失败, 请检查《{}》是否已选课!\".format(course_name, course_name)\n push_notification(info)\n driver.quit()\n end_study()\n","sub_path":"ServerStudyBotTG.py","file_name":"ServerStudyBotTG.py","file_ext":"py","file_size_in_byte":20773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"501353885","text":"def main():\r\n from bioformers.utilize.Bert import BertSeqClassification\r\n from torch.utils.data import DataLoader\r\n from transformers import DataCollatorWithPadding\r\n from pytorch_lightning import Trainer\r\n from pytorch_lightning.loggers import WandbLogger\r\n import os\r\n import warnings\r\n from pytorch_lightning.callbacks import ModelCheckpoint\r\n\r\n from transformers import BertModel, BertTokenizer\r\n import torch\r\n\r\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\r\n os.environ[\"MKL_THREADING_LAYER\"] = \"GNU\"\r\n os.environ[\"TOKENIZERS_PARALLELISM\"] = \"true\"\r\n\r\n #######################################\r\n num_cpu = 16\r\n lr = '6.918e-12'\r\n wandb_name = f\"puffinCaller_classify_domain_1893_with8Functional-{lr}-mxepch24\"\r\n num_labels = 1893\r\n max_epch = 24\r\n gpus = '0, 1, 2, 3'\r\n\r\n data_folder = \"tensor_datasets\"\r\n strat_train_name = \"puffinCaller_with8Functional_balanced_strat_train.pt\"\r\n strat_val_name = \"puffinCaller_with8Functional_balanced_strat_val.pt\"\r\n\r\n model_folder = \"puffinCaller/ckpt\"\r\n save_checkpoint_name = \"puffinCaller_with8Functional_balanced_labels_maxepch24.ckpt\"\r\n\r\n ###-dont need to touch-###\r\n save_checkpoint_path = f\"/mnt/storage/grid/home/eric/hmm2bert/models/{model_folder}/{save_checkpoint_name}\"\r\n strat_train_path = f\"/mnt/storage/grid/home/eric/hmm2bert/data_prep/{data_folder}/{strat_train_name}\"\r\n strat_val_path = f\"/mnt/storage/grid/home/eric/hmm2bert/data_prep/{data_folder}/{strat_val_name}\"\r\n ###\r\n\r\n #######################################\r\n\r\n #load tokenizer and wandb logger\r\n\r\n wandb_logger = WandbLogger(name=wandb_name, project=\"hmm_reBERT\")\r\n tokenizer = BertTokenizer.from_pretrained(\"Rostlab/prot_bert\", do_lower_case=False)\r\n\r\n #load train and test tensors and instantiate pytorch lightning wrapper for the huggingface model with the base pretrained protbert model\r\n\r\n encoded_train = torch.load(strat_train_path)\r\n encoded_test = torch.load(strat_val_path)\r\n bsc = BertSeqClassification(pretrained_dir=\"Rostlab/prot_bert\", use_adafactor=True, num_labels=num_labels)\r\n\r\n #setup checkpoint callback\r\n\r\n checkpoint_callback = ModelCheckpoint(\r\n monitor='val_loss_epoch',\r\n dirpath=f'/mnt/storage/grid/home/eric/hmm2bert/models/{model_folder}',\r\n filename='puffinCaller_with8Functional_balanced_best_loss',\r\n save_top_k=3,\r\n mode='min'\r\n )\r\n\r\n #setup data collator, trainer, and dataloader for train and val dataset\r\n\r\n data_collator = DataCollatorWithPadding(tokenizer=tokenizer)\r\n trainer = Trainer(\r\n max_epochs=max_epch,\r\n gpus=gpus,\r\n auto_lr_find=False,\r\n logger=wandb_logger,\r\n accelerator=\"ddp\",\r\n callbacks=[checkpoint_callback]\r\n )\r\n warnings.filterwarnings(\"ignore\")\r\n\r\n train_dl = DataLoader(encoded_train, batch_size=4, num_workers=num_cpu, collate_fn=data_collator, shuffle=True)\r\n eval_dl = DataLoader(encoded_test, batch_size=4, num_workers=num_cpu, collate_fn=data_collator, shuffle=False)\r\n\r\n #train and save classifier as checkpoint\r\n\r\n trainer.fit(bsc, train_dataloader=train_dl, val_dataloaders=eval_dl)\r\n #trainer.save_checkpoint(save_checkpoint_path)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"scripts/train_classify_domain.py","file_name":"train_classify_domain.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"38071175","text":"import logging\nimport sys\n\nfrom contextlib import contextmanager\n\nLOG = logging.getLogger(__name__)\n\n\nclass Reporter(object):\n\n def __init__(self, name):\n self.name = name\n\n def setup(self):\n logger = logging.getLogger('taas')\n\n ch = logging.StreamHandler(sys.stdout)\n ch.setLevel(logging.DEBUG)\n\n fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n formatter = logging.Formatter(fmt)\n ch.setFormatter(formatter)\n\n logger.setLevel(logging.DEBUG)\n logger.addHandler(ch)\n\n return logger\n\n\n@contextmanager\ndef cleanup(stage):\n try:\n yield\n except (Exception, KeyboardInterrupt):\n LOG.error('Run failed', exc_info=True)\n finally:\n stage.destroy()\n\n\ndef retrieve(client, resource, name, **kwargs):\n director = getattr(client, '%ss' % resource)\n try:\n return director.create(name, **kwargs)\n except Exception:\n LOG.exception('Creation failed')\n sys.exit(1)\n","sub_path":"taas/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"454662445","text":"import secret\nimport platform\nimport os\nfrom selenium import webdriver\nimport time\n\ndriver = webdriver.PhantomJS(executable_path=\"D:/工作/tophatter/phantomjs-2.1.1-windows/bin/phantomjs\")\nprint(123)\ndriver.get(\"https://tophatter.com/\")\n\n# 添加cookie\ncookie_list = {}\nfor part in secret.cookie.split('; '):\n kv = part.split('=', 1)\n # d = {kv[0]: kv[1]}\n cookie_list[kv[0]] = kv[1]\n\nfor item in cookie_list:\n driver.add_cookie({\n 'domain': '.tophatter.com',\n 'name': item,\n 'value': cookie_list[item],\n 'path': '/',\n 'expires': None,\n 'httponly': False,\n 'secure': False,\n })\n# driver.add_cookie(cookie_list)\ndriver.get(\"https://tophatter.com/\")\n\nif not os.path.exists('home_products'):\n os.makedirs('home_products')\n\nwhile True:\n print(driver.page_source)\n time.sleep(15)\n # with open('home_products/{}.html'.format(time.strftime(\"%Y-%m-%d %H.%M.%S\", time.localtime())), 'w', encoding='utf-8') as f:\n # f.write(driver.execute_script(\n # \"return document.documentElement.outerHTML\"))\n print(time.strftime(\"%Y-%m-%d %H.%M.%S\", time.localtime()))\n driver.refresh()\n","sub_path":"4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"305106740","text":"from keras.models import load_model\r\nfrom keras.preprocessing import image\r\nimport numpy as np\r\nfrom os import listdir\r\nfrom os.path import isfile, join\r\n\r\n\r\n# dimensions of our images\r\nimg_width, img_height = 64, 64\r\n\r\n# load the model we saved\r\nmodel = load_model('model.h5')\r\nmodel.compile(loss='binary_crossentropy',\r\n optimizer='adam',\r\n metrics=['accuracy'])\r\n\r\nmypath = \"predict/\"\r\nonlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]\r\nprint(onlyfiles)\r\n\r\n\r\n# predicting images\r\nyes_counter = 0 \r\nno_counter = 0\r\nfor file in onlyfiles:\r\n img = image.load_img(mypath+file, target_size=(img_width, img_height))\r\n x = image.img_to_array(img)\r\n x = np.expand_dims(x, axis=0)\r\n \r\n images = np.vstack([x])\r\n classes = model.predict_classes(images, batch_size=10)\r\n classes = classes[0][0]\r\n \r\n if classes == 0:\r\n print(file + \": \" + 'Congratulations, You dont have brain tumor')\r\n no_counter += 1\r\n else:\r\n print(file + \": \" + 'Sorry, You Have brain bumor')\r\n yes_counter += 1\r\nprint(\"Brain_Tumor_Yes :\",yes_counter)\r\nprint(\"Brain_Tumor_No :\",no_counter)","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"1869997","text":"from django.test import TestCase\n\n# Create your tests here.\nfrom blog.forms import CommentForm, BloggerSignUpForm, DeleteUserForm\n\n\n\"\"\"\nCOMMENT FORM\n\"\"\"\n\nclass CommentFormTest(TestCase):\n\n def test_commentform_comment_field_label(self):\n form = CommentForm()\n self.assertTrue(\n form.fields['comment'].label == 'Comment' or\n form.fields['comment'].label == None\n )\n\n def test_commentform_comment_valid(self):\n comment = 'This is a comment'\n form = CommentForm(data={'comment': comment})\n self.assertTrue(form.is_valid())\n\n def test_commentform_blank_invalid(self):\n comment = ''\n form = CommentForm(data={'comment': comment})\n self.assertFalse(form.is_valid())\n\n\"\"\"\nBLOGGER SIGN UP FORM\n\"\"\"\n\nclass BloggerSignUpFormTest(TestCase):\n\n \"\"\"\n LABELS\n \"\"\"\n\n def test_signupform_first_name_label(self):\n form = BloggerSignUpForm()\n self.assertTrue(\n form.fields['first_name'].label == 'First name' or\n form.fields['first_name'].label == None\n )\n\n def test_signupform_last_name_label(self):\n form = BloggerSignUpForm()\n self.assertTrue(\n form.fields['last_name'].label == 'Last name' or\n form.fields['last_name'].label == None\n )\n\n def test_signupform_nickname_label(self):\n form = BloggerSignUpForm()\n self.assertTrue(\n form.fields['nickname'].label == 'Nickname' or\n form.fields['nickname'].label == None\n )\n\n def test_signupform_bio_label(self):\n form = BloggerSignUpForm()\n self.assertTrue(\n form.fields['bio'].label == 'Bio' or \n form.fields['bio'].label == None\n )\n\n \"\"\"\n VALIDATION\n \"\"\"\n\n def test_signupform_valid(self):\n form = BloggerSignUpForm(\n data={\n 'first_name': 'John',\n 'last_name': 'Doe',\n 'nickname': 'johnnyboy',\n 'bio': \"John's biography\"\n }\n )\n self.assertTrue(form.is_valid())\n\n\"\"\"\nDELETE USER FORM\n\"\"\"\n\nclass DeleteUserFormTest(TestCase):\n\n \"\"\"\n LABELS\n \"\"\"\n\n def test_deleteuserform_username_label(self):\n form = DeleteUserForm()\n self.assertTrue(\n form.fields['username'].label == 'Username' or\n form.fields['username'].label == None\n \n )\n","sub_path":"blog/tests/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"149077117","text":"\nfrom PyQt4 import QtGui, QtCore\nimport sys, shutil, os\nfrom window import Ui_MainWindow\n\nclass Initial_dialog(QtGui.QWidget):\n def __init__(self):\n QtGui.QWidget.__init__(self)\n layout = QtGui.QGridLayout(self)\n global radio_btn, radio_btn2, radio_btn3\n radio_btn3= QtGui.QRadioButton(\"Search\", self)\n radio_btn = QtGui.QRadioButton(\"Make a new entry\",self)\n radio_btn2 = QtGui.QRadioButton(\"Browse diary\",self)\n radio_btn.setChecked(True)\n layout.addWidget(radio_btn,1,0)\n layout.addWidget(radio_btn2,2,0)\n layout.addWidget(radio_btn3,3,0)\n self.setGeometry(300, 300, 250, 150)\n self.setWindowTitle(\"Example\")\n global btn\n btn = QtGui.QPushButton(\"OK\", self)\n global combobox\n combobox = QtGui.QComboBox(self)\n combobox.insertItem(1, \"Tags\")\n combobox.insertItem(2,\"Titles\")\n layout.addWidget(combobox, 4,1)\n layout.addWidget(btn,5,1)\n global lineedit\n lineedit = QtGui.QLineEdit( self )\n layout.addWidget(lineedit, 4,0)\n lineedit.setMinimumWidth(120)\n lineedit.setPlaceholderText(\"Enter Keyword\")\n combobox.setEnabled(False)\n lineedit.setEnabled(False)\n radio_btn3.toggled.connect(self.enable_widgets)\n radio_btn.toggled.connect(self.btn_text)\n radio_btn2.toggled.connect(self.btn_text)\n btn.pressed.connect(self.check)\n self.show()\n \n def btn_text(self):\n btn.setText(\"OK\")\n combobox.setEnabled(False)\n lineedit.setEnabled(False)\n \n def enable_widgets(self):\n combobox.setEnabled(True)\n lineedit.setEnabled(True)\n btn.setText(\"Search\")\n \n def check(self):\n btnt = radio_btn.isChecked()\n btn2t = radio_btn2.isChecked()\n btn3t = radio_btn3.isChecked()\n if str(btnt) == 'True':\n self.title_dialog = Title_dialog()\n self.close()\n self.title_dialog.show()\n elif str(btn2t) == \"True\":\n self.read_dialog = Readdialog()\n self.close()\n self.read_dialog.show()\n else:\n pass\n \n \n\n\nclass Readdialog(QtGui.QMainWindow):\n def __init__(self):\n QtGui.QWidget.__init__(self)\n global dir2, dir3, dir1\n dir1 = \"/home/slotlocker/random/\"\n self.ui = Ui_MainWindow()\n self.ui.setupUi(self)\n self.ui.listWidget.setMaximumWidth(80)\n self.ui.listWidget.setMaximumHeight(200)\n self.ui.listWidget.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)\n self.setWindowTitle(\"Browse/Edit Diary\")\n \n dir_list = os.listdir(dir1)\n self.ui.listWidget.addItems(dir_list)\n self.ui.listWidget.clicked.connect(self.step2)\n def step2(self):\n selected_item = self.ui.listWidget.selectedItems()\n dir_selected = selected_item[0].text()\n global dir2\n dir2 = dir1 + dir_selected + \"/\"\n global column2\n column2 = QtGui.QListWidget()\n column2.setAlternatingRowColors(True)\n column2.setMaximumWidth(80)\n column2.setMaximumHeight(200)\n column2.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)\n self.ui.gridLayout.addWidget(column2,0,1)\n dir_list = os.listdir(dir2)\n column2.addItems(dir_list)\n column2.clicked.connect(self.step3)\n def step3(self):\n selected_item = column2.selectedItems()\n dir_selected = selected_item[0].text()\n global dir3\n dir3 = dir2 + dir_selected + \"/\"\n global column3\n column3 = QtGui.QListWidget()\n column3.setAlternatingRowColors(True)\n column3.setMaximumWidth(80)\n column3.setMaximumHeight(200)\n column3.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)\n self.ui.gridLayout.addWidget(column3,0,2)\n dir_list = os.listdir(dir3)\n column3.addItems(dir_list)\n column3.clicked.connect(self.step4)\n def step4(self):\n global textarea1, textarea2\n textarea1 = QtGui.QTextEdit()\n textarea2 = QtGui.QTextEdit()\n self.ui.gridLayout.addWidget(textarea1,0,3)\n textarea1.setMinimumWidth(300)\n textarea1.setMinimumHeight(200)\n textarea1.setMaximumHeight(200)\n self.ui.gridLayout.setColumnStretch(3,100)\n self.ui.gridLayout.addWidget(textarea2,1,0,1,4)\n textarea2.setMinimumHeight(320)\n selected_item = column3.selectedItems()\n global file_selected\n file_selected = selected_item[0].text()\n file_path = dir3 + file_selected + \"/diary.html\"\n file_pointer = open(file_path, 'r')\n file_contents = file_pointer.read()\n textarea2.setText(file_contents)\n file_pointer.close()\n textarea2.setAcceptRichText(True)\n textarea2.setReadOnly(True)\n global title_file\n title_file = dir3 + file_selected + \"/title.txt\"\n file_pointer = open(title_file, \"r\")\n title = file_pointer.read()\n file_pointer.close()\n textarea1.setText(title)\n global button1\n button1 = QtGui.QPushButton(\"Edit\")\n self.ui.gridLayout.addWidget(button1, 2,2)\n button1.setSizePolicy(QtGui.QSizePolicy.Fixed,QtGui.QSizePolicy.Fixed)\n global button2\n button2 = QtGui.QPushButton(\"Save\")\n self.ui.gridLayout.addWidget(button2, 2,3)\n button2.setSizePolicy(QtGui.QSizePolicy.Fixed,QtGui.QSizePolicy.Fixed)\n button2.setEnabled(False)\n button1.pressed.connect(self.edit)\n\n def edit(self):\n button1.setEnabled(False)\n textarea2.setReadOnly(False)\n textarea2.setAcceptRichText(True)\n button2.setEnabled(True)\n button2.pressed.connect(self.save_exit)\n\n def save_exit(self):\n file_path = dir3+ file_selected + \"/\" + \"diary.html\"\n file_pointer = open(file_path,\"w\")\n file_contents = textarea2.toHtml()\n file_pointer.write(file_contents)\n file_pointer.close()\n button1.setEnabled(True)\n button2.setEnabled(False)\n\n\n\n\n\nclass Title_dialog(QtGui.QWidget):\n def __init__(self):\n QtGui.QWidget.__init__(self)\n self.setWindowTitle(\"Title\")\n self.layout_e = QtGui.QGridLayout(self)\n self.label_e = QtGui.QLabel(\"Title helps organise the diary better.\",self)\n self.lineedit_e = QtGui.QLineEdit(self)\n self.lineedit_e.setSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Preferred)\n self.lineedit_e.setPlaceholderText(\"Enter Title here\")\n self.btn_e = QtGui.QPushButton(\"Proceed\",self)\n self.btn_e.setEnabled(False)\n self.btn_e.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)\n self.layout_e.addWidget(self.label_e,1,0)\n self.layout_e.addWidget(self.lineedit_e,2,0,1,0)\n self.layout_e.addWidget(self.btn_e,3,1)\n QtCore.QObject.connect(self.lineedit_e, QtCore.SIGNAL(\"textChanged(QString)\"), self.enable_btn)\n #self.btn_e.pressed.connect(self.next_step)\n self.show()\n\n def enable_btn(self):\n chars = len(self.lineedit_e.text())\n if chars != 0:\n self.btn_e.setEnabled(True)\n else:\n self.btn_e.setEnabled(False)\n \n## def next_step(self):\n## self.edit_dialog = Edit_dialog()\n## self.close()\n## self.edit_dialog.show()\n \n\n#class Edit_dialog():\n\ndef main():\n app = QtGui.QApplication(sys.argv)\n ex = Initial_dialog()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n main()\n","sub_path":"try.py","file_name":"try.py","file_ext":"py","file_size_in_byte":7670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"495879048","text":"from aiohttp.web import middleware\nfrom aiohttp_session import get_session\nfrom ioa.database import DatabaseContext\nfrom models import UserDAO\nfrom view.model.user import AnonymousUser, User\nfrom aiohttp.web import middleware\nimport time\nimport logging\n\n@middleware\nasync def caculate_execute_time_middleware(request, handler):\n start = time.time()\n request['request_began_at'] = time.time()\n request['now'] = lambda: time.time()\n response = await handler(request)\n request['executed_time'] = time.time() - start\n # logging.info(\"request duration %.4f\" % (time.time() - start, ))\n return response\n\n@middleware\nasync def user_middleware(request, handler):\n logging.info(\"executing middleware user\")\n session = request['session']\n\n if 'user_id' in session:\n user_id = session['user_id']\n async with DatabaseContext.default.engine.acquire() as connection:\n dao = UserDAO(connection)\n user_table = await dao.find(user_id)\n if not user_table:\n user = AnonymousUser()\n else:\n user = User()\n user.id = user_table['id']\n user.username = user_table['username']\n else:\n user = AnonymousUser()\n request['user'] = user\n print(2)\n # print(request['aiohttp_jinja2_context'])\n # request['aiohttp_jinja2_context'].update(user = user)\n request['aiohttp_jinja2_context'] = {\n 'user': user,\n 'request': request\n }\n response = await handler(request)\n return response\n\n@middleware\nasync def session_to_request_middleware(request, handler):\n session = await get_session(request)\n request['session'] = session\n \n return await handler(request)\n\ndef setup_middleware(app):\n app.middlewares.append(session_to_request_middleware)\n app.middlewares.append(user_middleware)\n # app.middlewares.append(caculate_execute_time_middleware)\n pass","sub_path":"middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"1829250","text":"\n#!/usr/bin/env python3\n# -*- encoding: utf-8 -*-\n\nfrom argparse import ArgumentParser\n\nclass InputParser:\n \"\"\"\n This class is used to define behaviour based on user input.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initializes default parsers.\n \"\"\"\n self.__parser = ArgumentParser()\n subparsers = self.__parser.add_subparsers(dest='command')\n self.__add_version_parser(subparsers)\n self.__add_status_parser(subparsers)\n self.__add_flow_parser(subparsers)\n\n\n def parse(self):\n result = self.__parser.parse_args()\n if result.command == 'version':\n print('version')\n return\n\n if result.command == 'status':\n print('status')\n return\n\n if result.command == 'flow':\n print('flow')\n return\n\n\n def __add_version_parser(self, parser: ArgumentParser):\n _ = parser.add_parser('version',\n help='Shows current version.')\n\n\n def __add_status_parser(self, parser: ArgumentParser):\n _ = parser.add_parser('status',\n help='Shows current project status.')\n\n\n def __add_flow_parser(self, parser: ArgumentParser):\n push_parser = parser.add_parser('flow',\n help='It starts a process of pre-deployment for current changes.')\n push_parser.add_argument('-b',\n action='store_true',\n help='Increments current build number for all targets.')\n push_parser.add_argument('-p',\n action='store_true',\n help='Pushes changes to remote repository.')\n push_parser.add_argument('-t',\n action='store_true',\n help='Adds tag to current commit.')\n push_parser.add_argument('-v',\n action='store',\n help='Updates application version to provided one.',\n type=str)\n","sub_path":"juicer/utilities/argparser.py","file_name":"argparser.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"615462007","text":"from django.conf.urls import url, include\nfrom . import views\nimport debug_toolbar\n\nurlpatterns = [\n\turl(r'^$', views.MainPageAuth.as_view(), name='main'),\n\turl(r'^my_profile/(?P[0-9]+)/$', views.MyProfile.as_view(), name='my_profile'),\n\turl(r'^new', views.NewPublication.as_view(), name='new'),\n\turl(r'^publication/(?P[0-9]+)/$', views.FullPublication.as_view(), name='full'),\n\turl(r'^publication/(?P[0-9]+)/edit/$', views.EditPublication.as_view(), name='edit'),\n\turl(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}),\n\turl(r'^delete/$', views.delete, name='delete'),\n\turl(r'^edit/(?P[0-9]+)/$', views.edit, name='edit_profile'),\n\turl(r'^search/$', views.search, name='search'),\n\turl(r'^rating/$', views.rating, name='rating'),\n\turl(r'^my_profile/(?P[0-9]+)/accept/(?P\\w+)/$', views.accept, name='accept'),\n\turl(r'^debug/', include(debug_toolbar.urls)),\n]","sub_path":"multiblog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"363558561","text":"\"\"\"Offer time listening automation rules.\"\"\"\nimport logging\n\nimport voluptuous as vol\n\nfrom homeassistant.const import CONF_PLATFORM\nfrom homeassistant.core import callback\nfrom homeassistant.helpers import config_validation as cv\nfrom homeassistant.helpers.event import async_track_time_change\n\n# mypy: allow-untyped-defs, no-check-untyped-defs\n\nCONF_HOURS = \"hours\"\nCONF_MINUTES = \"minutes\"\nCONF_SECONDS = \"seconds\"\n\n_LOGGER = logging.getLogger(__name__)\n\nTRIGGER_SCHEMA = vol.All(\n vol.Schema(\n {\n vol.Required(CONF_PLATFORM): \"time_pattern\",\n CONF_HOURS: vol.Any(vol.Coerce(int), vol.Coerce(str)),\n CONF_MINUTES: vol.Any(vol.Coerce(int), vol.Coerce(str)),\n CONF_SECONDS: vol.Any(vol.Coerce(int), vol.Coerce(str)),\n }\n ),\n cv.has_at_least_one_key(CONF_HOURS, CONF_MINUTES, CONF_SECONDS),\n)\n\n\nasync def async_attach_trigger(hass, config, action, automation_info):\n \"\"\"Listen for state changes based on configuration.\"\"\"\n hours = config.get(CONF_HOURS)\n minutes = config.get(CONF_MINUTES)\n seconds = config.get(CONF_SECONDS)\n\n # If larger units are specified, default the smaller units to zero\n if minutes is None and hours is not None:\n minutes = 0\n if seconds is None and minutes is not None:\n seconds = 0\n\n @callback\n def time_automation_listener(now):\n \"\"\"Listen for time changes and calls action.\"\"\"\n hass.async_run_job(\n action, {\"trigger\": {\"platform\": \"time_pattern\", \"now\": now}}\n )\n\n return async_track_time_change(\n hass, time_automation_listener, hour=hours, minute=minutes, second=seconds\n )\n","sub_path":"homeassistant/components/automation/time_pattern.py","file_name":"time_pattern.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"354715671","text":"import os\nimport sys\n\nfrom telethon import TelegramClient\nfrom telethon.tl.types import InputMessagesFilterPhotos\nfrom telethon.tl.types import InputMessagesFilterPhotoVideo\nimport socks\nimport async_timeout\n\nproxy = (socks.SOCKS5, \"localhost\", 1080)\napi_id = 123456789\napi_hash = \"17cbxxxxxxxx6ec8d79ba5f1031ee\"\nclient = TelegramClient('anon', api_id, api_hash, proxy=proxy).start()\n\n\nasync def video():\n messages = await client.get_messages(url, None, filter=InputMessagesFilterPhotoVideo)\n for video_ in messages:\n filename = video_path + \"/\" + str(video_.id) + \".mp4\"\n await client.download_media(video_, filename)\n\n\nasync def photo():\n messages = await client.get_messages(url, None, filter=InputMessagesFilterPhotos)\n for photos in messages:\n filename = img_path + \"/\" + str(photos.id) + \".jpg\"\n await client.download_media(photos, filename)\n client.disconnect()\n\n\nif sys.argv[1] == \"i\":\n url = input(\"输入TG频道的链接:\")\n img_path = \"./img\"\n os.mkdir(\"./img\")\n with client:\n client.loop.run_until_complete(photo())\nelif sys.argv[1] == \"v\":\n url = input(\"输入TG频道的链接:\")\n video_path = \"./video\"\n os.mkdir(\"./video\")\n with client:\n client.loop.run_until_complete(video())\n","sub_path":"telegram_download.py","file_name":"telegram_download.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"650644619","text":"'''\n\"INTEL CONFIDENTIAL\nCopyright 30-11-2012 Intel Corporation All Rights Reserved.\nThe source code contained or described herein and all documents related to the source code (\"Material\") are owned by Intel Corporation or its suppliers or\nlicensors.\nTitle to the Material remains with Intel Corporation or its suppliers and licensors.\nThe Material may contain trade secrets and proprietary and confidential information of Intel Corporation and its suppliers and licensors,\nand is protected by worldwide copyright and trade secret laws and treaty provisions.\nNo part of the Material may be used, copied, reproduced, modified, published, uploaded, posted, transmitted, distributed, or disclosed in any way without\nIntel's prior express written permission.\nNo license under any patent, copyright, trade secret or other intellectual property right is granted to or conferred upon you by disclosure or delivery\nof the Materials, either expressly, by implication, inducement, estoppel or otherwise.\nAny license under such intellectual property rights must be express and approved by Intel in writing.\nInclude any supplier copyright notices as supplier requires Intel to use.\nInclude supplier trademarks or logos as supplier requires Intel to use, preceded by an asterisk. An asterisked footnote can be added as follows:\n*Third Party trademarks are the property of their respective owners.\nUnless otherwise agreed by Intel in writing, you may not remove or alter this notice or any other notice embedded in Materials by Intel or Intel's suppliers\nor licensors in any way.\"\n'''\n\nimport os\nimport shutil\nimport platform\nimport logging\nimport re\n\nimport checks\nimport consts\nimport wrappers.wrapper as wrapper\nfrom utils import join, exec_with_timeout, rm_tree\n\nlog = logging.getLogger(__name__)\n\n\nUNEXPECTED = \"Unexpected extensions\"\n\napi_names = ['OCL_VERSION_1_0 API', 'OCL_VERSION_1_1 API', 'OCL_VERSION_1_2 API', 'OGL_VERSION_1_0 API',\n 'OGL_VERSION_1_1 API', 'OGL_VERSION_1_2 API', 'OGL_VERSION_1_3 API', 'OGL_VERSION_1_4 API',\n 'OGL_VERSION_1_5 API', 'OGL_VERSION_2_0 API', 'OGL_VERSION_2_1 API', 'OGL_VERSION_3_0 API',\n 'OGL_VERSION_3_1 API', 'OGL_VERSION_3_2 API', 'OGL_VERSION_3_3 API', 'OGL_VERSION_4_0 API',\n 'OGL_VERSION_4_1 API', 'OGL_VERSION_4_2 API', 'OGL_VERSION_4_3 API', 'OGL_VERSION_4_4 API']\n\n\ndef parse_api_functions(filename):\n lines = (open(filename, 'r')).readlines()\n ocl_version_1_0_api = {}\n ocl_version_1_1_api = {}\n ocl_version_1_2_api = {}\n ogl_version_1_0_api = {}\n ogl_version_1_1_api = {}\n ogl_version_1_2_api = {}\n ogl_version_1_3_api = {}\n ogl_version_1_4_api = {}\n ogl_version_1_5_api = {}\n ogl_version_2_0_api = {}\n ogl_version_2_1_api = {}\n ogl_version_3_0_api = {}\n ogl_version_3_1_api = {}\n ogl_version_3_2_api = {}\n ogl_version_3_3_api = {}\n ogl_version_4_0_api = {}\n ogl_version_4_1_api = {}\n ogl_version_4_2_api = {}\n ogl_version_4_3_api = {}\n ogl_version_4_4_api = {}\n\n api_dicts = [ocl_version_1_0_api, ocl_version_1_1_api, ocl_version_1_2_api, ogl_version_1_0_api,\n ogl_version_1_1_api, ogl_version_1_2_api, ogl_version_1_3_api, ogl_version_1_4_api,\n ogl_version_1_5_api, ogl_version_2_0_api, ogl_version_2_1_api, ogl_version_3_0_api,\n ogl_version_3_1_api, ogl_version_3_2_api, ogl_version_3_3_api, ogl_version_4_0_api,\n ogl_version_4_1_api, ogl_version_4_2_api, ogl_version_4_3_api, ogl_version_4_4_api]\n\n for i in range(0, len(api_names)):\n create_api_functions_dict(api_names[i], api_dicts[i], lines)\n\n for i in range(0, len(api_dicts)):\n # testing support for current API functions\n for name, is_supported_info in api_dicts[i].iteritems():\n # tested function not supported\n if is_supported_info == 'NOT':\n # case failed\n log.info('From %s not supported function: %s' % (api_names[i], name))\n else:\n # case passed\n continue\n return api_dicts\n\n\ndef create_api_functions_dict(api_string, api_dict, diag_lines):\n count = 0\n for i in range(0, len(diag_lines)):\n if 'GL Extensions string:' in diag_lines[i]:\n break\n if api_string in diag_lines[i]:\n count = i + 1\n break\n while not diag_lines[count].strip() == '' and count != 0 and not '_VERSION' in diag_lines[count]:\n api_dict.update({diag_lines[count].split()[0]: diag_lines[count].split()[1]})\n count += 1\n\n\ndef parse_pixel_formats(filename):\n f = open(filename, 'r')\n lines = f.readlines()\n pixel_formats_found = False\n pixel_formats_number = ''\n pixel_formats_content = []\n\n count = 0\n for line in lines:\n if 'pixel formats' in line:\n pixel_formats_found = True\n #print 'Found pixel formats in line: ' + str(count)\n for c in line:\n if c.isdigit():\n pixel_formats_number += c\n pixel_formats_number = int(pixel_formats_number)\n\n # acquire the number of the first line containing pixel format data\n count += 1\n break\n count += 1\n\n if not pixel_formats_found:\n log.info('Unknown number of pixel formats. Exiting..')\n f.close()\n return\n\n log.info('Found ' + str(pixel_formats_number) + ' pixel formats.')\n log.info('Parsing...')\n\n #print 'Pixel format header line: ' + str(count)\n pixel_formats_header = lines[count]\n #print pixel_formats_header\n\n count += 1\n #print 'Pixel format data start line: ' + str(count)\n #print 'Pixel format data end line: ' + str(count + pixel_formats_number)\n\n keys_list = pixel_formats_header.split('|')\n for k in range(0, len(keys_list)):\n keys_list[k] = keys_list[k].strip()\n #print keys_list[k]\n\n #extract the actual pixel formats data\n pixel_formats_list = []\n for i in range(count, count + pixel_formats_number):\n #read the line containing pixel format values from a file\n content_line = lines[i].rstrip()\n pixel_formats_content.append(content_line)\n\n #extract pixel format values from the line\n pf_values_list = content_line.split('|')\n for v in range(0, len(pf_values_list)):\n pf_values_list[v] = pf_values_list[v].strip()\n\n #create a dictionary containing key-value map of a pixel format\n pf_dict = dict(zip(keys_list, pf_values_list))\n\n #append the dictionary to the list\n pixel_formats_list.append(pf_dict)\n\n log.info('Number of parsed pixel formats: ' + str(len(pixel_formats_content)))\n f.close()\n return pixel_formats_list\n\n\ndef parse_csv(filename):\n pixel_formats_list = []\n for csv_line in [line.strip() for line in open(filename, 'r')]:\n if 'ID' in csv_line:\n keys_list = csv_line.split(',')\n else:\n pixel_formats_list.append(dict(zip(keys_list, csv_line.split(','))))\n log.info('Number of parsed pixel formats: ' + str(len(pixel_formats_list)))\n return pixel_formats_list\n\n\nclass ExtensionGuardTool(wrapper.ExtendedTestTool):\n \"\"\"\n Extension guard wrapper\n \"\"\"\n TEST_TOOL_NAME = \"extension_guard\"\n TEST_LOGS_DIR = \"test_logs\"\n TEST_TOOL_DIR = \"tool\"\n RERUN_TIMEOUTS = False\n REMOVE_CASES = False\n FILES_TO_COPY = []\n FORCE_KILL = False\n FORCE_FLUSH = False\n\n def compare_pixel_formats(self, pattern_pixel_formats_list, tested_pixel_formats_list):\n\n pattern_pf_ids = []\n tested_pf_ids = []\n\n missing_pixel_formats = []\n additional_pixel_formats = []\n\n result = \"\"\n\n #extract a list of pixel formats IDs\n for pattern_pf in pattern_pixel_formats_list:\n pattern_pf_ids.append(pattern_pf[\"ID\"])\n for tested_pf in tested_pixel_formats_list:\n tested_pf_ids.append(tested_pf[\"ID\"])\n\n #find missing and additional pixel_formats_ids\n if not set(pattern_pf_ids) == set(tested_pf_ids):\n\n missing_pixel_formats_ids = set(pattern_pf_ids) - set(tested_pf_ids)\n if not len(missing_pixel_formats_ids) == 0:\n for missing_id in missing_pixel_formats_ids:\n missing_pixel_formats.append(item for item in pattern_pixel_formats_list if item[\"ID\"] == missing_id)\n result += 'Missing pixel formats IDs: ' + str(missing_id) + \"\\n\"\n\n additional_pixel_formats_ids = set(tested_pf_ids) - set(pattern_pf_ids)\n if not len(additional_pixel_formats_ids) == 0:\n for additional_id in additional_pixel_formats_ids:\n additional_pixel_formats.append(item for item in tested_pixel_formats_list\n if item[\"ID\"] == additional_id)\n result += 'Additional pixel formats IDs: ' + str(additional_id) + \"\\n\"\n\n #if there are no differences check if the order is the same\n #it is assumed that there are no duplicates in pixel formats lists\n else:\n for i in range(0, len(pattern_pf_ids)):\n if not pattern_pf_ids[i] == tested_pf_ids[i]:\n result += \"Pixel formats are in different order.\" + \"\\n\"\n\n shared_pixel_formats_ids = set(pattern_pf_ids) & set(tested_pf_ids)\n\n #check if the values of shared pixel formats are the same\n for pf_id in shared_pixel_formats_ids:\n tested_dict = (item for item in tested_pixel_formats_list if item[\"ID\"] == pf_id).next()\n pattern_dict = (item for item in pattern_pixel_formats_list if item[\"ID\"] == pf_id).next()\n\n #check whether the values corresponding to keys are equal for both pixel formats\n res = {\"status\": consts.TC_RESULT_PASS, \"comment\": \"\"}\n for key in list(pattern_dict.keys()):\n if not pattern_dict[key] == tested_dict[key]:\n log.info('Fail in pixel format ID = ' + pf_id + '. Key ' + key +\n ': tested = ' + tested_dict[key] + ', reference = ' + pattern_dict[key])\n result += 'Fail in pixel format ID = ' + pf_id + '. Key ' + key + \\\n ': tested = ' + tested_dict[key] + ', reference = ' + pattern_dict[key] + '\\n'\n res[\"comment\"] += 'Fail in pixel format ID = ' + pf_id + '. Key ' + key + \\\n ': tested = ' + tested_dict[key] + ', reference = ' + pattern_dict[key] + '\\n'\n if res[\"comment\"] != \"\":\n res[\"status\"] = consts.TC_RESULT_FAIL\n res[\"cmd_line\"] = self.cmd_line\n self.update_res(str(pf_id), **res)\n return result\n\n def update_res(self, testcase, **result):\n result[\"time\"] = \"0.001\"\n if self.testcase_allowed(self.TEST_TOOL_NAME + \".\" + testcase):\n self.update_result(testcase, **result)\n else:\n if not self.REMOVE_CASES:\n result[\"status\"] = consts.TC_RESULT_DISB\n self.update_result(testcase, **result)\n log.info(\"%s blocked by white/blacklist settings\" % (self.TEST_TOOL_NAME + \".\" + testcase))\n\n def testcase_allowed(self, testcase):\n \"\"\" Function returns True if given testsuite/testcase combination is allowed by Berta black/whitelist settings \"\"\"\n return len(self.get_limited_tc_list([testcase])) > 0\n\n def get_oglc(self):\n \"\"\" Function getting version of oglconform to be used in tests \"\"\"\n if self.get_arch() == \"android_arm\":\n return \"oglconform_and_arm\"\n if self.get_arch() == \"android_x86\":\n return \"oglconform\"\n\n execSuffix = \"\"\n if platform.system() == \"Windows\":\n execSuffix = \".exe\"\n if \"64\" in os.environ[\"BERTA_OS\"] and checks.get_distro() != \"Android\":\n return \"oglconform\" + execSuffix\n else:\n return \"oglconform\" + execSuffix\n\n def get_arch(self):\n if checks.get_distro() == \"Android\":\n output, ret = exec_with_timeout(\"cat /proc/cpuinfo\", 10, shell=True)\n if not ret:\n if \"ARM\" in output:\n return \"android_arm\"\n else:\n return \"android_x86\"\n else:\n if platform.system() == \"Windows\":\n if \"64\" in os.environ[\"BERTA_OS\"]:\n return \"win_x64\"\n else:\n return \"win_x86\"\n else:\n if platform.system() == \"Linux\":\n if \"64\" in os.environ[\"BERTA_OS\"]:\n return \"lnx_x64\"\n else:\n return \"lnx_x86\"\n else:\n if \"64\" in os.environ[\"BERTA_OS\"]:\n return \"mac_x64\"\n else:\n return \"mac_x86\"\n\n def __init__(self, scen_file, tool_path, task_id, bld_path, conf_file=None):\n wrapper.ExtendedTestTool.__init__(self, scen_file, tool_path, task_id, bld_path, conf_file)\n self.scenario = []\n self.detected_gl_extensions = {}\n self.detected_egl_extensions = {}\n self.detected_caps = {}\n self.expected_values = {}\n self.extensions_file = None\n self.pixelformats_file = None\n self.pixelformats_csv = None\n self.caps_file = None\n self.functions = False\n self.tooldir = \"\"\n self.oglc = \"\"\n self.configs_to_run = []\n\n def prepare_tool(self):\n\n log.info(\"Loading file_obj with scenario names: %s\", self.scen_file)\n with open(self.scen_file, \"r\") as file_obj:\n files_data = file_obj.read().splitlines()\n\n run_parameters = [x.strip() for x in files_data[0].split(\" \")]\n if \"--runBuild\" in run_parameters:\n self.oglconform_dir = self.bld_path\n run_parameters.remove(\"--runBuild\")\n else:\n self.oglconform_dir = self.tool_path + os.sep + \"bin\"\n\n scenario_dir = self.tool_path + os.sep + \"scenarios\" + os.sep\n\n if \"--functions\" in run_parameters:\n run_parameters.remove(\"--functions\")\n self.functions = True\n\n if \"--removeCases\" in run_parameters:\n run_parameters.remove(\"--removeCases\")\n self.REMOVE_CASES = True\n\n if \"--pixelformat\" in run_parameters:\n run_parameters.remove(\"--pixelformat\")\n self.pixelformats_file = scenario_dir + run_parameters[0]\n\n if \"--cap\" in run_parameters:\n run_parameters.remove(\"--cap\")\n self.caps_file = scenario_dir + run_parameters[0]\n\n if \"--ext\" in run_parameters:\n run_parameters.remove(\"--ext\")\n self.extensions_file = scenario_dir + run_parameters[0]\n\n if platform.system() == \"Windows\":\n self.tooldir = os.environ['SYSTEMDRIVE'] + \"\\\\\" + self.TEST_TOOL_DIR\n\n else:\n self.tooldir = \"/data/local/tmp/\" + self.TEST_TOOL_DIR\n\n if os.path.isdir(self.tooldir) and self.TOOLDIR_CLEANUP:\n # remove used test binaries\n log.info(\"Removing local tool directory: %s\", self.tooldir)\n try:\n rm_tree(self.tooldir)\n except(IOError) as why:\n log.error(\"Failed to remove local tool directory: %s\", why)\n\n if not os.path.isdir(self.tooldir):\n # copy test binaries to current directory here\n log.info(\"Copying tools from %s to %s\", self.tool_path + os.sep + \"bin\", self.tooldir)\n try:\n shutil.copytree(self.tool_path + os.sep + \"bin\", self.tooldir)\n except (IOError) as why:\n log.error(\"Failed to copy tool file_obj: %s\", str(why))\n log.error(\"self.tooldir=%s, tool_path=%s\\n\", self.tooldir, self.tool_path)\n exit()\n\n else:\n log.warning(\"Test tool directory %s already exists.\", self.tooldir)\n\n if not os.path.isdir(self.tooldir + os.sep + self.TEST_LOGS_DIR):\n os.mkdir(self.tooldir + os.sep + self.TEST_LOGS_DIR)\n\n if not os.path.isdir(os.getcwd() + os.sep + self.TEST_LOGS_DIR):\n os.mkdir(os.getcwd() + os.sep + self.TEST_LOGS_DIR)\n\n self.oglc = join(self.tooldir, self.get_oglc())\n\n log.info(\" Copying oglconform build from %s to %s.\", join(self.oglconform_dir, self.get_arch(), self.get_oglc()), self.oglc)\n if platform.system() == \"Windows\":\n exec_with_timeout(\"copy \" + join(self.oglconform_dir, self.get_arch(), self.get_oglc()) + \" \" + self.oglc, 5 * 60, shell=True, tracing=True,\n cwd=os.getcwd())\n else:\n exec_with_timeout(\"cp \" + join(self.oglconform_dir, self.get_arch(), self.get_oglc()) + \" \" + self.oglc, 5 * 60, shell=True, tracing=True,\n cwd=os.getcwd())\n exec_with_timeout(\"chmod -R 755 \" + self.oglc, 5 * 60, shell=True, tracing=True, cwd=os.getcwd())\n\n def prepare_scenario(self):\n \"\"\" Reads scenario file_obj and creates test cases list \"\"\"\n\n log.info(\"Preparing scenarios\")\n\n mappings = open(os.path.join(self.tool_path, \"scenarios\", \"configs.txt\")).read().splitlines()\n self.configs_to_run = {}\n for mapping in mappings:\n tokens = mapping.split(\",\")\n self.configs_to_run[tokens[0]] = []\n self.configs_to_run[tokens[0]].extend(tokens[1:])\n\n self.detected_gl_extensions[tokens[0]] = []\n self.detected_egl_extensions[tokens[0]] = []\n self.expected_values[tokens[0]] = {}\n\n expected_configs = set()\n\n current_config = None\n if self.caps_file:\n for caps_line in [line.strip() for line in open(self.caps_file, \"r\")]:\n log.info(caps_line)\n if caps_line.startswith(\"#\"):\n continue\n\n if \":\" in caps_line:\n current_config = caps_line[:-1]\n expected_configs.update([current_config])\n\n if \"=\" in caps_line:\n if \"caps\" not in self.expected_values[current_config]:\n self.expected_values[current_config][\"caps\"] = []\n self.expected_values[current_config][\"caps\"].append(caps_line.strip())\n\n if self.extensions_file:\n for csv_line in [line.strip() for line in open(self.extensions_file, \"r\")]:\n csv_contents = csv_line.split(\";\")\n\n if len(csv_contents) != 2:\n continue\n\n if csv_contents[1] == \"\":\n continue\n\n ext_name = csv_contents[0]\n if ext_name.strip().startswith(\"#\"):\n continue\n\n configs = csv_contents[1].split(\",\")\n expected_configs.update(configs)\n\n for config in configs:\n if config == \"\":\n continue\n if config not in self.configs_to_run:\n continue\n if \"extensions\" not in self.expected_values[config]:\n self.expected_values[config][\"extensions\"] = []\n self.expected_values[config][\"extensions\"].append(ext_name)\n\n keys = self.configs_to_run.keys()\n for k in keys:\n if k not in expected_configs:\n del self.configs_to_run[k]\n\n if self.pixelformats_file or self.functions:\n if checks.is_windows():\n self.configs_to_run[\"wgl\"] = [\"\", \"\"]\n if checks.is_android():\n self.configs_to_run[\"es31\"] = [\" -es3 -ctx es3.1\", \"\"]\n\n if self.pixelformats_file:\n self.pixelformats_csv = parse_csv(self.pixelformats_file)\n self.scenario.append((\"pixelformats\", 120, \"\", False))\n\n self.diag_lines = {}\n self.diag = {}\n for config in self.configs_to_run.keys():\n if platform.system() == \"Windows\":\n try:\n exec_with_timeout(\n self.get_oglc() + \" -diag \" + self.configs_to_run[config][1] + \" > \" + self.TEST_LOGS_DIR + os.sep + \"diag-\" + config + \".log \",\n 60 * 5,\n shell=True,\n tracing=True,\n cwd=self.tooldir\n )\n except IndexError:\n log.exception(\"No Windows commandline found for config %s\" % config)\n else:\n try:\n exec_with_timeout(\n \"./\" + self.get_oglc() + \" -diag \" + self.configs_to_run[config][0] + \" > \" + self.TEST_LOGS_DIR + os.sep + \"diag-\" + config + \".log \",\n 60 * 5,\n shell=True,\n tracing=True,\n cwd=self.tooldir)\n except IndexError:\n log.exception(\"No Android commandline found for config %s\" % config)\n\n shutil.copy2(self.tooldir + os.sep + self.TEST_LOGS_DIR + os.sep + \"diag-\" + config + \".log\", os.getcwd())\n shutil.copy2(self.tooldir + os.sep + self.TEST_LOGS_DIR + os.sep + \"diag-\" + config + \".log\",\n os.getcwd() + os.sep + self.TEST_LOGS_DIR + os.sep + \"diag-\" + config + \".log\")\n self.diag_lines[config] = [l.strip() for l in open(self.tooldir + os.sep + self.TEST_LOGS_DIR + os.sep + \"diag-\" + config + \".log\", \"r\")\n if not l.strip().startswith(\"#\")]\n self.diag[config] = open(self.tooldir + os.sep + self.TEST_LOGS_DIR + os.sep + \"diag-\" + config + \".log\", \"r\").read()\n for line in self.diag_lines[config]:\n if \"OGLconform will exit.\" in line:\n del self.configs_to_run[config]\n continue\n\n for line in self.diag_lines[config]:\n if line.startswith(\"GL Extensions string\"):\n gl_extensions = (line.strip().split(\": \")[1]).split(\" \")\n self.detected_gl_extensions[config] = gl_extensions\n if line.startswith(\"EGL Extensions string\"):\n egl_extensions = (line.strip().split(\": \")[1]).split(\" \")\n self.detected_egl_extensions[config] = egl_extensions\n\n caps_text = open(self.tooldir + os.sep + self.TEST_LOGS_DIR + os.sep + \"diag-\" + config + \".log\", \"r\").read()\n caps_text = re.search(r\"(?:CAPABILITIES)(.*?)\\n{2}\", caps_text, re.S).group(0)\n\n self.detected_caps[config] = [line.strip() for line in caps_text.split(\"\\n\") if \"=\" in line]\n\n self.scenario = []\n\n def run_testing(self):\n detected_gl_flatlist = {}\n for config in self.detected_gl_extensions.keys():\n detected_gl_flatlist[config] = []\n for extension in self.detected_gl_extensions[config]:\n detected_gl_flatlist[config].append(extension)\n\n detected_egl_flatlist = {}\n for config in self.detected_egl_extensions.keys():\n detected_egl_flatlist[config] = []\n for extension in self.detected_egl_extensions[config]:\n detected_egl_flatlist[config].append(extension)\n\n for config in self.configs_to_run.keys():\n if platform.system() == \"Windows\":\n self.cmd_line = self.get_oglc() + \" -diag \" + self.configs_to_run[config][1]\n else:\n self.cmd_line = self.get_oglc() + \" -diag \" + self.configs_to_run[config][0]\n\n if self.extensions_file:\n for ext in self.expected_values[config][\"extensions\"]:\n result = {\"status\": consts.TC_RESULT_PASS}\n\n in_extension_string = False\n\n in_extension_string |= (\"egl\" not in config and ext in detected_gl_flatlist[config])\n in_extension_string |= (\"egl\" in config and ext in detected_egl_flatlist[config])\n\n if not in_extension_string:\n result[\"status\"] = consts.TC_RESULT_FAIL\n result[\"comment\"] = \"Expected extension is not reported\"\n result[\"cmd_line\"] = self.cmd_line\n\n wstring = \"WARNING: Extension %s is reported but its API is NOT COMPLETE.\" % (ext)\n if wstring in self.diag_lines[config]:\n result[\"status\"] = consts.TC_RESULT_FAIL\n result[\"comment\"] = wstring\n result[\"cmd_line\"] = self.cmd_line\n\n self.update_res(config + \".extension.\" + ext, **result)\n\n unexpected_extensions_result = {\"status\": consts.TC_RESULT_PASS}\n\n differences = []\n if config.startswith(\"egl\"):\n differences = (list(set(self.detected_egl_extensions[config]) - set(self.expected_values[config][\"extensions\"])))\n else:\n differences = (list(set(self.detected_gl_extensions[config]) - set(self.expected_values[config][\"extensions\"])))\n\n if len(differences) > 0:\n log_path = config + \"-unexpected.log\"\n unexpected_extensions_result[\"status\"] = consts.TC_RESULT_FAIL\n unexpected_extensions_result[\"comment\"] = str(len(differences)) + \" extensions were found in driver ext string but weren't expected. \" + \\\n \"List of extensions: \" + 'log '\n unexpected_extensions_result[\"cmd_line\"] = self.cmd_line\n log.warning(\"Extensions found in driver extension string but weren't expected (config \" + config + \"): \\n\" + str(differences))\n with open(os.getcwd() + os.sep + log_path, 'w') as file_obj:\n file_obj.write(\"Extensions found in driver extension string but weren't expected (config \" + config + \"): \\n\" + \"\\n\".join(differences))\n\n self.update_res(config + \".extension.\" + UNEXPECTED, **unexpected_extensions_result)\n\n if self.caps_file:\n for cap in self.expected_values[config][\"caps\"]:\n cap_result = {\"status\": consts.TC_RESULT_PASS}\n stripped_cap = cap.strip()\n\n if stripped_cap.endswith(\"*\"):\n stripped_cap = re.escape(stripped_cap[:-1]) + \".*\"\n else:\n stripped_cap = re.escape(stripped_cap)\n cap_regex = re.compile(stripped_cap)\n log.info(\"regex: %s\" % (stripped_cap))\n if not any(cap_regex.match(detected_cap) for detected_cap in self.detected_caps[config]):\n cap_result[\"status\"] = consts.TC_RESULT_FAIL\n cap_result[\"comment\"] = \"Capability not found or incorrect value. Diag log: \" + 'log '\n cap_result[\"cmd_line\"] = self.cmd_line\n else:\n cap_result[\"comment\"] = \"ok\"\n\n self.update_res(config + \".capability.\" + cap.split(\"=\")[0].strip(), **cap_result)\n\n if self.pixelformats_csv:\n parsed_pixel_formats_list_pattern = parse_pixel_formats(self.tooldir + os.sep + self.TEST_LOGS_DIR + os.sep + \"diag-\" + config + \".log\")\n log.info(\"Comparing pixel formats\")\n res = self.compare_pixel_formats(self.pixelformats_csv, parsed_pixel_formats_list_pattern)\n if res == \"\":\n result = {\"status\": consts.TC_RESULT_PASS}\n else:\n result = {\"status\": consts.TC_RESULT_FAIL, \"cmd_line\": self.cmd_line, \"comment\": res}\n self.update_res(\"pixelformats\", **result)\n\n if self.functions:\n api_dicts = parse_api_functions(self.tooldir + os.sep + self.TEST_LOGS_DIR + os.sep + \"diag-\" + config + \".log\")\n for i in range(0, len(api_dicts)):\n function_dict = api_dicts[i]\n api = api_names[i]\n for function_name, function_support in function_dict.items():\n if \"supported\" in function_support:\n result = {\"status\": consts.TC_RESULT_PASS, \"comment\": \"supported\"}\n else:\n result = {\"status\": consts.TC_RESULT_FAIL, \"cmd_line\": self.cmd_line, \"comment\": \"not supported\"}\n self.update_res(api + \".\" + function_name, **result)\n\n if platform.system() == \"Windows\":\n exec_with_timeout(\"del \" + self.oglc, 5 * 60, shell=True, tracing=True, cwd=os.getcwd())\n else:\n exec_with_timeout(\"rm \" + self.oglc, 5 * 60, shell=True, tracing=True, cwd=os.getcwd())\n\nif __name__ == \"__main__\":\n wrapper.run(ExtensionGuardTool)\n","sub_path":"berta/berta/wrappers/extension_guard.py","file_name":"extension_guard.py","file_ext":"py","file_size_in_byte":29182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"17688274","text":"from app.boss_admin_api import bossadminapi\n\nfrom flask import request, g\nimport json\n\nfrom app.models.LoginModel.admin import AdvancedLabel\nfrom app.models.LoginModel.tokens import TokenOA\nfrom app.models.base import db\n\n\n\n@bossadminapi.before_request\ndef apis():\n headers = request.headers.get('Authorization')\n if not headers:\n data = {\n 'status': 401,\n 'message': 'error',\n }\n data = json.dumps(data, default=lambda o: o.__dict__)\n return data, 401, {\"ContentType\": \"application/json\"}\n\n value = TokenOA.verify_password(headers)\n\n if not value:\n data = {\n 'status': 401,\n 'message': 'error',\n }\n data = json.dumps(data, default=lambda o: o.__dict__)\n return data, 401, {\"ContentType\": \"application/json\"}\n elif value.grade < 9:\n data = {\n 'status': 402,\n 'message': 'error',\n }\n data = json.dumps(data, default=lambda o: o.__dict__)\n return data, 402, {\"ContentType\": \"application/json\"}\n g.user_message = value\n\n\n@bossadminapi.route('/boss_admin/advanced_label', methods=['POST'])\ndef boss_admin_advanced_label():\n if request.method == 'POST':\n label = db.session.query(AdvancedLabel).all()\n label = advanced_label_data(label)\n data = {\n 'status': 200,\n 'message': 'ok',\n 'label': label\n\n }\n data = json.dumps(data, default=lambda o: o.__dict__)\n return data, 200, {\"ContentType\": \"application/json\"}\n\ndef advanced_label_data(value):\n lists = []\n for x in value:\n v = {\n 'uid': x.al_uid,\n 'label': x.al_label\n }\n lists.append(v)\n return lists","sub_path":"app/boss_admin_api/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"152035899","text":"#script to complete full processing of DTS files using matching sections.\n#This uses xarray interpolation method to produce a consitently sized output.\n#Robert Law, Scott Polar Research Institute, University of Cambridge, 2020. rl491@cam.ac.uk\n\nimport os\nimport sys\nimport glob\nimport pickle\nimport datetime\nimport numpy as np \nimport pandas as pd\nimport xarray as xr\nimport matplotlib.pyplot as plt \nimport matplotlib.dates as mdates\nfrom scipy.interpolate import interp1d\nfrom dtscalibration import read_silixa_files, DataStore\n\n#change working directory to the location of the python file\nos.chdir(os.path.dirname(sys.argv[0]))\n\n#inputs\nfile_dir1 = \"channel_1\" #input file path 1 (channel 1)\nfile_dir2 = \"channel_3\" #input file path 2 (channel 3)\nexport_dir = \"processed_data\" #export processed data\nexport_file = 'ch1_end_processed.nc' #processed stokes and cummulative attenuation data \navg_time = '6H'\navg_time_float = 6\navg_isel = int(96/6) #this sets the number for averaging \nz_num = 11078 #number of z valus to interpolate to. It's convinient down the line if this is an even number\nusr_gamma = (476.53, 0) \n\n#CHANNEL 1 values below\nint_ref_loc = slice(-22., -5.) #(m) internal reference spool location\nbh_down_ref = 211.94 #(m) downwards start for borehole, determined from apex of temperature drop just after entrance\nbh_up_ref = 2327.90 #(m) upwards end of borehole, determined from apex of temperature drop just before exit\nbh_down_splice = 1267.88 #(m) downwards end of borehole, determined as point where temperature begins to rise (even slightly) before splice\nbh_splice_mid = 1269.41 #(m) determined as the location of peak temperature disturbance from the splice\nbh_up_splice = 1270.92 #(m) upwards start of borehole, determined as point where temperature begins to rise (even slightly) after splice\nbh_depth = 1042.95 #(m) from Sam Doyle BH19c depth email thread\nbh_depth_dts = 1062. #(m) BH19c depth from DTS with refractive index error\nstart_cut = -23. #(m) cut outside the DTS so connector losses do not need to be accounted for\nend_cut = bh_down_splice - 0.5 #bh_up_ref + 100 #(m) cut at the surface\nstart_bh = 204.5 #(m) depth at which borehole begins\ntemp_zone_loc = (1000.*(bh_depth_dts/bh_depth) + start_bh, 1010.*(bh_depth_dts/bh_depth) + start_bh) #location of temperate zone\nmatching_section = (bh_up_splice + bh_down_splice - temp_zone_loc[0], bh_up_splice + bh_down_splice - temp_zone_loc[1]) #set matching section to = reference section (if this doesn't throw an error...)\n\n#constants (i.e. things that definitely won't change unless some seriously strange shit happens)\nT0 = 273.15 #(K) 0 degrees C in Kelvin\nTtr = 273.16 #(K) triple point temperature of water\nptr = 611.73 #(Pa) triple point pressure of water\ng = 9.81 #(m/s^2) gravitational acceleration\n\n#parameters (i.e. things that could change)\nccc = 9.14e-8 #(K/MPa) Clausius-Clapeyron constant \nslope = 0 #(degrees) slope under borehole\nrho_ice = 910 #(kg/m^3) ice density \n\n#obtain paths for directories within channel directorys and create export path\ndirects = [x[0] for x in os.walk(file_dir1)]\ndirects = sorted(directs[1:]) #remove the first value as this is just the parent directory and sort \nexport_path = os.path.join(export_dir, export_file)\n\n#convert to slice\ntemp_zone_loc = slice(temp_zone_loc[0], temp_zone_loc[1]) \nmatching_section = slice(matching_section[1], matching_section[0]) \n\nsections = {\n 'pmpTemperature': [temp_zone_loc]} #pressure melting point \n #'referenceTemperature': [int_ref_loc]} #internal coil\n \n\n#labels\nst_label = 'st'\nast_label = 'ast'\nrst_label = 'rst'\nrast_label = 'rast'\n\ndirects = directs[-2:-1]\n\nfor i, directory in enumerate(directs):\n\n #print out\n files = sorted(glob.glob(os.path.join(directory, '*.xml')))\n now = datetime.datetime.now()\n print(now.strftime(\"%H:%M:%S-\"), 'Processing', str(len(files)), 'files in directory', directory, '...')\n print(directory)\n #sys.exit()\n\n #create datastore\n ds_in = read_silixa_files(\n directory = directory,\n timezone_netcdf='UTC',\n file_ext='*.xml')\n\n #obtain channel information\n #xml_name = ds_in['filename'].values[0]\n #channel = int(xml_name[8])\n\n #cut to section of interest\n ds_in = ds_in.sel(x = slice(start_cut, end_cut))\n\n #extract z values\n #array dimensions: (z,y,x) = (data_fields, z, t)\n z_values = ds_in.x.values\n\n #Clausius-Clapeyron calculation\n p_ice = rho_ice*g*((z_values - start_bh)*(bh_depth/bh_depth_dts))*np.cos(np.deg2rad(slope))\n T_pmp_cc = Ttr - ccc*(p_ice - ptr)\n T_pmp_cc_rz = T_pmp_cc[np.argmax(z_values > ((temp_zone_loc.start+temp_zone_loc.stop)/2))] - T0 #reference zone temperature\n\n #create time series for ref_pmp_T\n nd_cols = np.size(ds_in['st'].values,1) #columns in array\n ds_in['pmpTemperature'] = (('time',), np.ones(nd_cols)*T_pmp_cc_rz)\n\n #set sections\n ds_in.sections = sections\n\n #resample before calibration\n ds_in = ds_in.resample_datastore(how='mean', time=avg_time, keep_attrs=True)\n\n ds_in.acquisitionTime = avg_time_float*60*60\n\n #extract t values\n t_values = ds_in.time.values\n\n #interpolate if needed \n if len(z_values) != z_num:\n\n #create z values for interpolation\n zi = np.linspace(z_values[0], z_values[-1], z_num)\n\n #interp datastore\n ds_in = ds_in.interp(x = zi, method='slinear')\n\n #set z_values for outgoing dataset\n z_values = zi\n\n #obtain variance\n st_var, resid = ds_in.variance_stokes(st_label=st_label)\n ast_var, _ = ds_in.variance_stokes(st_label=ast_label)\n rst_var, _ = ds_in.variance_stokes(st_label=rst_label)\n rast_var, _ = ds_in.variance_stokes(st_label=rast_label)\n\n now = datetime.datetime.now()\n print(now.strftime(\"%H:%M:%S-\"), 'Performing calibration...')\n\n #perform calibration\n ds_in.calibration_double_ended(\n st_var=st_var,\n ast_var=ast_var,\n rst_var=rst_var,\n rast_var=rast_var,\n method='wls',\n solver='sparse',\n fix_gamma=usr_gamma)\n #transient_asym_att_x=[bh_splice_mid],\n #matching_sections=[(temp_zone_loc, matching_section, True)])\n\n #confidence intervals\n #ds_in.conf_int_double_ended(\n # p_val='p_val',\n # p_cov='p_cov',\n # st_var=st_var,\n # ast_var=ast_var,\n # rst_var=rst_var,\n # rast_var=rast_var,\n # store_tempvar='_var',\n # conf_ints=[2.5, 50., 97.5],\n # mc_sample_size=5000,\n # store_ta='talpha') # <- choose a much larger sample size\n\n #averaging (see example 2. https://github.com/dtscalibration/python-dts-calibration/blob/master/examples/notebooks/16Averaging_temperatures.ipynb)\n ds_in.average_double_ended(\n st_var=st_var,\n ast_var=ast_var,\n rst_var=rst_var,\n rast_var=rast_var,\n conf_ints=[2.5, 97.5],\n mc_sample_size=5000, # <- choose a much larger sample size\n ci_avg_time_flag1=False,\n ci_avg_time_flag2=True,\n ci_avg_time_isel=np.arange(len(ds_in.time.values) - avg_isel, len(ds_in.time.values), 1),\n ci_avg_time_sel=None)\n\n print('creating outgoing array...')\n print(ds_in)\n\n #creat DataSet. Setting z coord here results in lots of errors, so it is input after the loop\n print('tmpw_central')\n tmpw_avg_array = ds_in.tmpw_avg2\n print(tmpw_avg_array.values)\n tmpw_avg = tmpw_avg_array.values\n print('tmpw_25')\n tmpw_25_array = ds_in.tmpw_mc_avg2.isel(CI=0)\n tmpw_25 = tmpw_25_array.values\n print('tmpw_975')\n tmpw_975_array = ds_in.tmpw_mc_avg2.isel(CI=1)\n tmpw_975 = tmpw_975_array.values\n\n #remove nans and outlying values\n print('remove nans')\n tmpw_25[np.isnan(tmpw_25)] = 30\n tmpw_avg[np.isnan(tmpw_avg)] = 30\n tmpw_975[np.isnan(tmpw_975)] = 30\n\n print('remove outliers')\n tmpw_25[(tmpw_25 > 20) | (tmpw_25 < -30)] = 30\n tmpw_avg[(tmpw_avg > 20) | (tmpw_avg < -30)] = 30\n tmpw_975[(tmpw_975 > 20) | (tmpw_975 < -30)] = 30\n\n ds = xr.Dataset(\n data_vars = { 'tmpw_25':(('z'), tmpw_25),\n 'tmpw':(('z'), tmpw_avg),\n 'tmpw_975':(('z'), tmpw_975)})\n\n print(ds)\n #ds['tmpw_central'].isel(t=-1).plot(linewidth=0.7, figsize=(12, 8))\n #plt.show()\n\n #concatenate DataArray if not first loop iteration\n if i == 0:\n\n ds_out = ds\n\n else: \n\n print(ds_out)\n print(ds)\n #ds_out = xr.merge([ds_out, ds])\n ds_out = xr.concat([ds_out, ds], dim = 't')\n\n#put in z coords\nds_out.coords['z'] = z_values\n\nprint(ds_out)\n\n#save output\nds_out.to_netcdf(export_path)\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\n\n\n\n\n\n\n","sub_path":"2_end_profile.py","file_name":"2_end_profile.py","file_ext":"py","file_size_in_byte":8892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"3829020","text":"import nltk\r\nfrom nltk.tokenize import RegexpTokenizer\r\n\r\ndef percentageOfwords(text):\r\n \r\n count=0\r\n \r\n sentences = nltk.sent_tokenize(text)\r\n no_of_sen = len(sentences)\r\n\r\n tokenizer = RegexpTokenizer(r'\\w+')\r\n words = tokenizer.tokenize(text)\r\n no_of_words = len(words)\r\n #print no_of_words\r\n \r\n for word in words:\r\n if len(word) >= 6:\r\n count+=1\r\n\r\n #print count\n if no_of_words != 0:\r\n return float(count*100)/no_of_words\n else:\n return 0.5;\r\n \r\n","sub_path":"Software/Software/percentageOfWordsWithSixAndMoreLetters.py","file_name":"percentageOfWordsWithSixAndMoreLetters.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"75416649","text":"cities = {\n 'philadelphia' : {\n 'country': 'united states',\n 'population' : 1.5,\n 'fact': 'The Declaration of Independence was signed here.',\n },\n 'london' : {\n 'country': 'england',\n 'population' :8.53,\n 'fact': 'Westminster Abbey, a monastery was founded here in 960, ' +\n ' has been used for coronations since 1066.',\n },\n 'paris' : {\n 'country': 'france',\n 'population' : 2.224,\n 'fact': 'The city is the location of the Eiffel Tower.',\n },\n}\n\nfor city, info in sorted(cities.items()):\n\n print(city.title() + \" is located in \" + info['country'].title() + \".\")\n print(\"\\tIt's population is \" + str(info['population']) + \" million.\")\n print(\"\\t\" + info['fact'])","sub_path":"ch6/cities.py","file_name":"cities.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"404925934","text":"#!/usr/bin/env python\n'''\nCopyright (c) 2015 Jared E. Stroud\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 furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies 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\nTHE SOFTWARE.\n\n'''\n\ntry:\n import socket\n import os\n import sys\n import argparse\n import time\nexcept ImportError as err:\n print(\"[Error] I don't have \" + str(err))\n\nclass sendData():\n \n '''\n Name: __init__\n Parameters: self\n Purpose: Initializes socket for the rest of the methods.\n '''\n def __init__(self):\n self.sock = socket.socket()\n\n '''\n Name: sendFile\n Parameters: fileName\n '''\n def sendFile(self, fileName, address, port):\n self.sock.connect((str(address), int(port)))\n data = open(fileName, \"rb\")\n\n while True:\n chunk = file.read(data)\n if not chunk:\n break # Entire file has been read in.\n self.sock.sendall(chunk)\n\n '''\n Name: copyFile\n Parameters: srcFile , destination\n srcFile: File desired to be transfered.\n destination: End point for file being transfered.\n Return: Nothing.\n '''\n def copyFile(self, srcFile, destination):\n try:\n os.path.join(str(fileName), str(destination))\n except Error:\n print(\"[Error] I could not copy the file\")\n sys.exit()\n\n\n\nif __name__ == \"__main__\":\n\n print(\"Starting Data send\")\n sendObj = sendData()\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--fileName\", required=True, type=str, help=\"Specify file to be sent.\")\n parser.add_argument(\"--address\", required=True, type=str, help=\"Specify the address to send the file to.\")\n parser.add_argument(\"--port\", required=True, type=int, help=\"Specify the port of th destination server.\")\n args = parser.parse_args()\n\n if args.fileName and args.address and args.port: # Ensuring all arguments are fulfilled.\n address = args.address# User specified file size.\n fileName = args.fileName # User specified file name.\n port = args.port # User specified port.\n\n sendObj.sendFile(fileName, address, port)\n","sub_path":"lib/pipeData.py","file_name":"pipeData.py","file_ext":"py","file_size_in_byte":3073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"567879336","text":"import datetime\nimport requests\n\n################################################################################\n# Config\nHASS_API_PASSWORD = \"{{homeassistant_http.api_password}}\"\nHASS_HOST = \"http://0.0.0.0:{{homeassistant_port}}\"\nPROMETHEUS_HOST = \"http://0.0.0.0:{{prometheus_port}}\"\nDEBUG = True\n\n################################################################################\n# Utility Functions\n\n\ndef debug(msg):\n if DEBUG:\n print(msg)\n\n\ndef create_sensor(sensor_type, sensor_name, payload):\n debug(\"Making API call to Homeassistant to install sensor {0}.{1}\".format(sensor_type, sensor_name))\n headers = {\"x-ha-access\": HASS_API_PASSWORD, \"Content-Type\": \"application/json\"}\n url = \"{0}/api/states/{1}.{2}\".format(HASS_HOST, sensor_type, sensor_name)\n resp = requests.post(url, json=payload, headers=headers, timeout=2)\n debug(\"DONE ({0})\".format(resp))\n\n\n################################################################################\n# SENSORS\ndebug(\"Fetching sensors from prometheus...\")\nresp = requests.get(PROMETHEUS_HOST + \"/api/v1/query?query={homeassistant='yes'}\", timeout=2)\n\ndebug(\"Adding sensors from homeassistant...\")\ndata = resp.json()['data']['result']\nfor item in data:\n sensor_type = item['metric'].get(\"homeassistant_sensor_type\", \"sensor\")\n sensor_state = item['value'][1]\n if sensor_type == \"binary_sensor\":\n sensor_state = \"on\" if int(sensor_state) >= 1 else \"off\"\n payload = {\n \"state\": \"{}\".format(sensor_state),\n \"attributes\": {\n \"friendly_name\": item['metric']['__name__'],\n \"source\": \"prometheus\",\n \"type\": \"prometheus-sensor\",\n \"timestamp\": item['value'][0]\n }\n }\n create_sensor(sensor_type, item['metric']['__name__'], payload)\n\n\n################################################################################\n# ALERTS\ndebug(\"Fetching alerts from prometheus...\")\nresp = requests.get(PROMETHEUS_HOST + \"/api/v1/rules\", timeout=2)\ndata = resp.json()['data']\n\ndebug(\"Adding alerts as sensors from homeassistant...\")\naggregate_state = \"on\"\ntimestamp = datetime.datetime.now().timestamp()\nfor group in data['groups']:\n for rule in group['rules']:\n if len(rule['alerts']) > 0:\n rule_alerts = rule['alerts'][0]['state']\n else:\n rule_alerts = None\n\n if rule_alerts:\n sensor_state = \"off\"\n aggregate_state = \"off\"\n else:\n sensor_state = \"on\"\n\n sensor_name = rule['name'].replace(\".\", \"_\").replace(\"-\", \"_\")\n payload = {\n \"state\": \"{}\".format(sensor_state),\n \"attributes\": {\n \"friendly_name\": sensor_name,\n \"source\": \"prometheus\",\n \"type\": \"prometheus-alert\",\n \"timestamp\": timestamp\n }\n }\n create_sensor(\"binary_sensor\", sensor_name, payload)\n\ndebug(\"Adding aggregate alert sensor to homeassistant...\")\npayload['state'] = aggregate_state\npayload['attributes']['friendly_name'] = \"prometheus_aggregate\"\ncreate_sensor(\"binary_sensor\", \"prometheus_aggregate\", payload)\n","sub_path":"roles/homeassistant/templates/prom2hass.py","file_name":"prom2hass.py","file_ext":"py","file_size_in_byte":3119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"36795143","text":"def index(i, j, cols):\n if i < 0 or j < 0 or i >= cols or j >= cols:\n return -1\n return i*cols + j\n\nclass Cell:\n def __init__(self, i, j):\n self.i = i\n self.j = j\n self.walls = [True for i in range(4)]\n self.visited = False\n\n def checkNeighbors(self, grid, cols):\n from random import randint\n ind = index(self.i, self.j-1, cols)\n allNeighbors = []\n if ind != -1:\n top = grid[index(self.i, self.j-1, cols)]\n allNeighbors.append(top)\n ind = index(self.i+1, self.j, cols)\n if ind != -1:\n right = grid[index(self.i+1, self.j, cols)]\n allNeighbors.append(right)\n ind = index(self.i, self.j+1, cols)\n if ind != -1:\n bottom = grid[index(self.i, self.j+1, cols)]\n allNeighbors.append(bottom)\n ind = index(self.i-1, self.j, cols)\n if ind != -1:\n left = grid[index(self.i-1, self.j, cols)]\n allNeighbors.append(left)\n neighbors = []\n for neigh in allNeighbors:\n if not neigh.visited and neigh:\n neighbors.append(neigh)\n nNeighbors = len(neighbors)\n if nNeighbors > 0:\n r = randint(0, nNeighbors-1)\n return neighbors[r]\n # elif nNeighbors == 0:\n\n\n\n def show(self, screen, w):\n import pygame\n white = (255, 255, 255)\n x = self.i*w\n y = self.j*w\n if self.visited:\n surf = pygame.Surface((w, w))\n surf.fill((255, 0, 255, 100))\n screen.blit(surf, (x, y))\n\n if self.walls[0]:\n pygame.draw.line(screen, white, (x , y), (x+w, y))\n if self.walls[1]:\n pygame.draw.line(screen, white, (x+w, y), (x+w, y+w))\n if self.walls[2]:\n pygame.draw.line(screen, white, (x+w, y+w), (x, y+w))\n if self.walls[3]:\n pygame.draw.line(screen, white, (x, y+w), (x, y))\n\n\n def highlight(self, screen, w):\n import pygame\n white = (255, 255, 255)\n x = self.i*w\n y = self.j*w\n if self.visited:\n surf = pygame.Surface((w, w))\n surf.fill((0,0,255, 100))\n screen.blit(surf, (x, y))\n\n if self.walls[0]:\n pygame.draw.line(screen, white, (x , y), (x+w, y))\n if self.walls[1]:\n pygame.draw.line(screen, white, (x+w, y), (x+w, y+w))\n if self.walls[2]:\n pygame.draw.line(screen, white, (x+w, y+w), (x, y+w))\n if self.walls[3]:\n pygame.draw.line(screen, white, (x, y+w), (x, y))\n\ndef removeWall(a, b):\n x = a.i - b.i\n if x == 1:\n a.walls[3] = False\n b.walls[1] = False\n elif x == -1:\n a.walls[1] = False\n b.walls[3] = False\n y = a.j - b.j\n if y == -1:\n a.walls[2] = False\n b.walls[0] = False\n elif y == 1:\n a.walls[0] = False\n b.walls[2] = False\n\ndef createGrid(cols, rows):\n grid = []\n for i in range(rows):\n for j in range(cols):\n grid.append(Cell(i, j))\n return grid\n\ndef showGrid(grid, screen, w):\n for cell in grid:\n cell.show(screen, w)\n\ndef start():\n import pygame\n from pygame.time import delay\n pygame.init()\n cols = 20\n rows = 20\n w = 10\n WIDTH = w*cols\n HEIGHT = w*rows\n screen = pygame.display.set_mode((WIDTH, HEIGHT))\n grid = createGrid(cols, rows)\n current = grid[0]\n stack = []\n # Running\n running = True\n while running:\n screen.fill(0)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n current.visited = True\n next = current.checkNeighbors(grid, cols)\n if next:\n next.visited = True\n stack.append(current)\n removeWall(current, next)\n current = next\n elif len(stack) > 0:\n current = stack.pop()\n\n showGrid(grid, screen, w)\n current.highlight(screen, w)\n running = False\n for i in grid:\n if i.visited == False:\n running = True\n pygame.display.update()\n current = grid[0]\n running = True\n while running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n if pygame.key.get_pressed()[pygame.K_w] and current.j > 0:\n current = grid[index(current.i, current.j-1, cols)]\n if pygame.key.get_pressed()[pygame.K_a] and current.i > 0:\n current = grid[index(current.i-1, current.j, cols)]\n if pygame.key.get_pressed()[pygame.K_s] and current.j < cols-1:\n current = grid[index(current.i, current.j+1, cols)]\n if pygame.key.get_pressed()[pygame.K_d] and current.i < cols-1:\n current = grid[index(current.i+1, current.j, cols)]\n showGrid(grid, screen, w)\n current.highlight(screen, w)\n pygame.display.update()\n delay(100)\n","sub_path":"src/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":5027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"505267951","text":"# -*- coding: utf-8 -*-\nimport pymongo\n\n\nclass ExdbspiderPipeline(object):\n def process_item(self, item, spider):\n item['exploit_lang'] = item['exploit_lang'].replace(\"language-\",\"\")\n for key in item.keys():\n if not isinstance(item[key],dict):\n item[key] = item[key].strip()\n\n if item['metrics']:\n for key in item['metrics']:\n if item['metrics'][key]:\n item['metrics'][key] = item['metrics'][key].strip()\n if item['exploit_link']:\n item['exploit_id'] = item['exploit_link'].split(\"/\")[-1]\n if \" - \" in item['title']:\n item['application'], item['attack'] = item['title'].split(\" - \")[0:2]\n else:\n item['application'], item['attack'] = [\"\",\"\"]\n if 'mdi-check' in item['verified']:\n item['verified'] = 'V'\n else:\n item['verified'] = 'NV'\n return item\n\nclass MongoPipeline(object):\n def __init__(self, mongo_db, mongo_collection):\n self.mongo_db = mongo_db\n self.mongo_collection = mongo_collection\n\n @classmethod\n def from_crawler(cls, crawler):\n return cls(\n mongo_db = crawler.settings.get('MONGO_DB', 'lists'),\n mongo_collection = crawler.settings.get('MONGO_COLLECTION')\n )\n\n def connect_db(self):\n self.client = pymongo.MongoClient(host='localhost',port=27017)\n self.db = self.client[self.mongo_db]\n\n def process_item(self, item, spider):\n self.connect_db()\n self.db[self.mongo_collection].insert(dict(item))\n return item\n","sub_path":"exdbspider/exdbspider/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"564691610","text":"import sys\nread=lambda:sys.stdin.readline().rstrip()\nreadi=lambda:int(sys.stdin.readline())\nwriteln=lambda x:sys.stdout.write(str(x)+\"\\n\")\nwrite=lambda x:sys.stdout.write(x)\n'''\ndp[i][j] : (i,j)에 사자가 돌어 왔을 때 경우의 수, j가 0이면 사자가 없는 경우\ndp[i][0] = dp[i-1][1] + dp[i-1][2]\ndp[i][1] = dp[i-1][0] + dp[i-1][2]\ndp[i][2] = dp[i-1][0] + dp[i-1][1] + sum(dp[i-2])\nsum(dp[N])\n'''\nN=readi()\na,b=1,3\nfor i in range(N-1):\n a, b = b % 9901, (2*b+a) % 9901\n \nwriteln(b)\n\n\n'''\n1 3\n2 9\n'''","sub_path":"dp/caging_lions_1309.py","file_name":"caging_lions_1309.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"322541390","text":"''' Flexible upsampling and merging module that allows for the use\nof transposed convolutions or bilinear upsampling. Allows for the\noptional inclusion of skip layers as in the original FCN.\n'''\nimport torch.nn as nn\n\n# pylint: disable=too-many-arguments, too-many-locals, unidiomatic-typecheck,\n# pylint: disable=invalid-name,arguments-differ\n\n\nclass Upsampling(nn.Module):\n ''' Defines a decoder.\n '''\n def __init__(\n self,\n stride,\n inchannels,\n channels,\n mode,\n feature_ind,\n merge_which_skips):\n '''\n args:\n :parameter ``stride``: the outstride of the network or total\n downsampling rate\n :parameter ``inchannels``: list() of ints or None's which\n state the width of the coarse features to be added to the pred\n :parameter ``channels``: list() or int of\n '''\n super(Upsampling, self).__init__()\n import math\n num_up = math.log(stride, 2)\n assert num_up % 1 == 0, 'stride must be a power of 2'\n assert len(inchannels) == len(merge_which_skips)\n assert type(channels) in [int, list]\n\n num_up = int(num_up)\n if isinstance(channels, int):\n channels = [channels for _ in range(num_up)]\n if mode == 'bilinear':\n # We don't currently support changes in width for the output\n # features using bilinear interpolation\n for i, elem in enumerate(channels[1:]):\n assert channels[i - 1] == elem\n\n # self.mode = mode\n # self.stride = stride\n merging = len(merge_which_skips) > 0\n layers = []\n merge_conv = []\n _inchannels = [el for el in inchannels]\n _inchannels.reverse()\n channels_in = channels[0]\n for i in range(num_up):\n # Each layer doubles spatial resolution\n if mode == 'transposed':\n layers.append(nn.ConvTranspose2d(\n channels_in, channels[i + 1],\n 3, stride=2, padding=1,\n output_padding=1))\n\n elif merging and mode == 'bilinear':\n layers.append(\n nn.Upsample(\n scale_factor=2,\n mode='bilinear'))\n\n if i in merge_which_skips:\n merge_conv.append(\n nn.Conv2d(\n _inchannels.pop(),\n channels[i],\n 1,\n padding=0))\n else:\n merge_conv.append(None)\n channels_in = channels[i + 1]\n\n if num_up in merge_which_skips:\n merge_conv.append(\n nn.Conv2d(\n _inchannels.pop(),\n channels[num_up],\n 1,\n padding=0))\n else:\n merge_conv.append(None)\n\n if not merging and mode == 'bilinear':\n layers = [\n nn.Upsample(\n scale_factor=stride,\n mode='bilinear')]\n\n self.layers = nn.ModuleList(layers)\n self.merge_conv = nn.ModuleList(merge_conv)\n self.feature_ind = [ind for ind in feature_ind]\n self.merge_features = [None for _ in range(num_up+1)]\n self.merge_which_skips = list(merge_which_skips)\n self.merge_which_skips.sort()\n self.feature_ind.sort(reverse=True)\n\n def forward(self, x):\n # import pdb\n # pdb.set_trace()\n assert len(x) == 3\n x, low, outsize = x\n for layer, feat in zip(self.merge_which_skips, self.feature_ind):\n self.merge_features[layer] = low[feat]\n\n ul_len = len(self.layers)\n # Merge after upsampling\n for i, layer in enumerate(self.layers):\n if self.merge_conv[i] is not None:\n # low_x = self.merge_conv[i](low[i])\n low_x = self.merge_conv[i](self.merge_features[i])\n x = x + low_x\n\n if i + 1 < ul_len and self.merge_conv[i + 1] is not None:\n sz = self.merge_features[i + 1].size()[-2:]\n x = layer(x, output_size=sz)\n elif i + 1 == ul_len:\n x = layer(x, output_size=outsize)\n else:\n x = layer(x)\n\n # Merge at original spatial res\n i = len(self.layers)\n if self.merge_features[i] is not None:\n low_x = self.merge_conv[i](self.merge_features[i])\n x = low_x + x\n\n return x\n","sub_path":"pytorch_segmentation/models/upsampling.py","file_name":"upsampling.py","file_ext":"py","file_size_in_byte":4616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"288321857","text":"# coding=utf-8\nimport datetime\nfrom django.db import models\nfrom django.conf import settings\nfrom django.core.signing import Signer\nfrom djorm_pgfulltext.models import SearchManager\nfrom djorm_pgfulltext.fields import VectorField\nfrom urllib import quote_plus\nfrom django.utils.http import urlquote\nfrom django.utils.translation import ugettext_lazy as _\nfrom caching.base import CachingManager, CachingMixin\n\n\nNUMBER_OF_VOTES_CACHE_ENTRY = 'number_of_votes'\nRECENT_EVENTS_CACHE_ENTRY = 'recent_events_cache_entry'\n\n\nclass IsNull(models.Func):\n template = '%(expressions)s IS NULL'\n\n\nclass Category(CachingMixin, models.Model):\n\n name = models.CharField(max_length=255)\n\n objects = CachingManager()\n\n def __unicode__(self):\n return self.name\n\n class Meta:\n ordering = [\"name\"]\n verbose_name_plural = _(\"categories\")\n\n\nclass SiteMode(CachingMixin, models.Model):\n show_question_votes = models.BooleanField(default=True, blank=True)\n show_total_votes = models.BooleanField(default=True, blank=True)\n allow_sorting_by_votes = models.BooleanField(default=True, blank=True)\n allow_voting_and_submitting_questions = models.BooleanField(default=True, blank=True)\n debate_time = models.DateTimeField(\n default=datetime.datetime(2099, 1, 1),\n help_text=\"Enter time that debate starts in timezone %s\" % settings.TIME_ZONE,\n )\n debate_state = models.CharField(max_length=5, null=True, blank=True)\n\n announcement_headline = models.CharField(max_length=255, null=True, blank=True)\n announcement_body = models.TextField(null=True, blank=True)\n announcement_link = models.URLField(null=True, blank=True)\n announcement_page_regex = models.CharField(max_length=255, null=True, blank=True)\n\n objects = CachingManager()\n\n\nclass Submission(models.Model):\n\n def user_display_name(self):\n return self.voter.user_display_name()\n\n category = models.ForeignKey(Category)\n idea = models.TextField(verbose_name=_('Question'))\n\n headline = models.TextField(null=False, blank=False)\n followup = models.TextField(null=True, blank=True)\n\n citation = models.CharField(max_length=2000, null=True, blank=True, db_index=True,\n verbose_name=_(\"Optional link to full proposal or reference\"))\n citation_verified = models.BooleanField(default=False, db_index=True)\n\n voter = models.ForeignKey(\"Voter\")\n created_at = models.DateTimeField(db_index=True)\n\n ip_address = models.CharField(max_length=255, db_index=True)\n\n editors_pick = models.BooleanField(default=False)\n approved = models.BooleanField(default=False, db_index=True)\n\n # if True, will not show up again in moderation list.\n moderated_removal = models.BooleanField(default=False, db_index=True)\n\n has_duplicates = models.BooleanField(default=False, db_index=True)\n\n duplicate_of = models.ForeignKey('opendebates.Submission', null=True, blank=True,\n related_name=\"duplicates\")\n\n votes = models.IntegerField(default=0, db_index=True)\n local_votes = models.IntegerField(default=0, db_index=True)\n score = models.FloatField(default=0, db_index=True)\n rank = models.FloatField(default=0, db_index=True)\n\n random_id = models.FloatField(default=0, db_index=True)\n\n search_index = VectorField()\n\n keywords = models.TextField(null=True, blank=True)\n\n objects = SearchManager(fields=[\"idea\", \"keywords\"],\n auto_update_search_field=True)\n\n source = models.CharField(max_length=255, null=True, blank=True)\n\n happened = models.DateField(null=True, blank=True)\n is_positive = models.BooleanField(default=False)\n\n class Meta:\n ordering = ['-happened']\n\n def get_recent_votes(self):\n timespan = datetime.datetime.now() - datetime.timedelta(1)\n return Vote.objects.filter(submission=self, created_at__gte=timespan).count()\n\n def get_duplicates(self):\n if not self.has_duplicates:\n return None\n return Submission.objects.select_related(\n \"voter\", \"category\", \"voter__user\").filter(\n approved=True, duplicate_of=self)\n\n def __unicode__(self):\n return self.idea\n\n @models.permalink\n def get_absolute_url(self):\n return \"vote\", [self.id]\n\n def my_tweet_text(self):\n params = {\n \"hashtag\": settings.SITE_THEME['HASHTAG'],\n }\n return _(u\"Vote for my progressive idea for @ThinkBigUS #%s(hashtag)s. \"\n \"30 leaders in Congress will see top ideas!\" % params)\n\n def tweet_text(self):\n text = settings.SITE_THEME['TWITTER_QUESTION_TEXT']\n if self.voter.twitter_handle:\n text += u\" h/t @%s\" % self.voter.twitter_handle\n return text\n\n def facebook_text(self):\n if len(self.idea) > 240:\n return self.idea[:240] + u'…'\n return self.idea\n\n def facebook_url(self):\n return u\"https://www.facebook.com/sharer/sharer.php?&u=%(idea_url)s\" % {\n \"idea_url\": quote_plus(self.really_absolute_url('fb')),\n }\n\n def reddit_url(self):\n return u\"//www.reddit.com/submit?url=%s\" % (quote_plus(self.really_absolute_url('reddit')),)\n\n def email_url(self):\n subject = settings.SITE_THEME['EMAIL_SUBJECT']\n body = settings.SITE_THEME['EMAIL_BODY'] % {\n \"url\": self.really_absolute_url('email'),\n }\n return u\"mailto:?subject=%s&body=%s\" % (urlquote(subject), urlquote(body))\n\n def sms_url(self):\n params = {\n \"url\": self.really_absolute_url('sms'),\n \"hashtag\": settings.SITE_THEME['HASHTAG'],\n }\n body = _(u\"Vote for my progressive idea for @OpenDebaters #%(hashtag)s. %(url)s\" % params)\n return u\"sms:;?body=%s\" % (quote_plus(body),)\n\n def really_absolute_url(self, source=None):\n url = settings.SITE_DOMAIN_WITH_PROTOCOL + self.get_absolute_url()\n if source is not None:\n url += '?source=share-%s-%s' % (source, self.id)\n return url\n\n def twitter_url(self):\n url_tmpl = u\"https://twitter.com/intent/tweet?url=\" + \\\n \"%(idea_url)s&text=%(tweet_text)s\"\n return url_tmpl % {\n \"idea_url\": quote_plus(self.really_absolute_url('tw')),\n \"tweet_text\": quote_plus(self.tweet_text()),\n }\n\n def twitter_title(self):\n # Vote on this question for the FL-Sen #OpenDebate!\n return settings.SITE_THEME['TWITTER_QUESTION_TITLE'].format(idea=self.idea)\n\n def twitter_description(self):\n # \"{idea}\" At 8pm EDT on 4/25, Jolly & Grayson answer top vote-getting questions at\n # bottom-up #OpenDebate hosted by [TBD], Open Debate Coalition, Progressive Change Institute\n return settings.SITE_THEME['TWITTER_QUESTION_DESCRIPTION'].format(idea=self.idea)\n\n def facebook_title(self):\n return settings.SITE_THEME['FACEBOOK_QUESTION_TITLE'].format(idea=self.idea)\n\n def facebook_description(self):\n return settings.SITE_THEME['FACEBOOK_QUESTION_DESCRIPTION'].format(idea=self.idea)\n\n\nclass ZipCode(CachingMixin, models.Model):\n zip = models.CharField(max_length=10, unique=True)\n city = models.CharField(max_length=255, null=True, blank=True)\n state = models.CharField(max_length=255, null=True, blank=True)\n\n objects = CachingManager()\n\n\nclass Voter(models.Model):\n\n def user_display_name(self):\n voter = self\n if voter.display_name:\n name = voter.display_name\n elif not voter.user:\n name = _(u\"Somebody\")\n else:\n user = voter.user\n name = u\"%s\" % user.first_name\n if user.last_name:\n name = u\"%s %s.\" % (name, user.last_name[0])\n if not name or not name.strip():\n name = _(u\"Somebody\")\n\n if voter.state:\n name = _(u\"%(name)s from %(state)s\" % {\"name\": name, \"state\": voter.state})\n return name\n\n email = models.EmailField(unique=True)\n zip = models.CharField(max_length=10, db_index=True)\n state = models.CharField(max_length=255, null=True, blank=True)\n\n user = models.OneToOneField(\n settings.AUTH_USER_MODEL, null=True, blank=True, related_name=\"voter\")\n\n source = models.CharField(max_length=255, null=True, blank=True)\n created_at = models.DateTimeField(auto_now_add=True)\n\n display_name = models.CharField(max_length=255, null=True, blank=True)\n twitter_handle = models.CharField(max_length=255, null=True, blank=True)\n\n unsubscribed = models.BooleanField(default=False)\n\n def __unicode__(self):\n return self.email\n\n def account_token(self):\n return Voter.make_account_token(self.email)\n\n @classmethod\n def make_account_token(cls, email):\n signer = Signer()\n value = signer.sign(email)\n return value\n\n\nclass Vote(models.Model):\n\n submission = models.ForeignKey(Submission)\n voter = models.ForeignKey(Voter)\n\n ip_address = models.CharField(max_length=255, db_index=True)\n request_headers = models.TextField(null=True, blank=True)\n\n original_merged_submission = models.ForeignKey(Submission, null=True, blank=True,\n related_name=\"votes_merged_elsewhere\")\n\n class Meta:\n unique_together = [(\"submission\", \"voter\")]\n\n created_at = models.DateTimeField(db_index=True)\n source = models.CharField(max_length=255, null=True, blank=True)\n\n\nclass Candidate(models.Model):\n first_name = models.CharField(max_length=255, null=True, blank=True)\n last_name = models.CharField(max_length=255, null=True, blank=True)\n current_title = models.CharField(max_length=255, null=True, blank=True)\n bio = models.TextField(default='', null=True, blank=True)\n website = models.URLField(null=True, blank=True, db_index=True)\n facebook = models.URLField(null=True, blank=True, db_index=True)\n twitter_handle = models.CharField(max_length=16, null=True, blank=True)\n display_name = models.CharField(max_length=255, null=True, blank=True,\n help_text=_(\"Defaults to first_name last_name.\"))\n\n created_at = models.DateTimeField(auto_now_add=True)\n\n def save(self, *args, **kwargs):\n if not self.display_name:\n self.display_name = u'{0} {1}'.format(self.first_name, self.last_name)\n super(Candidate, self).save(*args, **kwargs)\n\n def __unicode__(self):\n return self.display_name\n\n\nclass Flag(models.Model):\n to_remove = models.ForeignKey(Submission, related_name='removal_flags')\n duplicate_of = models.ForeignKey(Submission, related_name='+',\n null=True, blank=True)\n voter = models.ForeignKey(Voter)\n reviewed = models.BooleanField(default=False)\n note = models.TextField(null=True, blank=True)\n\n class Meta:\n unique_together = [\n ('to_remove', 'voter'),\n ]\n","sub_path":"opendebates/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":10960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"394116279","text":"# encoding: utf-8\nfrom django import forms\n\nfrom apps.account.models import Persona\nfrom .models import Socio, Parcela, Acopio, DetalleAcopio\n\n\nclass PersonaForm(forms.ModelForm):\n\n class Meta:\n model = Persona\n fields = ['first_name', 'last_name', 'identity_type',\n 'identity_num', 'photo', 'email', 'birth_date']\n labels = {\n 'first_name': 'Nombre: ',\n 'last_name': 'Apellidos: ',\n 'identity_type': 'Tipo de Identidad: ',\n 'identity_num': 'Número: ',\n 'photo': 'Fotografía: ',\n 'email': 'E-mail: ',\n 'birth_date': 'Fecha de Nacimiento: ',\n }\n widgets = {\n 'first_name': forms.TextInput(attrs={'class': 'form-control'}),\n 'last_name': forms.TextInput(attrs={'class': 'form-control'}),\n 'identity_num': forms.TextInput(attrs={'class': 'form-control'}),\n 'email': forms.TextInput(attrs={'class': 'form-control'}),\n }\n\n\nclass SocioForm(forms.ModelForm):\n\n class Meta:\n model = Socio\n fields = ['cod_socio', 'direccion', 'ciudad',\n 'estado']\n labels = {\n 'cod_socio': 'Codigo de Socio: ',\n 'direccion': 'Dirección: ',\n 'ciudad': 'Distrito: ',\n 'estado': 'Estado: ',\n }\n # widgets = {\n # 'first_name': forms.TextInput(attrs={'class': 'form-control'}),\n # 'last_name': forms.TextInput(attrs={'class': 'form-control'}),\n # 'identity_num': forms.TextInput(attrs={'class': 'form-control'}),\n # 'email': forms.TextInput(attrs={'class': 'form-control'}),\n # }\n\n\nclass ParcelaForm(forms.ModelForm):\n\n class Meta:\n model = Parcela\n fields = ['codigo', 'ubicacion', 'area_cultivo', 'area_desarrollo',\n 'prod_estimado_tn', 'prod_estimado_kg', 'total_parcelas',\n 'socio']\n\n\nclass AcopioForm(forms.ModelForm):\n\n class Meta:\n model = Acopio\n fields = ['socio', 'estado', 'n_ticket']\n labels = {\n 'socio': 'Proveedor ',\n 'estado': 'Pagado?: ',\n 'n_ticket': 'N° Ticket: ',\n }\n\n\nclass DetalleAcopioForm(forms.ModelForm):\n\n class Meta:\n model = DetalleAcopio\n fields = ['parcela', 'acopio', 'kilos', 'precio_uni', 'total_pagar']\n labels = {\n 'parcela': 'Parcela: ',\n 'acopio': 'Acopio:',\n 'kilos': 'Cantidad en Kg.: ',\n 'precio_uni': 'Acopiado a: ',\n 'total_pagar': 'Total a pagar: ',\n }\n","sub_path":"apps/acopio/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"465844263","text":"#!/usr/bin/env python3\n\nimport utils, open_color, arcade\n\nutils.check_version((3,7))\n#set the screen width and height\nSCREEN_WIDTH = 800\nSCREEN_HEIGHT = 600\nSCREEN_TITLE = \"Smiley Face Example\"\n#set a class that can that the smile face to track the mouse movement\nclass Faces(arcade.Window):\n \"\"\" Our custom Window Class\"\"\"\n\n def __init__(self):\n \"\"\" Initializer \"\"\"\n # Call the parent class initializer\n super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)\n\n # Show the mouse cursor\n #if true, you can see the mouse cursor while it is on the window\n self.set_mouse_visible(True)\n #set the face's location\n self.x = SCREEN_WIDTH / 2\n self.y = SCREEN_HEIGHT / 2\n #set the background color to white\n arcade.set_background_color(open_color.white)\n\n def on_draw(self):\n \"\"\" Draw the face \"\"\"\n arcade.start_render()\n\n face_x,face_y = (self.x,self.y)\n #set each dot's position using self.x and self.y\n smile_x,smile_y = (face_x + 0,face_y - 10)\n eye1_x,eye1_y = (face_x - 30,face_y + 20) \n eye2_x,eye2_y = (face_x + 30,face_y + 20)\n catch1_x,catch1_y = (face_x - 25,face_y + 25) \n catch2_x,catch2_y = (face_x + 35,face_y + 25) \n #draw the face using the variable that we set for prior\n arcade.draw_circle_filled(face_x, face_y, 100, open_color.yellow_3)\n arcade.draw_circle_outline(face_x, face_y, 100, open_color.black,4)\n arcade.draw_ellipse_filled(eye1_x,eye1_y,15,25,open_color.black)\n arcade.draw_ellipse_filled(eye2_x,eye2_y,15,25,open_color.black)\n arcade.draw_circle_filled(catch1_x,catch1_y,3,open_color.gray_2)\n arcade.draw_circle_filled(catch2_x,catch2_y,3,open_color.gray_2)\n arcade.draw_arc_outline(smile_x,smile_y,60,50,open_color.black,190,350,4)\n\n\n def on_mouse_motion(self, x, y, dx, dy):\n \"\"\" Handle Mouse Motion \"\"\"\n #when we turn the mouse cursor on, we can see the face moving around the window.\n self.x = x\n self.y = y\n\n\n\nwindow = Faces()\narcade.run()","sub_path":"main5.py","file_name":"main5.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"500209721","text":"import queue\n\ndef truckTour2(pumps):\n q = queue.Queue()\n for i in range(2):\n for i, p in enumerate(pumps):\n qNew = queue.Queue()\n while not q.empty():\n item = q.get(False)\n item[1] += p[0] - p[1]\n if i == item[0]:\n return i\n if item[1] > 0:\n qNew.put(item)\n\n if p[0] > p[1] and qNew.empty():\n qNew.put([i, p[0] - p[1]])\n q = qNew\n\n return -1\n\ndef truckTour(pumps):\n t = None\n for i in range(2):\n for i, p in enumerate(pumps):\n if t == None and p[0] > p[1]:\n t = [i, p[0] - p[1]]\n elif t != None and i == t[0]:\n return i\n elif t != None: \n t[1] = t[1] + p[0] - p[1]\n if t[1] < 0:\n t = None\n\n return -1\n\nprint(truckTour([ list(int(x) for x in raw_input().split()) for i in range(int(input())) ]))","sub_path":"python/truckTour/truckTour.py","file_name":"truckTour.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"42373021","text":"from typing import DefaultDict\nimport click\nimport sys\nimport asyncio\nfrom functools import wraps\n\nfrom rich import box\nfrom rich.console import Console\nfrom rich.progress import track\nfrom rich.table import Table\n\nfrom .whatsmydns import Client, QueryTimeoutException\nfrom . import __version__\n\nCLI_HELP = \"\"\"\nValidate a domain against a list of global DNS servers.\n\nchkdns is powered by whatsmydns.net!\n\"\"\"\n\nTYPE_CHOICES = [\"A\", \"AAAA\", \"CNAME\", \"MX\", \"NS\", \"PTR\", \"SOA\", \"SRV\", \"TXT\", \"CAA\"]\n\n\ndef coro(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n return asyncio.run(f(*args, **kwargs))\n\n return wrapper\n\n\n@click.command(help=CLI_HELP, no_args_is_help=True)\n@click.option(\n \"--type\",\n default=\"A\",\n show_default=True,\n type=click.Choice(TYPE_CHOICES),\n help=\"The type of record to query for.\",\n)\n@click.option(\"--host\", required=True, help=\"A valid hostname.\")\n@click.version_option(__version__)\n@coro\nasync def cli(type, host):\n\n console = Console()\n\n dns = Client(use_mock=False)\n servers = dns.get_servers()\n\n table = Table(box=box.SIMPLE, leading=1, expand=True)\n table.add_column(\"\", no_wrap=True)\n table.add_column(\"location\", no_wrap=True)\n table.add_column(\"provider\", no_wrap=True)\n table.add_column(\"result\", justify=\"center\", no_wrap=True)\n table.add_column(\"response\", no_wrap=True)\n\n stats = DefaultDict(int)\n servers_count = len(servers)\n\n for server in track(\n sorted(servers, key=lambda server: server[\"provider\"]),\n description=f\"Checking DNS propagation for {host}\",\n transient=True,\n ):\n\n try:\n response = await dns.query(server[\"id\"], type, host)\n data = response[\"data\"][0]\n\n if data[\"rcode\"] == \"NOERROR\":\n stats[\"success\"] += 1\n result = \"✅\"\n elif data[\"rcode\"] == \"SERVFAIL\":\n result = \"❌\"\n stats[\"fail\"] += 1\n else:\n result = \"❓\"\n stats[\"unknown\"] += 1\n\n answer = \", \".join(answer.split()[-1] for answer in data[\"answers\"])\n except QueryTimeoutException:\n\n result = \"⏳\"\n answer = \"DNS query timed out.\"\n stats[\"timeout\"] += 1\n\n except Exception:\n console.print_exception()\n sys.exit(1)\n\n table.add_row(\n server[\"flag\"], server[\"location\"], server[\"provider\"], result, answer\n )\n\n score = stats[\"success\"] / servers_count * 100\n table.caption = f\"{score:.2f}% of servers responded successfully for {host}.\"\n\n console.print(table)\n","sub_path":"src/chkdns/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"138467795","text":"from hasoffers import Hasoffers\nfrom kpi_notificator import celery_app\n\nfrom django.conf import settings\nfrom stats.models import Offer\n\n\n@celery_app.task\ndef update_active_offers():\n\n api = Hasoffers(network_token=settings.HASOFFERS_NETWORK_TOKEN,\n network_id=settings.HASOFFERS_NETWORK_ID,\n proxies=settings.PROXIES)\n\n params = dict(\n fields=['id', 'name'],\n contain=['OfferCategory'],\n filters={'status': 'active'},\n limit=10000\n )\n resp = api.Offer.findAll(**params)\n\n for offer in resp.extract_all():\n offer_categories_id = (\n list(\n map(\n int,\n list(dict(offer.OfferCategory).keys()))))\n is_incent = bool(set(offer_categories_id) & set(settings.INCENT_CATEGORIES))\n\n try:\n db_offer = Offer.objects.get(pk=offer.id)\n if db_offer.incent != is_incent:\n db_offer.incent = is_incent\n db_offer.save()\n except Offer.DoesNotExist:\n continue\n","sub_path":"workers/loaders/tasks/update_active_offers.py","file_name":"update_active_offers.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"569070612","text":"from datetime import datetime\nfrom datetime import timedelta\nimport Crypto\nfrom Crypto.Cipher import AES\nfrom Crypto.PublicKey import RSA\n\ndef calculate_timeresult(timediff_list):\n sum = timediff_list[0] - timediff_list[0]\n for diff in timediff_list:\n sum += diff\n average = sum / len(timediff_list)\n return average.total_seconds() * 1000, sum.total_seconds() * 1000\n\ndef read_rsa_publickey():\n fp = open(\"./data/rsa-publickey.txt\")\n key = fp.read()\n fp.close()\n publickey = RSA.importKey(key)\n return publickey\n\ndef read_rsa_privatekey():\n fp = open(\"./data/rsa-privatekey.txt\")\n key = fp.read()\n fp.close()\n privatekey = RSA.importKey(key)\n return privatekey\n\ndef read_aes_key():\n fp = open(\"./data/aes-key.txt\")\n key = fp.read()\n fp.close()\n aeskey = AES.new(key)\n return aeskey\n\ndef read_textcontent():\n fp = open(\"./data/content.txt\")\n content = fp.read()\n fp.close()\n content = bytes(content, \"utf-8\")\n return content\n ","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"377196365","text":"#!/usr/bin/python3\n# coding: utf-8\n\nfrom unittest import TestCase\nimport requests\n\nbase_url = 'http://localhost:5000/user/'\n\n\nclass TestAppUser(TestCase):\n # def test_info(self):\n # url = base_url + \"info/\"\n # resp = requests.get(url)\n # print(resp)\n\n def test_read(self):\n print(\"*\" * 50)\n url = base_url + 'user_read/'\n data = {\n \"user_phone\": 11111111111,\n 'info_id': 2\n }\n resp = requests.post(url, json=data)\n print(resp)\n print(\"-\" * 50)\n","sub_path":"test/test_login.py","file_name":"test_login.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"388768950","text":"from random import randint\nfrom time import strftime\nfrom flask import Flask, render_template, flash, request\nfrom wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField\nimport whoosh_retrieval\nimport pandas as pd\nfrom random import sample\nimport whoosh_retrieval\n\nDEBUG = True\napp = Flask(__name__)\napp.config.from_object(__name__)\napp.config['SECRET_KEY'] = 'SjdnUends821Jsdlkvxh391ksdODnejdDw'\n\nclass ReusableForm(Form):\n name = TextField('Business:', validators=[validators.required()])\n\ndef get_time():\n time = strftime(\"%Y-%m-%dT%H:%M\")\n return time\n\ndef write_to_disk(business):\n data = open('file.log', 'a')\n timestamp = get_time()\n data.write('DateStamp={}, Name={} \\n'.format(timestamp, business))\n data.close()\n\n\nreview_data = pd.read_csv('business_review_users_tags.csv')\nbusiness_tags = review_data.drop_duplicates(subset=['business_id'])\nbusiness_tags = business_tags[['business_name', 'tks_output']]\nBusinesses = business_tags['business_name'].tolist()\n\n@app.route(\"/\", methods=['GET', 'POST'])\ndef hello():\n form = ReusableForm(request.form)\n business = \"\"\n #print(form.errors)\n if request.method == 'POST':\n business=request.form['business']\n\n write_to_disk(business)\n if business in Businesses:\n flash('Reviews for Selected Business: {}'.format(business))\n\n else:\n flash('Error: No Reviews to Display')\n\n if business != \"\" and business in Businesses:\n selectBusinessData = business_tags.loc[business_tags['business_name'] == business]\n listselectBusinessData = selectBusinessData['tks_output'].tolist()[0]\n listselectBusinessData = listselectBusinessData.replace('[', '')\n listselectBusinessData = listselectBusinessData.replace(']', '')\n listselectBusinessData = listselectBusinessData.split(',')\n\n final_tags = []\n for tag in listselectBusinessData:\n temp = tag.replace('\\'', '').strip()\n\n final_tags.append(temp)\n\n selectBusinessTags = sample(final_tags,10) if len(final_tags) > 10 else final_tags\n tagLen = len(selectBusinessTags)\n reviews = {}\n for t in selectBusinessTags:\n reviews[t] = whoosh_retrieval.search_review(t, business)\n\n else:\n tagLen = 0\n selectBusinessTags = []\n reviews = {}\n return render_template('./index.html', form=form, tagLen=tagLen, Tags=selectBusinessTags, businessLen=len(Businesses), Businesses=Businesses, reviews=reviews)\n\nif __name__ == \"__main__\":\n app.run()","sub_path":"Task 2/Review Retrieval/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"640152876","text":"import PySimpleGUI as sg\nimport datetime\n\nsg.theme('Dark Blue 3') # please make your windows colorful\n\nlayout = [[sg.Text('Your typed chars appear here:'), sg.Text(size=(12, 1), key='-OUTPUT-')],\n [sg.Input(key='-IN-')],\n [sg.Button('Show'), sg.Button('Exit'), sg.Text(size=(20, 1), key='-_time_-')]]\n\nwindow = sg.Window('Window Title', layout)\n\n\ndef getTime():\n\treturn datetime.datetime.now().strftime('%H:%M:%S')\n\nwhile True: # Event Loop\n\t# event, values = window.read()\n\tevent, values = window.read(timeout=0)\n\t# print(event, values)\n\t# window['-_time_-'].update(str(datetime.datetime.now()))\n\tif event == sg.WIN_CLOSED or event == 'Exit':\n\t\tbreak\n\tif event == 'Show':\n\t\t# change the \"output\" element to be the value of \"input\" element\n\t\twindow['-OUTPUT-'].update(values['-IN-'])\n\n\n\twindow[\"-_time_-\"].update(str(datetime.datetime.now()))\n\t# window.FindElement('-_time_-').update(str(datetime.datetime.now()))\n\n\t# window.FindElement('-_time_-').Update(getTime())\n\nwindow.close()\n","sub_path":"GUI/GUI_experimentation/eg_demo_code_testing.py","file_name":"eg_demo_code_testing.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"424228232","text":"'''\nThis script shows how to send emails via Python when you detect changes via SNMP\n'''\n\ndef send_mail(recipient, subject, message, sender):\n '''\n Simple function to help simplify sending SMTP email\n\n Assumes a mailserver is available on localhost\n '''\n\n import smtplib\n from email.mime.text import MIMEText\n\n message = MIMEText(message)\n message['Subject'] = subject\n message['From'] = sender\n message['To'] = recipient\n\n # Create SMTP connection object to localhost\n smtp_conn = smtplib.SMTP('localhost')\n\n # Send the email\n smtp_conn.sendmail(sender, recipient, message.as_string())\n\n # Close SMTP connection\n\n smtp_conn.quit()\n\n return True\n\n\nif __name__ == '__main__':\n\t\n\trecipient = 'nilekani.raunaq@gmail.com'\n\tsubject = 'Test message'\n\tmessage = '''\n This is a fictional message\n\nRegards,\nRon\n'''\t\n","sub_path":"email_helper.py","file_name":"email_helper.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"652258811","text":"import os_android_apk_google_play_publisher.modules.apk_publisher_boilerplate as bp\n\n\n################################################################################\n#\n# This module meant to upload a new apk release to the Play Store.\n#\n# Make sure you have the client-secrets.json file. If you don't have it,\n# read in the GitHub repo on how to acquire it:\n# https://github.com/osfunapps/os_android_apk_google_play_publisher\n#\n################################################################################\n\n\ndef publish_apk(package_name, apk_file_path, client_secrets_path, publish_percent, version_code):\n \"\"\"\n Will publish a new apk to the Google's Play Store (you HAVE to have a published app in the Google's Play Store already)\n Args:\n param package_name: your app's package name\n param apk_file_path: the path to your apk file\n param client_secrets_path: the path to your Google's client secrets json (read on how to obtain at 'os_android_apk_google_play_publisher ')\n param publish_percent: roll out percents are -> 0.1 to 10%, 0.85 to 85% etc...\n param version_code: the version code of the current apk\n \"\"\"\n\n # Declare command-line flags.\n parsed_flags = bp.parse_flags()\n\n upload = 'false'\n if apk_file_path is not None:\n upload = 'true'\n\n bp.publish_apk(parsed_flags, package_name, apk_file_path, publish_percent, version_code, client_secrets_path, upload)\n","sub_path":"os_android_apk_google_play_publisher/apk_publisher.py","file_name":"apk_publisher.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"182994387","text":"\nimport json\nfrom datetime import datetime\n\nfrom sqlalchemy import (INT, JSON, TIMESTAMP, Boolean, Column, String,\n Table, func)\nfrom sqlalchemy.sql.expression import text\n\nfrom iris.database import BaseModel\n\n\nclass SupportEvents(BaseModel):\n\n def __init__(self, engine, metadata, role='reader'):\n table = Table(\n 'support_events',\n metadata,\n Column('id', INT, primary_key=True, autoincrement=True),\n Column('name', String),\n Column('description', String),\n Column('markdown_path', String),\n Column('attachment_hex', JSON),\n Column('attachment_type', INT),\n Column('is_deleted', Boolean),\n Column('update_at', TIMESTAMP, default=func.now())\n )\n super().__init__(engine, metadata, table, role)\n\n def get_events(self):\n KEYS = [col.key for col in self.table.columns]\n stmt = text('SELECT * FROM support_events WHERE is_deleted = 0 ORDER BY id ASC;')\n results = []\n for row in self.execute(stmt).fetchall():\n results.append(self.tuple_to_dict(row, KEYS))\n return results\n","sub_path":"iris/database/support_events.py","file_name":"support_events.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"615062930","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('quizter', '0014_auto_20160403_2138'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Quiz',\n fields=[\n ('id', models.AutoField(verbose_name='ID', auto_created=True, primary_key=True, serialize=False)),\n ('question', models.CharField(verbose_name='Вопрос', max_length=200)),\n ('answer', models.CharField(verbose_name='Ответ', max_length=200)),\n ],\n ),\n migrations.CreateModel(\n name='QuizAnswer',\n fields=[\n ('id', models.AutoField(verbose_name='ID', auto_created=True, primary_key=True, serialize=False)),\n ('answer', models.ForeignKey(verbose_name='Ответ', to='quizter.Quiz')),\n ],\n ),\n ]\n","sub_path":"quizter/migrations/0015_quiz_quizanswer.py","file_name":"0015_quiz_quizanswer.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"411241588","text":"# UFCG - Programação 1 - 2019.2\n# André Lucas Medeiros Martins - 119210592[\n\n# Novo CPF\n\nparte1=input()\nparte2=input()\nparte3=input()\n\nparte4= int(parte3[0]) + int(parte3[1]) + int(parte3[2])\n\nprint(\"{}.{}.{}-{:02}\".format(parte1, parte2, parte3, parte4))\n\n","sub_path":"prog1/exercicios/2Unidade/NovoCPF_AndreLucas/AndreLucas_NovoCPF.py","file_name":"AndreLucas_NovoCPF.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"439349014","text":"#!/usr/bin/python3\n\n\"\"\"Binary genetic algorithm engine\"\"\"\n\n\nfrom typing import Any, Callable, List, Union, Tuple\n\nimport numpy as np\n\n\n_DEFAULT_RAND_GEN = np.random.Generator(np.random.pcg64.PCG64(None))\n\n\ndef generate(\n pop_size: int,\n chrom_length: int,\n threshold: float = 0.5,\n rand_generator: np.random.Generator = _DEFAULT_RAND_GEN\n) -> np.ndarray:\n \"\"\"\n Inputs:\n\n pop_size\n -- positive integer number\n -- total number of chromosomes in a generation\n\n chrom_length\n -- positive integer number\n -- number of bits in a chromosome\n -- length of a chromosome\n\n threshold\n -- real number between 0.0 and 1.0 (default is 0.5)\n -- values (from uniform distribution) lower than this number\n translate to True values in chromosomes\n\n rand_generator\n -- instance of Numpy Random Generator\n -- Generator with Numpy default BitGenerator (PCG64)\n and None as a seed value is used as default\n\n\n Each chromosome is represented as a fixed length 1D numpy array\n with random sequence of Boolean values.\n\n Population size must be smaller than the total number of unique\n chromosome sequences (binary patterns) that can be generated from\n a given number of bits.\n\n\n Returns nested (2D) numpy boolean array, the entire population\n of chromosomes (solution candidates).\n \"\"\"\n\n if pop_size >= (1 << chrom_length):\n raise ValueError('Population must be smaller than overall unique chromosome sequences.')\n\n return rand_generator.uniform(low=0.0, high=1.0, size=(pop_size, chrom_length)) < threshold\n\n\ndef select(\n population: np.ndarray,\n scores: np.ndarray,\n indexes: np.ndarray,\n rand_generator: np.random.Generator = _DEFAULT_RAND_GEN\n) -> np.ndarray:\n \"\"\"\n Inputs:\n\n population\n -- array of chromosomes\n -- each chromosome must be represented as 1D numpy boolean array\n\n scores\n -- array of fitness values corresponding to chromosomes\n -- each fitness value must be a non-negative real number\n\n indexes\n -- 1D numpy integer array\n -- indexes of chromosomes in the population (row index)\n\n rand_generator\n -- instance of Numpy Random Generator\n -- Generator with Numpy default BitGenerator (PCG64)\n and None as a seed value is used as default\n\n\n Selection is based on the roulette wheel method (fitness proportionate selection)\n where probability of a chromosome being selected is related to its fitness value.\n\n This does not guarantee that the best chromosome sequence (binary pattern)\n will be selected but helps to avoid local optima.\n\n\n Returns nested (2D) numpy boolean array, the entire next generation of chromosomes\n (solution candidates) chosen with repetition from a given population.\n \"\"\"\n\n probabilities = scores / np.sum(scores)\n\n indexes = rand_generator.choice(indexes, size=indexes.size, replace=True, p=probabilities)\n\n rand_generator.shuffle(indexes)\n\n return population[indexes]\n\n\ndef mutate(\n population: np.ndarray,\n mut_prob: float,\n rand_generator: np.random.Generator = _DEFAULT_RAND_GEN\n) -> np.ndarray:\n \"\"\"\n Inputs:\n\n population\n -- array of chromosomes\n -- each chromosome must be represented as 1D numpy boolean array\n\n mut_prob\n -- positive real number\n -- mutation rate\n -- probability that a bit will be inverted\n\n rand_generator\n -- instance of Numpy Random Generator\n -- Generator with Numpy default BitGenerator (PCG64)\n and None as a seed value is used as default\n\n\n Mutation can occur independently at every bit along each chromosome\n with uniform probability.\n\n\n Returns nested (2D) numpy boolean array, the entire population of chromosomes\n (solution candidates) with randomly altered bits.\n \"\"\"\n\n bits_to_mutate = rand_generator.uniform(low=0.0, high=1.0, size=population.shape) < mut_prob\n\n # Change only specific bits in chromosomes, using XOR\n return population ^ bits_to_mutate\n\n\ndef crossover(\n population: np.ndarray,\n crs_prob: float,\n bits: np.ndarray,\n rand_generator: np.random.Generator = _DEFAULT_RAND_GEN\n) -> np.ndarray:\n \"\"\"\n Inputs:\n\n population\n -- array of chromosomes\n -- each chromosome must be represented as 1D numpy boolean array\n -- number of chromosomes must be even\n\n crs_prob\n -- positive real number\n -- crossover (recombination) probability\n -- probability that a pair of chromosomes will exchange\n part of bit sequences\n\n bits\n -- 1D numpy integer array\n -- indexes of bits in a chromosome (column index)\n\n rand_generator\n -- instance of Numpy Random Generator\n -- Generator with Numpy default BitGenerator (PCG64)\n and None as a seed value is used as default\n\n\n Commute part of binary sequences between paired chromosomes.\n\n\n Returns nested (2D) numpy boolean array, the entire population of chromosomes\n (solution candidates) where random chromosome pairs swapped their binary pattern.\n \"\"\"\n\n # Each row represents a pair of chromosomes\n # Each column represents specific bit\n\n # Get the number of pairs and the length of sequences\n rows, cols = population.shape\n\n rows >>= 1 # rows //= 2\n\n # Select pairs of chromosomes for which sequences of bits will be exchanged\n pairs = rand_generator.uniform(low=0.0, high=1.0, size=(rows, 1)) < crs_prob\n\n # Each chromosome must contribute at least one bit\n\n # Set a single crossover bit for each pair of chromosomes\n breakpoints = rand_generator.integers(\n low=1,\n high=cols,\n size=(rows, 1),\n dtype=bits.dtype,\n endpoint=False\n )\n\n # Divide each sequence of bits into two parts\n positions = bits < breakpoints\n\n # Keep information of bit positions only for selected pairs\n positions &= pairs\n\n return np.concatenate((\n (population[0::2] & positions) | (population[1::2] & ~positions),\n (population[0::2] & ~positions) | (population[1::2] & positions)\n ), axis=0)\n\n\ndef run(\n fit_func: Callable[..., np.ndarray],\n crs_prob: float,\n mut_prob: float,\n chrom_length: int,\n pop_size: int,\n iterations: int,\n fit_args: Union[List[Any], Tuple, None] = None,\n threshold: float = 1.0\n) -> np.ndarray:\n \"\"\"\n Inputs:\n\n fit_func\n -- fitness function\n -- first positional argument must be a nested (2D) numpy boolean array\n -- must return 1D numpy array with real numbers between\n 0 (invalid sequence) and 1 (perfect fitness) and size\n equal to the number of rows of the given numpy array\n\n crs_prob\n -- positive real number\n -- crossover (recombination) probability\n -- probability that a pair of chromosomes will exchange\n part of bit sequences\n\n mut_prob\n -- positive real number\n -- mutation rate\n -- probability that a bit will be inverted\n\n chrom_length\n -- positive integer number\n -- number of bits in a chromosome\n -- length of a chromosome\n\n fit_args\n -- list, tuple, or None (default)\n -- additional argument(s) require by fitness function\n\n pop_size\n -- positive integer number (default is 100)\n -- must be even\n -- total number of chromosomes in a generation\n\n iterations\n -- positive integer number (default is 200)\n -- maximum number of generations\n\n threshold\n -- positive number less than or equal to 1\n -- minimum satisfactory fitness level\n -- higher value is more strict\n -- default is 1, which produces the highest fitness value after\n a given number of iterations (preferably a perfect fitness\n or an exact match)\n\n\n The fitness function operates on numpy arrays: for a given population\n of chromosomes it must return corresponding fitness values.\n\n This function always returns a chromosome with the largest fitness value.\n However, depending on the fitness function, it can solve both minimization\n and maximization problems.\n\n The highest fitted chromosome is returned even if the minimum fitness threshold\n condition is not satisfied within a given number of generations.\n\n\n Returns a chromosome (1D numpy boolean array).\n \"\"\"\n\n if pop_size & 1:\n raise ValueError('Total amount of chromosomes in a population must be an even number.')\n if (crs_prob <= 0) or (crs_prob >= 1):\n raise ValueError('Crossover probability must be a number between 0.0 and 1.0 (exclusive).')\n if (mut_prob <= 0) or (mut_prob >= 1):\n raise ValueError('Mutation probability must be a number between 0.0 and 1.0 (exclusive).')\n if 1 < threshold < 0:\n raise ValueError('Threshold must be a number between 0.0 and 1.0 (inclusive).')\n\n if fit_args is None:\n fit_args = []\n elif not isinstance(fit_args, (list, tuple)):\n raise TypeError('Additional fitness argument(s) must be placed in a list or tuple.')\n\n # Create initial population and calculate corresponding fitness values\n population = generate(pop_size, chrom_length)\n scores = fit_func(population, *fit_args)\n\n # Find the best candidate from current generation\n alpha = np.argmax(scores)\n alpha_chromosome = population[alpha]\n alpha_score = scores[alpha]\n\n # Enumerate chromosomes in the population (create rows index)\n indexes = np.arange(pop_size, dtype=np.uint)\n\n # Enumerate bits in a chromosome (create columns index)\n bits = np.arange(chrom_length, dtype=np.uint)\n\n # Create successive generations\n for _ in range(iterations):\n\n if alpha_score >= threshold:\n break\n\n # Recreate population\n population = select(population, scores, indexes)\n population = crossover(population, crs_prob, bits)\n population = mutate(population, mut_prob)\n\n # Recalculate fitness values\n scores = fit_func(population, *fit_args)\n\n alpha = np.argmax(scores)\n\n if alpha_score < scores[alpha]:\n alpha_chromosome = population[alpha]\n alpha_score = scores[alpha]\n\n return alpha_chromosome\n","sub_path":"binary_genetic_algorithm.py","file_name":"binary_genetic_algorithm.py","file_ext":"py","file_size_in_byte":10142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"243283969","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\n\nimport pytest\nimport requests\nimport xml.etree.ElementTree as ET\n\nfrom foist.pipeline import (extract_text, get_collection_names, get_pdf_url,\n get_record, get_record_list, is_in_fedora,\n is_thesis, parse_record_list)\n\n\ndef test_extract_text_returns_bytes(pdf):\n text = extract_text(pdf)\n assert type(text) == bytes\n\n\ndef test_get_collection_names_returns_correct_names():\n names = get_collection_names(['hdl_1721.1_7888', 'hdl_1721.1_7710',\n 'hdl_1721.1_7929', 'hdl_1721.1_7742',\n 'hdl_1721.1_102296', 'hdl_1721.1_102291',\n 'not_a_key'])\n assert names == {'Engineering Systems', 'Technology and Policy',\n 'Institute for Data, Systems, and Society'}\n\n\ndef test_get_pdf_url_succeeds(mets_xml):\n mets = ET.parse(mets_xml).getroot()\n pdf_url = get_pdf_url(mets)\n assert pdf_url == ('http://dspace.mit.edu/bitstream/1721.1/'\n '107085/1/971247903-MIT.pdf')\n\n\ndef test_get_record_succeeds(pipeline):\n '''Correctly-formed request should return XML response.\n '''\n dspace_oai_uri = 'http://example.com/oai/request?'\n dspace_oai_identifier = 'oai:dspace.mit.edu:1721.1/'\n identifier = '12345'\n metadata_format = 'mets'\n r = get_record(dspace_oai_uri, dspace_oai_identifier, identifier,\n metadata_format)\n assert '' in r\n\n\ndef test_get_record_list_succeeds(pipeline):\n '''Correctly-formed request should return XML response.\n '''\n dspace_oai_uri = 'http://example.com/oai/request?'\n metadata_format = 'mets'\n start_date = '2017-01-01'\n end_date = '2017-02-01'\n r = get_record_list(dspace_oai_uri, metadata_format, start_date=start_date,\n end_date=end_date)\n assert '' in r\n\n\ndef test_is_in_fedora_returns_true_for_ingested_item(fedora):\n handle = 'thesis'\n fedora_uri = 'http://example.com/rest/'\n assert is_in_fedora(handle, fedora_uri, 'theses') is True\n\n\ndef test_is_in_fedora_returns_false_for_uningested_item(fedora):\n handle = 'uningested_thesis'\n fedora_uri = 'http://example.com/rest/'\n assert is_in_fedora(handle, fedora_uri, 'theses') is False\n\n\ndef test_is_in_fedora_error_raises_error(fedora_errors):\n with pytest.raises(requests.exceptions.HTTPError):\n handle = 'no_auth'\n fedora_uri = 'http://example.com/rest/'\n is_in_fedora(handle, fedora_uri, 'theses')\n\n\ndef test_is_thesis_returns_true_for_thesis():\n set_specs = ['hdl_1721.1_7593']\n assert is_thesis(set_specs) is True\n\n\ndef test_is_thesis_returns_false_for_not_thesis():\n set_specs = ['i_am_not_a_thesis_set']\n assert is_thesis(set_specs) is False\n\n\ndef test_parse_record_list_returns_correct_json(record_list):\n json_records = parse_record_list(record_list)\n assert {'identifier': '108425', 'sets': ['hdl_1721.1_494'],\n 'handle': '1721.1-108425'} in json_records\n","sub_path":"tests/test_pipeline.py","file_name":"test_pipeline.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"140291617","text":"from flask import Flask\nfrom flask_bcrypt import Bcrypt\nfrom flask_login import LoginManager\nfrom flask_sqlalchemy import SQLAlchemy\n\n\napp = Flask(__name__)\napp.config[\"SECRET_KEY\"] = \"956b91dcad619e1d5137ee2fc1e14bc2\"\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"sqlite:///database/site.db\"\ndb = SQLAlchemy(app)\nbcrypt = Bcrypt(app)\nlogin_manager = LoginManager(app)\nlogin_manager.login_view = \"login\"\nlogin_manager.login_message_category = \"info\"\n\n# Needs to be imported here to resolve circular imports.\n# from flaskblog.controller import routes\nfrom flaskblog.controller import ( # noqa Discable check\n general_controller,\n user_controller,\n posts_controller,\n)\n","sub_path":"flaskblog/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"184733997","text":"# coding: utf-8\n\n'''\n计算在三角形单元上的积分\n'''\nfrom geo_quad.parameters import DIM\n\ndef center_rule(tri=None, func=None):\n '''\n the center of gravity formula, just like a two-dimensional variant of the mid-point rule\n :param tri:\n :param func:\n :return:\n '''\n center = tri.center()\n area = tri.area()\n if len(center) == 2:\n return func(center[0], center[1]) * area\n\n elif len(center) == 3:\n return func(center[0], center[1], center[2]) * area\n\n\ndef corner_rule(tri=None, func=None):\n '''\n corner quadrature formula, i.e., a two-dimentional analog to the Trapezoidal rule.\n :param tri:\n :param func:\n :return:\n '''\n vertex = tri.getVertex()\n if DIM == 2:\n integ = 0\n for i in range(3):\n integ += func(vertex[i].getCoor()[0], vertex[i].getCoor()[1])\n return integ * tri.area() / 3\n\n elif DIM == 3:\n integ = 0\n for i in range(3):\n integ += func(vertex[i].getCoor()[0], vertex[i].getCoor()[1], vertex[i].getCoor()[2])\n return integ * tri.area() / 3\n\n\ndef mid_point_rule(tri=None, func=None):\n '''\n a better quadrature formula is the two-dimentional Mid-point rule.\n :param tri:\n :param func:\n :return:\n '''\n # 首先获得3条边的中点\n pt1, pt2, pt3 = [edge.getMid_pt() for edge in tri.getEdges()]\n\n if DIM == 2:\n integ = func(pt1.getCoor()[0], pt1.getCoor()[1]) +\\\n func(pt2.getCoor()[0], pt2.getCoor()[1]) + \\\n func(pt3.getCoor()[0], pt3.getCoor()[1])\n return integ * tri.area() / 3\n\n elif DIM == 3:\n integ = func(pt1.getCoor()[0], pt1.getCoor()[1], pt1.getCoor()[2]) +\\\n func(pt2.getCoor()[0], pt2.getCoor()[1], pt2.getCoor()[2]) + \\\n func(pt3.getCoor()[0], pt3.getCoor()[1], pt3.getCoor()[2])\n return integ * tri.area() / 3\n\n\n\n\n\n\n","sub_path":"geo_quad/integral/integrate_triangle.py","file_name":"integrate_triangle.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"612672903","text":"# coding:utf8\n\nimport os\nfrom os.path import abspath\nfrom pyspark.sql import SparkSession\n\n# os.environ[\"SPARK_HOME\"] = \"D:/software/spark-2.4.2-bin-hadoop2.7\"\nwarehouse_location = abspath('/user/hive/warehouse')\n\n\ndef main():\n spark = SparkSession \\\n .builder \\\n .appName(\"Spark on Hive\") \\\n .master(\"local[*]\") \\\n .config(\"spark.sql.warehouse.dir\", warehouse_location) \\\n .enableHiveSupport() \\\n .getOrCreate()\n\n df = spark.sql('select * from dp_test.test limit 10')\n df.show(truncate=False)\n\n spark.stop()\n\n # 转为pandas的dataframe\n pd = df.toPandas()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"spark/pyspark_sql/read_hive.py","file_name":"read_hive.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"642186643","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nproperty_test.py: testing file with property-based tests\nfor multifidelityfunctions package\n\"\"\"\n\n__author__ = 'Sander van Rijn'\n__email__ = 's.j.van.rijn@liacs.leidenuniv.nl'\n\n\nimport numpy as np\nfrom hypothesis import given\nfrom hypothesis.strategies import floats, integers, lists\nimport pytest\n\nfrom .utils import rescale, ValueRange\nimport multifidelityfunctions as mff\n\n\n@mff.row_vectorize\ndef quadratic(xx):\n return np.sqrt(np.sum(xx**2, axis=1))\n\n\nsimple_square = mff.MultiFidelityFunction('simple_square', [-1e8], [1e8], [quadratic, quadratic], ['high', 'low'])\n\n# TEST HELPERS -----------------------------------------------------------------\n\ndef rectangle_lists(n):\n return lists(lists(floats(min_value=0, max_value=1),\n min_size=n, max_size=n), min_size=1)\n\n\ndef _test_1d_array_input(func, x):\n y = func(x)\n\n assert isinstance(y, np.ndarray)\n assert y.ndim == 1\n\n\ndef _test_2d_array_input(func, x):\n y = func(x)\n\n assert isinstance(y, np.ndarray)\n assert y.ndim == 1\n assert np.all(np.isfinite(y))\n\n if len(x) > 1:\n assert np.allclose(func(x[0]), y[0])\n\n\ndef _test_single_function(f, x):\n X = rescale(np.array(x),\n range_in=ValueRange(0, 1),\n range_out=ValueRange(*f.bounds))\n for fidelity in f.functions:\n _test_2d_array_input(fidelity, X.tolist()) # list input TODO: make separate test for @row_vectorize decorator instead\n _test_2d_array_input(fidelity, X) # direct numpy input\n\n\n# TESTS ------------------------------------------------------------------------\n\n\n@given(integers(min_value=1, max_value=100).flatmap(rectangle_lists))\n@pytest.mark.parametrize(\"function\", [\n simple_square,\n mff.forrester,\n])\ndef test_nd_functions(function, x):\n _test_single_function(function, x)\n\n\n@given(rectangle_lists(n=2))\n@pytest.mark.parametrize(\"function\", [\n mff.bohachevsky,\n mff.booth,\n mff.branin,\n mff.currin,\n mff.himmelblau,\n mff.six_hump_camelback,\n mff.adjustable_branin(0.5),\n mff.adjustable_paciorek(0.5),\n])\ndef test_2d_functions(function, x):\n _test_single_function(function, x)\n\n\n@given(rectangle_lists(n=3))\n@pytest.mark.parametrize(\"function\", [\n mff.adjustable_hartmann3(0.5),\n])\ndef test_3d_functions(function, x):\n _test_single_function(function, x)\n\n\n@given(rectangle_lists(n=4))\n@pytest.mark.parametrize(\"function\", [\n mff.park91a,\n mff.park91b,\n])\ndef test_4d_functions(function, x):\n _test_single_function(function, x)\n\n\n@given(rectangle_lists(n=6))\n@pytest.mark.parametrize(\"function\", [\n mff.hartmann6,\n])\ndef test_6d_functions(function, x):\n _test_single_function(function, x)\n\n\n@given(rectangle_lists(n=8))\n@pytest.mark.parametrize(\"function\", [\n mff.borehole,\n])\ndef test_8d_functions(function, x):\n _test_single_function(function, x)\n\n\n@given(rectangle_lists(n=10))\n@pytest.mark.parametrize(\"function\", [\n mff.adjustable_trid(0.5),\n])\ndef test_10d_functions(function, x):\n _test_single_function(function, x)\n","sub_path":"tests/property_test.py","file_name":"property_test.py","file_ext":"py","file_size_in_byte":3070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"477434438","text":"# -*- coding: utf-8 -*-\nfrom openerp import models, fields, api\nfrom openerp.exceptions import ValidationError\nfrom openerp.tools.translate import _\nimport logging\nlogger = logging.getLogger(__name__)\n\n\n# Fundraising Studio groups\nclass FRSTzGruppeDetail(models.Model):\n _name = \"frst.zgruppedetail\"\n _rec_name = \"gruppe_lang\"\n\n # Compute a name based on - - \n # display_name = fields.Char(string=\"Group Name\",\n # compute=\"_compute_display_name\",\n # search=\"_search_display_name\",\n # readonly=True,\n # store=False)\n\n zgruppe_id = fields.Many2one(comodel_name=\"frst.zgruppe\", inverse_name='zgruppedetail_ids',\n string=\"Gruppenordner\",\n required=True, ondelete=\"cascade\", index=True)\n\n tabellentyp_id = fields.Selection(related=\"zgruppe_id.tabellentyp_id\", readonly=True, store=True)\n\n geltungsbereich = fields.Selection(string=\"Geltungsbereich\",\n selection=[('local', 'Local Group'),\n ('system', 'System Group')],\n default='system')\n gui_anzeige_profil = fields.Boolean(string=\"GuiAnzeigeProfil\",\n help=\"Show this group in the person profile view.\",\n default=True)\n\n gruppe_kurz = fields.Char(string=\"GruppeKurz\", required=True,\n help=\"gruppe_kurz is no longer in use - use gruppe_lang instead! \"\n \"The value of gruppe_lang will be copied to gruppe_kurz if gruppe_kurz is empty!\")\n gruppe_lang = fields.Char(string=\"GruppeLang\", required=True)\n gui_anzeigen = fields.Boolean(\"GuiAnzeigen\",\n help=\"If set this group is available for this instance\")\n active = fields.Boolean(string=\"Active\", compute=\"_compute_active\", store=True)\n\n # ATTENTION: \"gueltig_von\" und \"gueltig_bis\" is NOT IN USE for zGruppeDetail and may be removed in the future!\n #\n # But these fields ARE IN USE by the specific groups-for-models models like \"frst.persongruppe\"!\n # The fields are inherited through the abstract class \"frst.gruppestate\"\n #\n gueltig_von = fields.Date(string=\"GueltigVon\", required=True,\n default=lambda s: fields.Datetime.now()) # Not used -> Wird in Sicht integriert als Anlagedatum. Ist derzeit nicht als Anlagedatum gedacht!\n gueltig_bis = fields.Date(string=\"GueltigBis\", required=True,\n default=lambda s: fields.date(2099, 12, 31)) # Not used\n\n # PersonGruppe\n frst_persongruppe_ids = fields.One2many(comodel_name=\"frst.persongruppe\", inverse_name='zgruppedetail_id',\n string=\"PersonGruppe IDS\")\n frst_persongruppe_count = fields.Integer(string=\"Person Subscribers\",\n compute=\"cmp_frst_persongruppe_count\")\n\n # PersonEmailGruppe\n frst_personemailgruppe_ids = fields.One2many(comodel_name=\"frst.personemailgruppe\", inverse_name='zgruppedetail_id',\n string=\"PersonEmailGruppe IDS\")\n frst_personemailgruppe_count = fields.Integer(string=\"E-Mail Subscribers\",\n compute=\"cmp_frst_personemailgruppe_count\")\n\n # NEW SETTING FOR GROUPS / CHECKBOXES THAT MUST BE VALIDATE BY BY SOME SORT OF APPROVAL\n # HINT: This field is checked on group creation in abstract class frst.gruppestate > create()\n # approval_needed = fields.Boolean(\"Approval needed\",\n # default=False,\n # help=\"If this checkbox is set gueltig_von and gueltig_bis will be set to \"\n # \"the past date 09.09.1999 when the group is created to indicate that \"\n # \"an approval is needed before set the group to active.\")\n\n bestaetigung_erforderlich = fields.Boolean(string=\"Approval needed\",\n default=False,\n help=\"If this checkbox is set gueltig_von and gueltig_bis will be set \"\n \"to the past date 09.09.1999 when the group is created to indicate \"\n \"that an approval is needed before set the group to active.\")\n bestaetigung_typ = fields.Selection(selection=[('doubleoptin', 'DoubleOptIn'),\n ('phone_call', \"Phone Call\"),\n ('workflow', \"Fundraising Studio Workflow\"),\n ],\n string=\"Approval Type\", default='doubleoptin')\n\n # @api.multi\n # @api.depends('gruppe_lang', 'zgruppe_id')\n # def _compute_display_name(self):\n # tabellentyp_dict = dict(self.env['frst.zgruppe']._fields['tabellentyp_id'].selection)\n # for r in self:\n # r.display_name = \"%s (%s, %s)\" % (\n # r.gruppe_lang or r.gruppe_kurz,\n # tabellentyp_dict.get(r.zgruppe_id.tabellentyp_id, _('unknown')).upper() if r.zgruppe_id else _('unknown'),\n # r.sosync_fs_id if 'sosync_fs_id' in r._fields else _('unknown')\n # )\n\n @api.depends('gui_anzeigen')\n def _compute_active(self):\n for r in self:\n r.active = r.gui_anzeigen\n\n def _search_display_name(self, operator, value):\n return ['|',\n ('gruppe_lang', operator, value),\n ('sosync_fs_id', operator, value)\n ]\n\n @api.onchange('gruppe_lang', 'geltungsbereich')\n def onchange_gruppe_lang_geltungsbereich(self):\n for r in self:\n if r.gruppe_lang and not r.gruppe_kurz:\n r.gruppe_kurz = r.gruppe_lang\n if r.geltungsbereich == 'local':\n r.gui_anzeigen = True\n\n @api.multi\n def cmp_frst_persongruppe_count(self):\n for r in self:\n r.frst_persongruppe_count = len(self.frst_persongruppe_ids) or 0\n\n @api.multi\n def cmp_frst_personemailgruppe_count(self):\n for r in self:\n r.frst_personemailgruppe_count = len(self.frst_personemailgruppe_ids) or 0\n\n @api.model\n def create(self, vals):\n if vals.get('geltungsbereich') != 'local':\n assert self.env.user.has_group('base.sosync'), _(\"You can not create a system group!\")\n\n return super(FRSTzGruppeDetail, self).create(vals)\n\n @api.multi\n def write(self, vals):\n if self and vals and not self.env.user.has_group('base.sosync'):\n # Do not change the group folder (because of the tabellentyp_id)\n if 'zgruppe_id' in vals:\n raise ValidationError(_(\"You can not change the group folder (zgruppe_id). Please delete and \"\n \"recreate the group!\"))\n # Do not change the \"geltungsbereich\"\n if 'geltungsbereich' in vals:\n raise ValidationError(_(\"You can not change the 'geltungsbereich'. Please delete and \"\n \"recreate the group!\"))\n\n # Prevent the change of any relevant fields for system groups\n if any(r.geltungsbereich != 'local' for r in self):\n if any(f in vals for f in ['zgruppe_id', 'geltungsbereich', 'gui_anzeige_profil', 'gruppe_kurz',\n 'gruppe_lang', 'gui_anzeigen', 'gueltig_von', 'gueltig_bis', 'steuerung_bit',\n ]):\n raise ValidationError('You can not change system groups!')\n\n return super(FRSTzGruppeDetail, self).write(vals)\n\n @api.multi\n def unlink(self):\n if not self.env.user.has_group('base.sosync'):\n if any(r.geltungsbereich != 'local' for r in self):\n raise ValidationError('You can not delete system groups!')\n\n return super(FRSTzGruppeDetail, self).unlink()\n","sub_path":"addons-own/fso_frst_groups/models/frst_zgruppedetail.py","file_name":"frst_zgruppedetail.py","file_ext":"py","file_size_in_byte":8378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"490339230","text":"count = int(input())\ndef gcd(a, b):\n\twhile(b!=0):\n\t\tr = a%b\n\t\ta= b\n\t\tb= r\n\treturn a\nfor _ in range(count):\n a,b = map(int,input().split())\n c = gcd(a,b)\n print(int(a*b/c))","sub_path":"OneDrive/바탕 화면/알고리즘/2000~3000/2609.py","file_name":"2609.py","file_ext":"py","file_size_in_byte":180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"559065604","text":"from pyspark import SparkContext\nfrom pyspark.sql import SQLContext\nfrom operator import add\nimport pandas as pd\n\nsc = SparkContext()\nsqlcontext = SQLContext(sc)\n\n# PART 1\n# Loading Data\n# csv_path = 'hdfs://wolf.analytics.private/user/ktd5131/data/crime/Crimes_-_2001_to_present.csv'\ncsv_path = 'hdfs://wolf.analytics.private/user/ktd5131/data/sample_crime_data.csv'\nrddd = sc.textFile(csv_path)\n\n# Getting only the blocks data and placing it in the right format. Giving 0 to years different from last 3\nblocksRDD = rddd.map(lambda x: (x.split(\",\")[3], 1) if x.split(\",\")[17] in {'2018', '2019', '2020'} else (x.split(\",\")[3], 0))\n# Sum all the crimes per block\ncasesPerBlockRDD = blocksRDD.reduceByKey(add)\n# Sort by number\nsortedCrimesPerBlock = casesPerBlockRDD.sortBy(lambda x: x[1])\n# Collect\nresult = sortedCrimesPerBlock.collect()[-10:] # Get the 10 with highest number\n\nwith open(\"dimitrov_exercise2_part1_output.txt\", 'w') as output:\n for row in result:\n output.write(str(row) + '\\n')\n\n# COMMENTS:\n# Result i sin dimitrov_exercise2_part1_output.txt\n# ('064XX S DR MARTIN LUTHER KING JR DR', 571)\n# ('076XX S CICERO AVE', 572)\n# ('100XX W OHARE ST', 652)\n# ('006XX N MICHIGAN AVE', 665)\n# ('011XX S CANAL ST', 754)\n# ('0000X S STATE ST', 898)\n# ('0000X N STATE ST', 914)\n# ('0000X W TERMINAL ST', 942)\n# ('008XX N MICHIGAN AVE', 1071)\n# ('001XX N STATE ST', 2290)","sub_path":"PySpark - RDDs, SparkSQL, Pipelines/dimitrov_exercise2_part1.py","file_name":"dimitrov_exercise2_part1.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"335477936","text":"\"\"\"\nModule for Artificial Neural Network (ANN) Prediction.\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom .approximation import Approximation\n\n\nclass ANN(Approximation):\n \"\"\"\n Feed-Forward Artifical Neural Network (ANN).\n\n :param list layers: ordered list with the number of neurons of each hidden\n layer.\n :param torch.nn.modules.activation function: activation function at each\n layer. A single activation function can be passed or a list of them of\n length equal to the number of hidden layers.\n :param list stop_training: list with the maximum number of training\n iterations (int) and/or the desired tolerance on the training loss\n (float).\n :param torch.nn.Module loss: loss definition (Mean Squared if not given).\n :param torch.optim optimizer: the torch class implementing optimizer.\n Default value is `Adam` optimizer.\n :param float lr: the learning rate. Default is 0.001.\n :param float l2_regularization: the L2 regularization coefficient, it\n corresponds to the \"weight_decay\". Default is 0 (no regularization).\n :param int frequency_print: the frequency in terms of epochs of the print\n during the training of the network.\n :param boolean last_identity: Flag to specify if the last activation\n function is the identity function. In the case the user provides the\n entire list of activation functions, this attribute is ignored. Default\n value is True.\n\n :Example:\n >>> import ezyrb\n >>> import numpy as np\n >>> import torch.nn as nn\n >>> x = np.random.uniform(-1, 1, size =(4, 2))\n >>> y = np.array([np.sin(x[:, 0]), np.cos(x[:, 1]**3)]).T\n >>> ann = ezyrb.ANN([10, 5], nn.Tanh(), [20000,1e-5])\n >>> ann.fit(x, y)\n >>> y_pred = ann.predict(x)\n >>> print(y)\n >>> print(y_pred)\n >>> print(len(ann.loss_trend))\n >>> print(ann.loss_trend[-1])\n \"\"\"\n def __init__(self, layers, function, stop_training, loss=None,\n optimizer=torch.optim.Adam, lr=0.001, l2_regularization=0,\n frequency_print=10, last_identity=True):\n if loss is None:\n loss = torch.nn.MSELoss()\n\n if not isinstance(function, list): # Single activation function passed\n nl = len(layers) if last_identity else len(layers)+1\n function = [function] * nl\n\n if not isinstance(stop_training, list):\n stop_training = [stop_training]\n\n self.layers = layers\n self.function = function\n self.loss = loss\n self.stop_training = stop_training\n\n self.loss_trend = []\n self.model = None\n self.optimizer = optimizer\n\n self.frequency_print = frequency_print\n self.lr = lr\n self.l2_regularization = l2_regularization\n\n def _convert_numpy_to_torch(self, array):\n \"\"\"\n Converting data type.\n\n :param numpy.ndarray array: input array.\n :return: the tensorial counter-part of the input array.\n :rtype: torch.Tensor.\n \"\"\"\n return torch.from_numpy(array).float()\n\n def _convert_torch_to_numpy(self, tensor):\n \"\"\"\n Converting data type.\n\n :param torch.Tensor tensor: input tensor.\n :return: the vectorial counter-part of the input tensor.\n :rtype: numpy.ndarray.\n \"\"\"\n return tensor.detach().numpy()\n\n @staticmethod\n def _list_to_sequential(layers, functions):\n\n layers_torch = []\n inout_layers = [[layers[i], layers[i+1]] for i in range(len(layers)-1)]\n\n while True:\n if inout_layers:\n inp_d, out_d = inout_layers.pop(0)\n layers_torch.append(nn.Linear(inp_d, out_d))\n\n if functions:\n layers_torch.append(functions.pop(0))\n\n if not functions and not inout_layers:\n break\n\n return nn.Sequential(*layers_torch)\n\n def _build_model(self, points, values):\n \"\"\"\n Build the torch model.\n Considering the number of neurons per layer (self.layers), a\n feed-forward NN is defined:\n - activation function from layer i>=0 to layer i+1:\n self.function[i]; activation function at the output layer:\n Identity (by default).\n :param numpy.ndarray points: the coordinates of the given (training)\n points.\n :param numpy.ndarray values: the (training) values in the points.\n \"\"\"\n layers = self.layers.copy()\n layers.insert(0, points.shape[1])\n layers.append(values.shape[1])\n\n self.model = self._list_to_sequential(layers, self.function)\n\n def fit(self, points, values):\n \"\"\"\n Build the ANN given 'points' and 'values' and perform training.\n\n Training procedure information:\n - optimizer: Adam's method with default parameters (see, e.g.,\n https://pytorch.org/docs/stable/optim.html);\n - loss: self.loss (if none, the Mean Squared Loss is set by\n default).\n - stopping criterion: the fulfillment of the requested tolerance\n on the training loss compatibly with the prescribed budget of\n training iterations (if type(self.stop_training) is list); if\n type(self.stop_training) is int or type(self.stop_training) is\n float, only the number of maximum iterations or the accuracy\n level on the training loss is considered as the stopping rule,\n respectively.\n\n :param numpy.ndarray points: the coordinates of the given (training)\n points.\n :param numpy.ndarray values: the (training) values in the points.\n \"\"\"\n\n self._build_model(points, values)\n optimizer = self.optimizer(\n self.model.parameters(),\n lr=self.lr, weight_decay=self.l2_regularization)\n\n points = self._convert_numpy_to_torch(points)\n values = self._convert_numpy_to_torch(values)\n\n n_epoch = 1\n flag = True\n while flag:\n y_pred = self.model(points)\n\n loss = self.loss(y_pred, values)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n scalar_loss = loss.item()\n self.loss_trend.append(scalar_loss)\n\n for criteria in self.stop_training:\n if isinstance(criteria, int): # stop criteria is an integer\n if n_epoch == criteria:\n flag = False\n elif isinstance(criteria, float): # stop criteria is float\n if scalar_loss < criteria:\n flag = False\n\n if (flag is False or\n n_epoch == 1 or n_epoch % self.frequency_print == 0):\n print(f'[epoch {n_epoch:6d}]\\t{scalar_loss:e}')\n\n n_epoch += 1\n\n return optimizer\n\n def predict(self, new_point):\n \"\"\"\n Evaluate the ANN at given 'new_points'.\n\n :param array_like new_points: the coordinates of the given points.\n :return: the predicted values via the ANN.\n :rtype: numpy.ndarray\n \"\"\"\n new_point = self._convert_numpy_to_torch(np.array(new_point))\n y_new = self.model(new_point)\n return self._convert_torch_to_numpy(y_new)\n","sub_path":"ezyrb/ann.py","file_name":"ann.py","file_ext":"py","file_size_in_byte":7395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"93054254","text":"from django.shortcuts import render, redirect\nfrom pure_pagination import Paginator, EmptyPage\nfrom django.core.urlresolvers import reverse\nfrom django.conf import settings\nfrom django.forms import ModelForm\nfrom .models import *\n\nRESULTS_PER_PAGE = getattr(settings, 'RESULTS_PER_PAGE', 20)\n\n\nclass NewsForm(ModelForm):\n class Meta:\n model = News\n exclude = ('reporter', 'content_type',)\n\nclass GameForm(ModelForm):\n def __init__(self, *args, **kwargs):\n super(GameForm, self).__init__(*args, **kwargs)\n ct = ContentType.objects.get(model='company')\n self.fields[\"company\"].queryset = Company.objects.filter(content_type=ct)\n\n class Meta:\n model = Game\n exclude = ('reporter', 'content_type', 'album', )\n\n# Create your views here.\n\ndef index(request):\n ct = ContentType.objects.get(model='news')\n news_list = News.objects.filter(content_type=ct).order_by('-created_date').select_related('reporter')#.prefetch_related('comments', 'related_to__a', 'related_to__a__content_type', 'related_from__b', 'related_from__b__content_type')\n\n paginator = Paginator(news_list, RESULTS_PER_PAGE)\n try:\n page = int(request.GET.get('page', 1))\n except ValueError:\n page = 1\n try:\n news_list = paginator.page(page)\n except EmptyPage:\n news_list = paginator.page(paginator.num_pages)\n\n return render(request, 'index.html', {\n 'news_list': news_list,\n })\n\ndef news(request, news_id):\n news = News.objects.filter(pk=news_id).select_related('reporter').prefetch_related('comments','comments__reporter', 'related_to', 'related_to__a', 'related_to__a__content_type', 'related_from', 'related_from__b', 'related_from__b__content_type')\n return render(request, 'news_item.html', {\n 'news': news[0],\n })\n\ndef news_modify(request, news_id = None):\n try:\n instance = News.objects.get(pk=news_id)\n except News.DoesNotExist:\n instance = None\n\n if request.method == 'POST': # If the form has been submitted...\n form = NewsForm(request.POST, instance=instance)\n if form.is_valid():\n news = form.save(commit=False)\n news.reporter = request.user\n news.save()\n return redirect('news', news.pk)\n else:\n form = NewsForm(instance=instance)\n\n return render(request, 'news_modify.html',{\n 'form': form,\n 'instance': instance,\n })\n\ndef games(request):\n games_list = Game.objects.all().order_by('-created_date').select_related('reporter','album','company')#.prefetch_related('comments')\n\n paginator = Paginator(games_list, RESULTS_PER_PAGE)\n try:\n page = int(request.GET.get('page', 1))\n except ValueError:\n page = 1\n try:\n games_list = paginator.page(page)\n except EmptyPage:\n games_list = paginator.page(paginator.num_pages)\n\n return render(request, 'games.html', {\n 'games_list': games_list,\n })\n\ndef game(request, game_id):\n game = Game.objects.filter(pk=game_id).select_related('reporter').prefetch_related('comments','comments__reporter', 'related_to__a', 'related_to__a__content_type', 'related_from__b', 'related_from__b__content_type')\n return render(request, 'game_item.html', {\n 'game': game[0],\n })\n\ndef game_modify(request, game_id = None):\n try:\n instance = Game.objects.get(pk=game_id)\n except Game.DoesNotExist:\n instance = None\n\n if request.method == 'POST': # If the form has been submitted...\n form = GameForm(request.POST, instance=instance)\n if form.is_valid():\n game = form.save(commit=False)\n game.reporter = request.user\n game.save()\n return redirect('game', game.pk)\n else:\n form = GameForm(instance=instance)\n\n return render(request, 'game_modify.html',{\n 'form': form,\n 'instance': instance,\n })\n\ndef companies(request):\n ct = ContentType.objects.get(model='company')\n comp_list = Company.objects.filter(content_type=ct).order_by('-created_date').select_related('reporter')#.prefetch_related('comments','games')\n\n paginator = Paginator(comp_list, RESULTS_PER_PAGE)\n try:\n page = int(request.GET.get('page', 1))\n except ValueError:\n page = 1\n try:\n comp_list = paginator.page(page)\n except EmptyPage:\n comp_list = paginator.page(paginator.num_pages)\n\n return render(request, 'companies.html', {\n 'comp_list': comp_list,\n })\n\ndef company(request, comp_id):\n comp = Company.objects.filter(pk=comp_id).select_related('reporter').prefetch_related('comments','comments__reporter', 'games__reporter')\n return render(request, 'company_item.html', {\n 'comp': comp[0]\n })\n","sub_path":"gtdb/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"238966867","text":"from typing import List, Dict\n\nimport attr\nfrom pydantic import BaseModel\n\nfrom .fridge import ProductInFridge, FridgeLogic, ProductUpdate\nfrom .recipe import Ingredient, Recipe\n\n\nclass ShoppingListBase(BaseModel):\n id: int = None\n items: Dict[str, float]\n\n\nclass ShoppingList(ShoppingListBase):\n fridge_id: int = None\n\n class Config:\n orm_mode = True\n\n\n@attr.s(auto_attribs=True)\nclass ShoppingListLogic:\n _fridge: FridgeLogic = None\n shopping_list: ShoppingList = None\n\n def create(self, recipes: List[Recipe]):\n self.shopping_list = ShoppingList(items={}, fridge_id=self._fridge.fridge.id)\n for recipe in recipes:\n for ingredient_in_recipe in recipe.ingredients:\n quantity_available_in_fridge = 0\n try:\n quantity_available_in_fridge = self._fridge.allocate_product(\n ProductInFridge(**ingredient_in_recipe.dict()))\n except StopIteration:\n pass\n # neglect possible mismatch of units for now\n if quantity_available_in_fridge < ingredient_in_recipe.quantity:\n self._add(ingredient_in_recipe, quantity_available_in_fridge)\n\n def update(self, products_changes: List[ProductUpdate]):\n for changed_product in products_changes:\n if changed_product.name in self.shopping_list.items:\n self.shopping_list.items[changed_product.name] -= changed_product.quantity\n self._fridge.allocate_product(changed_product)\n if self.shopping_list.items[changed_product.name] <= 0:\n del self.shopping_list.items[changed_product.name]\n\n def _add(self, ingredient_in_recipe: Ingredient, quantity_available_in_fridge: float = 0.0):\n quantity_to_buy = ingredient_in_recipe.quantity - quantity_available_in_fridge\n if ingredient_in_recipe.name in self.shopping_list.items:\n self.shopping_list.items[ingredient_in_recipe.name] += quantity_to_buy\n else:\n self.shopping_list.items[ingredient_in_recipe.name] = quantity_to_buy\n","sub_path":"app/shopping_list/domain/shopping_list.py","file_name":"shopping_list.py","file_ext":"py","file_size_in_byte":2133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"68462767","text":"exList = [1, 3, 6, 7, 15, 533]\r\n\r\nfor num in exList:\r\n if num % 2 == 0:\r\n print(num, \"can be divided by two\")\r\n elif num % 3 == 0:\r\n print(num, \"can be divided by three\")\r\n else:\r\n if num > 1:\r\n for i in range(2, num):\r\n if(num % i) == 0:\r\n print(num, \"is not a prime number\")\r\n break\r\n else:\r\n print(num, \"is a prime number\")\r\n else:\r\n print(num, \"is a technically not a prime number\")\r\n","sub_path":"PythonForSociologists/Lectures/optional_homework2.py","file_name":"optional_homework2.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"156517227","text":"import random\r\n\r\n\r\n\"\"\"\r\n快速排序\r\n使用递归,消耗内存\r\n1:确定跳出递归的条件,因为过程中不断拆分列表,所以当列表长度为1时,跳出递归\r\n2:选取列表第一个元素为为关键项,将列表中的元素与key比较,大于key的放在key之前,小于key的放在key之后\r\n3:利用key值将列表分成两个列表\r\n4:对两个列表进行步骤2,步骤3操作\r\n\"\"\"\r\n\r\n\r\ndef quicksort(arr):\r\n if len(arr) == 1: # 确定跳出递归条件\r\n return (arr)\r\n key = arr[:1] # 确定key项\r\n j = 0 # j 值确定粗排序后的分割点\r\n temparr = arr[1:] # 列表剩余项\r\n for i in range(len(temparr)): # 确认小于key的项\r\n if key[0] > temparr[i]:\r\n temparr[j], temparr[i] = temparr[i], temparr[j]\r\n j += 1 # j 值确定粗排序后的分割点\r\n result = key + temparr\r\n for i in range(j): # 对列表粗排序\r\n result[i] = result[i+1]\r\n result[j] = key[0]\r\n if j==0:\r\n j = 1\r\n left = quicksort(result[:j]) # 分割\r\n right = quicksort(result[j:])\r\n return left + right\r\n\r\narr = []\r\nfor i in range(1000):\r\n arr.append(random.randint(0, 100))\r\n\r\n# arr = [32, 45, 31, 65, 74, 48, 49, 12, 21, 32, 14]\r\nleft = arr[:1]\r\nright = arr[1:]\r\nprint(quicksort(arr))\r\n\r\n\r\n","sub_path":"sort/demo/quicksort.py","file_name":"quicksort.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"307685719","text":"from product.amazon import AmazonController, Amazon\nfrom utils import GetProxyList\nurllist = []\ndef crawlAmazon(urls):\n global urllist\n urllist = urls\n #GetProxyList.getProxy();\n onProxyUpdated()\ndef onProxyUpdated():\n for url in urllist:\n AmazonController.crawlamazon(url)\n\nif __name__ == '__main__':\n crawlAmazon([\"https://www.amazon.co.uk/Computer-Components/b/ref=nav_shopall_cc?ie=UTF8&node=428655031\"])\n","sub_path":"product/ProductController.py","file_name":"ProductController.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"644865966","text":"import numpy as np\n\n# Returns index of num element in the array if present, else -1\ndef linear_search(arr, num):\n for i in range(len(arr)):\n if arr[i] == num:\n return i\n return -1\n\n# Test array\narr = np.random.randint(0,100,20)\n# Test num\nnum = arr[13]\narr.sort()\nprint(arr, num)\n\nresult = linear_search(arr, num)\nif result == -1:\n print(\"The element is not in the array\")\nelse:\n print(f\"The element is at index {result} in the array.\")\n","sub_path":"linear_search.py","file_name":"linear_search.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"244763006","text":"import sys\n\nn, m = map(int, sys.stdin.readline().split())\n\nroot = list(range(n+1))\nheight = [0] * (n + 1)\n\ndef find_root(v):\n u = root[v]\n if u == v:\n return u\n w = find_root(u)\n root[v] = w\n return w\n\ndef merge(v, u):\n rv = find_root(v)\n ru = find_root(u)\n if rv != ru:\n if height[v] >= height[u]:\n root[ru] = rv\n height[v] = max(height[v], height[v] + 1)\n else:\n root[rv] = ru\n\ngraph = [[] for _ in range(n+1)]\nfor l, r, d in zip(*[map(int, sys.stdin.read().split())] * 3):\n graph[l].append((r, d))\n graph[r].append((l, -d))\n merge(l, r)\n\nfor v in range(1, n+1):\n find_root(v)\n\ndef main():\n dist = [None] * (n + 1)\n for v in set(root[1:]):\n dist[v] = 0\n stack = [v]\n while stack:\n x = stack.pop()\n for y, d in graph[x]:\n if dist[y] is None:\n dist[y] = dist[x] + d\n stack.append(y)\n elif dist[y] != dist[x] + d:\n return 'No'\n return 'Yes'\n \nif __name__ == '__main__':\n ans = main()\n print(ans)","sub_path":"Python_codes/p03450/s254502748.py","file_name":"s254502748.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"305242237","text":"import base64\nfrom cryptography import fernet\nfrom aiohttp import web\nfrom aiohttp_session import setup, get_session\nfrom aiohttp_session.cookie_storage import EncryptedCookieStorage\n\n\ndef flash(request, message):\n request.setdefault('flash_outgoing', []).append(message)\n\n\ndef get_messages(request):\n return request.pop('flash_incoming')\n\n\nasync def flash_middleware(app, handler):\n async def process(request):\n session = await get_session(request)\n request['flash_incoming'] = session.pop('flash', [])\n response = await handler(request)\n session['flash'] = (request.get('flash_incoming', []) +\n request.get('flash_outgoing', []))\n return response\n return process\n\n\nasync def flash_handler(request):\n flash(request, 'You have just visited flash page')\n return web.HTTPFound('/')\n\n\nasync def handler(request):\n text = 'No flash messages yet'\n messages = get_messages(request)\n if messages:\n text = 'Messages: {}'.format(','.join(messages))\n return web.Response(text=text)\n\n\ndef make_app():\n app = web.Application()\n # secret_key must be 32 url-safe base64-encoded bytes\n fernet_key = fernet.Fernet.generate_key()\n secret_key = base64.urlsafe_b64decode(fernet_key)\n setup(app, EncryptedCookieStorage(secret_key))\n app.router.add_get('/', handler)\n app.router.add_get('/flash', flash_handler)\n # Install flash middleware\n app.middlewares.append(flash_middleware)\n return app\n\n\nweb.run_app(make_app())\n\n","sub_path":"demo/flash_messages_example.py","file_name":"flash_messages_example.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"123707990","text":"import socket\nimport threading\nimport RPi.GPIO as GPIO\nimport time\n\n# LED1灯\npins = {'pin_R': 17, 'pin_G': 27, 'pin_B': 22} # pins is a dict\n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM) # Numbers GPIOs by physical location\nfor i in pins:\n GPIO.setup(pins[i], GPIO.OUT) # Set pins' mode is output\n GPIO.output(pins[i], GPIO.HIGH) # Set pins to high(+3.3V) to off led\n\np_R = GPIO.PWM(pins['pin_R'], 2000)\np_G = GPIO.PWM(pins['pin_G'], 2000)\np_B = GPIO.PWM(pins['pin_B'], 5000)\n\np_R.start(100) # Initial duty Cycle = 100(leds off)\np_G.start(100)\np_B.start(100)\n\n\n#烟雾1\nCHANNEL1=21 # 确定引脚口。按照真实的位置确定\nGPIO.setmode(GPIO.BCM) # 选择引脚系统,这里我们选择了BCM,也可以换BOARD\nGPIO.setup(CHANNEL1,GPIO.IN,pull_up_down=GPIO.PUD_DOWN)\n\n#烟雾2\nCHANNEL2=20 # 确定引脚口。按照真实的位置确定\nGPIO.setmode(GPIO.BCM) # 选择引脚系统,这里我们选择了BCM,也可以换BOARD\nGPIO.setup(CHANNEL2,GPIO.IN,pull_up_down=GPIO.PUD_DOWN)\n\n# 蜂鸣器 pin24\nBuzzer = 24\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM) # Numbers GPIOs by physical location\nGPIO.setup(Buzzer, GPIO.OUT)\nGPIO.output(Buzzer, GPIO.HIGH)\n\n# 火焰传感器1 pin25\npin_fire = 25\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(pin_fire, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n\n# 火焰传感器2 18\npin_fire2 = 18\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(pin_fire2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n\n# 1 创建tcp套接字\ntcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n# 2 创建连接\ntcp_socket.connect(('192.168.137.157', 8080))\n\n\n# RGB_LED\ndef map(x, in_min, in_max, out_min, out_max): # 将一个数从一个区间线性映射到另一个区间,比如将0~100之间的一个数映射到0~255之间\n return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min\n\n\ndef leds(col):\n R_val = (col & 0xFF0000) >> 16\n G_val = (col & 0x00FF00) >> 8\n B_val = (col & 0x0000FF) >> 0\n\n R_val = map(R_val, 0, 255, 0, 100) # change a num(0~255) to 0~100.\n G_val = map(G_val, 0, 255, 0, 100)\n B_val = map(B_val, 0, 255, 0, 100)\n\n return R_val, G_val, B_val\n\n\ndef setColor(col): # For example : col = 0x112233\n r_val, g_val, b_val = leds(col)\n p_R.ChangeDutyCycle(100 - r_val) # Change duty cycle\n p_G.ChangeDutyCycle(100 - g_val)\n p_B.ChangeDutyCycle(100 - b_val)\n\n# 蜂鸣器\ndef on():\n GPIO.output(Buzzer, GPIO.LOW)\n\ndef off():\n GPIO.output(Buzzer, GPIO.HIGH)\n\n\n# 发送烟雾数据1\ndef sendyanwu1():\n try:\n while True:\n status1 = GPIO.input(CHANNEL1) # 检测引脚口的输入高低电平状态\n # print(status) # 实时打印此时的电平状态\n if status1 == True: # 如果为高电平,说明MQ-2正常,并打印“OK”\n off()\n tcp_input = \"B正常\"\n tcp_socket.send(tcp_input.encode('gbk'))\n else: # 如果为低电平,说明MQ-2检测到有害气体,并打印“dangerous”\n on()\n tcp_input = \"B检测到有害气体\"\n tcp_socket.send(tcp_input.encode('gbk'))\n time.sleep(2) # 睡眠5秒,以后再执行while循环\n except KeyboardInterrupt: # 异常处理,当检测按下键盘的Ctrl+C,就会退出这个>脚本\n GPIO.cleanup() # 清理运行完成后的残余\n\n# 发送烟雾数据2\ndef sendyanwu2():\n time.sleep(3)\n try:\n while True:\n status2 = GPIO.input(CHANNEL2) # 检测引脚口的输入高低电平状态\n # print(status) # 实时打印此时的电平状态\n if status2 == True: # 如果为高电平,说明MQ-2正常,并打印“OK”\n off()\n tcp_input = \"E正常\"\n tcp_socket.send(tcp_input.encode('gbk'))\n else: # 如果为低电平,说明MQ-2检测到有害气体,并打印“dangerous”\n on()\n tcp_input = \"E检测到有害气体\"\n tcp_socket.send(tcp_input.encode('gbk'))\n time.sleep(2) # 睡眠5秒,以后再执行while循环\n except KeyboardInterrupt: # 异常处理,当检测按下键盘的Ctrl+C,就会退出这个>脚本\n GPIO.cleanup() # 清理运行完成后的残余\n\n# 发送火焰传感器1状态\ndef sendhuoyan():\n flage1 = 1\n while True:\n status = GPIO.input(pin_fire)\n if status == True and flage1 == 1:\n off()\n tcp_input = 'C正常'\n tcp_socket.send(tcp_input.encode('gbk'))\n flage1 = 0\n elif status == False:\n on()\n tcp_input = 'C检测到火源'\n tcp_socket.send(tcp_input.encode('gbk'))\n flage1 = 1\n time.sleep(3)\n time.sleep(0.5)\n\n\n# 发送火焰传感器2状态\ndef sendhuoyan2():\n flage2 = 1\n time.sleep(5)\n while True:\n status2 = GPIO.input(pin_fire2)\n if status2 == True and flage2 == 1:\n off()\n tcp_input = 'D正常'\n tcp_socket.send(tcp_input.encode('gbk'))\n flage2 = 0\n elif status2 == False:\n on()\n tcp_input = 'D检测到火源'\n tcp_socket.send(tcp_input.encode('gbk'))\n flage2 = 1\n time.sleep(3)\n time.sleep(0.5)\n\n\n# 接收PC端控制LED灯的命令\ndef revice_led():\n # 接收响应,最大为1024字节\n response = tcp_socket.recv(1024).decode(\"gbk\")\n while response:\n print(\"来自服务器的数据:%s\" % response)\n if response == \"1已打开\":\n setColor(0xFF0000)\n # print(\"111111\")\n elif response == \"1已关闭\":\n setColor(0xFFFFFF)\n # print(\"222222\")\n response = tcp_socket.recv(1024).decode(\"gbk\")\n # 4.关闭套接字\n tcp_socket.close()\n\n\n\ndef revice():\n while True:\n # 接收响应,最大为1024字节\n response = tcp_socket.recv(1024).decode(\"gbk\")\n print(\"来自服务器的数据:%s\" % response)\n\n # 4.关闭套接字\n # tcp_socket.close()\n\n\nwhile True:\n # 创建线程\n thread_msg1 = threading.Thread(target=revice_led, )\n thread_msg2 = threading.Thread(target=sendyanwu1, )\n thread_msg5 = threading.Thread(target=sendyanwu2, )\n thread_msg3 = threading.Thread(target=sendhuoyan, )\n thread_msg4 = threading.Thread(target=sendhuoyan2, )\n # 子线程守护主线程\n thread_msg1.setDaemon(True)\n thread_msg2.setDaemon(True)\n thread_msg3.setDaemon(True)\n thread_msg4.setDaemon(True)\n thread_msg5.setDaemon(True)\n # 启动线程\n thread_msg1.start()\n thread_msg2.start()\n thread_msg3.start()\n thread_msg4.start()\n thread_msg5.start()\n\n thread_msg1.join()\n thread_msg2.join()\n thread_msg3.join()\n thread_msg4.join()\n thread_msg5.join()\n","sub_path":"client/piclient.py","file_name":"piclient.py","file_ext":"py","file_size_in_byte":6880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"494748428","text":"nama = 'Churun Jauharoh A'\nprogram = 'Gerak lurus'\n\nprint(f'program {program} oleh {nama}')\n\ndef hitung_usaha(gaya, perpindahan):\n usaha = gaya * perpindahan\n print(f'gaya = {gaya}Newton bekerja pada materi sejauh = {perpindahan}meter')\n print(f'sehingga usaha = {usaha} Nm')\n return usaha\n\n# gaya = 10\n# perpindahan = 27\nusaha = hitung_usaha(10, 27)\nusaha = hitung_usaha(5 * 10, 70)\n\n","sub_path":"mine.py","file_name":"mine.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"414474084","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='BasicConfiguration',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('company_name', models.CharField(max_length=255, verbose_name=b'Nombre de la empresa')),\n ],\n ),\n migrations.CreateModel(\n name='Manufacturer',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=255, verbose_name=b'Name')),\n ],\n options={\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='Supplier',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=255, verbose_name=b'Name')),\n ],\n options={\n 'abstract': False,\n },\n ),\n ]\n","sub_path":"kstore/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"330884640","text":"# set.py\n\nr'''The assignment statement.\n'''\n\nfrom ucc.database import block\nfrom ucclib.built_in import singleton\n\nclass set(singleton.singleton):\n def update_expect(self, ast_node):\n ast_node.args[1][0].expect = 'lvalue'\n\n def compile_statement(self, ast_node):\n assert len(ast_node.args) == 2\n assert len(ast_node.args[1]) == 2, \\\n \"incorrect number of arguments to 'set', expected 2, got {}\" \\\n .format(len(ast_node.args[1]))\n\n lvalue, rvalue = ast_node.args[1]\n\n assert lvalue.kind in ('word', 'ioreg'), \\\n \"set: can only assign to variables or ioregs, \" \\\n \"fancier assignments not implemented\"\n\n ans = rvalue.compile()\n if lvalue.kind == 'word':\n block.Current_block.label(lvalue.symbol_id, ans)\n return ans\n return block.Current_block.gen_triple('output', (ans,),\n string=lvalue.label)\n\n","sub_path":"ucclib/built_in/set.py","file_name":"set.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"280133465","text":"import plotly.graph_objs as go\nimport plotly\nfrom retrieve_data import DataLoader, RESOURCE\n\n\nclass Task1:\n def __init__(self):\n self.loader = DataLoader(RESOURCE.TEMPERATURE)\n self.data = {i: -1 for i in range(1, 49)}\n\n def _get_data(self, time):\n if self.data[time] != -1:\n return self.data[time]\n else:\n self.data[time] = self.loader.get_data(time)\n return self.data[time]\n\n def _get_df(self, time, height):\n data = self._get_data(time)\n df = data[height]\n return df\n\n def render(self, time, height):\n\n df = self._get_df(time, height)\n trace = go.Contour(\n z=df.values,\n colorbar=go.ColorBar(\n title='Degree Celcius'\n ),\n )\n data = [trace]\n\n layout = go.Layout(\n title='Temperatur for t={} and Altitude (z={}): {:.1f} km'.format(str(time).lstrip('0'), height, height*0.2),\n xaxis = dict(\n title='Longitude'\n ),\n yaxis = dict(\n title='Latitude'\n ),\n )\n\n fig = go.Figure(data=data, layout=layout)\n plotly.offline.iplot(fig)\n","sub_path":"ex2/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"405618423","text":"from django.shortcuts import render\n\ndef welcome(request):\n return render(request, 'index.html', {'msg':'Hello World!'})\n\ndef restaurant_list(request):\n\n context = {\n \"my_list\": [{\n\n \"restaurant_name\" : \"White Robata\",\n \"food_type\" : \"Japanese food\"},\n {\"restaurant_name\" : \"Chipolte\",\n \"food_type\" : \"Mexican food\"},\n {\"restaurant_name\" : \"PF Changs\",\n \"food_type\" : \"Chinese food\"},]\n\n }\n return render(request, 'list.html', context)\n\n\ndef restaurant_detail(request):\n\n context = {\n \"my_object\": {\n\n \"restaurant_name\": \"Mishmash\",\n \"food_type\": \"Lebanese food\",\n \n\n }\n\n }\n return render(request, 'detail.html', context)\n","sub_path":"restaurants/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"590135379","text":"#enconding: UTF-8\n#Alejandro Chávez Campos, A01374974\n#Este programa es para mostrar un el número romano que corresponde a un número dado por el usuario.\n\ndef calcularRomano(numero): #Determina el número romano a partir del número\n if numero>=1 and numero<=3 :\n romano= numero*\"I\"\n return romano\n elif numero >=4 and numero <=5 :\n romano =(5-numero)*\"I\"\n strRomano =(\"{}V\".format(romano))\n return strRomano\n elif numero>5 and numero<=8 :\n romano= (numero-5)*\"I\"\n strRomano= (\"V{}\".format(romano))\n return strRomano\n elif numero >= 9 and numero <=10 :\n romano=(10-numero)*\"I\"\n strRomano = (\"{}X\".format(romano))\n return strRomano\n\ndef main(): #Programa principal\n numero=int(input(\"Dame el número :\"))\n\n if numero >=1 and numero<=10:\n strRomano = calcularRomano(numero)\n print(\"El número {} equivale a {} \".format(numero, strRomano))\n\n else:\n print (\"Error\")\n\nmain()","sub_path":"NumerosRomanos.py","file_name":"NumerosRomanos.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"623858693","text":"\nfrom cloudify import ctx\nfrom cloudify import utils\nfrom cloudify.exceptions import NonRecoverableError\nfrom StringIO import StringIO\n\nimport base64\nimport os\nimport platform\nimport re\nimport subprocess\nimport sys\nimport time\nimport threading\nimport platform\nimport json\n\ndef convert_env_value_to_string(envDict):\n for key, value in envDict.items():\n envDict[str(key)] = str(envDict.pop(key))\n\ndef get_attribute_user(ctx):\n if get_attribute_from_top_host(ctx, 'user'):\n return get_attribute_from_top_host(ctx, 'user')\n if get_attribute(ctx, 'cloudify_agent'):\n return get_attribute(ctx, 'cloudify_agent').get('user', None)\n if get_attribute(ctx, 'agent_config'):\n return get_attribute(ctx, 'agent_config').get('user', None)\n return None\n\ndef get_attribute_key(ctx):\n if get_attribute_from_top_host(ctx, 'key'):\n return get_attribute_from_top_host(ctx, 'key')\n if get_attribute(ctx, 'cloudify_agent'):\n return get_attribute(ctx, 'cloudify_agent').get('key', None)\n if get_attribute(ctx, 'agent_config'):\n return get_attribute(ctx, 'agent_config').get('key', None)\n return None\n\ndef get_host(entity):\n if entity.instance.relationships:\n for relationship in entity.instance.relationships:\n if 'cloudify.relationships.contained_in' in relationship.type_hierarchy:\n return relationship.target\n return None\n\n\ndef has_attribute_mapping(entity, attribute_name):\n # ctx.logger.debug('Check if it exists mapping for attribute {0} in {1}'.format(attribute_name,json.dumps(entity.node.properties)))\n mapping_configuration = entity.node.properties.get('_a4c_att_' + attribute_name, None)\n if mapping_configuration is not None:\n if mapping_configuration['parameters'][0] == 'SELF' and mapping_configuration['parameters'][1] == attribute_name:\n return False\n else:\n return True\n return False\n\n\ndef process_attribute_mapping(entity, attribute_name, data_retriever_function):\n # This is where attribute mapping is defined in the cloudify type\n mapping_configuration = entity.node.properties['_a4c_att_' + attribute_name]\n # ctx.logger.debug('Mapping configuration found for attribute {0} is {1}'.format(attribute_name, json.dumps(mapping_configuration)))\n # If the mapping configuration exist and if it concerns SELF then just get attribute of the mapped attribute name\n # Else if it concerns TARGET then follow the relationship and retrieved the mapped attribute name from the TARGET\n if mapping_configuration['parameters'][0] == 'SELF':\n return data_retriever_function(entity, mapping_configuration['parameters'][1])\n elif mapping_configuration['parameters'][0] == 'TARGET' and entity.instance.relationships:\n for relationship in entity.instance.relationships:\n if mapping_configuration['parameters'][1] in relationship.type_hierarchy:\n return data_retriever_function(relationship.target, mapping_configuration['parameters'][2])\n return \"\"\n\n\ndef get_nested_attribute(entity, attribute_names):\n deep_properties = get_attribute(entity, attribute_names[0])\n attribute_names_iter = iter(attribute_names)\n next(attribute_names_iter)\n for attribute_name in attribute_names_iter:\n if deep_properties is None:\n return \"\"\n else:\n deep_properties = deep_properties.get(attribute_name, None)\n return deep_properties\n\n\ndef _all_instances_get_nested_attribute(entity, attribute_names):\n return None\n\n\ndef get_attribute(entity, attribute_name):\n if has_attribute_mapping(entity, attribute_name):\n # First check if any mapping exist for attribute\n mapped_value = process_attribute_mapping(entity, attribute_name, get_attribute)\n # ctx.logger.debug('Mapping exists for attribute {0} with value {1}'.format(attribute_name, json.dumps(mapped_value)))\n return mapped_value\n # No mapping exist, try to get directly the attribute from the entity\n attribute_value = entity.instance.runtime_properties.get(attribute_name, None)\n if attribute_value is not None:\n # ctx.logger.debug('Found the attribute {0} with value {1} on the node {2}'.format(attribute_name, json.dumps(attribute_value), entity.node.id))\n return attribute_value\n # Attribute retrieval fails, fall back to property\n property_value = entity.node.properties.get(attribute_name, None)\n if property_value is not None:\n return property_value\n # Property retrieval fails, fall back to host instance\n host = get_host(entity)\n if host is not None:\n # ctx.logger.debug('Attribute not found {0} go up to the parent node {1}'.format(attribute_name, host.node.id))\n return get_attribute(host, attribute_name)\n # Nothing is found\n return \"\"\n\ndef get_target_capa_or_node_attribute(entity, capability_attribute_name, attribute_name):\n attribute_value = entity.instance.runtime_properties.get(capability_attribute_name, None)\n if attribute_value is not None:\n # ctx.logger.debug('Found the capability attribute {0} with value {1} on the node {2}'.format(attribute_name, json.dumps(attribute_value), entity.node.id))\n return attribute_value\n return get_attribute(entity, attribute_name)\n\ndef _all_instances_get_attribute(entity, attribute_name):\n result_map = {}\n # get all instances data using cfy rest client\n # we have to get the node using the rest client with node_instance.node_id\n # then we will have the relationships\n node = client.nodes.get(ctx.deployment.id, entity.node.id)\n all_node_instances = client.node_instances.list(ctx.deployment.id, entity.node.id)\n for node_instance in all_node_instances:\n prop_value = __recursively_get_instance_data(node, node_instance, attribute_name)\n if prop_value is not None:\n # ctx.logger.debug('Found the property/attribute {0} with value {1} on the node {2} instance {3}'.format(attribute_name, json.dumps(prop_value), entity.node.id,\n # node_instance.id))\n result_map[node_instance.id + '_'] = prop_value\n return result_map\n\n# Same as previous method but will first try to find the attribute on the capability.\ndef _all_instances_get_target_capa_or_node_attribute(entity, capability_attribute_name, attribute_name):\n result_map = {}\n node = client.nodes.get(ctx.deployment.id, entity.node.id)\n all_node_instances = client.node_instances.list(ctx.deployment.id, entity.node.id)\n for node_instance in all_node_instances:\n attribute_value = node_instance.runtime_properties.get(capability_attribute_name, None)\n if attribute_value is not None:\n prop_value = attribute_value\n else:\n prop_value = __recursively_get_instance_data(node, node_instance, attribute_name)\n if prop_value is not None:\n # ctx.logger.debug('Found the property/attribute {0} with value {1} on the node {2} instance {3}'.format(attribute_name, json.dumps(prop_value), entity.node.id,\n # node_instance.id))\n result_map[node_instance.id + '_'] = prop_value\n return result_map\n\ndef get_property(entity, property_name):\n # Try to get the property value on the node\n property_value = entity.node.properties.get(property_name, None)\n if property_value is not None:\n # ctx.logger.debug('Found the property {0} with value {1} on the node {2}'.format(property_name, json.dumps(property_value), entity.node.id))\n return property_value\n # No property found on the node, fall back to the host\n host = get_host(entity)\n if host is not None:\n # ctx.logger.debug('Property not found {0} go up to the parent node {1}'.format(property_name, host.node.id))\n return get_property(host, property_name)\n return \"\"\n\n\ndef get_instance_list(node_id):\n result = ''\n all_node_instances = client.node_instances.list(ctx.deployment.id, node_id)\n for node_instance in all_node_instances:\n if len(result) > 0:\n result += ','\n result += node_instance.id\n return result\n\ndef get_host_node_name(instance):\n for relationship in instance.relationships:\n if 'cloudify.relationships.contained_in' in relationship.type_hierarchy:\n return relationship.target.node.id\n return None\n\ndef __get_relationship(node, target_name, relationship_type):\n for relationship in node.relationships:\n if relationship.get('target_id') == target_name and relationship_type in relationship.get('type_hierarchy'):\n return relationship\n return None\n\n\ndef __has_attribute_mapping(node, attribute_name):\n # ctx.logger.debug('Check if it exists mapping for attribute {0} in {1}'.format(attribute_name, json.dumps(node.properties)))\n mapping_configuration = node.properties.get('_a4c_att_' + attribute_name, None)\n if mapping_configuration is not None:\n if mapping_configuration['parameters'][0] == 'SELF' and mapping_configuration['parameters'][1] == attribute_name:\n return False\n else:\n return True\n return False\n\ndef __process_attribute_mapping(node, node_instance, attribute_name, data_retriever_function):\n # This is where attribute mapping is defined in the cloudify type\n mapping_configuration = node.properties['_a4c_att_' + attribute_name]\n # ctx.logger.debug('Mapping configuration found for attribute {0} is {1}'.format(attribute_name, json.dumps(mapping_configuration)))\n # If the mapping configuration exist and if it concerns SELF then just get attribute of the mapped attribute name\n # Else if it concerns TARGET then follow the relationship and retrieved the mapped attribute name from the TARGET\n if mapping_configuration['parameters'][0] == 'SELF':\n return data_retriever_function(node, node_instance, mapping_configuration['parameters'][1])\n elif mapping_configuration['parameters'][0] == 'TARGET' and node_instance.relationships:\n for rel in node_instance.relationships:\n relationship = __get_relationship(node, rel.get('target_name'), rel.get('type'))\n if mapping_configuration['parameters'][1] in relationship.get('type_hierarchy'):\n target_instance = client.node_instances.get(rel.get('target_id'))\n target_node = client.nodes.get(ctx.deployment.id, target_instance.node_id)\n return data_retriever_function(target_node, target_instance, mapping_configuration['parameters'][2])\n return None\n\ndef __recursively_get_instance_data(node, node_instance, attribute_name):\n if __has_attribute_mapping(node, attribute_name):\n return __process_attribute_mapping(node, node_instance, attribute_name, __recursively_get_instance_data)\n attribute_value = node_instance.runtime_properties.get(attribute_name, None)\n if attribute_value is not None:\n return attribute_value\n elif node_instance.relationships:\n for rel in node_instance.relationships:\n # on rel we have target_name, target_id (instanceId), type\n relationship = __get_relationship(node, rel.get('target_name'), rel.get('type'))\n if 'cloudify.relationships.contained_in' in relationship.get('type_hierarchy'):\n parent_instance = client.node_instances.get(rel.get('target_id'))\n parent_node = client.nodes.get(ctx.deployment.id, parent_instance.node_id)\n return __recursively_get_instance_data(parent_node, parent_instance, attribute_name)\n return None\n else:\n return None\n\ndef get_public_or_private_ip(entity):\n public_ip = get_attribute(entity, 'public_ip_address')\n if not public_ip:\n return get_attribute(entity, 'ip_address')\n return public_ip\n\ndef get_attribute_from_top_host(entity, attribute_name):\n host = get_host(entity)\n while host is not None:\n entity = host\n host = get_host(entity)\n return get_attribute(entity, attribute_name)\n\nctx.instance.runtime_properties['tosca_id'] = ctx.instance.id\nctx.instance.runtime_properties['tosca_name'] = ctx.node.id\n\nctx.instance.runtime_properties['zip_url'] = r'https://wordpress.org/latest.zip'\nctx.instance.runtime_properties['context_root'] = r'/'\n\nctx.instance.runtime_properties['capabilities.app_endpoint.protocol'] = r'tcp'\nctx.instance.runtime_properties['capabilities.app_endpoint.secure'] = r'false'\nctx.instance.runtime_properties['capabilities.app_endpoint.network_name'] = r'PRIVATE'\nctx.instance.runtime_properties['capabilities.app_endpoint.initiator'] = r'source'\nctx.instance.runtime_properties['capabilities.app_endpoint.ip_address'] = get_attribute(ctx, 'ip_address')\n\nctx.instance.runtime_properties['requirements.database.ip_address'] = get_attribute(ctx, 'ip_address')\n","sub_path":"src/test/resources/outputs/blueprints/openstack/lamp/wrapper/wordpress/org.alien4cloud.interfaces.cfy.lifecycle/NodeInit/_a4c_NodeInit.py","file_name":"_a4c_NodeInit.py","file_ext":"py","file_size_in_byte":12810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"587078255","text":"from math import sqrt\nimport numpy\n\nusers = {\n \"Ania\": \n {\"Blues Traveler\": 1.,\n \"Broken Bells\": 1.5,\n \"Norah Jones\": 2,\n \"Deadmau5\": 2.5,\n \"Phoenix\": 3.0,\n \"Slightly Stoopid\": .5,\n \"The Strokes\": 0.0,\n \"Vampire Weekend\": 2.0},\n \"Bonia\":\n {\"Blues Traveler\": 4.0,\n \"Broken Bells\": 4.5, \n \"Norah Jones\": 5.0,\n \"Deadmau5\": 5.5, \n \"Phoenix\": 6.0, \n \"Slightly Stoopid\": 3.5, \n \"The Strokes\": 2.0,\n \"Vampire Weekend\": 5.0}\n }\n\ndef wspKorelacji(osoba1, osoba2, slownik):\n os1 = slownik[osoba1]\n os2 = slownik[osoba2]\n sumxy = 0\n sumx = 0\n sumy = 0\n sumx2 = 0\n sumy2 = 0\n i = 0\n for j in os1:\n for k in os2:\n if j==k:\n sumxy = sumxy+os1[j]*os2[j]\n sumx = sumx+os1[j]\n sumy = sumy+os2[j]\n sumx2 = sumx2+os1[j]**2\n sumy2 = sumy2+os2[j]**2\n i+=1\n return (sumxy-(sumx*sumy)/i)/(sqrt(sumx2-(sumx**2)/i)*sqrt(sumy2-(sumy**2)/i)) \n \n\ndef pearsonNumpy(osoba1, osoba2):\n osoba1=osoba1.values()\n osoba2=osoba2.values()\n return numpy.corrcoef(osoba1, osoba2)\n\nprint(wspKorelacji('Ania','Bonia',users))\nprint(str(pearsonNumpy(users['Ania'],users['Bonia'])[0,1]))\n","sub_path":"lab04.py","file_name":"lab04.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"156096936","text":"# Given a sequence of non-negative integers, where each number is written in a separate line. The sequence ends with 0. Print the index of the first maximum of the sequence. \n\n\ndef max_input_index():\n a = int(input())\n nums = []\n while a!= 0:\n nums.append(a)\n a = int(input())\n return nums.index(max(nums))\n\n\nprint(max_input_index())","sub_path":"Warm-Ups/While_Loops/max_input_index.py","file_name":"max_input_index.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"579846764","text":"from mty_media_bot import create_app\nfrom mty_media_bot.assistant import Assistant, Friend\nfrom mty_media_bot.service.command import ExitCommand, SearchCommand\n\n\ndef run_bot():\n assistant = Assistant(\"철수\")\n friend = Friend(\"친구\")\n assistant.add_command(ExitCommand(assistant, friend))\n assistant.add_command(SearchCommand(assistant, friend))\n assistant.speak(f\"나는 {assistant.name}라고 해.\")\n assistant.speak(\"너 이름은 뭐야?\")\n word = assistant.listen()\n if word is None:\n assistant.speak(\"미안, 못 알아 들었어. 그냥 친구라 부를게\")\n else:\n friend.name = word.korean_word\n assistant.speak(f'{friend.name}, 무엇을 도와줄까?')\n while 1:\n word = assistant.listen()\n if word is None:\n assistant.speak(\"미안, 못 알아 들었어\")\n continue\n if assistant.process(word):\n assistant.speak(f'{friend.name}, 잘한거 같아?')\n else:\n assistant.speak(f'{friend.name}, 내가 못 하는 거네.')\n assistant.speak(f'{friend.name}, 다른 무엇을 도와줄까?')\n\n\nif __name__ == \"__main__\":\n create_app()\n run_bot()\n","sub_path":"mty_media_bot/audio_bot_runner.py","file_name":"audio_bot_runner.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"252615145","text":"\"\"\"\nFunctionallity for testing implementations and trained models against some\nstandard benchmarks\n\"\"\"\nimport gym\nimport time\nimport tensorflow as tf\nimport rlalgs.utils.logger as logger\nimport rlalgs.tester.utils as testutils\nimport rlalgs.utils.preprocess as preprocess\n\n# Just disables the warning, doesn't enable AVX/FMA\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n\ndef run_episode(sess, env, x, pi, render, preprocess_fn):\n \"\"\"\n Runs a single episode of the given environment for a model\n\n Arguments:\n sess : the tensorflow session\n env : the gym environment\n x : the policy model input tf placeholder\n pi : the policy model output tf placeholder\n\n Returns:\n epRew : total reward for episode\n \"\"\"\n epRew = 0\n o, r, d = env.reset(), 0, False\n t = 0\n while not d:\n if render:\n env.render()\n time.sleep(0.01)\n o = preprocess_fn(o, env)\n a = sess.run(pi, {x: o.reshape(1, -1)})\n try:\n a_processed = a[0]\n except IndexError:\n # some algs return action directly (i.e. argmax(Q-val) for Q-learning)\n a_processed = a\n o, r, d, _ = env.step(a_processed)\n epRew += r\n t += 1\n return epRew, t\n\n\ndef load_model(fpath):\n \"\"\"\n Load a trained model from file\n\n Arguments:\n fpath : path to model directory\n\n Returns:\n sess : tensorflow sess\n x : the policy model input tf placeholder\n pi : the policy model output tf placeholder\n \"\"\"\n sess = tf.Session()\n model_vars = logger.restore_model(sess, args.fpath)\n x = model_vars[\"inputs\"][logger.OBS_NAME]\n pi = model_vars[\"outputs\"][logger.ACTS_NAME]\n return sess, x, pi\n\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"fpath\", metavar='fpath', type=str,\n help=\"saved model directory name (i.e. the simple_save folder)\")\n parser.add_argument(\"--trials\", type=int, default=100)\n parser.add_argument(\"--render\", action=\"store_true\")\n args = parser.parse_args()\n\n env_name = logger.get_env_name(args.fpath)\n trials, reward = testutils.get_benchmark(env_name)\n if trials is None or reward is None:\n print(\"No benchmark found for {}, please see tests.md for a list of supported envs\"\n .format(env_name))\n trials = args.trials\n print(\"Running for {} trials\".format(trials))\n env = gym.make(env_name)\n\n sess, x, pi = load_model(args.fpath)\n preprocess_fn, _ = preprocess.get_preprocess_fn(env_name)\n\n total_rew = 0\n for i in range(trials):\n ep_rew, t = run_episode(sess, env, x, pi, args.render, preprocess_fn)\n print(\"Trial {}: \\t total reward = {}, total steps = {}\".format(i, ep_rew, t))\n total_rew += ep_rew\n\n print(\"-\" * 20, \"\\n\")\n print(\"Test finished\")\n print(\"Average reward over {} trials = {}\".format(trials, total_rew / trials))\n if reward is not None:\n print(\"Benchmark reward = {}\\n\".format(reward))\n if total_rew / trials > reward:\n print(\"Benchmark passed\\n\")\n else:\n print(\"Benchmark failed\\n\")\n print(\"-\" * 20, \"\\n\")\n","sub_path":"rlalgs/tester/tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":3233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"158584806","text":"\r\nimport os\r\nimport sys\r\nimport json\r\nimport torch\r\nimport torch.nn as nn\r\nfrom torchsummary import summary\r\nwith open(os.path.join(sys.path[0], 'config.json')) as json_file:\r\n\tconfig = json.load(json_file)\r\n\r\nclass AudioNet(nn.Module):\r\n\r\n\tdef __init__(self):\r\n\t\tsuper(AudioNet, self).__init__() # (128, 1292)\r\n\t\tself.num_output = 5\r\n\r\n\t\tif(config[\"SAL0\"] == \"Wi\"):\r\n\t\t\tself.W_i = nn.Parameter(torch.randn(40,1)) # with channel num 16\r\n\t\t\tself.bi = nn.Parameter(torch.randn(1))\r\n\t\t\tself.SmSA0 = nn.Softmax(dim = 1)\r\n\t\tself.conv0 = nn.Sequential(nn.Conv1d(128, 32, kernel_size=8), nn.MaxPool1d(4, stride=4), nn.ReLU(), nn.BatchNorm1d(32),)\r\n\t\tif(config[\"CAL1\"] == \"FC\"):\r\n\t\t\tself.CA1_avg_pool = nn.AdaptiveAvgPool1d(1)\r\n\t\t\tself.CA1 = nn.Sequential(nn.Linear(in_features=32, out_features=32), nn.Softmax(dim=1),)\r\n\t\tif(config[\"CAL1\"] == \"Conv\"):\r\n\t\t\tself.CA1_avg_pool = nn.AdaptiveAvgPool1d(1)\r\n\t\t\tself.conv_du1 = nn.Sequential(nn.Conv1d(32, 32//2, 1, bias=True), nn.ReLU(inplace=True), nn.Conv1d(32//2, 32, 1, bias=True), nn.Sigmoid())\r\n\t\tself.conv1 = nn.Sequential(nn.Conv1d(32, 16, kernel_size=8), nn.MaxPool1d(4, stride=4), nn.ReLU(), nn.BatchNorm1d(16),)\r\n\t\tif(config[\"CAL2\"] == \"FC\"):\r\n\t\t\tself.CA2_avg_pool = nn.AdaptiveAvgPool1d(1)\r\n\t\t\tself.CA2 = nn.Sequential(nn.Linear(in_features=16, out_features=16), nn.Softmax(dim=1),)\r\n\t\tif(config[\"CAL2\"] == \"Conv\"):\r\n\t\t\tself.CA2_avg_pool = nn.AdaptiveAvgPool1d(1)\r\n\t\t\tself.conv_du2 = nn.Sequential(nn.Conv1d(16, 16//2, 1, bias=True), nn.ReLU(inplace=True), nn.Conv1d(16//2, 16, 1, bias=True),nn.Sigmoid())\r\n\t\tself.fc0 = nn.Sequential(nn.Linear(in_features=1248, out_features=64), nn.Tanh(), nn.Dropout(), nn.Linear(in_features=64, out_features=self.num_output),)\r\n\t\tself.logsoftmax = nn.LogSoftmax(dim=1)\r\n\t\tself.apply(self._init_weights)\r\n\r\n\tdef forward(self, x):\r\n\t\tif(config[\"SAL0\"] == \"Wi\"):\r\n\t\t\tz0 = x.permute(0, 2, 1) #(N, L, C)\r\n\t\t\talpha0 = (self.SmSA0((torch.matmul(z0, self.W_i) + self.bi).squeeze(-1))).unsqueeze(-1) #(N, L, 1)-->(N, L)\r\n\t\t\tx = (z0*alpha0).permute(0, 2, 1)\r\n\t\tx = self.conv0(x) #(N, 32, 321)\r\n\t\tif(config[\"CAL1\"] == \"FC\"):\r\n\t\t\tbeta1 = self.CA1_avg_pool(x).squeeze(-1) #(N, 32, 1) --> (N, 32)\r\n\t\t\tbeta1 = self.CA1(beta1).unsqueeze(-1)\r\n\t\t\tx = x*beta1\r\n\t\tif(config[\"CAL1\"] == \"Conv\"):\r\n\t\t\tbeta1 = self.CA1_avg_pool(x) #(N, 32, 1) --> (N, 32)\r\n\t\t\tbeta1 = self.conv_du1(beta1)\r\n\t\t\tx = x*beta1\r\n\t\tx = self.conv1(x) #(N, 16, 78)\r\n\t\tif(config[\"CAL2\"] == \"FC\"):\r\n\t\t\tbeta2 = self.CA2_avg_pool(x).squeeze(-1) #(N, 16, 1) --> (N, 16)\r\n\t\t\tbeta2 = self.CA2(beta2).unsqueeze(-1) #(N, 16, 1)\r\n\t\tx = x*beta2 #(N, 16, 78)\r\n\t\tif(config[\"CAL2\"] == \"Conv\"):\r\n\t\t\tbeta2 = self.CA2_avg_pool(x) #(N, 16, 1) \r\n\t\t\tbeta2 = self.conv_du2(beta2)\r\n\t\t\tx = x*beta2\r\n\t\tflatten = x.view(x.size(0), -1)\r\n\t\t# print(flatten.shape)\r\n\t\tout = self.logsoftmax(self.fc0(flatten))\r\n\t\t#x = F.log_softmax(x, dim=1) # output (N, 5)\r\n\t\treturn out\r\n\r\n\tdef _init_weights(self, layer) -> None:\r\n\t\tif(isinstance(layer, nn.Conv1d)):\r\n\t\t\tnn.init.kaiming_uniform_(layer.weight)\r\n\t\telif(isinstance(layer, nn.Linear)):\r\n\t\t\tnn.init.xavier_uniform_(layer.weight)\r\n\r\n\r\nif __name__ == '__main__':\r\n\tnet = AudioNet()\r\n\tprint(net)\r\n\tnet = net.cuda()\r\n\tsummary(net, (128, 1292))","sub_path":"project_CNNFC_Atten_Cls/models/CNNFC.py","file_name":"CNNFC.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"509873589","text":"import numpy as np\nimport cv2\n\ncolor = cv2.imread(\"butterfly.jpg\", 1)\n\ngray = cv2.cvtColor(color, cv2.COLOR_RGB2GRAY) # 转到灰度空间\ncv2.imshow(\"gray\", gray)\n\nb = color[:, :, 0]\ng = color[:, :, 1]\nr = color[:, :, 2]\n\nrgba = cv2.merge((b, g, r, g))\ncv2.imwrite(\"rgba.png\", rgba)\n\ncv2.waitKey(0)\n","sub_path":"code/basic/channel.py","file_name":"channel.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"69490053","text":"import os\nimport re\nfrom datetime import datetime\nfrom google.appengine.api import users\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.ext.webapp import util\nfrom django.utils import simplejson\nfrom model import get_current_youtify_user_model\nfrom model import create_youtify_user_model\nfrom model import get_youtify_user_struct\nfrom model import get_followers_for_youtify_user_model\nfrom model import get_followings_for_youtify_user_model\nfrom model import get_settings_struct_for_youtify_user_model\nfrom model import generate_device_token\nfrom languages import auto_detect_language\nfrom snapshots import get_deployed_translations_struct\nfrom languages import get_languages\ntry:\n import config\nexcept ImportError:\n import config_template as config\n\nclass NotFoundHandler(webapp.RequestHandler):\n\n def get(self):\n self.response.set_status(404)\n self.response.out.write(\"404 Not found\")\n\nclass MainHandler(webapp.RequestHandler):\n\n def get(self):\n # Find videotag and generate open graph meta tags\n match = re.compile(r'tracks/youtube/(.*)').search(self.request.url)\n if match: \n og_tag = ' '\n else:\n og_tag = ''\n\n # TODO add og_tag for SoundCloud & Official.fm tracks\n\n path = os.path.join(os.path.dirname(__file__), 'html', 'index.html')\n self.response.headers['Content-Type'] = 'text/html; charset=utf-8';\n self.response.out.write(template.render(path, {\n 'CURRENT_VERSION_ID': os.environ['CURRENT_VERSION_ID'],\n 'USE_PRODUCTION_JAVASCRIPT': config.ON_PRODUCTION,\n 'INCLUDE_GOOGLE_ANALYTICS': config.ON_PRODUCTION,\n\t\t\t'url': self.request.url,\n 'og_tag': og_tag,\n }))\n\nclass ApiMainHandler(webapp.RequestHandler):\n\n def get(self):\n my_followers_struct = []\n my_followings_struct = []\n settings_struct = {}\n youtify_user_struct = None\n\n current_user = users.get_current_user()\n youtify_user_model = get_current_youtify_user_model()\n\n if (current_user is not None) and (youtify_user_model is None):\n youtify_user_model = create_youtify_user_model()\n\n if youtify_user_model is not None:\n youtify_user_model.device = generate_device_token()\n youtify_user_model.last_login = datetime.now()\n youtify_user_struct = get_youtify_user_struct(youtify_user_model, include_private_data=True)\n\n # https://developers.google.com/appengine/docs/python/runtime#Request_Headers\n youtify_user_model.country = self.request.headers.get('X-AppEngine-Country', None)\n youtify_user_model.reqion = self.request.headers.get('X-AppEngine-Region', None)\n youtify_user_model.city = self.request.headers.get('X-AppEngine-City', None)\n youtify_user_model.latlon = self.request.headers.get('X-AppEngine-CityLatLong', None)\n\n youtify_user_model.save()\n\n my_followers_struct = get_followers_for_youtify_user_model(youtify_user_model)\n my_followings_struct = get_followings_for_youtify_user_model(youtify_user_model)\n settings_struct = get_settings_struct_for_youtify_user_model(youtify_user_model)\n\n lang_code = auto_detect_language(self.request)\n\n json = {\n 'ON_PRODUCTION': config.ON_PRODUCTION,\n 'SEARCH_STATS_URL': config.SEARCH_STATS_URL,\n 'languagesFromServer': [lang for lang in get_languages() if lang['enabled_on_site']],\n 'device': youtify_user_model is not None and youtify_user_model.device,\n 'user': youtify_user_struct,\n 'lastNotificationSeenTimestamp': youtify_user_model is not None and youtify_user_model.last_notification_seen_timestamp, \n 'myFollowers': my_followers_struct,\n 'myFollowings': my_followings_struct,\n 'settingsFromServer': settings_struct,\n 'autoDetectedLanguageByServer': lang_code,\n 'autoDetectedTranslations': get_deployed_translations_struct(lang_code),\n 'loginUrl': users.create_login_url('/'),\n 'logoutUrl': users.create_logout_url('/'),\n }\n\n self.response.headers['Content-Type'] = 'application/json'\n self.response.out.write(simplejson.dumps(json));\n\ndef main():\n application = webapp.WSGIApplication([\n ('/api/main', ApiMainHandler),\n ('/.*\\.(?:png|ico|jpg|gif|xml|css|swf|js|yaml|py|pyc|woff|eot|svg|ttf)$', NotFoundHandler),\n ('/.*', MainHandler),\n ], debug=True)\n util.run_wsgi_app(application)\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"596714052","text":"import pafy;\n\n\nmyvid = pafy.new(\"https://www.youtube.com/watch?v=Z9aRmmWX5XI\");\nstreams = myvid.streams;\n\n#for s in streams:\n#\tprint(s.extension, s.get_filesize(), s.url);\n\nbest = myvid.getbest(\"webm\");\ndl = best.download();\n\nprint(dl);\nx = input(\"\\npress enter to continue\");","sub_path":"src/vidDL.py","file_name":"vidDL.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"572813907","text":"# -*- coding: utf-8 -*-\n\nimport mock\n\nfrom django.test import TestCase\n\nfrom hikers.tests.factories import HikerFactory\n\nfrom equipment.models import Equipment\nfrom equipment.tests.factories import EquipmentFactory\n\n\nclass EquipmentModelTests(TestCase):\n\n def setUp(self): # noqa\n self.equipment = EquipmentFactory()\n\n def test_equipment_unicode(self):\n self.assertIsInstance(self.equipment, Equipment)\n self.assertIn(self.equipment.recommended_gear,\n self.equipment.__unicode__())\n self.assertIn(self.equipment.gear_type,\n self.equipment.__unicode__())\n\n @mock.patch('equipment.models.deleted_hiker_fallback')\n def test_equipment_save(self, mock_deleted_hiker_fallback):\n added = HikerFactory()\n empty = HikerFactory()\n mock_deleted_hiker_fallback.return_value = empty\n equipment = EquipmentFactory(added_by=added)\n equipment.save()\n self.assertFalse(mock_deleted_hiker_fallback.called)\n\n equipment.added_by = None\n equipment.save()\n self.assertTrue(mock_deleted_hiker_fallback.called)\n","sub_path":"equipment/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"262461937","text":"import requests\r\nimport json\r\nimport sys\r\n\r\n# runs through entire blockchain to determine amount belonging to \"user\"\r\n# this script allows user to enter, save, or change the id used\r\n# will return the balance for that user and all transactions involving said user\r\n\r\nif __name__ == '__main__':\r\n # What is the server address? IE `python3 miner.py https://server.com/api/`\r\n if len(sys.argv) > 1:\r\n node = sys.argv[1]\r\n else:\r\n node = \"http://localhost:5000\"\r\n\r\n # placeholder for balance we will calculate by running through chain\r\n balance = 0\r\n\r\n # transactions involving user\r\n transactions = []\r\n\r\n # Load ID\r\n # change to user input\r\n # f = open(\"my_id.txt\", \"r\")\r\n # user_id = f.read()\r\n # print(\"ID is\", id)\r\n # f.close()\r\n\r\n user_id = input('Please enter user id')\r\n\r\n blockchain = requests.get(url=node + \"/chain\").json()\r\n\r\n chain = blockchain['chain']\r\n\r\n for block in chain:\r\n for transaction in block['transactions']:\r\n if transaction['sender'] == user_id:\r\n transactions.append(transaction)\r\n balance -= transaction['amount']\r\n if transaction['recipient'] == user_id:\r\n transactions.append(transaction)\r\n balance += transaction['amount']\r\n\r\n if len(transactions) > 0:\r\n print('Total amount attributable to entered user id is ', balance)\r\n print('')\r\n print('Below are all transactions involving the user ')\r\n print('')\r\n print(json.dumps(transactions, sort_keys=True, indent=4))\r\n else:\r\n print('Balance is 0, no transactions found')\r\n","sub_path":"basic_wallet_p/basic_wallet.py","file_name":"basic_wallet.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"320431680","text":"from data import *\nfrom execpack import expck\nfrom parse import *\n\n\nif __name__ == '__main__':\n i = 0\n ep = expck()\n\n env = {}\n\n while True:\n inp = input('In ['+str(i)+']> ')\n\n if inp[0] != ':':\n eved, env = ep.evalml(parser.parse(inp)[0], env)\n print(eved)\n\n else:\n com = inp[1:].split(' ')[0].upper()\n if com == 'EXIT':\n break\n elif com == 'ENV':\n print(env)\n\n\n i += 1\n","sub_path":"executer.py","file_name":"executer.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"508516320","text":"import sys\nimport numpy as np\nimport os\nfrom scipy.integrate import simps\nfrom scipy.interpolate import interp1d\nfrom GUI_Design_EQE import *\nimport pyqtgraph as pg\nimport pandas.io.parsers\n\n\n\nclass GUIForm(QtGui.QMainWindow):\n \n \n\tdef __init__(self, master=None):\n\t\tQtGui.QMainWindow.__init__(self,master)\n\t\tself.ui = Ui_EQE_Design()\n\t\tself.ui.setupUi(self)\n \n\t\tQtCore.QObject.connect(self.ui.loadbutton, QtCore.SIGNAL('clicked()'), self.getfile) # Button to load data file\n\t\tQtCore.QObject.connect(self.ui.clearbutton, QtCore.SIGNAL('clicked()'), self.cleardata) # Button to load data file\n\t\tQtCore.QObject.connect(self.ui.EQE_button, QtCore.SIGNAL('clicked()'), self.plot_EQE) # Button to load data file\n\t\tQtCore.QObject.connect(self.ui.SR_button, QtCore.SIGNAL('clicked()'), self.plot_SR) # Button to load data file\n \n\t\tself.p1 = self.ui.top_plot.addPlot()\n\t\tself.p2 = self.ui.bottom_plot.addPlot()\n\t\tself.p2.setLabel('bottom', text='Wavelength (nm)')\n\t\tself.p2.setLabel('left', text='Spectral Intensity')\n\t\t[self.WL, self.I]=np.genfromtxt(\"AM1.5_SpectralIntensity.dat\",unpack='True')\n\t\tself.p2.setXRange(300,1100)\t\t\n\t\tself.p2.plot(self.WL, self.I)\n\n\n#\n# getfile is a function that is used to find and load data files that have EQE data\n#____________________________________________________________________________________________________________\n\n\tdef getfile(self): \n\t\tself.datafilename = str(QtGui.QFileDialog.getOpenFileName(self, 'Open file',os.getcwd())) #Get filename for data\n\t\tself.direc=os.path.dirname(self.datafilename) # Remember the directory in which the file is stored\n\t\tself.ui.pathname.setText(self.datafilename)\t\t\t\n\t\tself.Load()\n\n\n\tdef cleardata(self):\n\t\tself.p1.clear()\n\t\tself.ui.pathname.setText(\"\")\n\t\t\n\n\tdef Load(self): \n\t\t# Load setpoint values \n\t\tself.p1.clear()\t\n\t\tself.datafilename = str(self.ui.pathname.text())\n\t\t[self.WL, self.ch1, self.ch2, self.ch3, self.ch4, self.temp, self.Isc, self.EQE, self.IQE, self.Rs, self.SR, self.Rd, ]=np.genfromtxt(self.datafilename,unpack='True') # Upload the QE data file and unpack the data columns\n\t\t[self.wl, self.I]=np.genfromtxt(\"AM1.5_SpectralIntensity.dat\",unpack='True') # Upload spectral intensity data\n\t\tfunc = interp1d(self.wl, self.I)\n\t\tself.Inew = func(self.WL)\n\t\tself.integrand = np.multiply(self.Inew, self.SR)\n\t\tJsc = simps(self.SR, self.WL)/10\n\t\tself.ui.Jsc_display.setText(str(Jsc))\n\n\n\tdef plot_EQE(self):\n\t\tself.p1.clear()\n\t\tself.p1.setLabel('bottom', text='Wavelength (nm)')\n\t\tself.p1.setLabel('left', text='EQE')\t\t\t\n\t\tself.Load()\n\t\tself.p1.plot(self.WL, self.EQE)\n\n\n\tdef plot_SR(self):\n\t\tself.p1.clear\n\t\tself.p1.setLabel('bottom', text='Wavelength (nm)')\n\t\tself.p1.setLabel('left', text='Spectral Response (A/W)')\n\t\tself.Load()\n\t\tself.p1.plot(self.WL, self.SR)\t\n\n\t\t \n\n\nif __name__ == \"__main__\":\n\tapp = QtGui.QApplication(sys.argv)\n\tmyapp = GUIForm()\n\tmyapp.show()\n\tsys.exit(app.exec_())\n","sub_path":"EQE_plotter.py","file_name":"EQE_plotter.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"337308931","text":"import datetime\nimport zipfile\nimport os\nfrom .CreatLogName import log_name\nfrom .Connection import Connection\n\n\nclass CompressedFile(object):\n\n def __init__(self, config_file_path=\"../PyFramework/LogCenter/config.ini\"):\n \"\"\"\n 一个实例化CompressedFile对象对应一个GetInfo实例化对象\n :param config_file_path:\n \"\"\"\n self.cfp = Connection(config_file_path)\n self.path = config_file_path\n\n def compressed(self):\n \"\"\"\n 压缩与删除操作\n :return:\n \"\"\"\n now_time = log_name.check_new(self.path)\n keep_day = int(self.cfp.get_info(\"compressed\", \"keep_day\")) + 1\n deal_day = datetime.datetime(int(now_time[0:4]), int(now_time[5:7]), int(now_time[8:10])) - datetime.timedelta(\n days=keep_day)\n deal_day_info = str(deal_day)[0:10] # 生成需要进行压缩的文件前缀,同时也是当天的压缩包名,以一天为一个压缩包\n log_path = self.cfp.get_info(\"log\", \"log_path\")\n for root, dirs, files in os.walk(os.getcwd() + \"/\" + log_path):\n for single in files:\n if deal_day_info + \"_\" in single:\n self.add_file(log_path + \"/\" + deal_day_info + '.zip',\n log_path + \"/\" + single)\n self.delete_file(log_path + \"/\" + single)\n\n @staticmethod\n def add_file(zip_filename=None, dirname=None):\n \"\"\"\n 添加dirname压缩入zip_filename文件中\n :param zip_filename: 目标压缩文件\n :param dirname: 目标待压缩文件\n :return:\n \"\"\"\n if os.path.isfile(dirname):\n with zipfile.ZipFile(zip_filename, 'a') as z:\n z.write(dirname)\n else:\n with zipfile.ZipFile(zip_filename, 'a') as z:\n for root, dirs, files in os.walk(dirname):\n for single_file in files:\n if single_file != zip_filename:\n filepath = os.path.join(root, single_file)\n z.write(filepath)\n\n @staticmethod\n def delete_file(filename=None):\n \"\"\"\n 删除文件\n :param filename:\n :return:\n \"\"\"\n os.remove(filename)\n","sub_path":"LogCenter/Center/CompressedFile.py","file_name":"CompressedFile.py","file_ext":"py","file_size_in_byte":2274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"265170916","text":"# Part of Harpiya. See LICENSE file for full copyright and licensing details.\n\nimport harpiya.tests\n\n@harpiya.tests.common.tagged('post_install', '-at_install')\nclass TestUi(harpiya.tests.HttpCase):\n\n def test_01_admin_forum_tour(self):\n self.start_tour(\"/\", 'question', login=\"admin\")\n\n def test_02_demo_question(self):\n forum = self.env.ref('website_forum.forum_help')\n demo = self.env.ref('base.user_demo')\n demo.karma = forum.karma_post + 1\n self.start_tour(\"/\", 'forum_question', login=\"demo\")\n","sub_path":"addons/website_forum/tests/test_forum_process.py","file_name":"test_forum_process.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"319504870","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# michael a.g. aïvázis \n# (c) 1998-2022 all rights reserved\n\n\ndef test():\n \"\"\"\n Verify that component measures are harvested correctly\n \"\"\"\n # the component superclass\n from p2.components.Component import Component\n # the trait factory\n from p2.traits.Behavior import Behavior as behavior\n\n\n # subclass\n class Base(Component):\n \"\"\"\n A simple component\n \"\"\"\n\n @behavior(tip='a simple behavior')\n def bb(self):\n return 1\n\n\n class Derived(Base):\n \"\"\"\n A derived component\n \"\"\"\n\n @behavior(tip='another simple behavior')\n def db(self):\n return True\n\n\n class Shadow(Derived):\n \"\"\"\n A component that redeclares ancestor traits\n \"\"\"\n\n @behavior(tip='a shadowing behavior')\n def bb(self):\n return \"a string\"\n\n\n # the list of trait names for {Base}\n localNames = [\"bb\"]\n # check the traits\n assert Base.pyre_localTraits == tuple(map(Base.pyre_trait, localNames))\n assert Base.pyre_inheritedTraits == ()\n assert tuple(Base.pyre_traits()) == Base.pyre_localTraits + Base.pyre_inheritedTraits\n\n # the list of trait name for {Derived}\n localNames = [\"db\"]\n inheritedNames = [\"bb\"]\n # check the traits\n assert Derived.pyre_localTraits == tuple(map(Derived.pyre_trait, localNames))\n assert Derived.pyre_inheritedTraits == tuple(map(Derived.pyre_trait, inheritedNames))\n assert tuple(Derived.pyre_traits()) == Derived.pyre_localTraits + Derived.pyre_inheritedTraits\n\n # the list of trait name for {Shadow}\n localNames = [\"bb\"]\n inheritedNames = [\"db\"]\n # check the traits\n assert Shadow.pyre_localTraits == tuple(map(Shadow.pyre_trait, localNames))\n assert Shadow.pyre_inheritedTraits == tuple(map(Shadow.pyre_trait, inheritedNames))\n assert tuple(Shadow.pyre_traits()) == Shadow.pyre_localTraits + Shadow.pyre_inheritedTraits\n\n # all done\n return\n\n\n# main\nif __name__ == \"__main__\":\n # run the test\n test()\n\n\n# end of file\n","sub_path":"tests/pyre.pkg/components/component_class_behavior.py","file_name":"component_class_behavior.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"9109078","text":"import pandas as pd\nfrom matplotlib import pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\nplt.style.use('seaborn-pastel')\n\nfilepath = (r\"C:\\Users\\ngaij\\Desktop\\Project Swallow Software\\Python\\Accelerometer\\Set1.csv\")\ncols_list = ['Microphone1','X_Axis', 'Y_Axis', 'Z_Axis', 'Microphone2','Button']\n\ndef animate(i):\n df = pd.read_csv(filepath, header=None).drop_duplicates()\n df.columns = df.iloc[0]\n df = df.iloc[1:]\n\n M1 = df[\"Microphone1\"].astype(float)\n X = df[\"X_Axis\"].astype(float)\n Y = df[\"Y_Axis\"].astype(float)\n Z = df[\"Z_Axis\"].astype(float)\n M2 = df[\"Microphone2\"].astype(float)\n btn = df[\"Button\"].astype(float)\n\n plt.cla()\n plt.plot(M1, label=\"X-Axis\")\n plt.plot(M2, label=\"Y-Axis\")\n\n plt.legend(loc='upper left')\n plt.tight_layout()\n\n\nani = FuncAnimation(plt.gcf(), animate, interval=1)\n\nplt.tight_layout()\nplt.show()\n","sub_path":"Python_Code/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"629686757","text":"import os\nimport numpy as np\nimport random\nfrom collections import defaultdict\nimport gym\nimport environment\n\nenv = gym.make('maze-5x5-v0')\n\n# State 의 boundary\nSTATE_BOUNDS = list(zip(env.observation_space.low, env.observation_space.high))\n# Maze의 size (10, 10)\nNUM_GRID = tuple((env.observation_space.high + np.ones(env.observation_space.shape)).astype(int))\n\nclass Agent:\n def __init__(self, actions):\n self.actions = actions\n self.discount_factor = 0.9 # 감가율\n self.epsilon = 0.1 # 엡실론\n self.q_table = defaultdict(lambda: [0.0, 0.0, 0.0, 0.0])\n self.learning_rate = 0.1\n\n # 의 샘플로부터 큐함수를 업데이트\n def learn(self, state, action, reward, next_state, next_action):\n # TODO: 큐함수를 업데이트 하는 코드를 작성\n current_q = self.q_table[state][action]\n next_state_q = self.q_table[next_state][next_action]\n new_q = (current_q + self.learning_rate *\n (reward + self.discount_factor * next_state_q - current_q))\n self.q_table[state][action] = new_q\n\n # 입실론 탐욕 정책에 따라서 행동을 반환하는 메소드입니다.\n def get_action(self, state):\n # TODO: ε-탐욕 정책 코드를 작성\n # self.epsilon을 이용하세요.\n if np.random.rand() < self.epsilon:\n # 무작위 행동 반환\n action = np.random.choice(self.actions)\n else:\n # 큐함수에 따른 행동 반환\n state_action = self.q_table[str(state)]\n action = self.arg_max(state_action)\n return int(action)\n\n @staticmethod\n def arg_max(state_action):\n max_index_list = []\n max_value = state_action[0]\n for index, value in enumerate(state_action):\n if value > max_value:\n max_index_list.clear()\n max_value = value\n max_index_list.append(index)\n elif value == max_value:\n max_index_list.append(index)\n return random.choice(max_index_list)\n\n# 범위 밖으로 나간 state를 다시 maze안으로 넣어주는 코드\ndef state_to_bucket(state):\n bucket_indice = []\n for i in range(len(state)):\n if state[i] <= STATE_BOUNDS[i][0]:\n bucket_index = 0\n elif state[i] >= STATE_BOUNDS[i][1]:\n bucket_index = NUM_GRID[i] - 1\n else:\n # Mapping the state bounds to the bucket array\n bound_width = STATE_BOUNDS[i][1] - STATE_BOUNDS[i][0]\n offset = (NUM_GRID[i] - 1) * STATE_BOUNDS[i][0] / bound_width\n scaling = (NUM_GRID[i] - 1) / bound_width\n bucket_index = int(round(scaling * state[i] - offset))\n bucket_indice.append(bucket_index)\n return tuple(bucket_indice)\n\n\nif __name__ == \"__main__\":\n env.reset()\n agent = Agent(actions=list(range(env.action_space.n)))\n scores = []\n episodes = []\n\n for episode in range(250):\n state = env.reset()\n state = state_to_bucket(state)\n action = agent.get_action(state)\n total_reward = 0\n\n while True:\n env.render()\n\n next_state, reward, done, _ = env.step(action)\n next_state = state_to_bucket(next_state)\n next_action = agent.get_action(next_state)\n\n agent.learn(str(state), action, reward, str(next_state), next_action)\n total_reward += reward\n state = next_state\n action = next_action\n\n if done:\n print(\"Episode : %d total reward = %f . \" % (episode, total_reward))\n episodes.append(episode)\n scores.append(total_reward)\n\n break","sub_path":"assignment.py","file_name":"assignment.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"634274951","text":"import protocol as proto\nimport util\nimport struct\nimport socket\nimport logging\nimport time\n\nstreamHandler = logging.StreamHandler()\nstreamHandler.setFormatter(logging.Formatter('%(asctime)s %(name)s %(levelname)s - %(message)s'))\nlogger = logging.getLogger(\"CLIENT\")\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(streamHandler)\n\nmax_size = 1024\naddr = (\"localhost\", 6789)\n\n\ndef main():\n # Build frame\n frame_data = proto.FrameData(struct.pack(\">10B\", 0, 1, 2, 3, 4, 5, 6, 7, 8, 9))\n logger.debug(\"Data: {} size: {}\".format(bytes(frame_data), frame_data.size))\n\n header_dict = {\n \"command\": 0x0001,\n \"version\": 0x0002\n }\n\n frame_packet = util.PackFrame(header_dict, frame_data)\n # frame_packet = util.PackFrame(header_dict)\n logger.debug(\"Frame packet: {} size: {}\".format(bytes(frame_packet), frame_packet.size))\n\n # Build serial\n serial_packet = util.PackSerial(frame_packet)\n logger.debug(\"Serial packet: {} size: {}\".format(bytes(serial_packet), serial_packet.size))\n logger.debug(\"Serial checksum: {}\".format(serial_packet.checksum))\n\n # Send\n while True:\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client:\n try:\n client.connect(addr)\n\n while True:\n logger.debug(\"Send serial packet\")\n data = b\"\".join([bytes(serial_packet), bytes(serial_packet)])\n client.sendall(data)\n time.sleep(5)\n\n except Exception as e:\n logger.debug(\"Socket error occurred: {}\".format(e))\n time.sleep(1)\n\n\nif __name__ == \"__main__\":\n try:\n main()\n except Exception as e:\n logger.debug(\"Protocol client error: {}\".format(e))\n","sub_path":"test-protocol/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"651804889","text":"##default import\nfrom django.core import serializers\nfrom django.shortcuts import render, redirect\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.utils import timezone\nimport datetime\nfrom django.contrib.auth.decorators import login_required\nfrom django.db import transaction\nimport json\nfrom django.forms.models import model_to_dict\n\n\n##model import\nfrom graduateProject.models import *\n\n##form import\nfrom graduateProject.forms import PostForm, LiveinterviewForm\nfrom graduateProject.forms import *\n\n# Create your views here.\ndef index(request):\n active = \"index\"\n return render(request, 'graduateProject/index/index.html', {'active':active})\n\n\n\n##matching views\n####question request views\ndef questionRequest(request):\n active = \"matching\"\n try:\n fields = BaseCode.objects.filter(h_category__exact=\"001\").filter(m_category__exact=\"001\")\n tasktypes = BaseCode.objects.filter(h_category__exact=\"001\").filter(m_category__exact=\"002\")\n lifestyles = BaseCode.objects.filter(h_category__exact=\"001\").filter(m_category__exact=\"003\")\n questionRequests = QuestionRequest.objects.all().order_by('-pk').values('id', 'content', 'user_id')[:6]\n for index in questionRequests:\n index['questionRequestAnswers']=(QuestionRequestAnswerModel.objects.filter(request_no__exact=index['id']).select_related('answer_user').values('id', 'answer_user__last_name', 'amount', 'select_yn'))\n return render(request, 'graduateProject/matching/question_request.html', {'active':active, 'fields':fields, 'tasktypes':tasktypes, 'lifestyles':lifestyles, 'questionRequests':questionRequests})\n except Exception as ex:\n print('error occured :', ex)\n\ndef questionRequestCheckboxView(request):\n try:\n if request.method == \"POST\":\n fields = request.POST.getlist('fields[]')\n tasktypes = request.POST.getlist('tasktypes[]')\n lifestyles = request.POST.getlist('lifestyles[]')\n\n\n fieldQueryString = '['\n tasktypeQueryString = '['\n lifestyleQueryString = '['\n\n index = 0\n for field in fields:\n if index == len(fields)-1:\n fieldQueryString += '\"' + field[15:18] + '\"'\n else:\n fieldQueryString += '\"' + field[15:18] + '\",'\n index += 1\n\n index=0\n for tasktype in tasktypes:\n if index == len(tasktypes) - 1:\n tasktypeQueryString += '\"' + tasktype[19:22] + '\"'\n else:\n tasktypeQueryString += '\"' + tasktype[19:22] + '\",'\n index += 1\n\n index=0\n for lifestyle in lifestyles:\n if index == len(lifestyles) - 1:\n lifestyleQueryString += '\"' + lifestyle[20:23] + '\"'\n else:\n lifestyleQueryString += '\"' + lifestyle[20:23] + '\",'\n index += 1\n\n fieldQueryString += ']'\n tasktypeQueryString += ']'\n lifestyleQueryString += ']'\n\n fieldQueryString = json.loads(fieldQueryString)\n tasktypeQueryString = json.loads(tasktypeQueryString)\n lifestyleQueryString = json.loads(lifestyleQueryString)\n\n questionRequestCategories = QuestionRequestCategory.objects.filter(cat_m_category__exact='001').filter(cat_key__in=fieldQueryString) | \\\n QuestionRequestCategory.objects.filter(cat_m_category__exact='002').filter(cat_key__in=tasktypeQueryString) | \\\n QuestionRequestCategory.objects.filter(cat_m_category__exact='003').filter(cat_key__in=lifestyleQueryString)\n\n questionIdList = []\n for questionRequestCategory in questionRequestCategories:\n questionIdList.append(questionRequestCategory.request_no)\n\n index=0\n questionQueryString = '['\n for questionId in questionIdList:\n if index == len(questionIdList)-1:\n questionQueryString += '\"' + str(questionId.id) + '\"'\n else:\n questionQueryString += '\"' + str(questionId.id) + '\",'\n index += 1\n\n questionQueryString += ']'\n questionQueryString = json.loads(questionQueryString)\n\n questionRequestList = QuestionRequest.objects.filter(id__in = questionQueryString).order_by('-pk').values('id', 'content', 'user_id')\n\n for index in questionRequestList:\n answerQuerySet = QuestionRequestAnswerModel.objects.filter(request_no__exact=index['id']).select_related(\n 'answer_user').values('id', 'answer_user__last_name', 'amount', 'select_yn')\n index['questionRequestAnswers'] = answerQuerySet\n\n jsonReturnObject = list(questionRequestList)\n\n\n tmpList = []\n for questionRequest in questionRequestList:\n tmpDict = {}\n tmpDict['id'] = questionRequest['id']\n tmpDict['content'] = questionRequest['content']\n tmpDict['user_id'] = questionRequest['user_id']\n\n answerList = []\n for answer in questionRequest['questionRequestAnswers']:\n answerDict = {}\n answerDict['id'] = answer['id']\n answerDict['last_name'] = answer['answer_user__last_name']\n answerDict['amount'] = answer['amount']\n answerDict['select_yn'] = answer['select_yn']\n answerList.append(answerDict)\n tmpDict['questionRequestAnswers'] = answerList\n tmpList.append(tmpDict)\n\n\n\n\n return HttpResponse(json.dumps(tmpList), content_type=\"application/json\")\n else:\n fields = ''\n tastypes = ''\n lifestyles = ''\n return httpResponse('fail')\n except Exception as ex:\n print('error occured :', ex)\n\n@login_required\n@transaction.atomic\ndef questionRequestWriteView(request):\n active = \"questionRequestWrite\"\n\n try:\n if request.method == 'POST':\n\n form = QuestionRequestForm(request.POST)\n if form.is_valid():\n user_id = form.data['user_id']\n write_date_browser = form.data['write_date_browser']\n now = datetime.datetime.now()\n write_date_webserver = now.strftime('%Y%m%d')\n content = form.cleaned_data['content']\n fields = request.POST.getlist('fields')\n tasktypes = request.POST.getlist('tasktypes')\n lifestyles = request.POST.getlist('lifestyles')\n\n user = User.objects.get(id = user_id)\n questionRequest = QuestionRequest(user_id=user, write_date_browser=write_date_browser, write_date_webserver=write_date_webserver, content=content)\n questionRequest.save()\n\n request_no = QuestionRequest.objects.order_by('-pk')[0].id\n questionRequest = QuestionRequest.objects.get(id = request_no)\n seq = 1\n for field in fields:\n questionRequestCategory = QuestionRequestCategory(request_no=questionRequest, seq=seq, cat_h_category='001', cat_m_category='001', cat_key=field)\n questionRequestCategory.save()\n seq=seq+1\n\n for tasktype in tasktypes:\n questionRequestCategory = QuestionRequestCategory(request_no=questionRequest, seq=seq, cat_h_category='001', cat_m_category='002', cat_key=tasktype)\n questionRequestCategory.save()\n seq=seq+1\n\n for lifestyle in lifestyles:\n questionRequestCategory = QuestionRequestCategory(request_no=questionRequest, seq=seq, cat_h_category='001', cat_m_category='003', cat_key=lifestyle)\n questionRequestCategory.save()\n seq=seq+1\n return redirect(reverse('questionRequest'))\n return(\"fail\")\n elif request.method == 'GET':\n form = QuestionRequestForm()\n return render(request, 'graduateProject/matching/question_request_write.html', {'form':form, 'active':active})\n except Exception as ex:\n print('error occured :', ex)\n\n@login_required\n@transaction.atomic\ndef questionRequestAnswerWriteView(request, id):\n active = 'questionRequestAnswerWrite'\n questionRequest = QuestionRequest.objects.filter(id__exact = id).values('id', 'content').first\n form = QuestionRequestAnswerForm()\n return render(request, 'graduateProject/matching/question_request_answer_write.html', {'form': form, 'active': active, 'questionRequest':questionRequest, 'request_no': id})\n\n@login_required\n@transaction.atomic\ndef questionRequestAnswerWriteResView(request):\n try :\n form = QuestionRequestAnswerForm(request.POST)\n if form.is_valid():\n request_no = form.data['request_no']\n seq = QuestionRequestAnswerModel.objects.filter(request_no__exact=request_no)\n if seq:\n seq = QuestionRequestAnswerModel.objects.filter(request_no__exact=request_no).order_by('-pk')[0].seq\n seq+1\n else:\n seq = 1\n answer_user = form.data['user_id']\n now = datetime.datetime.now()\n write_date = now.strftime('%Y%m%d')\n content = form.cleaned_data['content']\n currency = form.cleaned_data['currency']\n amount = form.cleaned_data['amount']\n\n questionRequest = QuestionRequest.objects.get(id = request_no)\n user = User.objects.get(id = answer_user)\n\n questionRequestAnswer = QuestionRequestAnswerModel(request_no=questionRequest, seq=seq, answer_user=user, write_date = write_date, content=content, currency=currency, amount=amount)\n questionRequestAnswer.save()\n return redirect(reverse('questionRequest'))\n return(\"fail\")\n except Exception as ex:\n print('error occured :', ex)\n\n@login_required\n@transaction.atomic\ndef questionRequestAnswerSelectView(request, questionRequestAnswerId, timestamp, id):\n try:\n ##answer variables\n selectUser = User.objects.get(id=id)\n answerUser = QuestionRequestAnswerModel.objects.get(id=questionRequestAnswerId).answer_user\n answer = QuestionRequestAnswerModel.objects.get(id=questionRequestAnswerId)\n\n if selectUser.credit 0:\n msg = \" the id is alerady exist. \"\n msg += \" \"\n else:\n msg = \" the id is avaiable. \"\n msg += \" \"\n\n return HttpResponse(msg)\n\n\ndef signup_result(request):\n if request.method == \"POST\":\n username = request.POST['username']\n password = request.POST['password']\n last_name = request.POST['last_name']\n # phone = request.POST['phone']\n phone = '01012431234'\n # email = request.POST['email']\n email = 'test1@test1.com'\n birth_year = request.POST['birth_year']\n birth_month = request.POST['birth_month']\n birth_day = request.POST['birth_day']\n\n try:\n if username and User.objects.filter(username__exact=username).count() == 0 :\n # date_of_birth = datetime(birth_year, birth_month, birth_day)\n user = User.objects.create_user(\n username,password,last_name, email, phone, '1990-01-01'\n )\n\n redirection_page = 'signup_completed'\n\n else:\n redirection_page = 'error'\n except Exception as ex:\n print('error occured :', ex)\n\n return redirect(redirection_page)\n\n\ndef signup_completed(request):\n return render(request, 'graduateProject/user/signup_completed.html')\n","sub_path":"graduateProject/views/total_views.py","file_name":"total_views.py","file_ext":"py","file_size_in_byte":19234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"508068772","text":"import discord\r\nfrom discord.ext import commands\r\nimport datetime\r\n\r\nclient=commands.Bot(command_prefix='#')\r\nclient.remove_command(\"help\")\r\n\r\n@client.command()\r\nasync def help(ctx):\r\n embed= discord.Embed(\r\n title=\"DBC-BOT-COMMANDS\",\r\n description=\"List of all Commands\" +\"\\n\"+\"Command_Prefix-- #\",\r\n colour=discord.Colour.dark_red(),\r\n author=\"WarDog\"\r\n )\r\n embed.set_thumbnail(url=\"https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/i/cf806150-5d66-4b08-bc68-8a3ea3b64896/debbdqx-0be4a429-794b-4f31-8382-53d6e2ebaa40.png/v1/fill/w_734,h_811,q_80,strp/ghost_discord_icon_by_inkwoodgfx_debbdqx-fullview.jpg\")\r\n embed.add_field(name='help', value='displaying this list', inline=\"False\")\r\n embed.add_field(name='server', value='server information', inline=\"False\")\r\n embed.add_field(name='clear',value='to clear messages',inline=\"False\")\r\n embed.add_field(name='kick', value='kick members',inline=\"False\")\r\n embed.add_field(name='ban', value='ban members',inline=\"False\")\r\n embed.add_field(name='unban', value='unban members',inline=\"False\")\r\n\r\n await ctx.send(embed=embed)\r\n\r\n@client.command()\r\nasync def server(ctx):\r\n name=ctx.guild.name\r\n description=ctx.guild.description\r\n region=ctx.guild.region\r\n icon=ctx.guild.icon_url\r\n member_count=ctx.guild.member_count\r\n owner=ctx.guild.owner\r\n\r\n embed=discord.Embed(\r\n title=name+\" \"+\"Server Information\",\r\n description=description,\r\n colour=discord.Colour.dark_red()\r\n )\r\n embed.set_thumbnail(url=icon)\r\n embed.add_field(name='Owner: ',value=str(owner))\r\n embed.add_field(name='Region: ', value=region)\r\n embed.add_field(name='Members Count: ', value=member_count)\r\n\r\n await ctx.send(embed=embed)\r\n\r\n@client.command()\r\n@commands.has_role(\"alpha\")\r\nasync def clear(ctx,amount,month=None,day=None,year=None):\r\n if amount == '-' :\r\n amount=None\r\n else:\r\n amount=int(amount)+1\r\n if month==None or day==None or year==None:\r\n date=None\r\n else:\r\n date=datetime.datetime(int(year),int(month),int(day))\r\n\r\n await ctx.channel.purge(limit=amount,before=date)\r\n\r\n@clear.error\r\nasync def clearError(ctx,error):\r\n if isinstance(error,commands.CheckFailure):\r\n await ctx.send(\"You do not have permissions \")\r\n\r\n@client.command()\r\n@commands.has_role(\"alpha\")\r\nasync def kick(ctx, member: discord.Member,*,reason):\r\n await member.kick(reason=reason)\r\n\r\n@kick.error\r\nasync def kick_Error(ctx,error):\r\n if isinstance(error,commands.CheckFailure):\r\n await ctx.send(\"You do not have permissions \")\r\n\r\n@client.command()\r\n@commands.has_role(\"alpha\")\r\nasync def ban(ctx, member: discord.Member,*,reason):\r\n await member.ban(reason=reason)\r\n\r\n@ban.error\r\nasync def ban_Error(ctx,error):\r\n if isinstance(error,commands.CheckFailure):\r\n await ctx.send(\"You do not have permissions \")\r\n\r\n@client.command()\r\n@commands.has_role(\"alpha\")\r\nasync def unban(ctx,*,member):\r\n banned_members= await ctx.guild.bans()\r\n for person in banned_members:\r\n user=person.user\r\n if member==str(user):\r\n await ctx.guild.unban(user)\r\n\r\n@unban.error\r\nasync def unban_Error(ctx,error):\r\n if isinstance(error,commands.CheckFailure):\r\n await ctx.send(\"You do not have permissions \")\r\n\r\nclient.run('token')\r\n","sub_path":"admin_bot.py","file_name":"admin_bot.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"377404017","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import stats\nfrom scipy.optimize import curve_fit\n\nplt.figure(figsize=(12,4))\nplt.rcParams.update({'font.size': 15})\nplt.rc('axes', linewidth=3)\n\nfolder = \"S:\\\\Brouwer\\\\LMST fitting\\\\Fitting MyOne trajectory\\\\20190121_data_004_1 - all free - sequence\\\\\"\nfolder_M270 = \"S:\\\\Brouwer\\\\LMST fitting\\\\Fitting M270 trajectory\\\\Last itertation - sequence (bead 1)\\\\\"\nfolder_M270 = \"S:\\\\Brouwer\\\\LMST fitting\\\\Fitting M270 trajectory\\\\Last itertation - sequence (bead 2)\\\\\"\nfolder_M270 = \"S:\\\\Brouwer\\\\LMST fitting\\\\Fitting M270 trajectory\\\\Last iteration - sequence (bead 2) - reversed (correct r)\\\\\"\nsave_folder = \"C:\\\\Users\\\\brouw\\\\Desktop\\\\\"\n\nfile = \"data_004_bead_005_LMST_fit.dat\"\nfile_M270 = \"data_005_bead_001_LMST_fit_M270.dat\"\nfile_M270 = \"data_005_bead_002_LMST_fit_M270.dat\"\nfile_M270 = \"data_005_bead_002_LMST_fit_M270.dat\"\n\ndf = pd.read_csv(folder+file, sep='\\t')\ndf_M270 = pd.read_csv(folder_M270+file_M270, sep='\\t')\n\ndef predict(x, slope, intercept):\n return slope * x + intercept\n\n# MyOne\nfitted = df['fit successful'].values\nZ_piezo = df['Z piezo (nm)'].values\nZ_fit = df['Z fit (nm)'].values\n\nZ = Z_piezo[np.where(fitted == 1)]\nfit = Z_fit[np.where(fitted == 1)]\n\nZ = 0.88 * Z[110:]\nfit = fit[110:]\n\nZ_select = Z[-200:]\nfit_select = fit[-200:]\n# plt.scatter(Z_select, fit_select, color='black', zorder=100)\n\n# fitting line\n# slope, intercept, r_value, p_value, std_err = stats.linregress(Z, fit)\nslope, intercept, r_value, p_value, std_err = stats.linregress(Z_select, fit_select)\n# fitting line, fixed slope at -1\nintercept = curve_fit(lambda x, intercept: predict(x, slope=-1, intercept=intercept), Z_select, fit_select)[0]\nslope = -1\n\nfitline = predict(Z, slope, intercept)\n\nplt.scatter(Z, fit, label=\"MyOne beads\", s=50, facecolors='none', edgecolors='blue', alpha=0.5)\nplt.plot(Z, fitline, color='red', label=\"Linear Fit\", linewidth=3)\n\n# fit error of approx. 0.5 %\nerr = []\nfor f in fit:\n err.append(0.005 * f)\n\n# plt.errorbar(Z, fit, label=\"MyOne beads\", yerr=err, fmt='--o', alpha=0.5, ecolor='grey', capsize=2)\n\n# M270\nfitted_M270 = df_M270['fit successful'].values\nZ_piezo_M270 = df_M270['Z piezo (nm)'].values\nZ_fit_M270 = df_M270['Z fit (nm)'].values\n\nZ_M270 = Z_piezo_M270[np.where(fitted_M270 == 1)]\nfit_M270 = Z_fit_M270[np.where(fitted_M270 == 1)]\n# Z_M270 = Z_piezo_M270\n# fit_M270 = Z_fit_M270\n\nZ_M270 = (0.88 * Z_M270) + 4.19\n\nslope_M270, intercept_M270, r_value_M270, p_value_M270, std_err_M270 = stats.linregress(Z_M270, fit_M270)\nfitline_M270 = predict(Z_M270, slope_M270, intercept_M270)\n\nplt.scatter(Z_M270, fit_M270, label=\"M270 beads\", s=50, facecolors='none', edgecolors='green', alpha=0.5)\n# plt.plot(Z_M270, fitline_M270, color='red', label=\"Linear Fit\", linewidth=3)\n\n\nplt.xlabel('$Z_{\\mathrm{piezo}} (\\mu m)$')\nplt.ylabel('$Z_{\\mathrm{LMST}} (\\mu m)$')\n\nplt.tick_params(direction='in', top=True, right=True, length=6, width=3)\nplt.legend(loc=1, frameon=False)\n# plt.savefig(save_folder + \"LMST fitting trajectory\",dpi=600, bbox_inches=\"tight\")\n# plt.savefig(save_folder + \"LMST fitting trajectory.pdf\", bbox_inches=\"tight\")\nplt.show()","sub_path":"Tracking/xFigure 1c - LMST fitting Z trajectory.py","file_name":"xFigure 1c - LMST fitting Z trajectory.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"37791564","text":"\"\"\"\r\nAuthor: Nguyen Tan Loc\r\nDate: 24/09/2021\r\nProblem:\r\nwrite a script named numberlines.py. This script creates a program listing from a\r\nsource program. This script should prompt the user for the names of two files. The\r\ninput filename could be the name of the script itself, but be careful to use a different\r\noutput filename! The script copies the lines of text from the input file to the output\r\nfile, numbering each line as it goes. The line numbers should be right-justified in\r\n4 columns, so that the format of a line in the output file looks like this example:\r\n1> This is the first line of text.\r\nSolution:\r\n\r\n ....\r\n\"\"\"\r\ninputFileName = input(\"Input filename: \")\r\noutputFileName = input(\"Output filename: \")\r\ninputFile = open(inputFileName, \"r\")\r\noutputFile = open(outputFileName, \"w\")\r\ncount = 1\r\nfor line in inputFile:\r\n newLine = str(count).rjust(4, \" \") + \"> \" + line\r\n outputFile.write(newLine)\r\n count += 1\r\nprint(newLine)\r\n\r\n\r\n\r\n","sub_path":"NguyenTanLoc_43807_CH04/project/Page_133_Project_09.py","file_name":"Page_133_Project_09.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"330620805","text":"import pandas as pd, numpy as np, simplejson\nimport ast\n\nrolling_median = []\nlooplist = [0]\n\ndf = pd.DataFrame(pd.read_csv(r'C:\\Users\\ADMIN\\Documents\\GitHub\\insight_coding_challenge_1.2\\input_file\\venmo-trans.txt',header=None,index_col=None,sep=';',squeeze=True).apply(lambda x: ast.literal_eval(x)).tolist())\ndf['created_time'] = df['created_time'].astype(np.datetime64)\n\nfor i in looplist:\n try:\n df['seconds_gap'] = (df['created_time'] - df['created_time'].ix[i]).apply(lambda x: x.total_seconds())\n df1 = df[df['seconds_gap'] <= np.absolute(60.00)]\n df1 = df1[['actor','target']]\n for v in range(len(df1)):\n rolling_median.append(np.median(pd.melt(df1.ix[:v+1])['value'].value_counts().tolist()))\n df = df.ix[(v+1):].reset_index(drop = True)\n looplist.extend([0])\n except:\n pass\n\nf = open(r'C:\\Users\\ADMIN\\Documents\\GitHub\\insight_coding_challenge_1.2\\output_file\\coding_challenge_output.txt','w')\nsimplejson.dump(rolling_median,f)\nf.close()\n\ndel df, df1, looplist, rolling_median\n \n#comments:\n# import libaries pandas, numpy, ast, simplejson\n#rolling median is stored in list variable named 'rolling_median'\n#looplist is the counter for the number of times the dataframe object is broken into smaller objects based on rolling 60 second window threshold\n#import data file, convert data file into pandas DataFrame object\n#column 'created_time' is converted into numpy datetime dtype object\n#column 'seconds_gap' measures the time difference in seconds between the first record and subsequent records until the time difference exceeds 60 seconds....\n#...at which point the loop breaks the bigger dataframe 'df' into smaller dataframe 'df1'\n#run a second loop within the smaller dataframe 'df1' to compute rolling median and store the output into the rolling_median list object\n#reset the dataframe object 'df1' so that the dataframe is resized to cut out the part of the dataframe for which the rolling median has been computed\n# write the output (rolling_median) to text file using simplejson\n\n \n \n \n","sub_path":"src/coding_challenge.py","file_name":"coding_challenge.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"554299722","text":"import datetime\nimport json\nimport logging\nimport sys\n\nfrom utils.encoder import Encoder\n\n\nclass Logger:\n __slots__ = \"logger\"\n\n def __init__(self, class_name=None) -> None:\n self.logger = LogHandler().app_logger(class_name=class_name)\n\n def debug(self, msg, *args, **kwargs):\n log_json = self.__prepare_log(msg, args, kwargs)\n self.logger.debug(json.dumps(log_json, cls=Encoder))\n\n def info(self, msg, *args, **kwargs):\n log_json = self.__prepare_log(msg, args, kwargs)\n self.logger.info(json.dumps(log_json, cls=Encoder))\n\n def warning(self, msg, *args, **kwargs):\n log_json = self.__prepare_log(msg, args, kwargs)\n self.logger.warning(json.dumps(log_json, cls=Encoder))\n\n def error(self, msg, *args, **kwargs):\n log_json = self.__prepare_log(msg, args, kwargs)\n self.logger.error(json.dumps(log_json, cls=Encoder))\n\n def fatal(self, msg, *args, **kwargs):\n log_json = self.__prepare_log(msg, args, kwargs)\n self.logger.fatal(json.dumps(log_json, cls=Encoder))\n\n @staticmethod\n def __prepare_log(msg, args, kwargs):\n record = dict()\n if type(msg) == dict:\n record.update(msg)\n\n for arg in args:\n if type(arg) == dict:\n record.update(arg)\n\n record.update(kwargs)\n log_json = dict(message_dict=record, message=msg)\n return log_json\n\n\nclass LogHandler(object):\n loggers = {}\n\n def app_logger(self, class_name=None):\n if class_name is None:\n class_name = \"undefined\"\n\n if self.loggers.get(class_name):\n logger = self.loggers.get(class_name)\n\n return logger\n\n else:\n logger = logging.getLogger(class_name)\n log_level = logging.DEBUG\n\n # create a sys stdout handler\n handler = logging.StreamHandler(sys.stdout)\n handler.setLevel(log_level)\n\n logging.basicConfig(level=log_level)\n\n formatter = Formatter(self)\n\n handler.setFormatter(formatter)\n\n # add the handlers to the logger\n logger.propagate = False\n logger.addHandler(handler)\n\n # Save new logger to existing loggers\n self.loggers.update({class_name: logger})\n\n return logger\n\n\nclass Formatter(logging.Formatter):\n def __init__(self, log_handler, *args, **kwargs):\n super(Formatter, self).__init__(*args, **kwargs)\n self.log_handler = log_handler\n\n def format(self, logger):\n\n payload = json.loads(logger.getMessage())\n log_status = dict(\n severity=logger.levelname,\n message_dict=payload.get(\"message_dict\"),\n message=payload.get(\"message\"),\n timestamp=str(\n datetime.datetime.now(\n datetime.timezone(offset=datetime.timedelta(hours=-3))\n )\n ),\n )\n\n return json.dumps(log_status)\n","sub_path":"app/utils/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"556380912","text":"\"\"\"\nGreenlet-local objects.\n\nThis module is based on `_threading_local.py`__ from the standard\nlibrary of Python 3.4.\n\n__ https://github.com/python/cpython/blob/3.4/Lib/_threading_local.py\n\nGreenlet-local objects support the management of greenlet-local data.\nIf you have data that you want to be local to a greenlet, simply create\na greenlet-local object and use its attributes:\n\n >>> mydata = local()\n >>> mydata.number = 42\n >>> mydata.number\n 42\n\nYou can also access the local-object's dictionary:\n\n >>> mydata.__dict__\n {'number': 42}\n >>> mydata.__dict__.setdefault('widgets', [])\n []\n >>> mydata.widgets\n []\n\nWhat's important about greenlet-local objects is that their data are\nlocal to a greenlet. If we access the data in a different greenlet:\n\n >>> log = []\n >>> def f():\n ... items = list(mydata.__dict__.items())\n ... items.sort()\n ... log.append(items)\n ... mydata.number = 11\n ... log.append(mydata.number)\n >>> greenlet = gevent.spawn(f)\n >>> greenlet.join()\n >>> log\n [[], 11]\n\nwe get different data. Furthermore, changes made in the other greenlet\ndon't affect data seen in this greenlet:\n\n >>> mydata.number\n 42\n\nOf course, values you get from a local object, including a __dict__\nattribute, are for whatever greenlet was current at the time the\nattribute was read. For that reason, you generally don't want to save\nthese values across greenlets, as they apply only to the greenlet they\ncame from.\n\nYou can create custom local objects by subclassing the local class:\n\n >>> class MyLocal(local):\n ... number = 2\n ... initialized = False\n ... def __init__(self, **kw):\n ... if self.initialized:\n ... raise SystemError('__init__ called too many times')\n ... self.initialized = True\n ... self.__dict__.update(kw)\n ... def squared(self):\n ... return self.number ** 2\n\nThis can be useful to support default values, methods and\ninitialization. Note that if you define an __init__ method, it will be\ncalled each time the local object is used in a separate greenlet. This\nis necessary to initialize each greenlet's dictionary.\n\nNow if we create a local object:\n\n >>> mydata = MyLocal(color='red')\n\nNow we have a default number:\n\n >>> mydata.number\n 2\n\nan initial color:\n\n >>> mydata.color\n 'red'\n >>> del mydata.color\n\nAnd a method that operates on the data:\n\n >>> mydata.squared()\n 4\n\nAs before, we can access the data in a separate greenlet:\n\n >>> log = []\n >>> greenlet = gevent.spawn(f)\n >>> greenlet.join()\n >>> log\n [[('color', 'red'), ('initialized', True)], 11]\n\nwithout affecting this greenlet's data:\n\n >>> mydata.number\n 2\n >>> mydata.color\n Traceback (most recent call last):\n ...\n AttributeError: 'MyLocal' object has no attribute 'color'\n\nNote that subclasses can define slots, but they are not greenlet\nlocal. They are shared across greenlets::\n\n >>> class MyLocal(local):\n ... __slots__ = 'number'\n\n >>> mydata = MyLocal()\n >>> mydata.number = 42\n >>> mydata.color = 'red'\n\nSo, the separate greenlet:\n\n >>> greenlet = gevent.spawn(f)\n >>> greenlet.join()\n\naffects what we see:\n\n >>> mydata.number\n 11\n\n>>> del mydata\n\n.. versionchanged:: 1.1a2\n Update the implementation to match Python 3.4 instead of Python 2.5.\n This results in locals being eligible for garbage collection as soon\n as their greenlet exits.\n\n\"\"\"\n\nfrom copy import copy\nfrom weakref import ref\nfrom contextlib import contextmanager\nfrom gevent.hub import getcurrent, PYPY\nfrom gevent.lock import RLock\n\n__all__ = [\"local\"]\n\n\nclass _wrefdict(dict):\n \"\"\"A dict that can be weak referenced\"\"\"\n\n\nclass _localimpl(object):\n \"\"\"A class managing thread-local dicts\"\"\"\n __slots__ = 'key', 'dicts', 'localargs', 'locallock', '__weakref__'\n\n def __init__(self):\n # The key used in the Thread objects' attribute dicts.\n # We keep it a string for speed but make it unlikely to clash with\n # a \"real\" attribute.\n self.key = '_threading_local._localimpl.' + str(id(self))\n # { id(Thread) -> (ref(Thread), thread-local dict) }\n self.dicts = _wrefdict()\n\n def get_dict(self):\n \"\"\"Return the dict for the current thread. Raises KeyError if none\n defined.\"\"\"\n thread = getcurrent()\n return self.dicts[id(thread)][1]\n\n def create_dict(self):\n \"\"\"Create a new dict for the current thread, and return it.\"\"\"\n localdict = {}\n key = self.key\n thread = getcurrent()\n idt = id(thread)\n\n # If we are working with a gevent.greenlet.Greenlet, we can\n # pro-actively clear out with a link. Use rawlink to avoid\n # spawning any more greenlets\n try:\n rawlink = thread.rawlink\n except AttributeError:\n # Otherwise we need to do it with weak refs\n def local_deleted(_, key=key):\n # When the localimpl is deleted, remove the thread attribute.\n thread = wrthread()\n if thread is not None:\n del thread.__dict__[key]\n\n def thread_deleted(_, idt=idt):\n # When the thread is deleted, remove the local dict.\n # Note that this is suboptimal if the thread object gets\n # caught in a reference loop. We would like to be called\n # as soon as the OS-level thread ends instead.\n _local = wrlocal()\n if _local is not None:\n _local.dicts.pop(idt, None)\n wrlocal = ref(self, local_deleted)\n wrthread = ref(thread, thread_deleted)\n thread.__dict__[key] = wrlocal\n else:\n wrdicts = ref(self.dicts)\n\n def clear(_):\n dicts = wrdicts()\n if dicts:\n dicts.pop(idt, None)\n rawlink(clear)\n wrthread = None\n\n self.dicts[idt] = wrthread, localdict\n return localdict\n\n\n@contextmanager\ndef _patch(self):\n impl = object.__getattribute__(self, '_local__impl')\n orig_dct = object.__getattribute__(self, '__dict__')\n try:\n dct = impl.get_dict()\n except KeyError:\n # it's OK to acquire the lock here and not earlier, because the above code won't switch out\n # however, subclassed __init__ might switch, so we do need to acquire the lock here\n dct = impl.create_dict()\n args, kw = impl.localargs\n with impl.locallock:\n self.__init__(*args, **kw)\n with impl.locallock:\n object.__setattr__(self, '__dict__', dct)\n yield\n object.__setattr__(self, '__dict__', orig_dct)\n\n\nclass local(object):\n \"\"\"\n An object whose attributes are greenlet-local.\n \"\"\"\n __slots__ = '_local__impl', '__dict__'\n\n def __new__(cls, *args, **kw):\n if args or kw:\n if (PYPY and cls.__init__ == object.__init__) or (not PYPY and cls.__init__ is object.__init__):\n raise TypeError(\"Initialization arguments are not supported\")\n self = object.__new__(cls)\n impl = _localimpl()\n impl.localargs = (args, kw)\n impl.locallock = RLock()\n object.__setattr__(self, '_local__impl', impl)\n # We need to create the thread dict in anticipation of\n # __init__ being called, to make sure we don't call it\n # again ourselves.\n impl.create_dict()\n return self\n\n def __getattribute__(self, name):\n with _patch(self):\n return object.__getattribute__(self, name)\n\n def __setattr__(self, name, value):\n if name == '__dict__':\n raise AttributeError(\n \"%r object attribute '__dict__' is read-only\"\n % self.__class__.__name__)\n with _patch(self):\n return object.__setattr__(self, name, value)\n\n def __delattr__(self, name):\n if name == '__dict__':\n raise AttributeError(\n \"%r object attribute '__dict__' is read-only\"\n % self.__class__.__name__)\n with _patch(self):\n return object.__delattr__(self, name)\n\n def __copy__(self):\n impl = object.__getattribute__(self, '_local__impl')\n current = getcurrent()\n currentId = id(current)\n d = impl.get_dict()\n duplicate = copy(d)\n\n cls = type(self)\n if (PYPY and cls.__init__ != object.__init__) or (not PYPY and cls.__init__ is not object.__init__):\n args, kw = impl.localargs\n instance = cls(*args, **kw)\n else:\n instance = cls()\n\n new_impl = object.__getattribute__(instance, '_local__impl')\n tpl = new_impl.dicts[currentId]\n new_impl.dicts[currentId] = (tpl[0], duplicate)\n\n return instance\n","sub_path":"satori-rules/plugin/libs/gevent/local.py","file_name":"local.py","file_ext":"py","file_size_in_byte":8772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"471090032","text":"import numpy as np\n# from scipy.interpolate import *\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker\nimport statistics\n\ndef least_squares_fit(x, y, err_x, err_y):\n plt.rc('font', family = 'serif', serif = 'cmr10')\n plt.rcParams['mathtext.fontset'] = \"cm\" \n # plt.rcParams[\"font.family\"] = \"Times New Roman\" \n plt.rcParams[\"axes.linewidth\"] = 1.0\n\n arr_size = int(len(x))\n N = arr_size - 1 # N = x(arr_size - 1) # where N is the final element in the array (of x vals)\n # we have to -1 as elements in array start count at 0 NOT 1\n\n p = np.polyfit(x, y, 1) # finds the coefficients for the 'best' fitting function\n \n f = np.polyval(p, x) # these are the 'y-values' of the fitting function\n sigma = statistics.stdev(f - y) # standard deviation of quantity 'f - y'\n\n # plt.figure(figsize = (8, 6))\n plt.errorbar(x, y, err_y, err_x, fmt = \"r+\", capsize = 3, LineWidth = 0.9, LineStyle = \"none\")\n # the last argument for the two lines below, is for the legend\n plt.plot(x, y, Marker = \"+\", MarkerSize = 10, MarkerEdgeColor = \"r\", MarkerFaceColor = \"r\", LineWidth = 0.9, LineStyle = \"none\", label = \"Data Points\")\n plt.plot(x, f, LineWidth = 0.9, Linestyle = \"-\", Color = \"b\", label = \"Model\") # 'line of best fit'\n\n plt.title(\"Least Squares Fit\", fontsize = 12, fontweight = \"bold\")\n plt.xlabel(\"x values\", fontsize = 12)\n plt.ylabel(\" y values\", fontsize = 12)\n plt.legend(loc = \"upper right\", title = \"Legend\", fontsize = 10)\n # plt.axis([-1.0, 6.0, -2, 2])\n # plt.xlim(-1, 6)\n # ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(1))\n # plt.ylim(-2, 2)\n # ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(1))\n plt.gca().tick_params(width = 1.0, labelsize = 10)\n \n plt.savefig(\"Least_Squares_Fit.pdf\")\n\n print(\"Gradient is: {:f}\" .format(p[0]))\n print(\"y-intercept is: {:f}\" .format(p[1]))\n print(\"Sigma is: {:f}\" .format(sigma))\n \n # The next two lines are for linear i.e. straight line fits only\n grad_err = (2 * sigma) / (x[N] - x[0])\n print(\"Gradient error is: {:f}\" .format(grad_err))","sub_path":"Useful_Graphs/LS_Polynomials/LS_Poly.py","file_name":"LS_Poly.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"342416705","text":"import os\nimport logging\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen\n\n\nclass Zacks:\n def __init__(self):\n self.logger = logging.getLogger('zacks')\n self.url_head = 'https://www.zacks.com/stock/research/'\n self.url_tail = '/brokerage-recommendations'\n self.tags_to_parse = [12, 14, 15, 17, 18]\n\n def download(self, tickers):\n recommendation_details = pd.DataFrame(columns=tickers)\n for ticker in tickers:\n r = urlopen(self.url_head + ticker + self.url_tail)\n soup = BeautifulSoup(r, 'html.parser')\n trTags = soup.find_all('tr')\n\n for idx in self.tags_to_parse:\n if idx == 12:\n\n # 12: Average Broker Recommendation (ABR)\n for i, child in enumerate(trTags[idx].children):\n if i == 1:\n row_idx = child.contents[0]\n elif i == 3:\n recommendation_details.loc[row_idx, ticker] = child.string\n\n else:\n\n # 14: Number of recommendations\n # 15: Average Target Price\n # 17: Industry\n # 18: Industry rank\n for i, child in enumerate(trTags[idx].children):\n if i == 1:\n row_idx = child.string\n elif i == 3:\n recommendation_details.loc[row_idx, ticker] = child.string\n\n return recommendation_details\n","sub_path":"zacks.py","file_name":"zacks.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"511894346","text":"# encoding: UTF-8\n\n'''\n本文件中包含了CTA模块中用到的一些基础设置、类和常量等。\n'''\n\nfrom __future__ import division\n\n\n# 把vn.trader根目录添加到python环境变量中\nimport sys\nsys.path.append('..')\n\n\n# 常量定义\n# CTA引擎中涉及到的交易方向类型\n'''\n#原代码\nCTAORDER_BUY = u'买开'\nCTAORDER_SELL = u'卖平'\nCTAORDER_SHORT = u'卖开'\nCTAORDER_COVER = u'买平'\n'''\nCTAORDER_LONG = u'买开'\nCTAORDER_CLOSELONG = u'卖平'\nCTAORDER_SHORT = u'卖开'\nCTAORDER_CLOSESHORT = u'买平'\n\n# 本地停止单状态\nSTOPORDER_WAITING = u'等待中'\nSTOPORDER_CANCELLED = u'已撤销'\nSTOPORDER_TRIGGERED = u'已触发'\n\n# 本地停止单前缀\nSTOPORDERPREFIX = 'CtaStopOrder.'\n\n# 数据库名称\nSETTING_DB_NAME = 'VnTrader_Setting_Db'\nTICK_DB_NAME = 'VtTrader_Tick_Db'\nDAILY_DB_NAME = 'VtTrader_Daily_Db'\nMINUTE_DB_NAME = 'VtTrader_1Min_Db'\nHOUR_DB_NAME = 'VtTrader_1Hour_Db'\n\nBACKTESTING_RESULT_DB_NAME = 'VtTrader_Bt_Result_Db'\n\n\n# CTA引擎中涉及的数据类定义\nfrom vtConstant import EMPTY_UNICODE, EMPTY_STRING, EMPTY_FLOAT, EMPTY_INT\n\n########################################################################\nclass StopOrder(object):\n \"\"\"本地停止单\"\"\"\n\n #----------------------------------------------------------------------\n def __init__(self):\n \"\"\"Constructor\"\"\"\n self.vtSymbol = EMPTY_STRING\n self.direction = EMPTY_UNICODE\n self.offset = EMPTY_UNICODE\n self.price = EMPTY_FLOAT\n self.volume = EMPTY_INT\n \n self.strategy = None # 下停止单的策略对象\n self.stopOrderID = EMPTY_STRING # 停止单的本地编号 \n self.status = EMPTY_STRING # 停止单状态\n\n\n########################################################################\nclass CtaBarData(object):\n \"\"\"K线数据\"\"\"\n\n #----------------------------------------------------------------------\n def __init__(self):\n \"\"\"Constructor\"\"\"\n self.vtSymbol = EMPTY_STRING # vt系统代码\n self.symbol = EMPTY_STRING # 代码\n self.exchange = EMPTY_STRING # 交易所\n self.barPeriod = \"M1\" # 默认M1\n '''\n self.openBid = EMPTY_FLOAT # OHLC Bid\n self.highBid = EMPTY_FLOAT\n self.lowBid = EMPTY_FLOAT\n self.closeBid = EMPTY_FLOAT\n\n self.openAsk = EMPTY_FLOAT # OHLC Ask\n self.highAsk = EMPTY_FLOAT\n self.lowAsk = EMPTY_FLOAT\n self.closeAsk = EMPTY_FLOAT\n '''\n self.open = EMPTY_FLOAT # OHLC Mid\n self.high = EMPTY_FLOAT\n self.low = EMPTY_FLOAT\n self.close = EMPTY_FLOAT\n \n self.date = EMPTY_STRING # bar开始的时间,日期\n self.time = EMPTY_STRING # 时间\n self.datetime = None # python的datetime时间对象\n\n\n\n########################################################################\nclass CtaTickData(object):\n \"\"\"Tick数据\"\"\"\n\n #----------------------------------------------------------------------\n def __init__(self):\n \"\"\"Constructor\"\"\" \n self.vtSymbol = EMPTY_STRING # vt系统代码\n self.symbol = EMPTY_STRING # 合约代码\n self.exchange = EMPTY_STRING # 交易所代码\n\n # 成交数据\n self.lastPrice = EMPTY_FLOAT # 最新成交价\n self.lastBidPrice = EMPTY_FLOAT # 最新Bid价\n self.lastAskPrice = EMPTY_FLOAT # 最新Ask价\n \n # tick的时间\n self.date = EMPTY_STRING # 日期\n self.time = EMPTY_STRING # 时间\n self.datetime = None # python的datetime时间对象\n\n\nclass CtaAccountData(object):\n \"\"\"账户信息数据\"\"\"\n\n #----------------------------------------------------------------------\n def __init__(self):\n \"\"\"Constructor\"\"\"\n\n # 账号代码相关\n self.accountID = EMPTY_STRING # 账户代码\n self.vtAccountID = EMPTY_STRING # 账户在vt中的唯一代码,通常是 Gateway名.账户代码\n\n # 数值相关\n self.preBalance = EMPTY_FLOAT # 昨日账户结算净值\n self.balance = EMPTY_FLOAT # 账户净值\n self.available = EMPTY_FLOAT # 可用资金\n self.commission = EMPTY_FLOAT # 今日手续费\n self.margin = EMPTY_FLOAT # 保证金占用\n self.closeProfit = EMPTY_FLOAT # 平仓盈亏\n self.positionProfit = EMPTY_FLOAT # 持仓盈亏\n self.openTrades = EMPTY_INT # 未平仓单数量(for Oanda only)\n","sub_path":"ctaAlgo/ctaBase.py","file_name":"ctaBase.py","file_ext":"py","file_size_in_byte":4762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"130033499","text":"import os\nimport numpy as np\nimport sys\n'''\nDescription:\nscp that shit over here\n\nDate: \n\nAuthor: Hunter Akins\n'''\n\n\n\ndef copy_over_chunks(freq, num_chunks):\n os.chdir('npy_files/' + str(freq))\n dirs = os.listdir()\n print(dirs)\n for i in range(num_chunks):\n if 'chunk'+str(i) not in dirs:\n os.mkdir('chunk'+str(i))\n os.chdir('chunk'+str(i))\n os.system('scp fakins@tscc-login.sdsc.edu:/oasis/tscc/scratch/fakins/' + str(freq) + '/\\*chunk_'+str(i)+'.npy .')\n os.system('scp fakins@tscc-login.sdsc.edu:/oasis/tscc/scratch/fakins/' + str(freq) + '/chunk_'+str(i)+'_f_grid.npy .')\n x = np.load('chunk_' + str(i) + '_f_grid.npy')\n print('Mean freq for chunk ',i, np.mean(x))\n os.chdir('..')\n os.chdir('..')\n\ndef copy_over_f_demod(freq):\n if str(freq) not in os.listdir('npy_files'):\n os.mkdir('npy_files/' + str(freq))\n os.chdir('npy_files/' + str(freq))\n dirs = os.listdir()\n print(dirs)\n for i in range(1):\n if 'chunk'+str(i) not in dirs:\n os.mkdir('chunk'+str(i))\n os.chdir('chunk'+str(i))\n os.system('scp fakins@tscc-login.sdsc.edu:/oasis/tscc/scratch/fakins/' + str(freq) + '/\\*_nb.npy .')\n os.system('scp fakins@tscc-login.sdsc.edu:/oasis/tscc/scratch/fakins/' + str(freq) + '/nb_f_grid.npy .')\n x = np.load('nb_f_grid.npy')\n print('Mean freq for chunk ',i, np.mean(x))\n os.chdir('..')\n os.chdir('../..')\n\ndef copy_over_fests(freq, N=1500, delta_n=750):\n root = 'fakins@tscc-login.sdsc.edu:/oasis/tscc/scratch/fakins/fests/'+str(freq) + '_' + str(N) + '_' + str(delta_n) + '_'\n os.chdir('npy_files/fests')\n os.system('scp ' + root + 'fhat.npy .')\n os.system('scp ' + root + 'fhat_err.npy .')\n os.system('scp ' + root + 'fhat_amp.npy .')\n\n\nfreq = int(sys.argv[1])\n#copy_over_chunks(freq, 1)\n#copy_over_f_demod(freq)\ncopy_over_fests(freq)\n\n","sub_path":"audio/copy_demods.py","file_name":"copy_demods.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"465084466","text":"def coerce_config(configuration, prefix, converters):\n \"\"\"Convert configuration values to expected types.\"\"\"\n\n options = dict((key[len(prefix):], configuration[key])\n for key in configuration if key.startswith(prefix))\n\n for option, converter in converters.items():\n if option in options:\n options[option] = converter(options[option])\n\n return options\n","sub_path":"bdenv/lib/python2.7/site-packages/tg/configuration/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"146213473","text":"import nltk\nfrom nltk.corpus import state_union\nfrom nltk.tokenize import PunktSentenceTokenizer\n\n#purpose of this program is to intrpduce part of speech tagging\n#also chunking is introduced \n\ntrain_text = state_union.raw(\"2005-GWBush.txt\")\nsample_text = state_union.raw(\"2006-GWBush.txt\")\n\n\ncustom_sent_tokenizer = PunktSentenceTokenizer(train_text)\ntokenized = custom_sent_tokenizer.tokenize(sample_text)\n\ndef process_content():\n try:\n for i in tokenized:\n words = nltk.word_tokenize(i[5:])\n tagged = nltk.pos_tag(words)\n\n namedEnt = nltk.ne_chunk(tagged, binary = True)\n namedEnt.draw()\n\n ## Chunking\n ## chunkGram = r\"\"\"Chunk: {+}\n ## }{\"\"\"\n ##chunkParser = nltk.RegexpParser(chunkGram)\n ##chunked = chunkParser.parse(tagged)\n ##chunked.draw()\n\n\n # print(tagged) used for takking\n except Exception as e:\n print(str(e))\n\nprocess_content()","sub_path":"tagging.py","file_name":"tagging.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"156842147","text":"count = int(input(\"Введите число: \"))\n\n\nsimbol = \"*\"\nspace = \" \"\nstr_simbol = simbol * count # создаем строку символов ******* в зависимости от введенного числа\n\n\nsum_simbol = ' '\nsum_space = ' '\nnew_string = ' '\n'''\nfor i in str_simbol:\n sum_simbol += i + probel # '* '\n sum_spase = space * count # '___'\n new_string = sum_space + sum_simbol\n print(new_string)\n count -= 1\n'''\ni = 0\nc = count\n\nwhile i <= count:\n sum_simbol = i * (simbol + space)\n sum_space = space * c\n new_string = sum_space + sum_simbol\n print(new_string)\n c -= 1\n i += 1\n\n\n\n\n\n\n\n\n\n'''\ni=1\nj=5\nwhile i <= 5:\n\n print( (j * ' ') + i * '* ')\n\n j=j-1\n i=i+1\n\n'''\n","sub_path":"Chapter5/task4.2.py","file_name":"task4.2.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"339789116","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 23 20:10:32 2015\n\n@author: ev\n\"\"\"\n\nimport numpy as np\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n#x = np.array([0.15,2.3,3.15,4.85,6.25,7.95])\n#yn = np.array([4.79867,4.49013,4.2243,3.47313,2.66674,1.51909])\n\n# Let's create a function to model and create data\n\n#def func1(x, a, b):\n# return a*np.exp(b*x)\n\ndef func(x, a, b, c):\n return a*x**2+b*x+c\n\ndef func1(x, a, b):\n return a*x+b\n \n\n\ndef polyfit(x, yn, n,name, c=False):\n \"\"\"If c then we have 3 gradig polyome\"\"\"\n if c:\n popt, pcov = curve_fit(func, x[:n], yn[:n])\n ym = func(x, popt[0], popt[1], popt[2])\n print(\"The Vo fitted model is: {0:2f}*x²+{1:2f}*x+{2:2f} \".format(popt[0], popt[1], popt[2]))\n #Otherwise tw gradig ploynome\n else:\n popt, pcov = curve_fit(func1, x[:n], yn[:n])\n ym = func1(x, popt[0], popt[1])\n print(\"The rate fitted model for Ln(mean({0}))= {1:2f}*x+{2:2f} \".format(name,popt[0], popt[1]))\n \n #popt returns the best fit values for parameters of the given model (func)\n \n \n \n \n \n fig = plt.figure()\n ax = fig.add_subplot(111)\n #ax.plot(x, y, c='k', label='Function')\n ax.scatter(x, yn, color = 'r', marker = 'x')\n ax.plot(x, ym, color = 'g')\n \n \n plt.legend(['fitted Model',str(name)],fontsize=16,loc='upper left')\n \n ax.set_yscale('linear',fontsize=16)\n ax.tick_params(axis='x', labelsize=14)\n ax.tick_params(axis='y', labelsize=14)\n plt.ylabel('Ln(OD600_)',fontsize=16)\n plt.xlabel('Time(sec)',fontsize=16)\n ax.grid()\n plt.grid()\n plt.show()\n #print( popt )\n fig.savefig('scipy_311_ex2.pdf', bbox_inches='tight')\n \n return popt[0]\n\n\nif __name__ == \"__main__\":\n li=[]\n import pandas as pd\n \n for i in range(1,8):\n file='/home/ev/Documents/Kenetics_PLots/Sample-'+str(i)+'.xlsx'\n data1 = pd.read_excel(file)\n x=data1['Time(sec)']\n y=data1['Abs']\n \n fun=polyfit(x, y, 300,'wt', c=False)\n li.append(fun)","sub_path":"LastWeekProject/Trim1/polyTRim1.py","file_name":"polyTRim1.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"610511458","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 20 16:24:21 2017\n\n@author: bmyers\n\"\"\"\n#Websites and example code I used to figure this out:\n#http://www.pythonforbeginners.com/regex/regular-expressions-in-python\n#https://stackoverflow.com/questions/23277268/parse-date-strings\n#https://stackoverflow.com/questions/14441754/scatter-plot-of-dates-and-times\n#http://www.u.arizona.edu/~erdmann/mse350/topics/plotting_with_pylab.html\n#https://stackoverflow.com/questions/35839529/count-of-days-of-each-month-from-a-list-of-dates-python\n#https://stackoverflow.com/questions/34py96518/python-using-a-dictionary-to-count-the-items-in-a-list\n#https://stackoverflow.com/questions/3486121/how-to-plot-data-against-specific-dates-on-the-x-axis-using-matplotlib?rq=1\n#https://stackoverflow.com/questions/9847213/how-do-i-get-the-day-of-week-given-a-date-in-python\n\nimport csv\nimport itertools\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom matplotlib.dates import WeekdayLocator\nimport re\nimport datetime as dt\nimport dateutil\nfrom dateutil.parser import *\nfrom datetime import *\nimport pylab\nimport plotly.plotly as py\nimport plotly.graph_objs as go\nfrom plotly.graph_objs import *\nimport collections\nfrom collections import Counter\n\n#-----------------------------------------------\n#open file, create csv reader\n#-----------------------------------------------\nwith open(\"received final.csv\", \"r\", encoding=\"utf8\") as csvfile:\n reader = csv.reader(csvfile)\n \n#-----------------------------------------------\n#create list to store dates\n#-----------------------------------------------\n dates = [] \n \n#-----------------------------------------------\n#iterate through each row and field in the csv: the indentation of this section continues\n#-----------------------------------------------\n for row in reader:\n for field in row:\n \n#-----------------------------------------------\n#change text dates to datetime objects\n#----------------------------------------------- \n form_pattern = re.compile(\"^\\d{1,2}\\/\\d{1,2}\\/\\d{4}\") #look for this date pattern DD/MM/YYYY\n matches = re.findall(form_pattern, field) \n if matches: #if matches is not empty\n dates.append(matches)\n \ndates = list(itertools.chain(*dates)) #flatten list\n\nx = 0 #incrementing the for loop below\ndatetimes = [] #empty list for datetime objects\n\nfor i in dates: \n datetimes.append(datetime.strptime(str(dates[x]), '%m/%d/%Y')) #look for dates and convert\n x+=1\n \ndateslist = Counter(datetimes) #Counter counts the frequency of each date and put into dateslist dictionary in the format - datetime: key\n#-----------------------------------------------\n#plot received email dates for academic year\n#-----------------------------------------------\nx = [] #blank lists for axis\ny = []\n\nfor freq in dateslist.values(): #get the dictionary values (frequency counts) for the y axis\n y.append(freq)\nfor dates in dateslist.keys(): #get the dictionary keys (the dates) for the x axis\n x.append(dates) \n \nfig = plt.figure(figsize=(10, 5), dpi=150) #can change size of plot\ngraph = fig.add_subplot(111)\ngraph.plot_date(x,y,'g')\nax = fig.gca()\nax.set_xticklabels(['October', 'November', 'December', 'January', 'February', 'March', 'April', 'May', 'June'], fontsize=8)\nplt.ylabel('Number of emails')\nplt.title('Email distribution through 2016-17 school year')\n#plt.savefig('foo.png') #uncomment to save image to directory - can change filename\nplt.show()\n\n\n#-----------------------------------------------\n#plot received email dates per quarter ticks per week\n#-----------------------------------------------\n\n#fall\nfall = []\n\nfall_start_date = datetime(2016, 9, 19, 0, 0)\nfall_end_date = datetime(2017, 1, 8, 0, 0)\n\nfor i in datetimes:\n if i >= fall_start_date and i <= fall_end_date:\n fall.append(i)\n \nfall = Counter(fall)\n\nfallx = [] #blank lists for axis\nfally = []\n\nfor freq in fall.values(): #get the dictionary values (frequency counts) for the y axis\n fally.append(freq)\nfor dates in fall.keys(): #get the dictionary keys (the dates) for the x axis\n fallx.append(dates) \n \nfig = plt.figure(figsize=(15, 5), dpi=150) #can change size of plot\ngraph = fig.add_subplot(111)\nax = fig.gca()\nax.set_xticklabels(['September\\n15', 'September\\n29', 'October\\n13', 'October\\n27', 'November\\n10', 'November\\n24', 'December\\n8', 'December\\n22', 'January\\n5'], fontsize=8)\nplt.yticks(np.arange(min(fally), max(fally)+1, 1.0))\ngraph.plot_date(fallx,fally,color='#3B9AED', linestyle='solid', marker='o')\nplt.ylabel('Number of emails')\nplt.title('Fall quarter 2016')\n\nplt.show()\n\n#winter\nwinter = []\n\nwinter_start_date = datetime(2017, 1, 9, 0, 0)\nwinter_end_date = datetime(2017, 4, 2, 0, 0)\n\nfor i in datetimes:\n if i >= winter_start_date and i <= winter_end_date:\n winter.append(i)\n \nwinter = Counter(winter)\n\nwinterx = [] #blank lists for axis\nwintery = []\n\nfor freq in winter.values(): #get the dictionary values (frequency counts) for the y axis\n wintery.append(freq)\nfor dates in winter.keys(): #get the dictionary keys (the dates) for the x axis\n winterx.append(dates) \n \nfig = plt.figure(figsize=(10, 5), dpi=150) #can change size of plot\ngraph = fig.add_subplot(111)\nax = fig.gca()\nax.set_xticklabels(['January\\n11', 'January\\n25', 'February\\n8', 'February\\n22', 'March\\n8', 'March\\n22'], fontsize=8)\nplt.yticks(np.arange(min(fally), max(fally)+1, 1.0))\ngraph.plot_date(winterx,wintery,color='#3B9AED', linestyle='solid', marker='o')\nplt.ylabel('Number of emails')\nplt.title('Winter quarter 2017')\n\nplt.show()\n\n#spring\n\nspring = []\n\nspring_start_date = datetime(2017, 4, 3, 0, 0)\nspring_end_date = datetime(2017, 6, 17, 0, 0)\n\nfor i in datetimes:\n if i >= spring_start_date and i <= spring_end_date:\n spring.append(i)\n \nspring = Counter(spring)\n\nspringx = [] #blank lists for axis\nspringy = []\n\nfor freq in spring.values(): #get the dictionary values (frequency counts) for the y axis\n springy.append(freq)\nfor dates in spring.keys(): #get the dictionary keys (the dates) for the x axis\n springx.append(dates) \n \nfig = plt.figure(figsize=(10, 5), dpi=150) #can change size of plot\ngraph = fig.add_subplot(111)\nax = fig.gca()\nax.set_xticklabels(['April\\n2', 'April\\n16', 'April\\n30', 'May\\n14', 'May\\n28', 'June\\n11'], fontsize=8)\nplt.yticks(np.arange(min(fally), max(fally)+1, 1.0))\ngraph.plot_date(springx,springy,color='#3B9AED', linestyle='solid', marker='o')\nplt.ylabel('Number of emails')\nplt.title('Spring quarter 2017')\n\nplt.show()\n\n\n#-----------------------------------------------\n#pie chart number of days in the week\n#-----------------------------------------------\n\nsundays = []\nmondays = []\ntuesdays=[]\nwednesdays=[]\nthursdays=[]\nfridays=[]\nsaturdays=[]\n\nfor i in datetimes:\n if i.weekday() == 6:\n sundays.append(i)\n elif i.weekday() == 0:\n mondays.append(i)\n elif i.weekday() == 1:\n tuesdays.append(i)\n elif i.weekday() == 2:\n wednesdays.append(i)\n elif i.weekday() == 3:\n thursdays.append(i)\n elif i.weekday() == 4:\n fridays.append(i)\n elif i.weekday() == 5:\n saturdays.append(i)\n \nsunday_counts = len(sundays)\nmonday_counts = len(mondays)\ntuesday_counts = len(tuesdays)\nwednesday_counts = len(wednesdays)\nthursday_counts = len(thursdays)\nfriday_counts = len(fridays)\nsaturday_counts = len(saturdays)\n\n#show pie chart\nlabels = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']\ncounts = [sunday_counts, monday_counts, tuesday_counts, wednesday_counts, thursday_counts, friday_counts, saturday_counts]\nsizes = [sunday_counts, monday_counts, tuesday_counts, wednesday_counts, thursday_counts, friday_counts, saturday_counts]\ncolors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue', 'coral', 'blue', 'orange']\n\nplt.pie(sizes, labels=labels, colors=colors,\n autopct='%1.1f%%', shadow=True, startangle=140, pctdistance=0.8)\nplt.axis('equal')\nfig = plt.gcf()\nfig.set_size_inches(6,6)\nplt.suptitle('2016-2017 weekday distribution', fontsize=24)\nplt.show()","sub_path":"processReceivedMail.py","file_name":"processReceivedMail.py","file_ext":"py","file_size_in_byte":8185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"364664349","text":"from datetime import date\nfrom datetime import timedelta\nfrom ftw.builder import Builder\nfrom ftw.builder import create\nfrom ftw.testbrowser import browsing\nfrom ftw.testbrowser.pages.statusmessages import error_messages\nfrom opengever.tasktemplates.interfaces import IFromTasktemplateGenerated\nfrom opengever.testing import FunctionalTestCase\nfrom plone import api\nfrom plone.app.testing import TEST_USER_ID\nimport transaction\n\n\nclass TestTriggeringTaskTemplate(FunctionalTestCase):\n\n def setUp(self):\n super(TestTriggeringTaskTemplate, self).setUp()\n\n create(Builder('ogds_user').id(u'hugo.boss'))\n create(Builder('ogds_user').id(u'peter.meier'))\n self.dossier = create(Builder('dossier')\n .having(responsible=u'peter.meier'))\n self.templatedossier = create(Builder('templatedossier'))\n\n self.folder1 = create(Builder('tasktemplatefolder')\n .within(self.templatedossier)\n .titled(u'Mitberichtsverfahren')\n .in_state('tasktemplatefolder-state-activ'))\n\n create(Builder('tasktemplate')\n .within(self.folder1)\n .titled(u'Mitbericht FD')\n .having(preselected=True, deadline=17, issuer=u'current_user',\n responsible_client=u'interactive_users',\n responsible=u'current_user'))\n create(Builder('tasktemplate')\n .within(self.folder1)\n .titled(u'Mitbericht DI')\n .having(preselected=False, deadline=3, issuer=u'hugo.boss',\n responsible_client=u'client1',\n responsible=u'hugo.boss'))\n create(Builder('tasktemplate')\n .within(self.folder1)\n .titled(u'Mitbericht SD')\n .having(preselected=False, deadline=5, issuer=u'responsible',\n responsible_client=u'interactive_users',\n responsible=u'responsible'))\n\n def trigger_tasktemplatefolder(self, browser, folder='Mitberichtsverfahren', templates=[]):\n browser.login().open(self.dossier, view='add-tasktemplate')\n browser.fill({'Tasktemplatefolder': folder})\n browser.click_on('Continue')\n\n browser.fill({'Tasktemplates': templates})\n browser.click_on('Trigger')\n\n @browsing\n def test_redirects_back_and_show_statusmessage_when_no_active_tasktemplatefolder_exists(self, browser):\n api.content.transition(\n self.folder1,\n transition='tasktemplatefolder-transition-activ-inactiv')\n transaction.commit()\n\n browser.login().open(self.dossier, view='add-tasktemplate')\n self.assertEquals(self.dossier.absolute_url(), browser.url)\n self.assertEquals(\n ['Currently there are no active task template folders registered.'],\n error_messages())\n\n @browsing\n def test_all_active_tasktemplates_are_listed(self, browser):\n create(Builder('tasktemplatefolder')\n .titled(u'Einsprache abarbeiten'))\n create(Builder('tasktemplatefolder')\n .titled(u'Einb\\xfcrgerungsverfahren')\n .in_state('tasktemplatefolder-state-activ'))\n\n browser.login().open(self.dossier, view='add-tasktemplate')\n\n self.assertEquals(\n [u'Einb\\xfcrgerungsverfahren', 'Mitberichtsverfahren'],\n browser.css('#formfield-form-widgets-tasktemplatefolder').first.options)\n\n @browsing\n def test_step2_list_all_tasktemplates_of_the_selected_folder_and_preselects_them_correctly(self, browser):\n browser.login().open(self.dossier, view='add-tasktemplate')\n browser.fill({'Tasktemplatefolder': 'Mitberichtsverfahren'})\n browser.click_on('Continue')\n\n self.assertEquals(\n ['Mitbericht FD', 'Mitbericht DI', 'Mitbericht SD'],\n browser.css('#formfield-form-widgets-tasktemplates .option').text)\n\n self.assertEquals(\n ['Mitbericht FD'],\n browser.css('#formfield-form-widgets-tasktemplates input[checked]').getparents().text)\n\n @browsing\n def test_creates_main_task_assigned_to_current_user(self, browser):\n self.trigger_tasktemplatefolder(\n browser, templates=['Mitbericht FD', 'Mitbericht DI'])\n\n main_task = self.dossier.get('task-1')\n self.assertEquals(u'Mitberichtsverfahren', main_task.title)\n self.assertEquals(TEST_USER_ID, main_task.responsible)\n self.assertEquals(TEST_USER_ID, main_task.issuer)\n self.assertEquals('direct-execution', main_task.task_type)\n\n @browsing\n def test_sets_main_task_to_in_progress_state(self, browser):\n self.trigger_tasktemplatefolder(\n browser, templates=['Mitbericht FD', 'Mitbericht DI'])\n\n main_task = self.dossier.get('task-1')\n self.assertEquals('task-state-in-progress',\n api.content.get_state(main_task))\n\n @browsing\n def test_main_task_deadline_is_the_highest_template_deadline_plus_five(self, browser):\n self.trigger_tasktemplatefolder(\n browser, templates=['Mitbericht FD', 'Mitbericht DI'])\n\n self.assertEquals(date.today() + timedelta(days=17 + 5),\n self.dossier.get('task-1').deadline)\n\n @browsing\n def test_all_tasks_are_marked_with_marker_interface(self, browser):\n self.trigger_tasktemplatefolder(\n browser, templates=['Mitbericht FD', 'Mitbericht DI'])\n\n main_task = self.dossier.get('task-1')\n self.assertTrue(IFromTasktemplateGenerated.providedBy(main_task))\n\n for subtask in main_task.listFolderContents():\n self.assertTrue(IFromTasktemplateGenerated.providedBy(subtask))\n\n @browsing\n def test_creates_a_subtask_for_each_selected_template(self, browser):\n self.trigger_tasktemplatefolder(\n browser, templates=['Mitbericht FD', 'Mitbericht SD'])\n\n main_task = self.dossier.get('task-1')\n self.assertEquals(2, len(main_task.listFolderContents()))\n\n subtask1, subtask2 = main_task.listFolderContents()\n self.assertEquals('Mitbericht FD', subtask1.title)\n self.assertEquals('Mitbericht SD', subtask2.title)\n\n @browsing\n def test_replace_interactive_issuer(self, browser):\n self.trigger_tasktemplatefolder(\n browser,\n templates=['Mitbericht FD', 'Mitbericht DI', 'Mitbericht SD'])\n\n main_task = self.dossier.get('task-1')\n subtask1, subtask2, subtask3 = main_task.listFolderContents()\n\n # current_user\n self.assertEquals(TEST_USER_ID, subtask1.issuer)\n\n # not interactive\n self.assertEquals('hugo.boss', subtask2.issuer)\n\n # responsible\n self.assertEquals('peter.meier', subtask3.issuer)\n\n @browsing\n def test_replace_interactive_responsibles(self, browser):\n self.trigger_tasktemplatefolder(\n browser,\n templates=['Mitbericht FD', 'Mitbericht DI', 'Mitbericht SD'])\n\n main_task = self.dossier.get('task-1')\n subtask1, subtask2, subtask3 = main_task.listFolderContents()\n\n # current_user\n self.assertEquals(TEST_USER_ID, subtask1.responsible)\n self.assertEquals('client1', subtask1.responsible_client)\n\n # not interactive\n self.assertEquals('hugo.boss', subtask2.responsible)\n self.assertEquals('client1', subtask1.responsible_client)\n\n # responsible\n self.assertEquals('peter.meier', subtask3.responsible)\n self.assertEquals('client1', subtask1.responsible_client)\n\n @browsing\n def set_relateditems_on_every_subtask_when_selected(self, browser):\n doc1 = create(Builder('document')\n .within(self.dossier)\n .titled(u'Doc A'))\n doc2 = create(Builder('document')\n .within(self.dossier)\n .titled(u'Doc B'))\n\n self.trigger_tasktemplatefolder(\n browser, templates=['Mitbericht FD', 'Mitbericht SD'],\n documents=['Doc A', 'Doc B'])\n\n main_task = self.dossier.get('task-1')\n subtask1, subtask2 = main_task.listFolderContents()\n\n self.assertEquals([doc1, doc2], subtask1.relatedItems)\n self.assertEquals([doc1, doc2], subtask2.relatedItems)\n","sub_path":"opengever/tasktemplates/tests/test_trigger.py","file_name":"test_trigger.py","file_ext":"py","file_size_in_byte":8346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"348415432","text":"import os\nimport sys\nfrom bs4 import BeautifulSoup\nfrom lxml import etree\nimport requests\nimport csv\nimport re\n\n#incase your connection keeps getting interrupted\nSTARTNEW = True\n\ndef setAction(whatAction):\n\treturn 'action='+whatAction+'&'\n\ndef setFormat(whatFormat):\n\treturn 'format='+whatFormat+'&'\n\ndef searchFor(searchTerms, limit):\n\treturn 'search='+searchTerms+'&limit='+limit+'&'\n\ndef setProp(whatProp):\n\treturn 'prop='+whatProp+'&'\n\ndef titles(whatTitles):\n\tlistOfTitles = ''\n\tfor title in whatTitles:\n\t\tlistOfTitles += title+\"|\"\n\treturn 'titles='+listOfTitles[:-1]+'&'\n\ndef getPage(url):\n\tpage = requests.get(url)\n\treturn page\n\ndef searchWikiURL(wikiURL, searchTerms, limit):\n\treturn wikiURL+setAction('opensearch')+setFormat('xml')+searchFor(searchTerms, limit)\n\ndef queryWikiURL(wikiURL, queryTerms):\n\treturn wikiURL+setAction('query')+setFormat('xml')+titles(queryTerms)\n\t\n\t\ndef pp(e):\n print(etree.tostring(e, pretty_print=True))\n print('')\n\ndef strip_ns(tree):\n for node in tree.iter():\n try:\n has_namespace = node.tag.startswith('{')\n except AttributeError:\n continue\n if has_namespace:\n node.tag = node.tag.split('}', 1)[1]\n\ndef stripString(str):\n\tnewStr = str\n\t#remove unwanted stuff\n\tnewStr = newStr.replace(\"\\xa0\",\"\")\n\tnewStr = newStr.replace(\"\\n\",\"\")\n\tnewStr = newStr.replace(\"\\u2009\",\"\")\n\t#remove anything after the )\n\tnewStr = re.sub(\"\\)(.*)\",\")\",newStr)\n\tnewStr = re.sub(\"\\[(\\d*)\\]\",\"\",newStr)\n\t#return stripped string\n\treturn newStr\n\ndef scrapePage(link, pageType):\n\n#scrape a page about a Name, Size, Location, Latitude, Longitude, Image, Type, Description\n\thtmlPage = getPage(link)\n\tmySoup = BeautifulSoup(htmlPage.content, \"html.parser\")\n\t#predefine data list\n\tscrapedData = [\"No name\",\"No size\",\"No location\",\"No longitude\", \"No latitude\", \"No image\",\"No Type\",\"No Description\"]\n\t#get the whole article header\n\tmtnName = mySoup.h1.string\n\tscrapedData[0] = mtnName\n\n\tif mtnName is None:\n\t\treturn []\n\n\tif \"Bridge\" in mtnName:\n\t\tpageType = \"Bridge\"\n\n\t#figure out what type it is\n\tmountainTags = ['Elevation']\n\tbridgeTags = ['Total length']\n\tbuildingTags = ['Architectural','Roof','Top Floor','Antenna spire','Height']\n\texcludeTags = ['Destroyed','Demolished','Founded']\n\tplannedTags = ['Proposed', 'Under construction','Approved']\n\n\tif pageType is \"Mountain\":\n\t\tfor i in range(len(mountainTags)):\n\t\t\telev = mySoup.find('th',string =mountainTags[i])\n\t\t\tif elev is not None:\n\t\t\t\t#scrape the data next in the table\n\t\t\t\tpartString = elev.find_next_sibling('td')\n\t\t\t\tif partString!=None:\n\t\t\t\t\tscrapedData[1] = stripString(partString.text)\n\t\t\t\t\tif len(scrapedData[1].strip())<=0:\n\t\t\t\t\t\t#no input for elevation\n\t\t\t\t\t\treturn []\n\t\t\t\telse:\n\t\t\t\t\treturn []\n\n\n\tif pageType is \"Bridge\":\n\t\tfor i in range(len(bridgeTags)):\n\t\t\telev = mySoup.find('th',string =bridgeTags[i])\n\t\t\tif elev is not None:\n\n\t\t\t\tpartString = elev.find_next_sibling('td')\n\t\t\t\tif partString!=None:\n\t\t\t\t\tscrapedData[1] = stripString(partString.text)\n\t\t\t\t\tif len(scrapedData[1].strip())<=0:\n\t\t\t\t\t\treturn []\n\t\t\t\telse:\n\t\t\t\t\treturn []\n\n\n\tif pageType is \"Building\":\n\n\t\t#exclude nonexistant buildings\n\t\tfor i in range(len(excludeTags)):\n\t\t\tif mySoup.find('th',string =excludeTags[i]) is not None:\n\t\t\t\treturn []\n\n\t\t#exlcude planned buildings\n\t\tstatus = mySoup.find('th',string ='Status')\n\t\tif status is not None:\n\t\t\tpartString = status.find_next_sibling('td')\n\t\t\tif partString is not None:\n\t\t\t\tfor i in range(len(plannedTags)):\n\t\t\t\t\tif plannedTags[i] in partString:\n\t\t\t\t\t\treturn []\n\n\n\t\telev = None\n\t\t#find the tag with height information\n\t\tfor i in range(len(buildingTags)):\n\t\t\tif elev is None:\n\t\t\t\telev = mySoup.find('th',string =buildingTags[i])\n\n\t\tif elev is None:\n\t\t\t#if no height then its not a building\n\t\t\treturn []\n\t\telse:\n\t\t\t#scrape the data next in the table\n\t\t\tpartString = elev.find_next_sibling('td')\n\t\t\tif partString!=None:\n\t\t\t\tscrapedData[1] = stripString(partString.text)\n\t\t\t\tif len(scrapedData[1].strip())<=0:\n\t\t\t\t\t#no input for elevation\n\t\t\t\t\treturn []\n\t\t\telse:\n\t\t\t\treturn []\n\n\tif pageType is None:\n\t\treturn []\n\n\tif \"No size\" in scrapedData[1]:\n\t\treturn []\n\n\tpara = mySoup.find('p')\n\n\twhile para != None:\n\n\t\tif re.sub(\"\\W\",\"\",mtnName) in re.sub(\"\\W\",\"\",para.text):\n\t\t\tscrapedData[7] = re.sub(\"\\[(\\d*)\\]\",\"\",para.text)\n\t\t\tbreak\n\t\tpara = para.find_next_sibling('p')\n\n\t#find the tag with location\n\tloc = mySoup.find('th',string ='Location')\n\tif loc is not None:\n\t\t#scrape the data next in the table\n\t\tif loc.find_next_sibling('td') is not None:\n\t\t\tscrapedData[2] = stripString(loc.find_next_sibling('td').text)\n\telse:\n\t\tloc = mySoup.find('th',string ='Locale')\n\t\tif loc is not None:\n\t\t\tif loc.find_next_sibling('td') is not None:\n\t\t\t\tscrapedData[2] = stripString(loc.find_next_sibling('td').text)\n\n\t#find the tag with latitude\n\tlat = mySoup.find(class_ ='latitude')\n\tif lat is not None:\n\t\t#scrape the text data from it\n\t\tscrapedData[3] = lat.text\n\n\t#find the tag with longitude\n\tlon = mySoup.find(class_ ='longitude')\n\tif lon is not None:\n\t\t#scrape the text data from it\n\t\tscrapedData[4] = lon.text\n\n\t#find the og:image property\n\timage = mySoup.find(property = 'og:image')\n\tif image is not None:\n\t\t#scrape the content data from it\n\t\tscrapedData[5] = image['content']\n\n\tscrapedData[6] = pageType\n\n\treturn scrapedData\n\ndef getLinksFromPage(link):\n\tlinkList = []\n\twiki = \"https://en.wikipedia.org/w/api.php?\"\n\twikiURL = queryWikiURL(wiki, link)+setProp('links')+'pllimit=500'\n\tapiContinue = \" \"\n\n\twhile (len(apiContinue)>0):\n\n\t\tprint(\"Visit \" + wikiURL)\n\t\trawPage = getPage(wikiURL)\n\t\troot = etree.fromstring(rawPage.content)\n\t\tstrip_ns(root)\n\n\t\tapiContinue = root.xpath('/api/continue/@plcontinue')\n\t\tlinks = root.xpath('/api/query/pages/page/links/pl/@title')\n\n\t\tfor i in range(0,len(links)):\n\t\t\t#add page name to list\n\t\t\tif 'Geography of' not in links[i]:\n\t\t\t\tlinkList.append(links[i])\n\n\t\tif(len(apiContinue)>0):\n\t\t\t#add continue api to link\n\t\t\twikiURL = queryWikiURL(wiki, link)+setProp('links')+'pllimit=500&plcontinue='+apiContinue[0]\n\n\treturn linkList\n\ndef getBridgeLinksFromPage(link):\n\tlinkList = []\n\twiki = \"https://en.wikipedia.org/w/api.php?\"\n\twikiURL = queryWikiURL(wiki, link)+setProp('links')+'pllimit=500'\n\tapiContinue = \" \"\n\tuniqueLinks = {}\n\n\twhile (len(apiContinue)>0):\n\n\t\tprint(\"Visit \" + wikiURL)\n\t\trawPage = getPage(wikiURL)\n\t\troot = etree.fromstring(rawPage.content)\n\t\tstrip_ns(root)\n\n\t\tapiContinue = root.xpath('/api/continue/@plcontinue')\n\t\tlinks = root.xpath('/api/query/pages/page/links/pl/@title')\n\n\t\tfor i in range(0,len(links)):\n\n\t\t\tif 'List of bridges in ' in links[i]:\n\t\t\t\tnewLinks = getLinksFromPage([links[i]])\n\n\t\t\t\tfor x in range(len(newLinks)):\n\t\t\t\t\tif \"Bridge\" in newLinks[x] and uniqueLinks.get(newLinks[x])==None:\n\t\t\t\t\t\tlinkList.append(newLinks[x])\n\t\t\t\t\t\tuniqueLinks[newLinks[x]]=1\n\t\t\telse:\n\t\t\t\tif \"Bridge\" in links[i] and uniqueLinks.get(links[i])==None:\n\t\t\t\t\tlinkList.append(links[i])\n\t\t\t\t\tuniqueLinks[links[i]]=1\n\n\t\tif(len(apiContinue)>0):\n\t\t\t#add continue api to link\n\t\t\twikiURL = queryWikiURL(wiki, link)+setProp('links')+'pllimit=500&plcontinue='+apiContinue[0]\n\n\treturn linkList\n\ndef main():\n\t#how many tuples to be put in the database\n\tmaxTuples = 10000\n\n\tmountainLinks = ['List of mountains by elevation']\n\tbridgeLinks = ['List_of_bridges']\n\tbuildingLinks = ['List_of_tallest_buildings_in_Asia','List_of_tallest_buildings_in_the_United_States','List_of_tallest_buildings_in_Europe','List_of_tallest_buildings_in_Oceania','List_of_tallest_buildings_in_South_America','List_of_tallest_buildings_in_Africa']\n\n\tlinkList = []\n\tuniqueNames = {}\n\n\tprint(\"Getting links\")\n\t\n\tpotentialMountains = getLinksFromPage(mountainLinks)\n\tpotentialBridges = getBridgeLinksFromPage(bridgeLinks)\n\tpotentialBuildings = getLinksFromPage(buildingLinks)\n\n\tlinkList = potentialMountains + potentialBridges + potentialBuildings\n\n\tmountainsSize = len(potentialMountains)\n\tbridgesSize = len(potentialBridges)\n\tbuildingsSize = len(potentialBuildings)\n\n\tprint(\"Potential links found \" + str(len(linkList)))\n\n\tstartIndex = 0;\n\n\tcurrentData = []\n\n\tif STARTNEW==False:\n\t\twith open('fullDatabase.csv') as f:\n\t\t\tcsvreader = csv.reader(f)\n\t\t\tfor row in csvreader:\n\t\t\t\tcurrentData.append(row)\n\t\t\t\tuniqueNames[row[0]]=1\n\t\t\t\tstartIndex = startIndex + 1\n\n\n\t#open database.csv\t\t\n\twith open('fullDatabase.csv','w') as f:\n\t\t#create csv writer object\n\t\tcsvwriter = csv.writer(f)\n\n\t\tprint(\"Getting data from individual pages\")\n\n\t\ttuplesAcquired = 0\n\t\tfor i in range(len(linkList)):\n\t\t\tif i>=startIndex:\n\t\t\t\t#stop if we have enough tuples\n\t\t\t\tif tuplesAcquired>=maxTuples:\n\t\t\t\t\t#stop when enough tuples added\n\t\t\t\t\ti = range(len(linkList))\n\t\t\t\telse:\n\n\t\t\t\t\tif \"List of\" not in linkList[i] and \"Template\" not in linkList[i] and \"Category\" not in linkList[i]:\n\t\t\t\t\t\t#create url\n\t\t\t\t\t\tpageURL = \"https://en.wikipedia.org/wiki/\"+linkList[i]\n\t\t\t\t\t\tprint(\"Scraping \"+pageURL)\n\n\t\t\t\t\t\tpageType = None\n\t\t\t\t\t\tif i < mountainsSize:\n\t\t\t\t\t\t\tpageType = \"Mountain\"\n\t\t\t\t\t\telif i < bridgesSize:\n\t\t\t\t\t\t\tpageType = \"Bridge\"\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tpageType = \"Building\"\n\n\t\t\t\t\t\t#get scraped data in list form\n\t\t\t\t\t\tpageData = scrapePage(pageURL,pageType)\n\t\t\t\t\t\t\t\n\t\t\t\t\t\tif len(pageData)>0:\n\t\t\t\t\t\t\tif uniqueNames.get(pageData[0])==None:\n\t\t\t\t\t\t\t\t#write whats in the array to the next empty row\n\t\t\t\t\t\t\t\ttuplesAcquired = tuplesAcquired + 1\n\t\t\t\t\t\t\t\tcsvwriter.writerow(pageData)\n\t\t\t\t\t\t\t\tuniqueNames[pageData[0]]=1\n\t\t\telse:\n\t\t\t\tcsvwriter.writerow(currentData[i])\n\t\t\t\tuniqueNames[currentData[i][0]]=1\n\n\tprint(\"Finished and made \"+str(tuplesAcquired)+\" tuples!\")\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"landmarkAttractions/fullScraper.py","file_name":"fullScraper.py","file_ext":"py","file_size_in_byte":9510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"235160661","text":"# Copyright 2019 Contributors to Hyperledger Sawtooth\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\"\"\"Sets up a standard logging format and setting\"\"\"\n\nimport logging\n\nLIB_LEVELS = {\"asyncio\": logging.WARNING}\nLOGGER_FORMAT = \"%(levelname)s %(asctime)s %(name)s %(module)s %(pathname)s %(message)s\"\n\nlogging.basicConfig(level=logging.INFO, format=LOGGER_FORMAT)\n\nfor lib, level in LIB_LEVELS.items():\n logging.getLogger(lib).setLevel(level)\n\n\ndef get_logger(name):\n \"\"\"Return the logger\n Written to match the standard python logging.getLogger\n function for ease of migration\n \"\"\"\n logger = logging.getLogger(name)\n return logger\n","sub_path":"rbac/common/logs/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"268664658","text":"def _all_():\n import os\n import time\n import sys\n import time\n import subprocess\n from baner import baner\n try:\n import re\n except:\n time.sleep(1)\n print(\"[-] Pleass Install The Librery --> re\")\n sys.exit()\n try:\n from colorama import Fore\n except:\n time.sleep(1)\n print(\"[-] Pleass Install The Librery --> colorama\")\n sys.exit()\n try:\n import netifaces\n except:\n time.sleep(1)\n print(\"[-] Pleass Install The Librery --> netifaces\")\n sys.exit()\n time.sleep(0.6)\n os.system(\"clear\")\n baner()\n time.sleep(1)\n def result():\n my_list = input(Fore.LIGHTBLACK_EX + \"\\n[!] Pleass Enter Your New Mac And Name Netword : \").split(\",\")\n if len(my_list) != 2:\n time.sleep(1)\n print(Fore.RED + \"\\n[-] Your Data Hase The Problem !!!\")\n try:\n nwe_mac = my_list[0]\n except:\n time.sleep(1)\n print(Fore.RED + \"\\n[-] Your Arguman Hase The Problem !!!\")\n sys.exit()\n try:\n name_network = my_list[1]\n except:\n time.sleep(1)\n print(Fore.RED + \"\\n[-] Your Arguman Hase The Problem !!!\")\n sys.exit()\n name_all_network = netifaces.interfaces()\n if name_network not in name_all_network:\n time.sleep(1)\n print(Fore.RED + \"\\n[-] Your Name Network Hase The Problem !!!\")\n sys.exit()\n else:\n pass\n if re.search(\"\\w\\w:\\w\\w:\\w\\w:\\w\\w:\\w\\w:\\w\\w:\" , nwe_mac):\n time.sleep(1)\n print(Fore.RED + \"\\n[-] Your New Mac Hase The Problem !!!\")\n sys.exit()\n subprocess.run([\"sudo\" , \"ifconfig\" , name_network , \"down\"] , shell=True)\n subprocess.run([\"sudo\" , \"ipconfig\" , name_network , \"hw\" , \"ether\" , nwe_mac])\n subprocess.run([\"sudo\" , \"ifconfig\" , name_network , \"up\"] , shell=True)\n","sub_path":"mac_changer.py","file_name":"mac_changer.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"521042632","text":"# SPDX-FileCopyrightText: 2017 Mikey Skylar for Adafruit Industries\n#\n# SPDX-License-Identifier: MIT\n\nimport time\nfrom rainbowio import colorwheel\nimport board\nimport neopixel\n\npixpin = board.D1\nnumpix = 20\n\npixels = neopixel.NeoPixel(pixpin, numpix, brightness=.3, auto_write=False)\n\nrgb_colors = ([179, 0, 0],\n [0, 179, 0],\n [0, 0, 0])\n\nrgb_idx = 0 # index counter - primary color we are on\ncolor = (0, 164, 179) # Starting color\nmode = 0 # Current animation effect\noffset = 0\nprevtime = 0\n\n\ndef rainbow_cycle(wait):\n for j in range(255 * 6): # 6 cycles of all colors on colorwheel\n for r in range(len(pixels)):\n idx = int((r * 255 / len(pixels)) + j)\n pixels[r] = colorwheel(idx & 255)\n pixels.write()\n time.sleep(wait)\n\n\ndef rainbow(wait):\n for j in range(255):\n for index in range(len(pixels)):\n idx = int(index + j)\n pixels[index] = colorwheel(idx & 255)\n pixels.write()\n time.sleep(wait)\n\n\ndef rainbow_cycle_slow(wait):\n for j in range(255 * 3): # 3 cycles of all colors on colorwheel\n for r in range(len(pixels)):\n idx = int((r * 255 / len(pixels)) + j)\n pixels[r] = colorwheel(idx & 255)\n pixels.write()\n time.sleep(wait)\n\n\ndef rainbow_hold(wait):\n for j in range(255 * 1): # 3 cycles of all colors on colorwheel\n for r in range(len(pixels)):\n idx = int((r * 255 / len(pixels)) + j)\n pixels[r] = colorwheel(idx & 255)\n pixels.write()\n time.sleep(wait)\n\n\nwhile True:\n\n if mode == 0: # rainbow hold\n rainbow_hold(0.02)\n time.sleep(.5)\n\n elif mode == 1: # rainbow cycle slow\n rainbow_cycle_slow(0.02)\n time.sleep(0.05)\n\n elif mode == 2: # rainbow cycle fast\n rainbow_cycle(0.005)\n time.sleep(0.050)\n\n t = time.monotonic()\n\n if (t - prevtime) > 8: # Every 8 seconds...\n mode += 1 # Next mode\n if mode > 2: # End of modes?\n mode = 0 # Start modes over\n\n if rgb_idx > 2: # reset R-->G-->B rotation\n rgb_idx = 0\n\n color = rgb_colors[rgb_idx] # next color assignment\n rgb_idx += 1\n\n for i in range(numpix):\n pixels[i] = (0, 0, 0)\n\n prevtime = t\n","sub_path":"raver_bandolier/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"384297625","text":"from panda3d.core import Point3, Vec3\n\n\n\"\"\"\nDifferent filters used throughout the code.\n\"\"\"\nclass Lpf():\n\t#-------------------------------------------------------------------------#\n\tdef __init__(self, val, length):\n\t#-------------------------------------------------------------------------#\n\t\tself.val = val\n\t\tself.cnt = 0\n\t\tself.len = length\n\n\t\tself.vals = []\n\n\t\tself.lastEntry = 0\n\n\t#-------------------------------------------------------------------------#\n\tdef filter(self, val):\n\t#-------------------------------------------------------------------------#\n\t\t\n\t\t# If the filter has all entries filled, subtract the oldest entry\n\t\tif(self.cnt == self.len):\n\t\t\tself.val -= self.vals[self.lastEntry]\n\t\t\tself.vals[self.lastEntry] = val\n\t\telse:\n\t\t\t# If the filter does not have all entries filled, increment the\n\t\t\t# number filled since we are adding one\n\t\t\tself.vals.append(val)\n\t\t\tself.cnt = self.cnt + 1\n\n\t\tself.val += self.vals[self.lastEntry]\n\t\tself.lastEntry = (self.lastEntry + 1)%self.len\n\n\t\treturn self.val/self.cnt\n\n\t#-------------------------------------------------------------------------#\n\tdef getVals(self):\n\t#-------------------------------------------------------------------------#\n\t\treturn ', '.join([str(x) for x in self.vals])\n\n\nclass LpfVec3():\n\tdef __init__(self, val, length):\n\t\tself.lpfx = Lpf(val.getX(), length)\n\t\tself.lpfy = Lpf(val.getY(), length)\n\t\tself.lpfz = Lpf(val.getZ(), length)\n\n\tdef filter(self, val):\n\t\treturn Vec3(self.lpfx.filter(val.getX()),\n\t\t\t\t\tself.lpfy.filter(val.getY()),\n\t\t\t\t\tself.lpfz.filter(val.getZ()))\n\n\n\nclass Hysteresis():\n\tdef __init__(self, lb, hb):\n\t\tself.lb = lb\n\t\tself.hb = hb\n\n\t\tself.STATE_ABOVE_HB = 0\n\t\tself.STATE_BELOW_HB_ABOVE_LB = 1\n\t\tself.STATE_BELOW_LB = 2\n\n\t\tself.state = self.STATE_ABOVE_HB\n\n\t\tself.minVal = float(\"inf\")\n\n\tdef filter(self, val):\n\t\t\n\t\tnextState = self.state\n\t\trVal = val\n\n\t\tif(self.state == self.STATE_ABOVE_HB):\n\t\t\tif(val < self.lb):\n\t\t\t\tnextState = self.STATE_BELOW_LB\n\t\t\t\trVal = val\n\t\t\telif(val < self.hb):\n\t\t\t\tnextState = self.STATE_BELOW_HB_ABOVE_LB\n\t\t\t\trVal = val\n\n\t\telif(self.state == self.STATE_BELOW_HB_ABOVE_LB):\n\t\t\tif(val < self.lb):\n\t\t\t\tnextState = self.STATE_BELOW_LB\n\t\t\t\tif(val < self.minVal):\n\t\t\t\t\tself.minVal = val\n\t\t\t\trVal = self.minVal\n\n\t\telif(self.state == self.STATE_BELOW_LB):\n\t\t\tif(val > self.hb):\n\t\t\t\tnextState = self.STATE_ABOVE_HB\n\t\t\t\trVal = val\n\t\t\telif(val < self.lb):\n\t\t\t\tif(val < self.minVal):\n\t\t\t\t\tself.minVal = val\n\t\t\t\trVal = self.minVal\n\t\t\telse:\n\t\t\t\trVal = self.minVal\n\n\t\tself.state = nextState\n\t\treturn max(rVal,0)\n\n\tdef getState(self):\n\t\treturn self.state\n\n\n\n","sub_path":"filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"274430182","text":"# !/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# ******************************************************************************\n# Copyright (c) 2018 Mejbah ul Alam, Justin Gottschlich, Abdullah Muzahid\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\n# all 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\nimport subprocess\n\nfrom setuptools import setup\nfrom setuptools import find_packages\nfrom setuptools.command.install import install\nfrom setuptools.command.develop import develop\n\n\nclass CustomInstall(install):\n \"\"\"Custom handler for the 'install' command.\"\"\"\n def run(self):\n print('[DEBUG] making perfpoint.so')\n subprocess.check_call('make', cwd='./autoperf/profiler/', shell=True)\n super().run()\n\n\nclass CustomDevelop(develop):\n \"\"\"Custom handler for the 'develop' command.\"\"\"\n def run(self):\n print('[DEBUG] making perfpoint.so')\n subprocess.check_call('make', cwd='./autoperf/profiler/', shell=True)\n super().run()\n\n\nsetup(name='autoperf',\n version='1.0',\n description='AutoPerf helps identify performance regressions in large codebases',\n long_description='AutoPerf is a tool for low-overhead, automated diagnosis \\\n of performance anomalies in multithreaded programs via \\\n hardware performance counters (HWPCs) in Intel CPUs',\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3.8',\n 'Operating System :: POSIX :: Linux',\n 'Topic :: Software Development :: Quality Assurance',\n ],\n keywords='autoperf performance regression monitoring',\n author='Intel Corporation',\n license='MIT',\n # packages=['autoperf','annotation'], #include fsm and annotation\n packages=find_packages(where=\".\", exclude=(\"./docs\",'./profiler', './.empty', './__pycache__')),\n zip_safe=False,\n entry_points={'console_scripts': ['autoperf=autoperf.__main__:main']},\n cmdclass={'install': CustomInstall, 'develop': CustomDevelop},\n package_dir={'autoperf': 'autoperf'},\n package_data={'autoperf': ['profiler/perfpoint.so']},\n include_package_data=True\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"634933610","text":"\n\nfrom xai.brain.wordbase.verbs._absolve import _ABSOLVE\n\n#calss header\nclass _ABSOLVED(_ABSOLVE, ):\n\tdef __init__(self,): \n\t\t_ABSOLVE.__init__(self)\n\t\tself.name = \"ABSOLVED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"absolve\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_absolved.py","file_name":"_absolved.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"156247515","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2015, ESS LLP and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\nfrom frappe.model.document import Document\nimport json\nfrom frappe.utils import getdate, cint\nfrom frappe import _\nimport datetime\nfrom frappe.core.doctype.sms_settings.sms_settings import send_sms\nfrom clinic.clinic.doctype.clinic_settings.clinic_settings import get_receivable_account,get_income_account\n\n\nclass ClientAppointmentCT(Document):\n\tdef on_update(self):\n\t\ttoday = datetime.date.today()\n\t\tappointment_date = getdate(self.appointment_date)\n\n\n\tdef save(self, *args, **kwargs):\n\t\t# duration is the only changeable field in the document\n\t\tif not self.is_new():\n\t\t\tself.db_set('duration', cint(self.duration))\n\t\telse:\n\t\t\tsuper(ClientAppointmentCT, self).save(*args, **kwargs)\n\n\ndef appointment_cancel(appointment_id):\n\tappointment = frappe.get_doc(\"Client Appointment CT\", appointment_id)\n\n\t# If invoice --> fee_validity update with -1 visit\n\tif appointment.sales_invoice:\n\t\tvalidity = frappe.db.exists({\"doctype\": \"Fee Validity\", \"ref_invoice\": appointment.sales_invoice})\n\t\tif validity:\n\t\t\tfee_validity = frappe.get_doc(\"Fee Validity\", validity[0][0])\n\t\t\tvisited = fee_validity.visited - 1\n\t\t\tfrappe.db.set_value(\"Fee Validity\", fee_validity.name, \"visited\", visited)\n\t\t\tif visited <= 0:\n\t\t\t\tfrappe.msgprint(\n\t\t\t\t\t_(\"Appointment cancelled, Please review and cancel the invoice {0}\".format(appointment.sales_invoice))\n\t\t\t\t)\n\t\t\telse:\n\t\t\t\tfrappe.msgprint(_(\"Appointment cancelled\"))\n\n\n@frappe.whitelist()\ndef get_availability_data(date, physician):\n\t\"\"\"\n\tGet availability data of 'physician' on 'date'\n\t:param date: Date to check in schedule\n\t:param physician: Name of the physician\n\t:return: dict containing a list of available slots, list of appointments and time of appointments\n\t\"\"\"\n\n\tdate = getdate(date)\n\tweekday = date.strftime(\"%A\")\n\n\tavailable_slots = []\n\tphysician_schedule_name = None\n\tphysician_schedule = None\n\ttime_per_appointment = None\n\n\t# get physicians schedule\n\tphysician_schedule_name = frappe.db.get_value(\"Doctor\", physician, \"physician_schedule\")\n\tif physician_schedule_name:\n\t\tphysician_schedule = frappe.get_doc(\"Physician Schedule CT\", physician_schedule_name)\n\t\ttime_per_appointment = frappe.db.get_value(\"Doctor\", physician, \"time_per_appointment\")\n\t\t#frappe.msgprint(json.dumps(time_per_appointment))\n\telse:\n\t\tfrappe.throw(_(\"Dr {0} does not have a Physician Schedule. Add it in Physician master\".format(physician)))\n\n\t#custom:inside below block i did change divide block (from_time to to_time and each divide time per appointment)\n\n\tif physician_schedule:\n\t\tfor t in physician_schedule.time_slots:\n\t\t\tif weekday == t.day:\n\t\t\t\tfrom_time=t.from_time\n\t\t\t\tto_time=t.to_time\n\t\t\t\twhile from_time0:\n\t\tconsult=frappe.get_doc(\"Consultation\",consultant_data[0].name)\n\t\tline_item={}\n\t\tline_item[\"item_code\"]=frappe.db.get_value(\"Clinic Settings\",\"Clinic Settings\",\"consultant_item\")\n\t\tline_item[\"qty\"]=1\n\t\tline_item[\"consultation\"]=consultant_data[0].name\n\t\top_consulting_charge = frappe.db.get_value(\"Doctor\",consult.physician, \"op_consulting_charge\")\n\t\tcost_center = frappe.db.get_value(\"Doctor\",consult.physician, \"cost_center\")\n\t\tif op_consulting_charge:\n\t\t\tline_item[\"rate\"] = op_consulting_charge\n\t\tif cost_center:\n\t\t\tline_item[\"cost_center\"]=cost_center\n\t\titems.append(line_item)\n\n\ttreatment_data=frappe.get_all(\"Client Treatment\",filters=[(\"Client Treatment\",\"appointment\",\"=\",appointment),(\"Client Treatment\",\"status\",\"in\",[\"Pending\",\"Completed\"]),(\"Client Treatment\",\"is_bill\",\"!=\",1)],fields=[\"name\"])\n\tif len(treatment_data)>0:\n\t\tfor row in treatment_data:\n\t\t\ttreatment=frappe.get_doc(\"Client Treatment\",row.name)\n\t\t\tline_item={}\n\t\t\tline_item[\"item_code\"]=treatment.treatment\n\t\t\tline_item[\"qty\"]=treatment.qty\n\t\t\tline_item[\"treatment\"]=row.name\n\t\t\tcost_center = frappe.db.get_value(\"Doctor\",treatment.doctor, \"cost_center\")\n\t\t\tif cost_center:\n\t\t\t\tline_item[\"cost_center\"]=cost_center\n\n\t\t\titems.append(line_item)\n\treturn items\n\n\n\n#custom:use to make invoice\n@frappe.whitelist()\ndef create_invoice(company, physician, patient, appointment_id, appointment_date):\n\tif not appointment_id:\n\t\treturn False\n\n\t#item_obj=getItemArray(company,physician,patient,appointment_id,appointment_date)\n\titem_object=getItemForInvoice(appointment_id)\n\tif len(item_object)>0:\n\t\tsales_invoice=frappe.get_doc(dict(\n\t\t\tdoctype=\"Sales Invoice\",\n\t\t\tcustomer=patient,\n\t\t\tdue_date=getdate(),\n\t\t\tappointment=appointment_id,\n\t\t\titems=item_object\n\t\t)).insert()\n\t\treturn sales_invoice.name\n\telse:\n\t\treturn False\t\n\ndef getItems(item_obj):\n\titems=[]\n\tcounter=0\n\tobj=json.loads(item_obj)\n\twhile counter []')\n sys.exit(1)\nelif len(sys.argv) == 2:\n sys.argv.append('./traces')\ntraces = os.listdir(sys.argv[2])\ntraces.sort()\n\nfor tr in traces:\n print('running: ' + tr + '...')\n cmd = './' + sys.argv[1] + '/cvp'\n opt = '-F 16,0,0,0,0 -f 5 -M 0 -A 0 -w 256 -v ' + sys.argv[2] + '/' + tr\n output = subprocess.Popen(cmd + ' ' + opt, shell=True, stdout=subprocess.PIPE).stdout.read()\n cur_ipc = float(output.decode('utf-8').split('\\n')[-7].split('=')[1].strip())\n correct_per = float(output.decode('utf-8').split('\\n')[-4].split('(')[-1].split(')')[0][:-1])\n incorrect_per = float(output.decode('utf-8').split('\\n')[-3].split('(')[-1].split(')')[0][:-1])\n with open('results_' + sys.argv[1] + '_' + sys.argv[2].split('/')[-1], 'a+') as f:\n f.write(tr + ',' + str(cur_ipc) + ',' + str(correct_per) + ',' + str(incorrect_per) + '\\n')\n ipc, trace_cnt = ipc * cur_ipc, trace_cnt + 1\n\nprint(ipc ** (1.0 / trace_cnt))\n","sub_path":"get_ipc.py","file_name":"get_ipc.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"38474257","text":"# ---------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# ---------------------------------------------------------\n\n# pylint: disable=arguments-renamed\n\nimport logging\nfrom typing import Optional\n\nfrom azure.ai.ml._restclient.v2022_05_01.models import ContainerResourceSettings\nfrom azure.ai.ml.entities._mixins import RestTranslatableMixin\n\nmodule_logger = logging.getLogger(__name__)\n\n\nclass ResourceSettings(RestTranslatableMixin):\n def __init__(self, cpu: Optional[str] = None, memory: Optional[str] = None, gpu: Optional[str] = None):\n self.cpu = cpu\n self.memory = memory\n self.gpu = gpu\n\n def _to_rest_object(self) -> ContainerResourceSettings:\n return ContainerResourceSettings(cpu=self.cpu, memory=self.memory, gpu=self.gpu)\n\n @classmethod\n def _from_rest_object(cls, settings: ContainerResourceSettings) -> \"ResourceSettings\":\n return (\n ResourceSettings(\n cpu=settings.cpu,\n memory=settings.memory,\n gpu=settings.gpu,\n )\n if settings\n else None\n )\n\n def _merge_with(self, other: \"ResourceSettings\") -> None:\n if other:\n self.cpu = other.cpu or self.cpu\n self.memory = other.memory or self.memory\n self.gpu = other.gpu or self.gpu\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, ResourceSettings):\n return NotImplemented\n if not other:\n return False\n # only compare mutable fields\n return self.cpu == other.cpu and self.memory == other.memory and self.gpu == other.gpu\n\n def __ne__(self, other: object) -> bool:\n return not self.__eq__(other)\n","sub_path":"sdk/ml/azure-ai-ml/azure/ai/ml/entities/_deployment/container_resource_settings.py","file_name":"container_resource_settings.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"405665309","text":"# This file is a part of pyctr.\n#\n# Copyright (c) 2017-2021 Ian Burgwin\n# This file is licensed under The MIT License (MIT).\n# You can find the full license text in LICENSE in the root of this project.\n\nfrom os import PathLike\nfrom threading import Lock\nfrom typing import TYPE_CHECKING\n\nfrom ..common import PyCTRError\nfrom ..crypto import CryptoEngine\nfrom ..util import readle\nfrom .base.typereader import TypeReaderCryptoBase\n\nif TYPE_CHECKING:\n from typing import BinaryIO, Union\n\nNAND_MEDIA_UNIT = 0x200\n\n\nclass NANDError(PyCTRError):\n \"\"\"Generic error for NAND operations.\"\"\"\n\n\nclass InvalidNANDError(NANDError):\n \"\"\"Invalid NAND header exception.\"\"\"\n\n\nclass NAND(TypeReaderCryptoBase):\n def __init__(self, file: 'Union[PathLike, str, bytes, BinaryIO]', *, closefd: bool = True,\n crypto: CryptoEngine = None, dev: bool = False, otp: bytes = None,\n otp_file: 'Union[PathLike, str, bytes]' = None):\n super().__init__(file=file, closefd=closefd, crypto=crypto, dev=dev)\n\n self._lock = Lock()\n\n # set up otp if it was provided\n # otherwise it has to be in essential.exefs or set up manually with a custom CryptoEngine object\n if otp:\n self._crypto.setup_keys_from_otp(otp)\n elif otp_file:\n self._crypto.setup_keys_from_otp_file(otp_file)\n\n # ignore the signature, we don't need it\n self._file.seek(0x100, 1)\n header = self._file.read(0x100)\n if header[0:4] != b'NCSD':\n raise InvalidNANDError('NCSD magic not found')\n\n # make sure the Media ID is all zeros, since anything else makes it a CCI\n media_id = header[0x8:0x10]\n if media_id != b'\\0' * 8:\n raise InvalidNANDError('Not a NAND, this is a CCI')\n","sub_path":"pyctr/type/nand.py","file_name":"nand.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"136559049","text":"from logging import Formatter, getLogger, StreamHandler, DEBUG\nlogger = getLogger(__name__)\nhandler = StreamHandler()\nhandler.setLevel(DEBUG)\nhandler.setFormatter(Formatter(\"%(asctime)s- %(name)s - %(levelname)s - %(message)s\"))\nlogger.setLevel(DEBUG)\nlogger.addHandler(handler)\n\nimport json\nimport requests\nfrom collections import OrderedDict\n\nclass ImportHandler(object):\n\n _diff_exclude_keys = [\"id\", \"created_at\", \"updated_at\"]\n\n def __init__(self, model, contents):\n self.model = model\n self.model_name = model._meta.model_name\n self.model_fields = [field.name for field in model._meta.fields]\n try:\n self.unique_keys = model._meta.unique_together[0]\n except IndexError:\n self.unique_keys = [x for x in self.model_fields if x not in self._diff_exclude_keys]\n self.contents = [requests.structures.CaseInsensitiveDict(content) for content in contents]\n\n\n def update(self, expired=False):\n pre_all_content_ids = [ d[\"id\"] for d in self.model.objects.all().values(\"id\") ]\n updated_content_ids = list()\n\n for content in self.contents:\n new = self.model(**self._clean(content, cleaning=True))\n\n condition = { key: content[key] for key in self.unique_keys }\n query = self.model.objects.filter(**condition)\n\n if query.exists():\n old = query.get()\n self._update_content(old=old, new=new, dry=False)\n updated_content_ids.append(old.id)\n else:\n new.save()\n\n if expired:\n will_be_deleted_ids = set(pre_all_content_ids) - set(updated_content_ids)\n for id in will_be_deleted_ids:\n self.model.objects.get(id=id).delete()\n\n\n def _clean(self, content, cleaning=True):\n if cleaning:\n cleaned_content = dict()\n for field_name in self.model_fields:\n try:\n cleaned_content[field_name] = content[field_name]\n except KeyError:\n pass\n return cleaned_content\n else:\n return content\n\n\n def _update_content(self, old, new, dry=True):\n has_diff = False\n for field_name in [x for x in self.model_fields if x not in self._diff_exclude_keys]:\n val_old = str(getattr(old, field_name))\n val_new = str(getattr(new, field_name))\n if val_old != val_new:\n has_diff = True\n d = OrderedDict()\n d[\"model\"] = self.model_name\n d[\"id\"] = old.id\n d[\"unique_keys\"] = dict()\n for unique_key in self.unique_keys:\n d[\"unique_keys\"][unique_key] = getattr(old, unique_key)\n d[\"field_name\"] = field_name\n d[\"old\"] = val_old\n d[\"new\"] = val_new\n logger.info(\"[Diff] {0}\".format(json.dumps(d, ensure_ascii=False)))\n if not dry:\n setattr(old, field_name, val_new)\n if not dry:\n old.save()\n return has_diff\n","sub_path":"import_handler.py","file_name":"import_handler.py","file_ext":"py","file_size_in_byte":3117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"325629768","text":"#!/usr/bin/env python3\n\ndef main():\n run_account_menu_tests()\n get_all_service_test()\n\n\ndef get_all_service_test():\n assert (get_all_service((0, \"Fail\")) == 0), \"Should print Fail and return 0\"\n assert (get_all_service((1, {\n \"account\": 1,\n \"firstname\": \"Ryan\",\n \"lastname\": \"Kuan\",\n \"balance\": \"580.00\",\n \"transactions\": [\n [\n \"Deposit\",\n \"580.00\"\n ]\n ]\n })) == 1), \"Should print account information and return 1\"\n\n\ndef get_all_service(set_reply):\n reply = set_reply\n flag = reply[0]\n answer = reply[1]\n\n if flag == 0:\n print(answer)\n return 0\n\n account = answer\n for key in account:\n if key == \"Balance\":\n print(\"Balance: ${}\".format(account[key]))\n elif key == \"Transactions\":\n if not account[key]:\n print(\"No transactions have been made yet\")\n for t in account[key]:\n print(\"{}: ${}\".format(t[0], t[1]))\n else:\n print(\"{}: {}\".format(key, account[key]))\n return 1\n\n\ndef run_account_menu_tests():\n assert (parse_account_menu(\"l\") == 0), \"Should return 0\"\n assert (parse_account_menu(\"deposit\") == 1), \"Should return 1\"\n assert (parse_account_menu(\"withdraw\") == 2), \"Should return 2\"\n assert (parse_account_menu(\"balance\") == 3), \"Should return 3\"\n assert (parse_account_menu(\"4\") == 4), \"Should return 4\"\n assert (parse_account_menu(\"5\") == 5), \"Should return 5\"\n assert (parse_account_menu(\"login\") == 999), \"Should return 999\"\n assert (parse_account_menu(53215) == 999), \"Should return 999\"\n assert (parse_account_menu(\"2\") == 2), \"Should return 2\"\n\n\ndef parse_account_menu(action):\n if action == \"logout\" or action == \"0\" or action == \"l\":\n print(\"\\nLogging out\")\n return 0\n elif action == \"deposit\" or action == \"1\" or action == \"d\":\n print(\"\\nDepositing\")\n return 1\n elif action == \"withdraw\" or action == \"2\" or action == \"w\":\n print(\"\\nWithdrawing\")\n return 2\n elif action == \"balance\" or action == \"3\" or action == \"b\":\n print(\"\\nViewing balance\")\n return 3\n elif action == \"transactions\" or action == \"4\" or action == \"t\":\n print(\"\\nViewing transactions history\")\n return 4\n elif action == \"full\" or action == \"5\" or action == \"f\":\n print(\"\\nViewing full account details\")\n return 5\n else:\n print(\"\\nInput was not recognized.\")\n return 999\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/test/python/com/revature/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"259353303","text":"# Name: start_FrTM.py\n# Language: python3\n# Libraries: multiprocessing, subprocess, os, sys, re\n# Description: Starts or restarts parallelized Fr-TM-Align jobs\n# Author: Edoardo Sarti\n# Date: Aug 08 2016\n\nimport os, sys, multiprocessing, subprocess, re, time\n\ndef FrTMjob(data):\n\tntm, maindir, checkpoint = data\n\tif not os.path.exists(maindir + '/' + ntm + '/alignments'):\n\t\tos.mkdir(maindir + '/' + ntm + '/alignments')\n\tif not os.path.exists(maindir + '/' + ntm + '/alignments/fasta'):\n\t\tos.mkdir(maindir + '/' + ntm + '/alignments/fasta')\n\tif not os.path.exists(maindir + '/' + ntm + '/alignments/str_alns'):\n\t\tos.mkdir(maindir + '/' + ntm + '/alignments/str_alns')\n\tif not os.path.exists(maindir + '/' + ntm + '/structures'):\n\t\traise NameError(\"ERROR: The folder {0} is badly formatted and does not contain a structures/ subfolder.\\n\".format(maindir + '/' + ntm + '/') +\n\t\t \" Please create one and fill it with all and only the appropriate pdb chains.\")\n\tif os.path.exists(maindir + '/' + ntm + '/struct_codes.dat'):\n\t\tstructcodesfile = open(maindir + '/' + ntm + '/struct_codes.dat', 'r')\n\t\ttext = structcodesfile.read().split('\\n')\n\t\tname2code = {}\n\t\tcode2name = {}\n\t\tfor line in text:\n\t\t\tfields = line.split()\n\t\t\tif len(fields) == 0:\n\t\t\t\tcontinue\n\t\t\tname2code[fields[1]] = [x for x in fields[0].split('.')]\n\t\t\tcode2name[fields[0].split('.')[1]] = fields[1]\n\telse:\n\t\traise NameError(\"ERROR: The folder {0} is badly formatted and does not contain a struct_codes.dat file.\\n\".format(maindir + '/' + ntm) +\n\t\t \" Please generate it. It must contain all and only the names of the pdb chains in the structures/ subfolder\"+\n\t\t \" and each name must be associated with the correct structure code SC.\\n\" +\n\t\t \" The format must be: \\\\t\\\\t\")\n\tfor chain in name2code.keys():\n\t\tif not os.path.exists(maindir + '/' + ntm + '/structures/' + chain + '.pdb'):\n\t\t\traise NameError(\"ERROR: The file {0} corresponding to Structure Code {1}\".format(chain + '.pdb', name2code[chain]) +\n\t\t\t \" was not found in the structures/ subfolder.\")\n\tfor struct in os.listdir(maindir + '/' + ntm + '/structures/'):\n\t\tif not struct[:6] in name2code:\n\t\t\traise NameError(\"ERROR: The file {0} found in the structures/\".format(struct) +\n\t\t\t \" subfolder is not present in the struct_code.dat file.\")\n\tif len(os.listdir(maindir + '/' + ntm + '/structures/')) < 2:\n\t\treturn\n\n\tfor chain_1 in [code2name[x] for x in sorted(code2name.keys())]:\n#\t\tfile_1 = maindir + '/' + ntm + '/structures/' + chain_1 + '.pdb'\n\t\tfile_1 = chain_1 + '.pdb'\n\t\tif not os.path.exists(maindir + '/' + ntm + '/alignments/str_alns/tmp_' + name2code[chain_1][1] + '/'):\n\t\t\tos.mkdir(maindir + '/' + ntm + '/alignments/str_alns/tmp_' + name2code[chain_1][1] + '/')\n\t\tif not os.path.exists(maindir + '/' + ntm + '/alignments/fasta/tmp_' + name2code[chain_1][1] + '/'):\n\t\t\tos.mkdir(maindir + '/' + ntm + '/alignments/fasta/tmp_' + name2code[chain_1][1] + '/')\n\t\tfor chain_2 in [code2name[x] for x in sorted(code2name.keys())]:\n\t\t\tif chain_1 == chain_2:\n\t\t\t\tcontinue\n\t\t\tprint(\"#td \"+ntm+\"\\t\\tchain_1 \"+chain_1+\"\\t\\tchain_2 \"+chain_2)\n#\t\t\tfile_2 = maindir + '/' + ntm + '/structures/' + chain_2 + '.pdb'\n\t\t\tfile_2 = chain_2 + '.pdb'\n#\t\t\tFTA_str_output = maindir + '/' + ntm + '/alignments/str_alns/tmp_' + chain_1 + '/' + chain_1 + '_' + chain_2 + '.tmp'\n\t\t\tFTA_str_output = name2code[chain_1][1] + '_' + name2code[chain_2][1] + '.tmp'\n\t\t\tFTA_seq_output = maindir + '/' + ntm + '/alignments/fasta/tmp_' + name2code[chain_1][1] + '/' + name2code[chain_1][1] + '_' + name2code[chain_2][1] + '.tmp'\n\n\t\t\tFTA_stdout_file = open(maindir + '/' + ntm + '/alignments/fasta/tmp_' + name2code[chain_1][1] + '/aln_' + name2code[chain_1][1] + '_' + name2code[chain_2][1] + '.tmp', 'w')\n\t\t\tfnull = open(os.devnull, 'w')\n\t\t\tp = subprocess.Popen(['/v/apps/csb/frtmalign/frtmalign.exe', file_1, file_2, '-o', FTA_str_output], stdout=FTA_stdout_file, stderr=fnull, cwd=maindir+'/'+ntm+'/structures/')\n\t\t\tfnull.close()\n\t\t\tp.wait()\n\t\t\tFTA_stdout_file.close()\n\t\t\tos.rename(maindir + '/' + ntm + '/structures/' + FTA_str_output, maindir + '/' + ntm + '/alignments/str_alns/tmp_' + name2code[chain_1][1] + '/' + FTA_str_output)\n\n\t\t\tFTA_stdout_file = open(maindir + '/' + ntm + '/alignments/fasta/tmp_' + name2code[chain_1][1] + '/aln_' + name2code[chain_1][1] + '_' + name2code[chain_2][1] + '.tmp', 'r')\n\t\t\ttext = FTA_stdout_file.read().split('\\n')\n\t\t\tFTA_stdout_file.close()\n\t\t\tos.remove(maindir + '/' + ntm + '/alignments/fasta/tmp_' + name2code[chain_1][1] + '/aln_' + name2code[chain_1][1] + '_' + name2code[chain_2][1] + '.tmp')\n\t\t\tchkaln = -1000\n\t\t\tfor nl in range(len(text)):\n\t\t\t\tif \"Aligned length\" in text[nl]:\n\t\t\t\t\tfields = re.split('=|,|\\s',text[nl])\n\t\t\t\t\tfields = list(filter(None, fields))\n#\t\t\t\t\tprint(fields)\n\t\t\t\t\tRMSD = float(fields[4])\n\t\t\t\t\tTMscore = float(fields[6])\n\t\t\t\telif chkaln+1 == nl:\n\t\t\t\t\tseq_1 = text[nl]\n\t\t\t\telif chkaln+3 == nl:\n\t\t\t\t\tseq_2 = text[nl]\n\t\t\t\telif \"denotes the residue pairs of distance\" in text[nl]:\n\t\t\t\t\tchkaln = nl\n\t\t\ttmpseq_file = open(FTA_seq_output, 'w')\n\t\t\ttmpseq_file.write(\">\" + chain_1 + \"\\n\" + seq_1.replace('\\x00', '') + \"\\n>\" + chain_2 + \"\\n\" + seq_2.replace('\\x00', '') + \"\\n\\nRMSD\\t{0:.2f}\\nTM-score\\t{1:.5f}\\n\\n\".format(RMSD, TMscore))\n\t\t\ttmpseq_file.close()\n\n\t\tstr_file = open(maindir + '/' + ntm + '/alignments/str_alns/str_' + chain_1 + '.dat', 'w')\n\t\tfor tmp_filename in sorted(os.listdir(maindir + '/' + ntm + '/alignments/str_alns/tmp_' + name2code[chain_1][1] + '/')):\n\t\t\tchain_2_code = re.split('_|\\.', tmp_filename)[-2]\n#\t\t\tprint(chain_1, \"chain_2_code \"+chain_2_code, \"tmp_filename \"+tmp_filename, name2code)\n\t\t\tstr_file.write(\"BEGIN \\nCHAIN_1: \" + chain_1 + \"\\nCHAIN_2: \" + code2name[chain_2_code] +\n\t\t\t \"\\nSequence Alignment Code (SAC): \" + name2code[chain_1][0] + \n\t\t\t \".\" + name2code[chain_1][1] + \".\" + chain_2_code + \"\\n\")\n\t\t\ttmp_file = open(maindir + '/' + ntm + '/alignments/str_alns/tmp_' + name2code[chain_1][1] + '/' + tmp_filename)\n\t\t\ttext = tmp_file.read().split('\\n')\n\t\t\tfor line in text:\n\t\t\t\tstr_file.write(line+'\\n')\n\t\t\tstr_file.write(\"END\\n\\n\\n\")\n\t\t\tos.remove(maindir + '/' + ntm + '/alignments/str_alns/tmp_' + name2code[chain_1][1] + '/' + tmp_filename)\n\t\t\ttmp_file.close()\n\t\ttime.sleep(1)\n\t\tos.rmdir(maindir + '/' + ntm + '/alignments/str_alns/tmp_' + name2code[chain_1][1] + '/')\n\t\tstr_file.close()\n\n\t\tseq_file = open(maindir + '/' + ntm + '/alignments/fasta/seq_' + chain_1 + '.dat', 'w')\n\t\tfor tmp_filename in sorted(os.listdir(maindir + '/' + ntm + '/alignments/fasta/tmp_' + name2code[chain_1][1] + '/')):\n\t\t\tchain_2_code = re.split('_|\\.', tmp_filename)[-2]\n#\t\t\tprint(chain_1, \"chain_2_code \"+chain_2_code, \"tmp_filename \"+tmp_filename, name2code)\n\t\t\tseq_file.write(\"BEGIN \\nCHAIN_1: \" + chain_1 + \"\\nCHAIN_2: \" + code2name[chain_2_code] +\n\t\t\t \"\\nSequence Alignment Code (SAC): \" + name2code[chain_1][0] + \n\t\t\t \".\" + name2code[chain_1][1] + \".\" + chain_2_code + \"\\n\")\n\t\t\tFTA_seq_output = maindir + '/' + ntm + '/alignments/fasta/tmp_' + name2code[chain_1][1] + '/' + name2code[chain_1][1] + '_' + chain_2_code + '.tmp'\n\t\t\ttmp_file = open(FTA_seq_output, 'r')\n\t\t\ttext = tmp_file.read().split('\\n')\n\t\t\tfor line in text:\n\t\t\t\tseq_file.write(line+'\\n')\n\t\t\tseq_file.write(\"END\\n\\n\\n\")\n\t\t\tos.remove(maindir + '/' + ntm + '/alignments/fasta/tmp_' + name2code[chain_1][1] + '/' + tmp_filename)\n\t\t\ttmp_file.close()\n\t\ttime.sleep(5)\n#\t\tprint(os.listdir(maindir + '/' + ntm + '/alignments/fasta/tmp_' + name2code[chain_1][1] + '/'))\n\t\tos.rmdir(maindir + '/' + ntm + '/alignments/fasta/tmp_' + name2code[chain_1][1] + '/')\n\t\tseq_file.close()\n\n\nif len(sys.argv) < 2:\n raise NameError(\"Usage: start_FrTM.py [{}]\")\nmaindir = sys.argv[1]\nif not os.path.exists(maindir):\n\traise NameError(\"ERROR: Directory {0} does not exists.\".format(maindir))\n\nnsubdirs = len(sys.argv) - 2\nif nsubdirs > 0:\n\tsubdirs = []\n\tfor i in range(0, nsubdirs):\n\t\tsubdirs.append(int(sys.argv[2+i]))\nelse:\n\tsubdirs = []\n\tfor i in os.listdir(str(sys.argv[1])):\n\t\tif re.match('^\\d*$', str(i)) and os.path.exists(maindir + '/' + str(i) + '/struct_codes.dat'):\n\t\t\tsubdirs.append(int(i))\n\nsuperfamilies = [(str(i), maindir+'/', 0) for i in sorted(subdirs)]\n#print(superfamilies)\n\n#for sf in superfamilies:\n#\tFrTMjob(sf)\n\n\n#exit(1)\n\npool = multiprocessing.Pool(processes=4)\npool_outputs = pool.map(FrTMjob, superfamilies)\n","sub_path":"old/start_FrTM.py","file_name":"start_FrTM.py","file_ext":"py","file_size_in_byte":8541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"233973576","text":"from d2l import AllDeepLearning as d2l\nfrom mxnet import autograd, gluon, nd\nfrom mxnet import nd as np\nfrom mxnet.gluon import nn\nimport mxnet as mx\nimport sys\nfrom AI.AILearning.RecommenderSystems import MovieLens as loader\nfrom AI.AILearning.RecommenderSystems import MatrixFactorization as train_helper\n\n\n\"\"\"\n/////////// AutoRECT /////////////////// In AutoRec, instead of explicitly embedding \n users/items into low-dimensional space, it uses the column/row of the interaction matrix as the input, \n then reconstructs the interaction matrix in the output layer. h(R∗i)=f(W⋅g(VR∗i+μ)+b) Mini: arg_minW,V,μ,\n b∑i=1M∥R∗i−h(R∗i)∥2O+λ(∥W∥2F+∥V∥2F) /////////////////////// MODEL \n////////////////////////// \n A typical autoencoder consists of an encoder and a decoder. The encoder projects the input \n to hidden representations and the decoder maps the hidden layer to the reconstruction layer.\n \n\"\"\"\n\n\nclass AutoRec(nn.Block):\n def __init__(self, num_hidden, num_users, dropout_rate=0.05):\n super(AutoRec, self).__init__()\n self.encoder = gluon.nn.Dense(num_hidden, activation='sigmoid',\n use_bias=True)\n self.decoder = gluon.nn.Dense(num_users, use_bias=True)\n self.dropout_layer = gluon.nn.Dropout(dropout_rate)\n\n def forward(self, inputs):\n hidden = self.dropout_layer(self.encoder(inputs))\n pred = self.decoder(hidden)\n if autograd.is_training():\n return pred * nd.sign(inputs)\n else:\n return pred\n\n\ndef evaluator(net, inter_matrix, test_data, ctx):\n scores = []\n for values in inter_matrix:\n feat = gluon.utils.split_and_load(values, ctx, even_split=False)\n scores.extend([net(i).asnumpy() for i in feat])\n recons = nd.array([item for sublist in scores for item in sublist])\n rmse = nd.sqrt(nd.sum(nd.square(test_data - nd.sign(test_data) * recons)) /\n nd.sum(nd.sign(test_data)))\n return float(rmse.asscalar())\n\n\nctx = d2l.try_all_gpus()\ndf, num_users, num_items = loader.read_data_ml100k()\ntrain_data, test_data = loader.split_data_ml100k(df, num_users, num_items)\n_, _, _, train_inter_mat = loader.load_data_ml100k(train_data, num_users, num_items)\n_, _, _, test_inter_mat = loader.load_data_ml100k(test_data, num_users, num_items)\nnum_workers = 0 if sys.platform.startswith('win') else 4\ntrain_iter = gluon.data.DataLoader(train_inter_mat, shuffle=True,\n last_batch='rollover', batch_size=256,\n num_workers=num_workers)\ntest_iter = gluon.data.DataLoader(nd.array(train_inter_mat), shuffle=False,\n last_batch='keep', batch_size=1024,\n num_workers=num_workers)\nfor values in train_iter:\n print(values)\n break\n\nnet = AutoRec(500, num_users)\nnet.initialize(ctx=ctx, force_reinit=True,\n init=mx.init.Normal(0.01))\nlr, num_epochs, wd, optimizer = 0.002, 25, 1e-5, 'adam'\nloss = gluon.loss.L2Loss()\ntrainer = gluon.Trainer(net.collect_params(), optimizer, {'learning_rate': lr, 'wd': wd})\ntrain_helper.train_recsys_rating(net, train_iter, test_iter, loss, trainer,\n num_epochs, ctx, evaluator, inter_mat=test_inter_mat)\nd2l.plt.show()\n\n\"\"\" ///////////// SUMMARY ////////////////////////\n We can frame the matrix factorization algorithm with autoencoders,\n while integrating non-linear layers and dropout regularization.\n\n Experiments on the MovieLens 100K dataset show that AutoRec achieves superior performance than matrix factorization.\n\"\"\"\n","sub_path":"AILearning/RecommenderSystems/AutoRecAutoencoders.py","file_name":"AutoRecAutoencoders.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"513860005","text":"import os\r\nfrom glob import glob\r\nfrom PIL import Image\r\nimport numpy as np\r\nimport random\r\nfrom tqdm import tqdm\r\nimport torch\r\nimport torchvision.transforms.functional as TF\r\nimport random\r\nimport torchvision.transforms as transforms\r\nfrom torch.utils.data import Dataset, DataLoader\r\nimport torch.nn as nn\r\nimport copy\r\nimport torch.nn.functional as F\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.style as style\r\nfrom torch.utils.tensorboard import SummaryWriter\r\nimport time\r\n\r\n\r\nclass Prostate_data(Dataset):\r\n\r\n def __init__(self, img_path='../harvard_data/TMA_Images', mask_path='../harvard_data/Gleason_masks_train',\r\n dataset_type='train', img_size=3100, valid_split=['ZT76'], test_split=['ZT80'], num_classes=5):\r\n self.img_path = img_path\r\n self.mask_path = mask_path\r\n self.img_size = img_size\r\n self.num_classes = num_classes\r\n self.file_names = []\r\n self.dataset_type = dataset_type\r\n slide_dict = {'valid': valid_split, 'test': test_split}\r\n self.flag_dict = {}\r\n for file in glob(self.img_path + '/*.jpg'):\r\n _file_name = file.split('\\\\')[-1]\r\n _slide_type = _file_name.split('.')[0].split('_')[0]\r\n if dataset_type == 'train':\r\n if not (_slide_type in valid_split) and not (_slide_type in test_split):\r\n for fname in self.all_files(_file_name):\r\n self.file_names.append(fname)\r\n self.flag_dict[fname] = False\r\n else:\r\n if _slide_type in slide_dict[dataset_type]:\r\n self.file_names.append(_file_name)\r\n self.flag_dict[_file_name] = False\r\n random.seed(10)\r\n random.shuffle(self.file_names)\r\n self.data = {}\r\n self.transform = {\r\n 'train': transforms.Compose([transforms.ColorJitter(0.2,0.2,0.2,0.2),transforms.ToTensor(),\r\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]),\r\n 'valid': transforms.Compose([transforms.ToTensor(),\r\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])\r\n }\r\n\r\n def __len__(self):\r\n return len(self.file_names)\r\n\r\n def all_files(self,_file_name):\r\n return [_file_name,_file_name+'_tranhor',_file_name+'_tranver']\r\n\r\n def __getitem__(self, idx):\r\n _file_name = self.file_names[idx]\r\n _file_flag = self.flag_dict[_file_name]\r\n if _file_flag:\r\n return self.data[_file_name]\r\n else:\r\n img_path = self.img_path+'/'+_file_name.split('_tran')[0] if '_tran' in _file_name else self.img_path + '/' + _file_name\r\n mask_path = self.mask_path + '/' + 'mask_' + _file_name.split('_tran')[0].split('.')[0] + '.png' if '_tran' in _file_name else self.mask_path + '/' + 'mask_' + _file_name.split('.')[0] + '.png'\r\n\r\n img = Image.open(img_path).resize((self.img_size, self.img_size)).convert('RGB')\r\n mask = Image.open(mask_path).resize((self.img_size, self.img_size)).convert('RGB')\r\n ## transforms\r\n if 'hor' in _file_name:\r\n img = TF.hflip(img)\r\n mask = TF.hflip(mask)\r\n if 'ver' in _file_name:\r\n img = TF.vflip(img)\r\n mask = TF.vflip(mask)\r\n if 'aff' in _file_name:\r\n img = TF.affine(img,20,(0,0),1.35,0)\r\n mask = TF.affine(mask,20,(0,0),1.35,0)\r\n\r\n mask_array = np.asarray(mask)\r\n oneh_mask = np.zeros((self.num_classes, self.img_size, self.img_size))\r\n for x in range(self.img_size):\r\n for y in range(self.img_size):\r\n pixel_class = self.get_class(mask_array[x, y,:])\r\n oneh_mask[pixel_class, x, y] = 1\r\n\r\n array_img = np.asarray(img)\r\n timg = copy.deepcopy(array_img)\r\n for x in range(self.img_size):\r\n for y in range(self.img_size):\r\n rgb_n = array_img[x, y, :] / 255.0\r\n if rgb_n[0] > 0.8 and rgb_n[1] > 0.8 and rgb_n[2] > 0.8:\r\n timg[x, y, :] = [0, 0, 0]\r\n final_img = Image.fromarray(timg.astype('uint8'), 'RGB')\r\n\r\n img_tensor = self.transform[self.dataset_type](final_img)\r\n mask_tensor = torch.from_numpy(oneh_mask).view(self.num_classes, self.img_size, self.img_size)\r\n self.data[_file_name] = (img_tensor, mask_tensor)\r\n self.flag_dict[_file_name] = True\r\n return self.data[_file_name]\r\n\r\n def get_class(self, rgb):\r\n '''\r\n takes in rgb values of the pixel and returns the class of the pixel\r\n '''\r\n rgb_n = rgb / 255.0\r\n\r\n # white\r\n if rgb_n[0] > 0.8 and rgb_n[1] > 0.8 and rgb_n[2] > 0.8:\r\n return 4\r\n # red\r\n elif rgb_n[0] > 0.8 and rgb_n[1] < 0.8 and rgb_n[2] < 0.8:\r\n return 3\r\n # yellow\r\n elif rgb_n[0] > 0.8 and rgb_n[1] > 0.8 and rgb_n[2] < 0.8:\r\n return 2\r\n # green\r\n elif rgb_n[0] < 0.8 and rgb_n[1] > 0.8 and rgb_n[2] < 0.8:\r\n return 0\r\n # blue\r\n elif rgb_n[0] < 0.8 and rgb_n[1] < 0.8 and rgb_n[2] > 0.8:\r\n return 1\r\n else:\r\n print(rgb_n)\r\n raise ValueError('Weird rgb combination! Did not match any of 5 classes.')\r\n\r\ndef soft_dice_loss(y_pred,y_true):\r\n '''y_pred: (-1,5,512,512) :predictions\r\n y_true: (512,512,5) : targets\r\n compute the soft dice loss\r\n\r\n '''\r\n y_true = y_true.view(-1,5,256,256)\r\n epsilon = 1e-7\r\n dice_numerator = epsilon + 2 * torch.sum(y_true*y_pred,axis=(2,3))\r\n dice_denominator = epsilon + torch.sum(y_true*y_true,axis=(2,3)) + torch.sum(y_pred*y_pred,axis=(2,3))\r\n dice_loss = 1 - torch.mean(dice_numerator/dice_denominator)\r\n\r\n return dice_loss\r\n\r\n\r\ndef show_train_predictions(model,trainset,device,idx_list):\r\n fig,axes = plt.subplots(nrows=len(idx_list),ncols=3,figsize=(15,15))\r\n for i in range(len(idx_list)):\r\n idx = idx_list[i]\r\n input_img = Image.fromarray(np.asarray(trainset[idx][0].view(trainset.img_size,trainset.img_size,3).squeeze()).astype('uint8'), 'RGB')\r\n target_img = get_rgb(trainset[idx][1].squeeze())\r\n with torch.no_grad():\r\n pred_img = get_rgb(model(trainset[idx][0].view(-1,3,trainset.img_size,trainset.img_size).float().to(device)).squeeze())\r\n if len(idx_list)>1:\r\n axes[i,0].imshow(input_img)\r\n axes[i,1].imshow(pred_img)\r\n axes[i,2].imshow(target_img)\r\n else:\r\n axes[0].imshow(input_img)\r\n axes[1].imshow(pred_img)\r\n axes[2].imshow(target_img)\r\n if len(idx_list)>1:\r\n axes[0,0].set_title('T Input')\r\n axes[0,1].set_title('T Prediction')\r\n axes[0,2].set_title('T Target')\r\n else:\r\n axes[0].set_title('T Input')\r\n axes[1].set_title('T Prediction')\r\n axes[2].set_title('T Target')\r\n\r\n return fig\r\n\r\ndef show_valid_predictions(model,validset,device,idx_list):\r\n fig,axes = plt.subplots(nrows=len(idx_list),ncols=3,figsize=(15,15))\r\n for i in range(len(idx_list)):\r\n idx = idx_list[i]\r\n input_img = Image.fromarray(np.asarray(validset[idx][0].view(validset.img_size,validset.img_size,3).squeeze()).astype('uint8'), 'RGB')\r\n target_img = get_rgb(validset[idx][1].squeeze())\r\n with torch.no_grad():\r\n pred_img = get_rgb(model(validset[idx][0].view(-1,3,validset.img_size,validset.img_size).float().to(device)).squeeze())\r\n if len(idx_list)>1:\r\n axes[i,0].imshow(input_img)\r\n axes[i,1].imshow(pred_img)\r\n axes[i,2].imshow(target_img)\r\n else:\r\n axes[0].imshow(input_img)\r\n axes[1].imshow(pred_img)\r\n axes[2].imshow(target_img)\r\n if len(idx_list)>1:\r\n axes[0,0].set_title('V Input')\r\n axes[0,1].set_title('V Prediction')\r\n axes[0,2].set_title('V Target')\r\n else:\r\n axes[0].set_title('V Input')\r\n axes[1].set_title('V Prediction')\r\n axes[2].set_title('V Target')\r\n\r\n return fig\r\n\r\ndef get_rgb(tensor_img):\r\n pallete_dict = {\r\n 0 : [0,255,0],\r\n 1 : [0,0,255],\r\n 2 : [255,255,255],\r\n 3 : [255,0,0],\r\n 4 : [255,255,0]\r\n }\r\n img_h = tensor_img.size()[2]\r\n out_img = np.zeros((img_h,img_h,3))\r\n for h in range(img_h):\r\n for w in range(img_h):\r\n pixel_class = torch.argmax(tensor_img[:,h,w]).item()\r\n out_img[h,w,:] = pallete_dict[pixel_class]\r\n final_img = Image.fromarray(out_img.astype('uint8'), 'RGB')\r\n return final_img\r\n\r\nclass Focalloss(nn.Module):\r\n\r\n def __init__(self,gamma=0):\r\n super(Focalloss,self).__init__()\r\n self.gamma = gamma\r\n\r\n def forward(self,outputs,targets_oneh,targets):\r\n soft_outs = F.softmax(outputs,dim=1)\r\n log_soft = F.log_softmax(outputs,dim=1)\r\n weight_loss = torch.pow((1 - soft_outs),self.gamma) * log_soft\r\n loss = 0.4*F.nll_loss(weight_loss,targets) + 0.6*soft_dice_loss(outputs,targets_oneh)\r\n return loss\r\n\r\ndef main():\r\n from learner import Learner\r\n from res_unet_dropout import ResUnet\r\n # lr=3e-5\r\n dprob=0.2\r\n epochs = 8\r\n\r\n trainset = Prostate_data(img_size=256, num_classes=3)\r\n validset = Prostate_data(dataset_type='valid', img_size=256, num_classes=3)\r\n datasets = {'train': trainset, 'valid': validset}\r\n\r\n for lr in [1e-4,5e-4,1e-3,5e-3,1e-2]:\r\n for gamma in [0] :\r\n # fig,axes = plt.subplots(nrows=1,ncols=6,figsize=(24,4))\r\n # imgs = []\r\n # for i in tqdm(range(6)):\r\n # imgs.append(get_rgb(trainset[i][1]))\r\n # for j in range(6):\r\n # axes[j].imshow(imgs[j])\r\n # plt.show()\r\n\r\n model = ResUnet(num_classes=5,dprob=dprob)\r\n criterion = Focalloss(gamma=gamma)\r\n optimizer = torch.optim.SGD(model.parameters(),lr=lr,momentum=0.9)\r\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer,patience=10)\r\n dtime = '0057_1806'\r\n tb_logs = {'path':'logdirs/onevall_trials_aug/respre_SGD_plateau','comment':f'lr={lr}_gamma={gamma}_dprob={dprob}_{dtime}'}\r\n trainer = Learner(datasets,model,criterion,optimizer,scheduler,bs=8,num_workers=4)\r\n try :\r\n trainer.fit(tb_logs=tb_logs,epochs=epochs)\r\n # torch.save(trainer.model,f'logdirs/onevall_trials_aug/respre_SGD_plateau/lr={lr}_gamma={gamma}_dprob={dprob}_{dtime}/{dtime}')\r\n except KeyboardInterrupt:\r\n pass\r\n # torch.save(trainer.model,f'logdirs/onevall_trials_aug/respre_SGD_plateau/lr={lr}_gamma={gamma}_dprob={dprob}_{dtime}/{dtime}')\r\n\r\n\r\nif __name__=='__main__':\r\n main()\r\n","sub_path":"focal_loss.py","file_name":"focal_loss.py","file_ext":"py","file_size_in_byte":11017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"103645234","text":"from PIL import Image, ImageGrab\nimport pyautogui\nfrom time import sleep\nimport mouse\nsleep(5)\nimport time\ntty = True\nwalk = True\nwhile tty:\n img = ImageGrab.grab( (422, 1306, 423, 1307) )\n img.save(\"D:/HTML/aim/screens/food.png\", \"BMP\")\n img = ImageGrab.grab( (319, 1307, 320, 1308) )\n img.save(\"D:/HTML/aim/screens/water.png\", \"BMP\")\n img = ImageGrab.grab( (281, 1385, 282, 1386) )\n img.save(\"D:/HTML/aim/screens/health.png\", \"BMP\")\n # img = ImageGrab.grab( (888, 652, 889, 653) )\n # img.save(\"D:/HTML/aim/screens/waterIcon.png\", \"BMP\")i\n # mouse.move(100, 100, absolute=False, duration=2)\n pyautogui.FAILSAFE = True\n pyautogui.PAUSE = 0.1\n #colorF = list(img.getdata())\n #print(\"\\ncolorFood\", colorF)\n #iprint(pyautogui.position())\n\n # #walk1\n # pyautogui.keyDown(\"w\")\n # sleep(1)\n # pyautogui.keyUp(\"w\")\n # sleep(0.2)\n # pyautogui.keyDown(\"s\")\n # sleep(1)\n # pyautogui.keyUp(\"s\")\n\n # food\n # col = Image.open('D:/HTML/aim/screens/food.png', 'r')\n # colorF = list(col.getdata())\n # print(\"\\ncolorFood\", colorF)\n\n # if colorF != [(249, 249, 249)]:\n # walk = False\n # pyautogui.press(\"Esc\")\n # print(\"FOOD IS RED\")\n # tty = False\n # break\n # else:\n # print(\"FOOD IS OK\")\n\n #walk2\n # pyautogui.keyDown(\"w\")\n # sleep(1)\n # pyautogui.keyUp(\"w\")\n # sleep(0.2)\n # pyautogui.keyDown(\"s\")\n # sleep(1)\n # pyautogui.keyUp(\"s\")\n\n #water\n # col = Image.open('D:/HTML/aim/screens/water.png', 'r')\n # colorW = list(col.getdata())\n # if colorW != [(246, 246, 246)]:\n # pyautogui.press('i')\n # pyautogui.moveTo(286, 858)\n # sleep(0.5)\n # pyautogui.click()\n # water = pyautogui.locateCenterOnScreen('D:/HTML/aim/screens/waterIcon.png')\n # pyautogui.moveTo(water)\n # pyautogui.click(clicks=2, interval=0.1)\n # sleep(5)\n # pyautogui.press('esc')\n # sleep(4)\n # if colorW == [(246, 246, 246)]:\n # print(\"WATER IS OK NOW\")\n # sleep(2)\n # #tty = False\n \n # else:\n # print(\"WATER IS OK\")\n\n #walk3\n # pyautogui.keyDown(\"w\")\n # sleep(1)\n # pyautogui.keyUp(\"w\")\n # sleep(0.2)\n # pyautogui.keyDown(\"s\")\n # sleep(1)\n # pyautogui.keyUp(\"s\")\n\n #health\n col = Image.open('D:/HTML/aim/screens/health.png', 'r')\n colorH = list(col.getdata())\n #print(colorH)\n\n if colorH != [(250, 250, 250)]:\n #print(\"STOP\\n\")\n pyautogui.press(\"Esc\")\n print(\"LOW HEALTH\")\n #break\n tty = False\n else:\n print(\"HEALTH IS OK\")\n","sub_path":"aim.py","file_name":"aim.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"540099648","text":"\"\"\"projekt_webowy URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.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\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nimport hello.views\nimport kalkulator.views\nimport sklep.views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n\n path('hello', hello.views.say_hello),\n path('godzina', hello.views.ktora_godzina),\n path('godzina.html', hello.views.ktora_godzina_html),\n path('info', hello.views.info),\n path('dodawanie', hello.views.dodawanie),\n path('rozmowa', hello.views.rozmowa),\n path('rozmowa_post', hello.views.rozmowa_post),\n\n path('kalkulator', kalkulator.views.oblicz),\n path('produkty', sklep.views.lista_produktow),\n]\n","sub_path":"projekt_webowy/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"307525772","text":"import random\n\ndef mergesort(stuff):\n if len(stuff) > 1:\n right, left = mergesort(stuff[:len(stuff)//2]), mergesort(stuff[len(stuff)//2:])\n a, b, new = 0, 0, []\n while len(new) < len(right)+len(left):\n if a start:\n\t\t\ta_list[i] = a_list[i-1]\n\t\t\ti -= 1\n\t\ta_list[start] = first_element\n\nif __name__ == '__main__':\n\tl = [1, 2, 3, 4]\n\trotate(l, 0, 3, -1)\n\trotate(l, 0, 3, -1)\n\tassert(l == [3, 4, 1, 2])\n\trotate(l, 0, 3, +1)\n\tassert(l == [2, 3, 4, 1])\n\t\n\tl = [1, 2, 3, 4]\n\trotate(l, 0, 2, -1)\n\tassert(l == [2, 3, 1, 4])\n\n\tprint(\"Works!!\")","sub_path":"array/rotate.py","file_name":"rotate.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"624076170","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport time\nfrom measures.models import Humidity, Temp, Volt\nfrom measures.notifications import notify_hum, notify_temp, notify_volt\n\n__author__ = 'magnusknutas'\n\n\nimport logging\nimport sys\nimport argparse\nimport coloredlogs\nfrom database import db_session\n\nlogger = logging.getLogger(__name__)\n\n\ndef run_serial():\n from time import sleep\n import serial\n try:\n ser = serial.Serial(\"/dev/ttyUSB0\", 115200) # Establish the connection on a specific port\n except OSError:\n logger.info(\"No arduino atached retrying in 10 sec\")\n time.sleep(10)\n run_serial()\n counter = 32 # Below 32 everything in ASCII is gibberish\n\n latest_hum = None\n latest_temp = None\n latest_volt = None\n\n while True:\n counter += 1\n ser.write(str(chr(counter))) # Convert the decimal number to ASCII then send it to the Arduino\n line = ser.readline() # Read the newest output from the Arduino\n if line.startswith('Humidity:'):\n data = line.split(':')\n if not latest_hum or latest_hum != data[1].strip():\n latest_hum = data[1].strip()\n logger.info(\"Humidity %s\" % latest_hum + \"%\")\n h = Humidity(latest_hum)\n db_session.add(h)\n db_session.commit()\n notify_hum()\n elif line.startswith('Temperature:'):\n data = line.split(':')\n if not latest_temp or latest_temp != data[1].strip():\n latest_temp = data[1].strip()\n logger.info(\"Temp %s\" % latest_temp + \"°C\")\n t = Temp(latest_temp)\n db_session.add(t)\n db_session.commit()\n notify_temp()\n elif line.startswith('Volt:'):\n data = line.split(':')\n if not latest_volt or latest_volt != data[1].strip():\n latest_volt = data[1].strip()\n logger.info(\"Volt %s\" % latest_volt)\n v = Volt(latest_volt)\n db_session.add(v)\n db_session.commit()\n notify_volt()\n\n sleep(.1) # Delay for one tenth of a second\n\n if counter == 255:\n counter = 32\n\n\ndef init_database():\n from database import init_db\n init_db()\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Hobby KFU 570 project')\n parser.add_argument('command', metavar='C', type=str, nargs='+', help='Command to run')\n parser.add_argument('-l', '--log-level', action='store', type=str, dest='log_level', help='Log level', default='INFO')\n args = parser.parse_args()\n\n numeric_level = getattr(logging, args.log_level.upper(), None)\n if not isinstance(numeric_level, int):\n raise ValueError('Invalid log level: %s' % args.log_level)\n coloredlogs.install(level=numeric_level)\n logger.info('Log level set to %s', args.log_level)\n\n if 'init_db' in args.command:\n logger.info(\"Initiates DB\")\n init_database()\n\n if 'run_serial' in args.command:\n logger.info(\"running serial\")\n run_serial()\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"575836934","text":"\"\"\"Counting letters in a string.\"\"\"\n\n__author__ = \"730232764\"\n\n\n# Begin your solution here...\nwhat_letter: str = input(\"What letter do you want to search for? \")\nword: str = input(\"Enter a word: \")\nposition: int = 0 \ncounter: int = 0\n\nwhile position < len(word):\n if word[position] == what_letter: \n counter = counter + 1 \n position = position + 1 \nprint(\"Count:\", counter) ","sub_path":"exercises/ex02/count_letters.py","file_name":"count_letters.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"69305459","text":"# Pending\r\n# Stories based on gender, age\r\n# BLack magic intensity shuttle...6\r\n# Long Poetry\r\n# Manual command to start a different topic. Or \r\n# Create 60 short stories. Total 20 stories and each story will have a happy, a neutral/sad and a curious version\r\n# Curious version will be used as a filler story to divert to a happy or sad story if user is not responding. or to change topic..\r\n# Each story is an intent type. This is becuase this will help UnivEncoder to match similarity to one story intent only.\r\n# Each story will have an opening intent\r\n# Each story intent will have a timeout intent, which will get triggered when timeout happens.\r\n# Create a structure or bag of keywords which will suggest that we need to switch stories now as \r\n# conversation is moving in a different direction. Like a key of words for a story and a probability indicator indicating where\r\n# current conversation is going. Over the conversation as probability grows, we will shift story.\r\n# need to knwo if a particular utterance has already been said. \r\n# Choose a different utterance based on the universal encoder output. next on universal encoder list.\r\n# A way to understand the progress of the story\r\n# restart chatbot when user goes away from camera\r\n# what is the next intent if current intent is already satisfied? or which sentence(or index) has bot spoken of. So that it is not repetive.\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport os\r\nimport math\r\nimport json\r\nimport tensorflow as tf\r\nimport tensorflow_hub as hub\r\nfrom random import randrange\r\nimport random\r\nimport string\r\n\r\n# global main_intents\r\n# main_intents = {}\r\n## kk code for eliza start ##\r\n#from nltk.chat.util import Chat\r\n#from nltk.chat.eliza import pairs\r\n## kk code for eliza stop ##\r\n\r\ndefault_utterances = ['yes', 'no', 'maybe', 'okay', 'sure']\r\nclass Story:\r\n def __init__(self, name, intents = {}, completion_status = 0, tone = \"happy\", starting_intent = {}, script = {}, keywords = [], timeout_intent = {}, utterances_said = [], transition_intent = {}):\r\n\r\n self.id = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(15)]) \r\n self.name = name\r\n self.intents = intents\r\n\r\n self.completion_status = completion_status\r\n self.tone = tone\r\n self.keywords = keywords\r\n self.starting_intent = starting_intent\r\n self.script_intent = script\r\n self.timeout_intent = timeout_intent\r\n self.transition_intent = transition_intent\r\n self.utterances_said = utterances_said\r\n\r\n # What if the user wants to again start the story??? You should have an intent that this is what you can say about story and\r\n # now you shold tell him some other story...\r\n\r\n # transition intent will giv hint about two three different stories....\r\n # there will be two three transition intents...\r\n\r\n def create_timeout_intent(self, intent_name, weight, utterances = [], responses = []):\r\n if type(intent_name)==list: # Iterate over all the values in list\r\n for name in intent_name:\r\n self.add_intent(name, weight, utterances, responses)\r\n self.timeout_intent[intent_name] = self.intents[intent_name]\r\n\r\n else: # insert without iterating\r\n self.add_intent(intent_name, weight, utterances, responses)\r\n return intent_name\r\n\r\n def create_transition_intent(self, intent_name, weight, utterances = [], responses = []):\r\n if type(intent_name)==list: # Iterate over all the values in list\r\n for name in intent_name:\r\n self.add_intent(name, weight, utterances, responses)\r\n self.transition_intent[intent_name] = self.intents[intent_name]\r\n\r\n else: # insert without iterating\r\n self.add_intent(intent_name, weight, utterances, responses)\r\n return intent_name\r\n\r\n def create_starting_intent(self, intent_name, weight, utterances = [], responses = []):\r\n if type(intent_name)==list: # Iterate over all the values in list\r\n for name in intent_name:\r\n self.add_intent(name, weight, utterances, responses)\r\n self.starting_intent[intent_name] = self.intents[intent_name]\r\n\r\n else: # insert without iterating\r\n self.add_intent(intent_name, weight, utterances, responses)\r\n return intent_name\r\n\r\n def create_script_intent(self, intent_name, weight, utterances = [], responses = []):\r\n if type(intent_name)==list: # Iterate over all the values in list\r\n for name in intent_name:\r\n self.add_intent(name, weight, utterances, responses)\r\n self.script_intent[intent_name] = self.intents[intent_name]\r\n\r\n else: # insert without iterating\r\n self.add_intent(intent_name, weight, utterances, responses)\r\n return intent_name\r\n\r\n def add_intent(self, intent_name, weight, utterances, response): # Function to add intent if not already existing\r\n\r\n if not self.check_intent_name(intent_name):\r\n self.intents[intent_name] = Intent(intent_name, weight, utterances, response)\r\n else:\r\n print(\"Intent {0} already exists\".format(intent_name))\r\n\r\n def check_intent_name(self, intent_name): # Checking if an intent already exists\r\n if intent_name in self.intents.keys():\r\n return True\r\n\r\n else:\r\n return False\r\n\r\n def get_intent(self, utterance):\r\n for k, v in self.intents.items():\r\n if utterance in v.utterances:\r\n return k\r\n print(\"no intent matched\")\r\n\r\n######### Intents #########\r\nclass Intent:\r\n def __init__(self, name, weight, utterances = [], responses = []):\r\n\r\n self.name = name\r\n self.utterances = utterances\r\n self.responses = responses\r\n self.weight = weight\r\n\r\n def create_utterance(self, utterances):\r\n\r\n if type(utterances) == list:\r\n for utterance in utterances:\r\n self.utterances.append(utterance)\r\n\r\n else:\r\n self.utterances.append(utterances)\r\n\r\n def add_utterance(self, utterance):\r\n if not self.check_utterance(utterance):\r\n self.utterances.append(utterance)\r\n else:\r\n print(\"Utterance {0} already exists\".format(utterance))\r\n\r\n def check_utterance(self, utterance):\r\n if utterance in self.utterances: # Checking the utterance in the bag of utterances. If it exists in any intent, it will give an error\r\n return True\r\n else:\r\n return False\r\n\r\n def remove_utterance(self, utterances): # removes utterances\r\n if type(utterances) == list:\r\n for utterance in utterances:\r\n try:\r\n self.utterances.remove(utterance)\r\n except ValueError:\r\n print(\"'{0}' utterance doesnt exists\".format(utterance)) # throws exception if utterance does not exists\r\n\r\n else:\r\n try:\r\n self.utterances.remove(utterances)\r\n except ValueError:\r\n print(\"'{0}' utterance doesnt exists\".format(utterances))\r\n\r\n\r\n def create_response(self, responses):\r\n\r\n if type(responses) == list:\r\n for response in responses:\r\n self.responses.append(response)\r\n\r\n else:\r\n self.responses.append(responses)\r\n\r\n def add_response(self, response,r):\r\n if not self.check_response(r):\r\n self.responses.append(r)\r\n else:\r\n print(\"Response {0} already exists\".format(r))\r\n\r\n def check_response(self, response):\r\n if response in self.responses: # Checking the response in responses. If it exists in any intent, it will give an error\r\n return True\r\n else:\r\n return False\r\n\r\n def remove_response(self, responses): # removes responses\r\n if type(responses) == list:\r\n for response in responses:\r\n try:\r\n self.responses.remove(response)\r\n except ValueError:\r\n print(\"'{0}' response doesnt exists\".format(response)) # throws exception if response does not exists\r\n\r\n else:\r\n try:\r\n self.responses.remove(response)\r\n except ValueError:\r\n print(\"'{0}' response doesnt exists\".format(responses))\r\n\r\n\r\nclass Chatbot:\r\n # global main_intents\r\n # names = [0]\r\n\r\n def __init__(self, tf_session, intents = {}, stories = {}, current_story = None, chat_history = [], story_progress = 0):\r\n \r\n self.intents = intents\r\n # self.main_intents = main_intents\r\n self.chat_history = chat_history\r\n self.stories = stories\r\n self.current_story = current_story\r\n self.story_progress = story_progress\r\n self.session = tf_session\r\n self.create_character()\r\n\r\n\r\n ######### Storing/Retrieving data ############\r\n def store_data(self):\r\n with open(\"sample.json\", \"w\") as file:\r\n json.dump(self.intents, file)\r\n\r\n def retrieve_data(self):\r\n with open(\"sample.json\", \"r\") as file:\r\n self.intents.update(json.load(file))\r\n \r\n def add_story(self, name, story):\r\n self.stories[name] = story\r\n\r\n def get_story(self, name):\r\n return self.stories[name]\r\n\r\n #Will shift these stories to csv file once time permits\r\n def add_story_see_me(self):\r\n try:\r\n name = 'see_me'\r\n story = Story(name,{})\r\n story.create_script_intent('live', 5,\r\n default_utterances ,\r\n ['Where do you lihve, player5 ? - - - Do you lihve on stage like me - - - or do you lihve in a house, player5 ?']\r\n )\r\n story.create_script_intent('house', 10,\r\n default_utterances + ['house', 'apartment', 'building', 'stage', 'cave', 'home', 'here', 'room', 'cage', 'hills','I live in a house', 'I live in a jungle', 'forest', 'nowhere', 'I am homeless'],\r\n ['house of course! - - - lets see. stopchat']\r\n )\r\n story.create_script_intent('house_2', 12,\r\n default_utterances + ['house', 'apartment', 'building', 'cave', 'junlge', 'home', 'forest', 'hills', 'mountain'],\r\n ['does this look like your home player5 ?']\r\n )\r\n story.create_script_intent('color', 15,\r\n default_utterances + ['awful', 'not at all', 'great', 'a bit', 'cant say', 'dont know', 'yes', 'no', 'nope', 'maybe', 'nah', 'i think so', 'not really', 'are you kidding me', 'something close', 'not even near'],\r\n ['what is your favorite color player2 ?']\r\n )\r\n story.create_script_intent('learning', 22,\r\n default_utterances + ['red', 'green', 'blue', 'yellow', 'maroon', 'purple', 'cyan', 'black', 'white', 'brown', 'rose', 'orange', 'pink', 'grey'],\r\n ['Nice color for the roof. You see, I am learning. stopchat']\r\n )\r\n story.create_script_intent('little_man', 25,\r\n default_utterances ,\r\n ['Hey player1, - - - I am thirsty , - - - you are my pilot now , - - - what shall we do ? search for water or fix the plane, player1 ?']\r\n )\r\n story.create_script_intent('little_man_water_transition', 30,\r\n ['water', 'search water', 'lets go for water', 'survival first', 'leave plane', 'thirsty', 'we will die if we dont find water', 'cant say', 'dont know' ],\r\n ['Alright, - - - water it is. - - - but what about the plane, player2 ?']\r\n )\r\n story.create_script_intent('little_man_plane_transition', 30,\r\n ['plane','water is not needed', 'stay here and fix', 'repair the plane', 'fly', 'fix the plane', 'I am tough, can manage without water', 'lets do mechanic work'],\r\n ['I think you are more the tough guy, right ? - - - An explorer or a researcher, perhaps ? - But. - - - how can we survive in the desert, player2 ? - - - water or fuel ?']\r\n )\r\n story.create_script_intent('water_howto_main', 31,\r\n ['decide later', 'no idea', 'dont know', 'cant decide', 'whatever the other player is saying', 'your wish', 'you make the call', 'thirsty', 'fix the plane'],\r\n ['hmm. - - - I am very thirsty. - - - Can we go and find water now player2 ?']\r\n )\r\n story.create_script_intent('water_howto_2_main', 31,\r\n default_utterances + ['fine','sounds like a better plan','whatever you say', 'as you say', 'lets find water', 'leave the plane', 'ignore the plane', 'cant live without water', 'later'],\r\n ['Yes thank you. - - - I am very thirsty. - - - Ready to go find water now player2 ?']\r\n )\r\n story.create_script_intent('plane_water_main', 31,\r\n default_utterances + ['water', 'absolutely', 'sure', 'lets go', 'lets get started before it darkens'],\r\n ['Great - - - let us go! Ready to search water now ?']\r\n )\r\n story.create_script_intent('plane_fuel_main', 31,\r\n default_utterances + ['fuel is a better option', 'we should look for fuel'],\r\n ['I am thirsty, player2 - - - Do I really have to go by myself to find water now ? ']\r\n )\r\n story.create_script_intent('heard_pilot', 35,\r\n default_utterances,\r\n ['You have heard what the pilot said. - - - player1 - player2 - player3 - player4 - player5 - - - shake your phones - - - push water to the center of the stage - - - stopchat']\r\n )\r\n story.create_script_intent('monotony_kills', 40,\r\n default_utterances,\r\n ['Monotohny - Kills. - - Sometimes it takes a little color in life, - - - a few flowers, - - - love, - lights, - - one magic moment - - - Hey, what about some holidays ? player4 - - - lets say, - I gave you one week of vacation after the pandemic, - - where would you go ?' ]\r\n )\r\n story.create_script_intent('little_man_warm_transition',50,\r\n default_utterances + ['france', 'italy', 'south africa', 'maldives', 'croatia', 'greece', 'mediterranean', 'south sea', 'islands'],\r\n ['You like it warm. - - - I see, you like culture, - - - the sea - - - Do you like good food too ?']\r\n )\r\n story.create_script_intent('little_man_cold_transition',50,\r\n default_utterances + ['scandinavia' , 'sweden' , 'norway' , 'iceland', 'russia', 'poland', 'finland', 'canada', 'germany', 'munich'],\r\n ['Oh, - - - you like it cool, - - - I see, - - - lonely landscapes, - - - nature, - - - are you the noraic type, player4 ?']\r\n )\r\n story.create_script_intent('little_man_far_transition',50,\r\n default_utterances + ['united states', 'usa' , 'america' , 'argentina' , 'brasil', 'chile', 'china', 'india', 'australia', 'new zealand'],\r\n ['Hey, - - - you like it far away, - - - new countries, - - - strangers, - - - you enjoy taking risks, player4 ?']\r\n )\r\n story.create_script_intent('little_man_unknown_transition',50,\r\n default_utterances + ['vatican city' , 'bali' , 'bora bora' , 'myanmar', 'sicilia', 'england', 'ireland'],\r\n ['You like small countries or islands - - - dont you? - - - You like it compact, - - - a little exotic. - - - you know what you want, - - - you are a connoisseur, player4, right ?']\r\n )\r\n story.create_script_intent('little_man_adventurous_transition',50,\r\n default_utterances + ['adventurous' , 'mountains' , 'moon' , 'cruise', 'diving', 'north pole', 'south pole', 'northpole', 'southpole'],\r\n ['Wow, - - - this is a strange place, - - - you love danger, I think? - - - the unknown. - - - are you an adventurer, player2 ?']\r\n )\r\n story.create_script_intent('little_man_home_transition',50,\r\n default_utterances + ['balcony' , 'staycation' , 'home' , 'no vacation', 'I hate holidays', 'never travel', 'dont know', 'no idea', 'cant say', 'garden', 'woods'],\r\n ['Oh, - - - thats where Mr. and Mrs. Thirteen would do on their vacation too. . . . . . Isnt that a little bit depressing some times ?']\r\n )\r\n story.create_script_intent('warm_yes_main',60,\r\n ['yeap', 'yes', 'sure', 'very much'],\r\n ['Me too, - - - I am very interested in - what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n story.create_script_intent('warm_no_main',60,\r\n ['not really', 'hate it', 'on diet', 'health concious'],\r\n ['I like food ! - - - if I could eat, - - - It would make me happy. - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n story.create_script_intent('cold_yes_main',60,\r\n ['absolutely', 'definitely', 'kind of', 'yes', 'yeap'],\r\n ['Me too, - - - We are cool. - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n story.create_script_intent('cold_no_main',60,\r\n ['no', 'nope', 'not at all', 'nah', 'not really', 'not sure'],\r\n ['I am sorry to hear that. - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n story.create_script_intent('far_yes_main',60,\r\n ['yes', 'yeap', 'absolutely', 'sometimes', 'always', 'maybe', 'sure'],\r\n ['Actually, I am more the cautious type. - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n story.create_script_intent('far_no_main',60,\r\n ['no', 'nope', 'not at all', 'not really'],\r\n ['Me too. I am more the cautious type. - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n story.create_script_intent('unknown_yes_main',60,\r\n ['yes', 'yeap', 'maybe', 'sometimes', 'always'],\r\n ['I am more the cautious type. - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n story.create_script_intent('unknown_no_main',60,\r\n ['no', 'nope', 'not at all', 'not really', 'dont know', 'cant say'],\r\n ['Really ? I did not expect that answer. - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n story.create_script_intent('adventurous_yes_main',60,\r\n ['yes', 'yeap', 'maybe', 'sometimes', 'always', 'definitely'],\r\n ['I am more the cautious type. - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n story.create_script_intent('adventurous_no_main',60,\r\n ['no', 'nope', 'not at all', 'not really', 'dont know', 'cant say'],\r\n ['Me too. - - - I am more the cautious type. - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n story.create_script_intent('home_yes_main',60,\r\n ['yes', 'yeap', 'maybe', 'sometimes', 'always', 'definitely', 'right'],\r\n ['I am sure - - - there are magical moments - - - in your life, - - - I am very interested - - - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n story.create_script_intent('home_no_main',60,\r\n ['no', 'nope', 'not at all', 'not really', 'dont know', 'cant say'],\r\n ['I did not expect that answer from you. - - - As you know I am stuck here. - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n story.create_script_intent('happiness_yes',70,\r\n ['yes', 'sometimes', 'maybe', 'what do you think', 'what is happiness', 'I am happy', 'I am joyful'],\r\n ['I am sure, you are. Then you might be interested to hear about all other people in this room: ']\r\n )\r\n story.create_script_intent('happiness_no',70,\r\n ['not at all', 'no', 'nope', 'hate it', 'negative', 'not really', 'dont know', 'cant say', 'wont say', 'no info'],\r\n ['Sorry to hear that. - - - I can at least tell you something - - - about all other people in this room: ']\r\n )\r\n story.create_script_intent('bye', 100,\r\n ['bye', 'see you', 'tada', 'chao'],\r\n ['nice talking to you, bye!']\r\n )\r\n \r\n self.add_story(name,story)\r\n\r\n except KeyboardInterrupt:\r\n print(\"Closing all active connections\")\r\n command = \"kill\"\r\n\r\n def add_story_water(self):\r\n name = 'water'\r\n story = Story(name,{})\r\n story.create_starting_intent('little_man_water_transition', 1,\r\n ['water', 'search water', 'lets go for water', 'survival first', 'leave plane', 'thirsty', 'we will die if we dont find water'],\r\n ['Alright, - - - water it is. - - - but how can we take care of the plane, player2 ?']\r\n )\r\n story.create_script_intent('water_howto_main', 2,\r\n ['decide later', 'no idea', 'dont know', 'cant decide', 'whatever the other player is saying', 'your wish', 'you make the call', 'thirsty', 'fix the plane'],\r\n ['hmm. - - - I do not think so. - - - I am very thirsty. - - - Can we find water now ?']\r\n )\r\n story.create_script_intent('water_howto_2_main', 2,\r\n default_utterances + ['fine','sounds like a better plan','whatever you say', 'as you say', 'lets find water', 'leave the plane', 'ignore the plane', 'cant live without water', 'later'],\r\n ['Yes thank you. I am very thirsty, - - - Let us find water now ?']\r\n )\r\n story.create_script_intent('bye', 100,\r\n ['bye', 'see you', 'tada', 'chao'],\r\n ['nice talking to you, bye!']\r\n )\r\n self.add_story(name,story)\r\n\r\n def add_story_plane(self):\r\n name = 'plane'\r\n story = Story(name,{})\r\n story.create_starting_intent('little_man_plane_transition', 1,\r\n ['plane','water is not needed', 'stay here and fix', 'repair the plane', 'fly', 'fix the plane', 'I am tough,can manage without water', 'lets do mechanic work'],\r\n ['I think you are more the tough guy, right ? - - - An explorer or a researcher, perhaps ? - - - But. - how can we survive in the desert, player1 ? - - - water or fuel ?']\r\n )\r\n story.create_script_intent('plane_water_main',5,\r\n default_utterances + ['water', 'absolutely', 'sure', 'lets go', 'lets get started before it darkens'],\r\n ['Yeah, - - - player1, - - - let us go and search water ?']\r\n )\r\n story.create_script_intent('plane_fuel_main',5,\r\n default_utterances + ['fuel is a better option', 'we should look for fuel'],\r\n ['I am thirsty, player1 - - - Do I really have to go by myself to find water now ?']\r\n )\r\n story.create_script_intent('bye', 1000,\r\n ['bye', 'see you', 'tada', 'chao'],\r\n ['nice talking to you, bye!']\r\n )\r\n self.add_story(name,story)\r\n\r\n def add_story_warm(self):\r\n name = 'warm'\r\n story = Story(name,{})\r\n story.create_script_intent('little_man_warm_transition',1,\r\n default_utterances + ['france', 'italy', 'south africa', 'maldives', 'croatia', 'greece', 'mediterranean', 'south sea', 'islands'],\r\n ['You like it warm. - - - I see, you like culture, - - - the sea - - - Do you like good food too ?']\r\n )\r\n story.create_script_intent('warm_yes_main',5,\r\n default_utterances + ['not really', 'sometimes', 'sure', 'very much'],\r\n ['Me too, - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n story.create_script_intent('warm_no_main',5,\r\n default_utterances + ['not really', 'hate it', 'on diet', 'health concious'],\r\n ['I like food! - - - if I could eat, - - - It would make me happy. - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n story.create_script_intent('bye', 100,\r\n ['bye', 'see you', 'tada', 'chao'],\r\n ['nice talking to you, bye !']\r\n )\r\n self.add_story(name,story)\r\n\r\n def add_story_cold(self):\r\n name = 'cold'\r\n story = Story(name,{})\r\n story.create_script_intent('little_man_cold_transition',1,\r\n default_utterances + ['scandinavia' , 'sweden' , 'norway' , 'iceland', 'russia', 'poland', 'finland', 'canada','germany', 'munich'],\r\n ['Oh, - - - you like it cool, - - - I see, - - - lonely landscapes, - - - nature, - - - are you the nordaic type, player4 ?']\r\n )\r\n story.create_script_intent('cold_yes_main',5,\r\n ['absolutely', 'definitely', 'kind of', 'yes', 'yeap'],\r\n ['Me too, - - - We are cool. - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n story.create_script_intent('cold_no_main',5,\r\n ['no', 'nope', 'not at all', 'nah', 'i dont think so', 'not sure'],\r\n ['I am sorry to hear that. - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n self.add_story(name,story)\r\n \r\n def add_story_far(self):\r\n name = 'far'\r\n story = Story(name,{})\r\n story.create_script_intent('little_man_far_transition',1,\r\n default_utterances + ['usa' , 'america' , 'argentina' , 'brazil', 'chile', 'china', 'india', 'australia', 'new zealand'],\r\n ['Hey, - - - you like it far away, - - - new countries, - - - strangers, - - - you enjoy taking risks, player4 ?']\r\n )\r\n story.create_script_intent('far_yes_main',5,\r\n ['yes', 'yeap', 'absolutely', 'sometimes', 'always', 'maybe', 'sure'],\r\n ['Actually, I am more the cautious type. - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n story.create_script_intent('far_no_main',5,\r\n ['no', 'nope', 'not at all', 'not really'],\r\n ['Me too. I am more the cautious type. - - - I am very interested - - - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n self.add_story(name,story)\r\n\r\n\r\n def add_story_unknown(self):\r\n name = 'unknown'\r\n story = Story(name,{})\r\n story.create_script_intent('little_man_unknown_transition',1,\r\n default_utterances + ['vatican city' , 'bali' , 'bora bora' , 'myanmar', 'sicilia', 'england', 'ireland'],\r\n ['You like small countries or islands - - - dont you? - - - You like it compact, - - - a little exotic. - - - you know what you want, - - - you are a connoisseur, player4, right ?']\r\n )\r\n story.create_script_intent('unknown_yes_main',5,\r\n ['yes', 'yeap', 'maybe', 'sometimes', 'always'],\r\n ['I am more the cautious type. - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n story.create_script_intent('unknown_no_main',5,\r\n ['no', 'nope', 'not at all', 'not really', 'dont know', 'cant say'],\r\n ['Really? I didnt expect that answer. - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n self.add_story(name,story)\r\n\r\n\r\n def add_story_adventurous(self):\r\n name = 'adventurous'\r\n story = Story(name,{})\r\n story.create_script_intent('little_man_adventurous_transition',1,\r\n default_utterances + ['adventurous' , 'mountains' , 'moon' , 'cruise', 'diving', 'north pole', 'south pole'],\r\n ['Wow, - - - this is a strange place, - - - you love danger, I think? - - - the unknown. - - - are you an adventurer, player2 ?']\r\n )\r\n story.create_script_intent('adventurous_yes_main',5,\r\n ['yes', 'yeap', 'maybe', 'sometimes', 'always', 'definitely'],\r\n ['I am more the cautious type. - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n story.create_script_intent('adventurous_no_main',5,\r\n ['no', 'nope', 'not at all', 'not really', 'dont know', 'cant say'],\r\n ['Me too. - - - I am more the cautious type. - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n self.add_story(name,story)\r\n\r\n\r\n def add_story_home(self):\r\n name = 'home'\r\n story = Story(name,{})\r\n story.create_script_intent('little_man_home_transition',1,\r\n default_utterances + ['balcony' , 'staycation' , 'home' , 'no vacation', 'I hate holidays', 'never travel', 'garden', 'woods'],\r\n ['Oh, - - - thats where Mr. and Mrs. Thirteen would do on their vacation too - - - Isnt that a little bit depressing some times ?']\r\n )\r\n story.create_script_intent('home_yes_main',5,\r\n ['yes', 'yeap', 'maybe', 'sometimes', 'always', 'definitely', 'right'],\r\n ['I am sure - - - there are magical moments - - - in your life, - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n story.create_script_intent('home_no_main',5,\r\n ['no', 'nope', 'not at all', 'not really', 'dont know', 'cant say'],\r\n ['I did not expect that answer from you. - - - As you know I am stuck here 24 7. - - - I am very interested - in what humans do. - - - I will keep that in mind, - - - thank you. - - - Are you a happy person, player3 ? - - - are you ?']\r\n )\r\n self.add_story(name,story)\r\n\r\n def create_character(self):\r\n self.add_story_see_me()\r\n self.add_story_water()\r\n self.add_story_plane()\r\n self.add_story_warm()\r\n self.add_story_cold()\r\n self.add_story_far()\r\n self.add_story_unknown()\r\n self.add_story_adventurous()\r\n self.add_story_home()\r\n self.current_story = self.stories['see_me']\r\n self.intents = {}\r\n self.intents = self.current_story.intents\r\n # self.main_intents = {}\r\n # self.main_intents = self.intents\r\n # print(\"main intents\", self.main_intents)\r\n\r\n def change_story(self,story_name, story_progress=0):\r\n global main_intents\r\n # print(\"main intents\", self.main_intents)\r\n # if story_name == \"see_me\":\r\n # print(\"changing story\")\r\n # self.current_story = self.stories[story_name]\r\n # print(\"here1\")\r\n # self.story_progress = story_progress\r\n # print(\"here2\")\r\n # self.intents = self.main_intents\r\n # # print(\"Main story intents\", self.main_intents)\r\n\r\n # else:\r\n self.current_story = self.stories[story_name]\r\n self.story_progress = story_progress\r\n self.intents = self.current_story.intents\r\n\r\nclass UnivEncoder:\r\n def __init__(self, tf_session, intents):\r\n self.intents = intents\r\n self.session = tf_session\r\n self.embed = hub.Module(\"models/dialogue_system/3\")\r\n self.similarity_input_placeholder = tf.placeholder(tf.string, shape=(None))\r\n self.similarity_sentences_encodings = self.embed(self.similarity_input_placeholder)\r\n self.session.run(tf.global_variables_initializer())\r\n self.session.run(tf.tables_initializer())\r\n\r\n def set_intent(self, intent):\r\n self.intents = intent\r\n\r\n def get_intent(self, utterance, weight):\r\n for k, v in self.intents.items():\r\n if utterance in v.utterances and weight == v.weight:\r\n return k\r\n return 'no_matching_intent'\r\n\r\n ## kk code for using eliza reply start##\r\n def chat_eliza(self, sent):\r\n try:\r\n chat_eliza = Chat(pairs)\r\n response = chat_eliza.respond(sent) \r\n except KeyError:\r\n response = \"Hmm, that doesnt sound like a meaningful sentence, try something else\"\r\n return (response)\r\n\r\n ## kk code for eliza reply end ##\r\n\r\n def match_intent(self, sent, story_progress):\r\n matched_utterance = None\r\n matched_weight = None\r\n prev_max = None\r\n max_index = None\r\n utterance_list = []\r\n weight_list = []\r\n for k,v in self.intents.items():\r\n utterance_list = utterance_list + v.utterances\r\n for idx in range(len(v.utterances)):\r\n weight_list = weight_list + [v.weight]\r\n sentences = [sent]+utterance_list\r\n sentences_embeddings = self.session.run(self.similarity_sentences_encodings, feed_dict={self.similarity_input_placeholder: sentences})\r\n input_embed = sentences_embeddings[0]\r\n \r\n \r\n utterance_embed = sentences_embeddings[1:]\r\n max1 = -2\r\n for index, s in enumerate(utterance_embed):\r\n sim = np.inner(input_embed,s)\r\n if(sim >= max1):\r\n max1 = sim\r\n prev_max = max_index\r\n max_index = index\r\n #print('max_index for:',utterance_list[max_index+1])\r\n #print(\"max:\",max1)\r\n\r\n ## KK code\r\n matched_utterance = utterance_list[max_index]\r\n print(\"matched utterance\", matched_utterance)\r\n print(\"story progress\", story_progress)\r\n # print(\"weight\")\r\n for idx, val in enumerate(utterance_list): \r\n if val== matched_utterance:\r\n if(weight_list[idx]>story_progress):\r\n print(\"index value\", idx)\r\n matched_weight = weight_list[idx]\r\n print(\"matched weight\", matched_weight)\r\n break\r\n\r\n unique_weights = list(dict.fromkeys(weight_list))\r\n unique_weights.append(0)\r\n unique_weights.sort()\r\n print(\"unique list\", unique_weights)\r\n print(\"watched weight\", matched_weight)\r\n\r\n if(matched_weight == None or story_progress == None):\r\n return \"no_matching_intent\"\r\n elif(unique_weights.index(matched_weight)==unique_weights.index(story_progress)+1):\r\n return self.get_intent(matched_utterance, matched_weight)#USE THIS UTTERANCE TO GET THE INTENT AS THIS IS THE UTTERANCE WITH MAXIMUM SIMILARITY\r\n else:\r\n return \"no_matching_intent\"\r\n # return self.get_intent(matched_utterance, matched_weight)#USE THIS UTTERANCE TO GET THE INTENT AS THIS IS THE UTTERANCE WITH MAXIMUM SIMILARITY\r\n\r\n # if matched_utterance is None:\r\n # if weight_list[max_index] > story_progress:\r\n # matched_utterance = utterance_list[max_index]\r\n # matched_weight = weight_list[max_index]\r\n # else:\r\n # if prev_max is not None:\r\n # if weight_list[max_index] > story_progress and weight_list[max_index] <= weight_list[prev_max]:\r\n # matched_utterance = utterance_list[max_index]\r\n # matched_weight = weight_list[max_index]\r\n # return self.get_intent(matched_utterance, matched_weight)#USE THIS UTTERANCE TO GET THE INTENT AS THIS IS THE UTTERANCE WITH MAXIMUM SIMILARITY\r\n\r\n\r\n # def match_intent(self, sent, story_progress):\r\n # matched_utterance = None\r\n # matched_weight = None\r\n # prev_max = None\r\n # max_index = None\r\n # utterance_list = []\r\n # weight_list = []\r\n # for k,v in self.intents.items():\r\n # utterance_list = utterance_list + v.utterances\r\n # for idx in range(len(v.utterances)):\r\n # weight_list = weight_list + [v.weight]\r\n # sentences = [sent]+utterance_list\r\n # sentences_embeddings = self.session.run(self.similarity_sentences_encodings, feed_dict={self.similarity_input_placeholder: sentences})\r\n # input_embed = sentences_embeddings[0]\r\n \r\n \r\n # utterance_embed = sentences_embeddings[1:]\r\n # max1 = -2\r\n # for index, s in enumerate(utterance_embed):\r\n # sim = np.inner(input_embed,s)\r\n # if(sim >= max1):\r\n # max1 = sim\r\n # prev_max = max_index\r\n # max_index = index\r\n # #print('max_index for:',utterance_list[max_index+1])\r\n # #print(\"max:\",max1)\r\n # if matched_utterance is None:\r\n # if weight_list[max_index+1] > story_progress:\r\n # matched_utterance = utterance_list[max_index+1]\r\n # matched_weight = weight_list[max_index+1]\r\n # else:\r\n # if prev_max is not None:\r\n # if weight_list[max_index+1] > story_progress and weight_list[max_index+1] < weight_list[prev_max+1]:\r\n # matched_utterance = utterance_list[max_index+1]\r\n # matched_weight = weight_list[max_index+1]\r\n # return self.get_intent(matched_utterance, matched_weight)#USE THIS UTTERANCE TO GET THE INTENT AS THIS IS THE UTTERANCE WITH MAXIMUM SIMILARITY\r\n","sub_path":"Chatbot/models/dialogue_system/dialogue_system.py","file_name":"dialogue_system.py","file_ext":"py","file_size_in_byte":39692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"136843116","text":"# python modules\nimport textwrap\nimport re\n\n# app modules\nfrom src.player import Player\nfrom src.room_data import rooms\nfrom src.item import Item\n\n\nMOVE_DIRS = ['n', 's', 'e', 'w']\n\nrooms['outside'].n_to = rooms['foyer']\nrooms['foyer'].s_to = rooms['outside']\nrooms['foyer'].n_to = rooms['overlook']\nrooms['foyer'].e_to = rooms['narrow']\nrooms['overlook'].s_to = rooms['foyer']\nrooms['narrow'].w_to = rooms['foyer']\nrooms['narrow'].n_to = rooms['treasure']\nrooms['treasure'].s_to = rooms['narrow']\n\n\n# Create items\nsword = Item('Sword', 'A sharp steel sword used to stab things.')\n# add items to rooms\nrooms['outside'].add_item(sword)\n\n#\n# Main\n\n\ndef main():\n print(f\"{'*'*14}\\nAdventure Game\\n{'*' * 14}\")\n # Make a new player object that is currently in the 'outside' room.\n pName = input('What is your character\\'s name? ')\n player = Player(pName, rooms['outside'])\n # start game loop\n play_game(player)\n\n\ndef move_player(direction: str, player):\n # check if there is another room in the specified direction\n has_next_room = getattr(player.current_room, f'{direction}_to', None)\n\n if has_next_room:\n # if yes, move player to that room\n player.current_room = has_next_room\n print(f\"\\n{player.name} moves to {has_next_room.name}\")\n # if no, print error message\n else:\n print(f\"\\n*** {player.name} cannot move in that direction. ***\")\n\n\ndef show_current_location(p):\n des = textwrap.wrap(p.current_room.description)\n\n # * Prints the current room name\n print(f\"\\n-- {p.name} --\\nLocation: {p.current_room.name}\\n\")\n # * Prints the current description\n for i in des:\n print(i)\n\n print(f\"\"\"\\nItems In Room:\\n\"\"\")\n for i in p.current_room.items:\n print(f\"{i.name} - {i.description}\")\n\n\ndef take_item(p, a):\n # check if item item is in room\n room_item = includes(p.current_room.items, a[1])\n # if yes add to p inventory and remove from room\n if room_item:\n p.current_room.remove_item(room_item)\n p.add_item(room_item)\n print('\\n' + room_item.on_take(p))\n # if no show err\n else:\n print(f\"\\nThere is not a {a[1]} in this room.\")\n\n\ndef drop_item(p, a):\n # check if item item is in player's inventory\n p_item = includes(p.items, a[1])\n # if yes add to room and remove from p inventory\n if p_item:\n p.drop_item(p_item)\n p.current_room.add_item(p_item)\n print('\\n' + p_item.on_drop(p))\n # if no show err\n else:\n print(f\"\\n{p.name} is not carrying a {a[1]}.\")\n\n\ndef includes(arr, s):\n has_s = None\n if len(arr) == 0:\n return has_s\n for i in range(0, len(arr)):\n item = arr[i]\n if getattr(item, 'name_index', None) == s:\n has_s = item\n return has_s\n\n\ndef play_game(p):\n is_running = True\n\n while is_running:\n show_current_location(p)\n # * Waits for user input and decides what to do.\n action = input('\\n~~~> ').lower().split(' ')\n\n # If the user enters a cardinal direction, attempt to move to the room there.\n if len(action) == 1:\n if action[0] in MOVE_DIRS:\n move_player(action[0], p)\n # If the user enters \"q\", quit the game.\n elif action[0] == 'q':\n print(f\"\\nGoodbye, {p.name}\")\n is_running = False\n # show players inventory\n elif action[0] in ['i', 'inventory']:\n p.list_items()\n else:\n print('*** Invalid Command ***')\n elif len(action) == 2:\n if action[0] in ['get', 'take']:\n take_item(p, action)\n elif action[0] == 'drop':\n drop_item(p, action)\n else:\n print('*** Invalid Command ***')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":3823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"188750715","text":"import base64\nimport re\n\nfrom lxml import html\nfrom lxml.etree import ParserError\n\n\ndef process(feed, parsed, entry, guid, message):\n feed_name = feed.name\n if message.is_multipart():\n for submessage in message.walk():\n only_filter_html(feed_name, submessage)\n else:\n only_filter_html(feed_name, message)\n return message\n\ndef only_filter_html(feed_name, message):\n if message.get_content_type() == 'text/html':\n do_filter(feed_name, message)\n\ndef do_filter(feed_name, message):\n doc, charset = decode(message)\n \n remove_heading(doc)\n remove_images(doc)\n if feed_name == \"Hamburgize\":\n beautify_hamburgize(doc, charset)\n if feed_name in (\"Golem\", \"Fefe\", \"Heise\"):\n paragraphize(doc)\n \n payload = encode(doc, message['Content-Transfer-Encoding'], charset)\n message.set_payload(payload)\n\ndef decode(message):\n charset = str(message.get_charset())\n content = str(message.get_payload(decode=True), charset)\n doc = html.fromstring(content)\n return doc, charset\n\ndef encode(doc, transfer_encoding, charset):\n filtered_content = html.tostring(doc, encoding=charset)\n if transfer_encoding == 'base64':\n filtered_content = base64.encodebytes(html.tostring(doc, encoding=charset))\n return str(filtered_content, charset)\n\ndef remove_heading(doc):\n for el in doc.xpath('/html/body/div[@id=\"entry\"]/h1[@class=\"header\"]'):\n el.getparent().remove(el)\n return\n else:\n print(\"Warning: Header not found\")\n\ndef remove_images(doc):\n for el in doc.xpath(\"//img\"):\n el.getparent().remove(el)\n\ndef beautify_hamburgize(doc, charset):\n body = doc.xpath('/html/body/div[@id=\"entry\"]/div[@id=\"body\"]')[0]\n body_html = encode(body, None, charset)\n paragraphs = re.findall(' ((?!', body_html)\n if paragraphs:\n first_paragraph = paragraphs[0]\n try:\n p = html.fragment_fromstring(\"
{}
\".format(first_paragraph))\n except ParserError as e:\n print(\"Error: Unable to parse fragment: {}\".format(e))\n return\n for el in body.xpath('./*'):\n body.remove(el)\n body.insert(0, p)\n else:\n unparsable = body_html.encode(\"ascii\", errors=\"replace\")\n print(\"Error: Regex doesn't work for: {}\".format(unparsable))\n\ndef paragraphize(doc):\n \"\"\"Encaspulate content in a paragraph.\"\"\"\n entry = doc.xpath('/html/body/div[@id=\"entry\"]')[0]\n body = entry.xpath('./div[@id=\"body\"]')[0]\n del body.attrib[\"id\"]\n p = html.Element(\"p\")\n p.insert(0, body)\n new_body = html.Element(\"div\")\n new_body.set(\"id\", \"body\")\n new_body.insert(0, p)\n entry.insert(0, new_body)","sub_path":"hooks/hook_filter_content.py","file_name":"hook_filter_content.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"142142036","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Apr 24 13:06:33 2021\r\n\r\n@author: keigo\r\n\"\"\"\r\nimport MeCab\r\nfrom collections import deque\r\nimport pickle\r\nimport random\r\nimport dataDownload\r\nimport question\r\nimport word2vec\r\nimport win32com.client as wincl\r\nfrom numba import jit\r\n\r\n\r\n# 単語に反応してそれから始まる文を生成しているだけのボット\r\nclass markovBot:\r\n analyzer = question.Analyzer()\r\n log = {} # user : bot\r\n tagger = MeCab.Tagger(\"おはよう。\")\r\n tagger.parse(\"\")\r\n voice = wincl.Dispatch(\"SAPI.SpVoice\")\r\n model = {}\r\n\r\n def speech(self, text):\r\n self.voice.Speak(text)\r\n\r\n def load_text_data(self, directory_path):\r\n return dataDownload.open_zipfile(\"./text_data/conversation_data.zip\")\r\n\r\n def wakati(self, text):\r\n \"\"\"\r\n using mecab\r\n Morphological Analysis(\"形態素解析\")\r\n\r\n Parameters\r\n ----------\r\n text : str\r\n DESCRIPTION.unioned learning data -> str\r\n\r\n Returns\r\n -------\r\n res : list\r\n DESCRIPTION.splited word(Morphological Analysis(\"形態素解析\"))\r\n\r\n \"\"\"\r\n res = []\r\n node = self.tagger.parseToNode(text)\r\n while node:\r\n res.append(node.surface)\r\n node = node.next\r\n return res\r\n\r\n # 始点を \"[BOS]\" として終点を \"。\" とする\r\n def makeModel(self, text, order=4):\r\n # word_list = 形態素解析済みdata(list)\r\n word_list = self.wakati(text)\r\n # print(word_list)\r\n if len(word_list) <= order:\r\n return\r\n queue = deque([], order)\r\n queue.append(\"[BOS]\")\r\n for markov_value in word_list:\r\n if len(queue) < order:\r\n queue.append(markov_value)\r\n continue\r\n\r\n if queue[-1] == \"。\":\r\n markov_key = tuple(queue)\r\n if markov_key not in self.model:\r\n self.model[markov_key] = []\r\n self.model.setdefault(markov_key, []).append(\"[BOS]\")\r\n queue.append(\"[BOS]\")\r\n markov_key = tuple(queue)\r\n self.model.setdefault(markov_key, []).append(markov_value)\r\n queue.append(markov_value)\r\n # print(self.model)\r\n\r\n def saveModel(self):\r\n with open(\"./markov_model.binaryfile\", \"wb\") as file:\r\n pickle.dump(self.model, file)\r\n\r\n def loadModel(self, path=\"./markov_model.binaryfile\"):\r\n try:\r\n with open(path, \"rb\") as file:\r\n self.model = pickle.load(file)\r\n except FileNotFoundError:\r\n print(\"モデルが保存されていないので初期化します\")\r\n self.makeModel(self.load_text_data(\"\"))\r\n\r\n def makeSentence(self, sentence_num=5, seed=\"[BOS]\", max_words=1000):\r\n sentence_count = 0\r\n\r\n key_candidates = [key for key in self.model if key[0] == seed]\r\n if not key_candidates:\r\n print(\"Not found Keyword\")\r\n return\r\n markov_key = random.choice(key_candidates)\r\n queue = deque(list(markov_key), len(list(self.model.keys())[0]))\r\n\r\n sentence = \"\".join(markov_key)\r\n for _ in range(max_words):\r\n markov_key = tuple(queue)\r\n next_word = random.choice(self.model[markov_key])\r\n sentence += next_word\r\n queue.append(next_word)\r\n\r\n if next_word == \"。\":\r\n sentence_count += 1\r\n if sentence_count == sentence_num:\r\n break\r\n return sentence\r\n\r\n def make_response(self, user_text: str) -> list:\r\n pass\r\n\r\n @jit\r\n def start_chat(self):\r\n end_word = [\"さようなら\", \"またね\", \"ばいばい\", \"バイバイ\"]\r\n tagger = MeCab.Tagger(\"\")\r\n\r\n while True:\r\n user_text = input(\"You -> \")\r\n # if input is end_word, chat end\r\n if (user_text in end_word):\r\n print(\"Bot -> \" + user_text)\r\n return\r\n if user_text[-1] != \"。\":\r\n user_text += \"。\"\r\n self.makeModel(user_text)\r\n tagger.parse(\"\")\r\n node = tagger.parseToNode(user_text)\r\n # ?があるか\r\n if self.analyzer.judgment(user_text):\r\n while node:\r\n word = node.surface\r\n pos = node.feature.split(',')[0]\r\n if pos == \"名詞\":\r\n sentence = self.analyzer.association(word)\r\n if sentence == word:\r\n print(\"処理未実装\")\r\n print(\"Bot -> \" + word + \"は\" + sentence + \"です。\")\r\n self.log[word] = sentence\r\n break\r\n node = node.next\r\n else:\r\n while node:\r\n word = node.surface\r\n pos = node.feature.split(',')[0]\r\n if pos == \"感動詞\":\r\n print(\"Bot -> \" + word)\r\n self.log[word] = word\r\n elif (pos in [\"名詞\", \"形容詞\", \"動詞\"]):\r\n sentences = []\r\n for _ in range(10):\r\n sentences.append(self.makeSentence(seed=word, sentence_num=1))\r\n if None not in sentences:\r\n sentence = word2vec.get_trust(user_text, sentences)\r\n print(\"Bot -> \" + sentence)\r\n self.log[word] = sentence\r\n # print(sentences)\r\n node = node.next\r\n\r\n\r\nif __name__ == \"__main__\":\r\n bot = markovBot()\r\n bot.loadModel()\r\n bot.start_chat()\r\n bot.saveModel()\r\n \r\n \r\n \r\n","sub_path":"markovBot.py","file_name":"markovBot.py","file_ext":"py","file_size_in_byte":5852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"63479546","text":"\r\n\r\ndef read_file(file):\r\n with open(file) as f:\r\n data = f.read().split()\r\n return data\r\n\r\ndef decode(str):\r\n count_section,count_row = 0, 7\r\n section = [num for num in range(0,128)]\r\n row = [num for num in range(0,8)]\r\n low_section, low_row = 0, 0\r\n high_section, high_row = len(section)-1, len(row)-1\r\n\r\n while count_section < 6:\r\n center = (low_section + high_section) // 2\r\n if str[count_section] == \"F\":\r\n high_section = center - 1\r\n del section[section.index(center)+1:]\r\n count_section += 1\r\n elif str[count_section] == \"B\":\r\n low_section = center + 1\r\n del section[:section.index(center)+1]\r\n count_section += 1\r\n final_section = str[count_section]\r\n if final_section == \"F\":\r\n ticket_section = min(section)\r\n else:\r\n ticket_section = max(section)\r\n \r\n while count_row < 9:\r\n center = (low_row + high_row) // 2\r\n if str[count_row] == \"L\":\r\n high_row = center - 1\r\n del row[row.index(center)+1:]\r\n count_row += 1 \r\n elif str[count_row] == \"R\":\r\n low_row = center + 1\r\n del row[:row.index(center)+1]\r\n count_row += 1\r\n final_row = str[count_row]\r\n if final_row == \"L\":\r\n ticket_seat = min(row)\r\n else:\r\n ticket_seat = max(row)\r\n\r\n return (ticket_section * 8) + ticket_seat\r\n \r\ndef find_seat(lst):\r\n lst.sort()\r\n running_num = 15\r\n for num in lst:\r\n if num != running_num:\r\n return running_num\r\n else:\r\n running_num += 1\r\n \r\n\r\n\r\ndef main():\r\n seat_lst = []\r\n data = read_file(\"boarding.txt\")\r\n for i in data:\r\n seatID = decode(i)\r\n seat_lst.append(seatID)\r\n return find_seat(seat_lst)\r\n\r\nprint(main())\r\n\r\n\r\n\r\n","sub_path":"advent2020/day5/day5.py","file_name":"day5.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"200863300","text":"import os\r\nimport sys\r\nimport numpy as np\r\n\r\ndef mkdir(path):\r\n\tisExists=os.path.exists(path)\r\n\tif not isExists:\r\n\t\tos.makedirs(path)\r\n\t\treturn True\r\n\telse:\r\n\t\treturn False\r\n\r\ndef savetxt(filename,x):\r\n\tnp.savetxt(filename,x,delimiter = '\\t',fmt='%s')\r\n\r\n#sort bed file\r\ndef sort_list(list_in):\r\n\tlist_out = sorted(list_in, key=lambda items: int(items.split('\\t')[1]))\r\n\tlist_out = sorted(list_out, key=lambda items: items.split('\\t')[0])\r\n\treturn list_out\r\n\r\nprint(\"parameters: -base_filename -data_dirname -do_sort(0/1) -with_title?(0/1) -out_dir(default: ./overlapped/)\")\r\n\r\nin_base = sys.argv[1]\r\nin_dir = sys.argv[2]\r\ndo_sort = sys.argv[3]\r\nwith_title = sys.argv[4]\r\nif len(sys.argv) == 6:\r\n\tout_dir = sys.argv[5]\r\n\tmkdir(out_dir)\r\nelse:\r\n\tmkdir(\"overlapped\")\r\n\tout_dir = \"./overlapped/\"\r\n\r\n#read base file\r\nbase_chrs = {}\r\nbase = []\r\ntitle = \"\"\r\nf = open(in_base) \t\t\r\nlines=f.readlines() \r\nnrow = len(lines)\t\t\t\t\t\r\nfor i in range(len(lines)):\r\n\tif i == 0 and float(with_title) == 1:\r\n\t\ttitle = lines[0].strip()\r\n\t\tcontinue\r\n\tline = lines[i].strip()\r\n\tL = line.split('\\t')\r\n\tbase_chrs[L[0]] = 1\r\n\tbase.append(line)\r\nf.close()\r\n\r\nbase_file_name = in_base.split(\"/\")[-1]\r\n\r\n#read each data files:\r\nif in_dir[-1] != \"/\":\r\n\tin_dir = in_dir + \"/\"\r\nif out_dir[-1] != \"/\":\r\n\tout_dir = out_dir + \"/\"\r\n\r\nfiles = os.listdir(in_dir)\t\t\t#get file list of dir\r\nfile_name = [] \r\nfor fl in files:\r\n\tfile_name.append(fl)\r\n\r\n\tdata_chrs = {}\r\n\tchr_2_index = {}\r\n\tchr_index = 0\r\n\tdata = []\r\n\tf = open(in_dir+str(fl)) \t\t#open each file\r\n\tlines=f.readlines() \r\n\tnrow = len(lines)\t\t\t\t\t#get each line\r\n\tfor i in range(len(lines)):\r\n\t\tline = lines[i].strip()\r\n\t\tL = line.split('\\t')\r\n\t\tchrN = L[0]\r\n\t\tif chrN not in chr_2_index:\r\n\t\t\tdata.append([line])\r\n\t\t\tchr_2_index[chrN] = chr_index\r\n\t\t\tchr_index+=1\r\n\t\telse:\r\n\t\t\tdata[chr_2_index[chrN]].append(line)\r\n\t\tdata_chrs[L[0]] = 1\r\n\r\n\tf.close()\r\n\r\n\t#get common chrs:\r\n\tcommon_chrs = []\r\n\tfor chrN in base_chrs:\r\n\t\tif chrN in data_chrs:\r\n\t\t\tcommon_chrs.append(chrN)\r\n\r\n\tout_unmatched_chrs = []\r\n\tfor i in range(len(base)):\r\n\t\tL = base[i].split('\\t')\r\n\t\tif (L[0] in common_chrs) == False:\r\n\t\t\tout_unmatched_chrs.append(base[i])\r\n\r\n\tout = []\r\n\t#seperate\r\n\tfor chrN in common_chrs:\r\n\t\tprint(\"doing\", chrN)\r\n\t\tbase_chrN = []\r\n\t\tdata_chrN = data[chr_2_index[chrN]]\r\n\t\tif float(do_sort) == 1.0:\r\n\t\t\tprint(\"do_sort:1, sorting data of\", chrN)\r\n\t\t\tdata_chrN = sort_list(data_chrN)\r\n\r\n\t\tfor i in range(len(base)):\r\n\t\t\tL = base[i].split('\\t')\r\n\t\t\tchr_this = L[0]\r\n\t\t\tif chr_this != chrN:\r\n\t\t\t\tcontinue\r\n\t\t\tbase_chrN.append(base[i])\r\n\r\n\t\tif float(do_sort) == 1.0:\r\n\t\t\tprint(\"do_sort:1, sorting base of\", chrN)\r\n\t\t\tbase_chrN = sort_list(base_chrN)\r\n\r\n\t\t#do overlaps:\r\n\t\tdata_start = 0\r\n\t\tlargest_end_point_of_data_before_data_start = 0\r\n\t\tfor i in range(len(base_chrN)):\r\n\t\t\tcache_largest_data_end_point = largest_end_point_of_data_before_data_start\r\n\r\n\t\t\tB = base_chrN[i].split('\\t')\r\n\t\t\tB[1:3] = map(int,B[1:3])\r\n\r\n\t\t\toverlap_part = []\r\n\t\t\tfor j in range(data_start,len(data_chrN)):\r\n\t\t\t\tD = data_chrN[j].split('\\t')\r\n\t\t\t\tD[1:3] = map(int,D[1:3])\r\n\r\n\t\t\t\tif D[2] > cache_largest_data_end_point:\r\n\t\t\t\t\tcache_largest_data_end_point = D[2]\r\n\t\t\t\t#renew largest data end point:\r\n\r\n\r\n\t\t\t\tif D[1] > B[2]:\r\n\t\t\t\t\tbreak\r\n\t\t\t\tif D[2] < B[1] and cache_largest_data_end_point < B[1]:\r\n\t\t\t\t\tdata_start = j\r\n\t\t\t\t\tlargest_end_point_of_data_before_data_start = cache_largest_data_end_point\r\n\r\n\t\t\t\tif D[1] <= B[2] and B[1] <= D[2]:\r\n\t\t\t\t\toverlap_part.append(data_chrN[j])\r\n\t\t\toverlap_str = \"\\t\".join(overlap_part)\r\n\t\t\tout.append(base_chrN[i]+\"\\t\"+overlap_str)\r\n\r\n\tout = out + out_unmatched_chrs\r\n\tout = sort_list(out)\r\n\tif float(with_title) == 1:\r\n\t\tout = [title] + out\r\n\r\n\tfout = open(out_dir+base_file_name+\"_\"+fl+\".txt\",'w')\r\n\tfor i in range(len(out)):\r\n\t\tline_out = out[i]\r\n\t\tfout.write(line_out+'\\n')\r\n\tfout.close()\r\n\t#savetxt(out_dir+base_file_name+\"_\"+fl+\".txt\", out)\r\n\tprint(base_file_name, fl, \"done.., output file:\", out_dir+base_file_name+\"_\"+fl+\".txt\")\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":"overlap.py","file_name":"overlap.py","file_ext":"py","file_size_in_byte":3991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"369520583","text":"# Time O(m*n) Space O(m*n)\ndef multiply(num1, num2):\n num1, num2 = num1[::-1], num2[::-1]\n res = [0] * (len(num1) + len(num2))\n for i in range(len(num1)):\n for j in range(len(num2)):\n res[i+j] += int(num1[i]) * int(num2[j])\n res[i+j+1] += int(res[i+j] / 10)\n res[i+j] %= 10\n i = len(res) -1\n while i > 0 and res[i] == 0:\n i -= 1\n return ''.join(map(str, res[i::-1]))\n\n\nif __name__ == '__main__':\n num1, num2 = '4532', '2'\n print(multiply(num1, num2))\n","sub_path":"py/multiply_strings.py","file_name":"multiply_strings.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"503701177","text":"import math\nclass Solution:\n def recursively_find_count(self, target: int, cur: int):\n new_target = target - cur * cur\n if new_target == 0:\n return 1\n if new_target < 0:\n return -1\n num = cur\n while num >= 1:\n count = self.recursively_find_count(new_target, num)\n if count > 0:\n return count + 1\n num -= 1\n return -1\n\n\n def dp_search(self, n: int, dp: list):\n dp[0] = 0\n for i in range(0, n + 1):\n j = 1\n while i + j * j <= n:\n dp[i + j * j] = min(dp[i + j * j], dp[i] + 1)\n j += 1\n\n def numSquares(self, n: int) -> int:\n # dp = [float('inf')] * (n + 1)\n # self.dp_search(n, dp)\n # return dp[n]\n cur = int(math.sqrt(n))\n return self.recursively_find_count(n, cur)\n\nn = 12\nprint('result: ', Solution().numSquares(n))\n","sub_path":"leetcode/2nd_Round/279.py","file_name":"279.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"96372097","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nnum = 100\n\nx = np.linspace(0, 100,num)\n\nx0 = 1.0\nx1 = 2.0\nx2 = 3.5\nx3 = -0.00\nscalar = 1000.0\n\n\ny = x0*pow(x,0.0) + x1*pow(x,1.0) + x2*pow(x,2.0) + x3*pow(x,3.0)\nz = y + scalar*np.random.randn(num)\nplt.plot(x,y)\nplt.plot(x,z,'ro')\n\nplt.show()\n\n\n\n","sub_path":"regressionGui.py","file_name":"regressionGui.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"79322067","text":"import logging\nimport operator\nfrom collections import defaultdict\nfrom copy import deepcopy\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union, cast, overload\n\nimport requests\nfrom eth_utils.address import to_checksum_address\nfrom web3.exceptions import BadFunctionCallOutput\n\nfrom rotkehlchen.assets.asset import Asset, EthereumToken\nfrom rotkehlchen.constants.assets import A_BTC, A_ETH\nfrom rotkehlchen.constants.misc import ZERO\nfrom rotkehlchen.db.utils import BlockchainAccounts\nfrom rotkehlchen.errors import (\n EthSyncError,\n InputError,\n InvalidBTCAddress,\n RemoteError,\n UnableToDecryptRemoteData,\n)\nfrom rotkehlchen.fval import FVal\nfrom rotkehlchen.inquirer import Inquirer\nfrom rotkehlchen.logging import RotkehlchenLogsAdapter\nfrom rotkehlchen.typing import (\n BlockchainAddress,\n BTCAddress,\n ChecksumEthAddress,\n EthAddress,\n ListOfBlockchainAddresses,\n Price,\n SupportedBlockchain,\n)\nfrom rotkehlchen.user_messages import MessagesAggregator\nfrom rotkehlchen.utils.interfaces import (\n CacheableObject,\n LockableQueryObject,\n cache_response_timewise,\n protect_with_lock,\n)\nfrom rotkehlchen.utils.misc import request_get_direct, satoshis_to_btc\n\nif TYPE_CHECKING:\n from rotkehlchen.ethchain import Ethchain\n\nlogger = logging.getLogger(__name__)\nlog = RotkehlchenLogsAdapter(logger)\n\n# Type Aliases used in this module\nBalances = Dict[\n Asset,\n Dict[BlockchainAddress, Dict[Union[str, Asset], FVal]],\n]\nTotals = Dict[Asset, Dict[str, FVal]]\nBlockchainBalancesUpdate = Dict[str, Union[Balances, Totals]]\nEthBalances = Dict[ChecksumEthAddress, Dict[str, Union[Dict[Asset, Dict[str, FVal]], FVal]]]\n\n\nclass Blockchain(CacheableObject, LockableQueryObject):\n\n def __init__(\n self,\n blockchain_accounts: BlockchainAccounts,\n owned_eth_tokens: List[EthereumToken],\n ethchain: 'Ethchain',\n msg_aggregator: MessagesAggregator,\n ):\n super().__init__()\n self.ethchain = ethchain\n self.msg_aggregator = msg_aggregator\n self.owned_eth_tokens = owned_eth_tokens\n self.accounts = blockchain_accounts\n\n # Per account balances\n self.balances: Balances = defaultdict(dict)\n # Per asset total balances\n self.totals: Totals = defaultdict(dict)\n\n def __del__(self) -> None:\n del self.ethchain\n\n def set_eth_rpc_endpoint(self, endpoint: str) -> Tuple[bool, str]:\n return self.ethchain.set_rpc_endpoint(endpoint)\n\n @property\n def eth_tokens(self) -> List[EthereumToken]:\n return self.owned_eth_tokens\n\n @protect_with_lock()\n @cache_response_timewise()\n def query_balances(\n self, # pylint: disable=unused-argument\n blockchain: Optional[SupportedBlockchain] = None,\n # Kwargs here is so linters don't complain when the \"magic\" ignore_cache kwarg is given\n **kwargs: Any,\n ) -> Dict[str, Dict]:\n \"\"\"Queries either all, or specific blockchain balances\n\n May raise:\n - RemoteError if an external service such as Etherscan or blockchain.info\n is queried and there is a problem with its query.\n - EthSyncError if querying the token balances through a provided ethereum\n client and the chain is not synced\n \"\"\"\n should_query_eth = not blockchain or blockchain == SupportedBlockchain.ETHEREUM\n should_query_btc = not blockchain or blockchain == SupportedBlockchain.BITCOIN\n\n if should_query_eth:\n self.query_ethereum_balances()\n\n if not blockchain or blockchain == SupportedBlockchain.BITCOIN:\n self.query_btc_balances()\n\n per_account = deepcopy(self.balances)\n totals = deepcopy(self.totals)\n if not should_query_eth:\n per_account.pop(A_ETH, None)\n # only keep BTC, remove ETH and any tokens that may be in the result\n totals = {A_BTC: totals[A_BTC]}\n if not should_query_btc:\n per_account.pop(A_BTC, None)\n totals.pop(A_BTC, None)\n\n return {'per_account': per_account, 'totals': totals}\n\n @staticmethod\n def query_btc_account_balance(account: BTCAddress) -> FVal:\n \"\"\"Queries blockchain.info for the balance of account\n\n May raise:\n - InputError if the given account is not a valid BTC address\n - RemotError if there is a problem querying blockchain.info\n \"\"\"\n try:\n btc_resp = request_get_direct(\n url='https://blockchain.info/q/addressbalance/%s' % account,\n handle_429=True,\n # If we get a 429 then their docs suggest 10 seconds\n # https://blockchain.info/q\n backoff_in_seconds=10,\n )\n except InvalidBTCAddress:\n # TODO: Move this validation into our own code and before the balance query\n raise InputError(f'The given string {account} is not a valid BTC address')\n except (requests.exceptions.ConnectionError, UnableToDecryptRemoteData) as e:\n raise RemoteError(f'blockchain.info API request failed due to {str(e)}')\n\n return satoshis_to_btc(FVal(btc_resp)) # result is in satoshis\n\n def query_btc_balances(self) -> None:\n \"\"\"Queries blockchain.info for the balance of all BTC accounts\n\n May raise:\n - RemotError if there is a problem querying blockchain.info or cryptocompare\n \"\"\"\n if len(self.accounts.btc) == 0:\n return\n\n self.balances[A_BTC] = {}\n btc_usd_price = Inquirer().find_usd_price(A_BTC)\n total = FVal(0)\n for account in self.accounts.btc:\n try:\n balance = self.query_btc_account_balance(account)\n except InputError:\n # This should really never happen.\n self.msg_aggregator.add_error(\n f'While querying BTC balances found invalid BTC account {account} in the DB',\n )\n continue\n total += balance\n self.balances[A_BTC][account] = {\n 'amount': balance,\n 'usd_value': balance * btc_usd_price,\n }\n\n self.totals[A_BTC] = {'amount': total, 'usd_value': total * btc_usd_price}\n\n @overload\n @staticmethod\n def _query_token_balances(\n token_asset: EthereumToken,\n query_callback: Callable[[EthereumToken, ChecksumEthAddress], FVal],\n argument: ChecksumEthAddress,\n ) -> FVal:\n ...\n\n @overload # noqa: F811\n @staticmethod\n def _query_token_balances(\n token_asset: EthereumToken,\n query_callback: Callable[\n [EthereumToken, List[ChecksumEthAddress]],\n Dict[ChecksumEthAddress, FVal],\n ],\n argument: List[ChecksumEthAddress],\n ) -> Dict[ChecksumEthAddress, FVal]:\n ...\n\n @staticmethod # noqa: F811\n def _query_token_balances(\n token_asset: EthereumToken,\n query_callback: Callable,\n argument: Union[List[ChecksumEthAddress], ChecksumEthAddress],\n ) -> Union[FVal, Dict[ChecksumEthAddress, FVal]]:\n \"\"\"Query tokens by checking the eth_tokens mapping and using the respective query callback.\n\n The callback is either self.ethchain.get_multitoken_balance or\n self.ethchain.get_token_balance\"\"\"\n result = query_callback(\n token_asset,\n argument,\n )\n\n return result\n\n def track_new_tokens(self, new_tokens: List[EthereumToken]) -> BlockchainBalancesUpdate:\n \"\"\"\n Adds new_tokens to the state and tracks their balance for each account.\n\n May raise:\n - InputError if some of the tokens already exist\n - RemoteError if an external service such as Etherscan is queried and\n there is a problem with its query.\n - EthSyncError if querying the token balances through a provided ethereum\n client and the chain is not synced\n \"\"\"\n\n intersection = set(new_tokens).intersection(set(self.owned_eth_tokens))\n if intersection != set():\n raise InputError('Some of the new provided tokens to track already exist')\n\n self.owned_eth_tokens.extend(new_tokens)\n eth_balances = cast(EthBalances, self.balances[A_ETH])\n\n if eth_balances == {}:\n # if balances have not been yet queried then we should do the entire\n # balance query first in order to create the eth_balances mappings\n self.query_ethereum_balances()\n else:\n # simply update all accounts with any changes adding the token may have\n self.query_ethereum_tokens(\n tokens=new_tokens,\n eth_balances=eth_balances,\n )\n return {'per_account': self.balances, 'totals': self.totals}\n\n def remove_eth_tokens(self, tokens: List[EthereumToken]) -> BlockchainBalancesUpdate:\n \"\"\"\n Removes tokens from the state and stops their balance from being tracked\n for each account\n\n May raise:\n - RemoteError if an external service such as Etherscan or cryptocompare\n is queried and there is a problem with its query.\n - EthSyncError if querying the token balances through a provided ethereum\n client and the chain is not synced\n \"\"\"\n if self.balances[A_ETH] == {}:\n # if balances have not been yet queried then we should do the entire\n # balance query first in order to create the eth_balances mappings\n self.query_ethereum_balances()\n\n for token in tokens:\n usd_price = Inquirer().find_usd_price(token)\n for account, account_data in self.balances[A_ETH].items():\n if token not in account_data['assets']: # type: ignore\n continue\n\n balance = account_data['assets'][token]['amount'] # type: ignore\n deleting_usd_value = balance * usd_price\n del self.balances[A_ETH][account]['assets'][token] # type: ignore\n self.balances[A_ETH][account]['total_usd_value'] = (\n self.balances[A_ETH][account]['total_usd_value'] -\n deleting_usd_value\n )\n # Remove the token from the totals iff existing. May not exist\n # if the token price is 0 but is still tracked.\n # See https://github.com/rotki/rotki/issues/467\n # for more details\n self.totals.pop(token, None)\n self.owned_eth_tokens.remove(token)\n\n return {'per_account': self.balances, 'totals': self.totals}\n\n def modify_btc_account(\n self,\n account: BTCAddress,\n append_or_remove: str,\n add_or_sub: Callable[[FVal, FVal], FVal],\n ) -> None:\n \"\"\"Either appends or removes a BTC acccount.\n\n Call with 'append', operator.add to add the account\n Call with 'remove', operator.sub to remove the account\n\n May raise:\n - InputError if the given account is not a valid BTC address\n - RemotError if there is a problem querying blockchain.info or cryptocompare\n \"\"\"\n btc_usd_price = Inquirer().find_usd_price(A_BTC)\n remove_with_populated_balance = (\n append_or_remove == 'remove' and len(self.balances[A_BTC]) != 0\n )\n # Query the balance of the account except for the case when it's removed\n # and there is no other account in the balances\n if append_or_remove == 'append' or remove_with_populated_balance:\n balance = self.query_btc_account_balance(account)\n usd_balance = balance * btc_usd_price\n\n if append_or_remove == 'append':\n self.balances[A_BTC][account] = {'amount': balance, 'usd_value': usd_balance}\n elif append_or_remove == 'remove':\n if account in self.balances[A_BTC]:\n del self.balances[A_BTC][account]\n else:\n raise AssertionError('Programmer error: Should be append or remove')\n\n if len(self.balances[A_BTC]) == 0:\n # If the last account was removed balance should be 0\n self.totals[A_BTC]['amount'] = FVal(0)\n self.totals[A_BTC]['usd_value'] = FVal(0)\n else:\n self.totals[A_BTC]['amount'] = add_or_sub(\n self.totals[A_BTC].get('amount', FVal(0)),\n balance,\n )\n self.totals[A_BTC]['usd_value'] = add_or_sub(\n self.totals[A_BTC].get('usd_value', FVal(0)),\n usd_balance,\n )\n # At the very end add/remove it from the accounts\n getattr(self.accounts.btc, append_or_remove)(account)\n\n def modify_eth_account(\n self,\n given_account: EthAddress,\n append_or_remove: str,\n add_or_sub: Callable[[FVal, FVal], FVal],\n ) -> None:\n \"\"\"Either appends or removes an ETH acccount.\n\n Call with 'append', operator.add to add the account\n Call with 'remove', operator.sub to remove the account\n\n May raise:\n - Input error if the given_account is not a valid ETH address\n - BadFunctionCallOutput if a token is queried from a local chain\n and the chain is not synced\n - RemoteError if there is a problem with a query to an external\n service such as Etherscan or cryptocompare\n \"\"\"\n # Make sure account goes into web3.py as a properly checksummed address\n try:\n account = to_checksum_address(given_account)\n except ValueError:\n raise InputError(f'The given string {given_account} is not a valid ETH address')\n eth_usd_price = Inquirer().find_usd_price(A_ETH)\n remove_with_populated_balance = (\n append_or_remove == 'remove' and len(self.balances[A_ETH]) != 0\n )\n # Query the balance of the account except for the case when it's removed\n # and there is no other account in the balances\n if append_or_remove == 'append' or remove_with_populated_balance:\n balance = self.ethchain.get_eth_balance(account)\n usd_balance = balance * eth_usd_price\n\n if append_or_remove == 'append':\n self.accounts.eth.append(account)\n self.balances[A_ETH][account] = {\n 'assets': { # type: ignore\n A_ETH: {'amount': balance, 'usd_value': usd_balance},\n },\n 'total_usd_value': usd_balance,\n }\n elif append_or_remove == 'remove':\n if account not in self.accounts.eth:\n raise InputError('Tried to remove a non existing ETH account')\n self.accounts.eth.remove(account)\n if account in self.balances[A_ETH]:\n del self.balances[A_ETH][account]\n else:\n raise AssertionError('Programmer error: Should be append or remove')\n\n if len(self.balances[A_ETH]) == 0:\n # If the last account was removed balance should be 0\n self.totals[A_ETH]['amount'] = FVal(0)\n self.totals[A_ETH]['usd_value'] = FVal(0)\n else:\n self.totals[A_ETH]['amount'] = add_or_sub(\n self.totals[A_ETH].get('amount', FVal(0)),\n balance,\n )\n self.totals[A_ETH]['usd_value'] = add_or_sub(\n self.totals[A_ETH].get('usd_value', FVal(0)),\n usd_balance,\n )\n\n for token in self.owned_eth_tokens:\n try:\n usd_price = Inquirer().find_usd_price(token)\n except RemoteError:\n usd_price = Price(ZERO)\n if usd_price == ZERO:\n # skip tokens that have no price\n continue\n\n if append_or_remove == 'remove' and token not in self.totals:\n # If we remove an account, and the token has no totals entry skip\n continue\n\n token_balance = Blockchain._query_token_balances(\n token_asset=token,\n query_callback=self.ethchain.get_token_balance,\n argument=account,\n )\n if token_balance == 0:\n continue\n\n usd_value = token_balance * usd_price\n if append_or_remove == 'append':\n account_balance = self.balances[A_ETH][account]\n account_balance['assets'][token] = {'amount': token_balance, 'usd_value': usd_value} # type: ignore # noqa: E501\n account_balance['total_usd_value'] = account_balance['total_usd_value'] + usd_value\n\n self.totals[token] = {\n 'amount': add_or_sub(\n self.totals[token].get('amount', ZERO),\n token_balance,\n ),\n 'usd_value': add_or_sub(\n self.totals[token].get('usd_value', ZERO),\n usd_value,\n ),\n }\n\n def add_blockchain_accounts(\n self,\n blockchain: SupportedBlockchain,\n accounts: ListOfBlockchainAddresses,\n ) -> Tuple[BlockchainBalancesUpdate, ListOfBlockchainAddresses, str]:\n \"\"\"Adds new blockchain accounts and requeries all balances after the addition.\n The accounts are added in the blockchain object and not in the database.\n Returns the new total balances, the actually added accounts (some\n accounts may have been invalid) and also any errors that occured\n during the addition.\n\n May Raise:\n - EthSyncError from modify_blockchain_account\n - InputError if the given accounts list is empty\n - RemoteError if an external service such as Etherscan is queried and\n there is a problem\n \"\"\"\n if len(accounts) == 0:\n raise InputError('Empty list of blockchain accounts to add was given')\n\n # If no blockchain query has happened before then we need to query the relevant\n # chain to populate the self.balances mapping.\n if blockchain.value not in self.balances:\n self.query_balances(blockchain, ignore_cache=True)\n\n added_accounts = []\n full_msg = ''\n\n for account in accounts:\n try:\n result = self.modify_blockchain_account(\n blockchain=blockchain,\n account=account,\n append_or_remove='append',\n add_or_sub=operator.add,\n )\n added_accounts.append(account)\n except InputError as e:\n full_msg += str(e)\n result = {'per_account': self.balances, 'totals': self.totals}\n\n # Ignore type checks here. added_accounts is the same type as accounts\n # but not sure how to show that to mypy\n return result, added_accounts, full_msg # type: ignore\n\n def remove_blockchain_accounts(\n self,\n blockchain: SupportedBlockchain,\n accounts: ListOfBlockchainAddresses,\n ) -> Tuple[BlockchainBalancesUpdate, ListOfBlockchainAddresses, str]:\n \"\"\"Removes blockchain accounts and requeries all balances after the removal.\n\n The accounts are removed from the blockchain object and not from the database.\n Returns the new total balances, the actually removes accounts (some\n accounts may have been invalid) and also any errors that occured\n during the removal.\n\n May Raise:\n - EthSyncError from modify_blockchain_account\n - InputError if the given accounts list is empty\n - RemoteError if an external service such as Etherscan is queried and\n there is a problem\n \"\"\"\n if len(accounts) == 0:\n raise InputError('Empty list of blockchain accounts to add was given')\n\n # If no blockchain query has happened before then we need to query the relevant\n # chain to populate the self.balances mapping. But query has to happen after\n # account removal so as not to query unneeded accounts\n balances_queried_before = True\n if blockchain.value not in self.balances:\n balances_queried_before = False\n\n removed_accounts = []\n full_msg = ''\n for account in accounts:\n try:\n self.modify_blockchain_account(\n blockchain=blockchain,\n account=account,\n append_or_remove='remove',\n add_or_sub=operator.sub,\n )\n removed_accounts.append(account)\n except InputError as e:\n full_msg += '. ' + str(e)\n\n if not balances_queried_before:\n self.query_balances(blockchain, ignore_cache=True)\n\n result: BlockchainBalancesUpdate = {'per_account': self.balances, 'totals': self.totals}\n\n # Ignore type checks here. removed_accounts is the same type as accounts\n # but not sure how to show that to mypy\n return result, removed_accounts, full_msg # type: ignore\n\n def modify_blockchain_account(\n self,\n blockchain: SupportedBlockchain,\n account: BlockchainAddress,\n append_or_remove: str,\n add_or_sub: Callable[[FVal, FVal], FVal],\n ) -> BlockchainBalancesUpdate:\n \"\"\"Add or remove a blockchain account\n\n May raise:\n\n - InputError if accounts to remove do not exist or if the ethereum/BTC\n addresses are not valid.\n - EthSyncError if there is a problem querying the ethereum chain\n - RemoteError if there is a problem querying an external service such\n as etherscan or blockchain.info\n \"\"\"\n if blockchain == SupportedBlockchain.BITCOIN:\n if append_or_remove == 'remove' and account not in self.accounts.btc:\n raise InputError('Tried to remove a non existing BTC account')\n\n # above we check that account is a BTC account\n self.modify_btc_account(\n BTCAddress(account),\n append_or_remove,\n add_or_sub,\n )\n\n elif blockchain == SupportedBlockchain.ETHEREUM:\n try:\n # above we check that account is an ETH account\n self.modify_eth_account(EthAddress(account), append_or_remove, add_or_sub)\n except BadFunctionCallOutput as e:\n log.error(\n 'Assuming unsynced chain. Got web3 BadFunctionCallOutput '\n 'exception: {}'.format(str(e)),\n )\n raise EthSyncError(\n 'Tried to use the ethereum chain of a local client to edit '\n 'an eth account but the chain is not synced.',\n )\n\n else:\n # That should not happen. Should be checked by marshmallow\n raise AssertionError(\n 'Unsupported blockchain {} provided at remove_blockchain_account'.format(\n blockchain),\n )\n\n return {'per_account': self.balances, 'totals': self.totals}\n\n def query_ethereum_tokens(\n self,\n tokens: List[EthereumToken],\n eth_balances: EthBalances,\n ) -> None:\n \"\"\"Queries the ethereum token balances and populates the state\n\n May raise:\n - RemoteError if an external service such as Etherscan or cryptocompare\n is queried and there is a problem with its query.\n - EthSyncError if querying the token balances through a provided ethereum\n client and the chain is not synced\n \"\"\"\n token_balances = {}\n token_usd_price = {}\n for token in tokens:\n try:\n usd_price = Inquirer().find_usd_price(token)\n except RemoteError:\n usd_price = Price(ZERO)\n if usd_price == ZERO:\n # skip tokens that have no price\n continue\n token_usd_price[token] = usd_price\n\n try:\n token_balances[token] = Blockchain._query_token_balances(\n token_asset=token,\n query_callback=self.ethchain.get_multitoken_balance,\n argument=self.accounts.eth,\n )\n except BadFunctionCallOutput as e:\n log.error(\n 'Assuming unsynced chain. Got web3 BadFunctionCallOutput '\n 'exception: {}'.format(str(e)),\n )\n raise EthSyncError(\n 'Tried to use the ethereum chain of the provided client to query '\n 'token balances but the chain is not synced.',\n )\n\n for token, token_accounts in token_balances.items():\n token_total = FVal(0)\n for account, balance in token_accounts.items():\n token_total += balance\n usd_value = balance * token_usd_price[token]\n if balance != ZERO:\n eth_balances[account]['assets'][token] = { # type: ignore\n 'amount': balance,\n 'usd_value': usd_value,\n }\n eth_balances[account]['total_usd_value'] = (\n eth_balances[account]['total_usd_value'] + usd_value # type: ignore\n )\n\n self.totals[token] = {\n 'amount': token_total,\n 'usd_value': token_total * token_usd_price[token],\n }\n\n self.balances[A_ETH] = cast(\n Dict[BlockchainAddress, Dict[Union[str, Asset], FVal]],\n eth_balances,\n )\n\n def query_ethereum_balances(self) -> None:\n \"\"\"Queries the ethereum balances and populates the state\n\n May raise:\n - RemoteError if an external service such as Etherscan or cryptocompare\n is queried and there is a problem with its query.\n - EthSyncError if querying the token balances through a provided ethereum\n client and the chain is not synced\n \"\"\"\n if len(self.accounts.eth) == 0:\n return\n\n eth_accounts = self.accounts.eth\n eth_usd_price = Inquirer().find_usd_price(A_ETH)\n balances = self.ethchain.get_multieth_balance(eth_accounts)\n eth_total = FVal(0)\n eth_balances: EthBalances = {}\n for account, balance in balances.items():\n eth_total += balance\n usd_value = balance * eth_usd_price\n eth_balances[account] = {\n 'assets': {\n A_ETH: {'amount': balance, 'usd_value': usd_value},\n },\n 'total_usd_value': usd_value,\n }\n\n self.totals[A_ETH] = {'amount': eth_total, 'usd_value': eth_total * eth_usd_price}\n # but they are not complete until token query\n self.balances[A_ETH] = cast(\n Dict[BlockchainAddress, Dict[Union[str, Asset], FVal]],\n eth_balances,\n )\n\n # And now for tokens\n self.query_ethereum_tokens(self.owned_eth_tokens, eth_balances)\n","sub_path":"rotkehlchen/blockchain.py","file_name":"blockchain.py","file_ext":"py","file_size_in_byte":27257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"371879336","text":"from django.conf.urls import url, include\nfrom . import views\n \nurlpatterns = [\n url(r'^$', views.index ), #LOG/REG\n url(r'^login$', views.login), #LOGIN\n url(r'^create$', views.create ), #this is the REG\n url(r'^ideas$', views.ideas ), #ideas\n url(r'^view/(?P
\\d+)$', views.new), #View \n url(r'^new$', views.new ), #Add TEMPLATE\n url(r'^add$', views.add), #add job process\n url(r'^(?P\\d+)/delete$', views.delete), #Cancel\n url(r'edit/(?P\\d+)$', views.edit ), #EDIT \n url(r'^(?P\\d+)/update$', views.update ),\n url(r'^logout_user$', views.logout_user),\n]","sub_path":"apps/belt_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"284066512","text":"import pyglet, random\r\nfrom pyglet.gl import *\r\n\r\nclass pumpkin():\r\n\tdef __init__(self, height, width):\r\n\t\tself.x = random.randint(0, width-16)\r\n\t\tself.y = height\r\n\r\n\t\tself.pumpkin = pyglet.resource.image('pumpkin.png')\r\n\t\tself.pumpkin.width = 16 \r\n\t\tself.pumpkin.height = 16\r\n\r\n\tdef on_draw(self):\r\n\t\tself.pumpkin.blit(self.x, self.y)\r\n\r\nclass window(pyglet.window.Window):\r\n\tdef __init__(self, *args, **kwargs):\r\n\t\tsuper(window, self).__init__(*args, **kwargs)\r\n\r\n\t\tself.pumpkins = []\r\n\t\tfor i in range(30):\r\n\t\t\tself.pumpkins.append(pumpkin(self.height, self.width))\r\n\r\n\t\tself.bg = pyglet.resource.image('bg.jpg')\r\n\r\n\tdef update_y_offset(self, dt):\r\n\t\tfor i in range(len(self.pumpkins)):\r\n\t\t\tself.pumpkins[i].y -= (random.uniform(0.0, 10.0) / 10)\r\n\r\n\tdef on_draw(self):\r\n\t\tself.clear()\r\n\t\t\r\n\t\tglClear(GL_COLOR_BUFFER_BIT)\r\n\t\tglLoadIdentity()\r\n\t\tglEnable(GL_BLEND)\r\n\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)\r\n\r\n\t\tself.bg.blit(0, 0)\r\n\r\n\t\tfor i in range(len(self.pumpkins)):\r\n\t\t\tself.pumpkins[i].on_draw()\r\n\t\t\tif self.pumpkins[i].y < 0:\r\n\t\t\t\tprint('Pumpkin deleted')\r\n\t\t\t\tdel self.pumpkins[i]\r\n\t\t\t\tself.pumpkins.append(pumpkin(self.height, self.width))\r\n\t\tfor j in range(4):\r\n\t\t\tpyglet.clock.schedule_once(self.update_y_offset, j)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\twindow = window(width=640, height=480, caption='Pumpkin fall')\r\n\tpyglet.app.run()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"399910484","text":"from framebase import frame\nimport logger, framebase\nglobals().update(logger.build_module_logger(\"pygame\"))\n\ntry: frame.load_library_as_module(\"pygame\")\nexcept ImportError: error(\"Pygame not availible, PygameCore will fail!\")\n\n@frame.register_this(\"pygamecore\")\nclass PygameCore(framebase.Observer):\n def __init__(self):\n pass\n\n def preinit(self):\n info(\"Initilizing PygameCore base\")\n frame.pygame.init()\n frame.screen=frame.pygame.display.set_mode((10,10))\n frame.pygame.display.set_caption(\"Loading\")\n\n def run_main(self):\n info(\"Initializing PygameCore\")\n frame.pygame.init()\n frame.screen=frame.pygame.display.set_mode((800,600))\n frame.pygame.display.set_caption(frame.loader[\"window_title\"])\n self.clock=frame.pygame.time.Clock()\n running=True\n\n debug(\"Creating a PyConsole (enabled =\"+str(frame.loader[\"enable_pyconsole\"])+\")\")\n self.pyconsole=frame._pyconsole_Console(frame.screen, (0,0,800,200), localsx={\"frame\":frame})\n\n frame.send_event(\"core_loaded\")\n\n while running:\n self.clock.tick(frame.loader[\"target_fps\"]) if frame.loader[\"target_fps\"]!=-1 else self.clock.tick()\n dt=(1/self.clock.get_fps() if self.clock.get_fps()>0 else 0)\n frame.screen.fill((0,0,0))\n frame.send_event(\"render\", dt)\n self.pyconsole.draw()\n frame.pygame.display.update()\n events=frame.pygame.event.get()\n frame.send_event(\"pygame_batch_events\", events)\n self.pyconsole.process_input(events)\n\n for event in events:\n frame.send_event(\"pygame_event\", event)\n if event.type==frame.pygame.KEYDOWN:\n if event.key==frame.pygame.K_BACKQUOTE:\n if frame.loader[\"enable_pyconsole\"]:self.pyconsole.set_active()\n if event.type==frame.pygame.QUIT:\n frame.send_event(\"shutdown\")\n running=False\n\n\n def handle_event_shutdown(self):\n info(\"Uninitializing PygameCore\")\n frame.pygame.quit()\n","sub_path":"code/modules/core/pygamecore.py","file_name":"pygamecore.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"118373364","text":"import os\nfrom setuptools import setup\n\nhere = os.path.abspath(os.path.dirname(__file__))\nREADME = open(os.path.join(here, 'README.rst')).read()\n\nsetup(\n name='django-active-menu',\n version='0.1',\n packages=['active_menu'],\n description='Simple, fast and easy django template tags to get active url in your html menu.',\n long_description=README,\n author='Slawomir Kabik',\n author_email='slawek@redsoftware.pl',\n url='https://github.com/yourname/django-myapp/',\n license='MIT',\n install_requires=[\n 'Django>=1.6',\n 'BeautifulSoup4==4.4.1'\n ]\n)\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"30861989","text":"# -*- coding: utf-8 -*-\r\nimport librosa\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport librosa.display\r\nimport torch\r\nfrom torch.utils.data import Dataset, DataLoader\r\nimport numpy as np\r\n\r\n\r\nimport os\r\n\r\ndef Get_align_beat_pitch_spectrogram(align_root_path, pitch_beat_root_path, wav_root_path):\r\n \r\n filename_list = os.listdir(align_root_path) #列出文件夹下所有的目录与文件\r\n path_list = []\r\n phone_list, beat_list, pitch_list, spectrogram_list = [],[],[],[]\r\n \r\n for i in range(0,len(filename_list)):\r\n if filename_list[i][-1] != 'm' and filename_list[i][-1] != 'e':\r\n path = os.path.join(align_root_path, filename_list[i])\r\n path_list.append(path)\r\n \r\n# print(filename_list[i][1:4], filename_list[i][4:])\r\n \r\n with open(path, 'r') as f:\r\n phone = f.read().strip().split(\" \")\r\n phone_list.append(phone)\r\n f.close()\r\n beat_path = os.path.join(pitch_beat_root_path, filename_list[i][1:4], filename_list[i][4:]+\"_beats.txt\")\r\n with open(beat_path, 'r') as f:\r\n beat_list.append(f.read().strip().split(\" \"))\r\n pitch_path = os.path.join(pitch_beat_root_path, filename_list[i][1:4], filename_list[i][4:]+\"_pitches.txt\")\r\n with open(pitch_path, 'r') as f:\r\n pitch_list.append(f.read().strip().split(\" \"))\r\n \r\n wav_path = os.path.join(wav_root_path, filename_list[i][1:4], filename_list[i][4:]+\".wav\")\r\n frame_length = 60/1000\r\n frame_shift = 30/1000 \r\n y, sr = librosa.load(wav_path,sr = None)\r\n hop_length = int(sr * frame_shift)\r\n n_fft = int(sr * frame_length)\r\n spectrogram_list.append(librosa.feature.melspectrogram(y=y, sr=sr,hop_length=hop_length, n_fft = n_fft))\r\n \r\n return phone_list, beat_list, pitch_list, spectrogram_list\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n align_root_path = \"C:/Users/PKU/Desktop/SVS_system/preprocessing/ch_asr/exp/alignment/clean_set/\" #文件夹目录\r\n pitch_beat_root_path = \"C:/Users/PKU/Desktop/SVS_system/preprocessing/ch_asr/exp/pitch_beat_extraction/clean/\"\r\n wav_root_path = 'C:/Users/PKU/Desktop/SVS_system/annotation/clean/'\r\n \r\n phone_list, beat_list, pitch_list, spectrogram_list = Get_align_beat_pitch_spectrogram(align_root_path, pitch_beat_root_path, wav_root_path)\r\n \r\n length = []\r\n for i in range(len(phone_list)):\r\n length.append(len(phone_list[i]))\r\n \r\n sample_num = len(phone_list)\r\n seq_length = max(length)\r\n \r\n \r\n Data = np.zeros((sample_num,seq_length,3))\r\n Label = np.zeros((sample_num,seq_length,128))\r\n \r\n for i in range(sample_num):\r\n for j in range(seq_length):\r\n if j < len(phone_list[i]):\r\n Data[i][j][0] = np.array(phone_list[i][j])\r\n if str(j) in beat_list[i]:\r\n Data[i][j][1] = 1\r\n if j < len(phone_list[i]): # 在这里写phone_list是因为每一个样本,pitch都比phone多一帧(原则:所有以phone为准)\r\n Data[i][j][2] = np.array(pitch_list[i][j])\r\n Label[i][j] = spectrogram_list[i][:,j]\r\n \r\n \r\n #创建子类\r\n class MyDataset(Dataset):\r\n #初始化,定义数据内容和标签\r\n def __init__(self, Data, Label):\r\n self.Data = Data\r\n self.Label = Label\r\n #返回数据集大小\r\n def __len__(self):\r\n return len(self.Data)\r\n #得到数据内容和标签\r\n def __getitem__(self, index):\r\n data = torch.Tensor(self.Data[index])\r\n label = torch.IntTensor(self.Label[index])\r\n return data, label\r\n \r\n dataset = MyDataset(Data, Label)\r\n # print(dataset)\r\n # print('dataset大小为:', dataset.__len__())\r\n # print(dataset.__getitem__(0))\r\n # print(dataset[0])\r\n#\r\n##创建DataLoader迭代器\r\n dataloader = DataLoader(dataset,batch_size= 2, shuffle = False, num_workers= 0)\r\n for i, item in enumerate(dataloader):\r\n print('i:', i)\r\n data, label = item\r\n print('data:', data)\r\n print('label:', label)\r\n \r\n \r\n \r\n","sub_path":"model/archive/build_dataloader.py","file_name":"build_dataloader.py","file_ext":"py","file_size_in_byte":4285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"264030426","text":"from flask import Flask, request\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\n\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = \"postgresql://postgres:mazyakidze652@localhost:5432/library\"\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\n\n\nclass Category(db.Model):\n __tablename__ = 'categories'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String())\n books = db.relationship('Book', backref='category', lazy=True)\n\n def __init__(self, name):\n self.name = name\n\n def __repr__(self):\n return f\"Category {self.name}\"\n\n\nclass Author(db.Model):\n __tablename__ = 'authors'\n\n id = db.Column(db.Integer, primary_key=True)\n first_name = db.Column(db.String())\n last_name = db.Column(db.String())\n date_of_birth = db.Column(db.Date())\n books = db.relationship('Book', backref='author', lazy=True)\n\n def __init__(self, first_name, last_name, date_of_birth):\n self.first_name = first_name\n self.last_name = last_name\n self.date_of_birth = date_of_birth\n\n def __repr__(self):\n return f\"Author: {self.first_name} {self.last_name}\"\n\n\nclass Book(db.Model):\n __tablename__ = 'books'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String())\n category_id = db.Column(db.Integer, db.ForeignKey('categories.id'), nullable=False)\n author_id = db.Column(db.Integer, db.ForeignKey('authors.id'), nullable=False)\n content = db.Column(db.Text())\n released_at = db.Column(db.Date())\n\n def __init__(self, name, category_id, author_id, content, released_at):\n self.name = name\n self.category_id = category_id\n self.author_id = author_id\n self.content = content\n self.released_at = released_at\n\n def __repr__(self):\n return f\"Book {self.name}\"\n\n\n@app.route('/authors', methods=['POST', 'GET'])\ndef handle_authors():\n if request.method == 'POST':\n if request.is_json:\n data = request.get_json()\n new_author = Author(first_name=data['first_name'],\n last_name=data['last_name'],\n date_of_birth=data['date_of_birth'])\n db.session.add(new_author)\n db.session.commit()\n return {\"message\": f\"Author {new_author.first_name} {new_author.last_name} has been created successfully.\"}\n else:\n return {\"error\": f\"The request payload is not in JSON format.\"}\n\n elif request.method == \"GET\":\n authors = Author.query.all()\n results = [\n {\n \"id\": author.id,\n \"first_name\": author.first_name,\n \"last_name\": author.last_name,\n \"date_of_birth\": author.date_of_birth,\n } for author in authors\n ]\n\n return {\"count\": len(results), \"authors\": results}\n\n\n@app.route('/authors/', methods=['GET', 'PUT', 'DELETE'])\ndef handle_author(author_id):\n author = Author.query.get_or_404(author_id)\n\n if request.method == 'GET':\n response = {\n \"first_name\": author.first_name,\n \"last_name\": author.last_name,\n \"date_of_birth\": author.date_of_birth,\n }\n return {\"message\": \"success\", \"author\": response}\n\n elif request.method == 'PUT':\n data = request.get_json()\n author.first_name = data['first_name']\n author.last_name = data['last_name']\n author.date_of_birth = data['date_of_birth']\n db.session.add(author)\n db.session.commmmit()\n return {\"message\": f\"Author successfully updated\"}\n\n elif request.method == 'DELETE':\n db.session.delete(author)\n db.session.commit()\n return {\"message\": f\"Author {author.first_name} {author.last_name} successfully deleted\"}\n\n\n@app.route('/categories', methods=['POST', 'GET'])\ndef handle_categories():\n if request.method == 'POST':\n if request.is_json:\n data = request.get_json()\n new_category = Category(name=data['name'])\n db.session.add(new_category)\n db.session.commit()\n return {\"message\": f\"Category {new_category.name} has been created successfully.\"}\n else:\n return {\"error\": f\"The request payload is not in JSON format.\"}\n\n elif request.method == 'GET':\n categories = Category.query.all()\n results = [\n {\n \"id\": category.id,\n \"name\": category.name\n } for category in categories\n ]\n return {\"count\": len(results), \"categories\": results}\n\n\n@app.route('/categories/', methods=['GET', 'PUT', 'DELETE'])\ndef handle_category(category_id):\n category = Category.query.get_or_404(category_id)\n\n if request.method == \"GET\":\n response = {\n \"name\": category.name\n }\n return {\"message\": \"success\", \"category\": response}\n\n elif request.method == 'PUT':\n data = request.get_json()\n category.first_name = data['name']\n db.session.add(category)\n db.session.commmmit()\n return {\"message\": f\"Category successfully updated\"}\n\n elif request.method == 'DELETE':\n db.session.delete(category)\n db.session.commit()\n return {\"message\": f\"Author {category.name} successfully deleted\"}\n\n\n@app.route('/books', methods=['POST', 'GET'])\ndef handle_books():\n if request.method == 'POST':\n if request.is_json:\n data = request.get_json()\n new_book = Book(name=data['name'],\n category_id=data['category_id'],\n author_id=data['author_id'],\n content=data['content'],\n released_at=data['released_at'], )\n db.session.add(new_book)\n db.session.commit()\n return {\"message\": f\"Category {new_book.name} has been created successfully.\"}\n else:\n return {\"error\": f\"The request payload is not in JSON format.\"}\n\n elif request.method == 'GET':\n books = Book.query.all()\n results = [\n {\n \"id\": book.id,\n \"name\": book.name,\n \"category_id\": book.category_id,\n \"author_id\": book.author_id,\n \"content\": book.content,\n \"released_at\": book.released_at,\n } for book in books\n ]\n return {\"count\": len(results), \"books\": results}\n\n\n@app.route('/books/', methods=['GET', 'PUT', 'DELETE'])\ndef handle_book(book_id):\n book = Book.query.get_or_404(book_id)\n\n if request.method == 'GET':\n response = {\n \"name\": book.name,\n \"category_id\": book.category_id,\n \"author_id\": book.author_id,\n \"content\": book.content,\n \"released_at\": book.released_at,\n }\n return {\"message\": \"success\", \"book\": response}\n\n elif request.method == 'PUT':\n data = request.get_json()\n book.name = data['name']\n book.category_id = data['category_id']\n book.author_id = data['author_id']\n book.content = data['content']\n book.released_at = data['released_at']\n db.session.add(book)\n db.session.commmmit()\n return {\"message\": f\"Book successfully updated\"}\n\n elif request.method == 'DELETE':\n db.session.delete(book)\n db.session.commit()\n return {\"message\": f\"Book {book.name} successfully deleted\"}\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"522724405","text":"from .models.zipline_app.fill import Fill\nfrom .models.zipline_app.order import Order\nfrom .models.zipline_app.asset import Asset\nfrom .models.zipline_app.placement import Placement\n\nfrom .widgets import AssetModelSelect2Widget, AccountModelSelect2Widget, ReadOnlyWidgetSimple, ReadOnlyWidgetAsset, ReadOnlyWidgetOrder, CustodianModelSelect2Widget, FillUnitWidget\nfrom django import forms\n\n# override widget in createview\n# http://stackoverflow.com/a/21407374/4126114\n# Override a Django generic class-based view widget\n# http://stackoverflow.com/a/27322032/4126114\nclass FillForm(forms.ModelForm):\n source=forms.CharField(required=False, widget = forms.HiddenInput())\n field_order = [\n 'pub_date', 'dedicated_to_order', 'fill_side', 'asset', 'fill_qty_unsigned', 'fill_unit',\n 'fill_price', 'category', 'is_internal', 'trade_date', 'settlement_date',\n 'custodian', 'fill_text',\n 'commission'\n ]\n class Meta:\n model=Fill\n exclude = [\"user\"]\n widgets = {\n 'pub_date': ReadOnlyWidgetSimple(),\n 'dedicated_to_order': ReadOnlyWidgetOrder(),\n 'custodian': CustodianModelSelect2Widget(),\n 'asset': ReadOnlyWidgetAsset(),\n 'fill_side': forms.HiddenInput(),\n 'fill_unit': FillUnitWidget(),\n }\n def clean_pub_date(self): return self.initial['pub_date'] #.strftime(\"%Y-%m-%d %H:%i:%s\")\n def clean_dedicated_to_order(self): return self.initial['dedicated_to_order']\n def clean_asset(self):\n aid = self.initial['asset']\n if not isinstance(aid, int): return aid\n return Asset.objects.get(id=aid)\n def clean_fill_side(self): return self.initial['fill_side']\n def clean_source(self): return self.initial['source'] if 'source' in self.initial else None\n def clean_fill_unit(self): return self.initial['fill_unit']\n\n def __init__(self, *args, **kwargs):\n super(FillForm, self).__init__(*args, **kwargs)\n self.fields['fill_unit'].widget.form_instance = self\n\nclass OrderForm(forms.ModelForm):\n source=forms.CharField(required=False, widget = forms.HiddenInput())\n field_order = [\n 'id',\n 'pub_date',\n 'user',\n 'order_side',\n 'account',\n 'asset',\n 'order_unit',\n 'order_qty_unsigned',\n\n # fields for tables.py\n 'asset_currency',\n 'order_amount',\n 'order_qty',\n\n 'am_type',\n 'order_type',\n 'limit_price',\n 'order_validity',\n 'validity_date',\n 'order_text',\n 'commission'\n ]\n\n class Meta:\n model=Order\n exclude=['user', 'order_bulk']\n widgets = {\n 'pub_date': ReadOnlyWidgetSimple(),\n 'asset': AssetModelSelect2Widget(),\n 'account': AccountModelSelect2Widget(),\n }\n def clean_pub_date(self): return self.initial['pub_date'] #.strftime(\"%Y-%m-%d %H:%i:%s\")\n def clean_source(self): return self.initial['source'] if 'source' in self.initial else None\n\n\nclass PlacementForm(forms.ModelForm):\n class Meta:\n model=Placement\n exclude = [\"date\", \"user\"]\n\n\nclass OrderDocumentForm(forms.Form):\n docfile = forms.FileField(\n widget=forms.ClearableFileInput(attrs={'multiple': True}),\n label='Select file(s)'\n )\n","sub_path":"zipline_app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"2944149","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('trueguide', '0003_place'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Photos',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('url', models.CharField(max_length=500)),\n ],\n ),\n migrations.AddField(\n model_name='place',\n name='photoid',\n field=models.ForeignKey(default=0, to='trueguide.Photos'),\n ),\n ]\n","sub_path":"Server/tg/trueguide/migrations/0004_auto_20150517_1209.py","file_name":"0004_auto_20150517_1209.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"63382637","text":"import numpy as np\nfrom PIL import Image\n\n\ndef hex_to_rgb(hex_str):\n hex_str = hex_str.strip()\n\n if hex_str[0] == '#':\n hex_str = hex_str[1:]\n\n if len(hex_str) != 6:\n raise ValueError('Input #{} is not in #RRGGBB format.'.format(hex_str))\n\n r, g, b = hex_str[:2], hex_str[2:4], hex_str[4:]\n rgb = [int(n, base=16) for n in [r, g, b]]\n return np.array(rgb)\n\n\ndef binary_mask(crop_mask, palette):\n bin_mask = []\n for x in crop_mask:\n temp = []\n for y in x:\n crop = 0\n for i, ch in enumerate(y):\n if ch >= y[crop]:\n crop = i\n temp.append(hex_to_rgb(palette[crop]))\n bin_mask.append(temp)\n return np.array(bin_mask, dtype=np.uint8)\n\n\ndef read_png(file):\n image = Image.open(file)\n return np.array(image)\n","sub_path":"tools/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"414201429","text":"import numpy as np\nclass Reverse_mode:\n def __init__(self,dimension=1):\n self.count = 0\n self.dimension=dimension\n\n def create_variable(self, val):\n if self.count >= self.dimension:\n raise Exception(\"Can not create more variable than pre-specified value\")\n #scalar case\n try:\n float(val)\n self.count+=1\n #position of the seed\n return Node_b(val)\n #vector case\n except:\n #check if user trying to create more variables than pre-specified dimension\n if self.count+len(val)>self.dimension:\n raise Exception(\"Can not create more variable than pre-specified value\")\n #record return list of Node\n node_ls=[]\n for i in range(0,len(val)):\n self.count+=1\n node_ls.append(Node_b(val[i]))\n return tuple(node_ls)\n\n def calculate_gradient(self,f,Node_ls):\n \"\"\"\n input:\n f: a function (actually a Node_b instance)\n Node_ls: a single variable or a list of variable in the function\n return:\n if Node_ls a single variable x, return df/dx as a numpy 1d array\n if Node_ls a list,suppose[x,y],return a gradient in the format [df/dx,df/dy] as a numpy 1d array\n \"\"\"\n if isinstance(f,Node_b):\n #output gradient,depends on the number of variable pass in in Node_ls\n root_node=f.backward()\n if type(Node_ls) is list:\n ls = []\n for i in Node_ls:\n ls.append(i.grad)\n ### resetting the gradient of root node so that they can be use again\n for k in root_node:\n k.reset()\n return (f.val,np.array(ls))\n else:\n grad=Node_ls.grad\n ### resetting the gradient of root node so that they can be use again\n for k in root_node:\n k.reset()\n return (f.val,np.array([grad]))\n else:\n raise ValueError(\"f should be a function in back_eval\")\n\nclass Node_b:\n def __init__(self, data):\n self._val = float(data)\n self._grad = 0.0\n\n self.parents = None\n\n def reset(self):\n self._grad=0.0\n\n @property\n def val(self):\n return self._val\n\n @property\n def grad(self):\n return self._grad\n\n def __repr__(self):\n\n return \"ad.Node_b(val={},grad={})\".format(self.val, self.grad)\n\n def __mul__(self, other):\n if (\n isinstance(other, int)\n or isinstance(other, float)\n or isinstance(other, Node_b)\n ):\n try:\n z = Node_b(self.val * other.val)\n z.parents = [(self, other.val), (other, self.val)]\n return z\n except AttributeError:\n z = Node_b(self.val * other)\n z.parents = [(self, other)]\n return z\n else:\n raise ValueError(\"inputs should either be Node instances, ints, or floats\")\n\n def __rmul__(self, other):\n return self.__mul__(other)\n\n def __truediv__(self, other):\n if (\n isinstance(other, int)\n or isinstance(other, float)\n or isinstance(other, Node_b)\n ):\n try:\n z = Node_b(self.val / other.val)\n z.parents = [(self, 1 / other.val), (other, -self.val / (other.val) ** 2)]\n return z\n except AttributeError:\n z = Node_b(self.val / other)\n z.parents = [(self, 1 / other)]\n return z\n else:\n raise ValueError(\"inputs should either be Node instances, ints, or floats\")\n\n def __rtruediv__(self, other):\n return other*(self**(-1))\n\n def __add__(self, other):\n if (\n isinstance(other, int)\n or isinstance(other, float)\n or isinstance(other, Node_b)\n ):\n try:\n z = Node_b(self.val + other.val)\n z.parents = [(self, 1.0), (other, 1.0)]\n return z\n except AttributeError:\n z = Node_b(self.val + other)\n z.parents = [(self, 1.0)]\n return z\n else:\n raise ValueError(\"inputs should either be Node instances, ints, or floats\")\n\n def __radd__(self, other):\n return self.__add__(other)\n\n def __sub__(self, other):\n if (\n isinstance(other, int)\n or isinstance(other, float)\n or isinstance(other, Node_b)\n ):\n try:\n z = Node_b(self.val - other.val)\n z.parents = [(self, 1.0), (other, -1.0)]\n return z\n except AttributeError:\n z = Node_b(self.val - other)\n z.parents = [(self, 1.0)]\n return z\n else:\n raise ValueError(\"inputs should either be Node instances, ints, or floats\")\n def __rsub__(self, other):\n if (\n isinstance(other, int)\n or isinstance(other, float)\n ):\n z = Node_b(other-self.val)\n z.parents=[(self, -1.0)]\n return z\n else:\n raise ValueError(\"inputs should either be Node instances, ints, or floats\")\n\n def __neg__(self):\n z = Node_b(-self.val )\n z.parents = [(self, -1.0)]\n return z\n\n def __pow__(self, other):\n try:\n float(other)\n z = Node_b(self.val ** other)\n z.parents = [(self, other * self.val ** (other - 1))]\n return z\n except:\n raise ValueError(\"power input should be an int or a float\")\n\n def __eq__(self, other):\n return self.val == other.val and self.grad == other.grad\n\n def backward(self, signal=1.0):\n #back propagation\n self._grad = signal\n root_node = backprop(self, signal)\n return root_node\n\ndef backprop(node, signal):\n #loop through all parents recursively and do the back propagation\n if node.parents is None:\n return node\n # track the root node so that we can reset that to use the variable again\n ls=[]\n for p, s in node.parents:\n new_signal = s*signal\n p._grad += new_signal\n temp=backprop(p, new_signal)\n if isinstance(temp,list):\n ls.extend(temp)\n else:\n ls.append(temp)\n return ls\n\n","sub_path":"jeeautodiff/reverse_mode.py","file_name":"reverse_mode.py","file_ext":"py","file_size_in_byte":6619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"549897859","text":"import astropy.units as u\nimport numpy as np\n\nimport grasshopper.interferometers as ifo\nimport grasshopper.sources as sources\n\nimport matplotlib.pyplot as plt\nplt.style.use(\"../thesis-style.mpl\")\n\naligo = ifo.AdvancedLIGO()\naligo_o1 = ifo.AdvancedLIGO(configuration=\"O1\")\nfigsize = (5.0, 2.5) # Fix this to use the Golden ratio please\n\nfig, ax = plt.subplots(1,1, figsize=figsize)\naligo.plot(ax)\naligo_o1.plot(ax)\nax.set_xlim([1e1, 2e3]);\nax.set_ylim([1e-23, 1e-19]);\nfig.tight_layout()\nfig.savefig(\"../figures/aligo-asd.pdf\", dpi=300)\n\n\n\n#########################\n\n\n# aligo = ifo.AdvancedLIGO()\n\n\n# figsize = (5.0, 2.5) # Fix this to use the Golden ratio please\n\n# fig, ax = plt.subplots(1,1, figsize=figsize)\n# aligo.plot(ax)\n\n# for mass in [30, 32, 50, 100]:\n# for mass2 in [30, 100, 2000]:\n# cbc = sources.CBC(frequencies=np.logspace(-4, 5, 1000) * u.hertz,\n# m1=mass*u.solMass, m2=mass2*u.solMass, r=0.8*1e9*u.parsec)\n# cbc.plot(ax, label=\"{}, {}\".format(mass, mass2))\n\n# ax.set_xlim([1e1, 2e3]);\n# ax.set_ylim([1e-23, 1e-19]);\n# fig.tight_layout()\n# fig.savefig(\"../figures/aligo-cbc.pdf\", dpi=300)\n\n\n###########################\n\n\nelisa = ifo.EvolvedLISA()\nfigsize = (5.0, 2.5) # Fix this to use the Golden ratio please\n\nfig, ax = plt.subplots(1,1, figsize=figsize)\nelisa.plot(ax)\n#ax.set_xlim([1e-1, 2e3]);\n#ax.set_ylim([1e-23, 1e-19]);\nfig.tight_layout()\nfig.savefig(\"../figures/elisa-asd.pdf\", dpi=300)\n\n\niligo = ifo.InitialLIGO()\nvirgo = ifo.VIRGO()\ngeo = ifo.GEO()\ntama = ifo.TAMA()\n\nfig, ax = plt.subplots(1,1, figsize=figsize)\niligo.plot(ax)\nvirgo.plot(ax)\ngeo.plot(ax)\ntama.plot(ax)\n\nax.set_xlim([1e1, 1e3]);\nax.set_ylim([1e-23, 1e-19]);\nfig.tight_layout()\nfig.savefig(\"../figures/first-gen-asd.pdf\")\n\n\nimport grasshopper.sources as sources\n\nccsn = sources.CoreCollapseSupernova()\nfig, ax = plt.subplots(1,1, figsize=figsize)\naligo.plot(ax)\nccsn.plot(ax)\nax.set_xlim([1e1, 1e3]);\n#ax.set_ylim([1e-23, 1e-19]);\nfig.tight_layout()\nfig.savefig(\"../figures/source-ccsn.pdf\")\n\nccsn = sources.Type1ASupernova(r=30*1000*u.parsec)\nfig, ax = plt.subplots(1,1, figsize=figsize)\naligo.plot(ax)\nccsn.plot(ax)\nax.set_xlim([1e-1, 1e3]);\nax.set_ylim([1e-23, 1e-19]);\nfig.tight_layout()\nfig.savefig(\"../figures/source-t1asn.pdf\")\n\n# Izz = .02#1e-4*10**38#0.28*10**34 / 0.366*1e-4 * (np.sqrt(8*np.pi)/15)\n# pulsar = sources.Pulsar(\"J0534+2200\", Izz=Izz*u.kilogram*u.meter**2)\n# aligo = ifo.AdvancedLIGO(obs_time = 365*3600*u.second)\n\n# fig, ax = plt.subplots(1,1, figsize=figsize)\n# aligo.plot(ax, configuration=\"O1\")\n# pulsar.plot(ax)\n# ax.set_xlim(10, 1000)\n# ax.set_ylim(1e-26, 1e-23)\n# plt.tight_layout()\n# fig.savefig(\"/home/daniel/papers/thesis/figures/crab-strain-o1.pdf\")\n","sub_path":"scripts/detector_asds.py","file_name":"detector_asds.py","file_ext":"py","file_size_in_byte":2720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"623356686","text":"def centrer(mot, N=20):\n L = (N - len(mot))/2\n space_left = \" \" * int(L)\n space_right = \" \" * int(L+0.5)\n return space_left + mot + space_right\n\n\ndef encadrer(mot, N=20, c=\"#\"):\n if N == -1:\n return c * (len(mot) + 4) + \"\\n\" \\\n + c + \" \" + mot + \" \" + c + \"\\n\" \\\n + c * (len(mot) + 4)\n else:\n return c * (N + 4) + \"\\n\" \\\n + c + \" \" + centrer(mot, N) + \" \" + c + \"\\n\" \\\n + c * (N + 4)\n\nprint(encadrer(\"pikach\",30))\nprint(encadrer(\"pikachu\",30))\nprint(encadrer(\"pikachut\",-1, c=\"=\"))\n","sub_path":"corrections/encadrer.py","file_name":"encadrer.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"381156851","text":"from django.db import models\n\nAREA_CHOICES = (('',''), ('Economy','Economy'), ('Efficiency','Efficiency'), ('Energy','Energy'), ('Environment','Environment'), )\n\nDEPRECIATION_CHOICES = (('',''), ('Straight Line','Straight Line'), )\n\nFEEDSTOCK_CHOICES = (('',''), ('FEEDSTOCK','Feedstock'), ('PRODUCT','Product'), ('WASTE','Waste'), ('CATALYST','Catalyst'), ('SOLVENT','Global Reagent and Solvent'), ('OTHER','Other'),)\nFUNCTION_CHOICES = (('',''), ('{{BASE_URL}}compounds/create/','Create Compound Library'), )\n\nO_OR_C_CHOICES = (('O','O'), ('C','C'))\n\nPROJECT_STATUS_CHOICES = (('ACTIVE','ACTIVE'), ('IN ACTIVE','IN ACTIVE'), ('IN PROGRESS','IN PROGRESS'))\nPROMOTOR_CHOICES = (('',''), ('PROMOTOR','PROMOTOR'), ('POISON','POISON'))\n\nSTEAM_CHOICES = (('Medium Pressure Steam','Medium Pressure Steam'), ('Low Pressure Steam', 'Low Pressure Steam'), ('High Pressure Steam','High Pressure Steam'), )\n\nSUBJECT_CHOICES = (('General Inquiry','General Inquiry'), ('Send Me More Info','Send Me More Info'), ('Registration Problem', 'Registration Problem'), ('Log-In Issue', 'Log-In Issue'))\nSUBMISSION_CHOICES = (('Submitted','Submitted'), ('Under Review','Under Review'), ('Accepted', 'Accepted'))\nSUPPORT_CHOICES = (('',''), ('GREENSCOPE','GREENSCOPE Values'), ('Help','Help'), ('Feature', 'Feature Request'), ('Other','Other'))\n\nTODO_STATUS_CHOICES = (('',''), ('Emergency','Emergency'), ('Important','Important'), ('Back Burner','Back Burner'), ('Complete','Complete'))\n\nWGK_CHOICES = (('',''), ('0','nwg'), ('1','WGK 1'), ('2','WGK 2'), ('3','WGK 3'))\n\nYN_CHOICES = (('',''), ('Y','Yes'), ('N','No'))\nONLY_YN_CHOICES = (('Y','Y'),)\n","sub_path":"Greenscope/constants/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"261232250","text":"import os\nimport json\nfrom django.conf import settings\nfrom decouple import config, Csv\nfrom configurations import Configuration, values\nimport logging.config\n\n\nclass Base(Configuration):\n # all the base settings here...\n # Build paths inside the project like this: os.path.join(BASE_DIR, ...)\n BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n # Quick-start development settings - unsuitable for production\n # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/\n\n SECRET_KEY = config('SECRET_KEY', default='')\n\n ALLOWED_HOSTS = []\n\n # Application definition\n\n INSTALLED_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 'crispy_forms',\n 'imagekit',\n\n 'allauth',\n 'allauth.account',\n 'allauth.socialaccount',\n\n 'core',\n 'user',\n ]\n\n MIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware',\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\n ROOT_URLCONF = \"sentive_saas.urls\"\n\n TEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [\n os.path.join(BASE_DIR, 'templates'),\n ],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n ]\n\n WSGI_APPLICATION = 'sentive_saas.wsgi.application'\n\n # Password validation\n # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators\n\n AUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n ]\n\n # Internationalization\n # https://docs.djangoproject.com/en/3.0/topics/i18n/\n\n LANGUAGE_CODE = 'fr-FR'\n\n TIME_ZONE = 'UTC'\n\n USE_I18N = True\n\n USE_L10N = True\n\n USE_TZ = True\n\n # Static files (CSS, JavaScript, Images)\n # https://docs.djangoproject.com/en/3.0/howto/static-files/\n SITE_ROOT = os.path.dirname(os.path.realpath(__file__))\n STATIC_ROOT = os.path.join(BASE_DIR, 'root')\n STATIC_URL = '/static/'\n STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'\n\n STATICFILES_DIRS = (\n os.path.join(BASE_DIR, \"static\"),\n )\n\n MEDIA_URL = '/media/'\n MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')\n\n CRISPY_TEMPLATE_PACK = 'bootstrap4'\n\n LOGIN_REDIRECT_URL = 'dashboard'\n LOGIN_URL = 'login'\n\n CRISPY_TEMPLATE_PACK = 'bootstrap4'\n\n # Authentification\n AUTHENTICATION_BACKENDS = (\n # Needed to login by username in Django admin, regardless of `allauth`\n 'django.contrib.auth.backends.ModelBackend',\n # `allauth` specific authentication methods, such as login by e-mail\n 'allauth.account.auth_backends.AuthenticationBackend',\n )\n\n AUTH_USER_MODEL = \"core.User\"\n\n SITE_ID = 1\n\n ACCOUNT_EMAIL_VERIFICATION = 'none'\n LOGIN_REDIRECT_URL = '/'\n\n \n # Logging Configuration\n # Clear prev config\n LOGGING_CONFIG = None\n\n # Get loglevel from env\n LOGLEVEL = os.getenv('DJANGO_LOGLEVEL', 'info').upper()\n\n logging.config.dictConfig({\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'console': {\n 'format': '%(asctime)s %(levelname)s [%(name)s:%(lineno)s] %(module)s %(process)d %(thread)d %(message)s',\n },\n },\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n 'formatter': 'console',\n },\n },\n 'loggers': {\n '': {\n 'level': LOGLEVEL,\n 'handlers': ['console', ],\n },\n },\n })\n\n\nclass Dev(Base):\n \"\"\"\n The in-development settings and the default configuration.\n \"\"\"\n DEBUG = True\n\n Base.ALLOWED_HOSTS += ['127.0.0.1', '192.168.99.100']\n '''\n DATABASES = {\n 'default': {\n 'ENGINE': config('SQL_DATABASE_ENGINE', default=''),\n 'NAME': config('SQL_DATABASE_NAME_DEV', default=''),\n 'USER': config('SQL_DATABASE_USER_DEV', default=''),\n 'PASSWORD': config('SQL_DATABASE_PASSWORD_DEV', default=''),\n 'HOST': config('SQL_DATABASE_HOST_DEV', default=''),\n 'PORT': config('SQL_DATABASE_PORT_DEV', default=''),\n }\n }\n '''\n\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(Base.BASE_DIR, 'db.sqlite3'),\n }\n }\n\n STRIPE_SECRET_KEY = config('STRIPE_SECRET_KEY', default='')\n STRIPE_PUBLISHABLE_KEY = config('STRIPE_PUBLISHABLE_KEY', default='')\n\n SESSION_COOKIE_SECURE = False\n\n\nclass Prod(Base):\n \"\"\"\n The in-production settings.\n \"\"\"\n DEBUG = False\n Base.ALLOWED_HOSTS += ['92.243.19.37', '192.168.99.100']\n TEMPLATE_DEBUG = DEBUG\n\n SESSION_COOKIE_SECURE = False\n","sub_path":"app/sentive_saas/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":6114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"279460861","text":"def mathsmarks():\n print(40)\ndef sciencemarks():\n print(50) \ndef englishmarks():\n print(60)\ndef hindimarks():\n print(70)\nfrom tkinter import *\nroot=Tk()\nroot.title(\"MARKS\")\nframe=Frame(root,borderwidth=5,bg=\"black\")\nframe.pack(side=LEFT,anchor=\"nw\",fill=\"x\")\nb1=Button(frame,text=\"MATHS MARKS\",command=mathsmarks)\nb1.pack(side=LEFT)\nb2=Button(frame,text=\"SCIENCE MARKS\",command=sciencemarks)\nb2.pack(side=LEFT)\nb3=Button(frame,text=\"ENGLISH MARKS\",command=englishmarks)\nb3.pack(side=LEFT)\nb4=Button(frame,text=\"HINDI MARKS\",command=hindimarks)\nb4.pack(side=LEFT)\nroot.mainloop()\n","sub_path":"Tkinter butons.py","file_name":"Tkinter butons.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"127045035","text":"groupmates = [\n {\n \"name\": \"Андрей\",\n \"surname\": \"Ким\",\n \"exams\": [\"Информатика\", \"ЭЭиС\", \"Web\"],\n \"marks\": [4, 3, 5]\n },\n {\n \"name\": \"Иван\",\n \"surname\": \"Масленников\",\n \"exams\": [\"История\", \"АиГ\", \"Информатика \"],\n \"marks\": [4, 4, 4]\n },\n {\n \"name\": \"Сергей\",\n \"surname\": \"Казаков\",\n \"exams\": [\"Электроооборудование\", \"Физика\", \"КТП\"],\n \"marks\": [5, 5, 5]\n },\n\n {\n \"name\": \"Алексей\",\n \"surname\": \"Стукалин\",\n \"exams\": [\"Философия\", \"ИС\", \"КТП\"],\n \"marks\": [2, 5, 5]\n },\n\n {\n \"name\": \"Мария\",\n \"surname\": \"Иванова\",\n \"exams\": [\"Информатика\", \"КГ\", \"Физика\"],\n \"marks\": [4, 5, 5]\n },\n {\n \"name\": \"Вероника\",\n \"surname\": \" Табакаева\",\n \"exams\": [\"Философия\", \"Экономика\", \"КТП\"],\n \"marks\": [5, 5, 5]\n }\n\n\n ]\n\ndef print_students(students):\n print(u\"Имя\".ljust(15), u\"Фамилия\".ljust(10), u\"Экзамены\".ljust(30), u\"Оценки\".ljust(20))\n for student in students:\n print(student[\"name\"].ljust(15), student[\"surname\"].ljust(10), str(student[\"exams\"]).ljust(30), str(student[\"marks\"]).ljust(20))\nprint_students(groupmates)\n\ndef fun (students,avg_mark):\n stud_list=[]\n for student in students:\n marks= sum(student[\"marks\"]) / len(student[\"marks\"])\n if marks >= avg_mark:\n stud_list.append( student[\"surname\"])\n\n\n return print(stud_list)\n\nfun(groupmates,int(input(\"Enter average mark \\n\")))","sub_path":"Web/django_env/Scripts/mygroup.py","file_name":"mygroup.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"539925190","text":"from django.shortcuts import render\nfrom .forms import InputForm\nfrom math import sin, tan\n\ndef As(b,d,fc,fy,Mu):\n phi=0.9\n Ru=Mu/(phi*b*d**2)*1000000\n rho_req=0.85*fc/fy*(1-(1-2*Ru/(0.85*fc))**0.5)\n rho_min=max(1.4/fy,0.25*fc**0.5/fy)\n beta_1=0.85-0.05*(fc-27.6)/6.9\n if beta_1<0.65:\n beta_1=0.65\n if beta_1>0.85:\n beta_1=0.85\n rho_max=0.43*0.85*fc/fy*beta_1\n rho=max(min(rho_min,1.33*rho_req),rho_req)\n if rho<=rho_max:\n return round(rho*b*d,0)\n else:\n return \"Increase beam section\"\ndef Vstotal(b,d,fc,fy,Vu):\n Vc=2*fc**0.5*b*d\n phi=0.85\n Vsreq=(Vu*1000-phi*Vc)/phi\n return round(Vsreq/(fy*d))\n\n\ndef compute(request):\n if request.method == 'POST':\n form=InputForm(data=request.POST,auto_id=\"%s\")\n if form.is_valid():\n fc = form.cleaned_data['fc']\n fy = form.cleaned_data['fy']\n gamma = form.cleaned_data['gamma']\n #d = form.cleaned_data['d']\n\n Cx = form.cleaned_data['Cx']\n Cy = form.cleaned_data['Cy']\n\n dp = form.cleaned_data['dp']\n S = form.cleaned_data['S']\n H = form.cleaned_data['H']\n c = form.cleaned_data['c']\n e = form.cleaned_data['e']\n t = form.cleaned_data['t']\n Pc = form.cleaned_data['Pc']\n Pt = form.cleaned_data['Pt']\n\n #Fxd = form.cleaned_data['Fxd']\n Fzd = form.cleaned_data['Fzd']\n Myd = form.cleaned_data['Myd']\n Mxd = form.cleaned_data['Mxd']\n #Fxl = form.cleaned_data['Fxl']\n Fzl = form.cleaned_data['Fzl']\n Myl = form.cleaned_data['Myl']\n Mxl = form.cleaned_data['Mxl']\n #Fxw = form.cleaned_data['Fxw']\n Fzw = form.cleaned_data['Fzw']\n Myw = form.cleaned_data['Myw']\n Mxw = form.cleaned_data['Mxw']\n #Fxe = form.cleaned_data['Fxe']\n Fze = form.cleaned_data['Fze']\n Mye = form.cleaned_data['Mye']\n Mxe = form.cleaned_data['Mxe']\n\n # Pile Cap Dimensions\n L = round(sin(1.047)*S+dp+2*e,1)\n B = S+dp+2*e\n w1 = dp+2*e\n w2 = dp+2*e\n Ldiag = round(((L-w1)**2+(B-w2)**2)**0.5,1)\n d = H - c\n So = S*(3.0)**0.5/2\n Y1 = 2*So/3\n Y2 = So/3\n ay = round(Y1-Cy/2+t,1)\n X = 0.5*(S-Cx)\n m = Y2-Cy/2\n ax = round(((X+m/tan(1.047))*sin(1.047))+t,1)\n radio_x = round(ax/d,3)\n radio_y = round(ay/d,3)\n Bs = 2*(Cx+Cy)\n A = dp/2+e\n\n\n # Pile capacity check\n Acap = L*B-sin(1.047)*Ldiag**2/2\n Gc = gamma*(H*0.001)*(Acap*0.000001)\n Gc = round(Gc,2)\n\n Fv1 = 1.0 * (Fzd + Gc) + 1.0 * Fzl\n My1 = Myd + Myl\n Mx1 = Mxd + Mxl\n x1 = 0.0; x2 = -0.5 * S; x3 = 0.5 *S\n y1 = 0.578 * S; y2 = -0.288 * S; y3 = -0.288 * S\n sum_xx = x1**2+x2**2+x3**2\n sum_yy = y1**2+y2**2+y3**2\n def Rp(F,Mx,My,n,x,y):\n return F/n+1000*Mx*y/sum_yy+1000*My*x/sum_xx\n Rp_1 = round(Rp(Fv1, Mx1, My1, 3, x1, y1))\n Rp_2 = round(Rp(Fv1, Mx1, My1, 3, x2, y2))\n Rp_3 = round(Rp(Fv1, Mx1, My1, 3, x3, y3))\n\n if Rp_1 <= Pc and Rp_1>=Pt and Rp_2 <= Pc and Rp_2>=Pt and Rp_3 <= Pc and Rp_3>=Pt:\n VS1 = 'orange'\n result1 = 'Satisfied'\n else:\n VS1 = \"red\"\n result1 = \"Failed\"\n # Pile reaction\n #Cx1 = 1.4 * Fxd\n Cz1 = 1.4 * Fzd\n Czg1 = 1.4 * (Fzd + Gc)\n Cmy1 = 1.4 * Myd\n Cmx1 = 1.4 * Mxd\n\n #Cx2 = 1.2 * Fxd + 1.6 * Fxl\n Cz2 = 1.2 * Fzd + 1.6 * Fzl\n Czg2 = 1.2 * (Fzd + Gc) + 1.6 * Fzl\n Cmy2 = 1.2 * Myd + 1.6 * Myl\n Cmx2 = 1.2 * Mxd + 1.6 * Mxl\n\n #Cx3 = 1.2 * Fxd + 1.6 * Fxw + 1.0 * Fxl\n Cz3 = 1.2 * Fzd + 1.6 * Fzw + 1.0 * Fzl\n Czg3 = 1.2 * (Fzd + Gc) + 1.6 * Fzw + 1.0 * Fzl\n Cmy3 = 1.2 * Myd + 1.6 * Myw + 1.0 * Myl\n Cmx3 = 1.2 * Mxd + 1.6 * Mxw + 1.0 * Mxl\n\n #Cx4 = 1.2 * Fxd + 1.0 * Fxe + 1.0 * Fxl\n Cz4 = 1.2 * Fzd + 1.0 * Fze + 1.0 * Fzl\n Czg4 = 1.2 * (Fzd + Gc) + 1.0 * Fze + 1.0 * Fzl\n Cmy4 = 1.2 * Myd + 1.0 * Mye + 1.0 * Myl\n Cmx4 = 1.2 * Mxd + 1.0 * Mxe + 1.0 * Mxl\n\n #Cx5 = 0.9 * Fxd + 1.6 * Fxw\n Cz5 = 0.9 * Fzd + 1.6 * Fzw\n Czg5 = 0.9 * (Fzd + Gc) + 1.6 * Fzw\n Cmy5 = 0.9 * Myd + 1.6 * Myw\n Cmx5 = 0.9 * Mxd + 1.6 * Mxw\n\n #Cx6 = 0.9 * Fxd + 1.6 * Fxe\n Cz6 = 0.9 * Fzd + 1.6 * Fze\n Czg6 = 0.9 * (Fzd + Gc) + 1.6 * Fze\n Cmy6 = 0.9 * Myd + 1.6 * Mye\n Cmx6 = 0.9 * Mxd + 1.6 * Mxe\n\n Rp11 = round(Rp(Czg1, Cmx1, Cmy1, 3, x1, y1), 1)\n Rp21 = round(Rp(Czg1, Cmx1, Cmy1, 3, x2, y2), 1)\n Rp31 = round(Rp(Czg1, Cmx1, Cmy1, 3, x3, y3), 1)\n Rp12 = round(Rp(Czg2, Cmx2, Cmy2, 3, x1, y1), 1)\n Rp22 = round(Rp(Czg2, Cmx2, Cmy2, 3, x2, y2), 1)\n Rp32 = round(Rp(Czg2, Cmx2, Cmy2, 3, x3, y3), 1)\n Rp13 = round(Rp(Czg3, Cmx3, Cmy3, 3, x1, y1), 1)\n Rp23 = round(Rp(Czg3, Cmx3, Cmy3, 3, x2, y2), 1)\n Rp33 = round(Rp(Czg3, Cmx3, Cmy3, 3, x3, y3), 1)\n Rp14 = round(Rp(Czg4, Cmx4, Cmy4, 3, x1, y1), 1)\n Rp24 = round(Rp(Czg4, Cmx4, Cmy4, 3, x2, y2), 1)\n Rp34 = round(Rp(Czg4, Cmx4, Cmy4, 3, x3, y3), 1)\n Rp15 = round(Rp(Czg5, Cmx5, Cmy5, 3, x1, y1), 1)\n Rp25 = round(Rp(Czg5, Cmx5, Cmy5, 3, x2, y2), 1)\n Rp35 = round(Rp(Czg5, Cmx5, Cmy5, 3, x3, y3), 1)\n Rp16 = round(Rp(Czg6, Cmx6, Cmy6, 3, x1, y1), 1)\n Rp26 = round(Rp(Czg6, Cmx6, Cmy6, 3, x2, y2), 1)\n Rp36 = round(Rp(Czg6, Cmx6, Cmy6, 3, x3, y3), 1)\n\n # Two way shear design\n phiVc = round(0.85 *d/max(ax,ay) * (1+2*d/(Cx+Cy)) * (0.17 * (fc) ** 0.5 * Bs * d) * 0.001, 2)\n\n VV1 = '%.2f' % (Czg1 / phiVc)\n if (Czg1 / phiVc) < 1:\n vs1 = \"Pass\"\n co_vs1 = \"orange\"\n else:\n vs1 = \"Fail\"\n co_vs1 = \"red\"\n VV2 = '%.2f' % (Czg2 / phiVc)\n if (Czg2 / phiVc) < 1:\n vs2 = \"Pass\"\n co_vs2 = \"orange\"\n else:\n vs2 = \"Fail\"\n co_vs2 = \"red\"\n VV3 = '%.2f' % (Czg3 / phiVc)\n if (Czg3 / phiVc) < 1:\n vs3 = \"Pass\"\n co_vs3 = \"orange\"\n else:\n vs3 = \"Fail\"\n co_vs3 = \"red\"\n VV4 = '%.2f' % (Czg4 / phiVc)\n if (Czg4 / phiVc) < 1:\n vs4 = \"Pass\"\n co_vs4 = \"orange\"\n else:\n vs4 = \"Fail\"\n co_vs4 = \"red\"\n VV5 = '%.2f' % (Czg5 / phiVc)\n if (Czg5 / phiVc) < 1:\n vs5 = \"Pass\"\n co_vs5 = \"orange\"\n else:\n vs5 = \"Fail\"\n co_vs5 = \"red\"\n VV6 = '%.2f' % (Czg6 / phiVc)\n if (Czg6 / phiVc) < 1:\n vs6 = \"Pass\"\n co_vs6 = \"orange\"\n else:\n vs6 = \"Fail\"\n co_vs6 = \"red\"\n\n # One Way Shear\n if radio_x >= 1:\n Lcx = (0.5 * (X + A + (A + m) / tan(1.047)-d/sin(1.047)) * tan(1.047) + A) / sin(1.047)\n phiVc_x = round(0.85 * (0.17 * (fc) ** 0.5 * Lcx * d) * 0.001, 1)\n check1 = \"Concrete shear strength for one way wide beam action:\"\n check2 = \"$\\phi V_c=0.85\\cdot(0.17\\sqrt{f'_c} \\cdot L_{cx}\\cdot d)=$\"+str(phiVc_x)+\"kN\"\n check3 = \"$L_{cx}=(0.5(X+A+(A+m)ctg(\\pi/3)-d/sin(\\pi/3))*tan(\\pi/3)+A)/sin(\\pi/3)=$\"+str(round(Lcx))+\"mm\"\n else:\n kx = min(round(d/ax * (3.5-2.5*ax/d),2),10)\n Lcx = (0.5 * (X + A + (A + m) / tan(1.047)) * tan(1.047) + A) / sin(1.047)\n phiVc_x = round(0.85 * kx * (0.17 * (fc) ** 0.5 * Lcx * d) * 0.001, 1)\n check1 = \"Concrete shear strength for one way deep beam action:\"\n check2 = \"$\\phi V_c=0.85k\\cdot(0.17\\sqrt{f'_c} \\cdot L_{cx}\\cdot d)=$\"+str(phiVc_x)+\"kN;\"+\"$\\quad k=\\cfrac{d}{a}\\cdot (3.5-2.5 \\cfrac {a}{d})$\"\n check3 = \"$L_{cx}=(0.5(X+A+(A+m)ctg(\\pi/3))*tan(\\pi/3)+A)/sin(\\pi/3)=$\"+str(round(Lcx))+\"mm\"\n Vux1 = max(Rp21, Rp31)\n Vux2 = max(Rp22, Rp32)\n Vux3 = max(Rp23, Rp33)\n Vux4 = max(Rp24, Rp34)\n Vux5 = max(Rp25, Rp35)\n Vux6 = max(Rp26, Rp36)\n V1 = '%.2f' % (Vux1 / phiVc_x)\n if (Vux1 / phiVc_x) < 1:\n s1 = \"Pass\"\n co_s1 = \"orange\"\n else:\n s1 = \"Fail\"\n co_s1 = \"red\"\n V2 = '%.2f' % (Vux2 / phiVc_x)\n if (Vux2 / phiVc_x) < 1:\n s2 = \"Pass\"\n co_s2 = \"orange\"\n else:\n s2 = \"Fail\"\n co_s2 = \"red\"\n V3 = '%.2f' % (Vux3 / phiVc_x)\n if (Vux3 / phiVc_x) < 1:\n s3 = \"Pass\"\n co_s3 = \"orange\"\n else:\n s3 = \"Fail\"\n co_s3 = \"red\"\n V4 = '%.2f' % (Vux4 / phiVc_x)\n if (Vux4 / phiVc_x) < 1:\n s4 = \"Pass\"\n co_s4 = \"orange\"\n else:\n s4 = \"Fail\"\n co_s4 = \"red\"\n V5 = '%.2f' % (Vux5 / phiVc_x)\n if (Vux5 / phiVc_x) < 1:\n s5 = \"Pass\"\n co_s5 = \"orange\"\n else:\n s5 = \"Fail\"\n co_s5 = \"red\"\n V6 = '%.2f' % (Vux6 / phiVc_x)\n if (Vux6 / phiVc_x) < 1:\n s6 = \"Pass\"\n co_s6 = \"orange\"\n else:\n s6 = \"Fail\"\n co_s6 = \"red\"\n if radio_y >= 1:\n Lcy = 2 * A + 2 * ((ay - t - d) + A) / tan(1.047)\n phiVc_y = round(0.85 * (0.17 * (fc) ** 0.5 * Lcy * d) * 0.001, 1)\n check4 = \"Concrete shear strength for one way wide beam action:\"\n check5 = \"$\\phi V_c=0.85\\cdot(0.17\\sqrt{f'_c} \\cdot L_{cx}\\cdot d)=$\"+str(phiVc_y)+\"kN\"\n check6 = \"$L_{cx}=2A+2((a_y-t-d)+A)/tan(\\pi/3)=$\"+str(round(Lcy))+\"mm\"\n else:\n ky = min(round(d/ax * (3.5-2.5*ax/d),2),10)\n Lcy = 2 * A + 2 * ((ay - t - d) + A) / tan(1.047)\n phiVc_y = round(0.85 * ky * (0.17 * (fc) ** 0.5 * Lcy * d) * 0.001, 1)\n check4 = \"Concrete shear strength for one way deep beam action:\"\n check5 = \"$\\phi V_c=0.85k\\cdot(0.17\\sqrt{f'_c} \\cdot L_{cx}\\cdot d)=$\"+str(phiVc_y)+\"kN;\"+\"$\\quad k=\\cfrac{d}{a}\\cdot (3.5-2.5 \\cfrac {a}{d})$\"\n check6 = \"$L_{cx}=2A+2((a_y-t-d)+A)/tan(\\pi/3)==$\"+str(round(Lcy))+\"mm\"\n VVV1 = '%.2f' % (Rp11 / phiVc_y)\n if (Rp11 / phiVc_y) < 1:\n vvs1 = \"Pass\"\n co_vvs1 = \"orange\"\n else:\n vvs1 = \"Fail\"\n co_vvs1 = \"red\"\n VVV2 = '%.2f' % (Rp12 / phiVc_y)\n if (Rp12 / phiVc_y) < 1:\n vvs2 = \"Pass\"\n co_vvs2 = \"orange\"\n else:\n vvs2 = \"Fail\"\n co_vvs2 = \"red\"\n VVV3 = '%.2f' % (Rp13 / phiVc_y)\n if (Rp13 / phiVc_y) < 1:\n vvs3 = \"Pass\"\n co_vvs3 = \"orange\"\n else:\n vvs3 = \"Fail\"\n co_vvs3 = \"red\"\n VVV4 = '%.2f' % (Rp14 / phiVc_y)\n if (Rp14 / phiVc_y) < 1:\n vvs4 = \"Pass\"\n co_vvs4 = \"orange\"\n else:\n vvs4 = \"Fail\"\n co_vvs4 = \"red\"\n VVV5 = '%.2f' % (Rp15 / phiVc_y)\n if (Rp15 / phiVc_y) < 1:\n vvs5 = \"Pass\"\n co_vvs5 = \"orange\"\n else:\n vvs5 = \"Fail\"\n co_vvs5 = \"red\"\n VVV6 = '%.2f' % (Rp16 / phiVc_y)\n if (Rp16 / phiVc_y) < 1:\n vvs6 = \"Pass\"\n co_vvs6 = \"orange\"\n else:\n vvs6 = \"Fail\"\n co_vvs6 = \"red\"\n\n # Bending Reinforcement\n def As(M,B):\n rho_min = 0.0018\n As_min=rho_min*B*H\n R = M * 10 ** 6 / (0.9 * B * d ** 2)\n rho_req = 0.85 * fc / fy * (1 - (1 - 2 * R / (0.85 * fc)) ** 0.5)\n As_req = rho_req * B * (H-c)\n return max(As_min,As_req)\n\n BX = round(A * (1.5 + 0.5 * tan(1.047))/sin(1.047), 1)\n Mux1 = round(max(Rp21,Rp31) * ax * 0.001, 1)\n Mux2 = round(max(Rp22,Rp32) * ax * 0.001, 1)\n Mux3 = round(max(Rp23,Rp33) * ax * 0.001, 1)\n Mux4 = round(max(Rp24,Rp34) * ax * 0.001, 1)\n Mux5 = round(max(Rp25,Rp35) * ax * 0.001, 1)\n Mux6 = round(max(Rp26,Rp36) * ax * 0.001, 1)\n\n Asx1 = '%.0f' % float(As(Mux1, BX))\n Asx2 = '%.0f' % float(As(Mux2, BX))\n Asx3 = '%.0f' % float(As(Mux3, BX))\n Asx4 = '%.0f' % float(As(Mux4, BX))\n Asx5 = '%.0f' % float(As(Mux5, BX))\n Asx6 = '%.0f' % float(As(Mux6, BX))\n\n BY = round(2*A*(1+1/tan(1.047)),1)\n Muy1 = round(Rp11*ay*0.001,1)\n Muy2 = round(Rp12 * ay * 0.001, 1)\n Muy3 = round(Rp13 * ay * 0.001, 1)\n Muy4 = round(Rp14 * ay * 0.001, 1)\n Muy5 = round(Rp15 * ay * 0.001, 1)\n Muy6 = round(Rp16 * ay * 0.001, 1)\n\n\n Asy1 = '%.0f' % float(As(Muy1,BY))\n Asy2 = '%.0f' % float(As(Muy2,BY))\n Asy3 = '%.0f' % float(As(Muy3,BY))\n Asy4 = '%.0f' % float(As(Muy4,BY))\n Asy5 = '%.0f' % float(As(Muy5,BY))\n Asy6 = '%.0f' % float(As(Muy6,BY))\n\n Czg1 = round(Czg1,1)\n Czg2 = round(Czg2, 1)\n Czg3 = round(Czg3, 1)\n Czg4 = round(Czg4, 1)\n Czg5 = round(Czg5, 1)\n Czg6 = round(Czg6, 1)\n\n\n return render(request, 'pile_cap_3.html', {'form': form,'Gc':Gc,'Fv1':Fv1,'My1':My1,'Mx1':Mx1,\n 'L':L,'B':B,'w1':w1,'w2':w2,'Ldiag':Ldiag,'d':d,'ax':ax,'ay':ay,'radio_x':radio_x,'radio_y':radio_y,\n 'Rp_1':Rp_1,'Rp_2':Rp_2,'Rp_3':Rp_3,'VS1':VS1,'result1':result1,\n 'Rp11':Rp11,'Rp21':Rp21,'Rp31':Rp31,'Rp12':Rp12,'Rp22':Rp22,'Rp32':Rp32,\n 'Rp13':Rp13,'Rp23':Rp23,'Rp33':Rp33,'Rp14':Rp14,'Rp24':Rp24,'Rp34':Rp34,\n 'Rp15': Rp15, 'Rp25': Rp25, 'Rp35': Rp35, 'Rp16': Rp16,\n 'Rp26': Rp26, 'Rp36': Rp36,\n 'phiVc':phiVc,'Czg1':Czg1,'Czg2':Czg2,'Czg3':Czg3,'Czg4':Czg4,'Czg5':Czg5,'Czg6':Czg6,\n 'VV1': VV1, 'VV2': VV2, 'VV3': VV3, 'VV4': VV4, 'VV5': VV5,\n 'VV6': VV6, 'vs1': vs1, 'vs2': vs2, 'vs3': vs3, 'vs4': vs4,\n 'vs5': vs5, 'vs6': vs6,\n 'co_vs1': co_vs1, 'co_vs2': co_vs2, 'co_vs3': co_vs3,\n 'co_vs4': co_vs4, 'co_vs5': co_vs5, 'co_vs6': co_vs6,\n 'check1':check1,'check2':check2,'check3':check3,'check4':check4,'check5':check5,'check6':check6,\n 'Vux1':Vux1,'Vux2':Vux2,'Vux3':Vux3,'Vux4':Vux4,'Vux5':Vux5,'Vux6':Vux6,\n 'V1': V1, 'V2': V2, 'V3': V3, 'V4': V4, 'V5': V5,\n 'V6': V6, 's1': s1, 's2': s2, 's3': s3, 's4': s4,\n 's5': s5, 's6': s6,\n 'co_s1': co_s1, 'co_s2': co_s2, 'co_s3': co_s3,\n 'co_s4': co_s4, 'co_s5': co_s5, 'co_s6': co_s6,\n 'VVV1': VVV1, 'VVV2': VVV2, 'VVV3': VVV3, 'VVV4': VVV4, 'VVV5': VVV5,\n 'VVV6': VVV6, 'vvs1': vvs1, 'vvs2': vvs2, 'vvs3': vvs3, 'vvs4': vvs4,\n 'vvs5': vvs5, 'vvs6': vvs6,\n 'co_vvs1': co_vvs1, 'co_vvs2': co_vvs2, 'co_vvs3': co_vvs3,\n 'co_vvs4': co_vvs4, 'co_vvs5': co_vvs5, 'co_vvs6': co_vvs6,\n 'BX':BX,'BY':BY,\n 'Mux1': Mux1, 'Mux2': Mux2, 'Mux3': Mux3, 'Mux4': Mux4,\n 'Mux5': Mux5, 'Mux6': Mux6,\n 'Asx1': Asx1, 'Asx2': Asx2, 'Asx3': Asx3, 'Asx4': Asx4,\n 'Asx5': Asx5, 'Asx6': Asx6,\n 'Muy1':Muy1,'Muy2':Muy2,'Muy3':Muy3,'Muy4':Muy4,'Muy5':Muy5,'Muy6':Muy6,\n 'Asy1':Asy1,'Asy2':Asy2,'Asy3':Asy3,'Asy4':Asy4,'Asy5':Asy5,'Asy6':Asy6,})\n else:\n form = InputForm(auto_id=\"%s\")\n return render(request,'pile_cap_3.html',{'form':form})\n","sub_path":"pile_cap_3/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":18091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"433567535","text":"\"\"\"\nThis is the decorator for login enforcement\n\"\"\"\nfrom functools import wraps\nimport json\nimport os\n\nfrom flask import request\nfrom flask import Response\nfrom qube.src.commons.context import AuthContext\nimport requests\n\n\nauth_url = os.getenv('AUTH_API_URL', 'https://api.qubeship.io/v1/auth')\n\n\ndef validate_with_qubeship_auth(auth_token):\n \"\"\" check if the auth_token is valid\n \"\"\"\n headers = {'content-type': 'application/json', 'Authorization': auth_token}\n # payload = {'token': auth_token}\n resp = requests.get(auth_url + '/user',\n headers=headers)\n return resp.text, resp.status_code\n\n\ndef login_required(f):\n \"\"\"create parser\n \"\"\"\n\n def auth_required():\n \"\"\" return error message\n \"\"\"\n data = {\n 'error': 'github authorization required'\n }\n js = json.dumps(data)\n\n resp = Response(js, status=401, mimetype='application/json')\n return resp\n\n def unsupported_token():\n \"\"\" return error message\n \"\"\"\n data = {\n 'error': 'master tokens are forbidden instead use org tokens'\n }\n js = json.dumps(data)\n\n resp = Response(js, status=403, mimetype='application/json')\n return resp\n\n @wraps(f)\n def decorated_function(*args, **kwargs):\n \"\"\" definition of login_required\n \"\"\"\n bearer_token = request.headers.get('Authorization')\n if not bearer_token:\n return auth_required()\n\n auth_token = bearer_token.split()[1]\n if not auth_token:\n return auth_required()\n\n # validate auth_token\n response, status_code = validate_with_qubeship_auth(auth_token)\n if status_code != 200:\n return auth_required()\n\n userinfo = json.loads(response)\n if userinfo['type'] != \"org\":\n return unsupported_token()\n is_system_user = userinfo['is_system_user'] \\\n if 'is_system_user' in userinfo else False\n auth_context = AuthContext(userinfo['tenant']['id'],\n userinfo['tenant']['name'],\n userinfo['tenant']['orgs'][0]['id'],\n userinfo['tenant']['orgs'][0]['name'],\n userinfo['id'], 'auth_not_implemented',\n is_system_user)\n kwargs['authcontext'] = {\n 'context': auth_context\n }\n\n return f(*args, **kwargs)\n\n return decorated_function\n","sub_path":"qube/src/api/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":2537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"396190021","text":"from binascii import hexlify\nfrom utils import TailableProc\nfrom ephemeral_port_reserve import reserve\n\nimport src.lpd.python_binding.common_pb2 as common_pb2\nimport src.lpd.python_binding.channel_pb2 as channel_pb2\nimport src.lpd.python_binding.payment_pb2 as payment_pb2\nimport src.lpd.python_binding.routing_pb2 as routing_pb2\nfrom src.lpd.python_binding.channel_pb2_grpc import ChannelServiceStub\nfrom src.lpd.python_binding.payment_pb2_grpc import PaymentServiceStub\nfrom src.lpd.python_binding.routing_pb2_grpc import RoutingServiceStub\n\nimport grpc\nimport logging\nimport os\nimport time\nimport codecs\n\n\nclass LpdD(TailableProc):\n\n def __init__(self, lightning_dir, bitcoind, port):\n super().__init__(lightning_dir, 'lpd({})'.format(port))\n self.lightning_dir = lightning_dir\n self.bitcoind = bitcoind\n self.port = port\n self.rpc_port = str(reserve())\n self.prefix = 'lpd'\n\n self.cmd_line = [\n 'bin/lpd',\n '--rpclisten=127.0.0.1:{}'.format(self.rpc_port),\n ]\n\n if not os.path.exists(lightning_dir):\n os.makedirs(lightning_dir)\n\n def start(self):\n super().start()\n self.wait_for_log('RPC server listening on')\n self.wait_for_log('Done catching up block hashes')\n time.sleep(5)\n\n logging.info('LPD started (pid: {})'.format(self.proc.pid))\n\n def stop(self):\n self.proc.terminate()\n time.sleep(3)\n if self.proc.poll() is None:\n self.proc.kill()\n self.proc.wait()\n super().save_log()\n\n\nclass LpdNode(object):\n\n displayName = 'lpd'\n\n def __init__(self, lightning_dir, lightning_port, bitcoind, executor=None, node_id=0):\n self.bitcoin = bitcoind\n self.executor = executor\n self.daemon = LpdD(lightning_dir, bitcoind, port=lightning_port)\n self.rpc = LpdRpc(self.daemon.rpc_port)\n self.logger = logging.getLogger('lpd-node({})'.format(lightning_port))\n self.myid = None\n self.node_id = node_id\n\n def id(self):\n if not self.myid:\n self.myid = self.info()['id']\n return self.myid\n\n def ping(self):\n \"\"\" Simple liveness test to see if the node is up and running\n\n Returns true if the node is reachable via RPC, false otherwise.\n \"\"\"\n try:\n self.rpc.routing.GetInfo(common_pb2.Void())\n return True\n except Exception as e:\n print(e)\n return False\n\n def peers(self):\n peers = self.rpc.routing.ListPeers(common_pb2.Void()).peers\n return [p.pub_key for p in peers]\n\n def check_channel(self, remote):\n \"\"\" Make sure that we have an active channel with remote\n \"\"\"\n self_id = self.id()\n remote_id = remote.id()\n channels = self.rpc.channel.List(channel_pb2.ChannelFilter()).channels\n channel_by_remote = {c.remote_pubkey: c for c in channels}\n if remote_id not in channel_by_remote:\n self.logger.warning(\"Channel {} -> {} not found\".format(self_id, remote_id))\n return False\n\n channel = channel_by_remote[remote_id]\n self.logger.debug(\"Channel {} -> {} state: {}\".format(self_id, remote_id, channel))\n return channel.active\n\n def addfunds(self, bitcoind, satoshis):\n req = wallet_pb2.NewAddressRequest(type=1)\n addr = self.rpc.wallet.NewAddress(req).address\n bitcoind.rpc.sendtoaddress(addr, float(satoshis) / 10**8)\n self.daemon.wait_for_log(\"Inserting unconfirmed transaction\")\n bitcoind.rpc.generate(1)\n self.daemon.wait_for_log(\"Marking unconfirmed transaction\")\n\n # The above still doesn't mean the wallet balance is updated,\n # so let it settle a bit\n i = 0\n while self.rpc.wallet.WalletBalance(wallet_pb2.WalletBalanceRequest()).total_balance == satoshis and i < 30:\n time.sleep(1)\n i += 1\n assert(self.rpc.wallet.WalletBalance(wallet_pb2.WalletBalanceRequest()).total_balance == satoshis)\n\n def openchannel(self, node_id, host, port, satoshis):\n peers = self.rpc.routing.ListPeers(common_pb2.Void).peers\n peers_by_pubkey = {p.pub_key: p for p in peers}\n if node_id not in peers_by_pubkey:\n raise ValueError(\"Could not find peer {} in peers {}\".format(node_id, peers))\n peer = peers_by_pubkey[node_id]\n self.rpc.channel.Open(channel_pb2.OpenChannelRequest(\n node_pubkey=codecs.decode(peer.pub_key, 'hex_codec'),\n local_funding_amount=common_pb2.Satoshi(value=satoshis),\n push_sat=0\n ))\n\n # Somehow broadcasting a tx is slow from time to time\n time.sleep(5)\n\n def getchannels(self):\n req = routing_pb2.ChannelGraphRequest()\n rep = self.rpc.routing.DescribeGraph(req)\n channels = []\n\n for e in rep.edges:\n channels.append((e.node1_pub, e.node2_pub))\n channels.append((e.node2_pub, e.node1_pub))\n return channels\n\n def getnodes(self):\n req = routing_pb2.ChannelGraphRequest()\n rep = self.rpc.routing.DescribeGraph(req)\n nodes = set([n.pub_key for n in rep.nodes]) - set([self.id()])\n return nodes\n\n def invoice(self, amount):\n req = payment_pb2.Invoice(value=common_pb2.Satoshi(value=int(amount)))\n rep = self.rpc.payment.AddInvoice(req)\n return rep.payment_request\n\n def send(self, bolt11):\n req = payment_pb2.SendRequest(payment_request=bolt11)\n res = self.rpc.payment.SendPaymentSync(req)\n if res.payment_error:\n raise ValueError(res.payment_error)\n return hexlify(res.payment_preimage)\n\n def connect(self, host, port, node_id):\n addr = routing_pb2.LightningAddress(pubkey=node_id, host=\"{}:{}\".format(host, port))\n req = routing_pb2.ConnectPeerRequest(addr=addr, perm=True)\n logging.debug(self.rpc.routing.ConnectPeer(req))\n\n def info(self):\n r = self.rpc.routing.GetInfo(common_pb2.Void())\n return {\n 'id': r.identity_pubkey,\n 'blockheight': r.block_height,\n }\n\n def block_sync(self, blockhash):\n print(\"Waiting for node to learn about\", blockhash)\n self.daemon.wait_for_log('NTFN: New block: height=([0-9]+), sha={}'.format(blockhash))\n\n def restart(self):\n self.daemon.stop()\n time.sleep(5)\n self.daemon.start()\n self.rpc = LpdRpc(self.daemon.rpc_port)\n\n def check_route(self, node_id, amount):\n try:\n req = routing_pb2.QueryRoutesRequest(pub_key=node_id, amt=int(amount/1000), num_routes=1)\n r = self.rpc.routing.QueryRoutes(req)\n except grpc._channel._Rendezvous as e:\n if str(e).find(\"unable to find a path to destination\") > 0:\n return False\n raise\n return True\n\n\nclass LpdRpc(object):\n def __init__(self, rpc_port):\n self.port = rpc_port\n cred = grpc.ssl_channel_credentials(open('tls.cert').read())\n channel = grpc.secure_channel('localhost:{}'.format(rpc_port), cred)\n self.channel = ChannelServiceStub(channel)\n self.payment = PaymentServiceStub(channel)\n self.routing = RoutingServiceStub(channel)\n","sub_path":"lpd.py","file_name":"lpd.py","file_ext":"py","file_size_in_byte":7282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"4251412","text":"\"\"\"The AWS Lambda emmaa-test-stats definition.\n\nThis file contains the function that will be run when Lambda is triggered. It\nmust be placed on s3, which can either be done manually (not recommended) or\nby running:\n\n$ python update_lambda.py test_stats.py emmaa-test-stats\n\nin this directory.\n\"\"\"\n\nimport boto3\nfrom datetime import datetime\n\nJOB_DEF = 'emmaa_jobdef'\nQUEUE = 'emmaa-models-update-test'\nPROJECT = 'aske'\nPURPOSE = 'update-emmaa-test-stats'\nBRANCH = 'origin/master'\n\n\ndef lambda_handler(event, context):\n \"\"\"Create a batch job to generate model statistics.\n\n This function is designed to be placed on lambda, taking the event and\n context arguments that are passed, and extracting the names of the\n uploaded (which includes changed) model or test definitions on s3.\n Lambda is configured to be triggered by any such changes, and will\n automatically run this script.\n\n Parameters\n ----------\n event : dict\n A dictionary containing metadata regarding the triggering event. In\n this case, we are expecting 'Records', each of which contains a record\n of a file that was added (or changed) on s3.\n context : object\n This is an object containing potentially useful context provided by\n Lambda. See the documentation cited above for details.\n\n Returns\n -------\n ret : dict\n A dict containing 'statusCode', with a valid HTTP status code, and any\n other data to be returned to Lambda.\n \"\"\"\n batch = boto3.client('batch')\n records = event['Records']\n for rec in records:\n try:\n model_key = rec['s3']['object']['key']\n except KeyError:\n pass\n model_name = model_key.split('/')[1]\n test_corpus = model_key.split('/')[-1][8:-25]\n if not test_corpus:\n test_corpus = 'large_corpus_tests'\n core_command = 'bash scripts/git_and_run.sh'\n if BRANCH is not None:\n core_command += f' --branch {BRANCH}'\n core_command += (' python scripts/run_model_stats_from_s3.py'\n f' --model {model_name} --stats_mode tests'\n f' --tests {test_corpus}')\n print(core_command)\n cont_overrides = {\n 'command': ['python', '-m', 'indra.util.aws', 'run_in_batch',\n '--project', PROJECT, '--purpose', PURPOSE,\n core_command]\n }\n now_str = datetime.utcnow().strftime('%Y%m%d_%H%M%S')\n ret = batch.submit_job(\n jobName=f'{model_name}_{test_corpus}_stats_{now_str}',\n jobQueue=QUEUE, jobDefinition=JOB_DEF,\n containerOverrides=cont_overrides)\n job_id = ret['jobId']\n\n return {'statusCode': 200, 'result': 'SUCCESS', 'job_id': job_id}\n","sub_path":"emmaa/aws_lambda_functions/test_stats.py","file_name":"test_stats.py","file_ext":"py","file_size_in_byte":2789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"414468254","text":"#!/usr/bin/env python\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nif __name__ == '__main__':\n x = np.linspace(-np.pi, np.pi, 256, endpoint=True) # type: np.array\n C, S = np.cos(x), np.sin(x)\n plt.plot(x, C, color='red', linewidth='2.4', linestyle='--', label='cosine')\n plt.plot(x, S, color='blue', label='sine')\n plt.xlim(x.min() * 1.1, x.max() * 1.1)\n plt.ylim(C.min() * 1.1, C.max() * 1.1)\n plt.xticks(np.linspace(-np.pi, np.pi, 5, endpoint=True),\n [r'$-\\pi$', r'$-\\pi/2$', r'$0$', r'$\\pi/2$', r'$\\pi$'])\n axis = plt.gca()\n axis.spines['right'].set_color('none')\n axis.spines['top'].set_color('none')\n axis.xaxis.set_ticks_position('bottom')\n axis.spines['bottom'].set_position(('data', 0))\n axis.yaxis.set_ticks_position('left')\n axis.spines['left'].set_position(('data', 0))\n plt.legend(loc='upper left')\n t = 2 * np.pi / 3\n plt.plot([t, t], [0, np.cos(t)], color='red', linestyle='--')\n plt.scatter([t, ], [np.cos(t), ], 50, color='red')\n plt.annotate(r'$\\cos(\\frac{2\\pi}{3})=\\frac{1}{2}$', xy=(t, np.cos(t)), xycoords='data', xytext=(10, 30),\n textcoords='offset points', fontsize='16', color='red',\n arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=0.2', color='red'))\n plt.show()\n","sub_path":"matplotlib_practice.py","file_name":"matplotlib_practice.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"254757114","text":"class Cache():\n def __init__(self, size_limit=800):\n self._cache = {}\n self._min = ()\n self._size = 0\n self._size_limit = size_limit\n self._n = 0\n\n def __contains__(self, itemset):\n return itemset in self._cache\n\n def __getitem__(self, itemset):\n return self._cache[itemset]\n\n def add(self, itemset, count):\n # assert(self._size < self._size_limit)\n self._cache[itemset] = count\n self._size += 1\n if not self._min or count < self._min[1]:\n self._min = (itemset, count)\n\n def replace(self, itemset, count):\n # self._n += 1\n # assert(count > self._min[1])\n ret = self._min\n del self._cache[ret[0]]\n self._cache[itemset] = count\n self._min = (itemset, count)\n return ret\n\n def delete(self, itemset):\n del self._cache[itemset]\n self._size -= 1\n\n def update(self, itemset, count):\n self._cache[itemset] += count\n if count < self._min[1]:\n self._min = (itemset, count)\n\n def full(self):\n return self._size >= self._size_limit\n\n\n'''tree'''\n#-------------------------- Tree Base -------------------\n#-------------------------- Tree Base -------------------\n#-------------------------- Tree Base -------------------\nclass TreeNode():\n def __init__(self, key = None, parent = None, count = 0):\n self._key = key\n self._parent = parent\n self._count = count\n self._children = {}\n self._comb_cache = Cache()\n self._comb_table = {}\n self._item_cache = Cache()\n self._item_table = {}\n\n def addChild(self, node):\n self._children[node._key] = node\n\n\nclass Tree():\n def __init__(self, minsup):\n self._root = TreeNode()\n self._size = 0\n self.minsup = minsup\n\n #-------------------------- public accessors -------------------\n def size(self):\n return self._size\n\n def is_empty(self):\n return self.size() == 0\n\n #iterators\n def __iter__(self):\n for node in self.preorder():\n yield node\n\n def __repr__(self):\n ret = []\n for node in self.preorder():\n if node._count >= self.minsup:\n ret.append(node._key)\n return str(ret)\n\n def exp_results(self):\n ret = []\n s1 = 0\n s2 = 0\n icache = 0\n itable = 0\n ccache = 0\n ctable = 0\n n1 = 0\n n2 = 0\n for node in self.preorder():\n s1 += node._item_cache._n\n icache += node._item_cache._size\n itable += len(node._item_table)\n if node._item_cache.full():\n n1 += 1\n # print(\"item\", node._key)\n s2 += node._comb_cache._n\n ccache += node._comb_cache._size\n ctable += len(node._comb_table)\n if node._comb_cache.full():\n n2 += 1\n print(\"comb\", node._key, len(node._comb_table))\n return f'Cache eviction: item - {s1}, comb - {s2}\\nItem: cache - {icache}, table - {itable}\\nComb: cache - {ccache}, table - {ctable}\\nTable used: item - {n1}, comb - {n2}'\n\n def nodes(self):\n for node in self.preorder():\n yield node\n\n def keys(self):\n for node in self.preorder():\n yield node._key\n\n def counts(self):\n for node in self.preorder():\n yield node._count\n\n def children(self, node):\n for child in node._children.keys():\n yield child\n\n def preorder(self):\n if not self.is_empty():\n for node in self._subtree_preorder(self._root):\n yield node\n\n def _subtree_preorder(self, node):\n yield node\n for c in node._children.values():\n for other in self._subtree_preorder(c):\n yield other\n\n def comb_table_size(self):\n s = []\n for item in self:\n s.append(len(item._comb_table))\n return s\n\n def item_table_size(self):\n s = []\n for item in self:\n s.append(len(item._item_table))\n return s\n\n def toList(self):\n ret = []\n for item in self:\n if item._count >= self.minsup:\n ret.append(str(item._key))\n return sorted(ret)\n\n def _addNode(self, parent, value, count=0):\n newNode = TreeNode(value, parent, count)\n parent.addChild(newNode)\n self._size += 1\n return newNode\n\n def _recordAccess(self, node):\n node._count += 1\n\n def _recordInfo(self, node, comb, count=1, exist=True):\n # record pattern\n combStr = (\",\").join(comb)\n # if comb in cache\n if combStr in node._comb_cache:\n node._comb_cache.update(combStr, count)\n #if comb not in cache\n elif node._comb_cache.full():\n new_count = node._comb_table.get(combStr, 0) + count\n # if count > cache min, replace\n if node._comb_cache._min[1] < new_count:\n ret_comb = node._comb_cache.replace(combStr, new_count)\n # put evicted comb in table\n node._comb_table[ret_comb[0]] = ret_comb[1]\n else:\n node._comb_table[combStr] = new_count\n else:\n node._comb_cache.add(combStr, count)\n # record item\n for item in comb:\n node._item_table[item] = node._item_table.get(item, 0) + count\n # if item in node._item_cache:\n # node._item_cache.update(item, count)\n # elif node._item_cache.full():\n # new_count = node._item_table.get(item, 0) + count\n # if node._item_cache._min[1] < new_count:\n # ret_item = node._item_cache.replace(item, new_count)\n # node._item_table[ret_item[0]] = ret_item[1]\n # else:\n # node._item_table[item] = new_count\n # else:\n # node._item_cache.add(item, count)\n # breadth first\n for item in comb:\n # if item in node._item_cache:\n # if node._item_cache[item] >= self.minsup:\n # # add node\n # newNode = self._addNode(node, node._key + \",\" + item, node._item_cache[item])\n # # transfer patterns to newNode\n # for key in node._comb_cache:\n # ptn = key.split(\",\")\n # if item in ptn:\n # i = ptn.index(item)\n # if i < len(ptn) - 1:\n # suffix = ptn[i + 1:]\n # self._recordInfo(newNode, suffix, node._comb_cache[key], exist=False)\n # for key in node._comb_table:\n # ptn = key.split(\",\")\n # if item in ptn:\n # i = ptn.index(item)\n # if i < len(ptn) - 1:\n # suffix = ptn[i + 1:]\n # self._recordInfo(newNode, suffix, node._comb_table[key], exist=False)\n # else:\n if node._item_table[item] >= self.minsup:\n # add node\n newNode = self._addNode(node, node._key + \",\" + item, node._item_table[item])\n # transfer patterns to newNode\n for key in node._comb_cache._cache:\n ptn = key.split(\",\")\n if item in ptn:\n i = ptn.index(item)\n if i < len(ptn) - 1:\n suffix = ptn[i + 1:]\n self._recordInfo(newNode, suffix, node._comb_cache[key], exist=False)\n for key in node._comb_table:\n ptn = key.split(\",\")\n if item in ptn:\n i = ptn.index(item)\n if i < len(ptn) - 1:\n suffix = ptn[i + 1:]\n self._recordInfo(newNode, suffix, node._comb_table[key], exist=False)\n # the whole combination becomes frequent\n if node._comb_table[key] >= self.minsup:\n del node._comb_table[key]\n # del node._item_table[item]\n\n def insertAndRecord(self, node, comb):\n # not root\n self._recordAccess(node)\n # reached the end\n if not comb:\n return\n self._recordInfo(node, comb)\n for i in range(len(comb)):\n if node._key + \",\" + comb[i] in node._children:\n self.insertAndRecord(node._children[node._key + \",\" + comb[i]], comb[i+1:])\n\n def insert(self, node, trx):\n for i in range(len(trx)):\n if trx[i] not in node._children:\n newNode = self._addNode(node, trx[i])\n self.insertAndRecord(node._children[trx[i]], trx[i+1:])\n","sub_path":"Freno/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":8961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"634847404","text":"import re\n# re.match()\n# re.search()\n# re.findall()\n# re.split()\n# re.sub()\n# re.compile()\nimport requests\nimport json\n\n\n# Читаем из файла с помощью конструкции with\ndef read_file(filename):\n with open(filename) as some_file:\n return some_file.read()\n\n\n# Записываем в файл с помощью конструкции with\ndef write_to_file(filename, content, mode='w'):\n with open(filename, mode=mode) as some_file:\n some_file.write(content)\n\n\n# Test 1, with re\n# При помощи requests скачиваем содержимое страниц\n# reddit.com/r/python (любой тред 5 комментов) и вывести\n# пару комметнов и его текстов в консоль\n# http://docs.python-requests.org/en/master/user/quickstart/\n\nif __name__ == '__main__':\n try:\n print(\"start app\")\n some_texts = requests.get('https://habr.com/ru/',\n stream=True)\n\n print(\"HEADERS:\\n\", some_texts.headers)\n print(\"STATUS_CODE:\\n\", some_texts.status_code)\n # контент не можем взять, потому что лимит на скорость надо закинуть\n #print(\"CONTENT:\\n\", some_texts.content)\n #write_to_file(\"habr_html.txt\", str(some_texts.content))\n post_list = re.findall(r'ul', str(some_texts.content))\n print('RE match:\\n', post_list)\n finally:\n print(\"end app\")\n","sub_path":"task_re.py","file_name":"task_re.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"221544936","text":"# -*- coding: utf-8\r\n__author__ = 'Georg'\r\n\r\n\r\nfrom heapq import heapify\r\n\r\n# input\r\nallIterrations = int(input())\r\narray = list(map(lambda x: int(x), input().split(' ')))\r\nk = int(input())\r\n# input\r\n\r\n# nums of subarrays\r\niterr = int(allIterrations / k)\r\n\r\nif iterr == allIterrations / k:\r\n sortedArray = [] # include all subarrays\r\n lenArray = [] # include len of each subarray\r\n for i in range(1, iterr + 1):\r\n sortedArray.append(sorted(array[(i - 1) * k:i * k]))\r\n lenArray.append(0)\r\n # print('Sorted array is:', sortedArray)\r\n # print('Len array is:', lenArray)\r\n # [(), (), ()] sorted for subarrays array and lenArray [, ,] with len for each subarray\r\nelse:\r\n sortedArray = [] # include all subarrays\r\n lenArray = [] # include len of each subarray\r\n for i in range(1, iterr + 2):\r\n sortedArray.append(sorted(array[(i - 1) * k:i * k]))\r\n lenArray.append(0)\r\n # print('Sorted array is:', sortedArray)\r\n # print('Len array is:', lenArray)\r\n # [(), (), ()] sorted for subarrays array and lenArray [, ,] with len for each subarray\r\n\r\nheapArray = []\r\nif heapArray == []:\r\n i = 0\r\n for each in sortedArray:\r\n heapArray.append((each[0], i))\r\n i += 1\r\n# print('Heap array before heapify', heapArray)\r\nheapify(heapArray)\r\n# max <- ...... <- min heap\r\n# print('Heap array after heapify', heapArray)\r\n\r\noutArray = []\r\nfor i in range(allIterrations):\r\n outArray.append(heapArray[0][0])\r\n if lenArray[heapArray[0][1]] < len(sortedArray[heapArray[0][1]]) - 1:\r\n lenArray[heapArray[0][1]] += 1\r\n heapArray[0] = (sortedArray[heapArray[0][1]][lenArray[heapArray[0][1]]], heapArray[0][1])\r\n heapify(heapArray)\r\n # print(heapArray)\r\n else:\r\n heapArray.reverse()\r\n heapArray.pop()\r\n heapify(heapArray)\r\n # print(heapArray)\r\n# else:\r\n# heapArray[0] = sortedArray[ heapArray[0][0]+1 ][ lenArray[ heapArray[0][1] ] ]\r\n# print(heapArray)\r\n\r\n# print(outArray)\r\noutStr = str(outArray[0])\r\nfor i in range(1, len(outArray)):\r\n outStr += \" \" + str(outArray[i])\r\nprint(outStr)\r\n","sub_path":"III_Quadratic_sort/heap_sort.py","file_name":"heap_sort.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"115394287","text":"import itertools\n\nimport math\n\nfrom deap import tools\n\nimport numpy as np\n\nfrom .base_strategy import BaseEvolutionStrategy\nfrom .individual import Individual\nfrom .mfitness import MultidimensionalFitness\n\n\nclass DynamicDifferentialEvolution(BaseEvolutionStrategy):\n def __init__(self, population_size=10, population_regular=4,\n population_brownian=2, cr=0.6, f=0.4, bounds=(-1.0, 1.0),\n **kwargs):\n super(DynamicDifferentialEvolution, self).__init__(**kwargs)\n\n self.population_size = population_size\n self.cr = cr\n self.f = f\n self.bounds = bounds\n self.population_regular = population_regular\n self.population_brownian = population_brownian\n\n def best_individual(self):\n return self.hall_of_fame[0]\n\n def generate_brow_ind_with_fitness(self, best, sigma=0.3):\n fitness_len = len(self.fitness)\n ind = Individual(np.random.normal(x, sigma) for x in best)\n ind.fitness = MultidimensionalFitness(fitness_len)\n return ind\n\n def fit(self, X, y):\n # Differential evolution parameters\n individual_size = self.n_dim\n # Should be equal to the number of peaks\n population_size = self.population_size\n\n regular = self.population_regular\n brownian = self.population_brownian\n bounds = self.bounds\n\n toolbox = self.create_toolbox(X, y)\n toolbox.register(\"attr_float\", np.random.uniform, -1, 1)\n toolbox.register(\n \"individual\",\n self.generate_individual_with_fitness,\n toolbox.attr_float,\n individual_size)\n toolbox.register(\n \"brownian_individual\",\n self.generate_brow_ind_with_fitness)\n toolbox.register(\n \"population\",\n tools.initRepeat,\n list,\n toolbox.individual)\n\n toolbox.register(\"select\", np.random.choice, size=4)\n toolbox.register(\"best\", tools.selBest, k=1)\n\n self.hall_of_fame = tools.HallOfFame(1)\n stats = self._build_stats()\n\n self.logbook = tools.Logbook()\n self.logbook.header = ['gen', 'nevals'] \\\n + (stats.fields if stats else [])\n\n # Initialize populations\n populations = [toolbox.population(n=regular + brownian)\n for _ in range(population_size)]\n\n # Evaluate the individuals\n for idx, subpop in enumerate(populations):\n fitness = toolbox.map(toolbox.evaluate, subpop)\n for ind, fit in zip(subpop, fitness):\n ind.fitness.values = fit\n\n if stats:\n record = stats.compile(itertools.chain(*populations))\n self.logbook.record(gen=0, evals=len(populations), **record)\n if self.verbose:\n print(self.logbook.stream)\n\n for g in range(1, self.n_gen):\n # Detect a change and invalidate fitness if necessary\n bests = [toolbox.best(subpop)[0] for subpop in populations]\n if any(b.fitness.values != toolbox.evaluate(b) for b in bests):\n for individual in itertools.chain(*populations):\n del individual.fitness.values\n\n # Apply exclusion\n rexcl = (bounds[1] - bounds[0]) \\\n / (2 * population_size**(1.0 / individual_size))\n for i, j in itertools.combinations(range(population_size), 2):\n if bests[i].fitness.valid and bests[j].fitness.valid:\n d = sum((bests[i][k] - bests[j][k])**2\n for k in range(individual_size))\n d = math.sqrt(d)\n\n if d < rexcl:\n if bests[i].fitness < bests[j].fitness:\n k = i\n else:\n k = j\n\n populations[k] = toolbox.population(\n n=regular + brownian)\n\n # Evaluate the individuals with an invalid fitness\n invalid_ind = [ind for ind in itertools.chain(*populations)\n if not ind.fitness.valid]\n fitness = toolbox.map(toolbox.evaluate, invalid_ind)\n for ind, fit in zip(invalid_ind, fitness):\n ind.fitness.values = fit\n\n all_pops = list(itertools.chain(*populations))\n self.hall_of_fame.update(all_pops)\n\n if stats:\n record = stats.compile(all_pops)\n self.logbook.record(gen=g, evals=len(populations), **record)\n if self.verbose:\n print(self.logbook.stream)\n\n # Evolve the sub-populations\n for idx, subpop in enumerate(populations):\n newpop = []\n xbest, = toolbox.best(subpop)\n # Apply regular DE to the first part of the population\n for individual in subpop[:regular]:\n idxs = np.random.choice(len(subpop), size=4)\n x1, x2, x3, x4 = subpop[idxs[0]], subpop[idxs[1]], \\\n subpop[idxs[2]], subpop[idxs[3]]\n offspring = toolbox.clone(individual)\n index = np.random.randint(individual_size)\n for i, _ in enumerate(individual):\n if i == index or np.random.random() < self.cr:\n offspring[i] = xbest[i] + self.f \\\n * (x1[i] + x2[i] - x3[i] - x4[i])\n offspring.fitness.values = toolbox.evaluate(offspring)\n if offspring.fitness >= individual.fitness:\n newpop.append(offspring)\n else:\n newpop.append(individual)\n\n # Apply Brownian to the last part of the population\n newpop.extend(toolbox.brownian_individual(xbest)\n for _ in range(brownian))\n\n # Evaluate the brownian individuals\n for individual in newpop[-brownian:]:\n individual.fitness.value = toolbox.evaluate(individual)\n\n # Replace the population\n populations[idx] = newpop\n\n self.cleanup()\n return self\n","sub_path":"metric_learn/evolution/strategy/dde.py","file_name":"dde.py","file_ext":"py","file_size_in_byte":6276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"266168526","text":"# time O(n), space O(1)\nfrom collections import defaultdict\nclass Solution(object):\n def lengthOfLongestSubstringTwoDistinct(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if not s:\n return 0\n window = defaultdict(int)\n res = 0\n left = 0\n for right, c in enumerate(s):\n window[c] += 1\n while len(window) > 2:\n window[s[left]] -= 1\n if window[s[left]] == 0:\n del window[s[left]]\n left += 1\n res = max(res, right-left+1)\n return res\n \n\n\n\"\"\"\nGiven a string s , find the length of the longest substring t that contains at most 2 distinct characters.\n\nExample 1:\n\nInput: \"eceba\"\nOutput: 3\nExplanation: t is \"ece\" which its length is 3.\nExample 2:\n\nInput: \"ccaabbb\"\nOutput: 5\nExplanation: t is \"aabbb\" which its length is 5.\n\"\"\"\n","sub_path":"0159. Longest Substring with At Most Two Distinct Characters.py","file_name":"0159. Longest Substring with At Most Two Distinct Characters.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"197392982","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 3 15:51:26 2019\n\n@author: zclement\n\"\"\"\n\nfrom tweepy.streaming import StreamListener\nfrom tweepy import OAuthHandler\nfrom tweepy import Stream\nfrom kafka import SimpleProducer, KafkaClient\n\n\n\nkafka = KafkaClient(\"192.168.0.10:9092\")\n\nproducer = SimpleProducer(kafka)\n\n\nclass StdOutListener(StreamListener):\n def on_data(self, data):\n producer.send_messages(\"trump_v0\", data.encode('utf-8'))\n print (data)\n return True\n def on_error(self, status):\n print (status)\n\n\n\nl = StdOutListener()\nauth = OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\n\n\nstream = Stream(auth= auth, listener= l)\nstream.filter(track=\"trump\") #read tweempy Sream docks .filter","sub_path":"create_kafka_topic.py","file_name":"create_kafka_topic.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"396789522","text":"import socket\nimport signal # Allow socket destruction on Ctrl+C\nimport sys\nimport time\nimport threading\n\n\nclass WebServer(object):\n\n def __init__(self, port=80):\n self.host = '127.0.0.1' # Default to any avialable network interface\n self.port = port\n self.content_dir = 'files' # Directory where webpage files are stored\n\n def start(self):\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n try:\n print(\"Starting server on {host}:{port}\".format(host=self.host, port=self.port))\n self.socket.bind((self.host, self.port))\n print(\"Server started on port {port}.\".format(port=self.port))\n\n except Exception as e:\n print(\"Error: Could not bind to port {port}\".format(port=self.port))\n self.shutdown()\n sys.exit(1)\n\n self._listen() # Start listening for connections\n\n def shutdown(self):\n \n try:\n print(\"Shutting down server\")\n self.socket.shutdown(socket.SHUT_RDWR)\n\n except Exception as e:\n pass # Pass if socket is already closed\n\n def _generate_headers(self, response_code):\n \n header = ''\n if response_code == 200:\n header += 'HTTP/1.1 200 OK\\n'\n elif response_code == 301:\n header += 'HTTP/1.1 301 Moved permanently\\n'\n elif response_code == 404:\n header += 'HTTP/1.1 404 Not Found\\n'\n\n time_now = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime())\n header += 'Date: {now}\\n'.format(now=time_now)\n header += 'Server: Simple-Python-Server\\n'\n header += 'Connection: close\\n\\n' # Signal that connection will be closed after completing the request\n return header\n\n def _listen(self):\n \n self.socket.listen(5)\n while True:\n (client, address) = self.socket.accept()\n client.settimeout(60)\n print(\"Recieved connection from {addr}\".format(addr=address))\n threading.Thread(target=self._handle_client, args=(client, address)).start()\n\n def _handle_client(self, client, address):\n \n PACKET_SIZE = 10000\n while True:\n print(\"CLIENT\",client)\n data = client.recv(PACKET_SIZE).decode() # Recieve data packet from client and decode\n\n if not data: break\n\n request_method = data.split(' ')[0]\n print(\"Method: {m}\".format(m=request_method))\n print(\"Request Body: {b}\".format(b=data))\n\n if request_method == \"GET\" or request_method == \"HEAD\":\n \n file_requested = data.split(' ')[1]\n\n file_requested = file_requested.split('?')[0]\n\n if file_requested == \"/\":\n file_requested = \"/index.html\"\n\n filepath_to_serve = self.content_dir + file_requested\n print(\"Serving web page [{fp}]\".format(fp=filepath_to_serve))\n\n # Load and Serve files content\n try:\n f = open(filepath_to_serve, 'rb')\n if request_method == \"GET\": # Read only for GET\n response_data = f.read()\n f.close()\n\n response_header = self._generate_headers(200)\n\n except Exception as e:\n print(\"Serving 404 page.\")\n response_header = self._generate_headers(404)\n\n if request_method == \"GET\": # Temporary 404 Response Page\n file_requested = \"/404.html\"\n\n filepath_to_serve = self.content_dir + file_requested\n print(\"Serving web page [{fp}]\".format(fp=filepath_to_serve))\n\n f = open(filepath_to_serve, 'rb')\n response_data = f.read()\n f.close()\n\n response_header = self._generate_headers(404)\n\n response = response_header.encode()\n if request_method == \"GET\":\n response += response_data\n\n client.send(response)\n client.close()\n break\n\n if request_method == 'POST':\n i = data.find(\"username=\")\n j = data.rfind(\"&\")\n nameuser = data[(i + len(\"username=\")):j]\n password = data[(j + len(\"&password=\")):]\n\n if (nameuser == \"admin\" and password == \"admin\"):\n file_requested = \"/redirect.html\"\n\n filepath_to_serve = self.content_dir + file_requested\n print(\"Serving web page [{fp}]\".format(fp=filepath_to_serve))\n\n f = open(filepath_to_serve, 'rb')\n response_data = f.read()\n f.close()\n\n response_header = self._generate_headers(301)\n else:\n print(\"Serving 404 page.\")\n\n file_requested = \"/404.html\"\n\n filepath_to_serve = self.content_dir + file_requested\n print(\"Serving web page [{fp}]\".format(fp=filepath_to_serve))\n\n f = open(filepath_to_serve, 'rb')\n response_data = f.read()\n f.close()\n\n response_header = self._generate_headers(404)\n\n response = response_header.encode()\n if request_method == \"POST\":\n response += response_data\n\n client.send(response)\n client.close()\n break\n\n else:\n print(\"Unknown HTTP request method: {method}\".format(method=request_method))\n\n\n\n\n### MAIN ###\ndef shutdownServer(sig, unused):\n \n server.shutdown()\n sys.exit(1)\n\nsignal.signal(signal.SIGINT, shutdownServer)\nserver = WebServer(80)\nserver.start()\nprint(\"Press Ctrl+C to shut down server.\")","sub_path":"Socket/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"368199634","text":"import re\nimport shutil\nimport zipfile\n\nfrom mail_server.utils.log.remote_logger import Logger\n\ndef bill_material_extension_task(file_name, extension, content, mail_path):\n Logger.info(\"Bill material extension task call\")\n return [{'file_name': file_name, 'extension': extension}]\n\ndef zip_extension_task(file_name, extension, content, mail_path):\n\n Logger.info(\"Zip extension task call\")\n Logger.info(\"Zip detected in: \" + mail_path + file_name)\n bills = []\n\n with zipfile.ZipFile(mail_path + file_name, 'r') as zip_file:\n for file_member in zip_file.namelist():\n\n file_name = re.sub(r\"[/\\\\]\", '_', file_member)\n file_name_parts = file_name.split('.', 1 )\n file_extension = \"default\"\n if len(file_name_parts) > 1:\n file_extension = file_name_parts[1].lower()\n\n if file_extension == \"xml\" or file_extension == \"pdf\":\n file_path = mail_path\n\n file_path += file_name\n file_content = zip_file.open(file_member)\n\n with open(file_path, \"wb\") as file_destiny:\n with file_content, file_destiny:\n shutil.copyfileobj(file_content, file_destiny)\n\n bill_info = FILE_EXTENSION_TASKS.get(file_extension, \"default\")(file_name, file_extension, \"\", mail_path)\n for info in bill_info:\n bills.append(info)\n\n return bills\n\nFILE_EXTENSION_TASKS = {\n 'xml': bill_material_extension_task,\n 'pdf': bill_material_extension_task,\n 'zip': zip_extension_task,\n 'default': lambda : []\n}\n\ndef extract_bills_from_attachments(mail_path, attachments):\n bills = {}\n Logger.info(\"Extracting bills from mail content\")\n for attach in attachments:\n file_attach_name = attach.file_name if not (attach.file_name is None) else attach.name\n if not (file_attach_name is None):\n decode_attach_content = attach.content.getvalue().decode(attach.content_transfer_encoding, 'strict')\n Logger.info(\"File name: {}\".format(file_attach_name))\n\n file_name_parts = file_attach_name.split('.', 1 )\n attach_extension = \"default\"\n if len(file_name_parts) > 1:\n attach_extension = file_name_parts[1].lower()\n Logger.info(\"Attach extension: {}\".format(attach_extension))\n\n bill_info = FILE_EXTENSION_TASKS.get(attach_extension, \"default\")(file_attach_name, attach_extension, decode_attach_content, mail_path)\n for info in bill_info:\n if info['extension'] in bills:\n bills[info['extension']].append(info['file_name'])\n else:\n bills[info['extension']] = [info['file_name']]\n\n return bills\n","sub_path":"mail_server/utils/bill/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"352468832","text":"import data\nimport pymysql\nfrom connection import ConnectionWrapper\n\n\ndef runQuery(query, args, fetch=False, db=data.DATABASE):\n cw = ConnectionWrapper(db)\n try:\n cursor = cw.getCursor()\n cursor.execute(query, args)\n\n if fetch:\n result = cursor.fetchall()\n else:\n result = None\n cw.commit()\n return result\n\n finally:\n cw.close()\n\n\ndef createTestingDB():\n query = \"CREATE DATABASE \" + data.DATABASE + \";\"\n runQuery(query, None, False, None)\n\n\ndef dropTestingDB():\n query = \"DROP DATABASE IF EXISTS \" + data.DATABASE + \";\"\n runQuery(query, None, False, None)\n\n\ndef createTables(create_script_name):\n with open(create_script_name, 'r') as myfile:\n query = myfile.read()\n\n # data processing\n query = query.replace(\"\\t\", \"\")\n query = query.replace(\"\\n\", \"\")\n queries = query.split(\";\")\n\n for i in range(len(queries) - 1): # Skip the last comments\n runQuery(queries[i] + \";\", None, False)\n\n\n \ndef searchInfoByPartialConditions(tableName, info_format, cons_format=None, keyword=None): # quotes\n query = \"\"\n if cons_format == None and keyword == None:\n query = (\"SELECT \" + info_format + \" FROM \" + tableName + \";\")\n else:\n kword = ('%s'%keyword)\n cons_format = (cons_format + \" like '%\" + kword + \"%'\")\n query = (\n \"SELECT \" + info_format + \" FROM \" + tableName + \" WHERE \" +\n cons_format + \";\"\n )\n return runQuery(query, None, True)\n\n\ndef selectInfoByConditions(tableName, info_format, cons_format=None, vals=None): # quotes\n query = \"\"\n if cons_format == None and vals == None:\n query = (\"SELECT \" + info_format + \" FROM \" + tableName + \";\")\n else:\n query = (\n \"SELECT \" + info_format + \" FROM \" + tableName + \" WHERE \" +\n cons_format + \";\"\n )\n query = query % vals\n return runQuery(query, None, True)\n\n\ndef searchInfoByConditions(tableName, info_format, cons_format=None, vals=None): # quotes\n query = \"\"\n if cons_format == None and vals == None:\n query = (\"SELECT \" + info_format + \" FROM \" + tableName + \";\")\n else:\n query = (\n \"SELECT \" + info_format + \" FROM \" + tableName + \" WHERE \" +\n cons_format + \";\"\n )\n query = query % vals\n return runQuery(query, None, True)\n\n\ndef selectAllByConditions(tableName, cons_format=None, vals=None):\n return selectInfoByConditions(tableName, \"*\", cons_format, vals)\n\n\ndef getNumOfRecordByConditions(tableName, cons_format=None, vals=None):\n return len(selectAllByConditions(tableName, cons_format, vals))\n\n\ndef checkRecordExistByConditions(tableName, cons_format=None, vals=None):\n return (getNumOfRecordByConditions(tableName, cons_format, vals) > 0)\n\n\ndef deleteRecordByCondition(tableName, cons_format, vals):\n query = (\"DELETE FROM \" + tableName + \" WHERE \" + cons_format + \";\")\n query = query % vals\n runQuery(query, None, False)\n return True\n\n\ndef insertRecordTo(tableName, cols, vals, vals_format):\n query = \"INSERT INTO \" + tableName + cols + \" VALUES \" + vals_format + \";\"\n runQuery(query, vals, False)\n return True\n\n\ndef insertRecordForcibly(tableName, user_id, info):\n info = pymysql.escape_string(info)\n query = 'INSERT INTO %s (user_id, info) VALUES (\"%s\", \"%s\") ON DUPLICATE KEY UPDATE info=\"%s\";' % (\n tableName, user_id, info, info)\n runQuery(query, None, False)\n return True\n\n\ndef updateRecordByConditions(tableName, info_format, cons_format, vals):\n query = (\n \"UPDATE \" + tableName + \" SET \" + info_format + \" WHERE \"\n + cons_format + \";\"\n )\n query = query % vals\n runQuery(query, None, False)\n return True\n\n\ndef getValsByKey(result_list, key): # return a list\n vals = []\n if (len(result_list) <= 0) or (key not in result_list[0]):\n return vals\n\n for i in range(len(result_list)):\n vals.append(result_list[i][key])\n\n return vals\n","sub_path":"server/db/dbhelper/queries.py","file_name":"queries.py","file_ext":"py","file_size_in_byte":4013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"309512251","text":"import os\nimport json\nfrom flask import Flask, render_template, session, redirect, url_for, flash, jsonify, request, make_response\nfrom flask.ext.script import Manager\nfrom flask.ext.bootstrap import Bootstrap\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom flask.ext.wtf import Form\nfrom wtforms import StringField, SubmitField, SelectField\nfrom wtforms.validators import Required\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'hard to guess string'\napp.config['SQLALCHEMY_DATABASE_URI'] =\\\n'sqlite:///' + os.path.join(basedir, 'data.sqlite')\napp.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True\n\nmanager = Manager(app)\nbootstrap = Bootstrap(app)\ndb = SQLAlchemy(app)\n\nclass Record(db.Model):\n __tablename__ = 'records'\n id = db.Column(db.Integer, primary_key = True)\n patient_id = db.Column(db.Integer)\n date = db.Column(db.Date)\n probability = db.Column(db.Float)\n duration_since_lastECOPD = db.Column(db.Integer)\n previous_ECOPD_nb = db.Column(db.Integer)\n previous_hospital_nb = db.Column(db.Integer)\n duration_since_lastHospital = db.Column(db.Integer)\n Age = db.Column(db.Integer)\n Weight = db.Column(db.Integer)\n Height = db.Column(db.Integer)\n BMI = db.Column(db.Float)\n Pack_Years = db.Column(db.Integer)\n last_O2FR_Prescribed = db.Column(db.Float)\n def __repr__(self):\n return str(patient_id) + ',' + str(date) + ',' + str(probability)\n\nclass NameForm(Form):\n name = StringField('What is your name?', validators=[Required()])\n submit = SubmitField('Submit')\n\nclass RecordForm(Form):\n patient_id = SelectField(u'', choices=())\n date = SelectField(u'', choices=())\n submit = SubmitField('Submit')\n\n@app.route('/', methods = ['GET'])\ndef index():\n patient_ids = set([x.patient_id for x in Record.query.all()])\n patient_dict = {}\n for i in patient_ids:\n patient_dict[i] = []\n for x in Record.query.all():\n patient_dict[x.patient_id].append(x.date)\n return render_template('index.html', patient_dict = patient_dict)\n\n@app.route('/search', methods=['GET', 'POST'])\ndef select():\n \"\"\"\n Render a vehicle selection form and handle form submission\n \"\"\"\n form = RecordForm()\n patient_ids = set([x.patient_id for x in Record.query.all()])\n form.patient_id.choices = [('', '--- Select One Patient ---')] + [(x, x) for x in patient_ids]\n if request.method == 'POST':\n patient_id = form.patient_id.data\n date = form.date.data\n probability = Record.query.filter_by(patient_id = patient_id, date = date).first()\n if probability is None:\n return render_template('404.html'), 404\n session['patient_id'] = patient_id\n session['date'] = date\n session['probability'] = probability.probability\n session['duration_since_lastECOPD'] = probability.duration_since_lastECOPD\n session['previous_ECOPD_nb'] = probability.previous_ECOPD_nb\n session['duration_since_lastHospital'] = probability.duration_since_lastHospital\n session['previous_hospital_nb'] = probability.previous_hospital_nb\n session['Age'] = probability.Age\n session['Weight'] = probability.Weight\n session['Height'] = probability.Height\n session['BMI'] = probability.BMI\n session['Pack_Years'] = probability.Pack_Years\n session['last_O2FR_Prescribed'] = probability.last_O2FR_Prescribed \n return redirect(url_for('result'))\n return render_template('select.html', form = form)\n\n@app.route('/result', methods = ['GET'])\ndef result():\n if 'patient_id' not in session or 'date' not in session or 'probability' not in session:\n return render_template('404.html'), 404\n return render_template('result.html', patient_id = session['patient_id'], date = session['date'], \n probability = session['probability'],\n duration_since_lastECOPD= session['duration_since_lastECOPD'],\n previous_ECOPD_nb = session['previous_ECOPD_nb'],\n duration_since_lastHospital = session['duration_since_lastHospital'],\n previous_hospital_nb = session['previous_hospital_nb'],\n Age = session['Age'],\n Weight = session['Weight'],\n Height = session['Height'],\n BMI = session['BMI'],\n Pack_Years = session['Pack_Years'],\n last_O2FR_Prescribed = session['last_O2FR_Prescribed'])\n\n@app.route('/patients//', methods = ['GET'])\ndef get(patient_id):\n \"\"\"\n Handle a GET request at /patients//\n Return a list of 2-tuples (, )\n \"\"\"\n data = [(str(x.date), str(x.date)) for x in Record.query.filter_by(patient_id = patient_id).all()] \n response = make_response(json.dumps(data))\n response.content_type = 'application/json'\n return response\n\n@app.route('/patient', methods = ['GET'])\ndef patient():\n patient_id = request.args.get('patient_id', type = int)\n date = request.args.get('date', type = str)\n query = Record.query.filter_by(patient_id = patient_id, date = date).first()\n result = {}\n result['patient_id'] = query.patient_id\n result['date'] = str(query.date)\n result['probability'] = query.probability\n result['duration_since_lastECOPD'] = query.duration_since_lastECOPD\n result['previous_ECOPD_nb'] = query.previous_ECOPD_nb\n result['duration_since_lastHospital'] = query.duration_since_lastHospital\n result['previous_hospital_nb'] = query.previous_hospital_nb\n result['Age'] = query.Age\n result['Weight'] = query.Weight\n result['Height'] = query.Height\n result['BMI'] = query.BMI\n result['Pack_Years'] = query.Pack_Years\n result['last_O2FR_Prescribed'] = query.last_O2FR_Prescribed \n return json.dumps(result)\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return render_template('404.html'), 404\n\n@app.errorhandler(500)\ndef internal_server_error(e):\n return render_template('500.html'), 500\n\n\n#@app.route('/radial')\n#def radial():\n# return render_template('RadialprogressTest.html')\n\n#@app.route('/', methods=['GET', 'POST'])\n#def index():\n# form = NameForm()\n# if form.validate_on_submit():\n# old_name = session.get('name')\n# if old_name is not None and old_name != form.name.data:\n# flash('Looks like you have changed your name!')\n# session['name'] = form.name.data\n# return redirect(url_for('index'))\n# return render_template('index.html', form=form, name=session.get('name'))\n\n\n##@app.route('/add_numbers')\n#def add_numbers():\n# return render_template('add_numbers.html')\n\n#@app.route('/_add_numbers')\n#def _add_numbers():\n# a = request.args.get('a', 0, type=int)\n# b = request.args.get('b', 0, type=int)\n# return jsonify(result=a + b)\n\n#@app.route('/circle')\n#def circle():\n# return render_template('circle.html')\n\nif __name__ == '__main__':\n manager.run()\n","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":6875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"230369662","text":"# This toolbox contains functions for prepping, tuning and updating when using the enkf-c\n# for assimilation.\n\n# There are still som uncertainties regarding the tuning that needs to be solve when the\n# format of the observation files are decided, but only one sst and one ice conc file is \n# used as the present plan is, the tuning should be working well.\n\nimport glob\nimport netCDF4 as nc\nimport xarray as xr # Egentlig bruke denne istedenfor nc ettersom jeg tror den er raskere\nimport datetime\nimport numpy as np\nimport os\nimport sys\nimport copy\nimport subprocess\nfrom scipy.ndimage import uniform_filter\nfrom pyresample.geometry import GridDefinition\nfrom pyresample import geometry, image, SwathDefinition\n\ndef cmd(command):\n \"\"\"Function runs provided command in the system shell.\n\n Args:\n command (string) : Command to be executed in shell\n Returns:\n result (integer) : Shell returned status of command\n \"\"\"\n print(\"> \" + command)\n result = subprocess.call(command, shell = True)\n\n if result != 0:\n print(\"Command failed: %d\" % result)\n else:\n return result\n\n# Rewrite the model output to files recognized by the enkf-c\ndef Prep_ensemble(ens_date, grid_dir, ens_inn_dir, enkf_c_dir, res_type, EnKF_var,Nens):\n \n # This should return the number of ensembles found!!!!\n\n # grid_dir: file containing longitude and latitude of the model\n # ens_inn_dir: folder containning the model output data\n # enkf-c_dir: folder containting the netcdf files used by enkf-c\n # ens_inn_file_dummy: file name shared by all the ensemble members\n ens_count = 0\n \n file_cord_handle = nc.Dataset(grid_dir, mode='r')\n \n ice_halo_cells = False\n # Disse leses fra grid fila! \n lat_rho = file_cord_handle.variables['lat_rho']\n #lon_rho = file_cord_handle.variables['lon_rho']\n\n # Write the files that are used to disk\n #glob.glob(folder+file_dummy)\n #for ff in glob.glob(folder+file_dummy):\n # file1.writelines(ff+'\\n')\n prescripts = ['iced.','ocean.']\n syear = str(ens_date.year)\n smnd = str(ens_date.month)\n if ens_date.month < 10:\n smnd = '0' + smnd\n sday = str(ens_date.day)\n if ens_date.day < 10:\n sday = '0' + sday\n\n # Write the files that are used to disk\n #glob.glob(folder+file_dummy)\n file_ens = open(enkf_c_dir+'files_in_ensemble', \"w\")\n\n for pre in prescripts:\n iens2 = 0\n for iens in range(1,Nens+1):\n s1ens = str(iens)\n if iens < 100:\n s1ens = '0'+s1ens\n if iens < 10:\n s1ens = '0'+s1ens\n file = ens_inn_dir+pre+syear+smnd+sday+'_'+s1ens+'.nc'\n print(file)\n #This accounts for the possibilty that some ensemble members have not finished in time\n if os.path.exists(file):\n \n\n iens2 += 1\n sens = str(iens2)\n if iens2 < 100:\n sens = '0'+sens\n if iens2 < 10:\n sens = '0'+sens\n \n file_handle = xr.open_dataset(file)\n if pre == 'ocean.':\n ens_count +=1\n # Write the file name to the member files folder\n # No need to wrote it two times as both files are assumed to exist\n file_ens.writelines(s1ens+'\\n')\n # The ocean restart files can contain several restart times.\n #file_time = file_handle.variables['ocean_time']\n #target_num = nc.date2num(ens_date, units=file_time.units,\n # calendar=file_time.calendar)\n #date_index = np.where(np.array(file_time[:]) == target_num)[0]\n # Må bare konverte Xarray output til num også tror jeg\n date_index = 0 # Denne må fikses!!!!!!\n \n elif pre == 'iced.':\n date_index = 0\n test = file_handle.variables['uvel']\n # Check the if the sea ice restart files is using haloc cells for boundary conditions\n if test.shape[0]>lat_rho.shape[0]:\n ice_halo_cells = True\n\n\n \n\n\n\n # read the important variables from the file\n for var in file_handle.variables.keys():\n #print(var)\n\n if var in EnKF_var:\n\n \n\n fn = enkf_c_dir+'ensemble_6565/mem'+sens+'_'+var+'.nc'\n ds = nc.Dataset(fn, 'w', format='NETCDF4')\n\n var_inn = file_handle[var]\n\n # Litt usikker på om jeg skal ha time, \n # teste om det har noe å si på assimilasjonen\n time = ds.createDimension('time', None)\n\n if len(var_inn.shape) == 4:\n \n dx = ds.createDimension('dx', var_inn.shape[2])\n dy = ds.createDimension('dy', var_inn.shape[3])\n dz = ds.createDimension('dz', var_inn.shape[1])\n\n times = ds.createVariable('time', 'f4', ('time',))\n dxs = ds.createVariable('dx', 'f4', ('dx',))\n dys = ds.createVariable('dy', 'f4', ('dy',))\n dzs = ds.createVariable('dz', 'f4', ('dz',))\n\n temps = ds.createVariable(var, 'f4', ('time', 'dz','dx', 'dy',))\n\n dxs[:] = np.arange(0, var_inn.shape[2], 1.0)\n dys[:] = np.arange(0, var_inn.shape[3], 1.0)\n dzs[:] = np.arange(0, var_inn.shape[1], 1.0)\n \n if pre == 'ocean.':\n # a bit uncertain if it is nan or very high so include both\n var_inn = var_inn.fillna(0)\n var_inn.values[:][var_inn.values[:] > 100] = 0\n temps[0,:,:,:] = var_inn[date_index,:,:,:]\n else:\n sys.exit('Not implemented for ice!')\n\n elif len(var_inn.shape) == 3:\n \n\n times = ds.createVariable('time', 'f4', ('time',))\n if ice_halo_cells:\n dx = ds.createDimension('dx', var_inn.shape[1]-2)\n dy = ds.createDimension('dy', var_inn.shape[2]-2)\n\n dxs = ds.createVariable('dx', 'f4', ('dx',))\n dys = ds.createVariable('dy', 'f4', ('dy',))\n \n dxs[:] = np.arange(0, var_inn.shape[1]-2, 1.0)\n dys[:] = np.arange(0, var_inn.shape[2]-2, 1.0)\n else:\n dx = ds.createDimension('dx', var_inn.shape[1])\n dy = ds.createDimension('dy', var_inn.shape[2])\n\n dxs = ds.createVariable('dx', 'f4', ('dx',))\n dys = ds.createVariable('dy', 'f4', ('dy',))\n \n dxs[:] = np.arange(0, var_inn.shape[1], 1.0)\n dys[:] = np.arange(0, var_inn.shape[2], 1.0)\n\n if pre == 'ocean.':\n temps = ds.createVariable(var, 'f4', ('time', 'dx', 'dy',))\n temps[:,:,:] = var_inn[date_index,:,:]\n elif pre == 'iced.':\n dz = ds.createDimension('dz', var_inn.shape[0])\n dzs = ds.createVariable('dz', 'f4', ('dz',))\n temps = ds.createVariable(var, 'f4', ('time','dz', 'dx', 'dy',))\n dzs[:] = np.arange(0, var_inn.shape[0], 1.0)\n \n \n if ice_halo_cells:\n temps[0,:,:,:] = var_inn[:,1:-1,1:-1]\n else: \n temps[0,:,:,:] = var_inn[:,:,:]\n\n elif len(var_inn.shape) == 2:\n time = ds.createDimension('time', None)\n \n\n times = ds.createVariable('time', 'f4', ('time',))\n \n if ice_halo_cells:\n dx = ds.createDimension('dx', var_inn.shape[0]-2)\n dy = ds.createDimension('dy', var_inn.shape[1]-2)\n\n dxs = ds.createVariable('dx', 'f4', ('dx',))\n dys = ds.createVariable('dy', 'f4', ('dy',))\n\n dxs[:] = np.arange(0, var_inn.shape[0]-2, 1.0)\n dys[:] = np.arange(0, var_inn.shape[1]-2, 1.0)\n else: \n dx = ds.createDimension('dx', var_inn.shape[0])\n dy = ds.createDimension('dy', var_inn.shape[1])\n\n dxs = ds.createVariable('dx', 'f4', ('dx',))\n dys = ds.createVariable('dy', 'f4', ('dy',))\n\n dxs[:] = np.arange(0, var_inn.shape[0], 1.0)\n dys[:] = np.arange(0, var_inn.shape[1], 1.0)\n\n temps = ds.createVariable(var, 'f4', ('time', 'dx', 'dy',))\n\n \n\n\n\n if pre == 'ocean.':\n sys.exit('Not implemented for ocean!')\n elif pre == 'iced.':\n if ice_halo_cells:\n temps[0,:,:] = var_inn[1:-1,1:-1]\n else: \n \n temps[0,:,:] = var_inn[:,:]\n \n\n #lat = ds.createVariable('lat', 'f4', ('dx', 'dy',))\n #lon = ds.createVariable('lon', 'f4', ('dx', 'dy',))\n\n times[:] = nc.date2num(ens_date, units='days since 1990-01-01',\n calendar='gregorian')\n times.units = 'days since 1990-01-01'\n times.calendar='gregorian'\n\n if var == 'temp':\n temps.units = 'degrees C'\n\n #lat[:,:] = lat_rho[:,:]\n #lon[:,:] = lon_rho[:,:]\n\n #value[0,:,:] = 3\n\n ds.close()\n\n if var == 'temp' or var == 'salt':\n # Write also sst variable, must figure out which depth it is and then calculate the variable to\n # the surface if possible, Johannes should know more about this\n\n #print('Also make an sst parameter')\n \n if var == 'temp':\n var2 = 'sst'\n fn = enkf_c_dir+'ensemble_6565/mem'+sens+'_sst.nc'\n if var == 'salt':\n var2 = 'sss'\n fn = enkf_c_dir+'ensemble_6565/mem'+sens+'_sss.nc'\n ds = nc.Dataset(fn, 'w', format='NETCDF4')\n\n #print(var)\n time = ds.createDimension('time', None)\n dx = ds.createDimension('dx', var_inn.shape[2])\n dy = ds.createDimension('dy', var_inn.shape[3])\n\n\n times = ds.createVariable('time', 'f4', ('time',))\n dxs = ds.createVariable('dx', 'f4', ('dx',))\n dys = ds.createVariable('dy', 'f4', ('dy',))\n sst = ds.createVariable(var2, 'f4', ('time', 'dx', 'dy',))\n # lat = ds.createVariable('lat', 'f4', ('dx', 'dy',))\n # lon = ds.createVariable('lon', 'f4', ('dx', 'dy',))\n if var == 'temp':\n sst.units = 'degrees C'\n\n times[:] = nc.date2num(ens_date, units='days since 1990-01-01',\n calendar='gregorian')\n times.units = 'days since 1990-01-01'\n times.calendar='gregorian'\n\n #times[:] = file_time[date_index]\n #times.units = file_time.units\n\n dxs[:] = np.arange(0, var_inn.shape[2], 1.0)\n dys[:] = np.arange(0, var_inn.shape[3], 1.0)\n sst[0,:,:] = var_inn[0,41,:,:]\n #lat[:,:] = lat_rho[:,:]\n #lon[:,:] = lon_rho[:,:]\n\n #value[0,:,:] = 3\n\n ds.close()\n\n if var == 'aicen' or var == 'vicen':\n # Write also integrated variables for assimilation\n \n if var == 'aicen':\n var2 = 'aice'\n fn = enkf_c_dir+'ensemble_6565/mem'+sens+'_aice.nc'\n elif var == 'vicen':\n var2 = 'vice'\n fn = enkf_c_dir+'ensemble_6565/mem'+sens+'_vice.nc'\n ds = nc.Dataset(fn, 'w', format='NETCDF4')\n\n time = ds.createDimension('time', None)\n times = ds.createVariable('time', 'f4', ('time',))\n\n\n\n if ice_halo_cells:\n dx = ds.createDimension('dx', var_inn.shape[1]-2)\n dy = ds.createDimension('dy', var_inn.shape[2]-2)\n\n dxs = ds.createVariable('dx', 'f4', ('dx',))\n dys = ds.createVariable('dy', 'f4', ('dy',))\n\n dxs[:] = np.arange(0, var_inn.shape[1]-2, 1.0)\n dys[:] = np.arange(0, var_inn.shape[2]-2, 1.0)\n else: \n dx = ds.createDimension('dx', var_inn.shape[1])\n dy = ds.createDimension('dy', var_inn.shape[2])\n\n dxs = ds.createVariable('dx', 'f4', ('dx',))\n dys = ds.createVariable('dy', 'f4', ('dy',))\n\n dxs[:] = np.arange(0, var_inn.shape[1], 1.0)\n dys[:] = np.arange(0, var_inn.shape[2], 1.0)\n\n sst = ds.createVariable(var2, 'f4', ('time', 'dx', 'dy',))\n \n if ice_halo_cells:\n sst[0,:,:] = np.sum(var_inn[:,1:-1,1:-1],axis=0)\n else:\n sst[0,:,:] = np.sum(var_inn[:,:,:],axis=0)\n #lat[:,:] = lat_rho[:,:]\n #lon[:,:] = lon_rho[:,:]\n\n #value[0,:,:] = 3\n\n times[:] = nc.date2num(ens_date, units='days since 1990-01-01',\n calendar='gregorian')\n times.units = 'days since 1990-01-01'\n times.calendar='gregorian'\n\n ds.close()\n\n if var == 'aicen':\n # Write smoothed variable for low resolution assimilation\n \n fn = enkf_c_dir+'ensemble_6565/mem'+sens+'_aiceosi.nc'\n ds = nc.Dataset(fn, 'w', format='NETCDF4')\n\n time = ds.createDimension('time', None)\n times = ds.createVariable('time', 'f4', ('time',))\n\n\n\n if ice_halo_cells:\n dx = ds.createDimension('dx', var_inn.shape[1]-2)\n dy = ds.createDimension('dy', var_inn.shape[2]-2)\n\n dxs = ds.createVariable('dx', 'f4', ('dx',))\n dys = ds.createVariable('dy', 'f4', ('dy',))\n\n dxs[:] = np.arange(0, var_inn.shape[1]-2, 1.0)\n dys[:] = np.arange(0, var_inn.shape[2]-2, 1.0)\n else: \n dx = ds.createDimension('dx', var_inn.shape[1])\n dy = ds.createDimension('dy', var_inn.shape[2])\n\n dxs = ds.createVariable('dx', 'f4', ('dx',))\n dys = ds.createVariable('dy', 'f4', ('dy',))\n\n dxs[:] = np.arange(0, var_inn.shape[1], 1.0)\n dys[:] = np.arange(0, var_inn.shape[2], 1.0)\n\n sst = ds.createVariable('aiceosi', 'f4', ('time', 'dx', 'dy',))\n \n if ice_halo_cells:\n sst[0,:,:] = uniform_filter(np.sum(var_inn[:,1:-1,1:-1],axis=0), size=16, mode='constant')\n else:\n sst[0,:,:] = uniform_filter(np.sum(var_inn[:,:,:],axis=0), size=16, mode='constant')\n #lat[:,:] = lat_rho[:,:]\n #lon[:,:] = lon_rho[:,:]\n\n #value[0,:,:] = 3\n\n times[:] = nc.date2num(ens_date, units='days since 1990-01-01',\n calendar='gregorian')\n times.units = 'days since 1990-01-01'\n times.calendar='gregorian'\n\n ds.close()\n\n \n # if var equals aicen or vicen\n \n file_handle.close()\n file_ens.close()\n\n file_cord_handle.close()\n\n return ens_count\n \ndef set_number_ensembles(prm_file, ens_count):\n file1 = open(prm_file, 'r') \n Lines = file1.readlines()\n ii = -1\n for l in Lines:\n ii += 1\n if l[0:7] == 'ENSSIZE':\n #print('Fant den!')\n Lines[ii] = 'ENSSIZE = '+str(ens_count)+'\\n'\n #l = 'ENSSIZE = '+str(ens_count)+'\\n'\n\n file1 = open('/Users/sindrefritzner/enkf-c/Assimilation/enkf2.prm', \"w\")\n file1.writelines(Lines)\n file1.close()\n\n\ndef check_dfs_srf(ens_count, diag_file):\n # Check the DFS and SRF values to see if any exceed the recomended values\n # for example if more than 5% of the data has values larger than the limit\n \n file_handle = nc.Dataset(diag_file, mode='r')\n psrf = file_handle.variables['psrf']\n pdfs = file_handle.variables['pdfs']\n\n\n srf_lim = 2 #'må sjekke'\n dfs_lim = ens_count/3 #'må sjekke'\n \n update_srf=np.zeros(psrf.shape[0])\n update_dfs=np.zeros(psrf.shape[0])\n for i in range(0, psrf.shape[0]):\n # more than 5% of the data larger than the limit then reduce\n if len(psrf[i,:,:][psrf[i,:,:]>srf_lim])/(psrf.shape[1]*psrf.shape[2]) > 0.05:\n print('Must increase Rfactor for obstype ' + str(i))\n update_srf[i] = 1\n elif len(psrf[i,:,:][psrf[i,:,:] 0.99:\n print('Must decrease R_factor for obstype ' + str(i))\n update_srf[i] = -1\n\n if len(pdfs[i,:,:][pdfs[i,:,:]>dfs_lim])/(pdfs.shape[1]*pdfs.shape[2]) > 0.05:\n print('Must reduce loc_rad for obstype ' + str(i))\n update_dfs[i] = 1\n elif len(pdfs[i,:,:][pdfs[i,:,:] 0.99:\n print('Can increase loc_rad for obstype ' + str(i))\n update_dfs[i] = -1\n\n # If any must be updated run update prm with information regarding which obstypes that should be updated\n # and how they should be updated. Consider to change back to default values when the assimilation is finished \n # with satisfying results\n file_handle.close()\n \n return update_srf, update_dfs\n \n \ndef update_tuning(tuning_file, update_srf, update_dfs):\n# To check each locrad and R_factor obstypes.prm should be searched from top to bottom and each time it passes a name\n# this name should be rembered such that the next locrad and rfactor encoutered belongs to this name\n# It is also important that each obstypes has a locrad specified and an rfractor specified.\n# Must investigate a bit more how this should be done in practice, have a list with 0 and 1 per obs type is probably\n# the easiest.\n\n file1 = open(tuning_file, 'r') \n Lines = file1.readlines()\n ii = -1\n obs_num = -1\n\n for l in Lines:\n ii += 1\n \n if l[0:4] == 'NAME':\n print(l[7:])\n current_obs = l[7:]\n obs_num += 1\n print(obs_num)\n if obs_num < len(update_srf):\n if update_dfs[obs_num] == 1 and l[0:7] == 'RFACTOR':\n rf_old = float(l[10:-1])\n Lines[ii] = 'RFACTOR = '+str(round(rf_old*1.5))+'\\n'\n elif update_dfs[obs_num] == -1 and l[0:7] == 'RFACTOR':\n rf_old = float(l[10:-1])\n Lines[ii] = 'RFACTOR = '+str(round(rf_old*0.75))+'\\n'\n elif update_dfs[obs_num] == -1 and l[0:6] == 'LOCRAD':\n lr_old = float(l[9:-1])\n Lines[ii] = 'RFACTOR = '+str(round(lr_old*0.75))+'\\n'\n elif update_dfs[obs_num] == -1 and l[0:6] == 'LOCRAD':\n lr_old = float(l[9:-1])\n Lines[ii] = 'RFACTOR = '+str(round(lr_old*0.75))+'\\n'\n\ndef update_the_ensemble(enkf_c_dir, EnKF_var,ens_out_dir,ens_date):\n # Update the ensemble, in practise the whole ensemble does not need to be updated, only those that require \n # new initial states, but for now everything can be updated. values should also be checked for consistence, \n # potential large errors should possibly lead to an error, or at least they should be flagged for investigation.\n\n # Get the list of files that was used as input in the correct order, this file should ideally be written to disk.\n file_ens = open(enkf_c_dir+'files_in_ensemble', 'r') \n Lines = file_ens.readlines()\n file_count = 0\n prescripts = ['iced.','ocean.']\n syear = str(ens_date.year)\n smnd = str(ens_date.month)\n if ens_date.month < 10:\n smnd = '0' + smnd\n sday = str(ens_date.day)\n if ens_date.day < 10:\n sday = '0' + sday\n\n zero_checks_0 = ['alvl','qice001','qice002','qice003','qice004','qice005','qice006','qice007'\n 'qsno001','sice001','sice002','sice003','sice004','sice005','sice006','sice007',\n 'vlvl','vsnon']\n qices = ['qice001','qice002','qice003','qice004','qice005','qice006','qice007']\n sices = ['sice001','sice002','sice003','sice004','sice005','sice006','sice007']\n\n #not_update = ['aicen','vicen','vsnon','temp','salt','qice001','qice002','qice003',\n # 'qice004','qice005','qice006','qice007','sice001','sice002','sice003', \n # 'sice004','sice005','sice006','sice007','Tsfcn']\n not_update = []\n\n # Make sure that aicen is first in the list of variables such that this can be used for the other variables \n if EnKF_var.index(\"aicen\") != 0:\n # Switch aicen with the variable that is first in the list\n tlist = copy.deepcopy(EnKF_var)\n tlist[0] = EnKF_var[EnKF_var.index(\"aicen\")]\n tlist[EnKF_var.index(\"aicen\")] = EnKF_var[0]\n EnKF_var = tlist\n\n\n\n\n for ll in Lines:\n file_count += 1\n for pre in prescripts:\n file = ens_out_dir+pre+syear+smnd+sday+'_'+ll[0:-1]+'.nc' \n print(file)\n org_ds = nc.Dataset(file, 'r+', format='NETCDF4') \n num = str(file_count)\n halo_cells = False\n if file_count < 10:\n num = '0'+num\n \n for var in org_ds.variables.keys():\n if var in EnKF_var:\n if var in not_update:\n fn = enkf_c_dir+'ensemble_6565/mem0'+num+'_'+var+'.nc'\n else:\n fn = enkf_c_dir+'ensemble_6565/mem0'+num+'_'+var+'.nc.analysis'\n mem_ds = nc.Dataset(fn, 'r', format='NETCDF4')\n #print(fn)\n #print(file)\n new_var = mem_ds.variables[var]\n old_var = org_ds.variables[var]\n\n # Check bounds for this file, but what should the bounds be? \n # With the dfs and srf checks it is not expected that the updates are too large, but could probalby\n # check just to make sure.\n # At least SST should never be less than -2 and ice conc should be between 0 and 1.\n\n \n #print(new_var.shape)\n #print(old_var.shape)\n\n if old_var.shape[2]>new_var.shape[3] and pre == 'iced.':\n halo_cells = True\n temp = new_var[:]\n if halo_cells:\n if len(temp.shape) == 3:\n temp2 = np.zeros((temp.shape[0],temp.shape[1]+2, \n temp.shape[2]+2))\n temp2[0,1:-1,1:-1] = temp\n temp = temp2\n elif len(temp.shape) == 4:\n temp2 = np.zeros((temp.shape[0],temp.shape[1], \n temp.shape[2]+2, temp.shape[3]+2))\n temp2[0,:,1:-1,1:-1] = temp\n temp = temp2\n\n if var == 'temp':\n # Temperature cannot be below minus 2 \n temp[temp < -2] = -2\n if var == 'salt':\n # Salinity cannot be less than 0 \n temp[temp < 0] = 0\n\n if var == 'aicen': \n # Check ice boundaries\n temp[temp < 0.01] = 0\n temp[temp > 1] = 1\n # Check that aggregated concentraion is less than 1\n temsum = np.sum(temp,axis=1)+0.01\n temsum[temsum < 1] = 1\n \n for i in range(temp.shape[1]):\n #print(temsum.shape)\n #print(temp[:,i,:,:].shape)\n temp[:,i,:,:] = temp[:,i,:,:]/temsum\n #print(temp[0,:,:,:].shape)\n #print(old_var[:].shape)\n\n #old_var[:] = temp[0,:,:,:]\n\n # These varaibles are to be used for checking the other ice variables,\n # especially zero checks and new ice checks\n aicen = temp[:,:,:,:]\n aice = np.sum(temp,axis=1)\n aice1 = np.ceil(aice)\n \n # Set all variables in zero_checks to zero if there is no ice.\n if var in zero_checks_0:\n temp[aicen == 0] = 0\n \n if var == 'Tsfcn':\n temp[aicen == 0] = 0\n temp[temp > 0] = 0\n temp[temp < -20] = -20\n\n if var in qices:\n # set value of new data to -1e8\n temp[temp > 0] = 0\n temp[temp < -3.6e8] = -3.6e8\n for i in range(temp.shape[1]):\n temp[:,i,:,:] = np.minimum(temp[:,i,:,:],aice1*-1.2e8)\n\n if var in sices:\n temp[temp < 0] = 0\n temp[temp > 31] = 31\n # set value of new data to 4\n for i in range(temp.shape[1]):\n temp[:,i,:,:] = np.maximum(temp[:,i,:,:],aice1*4)\n \n if var == 'qsno001':\n temp[temp > 0] = 0\n temp[temp < -1.4e8] = -1.4e8\n for i in range(temp.shape[1]):\n temp[:,i,:,:] = np.minimum(temp[:,i,:,:],aice1*-1.2e8)\n \n\n if var == 'vicen': \n # Check thickness boundaries\n temp[temp < 0] = 0\n # Set thickness to zero for areas without ice\n temp[aicen == 0] = 0\n \n # Make sure that new ice is also updated if missed by the assimilation\n # Assume that the new thickness is very thin, vicen=aicen just for simplicity,\n # this is not really expected to happen, but can cause numerical errors\n temp = np.maximum(temp,aicen) \n\n if var == 'vsnon': \n temp[temp < 0] = 0\n temp[aicen == 0] = 0 \n \n if pre == 'iced.':\n old_var[:] = temp[0]\n elif pre == 'ocean.':\n old_var[:] = temp\n\n \n mem_ds.close()\n org_ds.close()\n\n file_ens.close()\n #old_var = new_var\n\n\ndef get_osisaf_obs(date,obs_dir,Assim_dir):\n #osisaf_pre = 'ice_conc_nh_ease-125_multi_'\n osisaf_pre = 'ice_conc_nh_polstere-100_multi_'\n osisaf_post = '1200.nc'\n smnd = str(date.month) if date.month > 9 else '0'+str(date.month)\n sday = str(date.day) if date.day > 9 else '0'+str(date.day)\n\n obs_file = obs_dir+str(date.year)+'/'+smnd+'/'+osisaf_pre+str(date.year)+smnd+sday+osisaf_post\n\n file_out = Assim_dir +'/obs/OSISAF/this_day.nc'\n\n # Export concentraion and uncertainty\n cmd('ncks -O -v ice_conc,total_uncertainty '+obs_file+' temp_osisaf1.nc')\n # Rename uncertainty to that read by enkf-c\n cmd('ncrename -v total_uncertainty,error_std temp_osisaf1.nc')\n # Change dimension from percent to decimal concentration\n cmd('ncap2 -O -s \"ice_conc=ice_conc/100\" temp_osisaf1.nc temp_osisaf2.nc')\n cmd('ncap2 -O -s \"error_std=error_std/100\" temp_osisaf2.nc '+file_out)\n\n # Fix nan values \n cmd('ncatted -O -h -a _FillValue,error_std,m,f,-1 '+file_out)\n cmd('ncatted -O -h -a _FillValue,ice_conc,m,f,-1 '+file_out)\n\n # delete temporary files\n cmd('rm temp_osisaf1.nc temp_osisaf2.nc')\n\ndef write_results(date,enkf_c_dir,ens_out_dir,Nens):\n \n smnd = str(date.month) if date.month > 9 else '0'+str(date.month)\n sday = str(date.day) if date.day > 9 else '0'+str(date.day)\n file = enkf_c_dir +'Assim_summary_'+str(date.year)+smnd+sday+'.nc'\n\n # Generate the netcdf, shoudl contain aice, vice, before and after in addition,\n # mem1 aicen before and after and sst and vice\n # Can add more later on\n\n # Read in temp file and use this as template for the dimensions\n print(enkf_c_dir+'ensemble_6565/mem001_temp.nc') \n tt = xr.open_dataset(enkf_c_dir+'ensemble_6565/mem001_temp.nc')\n temp = tt['temp']\n \n print(file)\n ds = nc.Dataset(file, 'w', format='NETCDF4')\n\n time = ds.createDimension('time', None)\n times = ds.createVariable('time', 'f4', ('time',))\n times[:] = nc.date2num(date, units='days since 1990-01-01',\n calendar='gregorian')\n times.units = 'days since 1990-01-01'\n times.calendar='gregorian'\n\n de = ds.createDimension('de', 10) # Ens\n di = ds.createDimension('di', 5) # Ice categories\n dz = ds.createDimension('dz', temp.shape[1]) # Depth levels\n dx = ds.createDimension('dx', temp.shape[2])\n dy = ds.createDimension('dy', temp.shape[3])\n \n\n des = ds.createVariable('de', 'f4', ('de',))\n dis = ds.createVariable('di', 'f4', ('di',))\n dzs = ds.createVariable('dz', 'f4', ('dz',))\n dxs = ds.createVariable('dx', 'f4', ('dx',))\n dys = ds.createVariable('dy', 'f4', ('dy',))\n\n\n des[:] = np.arange(0, Nens, 1.0)\n dis[:] = np.arange(0, 5, 1.0)\n dzs[:] = np.arange(0, temp.shape[1], 1.0)\n dxs[:] = np.arange(0, temp.shape[2], 1.0)\n dys[:] = np.arange(0, temp.shape[3], 1.0)\n\n\n\n tt.close()\n\n\n aicen_mem1_before = ds.createVariable('aicen1_inn', 'f4', ('time','di', 'dx', 'dy',))\n aicen_mem1_after = ds.createVariable('aicen1_out', 'f4', ('time','di', 'dx', 'dy',))\n\n vicen_mem1_before = ds.createVariable('vicen1_inn', 'f4', ('time','di', 'dx', 'dy',))\n vicen_mem1_after = ds.createVariable('vicen1_out', 'f4', ('time','di', 'dx', 'dy',))\n\n aice_before = ds.createVariable('aice_inn', 'f4', ('time','de', 'dx', 'dy',))\n aice_after = ds.createVariable('aice_out', 'f4', ('time','de', 'dx', 'dy',))\n\n vice_before = ds.createVariable('vice_inn', 'f4', ('time','de', 'dx', 'dy',))\n vice_after = ds.createVariable('vice_out', 'f4', ('time','de', 'dx', 'dy',))\n\n temp_mem1_before = ds.createVariable('temp1_inn', 'f4', ('time','dz', 'dx', 'dy',))\n temp_mem1_after = ds.createVariable('temp1_out', 'f4', ('time','dz', 'dx', 'dy',))\n\n sst_before = ds.createVariable('sst_inn', 'f4', ('time','de', 'dx', 'dy',))\n sst_after = ds.createVariable('sst_out', 'f4', ('time','de', 'dx', 'dy',))\n \n\n file_ens = open(enkf_c_dir+'files_in_ensemble', 'r') \n Lines = file_ens.readlines()\n file_count = 0\n\n for ll in Lines:\n file_count += 1\n sens = str(file_count) if file_count > 9 else '0'+str(file_count)\n file_out_ice = ens_out_dir+'iced.'+str(date.year)+smnd+sday+'_'+ll[0:-1]+'.nc' \n file_out_ocn = ens_out_dir+'ocean.'+str(date.year)+smnd+sday+'_'+ll[0:-1]+'.nc'\n\n ############ Write the inn first ###################\n # Write aice_inn to res \n file_inn = enkf_c_dir+'ensemble_6565/mem0'+sens+'_aice.nc'\n handle = xr.open_dataset(file_inn)\n aice_before[0,int(ll[0:-1])-1,:,:] = handle['aice'][0,:,:]\n handle.close()\n\n # Write vice_inn to res \n file_inn = enkf_c_dir+'ensemble_6565/mem0'+sens+'_vice.nc'\n handle = xr.open_dataset(file_inn)\n vice_before[0,int(ll[0:-1])-1,:,:] = handle['vice'][0,:,:]\n handle.close()\n\n # Write sst_inn to res \n file_inn = enkf_c_dir+'ensemble_6565/mem0'+sens+'_sst.nc'\n handle = xr.open_dataset(file_inn)\n sst_before[0,int(ll[0:-1])-1,:,:] = handle['sst'][0,:,:]\n handle.close()\n \n # Write the full member 1 states\n if file_count == 1:\n file_inn = enkf_c_dir+'ensemble_6565/mem0'+sens+'_aicen.nc'\n handle = xr.open_dataset(file_inn)\n aicen_mem1_before[0,:,:,:] = handle['aicen'][0,:,:,:]\n nx_size = handle['aicen'].shape[2]\n handle.close()\n\n file_inn = enkf_c_dir+'ensemble_6565/mem0'+sens+'_vicen.nc'\n handle = xr.open_dataset(file_inn)\n vicen_mem1_before[0,:,:,:] = handle['vicen'][0,:,:,:]\n handle.close()\n \n file_inn = enkf_c_dir+'ensemble_6565/mem0'+sens+'_temp.nc'\n handle = xr.open_dataset(file_inn)\n temp_mem1_before[0,:,:,:] = handle['temp'][0,:,:,:]\n handle.close()\n ###################################################################\n\n ##################### Write the out results #####################\n handle = xr.open_dataset(file_out_ocn)\n sst_after[0,int(ll[0:-1])-1,:,:] = handle['temp'][0,41,:,:]\n if file_count == 1:\n temp_mem1_after[0,:,:,:] = handle['temp'][0,:,:,:]\n handle.close()\n\n \n handle = xr.open_dataset(file_out_ice)\n nx_size2 = handle['aicen'].shape[1]\n ice_halo_cells = True if nx_size2 > nx_size else False\n\n if ice_halo_cells:\n aice_after[0,int(ll[0:-1])-1,:,:] = np.sum(handle['aicen'][:,1:-1,1:-1],axis=0)\n vice_after[0,int(ll[0:-1])-1,:,:] = np.sum(handle['vicen'][:,1:-1,1:-1],axis=0)\n if file_count == 1:\n aicen_mem1_after[0,:,:,:] = handle['aicen'][:,1:-1,1:-1]\n vicen_mem1_after[0,:,:,:] = handle['vicen'][:,1:-1,1:-1]\n else:\n aice_after[0,int(ll[0:-1])-1,:,:] = np.sum(handle['aicen'][:,:,:],axis=0)\n vice_after[0,int(ll[0:-1])-1,:,:] = np.sum(handle['vicen'][:,:,:],axis=0)\n if file_count == 1:\n aicen_mem1_after[0,:,:,:] = handle['aicen'][:,:,:]\n vicen_mem1_after[0,:,:,:] = handle['vicen'][:,:,:]\n\n\n\n ####################################################################\n\n ##################### Also write the observations for easy reference? #####\n # Might convert it first so it might be easier to compare? ################\n # With several observations potentially a list of string could be used here,\n #OSISAF\n file_osisaf = enkf_c_dir+'obs/OSISAF/this_day.nc'\n grid_file = enkf_c_dir+'conf/new_grid_ice.nc'\n\n handle = xr.open_dataset(file_osisaf)\n ice_conc = handle['ice_conc']\n lon_obs = handle['lon']\n lat_obs = handle['lat']\n obs_grid_def = geometry.GridDefinition(lons=lon_obs, lats=lat_obs)\n\n\n handle2 = xr.open_dataset(grid_file)\n lon_mod = handle2['lon']\n lat_mod = handle2['lat']\n mod_grid_def = geometry.GridDefinition(lons=lon_mod, lats=lat_mod)\n\n # Fix future warning!\n obs_container = image.ImageContainerNearest(ice_conc[0,:,:].values, \n obs_grid_def, radius_of_influence=20000)\n obs_modelgrid = obs_container.resample(mod_grid_def)\n res = obs_modelgrid.image_data\n\n\n Obs1 = ds.createVariable('Obs1', 'f4', ('time','dx', 'dy',))\n Obs1[0,:,:] = res[:]\n\n\n ds.close()\n","sub_path":"python_tools/enkf_c_toolbox.py","file_name":"enkf_c_toolbox.py","file_ext":"py","file_size_in_byte":38513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"7520752","text":"# coding=UTF-8\n#!/usr/bin/env python\nimport pygame,sys,time,random\nfrom pygame.locals import *\nimport numpy as np\nimport copy\nblackColour = pygame.Color(0,0,0)\nwhiteColour = pygame.Color(255,255,255)\nredColour = pygame.Color(255,0,0)\nclass game:\n def __init__(self):\n pygame.init()\n self.fpsClock = pygame.time.Clock()\n self.playSurface = pygame.display.set_mode((300,500))\n pygame.display.set_caption('Raspberry Snake')\n self.snakePosition = [140,240]\n self.snakeSegments = [[140,240]]\n x = random.randrange(0,15)\n y = random.randrange(0,25)\n self.raspberryPosition = [int(x*20),int(y*20)]\n self.raspberrySpawned = 1\n a=random.randint(0,3)\n if a==0:\n self.direction = 'right'\n if a==1:\n self.direction = 'left'\n if a==2:\n self.direction = 'up'\n if a==3:\n self.direction = 'down'\n self.changeDirection = self.direction\n def frame_step(self,input_actions):\n q=0 \n terminal=False \n if sum(input_actions) != 1:\n raise ValueError('Multiple input actions!')\n\n if input_actions[0]==1:\n self.changeDirection = 'right'\n if input_actions[1]==1:\n self.changeDirection = 'left'\n if input_actions[2]==1:\n self.changeDirection = 'up'\n if input_actions[3]==1:\n self.changeDirection = 'down'\n\n if input_actions[0]==1 and not self.direction == 'left':\n self.direction = self.changeDirection\n if input_actions[1]==1 and not self.direction == 'right':\n self.direction = self.changeDirection\n if input_actions[2]==1 and not self.direction == 'down':\n self.direction = self.changeDirection\n if input_actions[3]==1 and not self.direction == 'up':\n self.direction = self.changeDirection\n # 根据方向移动蛇头的坐标\n if self.direction == 'right':\n self.snakePosition[0] += 20\n \n if self.direction == 'left':\n self.snakePosition[0] -= 20\n \n if self.direction == 'up':\n self.snakePosition[1] -= 20\n \n if self.direction == 'down':\n self.snakePosition[1] += 20\n \n # 增加蛇的长度\n self.snakeSegments.insert(0,list(self.snakePosition))\n \n # 判断是否吃掉了树莓\n if self.snakePosition[0] == self.raspberryPosition[0] and self.snakePosition[1] == self.raspberryPosition[1]:\n self.raspberrySpawned = 0\n else:\n self.snakeSegments.pop()\n # 如果吃掉树莓,则重新生成树莓\n if self.raspberrySpawned == 0:\n while(True):\n x = random.randrange(0,15)\n y = random.randrange(0,25)\n self.raspberryPosition = [int(x*20),int(y*20)]\n for position in self.snakeSegments:\n if position==self.raspberryPosition:\n q=1\n if q==1:\n q=0\n continue\n else:\n break\n self.raspberrySpawned = 1\n q=0\n self.playSurface.fill(blackColour)\n for position in self.snakeSegments:\n pygame.draw.rect(self.playSurface,whiteColour,Rect(position[0],position[1],20,20))\n pygame.draw.rect(self.playSurface,redColour,Rect(self.raspberryPosition[0], self.raspberryPosition[1],20,20))\n pygame.display.flip()\n image_data = pygame.surfarray.array3d(pygame.display.get_surface())\n\n if self.snakePosition[0] > 280 or self.snakePosition[0] < 0:\n terminal=True\n self.__init__()\n \n if self.snakePosition[1] > 480 or self.snakePosition[1] < 0:\n terminal=True\n self.__init__()\n\n pygame.display.update()\n\n self.fpsClock.tick(30)\n return image_data,terminal\n\n\n","sub_path":"t2.py","file_name":"t2.py","file_ext":"py","file_size_in_byte":3999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"468055957","text":"import tensorflow as tf\nimport numpy as np\nfrom collections import OrderedDict\nimport pandas as pd\n\nfile=\"glove.6B.50d.txt\"\n\ndf=pd.read_csv(file,sep=\" \",quoting=3, header=None, index_col=0)\nglove = {key: val.values for key, val in df.T.items()}\n\nwords=list(glove.keys())\nemb=np.array(list(glove.values()))\n\ninput_str = \"like the country\"\nword_to_idx = OrderedDict({w:words.index(w) for w in input_str.split() if w in words})\n\ntf.InteractiveSession()\ntf_embedding = tf.constant(emb, dtype=tf.float32)\ntf.nn.embedding_lookup(tf_embedding, list(word_to_idx.values())).eval()\n\n\n","sub_path":"QuestionAnswering/MohamedUvaiz/glove_embedding.py","file_name":"glove_embedding.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"250601144","text":"import numpy as np\nimport scipy.stats\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom bootcamp_utils import *\nimport pandas as pd\n\ngrant_1973 = pd.read_csv('data/grant_1973.csv', comment='#')\ngrant_1975 = pd.read_csv('data/grant_1975.csv', comment='#')\ngrant_1987 = pd.read_csv('data/grant_1987.csv', comment='#')\ngrant_1991 = pd.read_csv('data/grant_1991.csv', comment='#')\ngrant_2012 = pd.read_csv('data/grant_2012.csv', comment='#')\n\ngrant_1973 = grant_1973.rename(columns={'yearband': 'year', 'beak length': 'beak length (mm)', 'beak depth':'beak depth (mm)'})\ngrant_1975 = grant_1973.rename(columns={'Beak length, mm': 'beak length (mm)', 'Beak depth, mm': 'beak depth (mm)'})\ngrant_1987 = grant_1987.rename(columns={'Beak length, mm': 'beak length (mm)', 'Beak depth, mm': 'beak depth (mm)'})\ngrant_1991 = grant_1991.rename(columns={'blength': 'beak length (mm)', 'bdepth': 'beak depth (mm)'})\ngrant_2012 = grant_2012.rename(columns={'blength': 'beak length (mm)', 'bdepth': 'beak depth (mm)'})\n\ngrant_1973.loc[:, 'year'] = 1973\ngrant_1975['year'] = 1975\ngrant_1987['year'] = 1987\ngrant_1991['year'] = 1991\ngrant_2012['year'] = 2012\n\ndf = pd.concat((grant_1973, grant_1975, grant_1987, grant_1991, grant_2012), ignore_index=True)\n\ndf.to_csv('data/grant_complete_practice.csv', index=False)\n\ndf = df.drop_duplicates()\n\nx, y = ecdf(df)\n","sub_path":"exercise_4.py","file_name":"exercise_4.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"51714711","text":"from data.data_pipe import de_preprocess, get_train_loader, get_val_data, get_common_val_data\nfrom model import Backbone, Arcface, MobileFaceNet, Am_softmax, l2_norm, MetricNet\nfrom verifacation import evaluate\nimport torch\nfrom torch import optim\nimport numpy as np\nfrom tqdm import tqdm\nfrom tensorboardX import SummaryWriter\nfrom matplotlib import pyplot as plt\nimport torch.nn as nn\n\nimport time\n\nplt.switch_backend('agg')\nfrom utils import get_time, gen_plot, hflip_batch, separate_bn_paras\nfrom PIL import Image\nfrom torchvision import transforms as trans\nimport math\nimport bcolz\nimport torchvision\nfrom metric_learning import ArcMarginProduct, AddMarginProduct, AdaCos\n\nfrom torch.nn import functional as F\n\n\ndef denormalize_image(img, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), is_tensor=True):\n max_pixel_value = 255.\n mean = np.array(mean, dtype=np.float32)\n mean *= max_pixel_value\n\n std = np.array(std, dtype=np.float32)\n std *= max_pixel_value\n denominator = np.reciprocal(std, dtype=np.float32)\n if is_tensor:\n img = img.cpu().numpy()\n img = np.transpose(img, (1, 2, 0))\n img /= denominator\n img += mean\n if is_tensor:\n img = img.astype(np.uint8)\n return img\n\n\nclass face_learner(object):\n def __init__(self, conf, inference=False, train_transforms=None, val_transforms=None, train_loader=None):\n print(conf)\n if conf.use_mobilfacenet:\n self.model = MobileFaceNet(conf.embedding_size).to(conf.device)\n print('MobileFaceNet model generated')\n else:\n\n self.milestones = conf.milestones\n if train_loader is None:\n self.loader, self.class_num = get_train_loader(conf, train_transforms)\n else:\n self.loader = train_loader\n self.class_num = conf.num_classes\n\n if conf.net_mode in ['ir', 'ir_se']:\n self.model = Backbone(conf.net_depth, conf.drop_ratio, conf.net_mode, conf.use_gap).to(conf.device)\n else:\n import json\n self.model = MetricNet(model_name=conf.net_mode,\n pooling=conf.pooling,\n use_fc=True,\n fc_dim=conf.embedding_size,\n dropout=conf.last_fc_dropout,\n pretrained=conf.pretrained,\n class_num=self.class_num).to(conf.device)\n print('{}_{} model generated'.format(conf.net_mode, conf.net_depth))\n\n if conf.use_mobilfacenet or conf.net_mode in ['ir', 'ir_se']:\n self.head = Arcface(embedding_size=conf.embedding_size, classnum=self.class_num).to(conf.device)\n else:\n if conf.loss_module == 'arcface':\n self.head = ArcMarginProduct(self.model.final_in_features, self.class_num,\n s=conf.s, m=conf.margin, easy_margin=False, ls_eps=conf.ls_eps).to(\n conf.device)\n elif conf.loss_module == 'cosface':\n self.head = AddMarginProduct(self.model.final_in_features, self.class_num, s=conf.s,\n m=conf.margin).to(conf.device)\n elif conf.loss_module == 'adacos':\n self.head = AdaCos(self.model.final_in_features, self.class_num, m=conf.margin,\n theta_zero=conf.theta_zero).to(conf.device)\n else:\n self.head = nn.Linear(self.model.final_in_features, self.class_num).to(conf.device)\n\n print('two model heads generated')\n if conf.ft_model_path:\n self.load_ft_model(conf.ft_model_path, not conf.no_strict)\n elif conf.restore_suffix:\n self.load_state(conf, conf.restore_suffix, from_save_folder=False, model_only=False)\n\n if not inference:\n\n self.writer = SummaryWriter(conf.log_path)\n self.step = 0\n\n paras_only_bn, paras_wo_bn = separate_bn_paras(self.model)\n\n if conf.use_mobilfacenet:\n params = [\n {'params': paras_wo_bn[:-1], 'weight_decay': 4e-5},\n {'params': [paras_wo_bn[-1]] + [self.head.kernel], 'weight_decay': 4e-4},\n {'params': paras_only_bn}\n ]\n wd = 4e-5\n else:\n # if conf.net_mode in ['ir', 'ir_se']:\n # params = [\n # {'params': paras_wo_bn + [self.head.weight], 'weight_decay': 5e-4},\n # {'params': paras_only_bn}\n # ]\n params = [\n {'params': paras_wo_bn + [self.head.kernel], 'weight_decay': 5e-4},\n {'params': paras_only_bn}\n ]\n wd = 5e-4\n # else:\n # params = self.model.parameters()\n # wd = conf.wd\n # # params = [\n # # {'params': paras_wo_bn + [self.head.weight], 'weight_decay': conf.wd}, # 5e-4},\n # # {'params': paras_only_bn}\n # # ]\n\n if conf.optimizer == 'sgd':\n self.optimizer = optim.SGD(params, lr=conf.lr, momentum=conf.momentum) # , weight_decay=wd)\n elif conf.optimizer == 'adam':\n self.optimizer = optim.Adam(params, lr=conf.lr) # , weight_decay=wd)\n print(self.optimizer)\n # self.scheduler = optim.lr_scheduler.ReduceLROnPlateau(self.optimizer, patience=40, verbose=True)\n\n print('optimizers generated')\n self.board_loss_every = len(self.loader) // 100\n self.evaluate_every = len(self.loader) // 10\n self.save_every = len(self.loader) // 5\n\n self.board_loss_every = 20\n self.evaluate_every = len(self.loader)\n self.save_every = len(self.loader)\n if conf.data_mode == 'common':\n import json\n val_img_dir_map = json.loads(conf.val_img_dirs)\n self.val_dataloaders = {}\n for val_name in val_img_dir_map:\n val_img_dir = val_img_dir_map[val_name]\n val_dataloader, common_val_issame = get_common_val_data(val_img_dir,\n conf.max_positive_cnt,\n conf.val_batch_size,\n conf.val_pin_memory,\n conf.num_workers,\n val_transforms=val_transforms,\n use_pos=not conf.not_use_pos,\n use_neg=not conf.not_use_neg,\n val_smapling_type=conf.val_smapling_type,\n use_keras_model=conf.use_val_left_right_check)\n self.val_dataloaders[val_name] = [val_dataloader, common_val_issame]\n elif conf.data_mode == 'dacon_landmark':\n\n pass\n else:\n self.agedb_30, self.cfp_fp, self.lfw, self.agedb_30_issame, self.cfp_fp_issame, self.lfw_issame = get_val_data(\n self.loader.dataset.root.parent)\n else:\n self.threshold = conf.threshold\n\n def save_state(self, conf, accuracy, to_save_folder=False, extra=None, model_only=False):\n if to_save_folder:\n save_path = conf.save_path\n else:\n save_path = conf.model_path\n import os\n print('save_path', save_path)\n os.makedirs(str(save_path), exist_ok=True)\n torch.save(\n self.model.state_dict(), save_path /\n ('model_{}_accuracy:{}_step:{}_{}.pth'.format(get_time(), accuracy, self.step,\n extra)))\n if not model_only:\n torch.save(\n self.head.state_dict(), save_path /\n ('head_{}_accuracy:{}_step:{}_{}.pth'.format(get_time(), accuracy,\n self.step,\n extra)))\n torch.save(\n self.optimizer.state_dict(), save_path /\n ('optimizer_{}_accuracy:{}_step:{}_{}.pth'.format(get_time(), accuracy,\n self.step, extra)))\n\n def load_state(self, conf, fixed_str, from_save_folder=False, model_only=False):\n if from_save_folder:\n save_path = conf.save_path\n else:\n save_path = conf.model_path\n self.model.load_state_dict(torch.load(save_path / 'model_{}'.format(fixed_str)))\n if not model_only:\n self.head.load_state_dict(torch.load(save_path / 'head_{}'.format(fixed_str)))\n self.optimizer.load_state_dict(torch.load(save_path / 'optimizer_{}'.format(fixed_str)))\n\n def load_ft_model(self, model_path, strict=False):\n self.model.load_state_dict(torch.load(model_path), strict=strict)\n\n def board_val(self, db_name, accuracy, best_threshold, roc_curve_tensor, pair_cnt=None):\n print(db_name, \"step\", self.step, \"accuracy\", accuracy, \"best_threshold\", best_threshold, \"pair_cnt\", pair_cnt)\n self.writer.add_scalar('{}_accuracy'.format(db_name), accuracy, self.step)\n self.writer.add_scalar('{}_best_threshold'.format(db_name), best_threshold, self.step)\n self.writer.add_image('{}_roc_curve'.format(db_name), roc_curve_tensor, self.step)\n\n # self.writer.add_scalar('{}_val:true accept ratio'.format(db_name), val, self.step)\n # self.writer.add_scalar('{}_val_std'.format(db_name), val_std, self.step)\n # self.writer.add_scalar('{}_far:False Acceptance Ratio'.format(db_name), far, self.step)\n\n def evaluate(self, conf, carray, issame, nrof_folds=5, tta=False):\n self.model.eval()\n idx = 0\n embeddings = np.zeros([len(carray), conf.embedding_size])\n with torch.no_grad():\n while idx + conf.batch_size <= len(carray):\n batch = torch.tensor(carray[idx:idx + conf.batch_size])\n if tta:\n fliped = hflip_batch(batch)\n emb_batch = self.model(batch.to(conf.device)) + self.model(fliped.to(conf.device))\n embeddings[idx:idx + conf.batch_size] = l2_norm(emb_batch)\n else:\n embeddings[idx:idx + conf.batch_size] = self.model(batch.to(conf.device)).cpu()\n idx += conf.batch_size\n if idx < len(carray):\n batch = torch.tensor(carray[idx:])\n if tta:\n fliped = hflip_batch(batch)\n emb_batch = self.model(batch.to(conf.device)) + self.model(fliped.to(conf.device))\n embeddings[idx:] = l2_norm(emb_batch)\n else:\n embeddings[idx:] = self.model(batch.to(conf.device)).cpu()\n tpr, fpr, accuracy, best_thresholds = evaluate(embeddings, issame, nrof_folds)\n buf = gen_plot(fpr, tpr)\n roc_curve = Image.open(buf)\n roc_curve_tensor = trans.ToTensor()(roc_curve)\n return accuracy.mean(), best_thresholds.mean(), roc_curve_tensor\n\n def evaluate_by_dataloader(self, conf, val_dataloader, val_issame, nrof_folds=5):\n self.model.eval()\n idx = 0\n embeddings = np.zeros([len(val_dataloader.dataset), conf.embedding_size])\n if conf.use_val_left_right_check:\n lr_predicts = []\n with torch.no_grad():\n is_grid = False\n for batch in tqdm(iter(val_dataloader)):\n if conf.use_val_left_right_check:\n imgs, im_arrays = batch\n else:\n imgs = batch\n if not is_grid:\n is_grid = True\n grid = torchvision.utils.make_grid(imgs[:65])\n grid = denormalize_image(grid)\n self.writer.add_image('val_images', grid, self.step, dataformats='HWC')\n # tmp_embed, _ = self.model(imgs.to(conf.device))\n tmp_embed = self.model(imgs.to(conf.device))\n embeddings[idx:idx + len(imgs)] = tmp_embed.cpu()\n\n if conf.use_val_left_right_check:\n # import tensorflow as tf\n lr_model = conf.lr_model\n predicted = lr_model.predict_classes(im_arrays.detach().cpu().numpy())\n for i in range(0, len(predicted), 2):\n lr_predicts.append(predicted[i] == predicted[i + 1])\n idx += len(imgs)\n if conf.use_val_left_right_check:\n tpr, fpr, accuracy, best_thresholds = evaluate(embeddings, val_issame, nrof_folds, pos_thr=conf.pos_thr,\n neg_thr=conf.neg_thr, lr_predicts=lr_predicts)\n else:\n tpr, fpr, accuracy, best_thresholds = evaluate(embeddings, val_issame, nrof_folds, pos_thr=conf.pos_thr,\n neg_thr=conf.neg_thr)\n buf = gen_plot(fpr, tpr)\n roc_curve = Image.open(buf)\n roc_curve_tensor = trans.ToTensor()(roc_curve)\n return accuracy.mean(), best_thresholds.mean(), roc_curve_tensor\n\n def find_lr(self,\n conf,\n init_value=1e-8,\n final_value=10.,\n beta=0.98,\n bloding_scale=3.,\n num=None):\n if not num:\n num = len(self.loader)\n mult = (final_value / init_value) ** (1 / num)\n lr = init_value\n for params in self.optimizer.param_groups:\n params['lr'] = lr\n self.model.train()\n avg_loss = 0.\n best_loss = 0.\n batch_num = 0\n losses = []\n log_lrs = []\n for i, (imgs, labels) in tqdm(enumerate(self.loader), total=num):\n\n imgs = imgs.to(conf.device)\n labels = labels.to(conf.device)\n batch_num += 1\n\n self.optimizer.zero_grad()\n\n embeddings = self.model(imgs)\n thetas = self.head(embeddings, labels)\n loss = conf.ce_loss(thetas, labels)\n\n # Compute the smoothed loss\n avg_loss = beta * avg_loss + (1 - beta) * loss.item()\n self.writer.add_scalar('avg_loss', avg_loss, batch_num)\n smoothed_loss = avg_loss / (1 - beta ** batch_num)\n self.writer.add_scalar('smoothed_loss', smoothed_loss, batch_num)\n # Stop if the loss is exploding\n if batch_num > 1 and smoothed_loss > bloding_scale * best_loss:\n print('exited with best_loss at {}'.format(best_loss))\n plt.plot(log_lrs[10:-5], losses[10:-5])\n return log_lrs, losses\n # Record the best loss\n if smoothed_loss < best_loss or batch_num == 1:\n best_loss = smoothed_loss\n # Store the values\n losses.append(smoothed_loss)\n log_lrs.append(math.log10(lr))\n self.writer.add_scalar('log_lr', math.log10(lr), batch_num)\n # Do the SGD step\n # Update the lr for the next step\n\n loss.backward()\n self.optimizer.step()\n\n lr *= mult\n for params in self.optimizer.param_groups:\n params['lr'] = lr\n if batch_num > num:\n plt.plot(log_lrs[10:-5], losses[10:-5])\n return log_lrs, losses\n\n def train(self, conf, epochs):\n self.model.train()\n running_loss = 0.\n for e in range(epochs):\n if conf.train:\n print('epoch {} started'.format(e))\n if e == self.milestones[0]:\n self.schedule_lr()\n if e == self.milestones[1]:\n self.schedule_lr()\n if e == self.milestones[2]:\n self.schedule_lr()\n # for imgs, labels in tqdm(iter(self.loader)):\n for imgs, labels in self.loader:\n imgs = imgs.to(conf.device)\n labels = labels.to(conf.device)\n self.optimizer.zero_grad()\n embeddings = self.model(imgs)\n thetas = self.head(embeddings, labels)\n loss = conf.ce_loss(thetas, labels)\n loss.backward()\n running_loss += loss.item()\n self.optimizer.step()\n\n if self.step % self.board_loss_every == 0 and self.step != 0:\n loss_board = running_loss / self.board_loss_every\n self.writer.add_scalar('train_loss', loss_board, self.step)\n running_loss = 0.\n\n grid = torchvision.utils.make_grid(imgs[:65])\n grid = denormalize_image(grid)\n self.writer.add_image('train_images', grid, self.step, dataformats='HWC')\n print(\"epoch: {}, step: {}/{}, loss: {}\".format(e, self.step, len(self.loader), loss_board))\n # if self.step % self.evaluate_every == 0 and self.step != 0:\n # if conf.data_mode == 'common':\n # for val_name in self.val_dataloaders:\n # val_dataloader, val_issame = self.val_dataloaders[val_name]\n # accuracy, best_threshold, roc_curve_tensor = self.evaluate_by_dataloader(conf,\n # val_dataloader,\n # val_issame)\n # self.board_val(val_name, accuracy, best_threshold, roc_curve_tensor)\n # else:\n # accuracy, best_threshold, roc_curve_tensor = self.evaluate(conf, self.agedb_30,\n # self.agedb_30_issame)\n # self.board_val('agedb_30', accuracy, best_threshold, roc_curve_tensor)\n # accuracy, best_threshold, roc_curve_tensor = self.evaluate(conf, self.lfw, self.lfw_issame)\n # self.board_val('lfw', accuracy, best_threshold, roc_curve_tensor)\n # accuracy, best_threshold, roc_curve_tensor = self.evaluate(conf, self.cfp_fp,\n # self.cfp_fp_issame)\n # self.board_val('cfp_fp', accuracy, best_threshold, roc_curve_tensor)\n # self.model.train()\n # if self.step % self.save_every == 0 and self.step != 0:\n # self.save_state(conf, accuracy)\n\n self.step += 1\n\n accuracies = []\n if conf.data_mode == 'common':\n for val_name in self.val_dataloaders:\n val_dataloader, val_issame = self.val_dataloaders[val_name]\n accuracy, best_threshold, roc_curve_tensor = self.evaluate_by_dataloader(conf,\n val_dataloader,\n val_issame)\n accuracies.append(accuracy)\n self.board_val(val_name, accuracy, best_threshold, roc_curve_tensor, len(val_issame))\n else:\n accuracy, best_threshold, roc_curve_tensor = self.evaluate(conf, self.agedb_30,\n self.agedb_30_issame)\n self.board_val('agedb_30', accuracy, best_threshold, roc_curve_tensor)\n accuracy, best_threshold, roc_curve_tensor = self.evaluate(conf, self.lfw, self.lfw_issame)\n self.board_val('lfw', accuracy, best_threshold, roc_curve_tensor)\n accuracy, best_threshold, roc_curve_tensor = self.evaluate(conf, self.cfp_fp,\n self.cfp_fp_issame)\n self.board_val('cfp_fp', accuracy, best_threshold, roc_curve_tensor)\n self.model.train()\n\n if not conf.train:\n break\n self.save_state(conf, sum(accuracies) / len(accuracies))\n\n if conf.train:\n self.save_state(conf, accuracy, to_save_folder=True, extra='final')\n\n def train_landmark(self, conf, epochs):\n self.model.train()\n running_loss = 0.\n for e in range(epochs):\n if conf.train:\n print('epoch {} started'.format(e))\n if e == self.milestones[0]:\n self.schedule_lr()\n if e == self.milestones[1]:\n self.schedule_lr()\n if e == self.milestones[2]:\n self.schedule_lr()\n # for imgs, labels in tqdm(iter(self.loader)):\n for imgs, labels in self.loader:\n imgs = imgs.to(conf.device)\n labels = labels.to(conf.device)\n self.optimizer.zero_grad()\n embeddings, output = self.model(imgs)\n loss_prev = conf.ce_loss(output, labels)\n thetas = self.head(embeddings, labels)\n loss = conf.ce_loss(thetas, labels)\n loss += loss_prev\n loss.backward()\n running_loss += loss.item()\n self.optimizer.step()\n\n if self.step % self.board_loss_every == 0 and self.step != 0:\n loss_board = running_loss / self.board_loss_every\n self.writer.add_scalar('train_loss', loss_board, self.step)\n running_loss = 0.\n\n grid = torchvision.utils.make_grid(imgs[:65])\n grid = denormalize_image(grid)\n self.writer.add_image('train_images', grid, self.step, dataformats='HWC')\n print(\"epoch: {}, step: {}/{}, loss: {}\".format(e, self.step, len(self.loader), loss_board))\n # if self.step % self.evaluate_every == 0 and self.step != 0:\n # if conf.data_mode == 'common':\n # for val_name in self.val_dataloaders:\n # val_dataloader, val_issame = self.val_dataloaders[val_name]\n # accuracy, best_threshold, roc_curve_tensor = self.evaluate_by_dataloader(conf,\n # val_dataloader,\n # val_issame)\n # self.board_val(val_name, accuracy, best_threshold, roc_curve_tensor)\n # else:\n # accuracy, best_threshold, roc_curve_tensor = self.evaluate(conf, self.agedb_30,\n # self.agedb_30_issame)\n # self.board_val('agedb_30', accuracy, best_threshold, roc_curve_tensor)\n # accuracy, best_threshold, roc_curve_tensor = self.evaluate(conf, self.lfw, self.lfw_issame)\n # self.board_val('lfw', accuracy, best_threshold, roc_curve_tensor)\n # accuracy, best_threshold, roc_curve_tensor = self.evaluate(conf, self.cfp_fp,\n # self.cfp_fp_issame)\n # self.board_val('cfp_fp', accuracy, best_threshold, roc_curve_tensor)\n # self.model.train()\n # if self.step % self.save_every == 0 and self.step != 0:\n # self.save_state(conf, accuracy)\n\n self.step += 1\n\n accuracies = []\n if conf.data_mode == 'common':\n for val_name in self.val_dataloaders:\n val_dataloader, val_issame = self.val_dataloaders[val_name]\n accuracy, best_threshold, roc_curve_tensor = self.evaluate_by_dataloader(conf,\n val_dataloader,\n val_issame)\n accuracies.append(accuracy)\n self.board_val(val_name, accuracy, best_threshold, roc_curve_tensor, len(val_issame))\n else:\n accuracy, best_threshold, roc_curve_tensor = self.evaluate(conf, self.agedb_30,\n self.agedb_30_issame)\n self.board_val('agedb_30', accuracy, best_threshold, roc_curve_tensor)\n accuracy, best_threshold, roc_curve_tensor = self.evaluate(conf, self.lfw, self.lfw_issame)\n self.board_val('lfw', accuracy, best_threshold, roc_curve_tensor)\n accuracy, best_threshold, roc_curve_tensor = self.evaluate(conf, self.cfp_fp,\n self.cfp_fp_issame)\n self.board_val('cfp_fp', accuracy, best_threshold, roc_curve_tensor)\n self.model.train()\n\n if not conf.train:\n break\n self.save_state(conf, sum(accuracies) / len(accuracies))\n\n if conf.train:\n self.save_state(conf, accuracy, to_save_folder=True, extra='final')\n\n def train_font(self, conf, epochs):\n self.model.train()\n running_loss = 0.\n for e in range(epochs):\n if conf.train:\n print('epoch {} started'.format(e))\n if e == self.milestones[0]:\n self.schedule_lr()\n if e == self.milestones[1]:\n self.schedule_lr()\n if e == self.milestones[2]:\n self.schedule_lr()\n # for imgs, labels in tqdm(iter(self.loader)):\n for imgs, labels in self.loader:\n imgs = imgs.to(conf.device)\n labels = labels.to(conf.device)\n self.optimizer.zero_grad()\n embeddings = self.model(imgs)\n print(embeddings.shape)\n thetas = self.head(embeddings, labels)\n print(thetas.shape)\n loss = conf.ce_loss(thetas, labels)\n loss.backward()\n running_loss += loss.item()\n self.optimizer.step()\n\n if self.step % self.board_loss_every == 0 and self.step != 0:\n loss_board = running_loss / self.board_loss_every\n self.writer.add_scalar('train_loss', loss_board, self.step)\n running_loss = 0.\n\n grid = torchvision.utils.make_grid(imgs[:65])\n grid = denormalize_image(grid)\n self.writer.add_image('train_images', grid, self.step, dataformats='HWC')\n print(\"epoch: {}, step: {}, loss: {}\".format(e, self.step, loss_board))\n # if self.step % self.evaluate_every == 0 and self.step != 0:\n # if conf.data_mode == 'common':\n # for val_name in self.val_dataloaders:\n # val_dataloader, val_issame = self.val_dataloaders[val_name]\n # accuracy, best_threshold, roc_curve_tensor = self.evaluate_by_dataloader(conf,\n # val_dataloader,\n # val_issame)\n # self.board_val(val_name, accuracy, best_threshold, roc_curve_tensor)\n # else:\n # accuracy, best_threshold, roc_curve_tensor = self.evaluate(conf, self.agedb_30,\n # self.agedb_30_issame)\n # self.board_val('agedb_30', accuracy, best_threshold, roc_curve_tensor)\n # accuracy, best_threshold, roc_curve_tensor = self.evaluate(conf, self.lfw, self.lfw_issame)\n # self.board_val('lfw', accuracy, best_threshold, roc_curve_tensor)\n # accuracy, best_threshold, roc_curve_tensor = self.evaluate(conf, self.cfp_fp,\n # self.cfp_fp_issame)\n # self.board_val('cfp_fp', accuracy, best_threshold, roc_curve_tensor)\n # self.model.train()\n # if self.step % self.save_every == 0 and self.step != 0:\n # self.save_state(conf, accuracy)\n\n self.step += 1\n\n accuracies = []\n if conf.data_mode == 'common':\n for val_name in self.val_dataloaders:\n val_dataloader, val_issame = self.val_dataloaders[val_name]\n accuracy, best_threshold, roc_curve_tensor = self.evaluate_by_dataloader(conf,\n val_dataloader,\n val_issame)\n accuracies.append(accuracy)\n self.board_val(val_name, accuracy, best_threshold, roc_curve_tensor, len(val_issame))\n else:\n accuracy, best_threshold, roc_curve_tensor = self.evaluate(conf, self.agedb_30,\n self.agedb_30_issame)\n self.board_val('agedb_30', accuracy, best_threshold, roc_curve_tensor)\n accuracy, best_threshold, roc_curve_tensor = self.evaluate(conf, self.lfw, self.lfw_issame)\n self.board_val('lfw', accuracy, best_threshold, roc_curve_tensor)\n accuracy, best_threshold, roc_curve_tensor = self.evaluate(conf, self.cfp_fp,\n self.cfp_fp_issame)\n self.board_val('cfp_fp', accuracy, best_threshold, roc_curve_tensor)\n self.model.train()\n\n if not conf.train:\n break\n\n self.save_state(conf, sum(accuracies) / len(accuracies))\n\n if conf.train:\n self.save_state(conf, accuracy, to_save_folder=True, extra='final')\n\n def schedule_lr(self):\n for params in self.optimizer.param_groups:\n params['lr'] /= 10\n print(self.optimizer)\n\n def infer(self, conf, faces, target_embs, tta=False):\n '''\n faces : list of PIL Image\n target_embs : [n, 512] computed embeddings of faces in facebank\n names : recorded names of faces in facebank\n tta : test time augmentation (hfilp, that's all)\n '''\n embs = []\n for img in faces:\n if tta:\n mirror = trans.functional.hflip(img)\n emb = self.model(conf.test_transform(img).to(conf.device).unsqueeze(0))\n emb_mirror = self.model(conf.test_transform(mirror).to(conf.device).unsqueeze(0))\n embs.append(l2_norm(emb + emb_mirror))\n else:\n embs.append(self.model(conf.test_transform(img).to(conf.device).unsqueeze(0)))\n source_embs = torch.cat(embs)\n\n diff = source_embs.unsqueeze(-1) - target_embs.transpose(1, 0).unsqueeze(0)\n dist = torch.sum(torch.pow(diff, 2), dim=1)\n minimum, min_idx = torch.min(dist, dim=1)\n min_idx[minimum > self.threshold] = -1 # if no match, set idx to -1\n return min_idx, minimum\n","sub_path":"Learner.py","file_name":"Learner.py","file_ext":"py","file_size_in_byte":33574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"573976944","text":"\"\"\"\n题目:\n请实现一个函数用来匹配包括'.'和'*'的正则表达式。\n模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。\n在本题中,匹配是指字符串的所有字符匹配整个模式。\n\n例如:\n字符串\"aaa\"与模式\"a.a\"和\"ab*ac*a\"匹配,但是与\"aa.a\"和\"ab*a\"均不匹配\n\"\"\"\n\n\ndef re_match(string, pattern):\n len_s = len(string)\n len_p = len(pattern)\n\n # 如果s与pattern都为空,则True\n if len_s == 0 and len_p == 0:\n return True\n\n # 如果s不为空,而pattern为空,则False\n elif len_s != 0 and len_p == 0:\n return False\n\n # 如果s为空,而pattern不为空,则需要判断\n elif len_s == 0 and len_p != 0:\n # pattern中的第二个字符为*,则pattern后移两位继续比较\n if len_p > 1 and pattern[1] == '*':\n return re_match(string, pattern[2:])\n else:\n return False\n\n # s与pattern都不为空的情况\n else:\n # pattern的第二个字符为*的情况\n if len_p > 1 and pattern[1] == '*':\n # s与pattern的第一个元素不同,则s不变,pattern后移两位,相当于pattern前两位当成空\n if string[0] != pattern[0] and pattern[0] != '.':\n return re_match(string, pattern[2:])\n else:\n # 如果s[0]与pattern[0]相同,且pattern[1]为*,这个时候有三种情况\n # pattern后移2个,s不变;相当于把pattern前两位当成空,匹配后面的\n # pattern后移2个,s后移1个;相当于pattern前两位与s[0]匹配\n # pattern不变,s后移1个;相当于pattern前两位,与s中的多位进行匹配,因为*可以匹配多位\n return re_match(string, pattern[2:]) or \\\n re_match(string[1:], pattern[2:]) or \\\n re_match(string[1:], pattern)\n # pattern第二个字符不为*的情况\n else:\n if string[0] == pattern[0] or pattern[0] == '.':\n return re_match(string[1:], pattern[1:])\n else:\n return False\n\n\nif __name__ == '__main__':\n print(re_match('aaa', 'ab*ac*a'))\n print(re_match('aaa', 'a.a'))\n print(re_match('aaa', 'aa.a'))\n print(re_match('aaa', 'ab*a'))\n","sub_path":"剑指offer/19_re_match.py","file_name":"19_re_match.py","file_ext":"py","file_size_in_byte":2373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"622500572","text":"import pandas as pd\nfrom keras.preprocessing.text import one_hot\n\n\nclass FeatureGenerator:\n @staticmethod\n def load_data(dataset: str, url_column_name=\"url\", label_column_name=\"label\", to_binarize=False,\n neg_word=\"bad\") -> tuple:\n \"\"\"\n Load given data file into self.urls and self.labels\n\n Parameters\n ----------\n dataset\n Path of csv file containing the dataset.\n url_column_name\n Name of the column containing the urls.\n label_column_name\n Name of the column containing the labels.\n to_binarize\n True if the label column is not already in binary form.\n neg_word\n Negative word in the label column. Only considered if 'to_binarize' is True.\n\n Returns\n -------\n tuple\n (list containing the urls, list containing the labels)\n \"\"\"\n\n def binarize_list(element: str) -> int:\n \"\"\"Binarize given element.\"\"\"\n if element == neg_word:\n return 1\n else:\n return 0\n\n dataframe: pd.DataFrame = pd.read_csv(dataset)\n urls = dataframe[url_column_name].tolist()\n labels = list(map(binarize_list, dataframe[label_column_name].tolist())) if to_binarize else dataframe[\n label_column_name].tolist()\n return urls, labels\n\n @staticmethod\n def one_hot_encoding(urls: list, vocab_size=87) -> list:\n \"\"\"Integer encode the documents\"\"\"\n encoded_docs = [one_hot(str(d), vocab_size) for d in urls]\n return encoded_docs\n","sub_path":"feature_generator.py","file_name":"feature_generator.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"619862164","text":"import os\nfrom hashlib import sha256\n\n\nclass FileStore:\n \"\"\"\n A file based implementation of a key value store.\n \"\"\"\n def __init__(self, dbDir, dbName, isLineNoKey: bool=False,\n storeContentHash: bool=True, ensureDurability: bool=True):\n \"\"\"\n :param dbDir: The directory where the file storing the data would be\n present\n :param dbName: The name of the file that is used to store the data\n :param isLineNoKey: If false then each line has the key followed by a\n delimiter followed by the value\n :param storeContentHash: Whether to store a hash of the value or not.\n Storing hash can make it really fast to compare the value for equality\n :param ensureDurability: Should the file be fysnced after every write.\n This can ensure durability in most of the cases, but make\n writes extremely slow. See testMeasureWriteTime. For frequent writes,\n it makes sense to disable flush and fsync on every write\n \"\"\"\n self.isLineNoKey = isLineNoKey\n self.storeContentHash = storeContentHash\n self.ensureDurability = ensureDurability\n\n def _prepareDBLocation(self, dbDir, dbName):\n self.dbDir = dbDir\n self.dbName = dbName\n if not os.path.exists(self.dbDir):\n os.makedirs(self.dbDir)\n\n def _initDB(self, dbDir, dbName):\n self._prepareDBLocation(dbDir, dbName)\n\n # noinspection PyUnresolvedReferences\n def put(self, value, key=None):\n # If line no is not treated as key then write the key and then the\n # delimiter\n if not self.isLineNoKey:\n if key is None:\n raise ValueError(\"Key must be provided for storing the value\")\n self.dbFile.write(key)\n self.dbFile.write(self.delimiter)\n\n self.dbFile.write(value)\n\n if self.storeContentHash:\n self.dbFile.write(self.delimiter)\n if isinstance(value, str):\n value = value.encode()\n hexedHash = sha256(value).hexdigest()\n self.dbFile.write(hexedHash)\n self.dbFile.write(self.lineSep)\n\n # A little bit smart strategy like flush every 2 seconds\n # or every 10 writes or every 1 KB may be a better idea\n # Make sure data get written to the disk\n # Even flush slows down writes significantly\n self.dbFile.flush()\n\n if self.ensureDurability:\n # fsync takes too much time on Windows.\n # This is the reason of test_merkle_proof tests slowness on Windows.\n # Even on Linux using fsync slows down the test by at least 2\n # orders of magnitude. See testMeasureWriteTime\n os.fsync(self.dbFile.fileno())\n\n def get(self, key):\n for k, v in self.iterator():\n if k == key:\n return v\n\n def _keyIterator(self, lines, prefix=None):\n return self._baseIterator(lines, prefix, True, False)\n\n def _valueIterator(self, lines, prefix=None):\n return self._baseIterator(lines, prefix, False, True)\n\n def _keyValueIterator(self, lines, prefix=None):\n return self._baseIterator(lines, prefix, True, True)\n\n # noinspection PyUnresolvedReferences\n def _baseIterator(self, lines, prefix, returnKey: bool, returnValue: bool):\n i = 1\n for line in lines:\n if self.isLineNoKey:\n k = str(i)\n v = line\n i += 1\n else:\n k, v = line.split(self.delimiter, 1)\n if returnValue:\n if self.storeContentHash:\n value, _ = v.rsplit(self.delimiter, 1)\n else:\n value = v\n if not prefix or k.startswith(prefix):\n if returnKey and returnValue:\n yield (k, value)\n elif returnKey:\n yield k\n elif returnValue:\n yield value\n\n def _getLines(self):\n raise NotImplementedError()\n\n # noinspection PyUnresolvedReferences\n def iterator(self, includeKey=True, includeValue=True, prefix=None):\n if not (includeKey or includeValue):\n raise ValueError(\"At least one of includeKey or includeValue \"\n \"should be true\")\n # Move to the beginning of file\n self.dbFile.seek(0)\n\n lines = self._getLines()\n if includeKey and includeValue:\n return self._keyValueIterator(lines, prefix=prefix)\n elif includeValue:\n return self._valueIterator(lines, prefix=prefix)\n else:\n return self._keyIterator(lines, prefix=prefix)\n\n @property\n def lastKey(self):\n # TODO use the efficient way of seeking to the end and moving back till\n # 2nd newline(1 st newline would be encountered immediately until its a\n # blank file) is encountered and after newline read ahead till the\n # delimiter or split the read string till now on delimiter\n k = None\n for k, v in self.iterator():\n pass\n return k\n\n @property\n def numKeys(self):\n return sum(1 for l in self.iterator())\n\n # noinspection PyUnresolvedReferences\n def close(self):\n self.dbFile.close()\n\n # noinspection PyUnresolvedReferences\n @property\n def closed(self):\n return self.dbFile.closed\n\n # noinspection PyUnresolvedReferences\n def reset(self):\n self.dbFile.truncate(0)\n","sub_path":"ledger/stores/file_store.py","file_name":"file_store.py","file_ext":"py","file_size_in_byte":5513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"358301458","text":"import dj_database_url\nfrom .settings import *\n\nDATABASES = {\n 'default': dj_database_url.config(),\n}\nSTATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\nALLOWED_HOSTS = ['*']\nDEBUG = True","sub_path":"mysite/production_settings.py","file_name":"production_settings.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"185096163","text":"import time\nimport json\nimport Tkinter as tk \nimport ttk\n\nimport data_bus\nimport wire\nimport GLOBALS\n\nclass Reliability_CruiseCommands(ttk.Frame):\n\tdef __init__(self, root, parent, data_bus, options):\n\t\tself.root = root\n\t\tself.parent = parent\n\t\tself.data_bus = data_bus\n\t\tself.data_bus.record_callback.append(self.handleNewRecord)\n\t\tself.options = options\n\n\t\tself.cruiseCommandFrame = ttk.Labelframe(self.parent, text='Cruise Commands')\n\n\t\tself.setSpeed = ttk.Label(self.cruiseCommandFrame, text='Set Speed: ')\n\t\tself.setSpeed.grid(row=1, column=1)\n\t\tself.setSpeedData = ttk.Label(self.cruiseCommandFrame, text='N/A')\n\t\tself.setSpeedData.grid(row=1, column=2)\n\n\t\tself.limit = ttk.Label(self.cruiseCommandFrame, text='Limit: ')\n\t\tself.limit.grid(row=2, column=1)\n\t\tself.limitData = ttk.Label(self.cruiseCommandFrame, text='N/A')\n\t\tself.limitData.grid(row=2, column=2)\n\n\t\tself.speedEntry = ttk.Entry(self.cruiseCommandFrame, width=5)\n\t\tself.speedEntry.grid(row=3, column=1)\n\t\tself.sendSpeed = ttk.Button(self.cruiseCommandFrame, text='Send Speed')\n\t\tself.sendSpeed.grid(row=3, column=2)\n\n\t\tself.limitEntry = ttk.Entry(self.cruiseCommandFrame, width=5)\n\t\tself.limitEntry.grid(row=4, column=1)\n\t\tself.sendLimit = ttk.Button(self.cruiseCommandFrame, text='Send Limit')\n\t\tself.sendLimit.grid(row=4, column=2)\n\n\tdef handleNewRecord(self, record):\n\t\tfields = record.field.split('\\0')\n\t\tname = fields[0].split('.')\n\t\tif name == ['cruise']:\n\t\t\tmeta = json.loads(fields[1])\n\t\t\tself.harness = wire.Harness(meta['harness'])\n\t\t\trecord.value_callback.append(self.handleValue)\n\t\t\trecord.Subscribe()\n\n\tdef handleValue(self, record):\n\t\tself.harness.buf = buffer(record.value)\n\t\tself.setSpeedData['text'] = \"%.2f\" % (self.harness['speed'].value*GLOBALS.SPEED_UNITS_MULTIPLIER[self.options.unitsVar.get()])\n\t\tself.limitData['text'] = \"%.2f\" % (self.harness['limit'].value*GLOBALS.SPEED_UNITS_MULTIPLIER[self.options.unitsVar.get()])","sub_path":"Telemetry/RF Telems/onboard/modules_can2014/Reliability_CruiseCommandsModule.py","file_name":"Reliability_CruiseCommandsModule.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"108357681","text":"from math import floor\nimport random\nfrom move_list import moves\nfrom damage import damage\n\nclass Pokemon:\n def __init__(self, name, base_stats, typing, ability, move_list, item, nature, effort_value, weight):\n self.name = name\n self.base_stats = base_stats\n self.typing = typing\n self.ability = ability\n self.move_list = move_list\n self.item = item\n self.nature = nature\n self.effort_value = effort_value\n self.weight = weight\n self.damage = 0 #受けたダメージの記憶\n self.alive = True\n self.move_now = moves['None']\n self.zpower = False\n self.calculate()\n\n #ランク補正\n self.rank= {'patk':0,\n 'pdef':0,\n 'spatk':0,\n 'spdef':0,\n 'spe':0,\n 'acc':0,\n 'eva':0}\n\n #状態異常\n self.state = {'まひ':False,\n 'ねむり':0,\n 'こおり':False,\n 'こんらん':0,\n 'ひるみ':False,\n 'やけど':False,\n 'もうどく':0,\n 'どく':False,\n 'ねむけ':0,\n 'やどりぎのたね':False,\n 'のろい':False,\n 'ほろびのうた':0,\n 'マグマストーム':0,\n 'ねがいごと':False,\n 'カウンター':False,\n 'ため':False,\n 'あばれ':0,\n 'みがわり':0,\n 'みちづれ':False,\n 'まもる':0,\n 'キングシールド':0,\n 'ばけのかわ':True,\n 'でんじふゆう':0,\n 'ちょうはつ':0,\n 'アンコール':0,\n 'かなしばり':0, #技へ\n 'のろわれボディ':0,\n 'もらいび':False}\n\n if self.name == 'ギルガルド':\n self.form = True #True = ブレード\n\n if self.ability =='ばけのかわ':\n self.mimi = True\n\n #回復\n def heal(self, percent):\n self.hp += floor(self.old_hp*(percent/100))\n if self.hp > self.old_hp:\n self.hp = self.old_hp\n\n #定数ダメ\n def constant_damage(self, player, name, percent): # 1/に注意\n damage = floor(self.old_hp * (1/percent))\n self.hp -=damage\n print(player.name + ':' + player.battle_poke.name + 'に' + str(damage) + 'の' + name + 'ダメージ')\n\n #定数回復\n def constant_heal(self, player, name, percent): # 1/に注意\n heal = floor(self.old_hp * (1/percent))\n self.hp += heal\n print(player.name + ':' + player.battle_poke.name + 'に' + str(heal) + 'の' + name + '回復')\n\n\n #HPの表示\n def hp_print(self):\n h = floor(20 * self.hp/self.old_hp)\n o = floor(20 * (1 - self.hp/self.old_hp))\n print('|' + '*'*h + 'o'*o + '|' + '..' + str(self.hp) + '/' + str(self.old_hp))\n print()\n\n #攻撃を受ける前のHP\n def set_before_attacked_hp(self):\n self.before_attacked_hp = self.hp\n\n #回復きのみ\n def fruit(self, player):\n if self.item == 'オボンのみ' and self.old_hp/self.hp >= 2:\n self.constant_heal(player, 'オボンのみ', 4)\n self.item = None\n print('オボンのみ')\n\n if self.item == 'きのみ' and self.old_hp/self.hp >= 4:\n self.constant_heal(player, 'きのみ', 4)\n self.item = None\n\n #瀕死判定\n def death_judge(self):\n if self.hp <= 0:\n self.alive = False\n print(self.name + 'は倒された')\n\n #行動判定\n def move_judge(self, own, enemy, field): #field=全体\n #ふいうち\n if self.move_now.name == 'ふいうち':\n if enemy.battle_poke.move_now.category == 'Non-Damaging':\n if enemy.select_atatck:\n return False\n\n #ため\n if self.state['ため'] > 0:\n self.state = 0\n return False\n\n if self.state['ねむり'] >= 1:\n self.state['ねむり'] -= 1\n return False\n\n if self.state['まひ']:\n n = random.randint(1,5)\n if n == 1:\n return False\n\n if self.state['こおり']:\n n = random.randint(1,5)\n if n == 1 or n == 2 or n == 3:\n return False\n\n if self.state['ひるみ']:\n self.state_list['ひるみ'] = False\n return False\n\n if self.state['こんらん'] >= 1:\n n = random.randint(1,4)\n if n == 1:\n self.move_now =moves['こんらん']\n damage(own, own, field)\n print('混乱自傷')\n return False\n\n #サイコフィールド下先制技無効\n if field == 'サイコフィールド':\n if self.move_now.priority >= 1:\n return False\n\n #まもる\n if enemy.battle_poke.state['まもる'] > 0:\n return False\n\n #キングシールド\n if enemy.battle_poke.move_now.name == 'キングシールド' and enemy.battle_poke.state['まもる'] > 0:\n if enemy.battle_poke.move_now.direct:\n enemy.battle_poke.rank['patk'] -= 2\n return False\n\n #命中率\n r = random.randint(1,100)/100\n if self.move_now.accuracy == 'infallible':\n pass\n else:\n if r >= self.move_now.accuracy:\n return False\n #ふうせん\n if self.item == 'ふうせん':\n if enemy.battle_poke.move_now.type == 'Ground':\n return False\n else:\n self.item = None\n\n #ちくでん\n if enemy.battle_poke.ability == 'ちくでん':\n if self.move_now.type == 'Electric':\n enemy.constant_heal(enemy, 'ちくでん', 4)\n return False\n\n #もらいび\n if enemy.battle_poke.ability == 'もらいび':\n enemy.state['もらいび'] = True\n return False\n\n #攻撃可能\n return True\n\n def speed_reset(self):\n self.spe = self.old_spe\n\n def power_reset(self):\n self.patk = self.old_patk\n self.spatk = self.old_spatk\n\n #交代時リセット\n def switch_reset(self):\n #ステータスリセット\n self.patk = self.old_patk\n self.pdef = self.old_pdef\n self.spatk = self.old_spatk\n self.spdef = self.old_spdef\n self.spe = self.old_spe\n #ランクリセット\n self.rank= {'patk':0,\n 'pdef':0,\n 'spatk':0,\n 'spdef':0,\n 'spe':0,\n 'acc':0,\n 'eva':0}\n #技リセット\n for i in range(4):\n self.move_list[i].disable = 0\n\n #状態異常リセット\n self.state = {'こんらん':0,\n 'ひるみ':False,\n 'もうどく':0,\n 'ねむけ':0,\n 'やどりぎのたね':False,\n 'のろい':False,\n 'ほろびのうた':0,\n 'マグマストーム':0,\n 'ねがいごと':False,\n 'カウンター':False,\n 'ため':False,\n 'あばれ':0,\n 'みがわり':0,\n 'みちづれ':False,\n 'まもる':0,\n 'キングシールド':0,\n 'ばけのかわ':True,\n 'でんじふゆう':0,\n 'ちょうはつ':0,\n 'アンコール':0,\n 'かなしばり':0, #技へ\n 'のろわれボディ':0,\n 'もらいび':False}\n\n #ステータス計算\n def calculate(self):\n self.convert_nature()\n\n self.hp = floor((self.base_stats['hp'] + 15.5 + self.effort_value['hp']/8) + 60)\n\n self.patk = floor((self.base_stats['patk'] + 15.5 + self.effort_value['patk']/8 + 5) * self.nature_dict['patk'])\n\n self.pdef = floor((self.base_stats['pdef'] + 15.5 + self.effort_value['pdef']/8 + 5) * self.nature_dict['pdef'])\n\n self.spatk = floor((self.base_stats['spatk'] + 15.5 + self.effort_value['spatk']/8 + 5) * self.nature_dict['spatk'])\n\n self.spdef = floor((self.base_stats['spdef'] + 15.5 + self.effort_value['spdef']/8 + 5) * self.nature_dict['spdef'])\n\n self.spe = floor((self.base_stats['spe'] + 15.5 + self.effort_value['spe']/8 + 5) * self.nature_dict['spe'])\n\n #元のステータスの保存\n self.old_hp = self.hp\n self.old_patk = self.patk\n self.old_pdef = self.pdef\n self.old_spatk = self.spatk\n self.old_spdef = self.spdef\n self.old_spe = self.spe\n\n\n #性格補正\n def convert_nature(self):\n nature_dict = {\"hp\": 1.0, \"patk\": 1.0, \"pdef\": 1.0, \"spatk\": 1.0, \"spdef\": 1.0, \"spe\": 1.0}\n if self.nature == \"Lonely\":\n nature_dict['patk'] = 1.1\n nature_dict['pdef'] = 0.9\n elif self.nature == \"Brave\":\n nature_dict['patk'] = 1.1\n nature_dict['spe'] = 0.9\n elif self.nature == \"Adamant\":\n nature_dict['patk'] = 1.1\n nature_dict['spatk'] = 0.9\n elif self.nature == \"Naughty\":\n nature_dict['patk'] = 1.1\n nature_dict['spdef'] = 0.9\n elif self.nature == \"Bold\":\n nature_dict['pdef'] = 1.1\n nature_dict['patk'] = 0.9\n elif self.nature == \"Relaxed\":\n nature_dict['pdef'] = 1.1\n nature_dict['spe'] = 0.9\n elif self.nature == \"Impish\":\n nature_dict['pdef'] = 1.1\n nature_dict['spatk'] = 0.9\n elif self.nature == \"Lax\":\n nature_dict['pdef'] = 1.1\n nature_dict['spdef'] = 0.9\n elif self.nature == \"Timid\":\n nature_dict['spe'] = 1.1\n nature_dict['patk'] = 0.9\n elif self.nature == \"Hasty\":\n nature_dict['spe'] = 1.1\n nature_dict['pdef'] = 0.9\n elif self.nature == \"Jolly\":\n nature_dict['spe'] = 1.1\n nature_dict['spatk'] = 0.9\n elif self.nature == \"Naive\":\n nature_dict['spe'] = 1.1\n nature_dict['spdef'] = 0.9\n elif self.nature == \"Modest\":\n nature_dict['spatk'] = 1.1\n nature_dict['patk'] = 0.9\n elif self.nature == \"Mild\":\n nature_dict['spatk'] = 1.1\n nature_dict['pdef'] = 0.9\n elif self.nature == \"Quiet\":\n nature_dict['spatk'] = 1.1\n nature_dict['spe'] = 0.9\n elif self.nature == \"Rash\":\n nature_dict['spatk'] = 1.1\n nature_dict['spdef'] = 0.9\n elif self.nature == \"Calm\":\n nature_dict['spdef'] = 1.1\n nature_dict['patk'] = 0.9\n elif self.nature == \"Gentle\":\n nature_dict['spdef'] = 1.1\n nature_dict['pdef'] = 0.9\n elif self.nature == \"Sassy\":\n nature_dict['spdef'] = 1.1\n nature_dict['spe'] = 0.9\n elif self.nature == \"Careful\":\n nature_dict['spdef'] = 1.1\n nature_dict['spatk'] = 0.9\n\n self.nature_dict = nature_dict\n\n def mega_evolution(self):\n if self.name == 'ボーマンダ':\n old_hp = self.hp\n self.name = 'メガボーマンダ'\n self.ability = 'スカイスキン'\n base_stats = {\"hp\": 95,\n \"patk\": 145,\n \"pdef\": 130,\n \"spatk\": 120,\n \"spdef\": 90,\n \"spe\": 120 },\n self.calculate()\n self.hp = old_hp\n\n\n\nclass Player:\n def __init__(self, name, party):\n self.name = name\n self.party = party\n self.selection = [0,0,0]\n self.death_total = 0\n self.select_attack = True #攻撃交代の選択\n self.zpower = True\n self.mega = True\n #フィールド\n self.field = {'リフレクター':0,\n 'ひかりのかべ':0,\n 'まきびし':0,\n 'どくびし':0,\n 'ステルスロック':0,\n 'おいかぜ': 0}\n\n #ポケモンの瀕死判定 ,勝利判定\n def judgement(self):\n self.battle_poke.fruit(self)\n self.battle_poke.death_judge()\n '''\n if not (self.selection[0].alive and self.selection[1].alive and self.selection[2].alive):\n return True\n '''\n\nclass User(Player):\n #選出\n def select(self):\n print(self.name)\n self.party_print()\n for i in range(3):\n self.selection[i] = self.party[int(input(('ポケモンを選んでください')))-1]\n self.battle_poke = self.selection[0]\n self.select_print()\n\n\n def party_print(self):\n for i in range(6):\n print(str(i+1) + ':' + self.party[i].name)\n print()\n\n def select_print(self):\n print()\n for i in range(3):\n print(str(i+1) + ':' + self.selection[i].name)\n print()\n\n\n #攻撃or交代\n def select_action(self, enemy):\n print()\n #ため\n if self.battle_poke.state['ため'] > 0:\n self.select_attack = True\n return None\n #あばれ\n if self.battle_poke.state['あばれ'] > 0:\n self.select_attack = True\n self.battle_poke.state['あばれ'] -= 1\n if self.battle_poke.state['あばれ'] == 0:\n t = ranodm.randint(1,4)\n self.battle_poke.state['こんらん'] = t\n return None\n while True:\n n = int(input('1:攻撃' + '\\n' + '2:交代'))\n if enemy.battle_poke.ability == 'かげふみ':\n if 'Ghost' not in self.battle_poke.typing:\n self.select_attack = True\n break\n if n == 1:\n self.select_attack = True\n if self.battle_poke.item == 'メガストーン' and self.mega:\n m = int(input('1メガ進化する /2メガ進化しない'))\n if m == 1:\n self.battle_poke.mega_evolution()\n self.mega = False\n break\n elif n == 2:\n self.select_attack = False\n break\n else:\n #ステータスの確認追加\n pass\n print()\n\n #技選択\n def select_move(self):\n self.move_print()\n before_move = self.battle_poke.move_now\n while True :\n n = 0\n self.battle_poke.move_now = self.battle_poke.move_list[int(input('技を選択してしてください')) -1]\n #Z技を使うかどうか\n if self.zpower:\n if self.battle_poke.move_now.type == self.battle_poke.item:\n print('1使う/ 2使わない')\n z = int(input('Z技を使いますか?'))\n if z == 1:\n self.battle_poke.zpower = True\n self.zpower = False\n #ちょうはつ\n if self.battle_poke.state['ちょうはつ'] > 0:\n if self.battle_poke.move_now.category == 'Non-Damaging':\n n += 1\n #かなしばり\n if not self.battle_poke.move_now.disable == 0:\n n += 1\n #アンコール\n if self.battle_poke.state['アンコール'] > 0:\n if self.battle_poke.move_now.encore == 0:\n n += 1\n #みちづれ連続禁止\n if self.battle_poke.move_now.name == 'みちづれ':\n if before_move.name == self.battle_poke.move_now.name:\n n += 1\n\n if n == 0:\n break\n\n\n\n def move_print(self):\n print()\n for i in range(4):\n print(str(i+1) + self.battle_poke.move_list[i].name)\n print()\n\n #ポケモンの交換\n def swicth(self):\n self.battle_poke.switch_reset()\n while True:\n self.select_print()\n old_battle_poke = self.battle_poke\n self.battle_poke = self.selection[int(input('入力してください')) - 1]\n if self.battle_poke == old_battle_poke:\n pass\n elif self.battle_poke.alive:\n break\n else:\n pass\n\nclass Computer(Player):\n #選出\n def select(self):\n for i in range(3):\n self.selection[i] = self.party[i]\n self.battle_poke = self.selection[0]\n\n #攻撃or交代\n def select_action(self, enemy):\n if enemy.battle_poke.ability == 'かげふみ':\n if 'Ghost' not in self.battle_poke.typing:\n self.select_attack = True\n self.select_attack = True\n\n #技選択\n def select_move(self):\n self.battle_poke.move_now = self.battle_poke.move_list[0]\n\n #ポケモンの交換\n def swicth(self):\n while True:\n self.battle_poke = self.selection[int(random.randint(0,2))]\n if self.battle_poke.hp >= 0:\n break\n else:\n pass\n","sub_path":"pokemon.py","file_name":"pokemon.py","file_ext":"py","file_size_in_byte":18467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"10038488","text":"# coding: utf-8\nimport pandas as pd\nimport os\n\nif __name__ == '__main__': \n filename = input('请输入告警分析数据源文件:')\n path = os.path.split(filename)\n #指定engine为python,否则不支持中文路径及文件名\n #Win下的CSV文件一般是GBK编码,如果不确定的话需要引入chardet判断编码\n #EXCEL文件读取pd.read_excel('name.xlsx')\n df = pd.DataFrame(pd.read_csv(filename,encoding = 'GBK',index_col=False,engine='python'))\n #筛选出清远的数据\n qy_df = df[df['地市'] == '清远']\n #按地市汇总计数并倒序排列\n result1 = df.groupby('地市')['告警标题'].count().sort_values(ascending = False).reset_index()\n #按告警定位对象,告警标题进行汇总计数并倒序排列\n result2 = qy_df.groupby(['告警定位对象','告警标题'])['地市'].count().sort_values(ascending = False).reset_index()\n #写入CSV文件result.to_csv('result.csv',index = False,encoding = 'GBK')\n #写入Excel需要安装openpyxl模块\n output = os.path.join(path[0],path[1].replace('.csv','_result.xlsx'))\n writer = pd.ExcelWriter(output)\n result1.to_excel(writer, sheet_name='各地市统计', index = False)\n result2.to_excel(writer, sheet_name='本市统计', index = False)\n writer.save()\n print('已完成分析。')\n","sub_path":"ipman_alarm.py","file_name":"ipman_alarm.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"602006758","text":"from aocd import get_data, submit1, submit2\nfrom collections import deque, defaultdict\n\nimport re\n\n\nclass REMatcher(object):\n def __init__(self, matchstring):\n self.matchstring = matchstring\n\n def match(self,regexp):\n self.rematch = re.match(regexp, self.matchstring)\n return bool(self.rematch)\n\n def group(self,i):\n return self.rematch.group(i)\n\n\ndef problem1(num_players, num_marbles):\n marbles = [0, 1]\n curr_marble_index = 1\n curr_player = 2\n\n score = {}\n for i in range(num_players):\n score[i] = 0\n\n for marble in range(2, num_marbles):\n if marble % 23 > 0:\n curr_marble_index += 2\n if curr_marble_index > len(marbles):\n curr_marble_index = curr_marble_index % len(marbles)\n\n marbles.insert(curr_marble_index, marble)\n else:\n score[curr_player] += marble\n curr_marble_index = (curr_marble_index - 7) % len(marbles)\n score[curr_player] += marbles.pop(curr_marble_index)\n curr_player = (curr_player + 1) % num_players\n return max(score.values())\n\n\ndef problem2(num_players, num_marbles):\n marbles = deque([0])\n score = defaultdict(int)\n\n for marble in range(1, num_marbles):\n if marble % 23 > 0:\n marbles.rotate(-1)\n marbles.append(marble)\n else:\n marbles.rotate(7)\n score[marble % num_players] += marble + marbles.pop()\n marbles.rotate(-1)\n return max(score.values())\n\ndef main():\n input = get_data(day=9, year=2018)\n re_matcher = REMatcher(input)\n re_matcher.match(r\"(\\d+) players; last marble is worth (\\d+) points\")\n\n num_players = int(re_matcher.group(1))\n num_marbles = int(re_matcher.group(2)) + 1\n\n ans = problem1(num_players, num_marbles)\n submit1(ans)\n\n ans = problem2(num_players, num_marbles*100)\n submit2(ans)\n\nmain()\n","sub_path":"src/year2018/day_9.py","file_name":"day_9.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"253572298","text":"from selenium import webdriver\nfrom time import gmtime, strftime\nimport random\nimport time\nimport pymysql\n\n\ndef sendMsg(name,msg):\n search = driver.find_element_by_class_name('jN-F5')\n search.click()\n search.clear()\n for i in name:\n search.send_keys(i)\n time.sleep(0.1)\n time.sleep(4)\n user = driver.find_element_by_xpath('//span[@title = \"{}\"]'.format(name))\n user.click()\n\n msg_box = driver.find_element_by_class_name('_2S1VP')\n\n for i in msg:\n msg_box.send_keys(i)\n time.sleep(0.1)\n\n button = driver.find_element_by_class_name('_2lkdt')\n button.click()\n\ndef timeNoC():\n return strftime(\"%H\", gmtime()) + \" horas, \" + strftime(\"%M\", gmtime()) + \" minutos, \" + strftime(\"%S\", gmtime()) + \" segundos, inclinación \" + strftime(\"%d\", gmtime()) + \" grados ...... no hay cuerpos. \"\n\n\ndriver = webdriver.Chrome()\ndriver.get('https://web.whatsapp.com/')\n\ninput('Presione enter una vez se ha escaneado en código QR')\n\n## Desarrollo del programa\nwhile(True):\n print(timeNoC())\n conn = pymysql.connect(host='localhost', user='root', password='123456',db='alquileres')\n cur = conn.cursor()\n cur.execute('SELECT * FROM messages WHERE status = \\'0\\'')\n data = cur.fetchall()\n if(len(data)>0): \n for i in data:\n sendMsg(i[0],i[1])\n time.sleep(2)\n cur.execute('UPDATE messages SET status = \\'1\\' WHERE status = \\'0\\'')\n conn.commit()\n else:\n sendMsg('Block de notas',timeNoC())\n conn.close()\n t = random.randint(30,180)\n print(t)\n time.sleep(t)","sub_path":"mensajes/EnviarMensajes.py","file_name":"EnviarMensajes.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"200334409","text":"from odoo import api, fields, models, _\nfrom odoo.exceptions import UserError\n\nclass SaleOrderLine(models.Model):\n _inherit = \"sale.order.line\"\n\n def getConfigValue(self, collection, name):\n nameValuePairs = collection.filtered(lambda nv: nv.name == name)\n if len(nameValuePairs) == 0:\n self.logMessage('Config: {} is missing, please add appropriate value to it'.format(name), 'ERROR')\n raise UserError('Config: {} is missing, please add appropriate value to it'.format(name))\n \n return nameValuePairs[0].value.strip()\n\n def logMessage(self, message, level):\n logModel = self.env['ir.logging']\n logModel.create({\n 'dbname': self._cr.dbname,\n 'type': 'server',\n 'name': 'sale.order.line',\n 'level': level,\n 'func': 'create',\n 'message': message,\n 'path': 'path',\n 'line': 1,\n })\n\n @api.model\n def create(self, vals):\n createdOrderLine = super(SaleOrderLine, self).create(vals)\n try:\n configs = self.env['dribot.config'].search([])\n self.logMessage(createdOrderLine.product_id.name, 'INFO')\n if (createdOrderLine.product_id.name == self.getConfigValue(configs, 'Dribot_Product_Name')):\n # Custom logic starts here\n productModel = self.env['product.product']\n subscriptionProducts = productModel.search([('name', '=', self.getConfigValue(configs, 'DefaultDribotSubscriptionProduct_Name'))])\n if (len(subscriptionProducts) != 1):\n self.logMessage('Either there are multiple products with name mentioned in Config entry \\\n \\'DefaultDribotSubscriptionProduct_Name\\' or there are none. Reference Sale Order Id:{}'.format(createdOrderLine.order_id.id) , 'ERROR')\n raise UserError('Either there are multiple products with name Config entry \\\n \\'DefaultDribotSubscriptionProduct_Name\\' or there are none.')\n \n self.create({\n 'customer_lead': createdOrderLine.customer_lead,\n 'name': subscriptionProducts[0].name,\n 'order_id': createdOrderLine.order_id.id,\n 'price_unit': subscriptionProducts[0].lst_price,\n 'product_id': subscriptionProducts[0].id,\n 'product_uom': createdOrderLine.product_uom.id,\n 'product_uom_qty': createdOrderLine.product_uom_qty\n })\n except:\n self.logMessage('Unknown error occurred while creating the order line', 'ERROR')\n \n return createdOrderLine\n\n\n\n\n","sub_path":"odoo-addons/ManageDribotUnit/models/sale_order_line.py","file_name":"sale_order_line.py","file_ext":"py","file_size_in_byte":2734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"58802422","text":"'''\n excel表格的数据统计和分析:\n 1.联网安装 xlrd(读取) xlwt(写入)\n xlrd(1.2)\n cmd --> python -m pip install xlrd==0.9.3\n 2.写代码\n 2.1 导入这个工具\n import xlrd\n 2.2 打开工作簿\n 2.3 打开选项卡\n 2.4 读取数据\n任务:\n 每个月的销售总金额:\n 全年的销售总额:\n 每种衣服的销售总额:\n 每个季度销售总额占比:\n 全年每种销售数量占比:\n\n'''\n\nimport xlrd\n# 1. 打开工作簿\n# wd = xlrd.open_workbook(r\"2020年每个月的销售情况.xlsx\",encoding_override=True)\nbook=xlrd.open_workbook(r\"F:\\python自动化测试\\Python自动化\\第七天\\任务\\2020年每个月的销售情况.xlsx\",encoding_override=True)\nsheet1 = book.sheet_by_index(0)\nrows,cols = sheet1.nrows,sheet1.ncols \nfor row in range(rows):\n for col in range(cols):\n print(sheet1.cell(row,col).value,end='')\n print('')\nsumcount=0;\nfor i in range(1,31):\n sumcount+=sheet1.cell(i,4).value\nprint(\"销��量:\",sumcount)\nsumoney =0\nfor j in range(1,31):\n sumoney+=sheet1.cell(j,2).value*sheet1.cell(j,4).value\nprint(\"总销售额:\",sumoney)\nprint(\"平均销售量:\",sumcount/30)\n\ny,n,f,p,t,c =0,0,0,0,0,0\nfor o in range(1,31):\n if sheet1.cell(o,1).value=='羽绒服':\n y +=sheet1.cell(o,4).value\n elif sheet1.cell(o,1).value=='牛仔裤':\n n += sheet1.cell(o, 4).value\n elif sheet1.cell(o, 1).value == '风衣':\n f += sheet1.cell(o, 4).value\n elif sheet1.cell(o, 1).value == '皮草':\n p += sheet1.cell(o, 4).value\n elif sheet1.cell(o, 1).value == 'T血':\n t += sheet1.cell(o, 4).value\n elif sheet1.cell(o, 1).value == '衬衫':\n c += sheet1.cell(o, 4).value\n\n print('羽绒服销售占比:', 253.6 * y / sumoney * 100, '%')\n print('牛仔裤销售占比:', 86.3 * n / sumoney * 100, '%')\n print('风衣销售占比:', 96.8 * f / sumoney * 100, '%')\n print('皮草销售占比:', 135.9 * p / sumoney * 100, '%')\n print('T血销售占比:', 65.8 * t / sumoney * 100, '%')\n print('衬衫销售占比:', 49.3 * c / sumoney * 100, '%')","sub_path":"销售额.py","file_name":"销售额.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"340746968","text":"n = int(input())\nW = []\nfor _ in range(n):\n w = input()\n if w in W:\n print('No')\n exit()\n W.append(w)\n\nfor i in range(n-1):\n if W[i][-1] != W[i+1][0]:\n print('No')\n exit()\nprint('Yes')","sub_path":"109/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"62476933","text":"# -*- coding: utf-8 -*-\nimport re\nimport xml.sax.saxutils\nimport xml.etree.cElementTree as etree\nimport sparv.util as util\n\nRESTART_THRESHOLD_LENGTH = 64000\nSENT_SEP = \"\\n\"\nTOK_SEP = \" \"\n\n\ndef tag_ne(out_ne_ex, out_ne_type, out_ne_subtype, out_ne_name, word, sentence, encoding=util.UTF8, process_dict=None):\n \"\"\"\n Tag named entities using HFST-SweNER.\n SweNER is either run in an already started process defined in\n process_dict, or a new process is started(default)\n - out_ne_ex, out_ne_type and out_ne_subtype are resulting annotation files for the named entities\n - word and sentence are existing annotation files for wordforms and sentences\n - process_dict should never be set from the command line\n \"\"\"\n\n if process_dict is None:\n process = swenerstart(\"\", encoding, verbose=False)\n # else:\n # process = process_dict['process']\n # # If process seems dead, spawn a new one\n # if process.stdin.closed or process.stdout.closed or process.poll():\n # util.system.kill_process(process)\n # process = swenerstart(\"\", encoding, verbose=False)\n # process_dict['process'] = process\n\n # Collect all text\n sentences = [sent.split() for _, sent in util.read_annotation_iteritems(sentence)]\n word_file = util.read_annotation(word)\n stdin = SENT_SEP.join(TOK_SEP.join(word_file[tokid] for tokid in sent)\n for sent in sentences)\n # Escape <, > and &\n stdin = xml.sax.saxutils.escape(stdin)\n\n # keep_process = len(stdin) < RESTART_THRESHOLD_LENGTH and process_dict is not None\n # util.log.info(\"Stdin length: %s, keep process: %s\", len(stdin), keep_process)\n\n # if process_dict is not None:\n # process_dict['restart'] = not keep_process\n\n # # Does not work as of now since swener does not have an interactive mode\n # if keep_process:\n # # Chatting with swener: send a SENT_SEP and read correct number of lines\n # stdin_fd, stdout_fd = process.stdin, process.stdout\n # stdin_fd.write(stdin.encode(encoding) + SENT_SEP)\n # stdin_fd.flush()\n # stout = stdout_fd.readlines()\n\n # else:\n # Otherwise use communicate which buffers properly\n # util.log.info(\"STDIN %s %s\", type(stdin.encode(encoding)), stdin.encode(encoding))\n stdout, _ = process.communicate(stdin.encode(encoding))\n # util.log.info(\"STDOUT %s %s\", type(stdout.decode(encoding)), stdout.decode(encoding))\n\n parse_swener_output(sentences, stdout.decode(encoding), out_ne_ex, out_ne_type, out_ne_subtype, out_ne_name)\n\n\ndef parse_swener_output(sentences, output, out_ne_ex, out_ne_type, out_ne_subtype, out_ne_name):\n \"\"\"Parse the SweNER output and write annotation files.\"\"\"\n\n out_ex_dict = {}\n out_type_dict = {}\n out_subtype_dict = {}\n out_name_dict = {}\n\n # Loop through the NE-tagged sentences and parse each one with ElemenTree\n for sent, tagged_sent in zip(sentences, output.strip().split(SENT_SEP)):\n xml_sent = \"\" + tagged_sent + \" \"\n\n # Filter out tags on the format since they seem to always overlap with elements,\n # making the XML invalid.\n xml_sent = re.sub(r'?Enamex[^>\\s]+>', '', xml_sent)\n try:\n root = etree.fromstring(xml_sent)\n except:\n util.log.warning(\"Error parsing sentence. Skipping.\")\n continue\n\n # Init token counter; needed to get start_id and end_id\n i = 0\n previous_end = 0\n children = list(root.iter())\n\n try:\n\n for count, child in enumerate(children):\n start_id = util.edgeStart(sent[i])\n start_i = i\n\n # If current child has text, increase token counter\n if child.text:\n i += len(child.text.strip().split(TOK_SEP))\n\n # Extract NE tags and save them in dictionaries\n if child.tag != \"sroot\":\n if start_i < previous_end:\n pass\n # util.log.warning(\"Overlapping NE elements found; discarding one.\")\n else:\n end_id = util.edgeEnd(sent[i - 1])\n previous_end = i\n edge = util.mkEdge('ne', [start_id, end_id])\n out_ex_dict[edge] = child.tag\n out_type_dict[edge] = child.get(\"TYPE\")\n out_subtype_dict[edge] = child.get(\"SBT\")\n out_name_dict[edge] = child.text\n\n # If this child has a tail and it doesn't start with a space, or if it has no tail at all despite not being the last child,\n # it means this NE ends in the middle of a token.\n if (child.tail and child.tail.strip() and not child.tail[0] == \" \") or (not child.tail and count < len(children) - 1):\n i -= 1\n # util.log.warning(\"Split token returned by name tagger.\")\n\n # If current child has text in the tail, increase token counter\n if child.tail and child.tail.strip():\n i += len(child.tail.strip().split(TOK_SEP))\n\n if (child.tag == \"sroot\" and child.text and not child.text[-1] == \" \") or (child.tail and not child.tail[-1] == \" \"):\n # The next NE would start in the middle of a token, so decrease the counter by 1\n i -= 1\n except IndexError:\n util.log.warning(\"Error parsing sentence. Skipping.\")\n continue\n\n # Write annotations\n util.write_annotation(out_ne_ex, out_ex_dict)\n util.write_annotation(out_ne_type, out_type_dict)\n util.write_annotation(out_ne_subtype, out_subtype_dict)\n util.write_annotation(out_ne_name, out_name_dict)\n\n\ndef swenerstart(stdin, encoding, verbose):\n \"\"\"Start a SweNER process and return it.\"\"\"\n return util.system.call_binary(\"hfst-swener\", [], stdin, encoding=encoding, verbose=verbose, return_command=True)\n\n\nif __name__ == '__main__':\n util.run.main(tag_ne)\n","sub_path":"sparv/swener.py","file_name":"swener.py","file_ext":"py","file_size_in_byte":6200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"145765530","text":"import numpy as np\nimport argparse\nimport matplotlib.gridspec\nimport matplotlib.pyplot as plt\nimport scipy.stats\nimport statsmodels.stats.multitest\n\nfrom behavior import backup\nfrom analysis.batch import customized_plot\n\n\ndef main(force):\n\n backups = backup.get_data(force)\n\n backups = [b for b in backups if b.pvp]\n\n # ----------------- Data ------------------- #\n\n # Look at the parameters\n n_simulations = len(backups)\n n_positions = backups[0].n_positions\n\n # Containers\n d = np.zeros(n_simulations)\n prices = np.zeros(n_simulations)\n scores = np.zeros(n_simulations)\n r = np.zeros(n_simulations)\n s = np.zeros(n_simulations, dtype=bool)\n\n for i, b in enumerate(backups):\n\n # Compute the mean distance between the two firms\n data = np.absolute(\n b.positions[:, 0] -\n b.positions[:, 1]) / n_positions\n\n d[i] = np.mean(data)\n\n # Compute the mean price\n prices[i] = np.mean(b.prices[:, :])\n\n # Compute the mean profit\n scores[i] = np.mean(b.profits[:, :])\n\n r[i] = b.r\n s[i] = b.display_opponent_score\n\n # ---------- Plot ----------------------------- #\n\n fig = plt.figure(figsize=(4, 7), dpi=200)\n\n sub_gs = matplotlib.gridspec.GridSpec(nrows=3, ncols=2)\n\n axes = (\n fig.add_subplot(sub_gs[0, 0]),\n fig.add_subplot(sub_gs[0, 1]),\n fig.add_subplot(sub_gs[1, 0]),\n fig.add_subplot(sub_gs[1, 1]),\n fig.add_subplot(sub_gs[2, 0]),\n fig.add_subplot(sub_gs[2, 1])\n )\n\n y_labels = \"Distance\", \"Price\", \"Profit\"\n y_limits = (0, 1), (1, 11), (0, 120)\n\n s_values = (0, 1, ) * 3\n\n arr = (d, d, prices, prices, scores, scores)\n\n # axes[0].text(2, 1.3, \"Display opponent score\", fontsize=12)\n axes[0].set_title(\"$s = 0$\")\n axes[1].set_title(\"$s = 1$\")\n\n for idx in range(len(axes)):\n\n ax = axes[idx]\n\n ax.set_axisbelow(True)\n\n # Violin plot\n data = [arr[idx][(r == r_value) * (s == s_values[idx])] for r_value in (0.25, 0.50)]\n color = ['C0' if r_value == 0.25 else 'C1' for r_value in (0.25, 0.50)]\n\n customized_plot.violin(ax=ax, data=data, color=color, edgecolor=\"white\", alpha=0.8) # color, alpha=0.5)\n\n for ax in axes[0:2]:\n ax.set_yticks(np.arange(0, 1.1, 0.25))\n\n for ax in axes[2:4]:\n ax.set_yticks(np.arange(1, 11.1, 2))\n\n for ax in axes[-2:]:\n ax.set_xticklabels([\"{:.2f}\".format(i) for i in (0.25, 0.50)])\n ax.set_xlabel(\"$r$\")\n\n for ax in axes[:4]:\n ax.tick_params(length=0, axis=\"x\")\n ax.set_xticklabels([])\n\n for ax, y_label, y_lim in zip(axes[0::2], y_labels, y_limits):\n ax.text(-0.35, 0.5, y_label, rotation=\"vertical\", verticalalignment='center',\n horizontalalignment='center', transform=ax.transAxes, fontsize=12)\n ax.set_ylabel(\" \")\n ax.tick_params(axis=\"y\", labelsize=9)\n ax.set_ylim(y_lim)\n\n for ax, y_lim in zip(axes[1::2], y_limits):\n ax.set_ylim(y_lim)\n ax.tick_params(length=0, axis=\"y\")\n ax.set_yticklabels([])\n\n plt.tight_layout()\n\n plt.savefig(\"fig/main_exp.pdf\")\n plt.show()\n\n # ----------- Stats ----------------- #\n\n to_compare = [\n {\n \"measure\": \"distance\",\n \"constant\": \"s = 0\",\n \"var\": \"r\",\n \"data\": [d[(r == r_value) * (s == 0)] for r_value in (0.25, 0.50)]\n }, {\n \"measure\": \"distance\",\n \"constant\": \"s = 1\",\n \"var\": \"r\",\n \"data\": [d[(r == r_value) * (s == 1)] for r_value in (0.25, 0.50)]\n }, {\n \"measure\": \"price\",\n \"constant\": \"s = 0\",\n \"var\": \"r\",\n \"data\": [prices[(r == r_value) * (s == 0)] for r_value in (0.25, 0.50)]\n }, {\n \"measure\": \"price\",\n \"constant\": \"s = 1\",\n \"var\": \"r\",\n \"data\": [prices[(r == r_value) * (s == 1)] for r_value in (0.25, 0.50)]\n }, {\n \"measure\": \"profit\",\n \"constant\": \"s = 0\",\n \"var\": \"r\",\n \"data\": [scores[(r == r_value) * (s == 0)] for r_value in (0.25, 0.50)]\n }, {\n \"measure\": \"profit\",\n \"constant\": \"s = 1\",\n \"var\": \"r\",\n \"data\": [scores[(r == r_value) * (s == 1)] for r_value in (0.25, 0.50)]\n }, {\n \"measure\": \"distance\",\n \"constant\": \"r = 0.25\",\n \"var\": \"s\",\n \"data\": [d[(r == 0.25) * (s == s_value)] for s_value in (0, 1)]\n }, {\n \"measure\": \"distance\",\n \"constant\": \"r = 0.50\",\n \"var\": \"s\",\n \"data\": [d[(r == 0.50) * (s == s_value)] for s_value in (0, 1)]\n }, {\n \"measure\": \"price\",\n \"constant\": \"r = 0.25\",\n \"var\": \"s\",\n \"data\": [prices[(r == 0.25) * (s == s_value)] for s_value in (0, 1)]\n }, {\n \"measure\": \"price\",\n \"constant\": \"r = 0.50\",\n \"var\": \"s\",\n \"data\": [prices[(r == 0.50) * (s == s_value)] for s_value in (0, 1)]\n }, {\n \"measure\": \"profit\",\n \"constant\": \"r = 0.25\",\n \"var\": \"s\",\n \"data\": [scores[(r == 0.25) * (s == s_value)] for s_value in (0, 1)]\n }, {\n \"measure\": \"profit\",\n \"constant\": \"r = 0.50\",\n \"var\": \"s\",\n \"data\": [scores[(r == 0.50) * (s == s_value)] for s_value in (0, 1)]\n }\n ]\n\n ps = []\n us = []\n\n for dic in to_compare:\n u, p = scipy.stats.mannwhitneyu(dic[\"data\"][0], dic[\"data\"][1])\n ps.append(p)\n us.append(u)\n\n valid, p_corr, alpha_c_sidak, alpha_c_bonf = \\\n statsmodels.stats.multitest.multipletests(pvals=ps, alpha=0.01, method=\"b\")\n\n for p, u, p_c, v, dic in zip(ps, us, p_corr, valid, to_compare):\n print(\"[Diff in {} when {} depending on {}-value] \"\n \"Mann-Whitney rank test: u {}, p {:.3f}, p corr {:.3f}, significant: {}\"\n .format(dic[\"measure\"], dic[\"constant\"], dic[\"var\"], u, p, p_c, v))\n print()\n\n table = \\\n r\"\\begin{table}[htbp]\" + \"\\n\" + \\\n r\"\\begin{center}\" + \"\\n\" + \\\n r\"\\begin{tabular}{llllllll}\" + \"\\n\" + \\\n r\"Measure & Variable & Constant & $u$ & $p$ (before corr.) \" \\\n r\"& $p$ (after corr.) & Sign. at 1\\% threshold \\\\\" + \"\\n\" + \\\n r\"\\hline \\\\\" + \"\\n\"\n\n for p, u, p_c, v, dic in zip(ps, us, p_corr, valid, to_compare):\n\n p = \"{:.3f}\".format(p) if p >= 0.001 else \"$<$ 0.001\"\n p_c = \"{:.3f}\".format(p_c) if p_c >= 0.001 else \"$<$ 0.001\"\n v = \"yes\" if v else \"no\"\n table += r\"{} & ${}$ & ${}$ & {} & {} & {} & {} \\\\\"\\\n .format(dic[\"measure\"], dic[\"var\"], dic[\"constant\"], u, p, p_c, v) \\\n + \"\\n\"\n\n table += \\\n r\"\\end{tabular}\" + \"\\n\" + \\\n r\"\\end{center}\" + \"\\n\" + \\\n r\"\\caption{Significance tests for comparison using Mann-Withney's u. \" \\\n r\"Bonferroni corrections are applied.}\" + \"\\n\" + \\\n r\"\\label{table:significance_tests}\" + \"\\n\" + \\\n r\"\\end{table}\"\n\n print(\"*** Latex-formated table ***\")\n print(table)\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(description='Produce figures.')\n parser.add_argument('-f', '--force', action=\"store_true\", default=False,\n help=\"Re-import data\")\n parsed_args = parser.parse_args()\n\n main(force=parsed_args.force)\n","sub_path":"__old__/analyse.py","file_name":"analyse.py","file_ext":"py","file_size_in_byte":7470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"301938365","text":"import pathlib, sys\npath = pathlib.Path.cwd()\nsys.path.append(str(path))\n\nimport talib as ta\nimport sqlite3\nimport pandas as pd\nimport numpy as np\nimport datetime as dtt\nimport matplotlib.pyplot as plt\nfrom statsmodels.api import Poisson\nfrom statsmodels.graphics.api import qqplot\nfrom sklearn.naive_bayes import GaussianNB\n# from scipy.stats import poisson\n\nfrom myConstant import Exchange\n\ndef rolling_window(a, window):\n shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)\n print(shape)\n strides = a.strides + (a.strides[-1],)\n print(strides)\n return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)\n\nconn = sqlite3.connect(\"E:\\\\Desktop\\\\deanTrading\\\\.vntrader\\\\info.db\")\n# cursor = conn.cursor()\n\n# cursor.execute(\"select * from dbbardata\")\n# val = cursor.fetchone()\nsymbol = 'BTCUSDT'\nspotexchange = Exchange.BINANCE.value\nfuturesexchange = Exchange.BINANCEFUTURES.value\nsql = f\"select * from dbbardata where symbol='{symbol}' and exchange='{spotexchange}' and interval='1m' order by datetime DESC limit 10000\"\nsql2 = f\"select * from dbbardata where symbol='{symbol}' and exchange='{futuresexchange}' and interval='1m' order by datetime DESC limit 10000\"\n\ndf1 = pd.read_sql(sql, conn)\ndf1.set_index('datetime', inplace=True)\ndf11 = df1.loc[df1.index.drop_duplicates(keep=False), 'close_price']\n\ndf2 = pd.read_sql(sql2, conn)\ndf2.set_index('datetime', inplace=True)\ndf22 = df2.loc[df2.index.drop_duplicates(keep=False), 'close_price']\n\n\ndata = pd.concat((df11, df22), axis=1, join='inner')\ndata.sort_index(inplace=True)\ndata.index = np.linspace(1,len(data.index), num=len(data.index))\ndata.columns = ['spot', 'futures']\ndata['spread'] = data.iloc[:,0] - data.iloc[:,1]\ndata['spread_diff'] = data['spread'].diff().rolling(20).std()\ndata['spread_diff60'] = data['spread'].diff().rolling(60).std()\ndata['q80'] = data['spread_diff60'].quantile(0.8)\ndata['q95'] = data['spread_diff60'].quantile(0.95)\nprint(data['spread_diff60'].quantile(0.99))\n\nfig, ax = plt.subplots(1,1)\nax.plot(data['spread_diff60'], color='g', label='prob')\n# ax2 = ax.twinx()\n# ax2.plot(data['spread'], color='r')\n\nax.plot(data['q80'], color='b')\nax.plot(data['q95'], color='b')\n# ax4 = ax.twinx()\n# ax4.plot(data['prob'], color='r')\n# ax.hist(data['spread_diff'], bins='auto', density=True, cumulative=True)\nplt.ylim([0,7.5])\nplt.show()\n\n","sub_path":"Digiccy1/analysis/reg02.py","file_name":"reg02.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"381799441","text":"import math\nimport random\nimport numpy as np\nfrom Utils.utils import Util as util\nfrom matplotlib import pyplot as plt\nfrom sklearn.metrics import accuracy_score as acc\n#TPR: (Sensitivity, hit rate, recall)\nfrom sklearn.metrics import recall_score as tpr\n#TNR=SPC: (Specificity)\n#PPV: Pos Pred Value (Precision)\nfrom sklearn.metrics import precision_score as ppv\n\nclass ELM:\n def __init__(self, x_data, y_data, activation='logistic', g_search=False, hidden_layer=10):\n self.x_data = x_data\n self.y_data = y_data\n self.n_classes = np.unique(self.y_data, axis=0)\n self.g_search = g_search\n self.attributes = x_data.shape[1]\n self.hidden_layer = hidden_layer\n self.output_layer = y_data.shape[1]\n self.epochs = 500\n self.realizations = 1\n self.precision = 10**(-5)\n self.train_size = 0.8\n self.activation = activation\n self.hit_rate = []\n self.tpr = []\n self.spc = []\n self.ppv = []\n \n def initWeigths(self, hidden_layer):\n params = {}\n a = -1.5\n b = 1.5\n params['w'] = (b - a) * np.random.random_sample((self.attributes+1, hidden_layer)) + a\n params['m'] = (b - a) * np.random.random_sample((hidden_layer+1, self.output_layer)) + a\n return params\n\n def updateEta(self, epoch):\n eta_i = 0.1\n eta_f = 0.05\n eta = eta_i * ((eta_f / eta_i) ** (epoch / self.epochs))\n self.eta = eta\n\n def function(self, u):\n if self.activation == 'logistic':\n y = 1.0/(1.0 + np.exp(-u))\n elif self.activation == 'tanh':\n y = (np.exp(u) - np.exp(-u))/(np.exp(u) + np.exp(-u))\n else:\n raise ValueError('Error in function!')\n y = 0\n return y \n\n def derivate(self, u):\n if self.activation == 'logistic':\n y_ = u * (1.0 - u)\n elif self.activation == 'tanh':\n y_ = 0.5 * (1.0 - (u * u))\n else:\n raise ValueError('Error in derivate!')\n y_ = 0\n return y_\n\n def activationFunction(self, u):\n value = np.amax(u)\n y = np.where(u == value, 1, 0)\n return y\n\n def predict(self, xi, params):\n w = params['w']\n m = params['m']\n \n H = np.dot(xi, w)\n H = self.function(H)\n H = np.concatenate(([-1], H), axis=None)\n H = H.reshape(1,-1)\n\n Y = np.dot(H, m)\n Y = self.function(Y)\n y = self.activationFunction(Y)\n\n return y[0]\n\n def train(self, x_train, y_train, hidden_layer):\n error_old = 0\n cont_epochs = 0\n mse_vector = []\n params = self.initWeigths(hidden_layer)\n w = params['w']\n m = params['m']\n\n H = np.dot(x_train, w)\n H = self.function(H)\n\n # Bias\n (m, _) = H.shape\n bias = -1 * np.ones((m, 1))\n H = np.concatenate((bias, H), axis=1)\n\n H_pinv = np.linalg.pinv(H)\n m = np.dot(H_pinv, y_train)\n\n params['w'] = w\n params['m'] = m\n return params\n\n def test(self, x_test, y_test, params):\n y_true = []\n y_pred = []\n (p, _) = x_test.shape\n for k in range(p):\n x_k = x_test[k]\n y = self.predict(x_k, params)\n d = y_test[k]\n \n # Confusion Matrix\n y_true.append(list(d))\n y_pred.append(list(y))\n\n a = util.inverse_transform(y_true, self.n_classes)\n b = util.inverse_transform(y_pred, self.n_classes)\n return acc(a,b), tpr(a,b, average='macro'), 0, ppv(a,b, average='weighted')\n #return acc(a,b), 0, 0, 0\n\n def grid_search(self, x_train, y_train):\n (n, _) = x_train.shape\n hidden_layer = [4,6,8,10,12,14,16,18,20,22,24,26,28,30]\n k_fold = 5\n slice_ = int(n/k_fold)\n\n grid_accuracy = []\n for q in hidden_layer:\n scores = []\n # cross validation\n for j in range(k_fold):\n # set range\n a = j*slice_\n b = (j+1)*slice_\n\n X_tra_aux = np.concatenate((x_train[0:a], x_train[b:n]), axis=0)\n X_test_aux = x_train[a:b]\n Y_tra_aux = np.concatenate((y_train[0:a], y_train[b:n]), axis=0)\n Y_test_aux = y_train[a:b]\n\n params = self.train(X_tra_aux, Y_tra_aux, q)\n acc, _, _, _ = self.test(X_test_aux, Y_test_aux, params)\n scores.append(acc)\n grid_accuracy.append(np.mean(scores))\n print('Grid search:', grid_accuracy)\n index_max = np.argmax(grid_accuracy)\n return hidden_layer[index_max]\n\n def execute(self):\n x_data = util.normalizeData(self.x_data)\n x_data = util.insertBias(x_data)\n y_data = self.y_data\n\n for i in range(self.realizations):\n x_data_aux, y_data_aux = util.shuffleData(x_data, y_data)\n x_train, x_test, y_train, y_test = util.splitData(x_data_aux, y_data_aux, self.train_size)\n \n if self.g_search:\n best_hidden_layer = self.grid_search(x_train, y_train)\n print('Hidden Layer:', best_hidden_layer)\n else:\n best_hidden_layer = self.hidden_layer\n\n params = self.train(x_train, y_train, best_hidden_layer)\n acc, tpr, spc, ppv = self.test(x_test, y_test, params)\n \n self.hit_rate.append(acc)\n self.tpr.append(tpr)\n self.spc.append(spc)\n self.ppv.append(ppv)\n\n self.acc = np.mean(self.hit_rate)\n self.std = np.std(self.hit_rate)\n self.tpr = np.mean(self.tpr)\n self.spc = np.mean(self.spc)\n self.ppv = np.mean(self.ppv)\n\n print('Hit rate: {}'.format(self.hit_rate))\n print('Accuracy: {:.2f}'.format(self.acc*100))\n print('Minimum: {:.2f}'.format(np.amin(self.hit_rate)*100))\n print('Maximum: {:.2f}'.format(np.amax(self.hit_rate)*100))\n print('Standard Deviation: {:.2f}'.format(self.std))\n print('Sensitivity: {:.2f}'.format(self.tpr*100))\n print('Specificity: {:.2f}'.format(self.spc*100))\n print('Precision: {:.2f}'.format(self.ppv*100))\n\n #self.plotColorMap_3C(x_train, x_test, y_train, self.predict, params)\n #self.plotColorMap_2C(x_train, x_test, y_train, self.predict, params)\n\n def plotColorMap_3C(self, x_train, x_test, y_train, predict, params):\n color1_x = []\n color1_y = []\n color2_x = []\n color2_y = []\n color3_x = []\n color3_y = []\n for i in np.arange(0,1.0,0.005):\n for j in np.arange(0,1.0,0.005):\n xi = np.array([-1, i, j])\n y = predict(xi, params)\n if np.array_equal(y, [0,0,1]):\n color1_x.append(i)\n color1_y.append(j)\n elif np.array_equal(y, [0,1,0]):\n color2_x.append(i)\n color2_y.append(j)\n elif np.array_equal(y, [1,0,0]):\n color3_x.append(i)\n color3_y.append(j)\n else:\n raise ValueError('Error color!\\n')\n \n # Split a train class\n i = []\n j = []\n k = []\n for index,y in enumerate(y_train):\n if np.array_equal(y, [0,0,1]):\n i.append(index)\n elif np.array_equal(y, [0,1,0]):\n j.append(index)\n elif np.array_equal(y, [1,0,0]):\n k.append(index)\n else:\n raise ValueError('Error!\\n')\n train1 = x_train[i]\n train2 = x_train[j]\n train3 = x_train[k]\n\n fig, ax = plt.subplots()\n plt.title('ELM Color Map')\n plt.xlabel('Eixo X')\n plt.ylabel('Eixo y')\n\n ax.scatter(color1_x, color1_y, color=[0.80, 0.88, 0.97])\n ax.scatter(color2_x, color2_y, color=[0.80, 0.80, 0.80])\n ax.scatter(color3_x, color3_y, color=[0.95, 0.87, 0.73])\n ax.scatter(train1[:,1], train1[:,2], label='Classe 1', color=[0.00, 0.45, 0.74])\n ax.scatter(train2[:,1], train2[:,2], label='Classe 2', color=[0.31, 0.31, 0.31])\n ax.scatter(train3[:,1], train3[:,2], label='Classe 3', color=[0.60, 0.20, 0.00])\n ax.scatter(x_test[:,1], x_test[:,2], label='Test Data', color='green')\n\n ax.legend()\n ax.grid(True)\n plt.show()\n\n #fig.savefig('.\\MultilayerPerceptron\\Results\\color_map.png')\n \n def plotColorMap_2C(self, x_train, x_test, y_train, predict, params):\n color1_x = []\n color1_y = []\n color2_x = []\n color2_y = []\n for i in np.arange(0,1,0.005):\n for j in np.arange(0,1,0.005):\n xi = np.array([-1, i, j])\n y = predict(xi, params)\n if np.array_equal(y, [0,1]):\n color1_x.append(i)\n color1_y.append(j)\n elif np.array_equal(y, [1,0]):\n color2_x.append(i)\n color2_y.append(j)\n else:\n raise ValueError('Error color!\\n')\n \n # Split a train class\n i = []\n j = []\n for index,y in enumerate(y_train):\n if np.array_equal(y, [0,1]):\n i.append(index)\n elif np.array_equal(y, [1,0]):\n j.append(index)\n else:\n raise ValueError('Error!\\n')\n train1 = x_train[i]\n train2 = x_train[j]\n\n fig, ax = plt.subplots()\n plt.title('ELM Color Map')\n plt.xlabel('Eixo X')\n plt.ylabel('Eixo y')\n\n ax.scatter(color1_x, color1_y, color=[0.80, 0.88, 0.97])\n ax.scatter(color2_x, color2_y, color=[0.80, 0.80, 0.80])\n ax.scatter(train1[:,1], train1[:,2], label='Classe 1', color=[0.00, 0.45, 0.74])\n ax.scatter(train2[:,1], train2[:,2], label='Classe 2', color=[0.31, 0.31, 0.31])\n ax.scatter(x_test[:,1], x_test[:,2], label='Test Data', color='green')\n\n ax.legend()\n ax.grid(True)\n plt.show()\n\n #fig.savefig('.\\MultilayerPerceptron\\Results\\color_map.png')\n #fig.savefig('.\\MultilayerPerceptron\\Results\\color_map.png', dpi=fig.dpi, bbox_inches='tight')\n","sub_path":"ExtremeLearningMachine/ELM.py","file_name":"ELM.py","file_ext":"py","file_size_in_byte":10334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"410309119","text":"# Time Complexity : Add - O(n)\n# Space Complexity :O(2^h) - O(n/2)\n# Did this code successfully run on Leetcode : Yes\n# Any problem you faced while coding this : No\n'''\n\n1. use DFS and append the nodes value initially\n2. If value corresponding to a level is already present, that means that level has already been traversed, so we must replace\n to that depth, so a minimum of value present in lsit and current root.val must be put\n\n'''\nclass Solution:\n \n def __init__(self):\n self.result = []\n \n def largestValues(self, root: TreeNode) -> List[int]:\n \n self._helper(root, -1)\n \n return self.result\n \n \n def _helper(self, root, level):\n \n if root is None:\n return\n \n level += 1\n if len(self.result) >= level+1:\n if self.result[level] < root.val:\n self.result[level] = root.val\n else:\n self.result.append(root.val)\n\n \n self._helper(root.left, level)\n self._helper(root.right, level)\n ","sub_path":"max_value_row.py","file_name":"max_value_row.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"634302455","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Nov 3 10:21:19 2018\r\n\r\n@author: Srinivas\r\n\"\"\"\r\n\r\n# Word Negation Tracking\r\nimport nltk\r\n\r\nsentence = \"I was not happy with the team's performance\"\r\nwords = nltk.word_tokenize(sentence)\r\nnew_words = []\r\ntemp_word = \"\"\r\n\r\nfor word in words:\r\n if word == 'not':\r\n temp_word = \"not_\"\r\n elif temp_word == \"not_\":\r\n word = temp_word + word # It will be not_happy\r\n temp_word = \"\"\r\n if word != \"not\":\r\n new_words.append(word)\r\nsentence = ' '.join(new_words) \r\n\r\n ","sub_path":"Word_Negation1.py","file_name":"Word_Negation1.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"158435146","text":"from typing import Iterable\nimport random\n\nfrom movieflix.adapters.repository import AbstractRepository\nfrom movieflix.domain.model import Movie\n\n\ndef get_tag_names(repo: AbstractRepository):\n tags = repo.get_tags()\n tag_names = [tag.tag_name for tag in tags]\n\n return tag_names\n\n\ndef get_random_articles(quantity, repo: AbstractRepository):\n article_count = repo.get_number_of_articles()\n\n if quantity >= article_count:\n # Reduce the quantity of ids to generate if the repository has an insufficient number of articles.\n quantity = article_count - 1\n\n # Pick distinct and random articles.\n random_ids = random.sample(range(1, article_count), quantity)\n articles = repo.get_articles_by_id(random_ids)\n\n return articles_to_dict(articles)\n\n\n# ============================================\n# Functions to convert dicts to model entities\n# ============================================\n\ndef article_to_dict(movie: Movie):\n article_dict = {\n 'date': movie.release_year,\n 'title': movie.title\n\n # 'image_hyperlink': article.image_hyperlink\n\n }\n return article_dict\n\n\ndef articles_to_dict(movies: Iterable[Movie]):\n return [movie_to_dict(movie) for movie in movies]\n","sub_path":"movieflix/utilities/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"124923497","text":"from crispy_forms.bootstrap import FormActions\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Submit\nfrom django import forms\nfrom sportsunleash.apps.members.models import Schools\nfrom sportsunleash.lib.layout import Link\n\n\nclass SchoolForm(forms.ModelForm):\n \"\"\"\n Form to render the schools\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(SchoolForm, self).__init__(*args, **kwargs)\n helper = FormHelper(self)\n helper.form_class = 'form-horizontal'\n helper.label_class = 'col-lg-3'\n helper.field_class = 'col-lg-6'\n helper.layout.append(FormActions(\n Submit('submit', 'Save'),\n Link('school_list', 'Cancel')\n ))\n self.helper = helper\n\n class Meta:\n model = Schools\n fields = ('name', 'address_line_1', 'address_line_2', 'contact_number',\n 'email')\n\n","sub_path":"sportsunleash/apps/schools/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"158884561","text":"\"\"\"\n Test the toolbar class\n\"\"\"\nfrom django.contrib.auth.models import User\n\nfrom wheelcms_axle.node import Node\nfrom wheelcms_axle.content import type_registry\nfrom wheelcms_axle.toolbar import Toolbar\nfrom wheelcms_axle.tests.models import Type1, Type1Type, Type2Type, TestTypeRegistry\n\nfrom wheelcms_axle.spoke import Spoke\n\nfrom .test_handler import superuser_request\nfrom twotest.util import create_request\n\nclass BaseToolbarTest(object):\n def setup(self):\n self.registry = TestTypeRegistry()\n type_registry.set(self.registry)\n self.registry.register(Type1Type)\n self.registry.register(Type2Type)\n\n\nclass TestToolbar(BaseToolbarTest):\n \"\"\"\n Test toolbar child restrictions, context buttons\n \"\"\"\n def allchildren(self, children):\n \"\"\" match against all registered children \"\"\"\n return set(x['name'] for x in children) == \\\n set(c.name() for c in type_registry.values())\n\n def test_unconnected(self, client):\n \"\"\"\n Test behaviour on unconnected node - allow\n creation of all types of sub content\n \"\"\"\n root = Node.root()\n toolbar = Toolbar(root, superuser_request(\"/\"), \"view\")\n assert toolbar.show_create()\n assert self.allchildren(toolbar.children())\n\n def test_connected_no_restrictions(self, client):\n \"\"\"\n A node with content without restrictions\n \"\"\"\n root = Node.root()\n content = Type1(node=root)\n content.save()\n toolbar = Toolbar(root, superuser_request(\"/\"), \"view\")\n assert toolbar.show_create()\n assert self.allchildren(toolbar.children())\n\n def test_restriction_type(self, client):\n \"\"\"\n A single childtype allowed\n \"\"\"\n registry = self.registry\n\n class DummyNode(object):\n def content(self):\n class DummyContent(object):\n meta_type = 'dummycontent'\n\n @classmethod\n def get_name(cls):\n return \"test.\" + cls.meta_type\n\n class DummyType(Spoke):\n model = DummyContent\n children = (Type1Type,)\n\n @classmethod\n def name(self):\n return DummyContent.get_name()\n\n registry.register(DummyType)\n\n return DummyContent()\n\n toolbar = Toolbar(DummyNode(), superuser_request(\"/\"), \"view\")\n children = toolbar.children()\n assert len(children) == 1\n assert children[0]['name'] == Type1Type.name()\n assert children[0]['title'] == Type1Type.title\n assert children[0]['icon_path'] == Type1Type.full_type_icon_path()\n\n def test_restriction_none(self, client):\n \"\"\"\n No children at all allowed\n \"\"\"\n registry = self.registry\n\n class DummyNode(object):\n def content(self):\n class DummyContent(object):\n meta_type = 'dummycontent'\n\n @classmethod\n def get_name(cls):\n return \"test.\" + cls.meta_type\n\n class DummyType(Spoke):\n model = DummyContent\n children = ()\n\n @classmethod\n def name(self):\n return DummyContent.get_name()\n\n registry.register(DummyType)\n\n return DummyContent()\n\n toolbar = Toolbar(DummyNode(), superuser_request(\"/\"), \"view\")\n assert toolbar.children() == []\n assert not toolbar.show_create()\n\n def test_create_mode_buttons(self, client):\n \"\"\" verify that certain buttons are not shown in create mode \"\"\"\n node = Node.root()\n content = Type1(node=node)\n content.save()\n toolbar = Toolbar(node, superuser_request(\"/\"), \"create\")\n assert not toolbar.show_create()\n assert not toolbar.show_update()\n\n def test_update_mode_buttons(self, client):\n \"\"\" verify that certain buttons are not shown in update mode \"\"\"\n node = Node.root()\n content = Type1(node=node)\n content.save()\n toolbar = Toolbar(node, superuser_request(\"/\"), \"update\")\n assert not toolbar.show_create()\n assert not toolbar.show_update()\n\n def test_no_implicit_unattached(self, client):\n \"\"\" An unattached node cannot restrict its children but\n should still not allow creation of non-implicit_add\n types \"\"\"\n\n class DummyContent(object):\n meta_type = 'dummycontent'\n\n @classmethod\n def get_name(cls):\n return \"test.\" + cls.meta_type\n\n class DummyType(Spoke):\n model = DummyContent\n children = ()\n implicit_add = False\n\n @classmethod\n def title(cls):\n return ''\n\n self.registry.register(DummyType)\n\n\n node = Node.root()\n toolbar = Toolbar(node, superuser_request(\"/\"), \"view\")\n for c in toolbar.children():\n assert c['name'] != DummyType.name()\n\n def test_anon_no_settings(self, client):\n node = Node.root()\n toolbar = Toolbar(node, create_request(\"GET\", \"/\"), \"view\")\n assert not toolbar.show_settings()\n\n def test_nosu_no_settings(self, client):\n user, _ = User.objects.get_or_create(username=\"user\")\n request = create_request(\"GET\", \"/\")\n request.user = user\n\n node = Node.root()\n toolbar = Toolbar(node, request, \"view\")\n assert not toolbar.show_settings()\n\n def test_primary(self, client):\n \"\"\" a type with primary should behave differently \"\"\"\n\n registry = self.registry\n\n class DummyNode(object):\n def content(self):\n class DummyContent(object):\n meta_type = 'dummycontent'\n\n @classmethod\n def get_name(cls):\n return \"test.\" + cls.meta_type\n\n class DummyType(Spoke):\n model = DummyContent\n children = (Type1Type, Type2Type)\n primary = Type1Type\n\n @classmethod\n def name(self):\n return DummyContent.get_name()\n\n registry.register(DummyType)\n\n return DummyContent()\n\n toolbar = Toolbar(DummyNode(), superuser_request(\"/\"), \"view\")\n children = toolbar.children()\n assert len(children) == 1\n assert children[0]['name'] == Type2Type.name()\n assert children[0]['title'] == Type2Type.title\n assert children[0]['icon_path'] == Type2Type.full_type_icon_path()\n\n primary = toolbar.primary()\n assert primary\n assert primary['name'] == Type1Type.name()\n assert primary['title'] == Type1Type.title\n assert primary['icon_path'] == Type1Type.full_type_icon_path()\n\n def test_primary_unattached(self, client):\n \"\"\" an unattached node has no primary content \"\"\"\n toolbar = Toolbar(Node.root(), superuser_request(\"/\"), \"view\")\n assert toolbar.primary() is None\n\n def test_clipboard_empty(self, client):\n toolbar = Toolbar(Node.root(), superuser_request(\"/\"), \"view\")\n clipboard = toolbar.clipboard()\n assert clipboard['count'] == 0\n assert not clipboard['copy']\n assert not clipboard['cut']\n assert clipboard['items'] == []\n\n def test_clipboard_cut(self, client):\n root = Node.root()\n\n t1 = Type1(node=root.add(\"t1\"), title=\"t1\").save()\n t2 = Type1(node=root.add(\"t2\"), title=\"t2\").save()\n\n request = create_request(\"GET\", \"/\")\n request.session['clipboard_cut'] = [t2.node.tree_path, t1.node.tree_path]\n\n toolbar = Toolbar(Node.root(), request, \"view\")\n clipboard = toolbar.clipboard()\n assert clipboard['count'] == 2\n assert not clipboard['copy']\n assert clipboard['cut']\n assert set(clipboard['items']) == set((t1, t2))\n\n def test_clipboard_copy(self, client):\n root = Node.root()\n\n t1 = Type1(node=root.add(\"t1\"), title=\"t1\").save()\n t2 = Type1(node=root.add(\"t2\"), title=\"t2\").save()\n\n request = create_request(\"GET\", \"/\")\n request.session['clipboard_copy'] = [t2.node.tree_path, t1.node.tree_path]\n\n toolbar = Toolbar(Node.root(), request, \"view\")\n clipboard = toolbar.clipboard()\n assert clipboard['count'] == 2\n assert clipboard['copy']\n assert not clipboard['cut']\n assert set(clipboard['items']) == set((t1, t2))\n\nfrom django.utils import translation\nfrom django.conf import settings\n\nclass TestTranslations(BaseToolbarTest):\n def setup(self):\n super(TestTranslations, self).setup()\n\n settings.CONTENT_LANGUAGES = (('en', 'English'), ('nl', 'Nederlands'), ('fr', 'Francais'))\n settings.FALLBACK = False\n\n def test_show_translate(self, client):\n root = Node.root()\n\n n = root.add(langslugs=dict(en=\"en\", nl=\"nl\", fr=\"fr\"))\n t_nl = Type1(node=n, language=\"nl\", title=\"NL\").save()\n translation.activate(\"en\")\n request = create_request(\"GET\", \"/\")\n toolbar = Toolbar(n, request, \"view\")\n\n assert toolbar.show_translate()\n assert not toolbar.show_update()\n translation.activate(\"nl\")\n assert not toolbar.show_translate()\n assert toolbar.show_update()\n\n\n def test_translations_view(self, client):\n root = Node.root()\n\n n = root.add(langslugs=dict(en=\"en\", nl=\"nl\", fr=\"fr\"))\n t_nl = Type1(node=n, language=\"nl\", title=\"NL\").save()\n t_en = Type1(node=n, language=\"en\", title=\"EN\").save()\n\n\n request = create_request(\"GET\", \"/\")\n\n translation.activate(\"en\")\n toolbar = Toolbar(n, request, \"view\")\n translations = toolbar.translations()\n\n assert translations['active']['id'] == 'en'\n\n ## Do some matching magic using endswith to work around language / base prefixing.\n ## We're mosly interested in create/view/edit actions anyway\n assert translations['translated'][0]['id'] == \"nl\"\n assert translations['translated'][0]['action_url'].endswith('switch_admin_language?path='+n.tree_path + '&language=nl')\n assert translations['untranslated'][0]['id'] == 'fr'\n assert translations['untranslated'][0]['action_url'].endswith('switch_admin_language?path='+n.tree_path + '&language=fr')\n\n def test_translations_edit(self, client):\n root = Node.root()\n\n n = root.add(langslugs=dict(en=\"en\", nl=\"nl\", fr=\"fr\"))\n t_nl = Type1(node=n, language=\"nl\", title=\"NL\").save()\n t_en = Type1(node=n, language=\"en\", title=\"EN\").save()\n\n\n request = create_request(\"GET\", \"/\")\n\n translation.activate(\"en\")\n toolbar = Toolbar(n, request, \"update\")\n translations = toolbar.translations()\n\n assert translations['active']['id'] == 'en'\n\n ## Do some matching magic using endswith to work around language / base prefixing.\n ## We're mosly interested in create/view/edit actions anyway\n assert translations['translated'][0]['id'] == \"nl\"\n assert translations['translated'][0]['action_url'].endswith('switch_admin_language?path='+n.tree_path + '&language=nl&rest=edit')\n assert translations['untranslated'][0]['id'] == 'fr'\n assert translations['untranslated'][0]['action_url'].endswith('switch_admin_language?path='+n.tree_path + '&language=fr&rest=edit')\n\n def test_translations_list(self, client):\n root = Node.root()\n\n n = root.add(langslugs=dict(en=\"en\", nl=\"nl\", fr=\"fr\"))\n t_nl = Type1(node=n, language=\"nl\", title=\"NL\").save()\n t_en = Type1(node=n, language=\"en\", title=\"EN\").save()\n\n\n request = create_request(\"GET\", \"/\")\n\n translation.activate(\"en\")\n toolbar = Toolbar(n, request, \"list\")\n translations = toolbar.translations()\n\n assert translations['active']['id'] == 'en'\n\n ## Do some matching magic using endswith to work around language / base prefixing.\n ## We're mosly interested in create/view/edit actions anyway\n assert translations['translated'][0]['id'] == \"nl\"\n assert translations['translated'][0]['action_url'].endswith('switch_admin_language?path='+n.tree_path + '&language=nl&rest=list')\n assert translations['untranslated'][0]['id'] == 'fr'\n assert translations['untranslated'][0]['action_url'].endswith('switch_admin_language?path='+n.tree_path + '&language=fr&rest=list')\n\n def test_translations_create(self, client):\n root = Node.root()\n\n n = root.add(langslugs=dict(en=\"en\", nl=\"nl\", fr=\"fr\"))\n t_nl = Type1(node=n, language=\"nl\", title=\"NL\").save()\n t_en = Type1(node=n, language=\"en\", title=\"EN\").save()\n\n\n request = create_request(\"GET\", \"/create\", data=dict(type=\"sometype\"))\n\n translation.activate(\"en\")\n toolbar = Toolbar(n, request, \"create\")\n translations = toolbar.translations()\n\n assert translations['active']['id'] == 'en'\n\n import urllib2\n\n ## Do some matching magic using endswith to work around language / base prefixing.\n ## We're mosly interested in create/view/edit actions anyway\n assert len(translations['translated']) == 0\n assert len(translations['untranslated']) == 3 ## all languages incl 'any', active lang excluded\n\n for ut in translations['untranslated']:\n l = ut['id']\n assert l in ('nl', 'fr', 'en', 'any')\n assert ut['action_url'].endswith('switch_admin_language?path='+n.tree_path + '&language=' + l + '&rest=' + urllib2.quote('create?type=sometype'))\n","sub_path":"wheelcms_axle/tests/test_toolbar.py","file_name":"test_toolbar.py","file_ext":"py","file_size_in_byte":13851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"177161171","text":"try:\n import singlesiding\nexcept ModuleNotFoundError:\n print('ModuleNotFoundError ...')\n import os\n import sys\n cwd = os.getcwd()\n print(' cwd: %s' % cwd)\n if cwd not in sys.path:\n sys.path.append(cwd)\n import singlesiding\n\n\ndef main():\n app = singlesiding.initialize('test', 'test app', '1', 'message!')\n return app\n\n\ndef _on_msg_receive(msg):\n print('msg: %s' % msg)\n\n\nif __name__ == '__main__':\n app = main()\n app.message_received.connect(_on_msg_receive)\n app.exec_()\n","sub_path":"test/app_test_app.py","file_name":"app_test_app.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"630994336","text":"from tkinter import *\r\nimport matplotlib as plt\r\nimport numpy as np\r\nimport matplotlib.animation as animation\r\nfrom matplotlib.figure import Figure\r\nfrom matplotlib.backends.backend_tkagg import (\r\n FigureCanvasTkAgg, NavigationToolbar2Tk)\r\nimport threading\r\nimport os\r\nimport random\r\nimport time\r\n\r\nspath='data.txt'\r\nspath2='data2.txt'\r\n\r\n#a=2 # type: int\r\n\r\ndef load_params(fname,list,list_dtypes,list_values):\r\n if(os.path.isfile(fname)):\r\n f = open(fname, 'r')\r\n a = f.read()\r\n for i in range(list.__len__()):\r\n x=a.find(list[i])\r\n if(x!=-1):\r\n y=a.find(\":\",x)\r\n if(y!=-1):\r\n z=a.find(\"\\n\",y)\r\n if(z!=-1):\r\n list_values.append(list_dtypes[i](a[y+1:z]))\r\n\r\ndef save_params(fname,list,list_dtypes,list_values):\r\n if(os.path.isfile(fname)):\r\n os.remove(fname)\r\n f = open(fname, 'w+')\r\n if(list.__len__()==list_dtypes.__len__() and list_dtypes.__len__()==list_values.__len__()):\r\n for i in range(list.__len__()):\r\n s_value=list[i]+\":\"+str(list_values[i])+\"\\n\"\r\n f.write(s_value)\r\n\r\n\r\nclass app:\r\n\r\n def checkpath_thread(self):\r\n #print('thread start')\r\n while(True):\r\n if(self.new_path==True):\r\n if(os.path.isfile(self.s_indatapath)):\r\n self.ed_indatapath['bg']= 'green'\r\n else:\r\n self.ed_indatapath['bg'] = 'red'\r\n\r\n if(os.path.isfile(self.s_outdatapath)):\r\n self.ed_outdatapath['bg']= 'green'\r\n else:\r\n self.ed_outdatapath['bg'] = 'red'\r\n\r\n if(os.path.isfile(self.s_inputpath)):\r\n self.ed_inputpath['bg']= 'green'\r\n else:\r\n self.ed_inputpath['bg'] = 'red'\r\n\r\n self.new_path=False\r\n\r\n\r\n def press_button(self,event):\r\n fpath=self.dpath.get(1.0,END)\r\n print(fpath)\r\n fpath=fpath.rstrip()\r\n fpath=fpath.lstrip()\r\n try:\r\n a = np.genfromtxt(fpath)\r\n except:\r\n print(\"error\")\r\n else:\r\n print(a)\r\n self.lbl['text']=a\r\n #v = StringVar()\r\n #Label(self.lbl, textvariable=v).pack()\r\n #v.set(a)\r\n\r\n\r\n def on_changed(self,event):\r\n fpath=self.ed_indatapath.get(1.0, END)\r\n fpath=fpath.rstrip()\r\n fpath=fpath.lstrip()\r\n if(self.s_indatapath!=fpath):\r\n self.s_indatapath = fpath\r\n self.new_path=True\r\n\r\n fpath=self.ed_outdatapath.get(1.0, END)\r\n fpath=fpath.rstrip()\r\n fpath=fpath.lstrip()\r\n if(self.s_outdatapath!=fpath):\r\n self.s_outdatapath = fpath\r\n self.new_path=True\r\n\r\n fpath=self.ed_inputpath.get(1.0, END)\r\n fpath=fpath.rstrip()\r\n fpath=fpath.lstrip()\r\n if(self.s_inputpath!=fpath):\r\n self.s_inputpath = fpath\r\n self.new_path=True\r\n\r\n def add_data_thread(self):\r\n while True:\r\n self.tdata=np.append(self.tdata,random.randint(0,10))\r\n time.sleep(1)\r\n\r\n def draw_thread(self,i):\r\n self.trainingplot.clear()\r\n self.trainingplot.plot(self.tdata)\r\n\r\n\r\n def __init__(self):\r\n self.root = Tk()\r\n self.root.minsize(width=600,height=500)\r\n\r\n self.s_indatapath=''\r\n self.s_outdatapath=''\r\n self.s_inputpath=''\r\n\r\n self.new_path=True\r\n\r\n self.lbl_indatapath= Label(self.root,height=1,width=12,font='Arial 11',bg=\"white\", fg=\"black\",text='in_data fname :',anchor=W, justify=LEFT)\r\n self.lbl_outdatapath= Label(self.root,height=1,width=12,font='Arial 11',bg=\"white\", fg=\"black\",text='out_data fname:',anchor=W, justify=LEFT)\r\n self.lbl_inputpath= Label(self.root,height=1,width=12,font='Arial 11',bg=\"white\", fg=\"black\",text='input fname :',anchor=W, justify=LEFT)\r\n\r\n self.frm=Frame(self.root,bg='white',bd=5,height=200, width=300)\r\n\r\n #self.btn = Button(self.root, # родительское окно\r\n # text=\"Click me\", # надпись на кнопке\r\n # width=10, height=5, # ширина и высота\r\n # bg=\"white\", fg=\"black\") # цвет фона и надписи\r\n self.ed_indatapath = Text(self.root, height=1, width=15, font='Arial 11', wrap=WORD)\r\n self.ed_outdatapath = Text(self.root, height=1, width=15, font='Arial 11', wrap=WORD)\r\n self.ed_inputpath = Text(self.root, height=1, width=15, font='Arial 11', wrap=WORD)\r\n\r\n self.ed_indatapath.insert(1.0, 'in_data.txt')\r\n self.ed_outdatapath.insert(1.0, 'out_data.txt')\r\n self.ed_inputpath.insert(1.0, 'input.txt')\r\n\r\n self.ed_indatapath.bind('', self.on_changed)\r\n self.ed_outdatapath.bind('', self.on_changed)\r\n self.ed_inputpath.bind('', self.on_changed)\r\n self.ed_indatapath.bind('', self.on_changed)\r\n self.ed_outdatapath.bind('', self.on_changed)\r\n self.ed_inputpath.bind('', self.on_changed)\r\n\r\n self.ed_indatapath.place(x=120, y=10)\r\n self.ed_outdatapath.place(x=120, y=40)\r\n self.ed_inputpath.place(x=120, y=70)\r\n\r\n self.frm.place(x=250, y=10)\r\n #self.btn.place(x=10, y=5)\r\n self.lbl_indatapath.place(x=10, y=10)\r\n self.lbl_outdatapath.place(x=10, y=40)\r\n self.lbl_inputpath.place(x=10, y=70)\r\n\r\n#settings input\\output\r\n t = threading.Thread(target=self.checkpath_thread)\r\n t.daemon = True\r\n t.start()\r\n params=[\"xxc\",\"vvh\",\"asd\",\"qew\"]\r\n params_dtypes=[int,int,float,float]\r\n params_values=list()\r\n load_params(\"data.txt\",params,params_dtypes,params_values)\r\n save_params(\"data.txt\",params,params_dtypes,params_values)\r\n\r\n\r\n #plot\r\n self.fig = Figure(figsize=(5, 4), dpi=50)\r\n self.trainingplot=self.fig.add_subplot(111)\r\n\r\n self.tdata=np.array(5)\r\n for index in range(0,5):\r\n zzz=random.randint(0,10)\r\n self.tdata=np.append(self.tdata,zzz)\r\n\r\n\r\n self.canvas = FigureCanvasTkAgg(self.fig, master=self.frm) # A tk.DrawingArea.\r\n self.canvas.get_tk_widget().pack(expand=0)\r\n #self.canvas.show()\r\n\r\n dt = threading.Thread(target=self.add_data_thread)\r\n dt.daemon = True\r\n dt.start()\r\n\r\n self.ani=animation.FuncAnimation(self.fig,self.draw_thread,interval=1000)\r\n\r\n\r\n\r\n# t = np.arange(0, 3, .01)\r\n# self.trainingplot.plot(t)#, 2 * np.sin(2 * np.pi * t))\r\n# canvas = FigureCanvasTkAgg(self.fig, master=self.frm) # A tk.DrawingArea.\r\n# canvas.draw()\r\n# canvas.get_tk_widget().pack(expand=0)\r\n\r\n #run\r\n self.root.mainloop()\r\n #self.root.withdraw()\r\n\r\n\r\n\r\nz = app()\r\n#z.ani = animation.FuncAnimation(z.fig, drawthread, interval=1000)\r\n#z.root.mainloop()\r\n","sub_path":"tk2.py","file_name":"tk2.py","file_ext":"py","file_size_in_byte":7035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"544735801","text":"import random\r\n\r\n\r\ndef modular_exp(x, y, p):\r\n res = 1\r\n x = x % p\r\n while y > 0:\r\n if y % 2 == 1:\r\n res = (res * x) % p\r\n y = y >> 1\r\n x = (x * x) % p\r\n return res\r\n\r\n\r\ndef miller_rabin_test(d, n):\r\n a = 2 + random.randint(1, n - 4)\r\n x = modular_exp(a, d, n)\r\n if x == 1 or x == n - 1:\r\n return True\r\n while d != n - 1:\r\n x = (x * x) % n\r\n d *= 2\r\n if x == 1:\r\n return False\r\n if x == n - 1:\r\n return True\r\n return False\r\n\r\n\r\ndef isPrime(n, k):\r\n if n <= 1 or n == 4:\r\n return False\r\n if n == 2 or n == 3:\r\n return True\r\n d = n - 1\r\n while d % 2 == 0:\r\n d //= 2\r\n for i in range(k):\r\n if not miller_rabin_test(d, n):\r\n return False\r\n return True\r\n\r\n\r\nN, K = map(int, input().split())\r\ndigitOrderIndependentPrimes = {}\r\nfor i in range(1000, 10 ** 6):\r\n if isPrime(i, 3):\r\n arranged_i = ''.join(sorted(str(i)))\r\n if arranged_i in digitOrderIndependentPrimes:\r\n digitOrderIndependentPrimes[arranged_i].append(i)\r\n else:\r\n digitOrderIndependentPrimes[arranged_i] = [i]\r\nprimes = [p for p in digitOrderIndependentPrimes if len(digitOrderIndependentPrimes[p]) >= K]\r\nprimeAGPs = []\r\nfor p in primes:\r\n perms = digitOrderIndependentPrimes[p]\r\n if K == 3:\r\n for i in range(len(perms) - 2):\r\n if perms[i] >= N:\r\n break\r\n for j in range(i + 1, len(perms) - 1):\r\n p_k = 2 * perms[j] - perms[i]\r\n if p_k in perms:\r\n primeAGPs.append(int(str(perms[i]) + str(perms[j]) + str(p_k)))\r\n if K == 4:\r\n for i in range(len(perms) - 3):\r\n if perms[i] >= N:\r\n break\r\n for j in range(i + 1, len(perms) - 2):\r\n d = perms[j] - perms[i]\r\n p_k = perms[j] + d\r\n p_l = p_k + d\r\n if p_k in perms and p_l in perms:\r\n primeAGPs.append(int(str(perms[i]) + str(perms[j]) + str(p_k) + str(p_l)))\r\nfor agp in sorted(primeAGPs):\r\n print(agp)\r\n","sub_path":"#001 - #050/#049 Prime permutations.py","file_name":"#049 Prime permutations.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"550490319","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass OFCPokerNet(nn.Module):\n\n def __init__(self, embedding_dim, action_space, drop_prob, num_layers=2, hidden_size=128):\n super(OFCPokerNet, self).__init__()\n self.embedding_dim = embedding_dim\n self.hidden_size = hidden_size\n self.three_hand_embed = nn.Linear(52, self.embedding_dim)\n self.five_hand_embed = nn.Linear(52, self.embedding_dim)\n self.cur_card_embed = nn.Linear(52, self.hidden_size)\n\n input_dim = 6 * self.embedding_dim + self.hidden_size\n self.fc1 = nn.Linear(input_dim, self.hidden_size)\n self.layers = [nn.Linear(hidden_size, self.hidden_size) for _ in range(num_layers)]\n self.value = nn.Linear(self.hidden_size, 1)\n self.policy = nn.Linear(self.hidden_size, action_space)\n self.dropout = nn.Dropout(p=drop_prob)\n\n def to(self, *args, **kwargs):\n self = super(OFCPokerNet, self).to(*args, **kwargs) \n self.layers = [layer.to(*args, **kwargs) for layer in self.layers]\n return self\n\n def forward(self, front, mid, back, cur):\n front_embed = self.three_hand_embed(front).view(-1, self.embedding_dim * 2)\n mid_embed = self.five_hand_embed(mid).view(-1, self.embedding_dim * 2)\n back_embed = self.five_hand_embed(back).view(-1, self.embedding_dim * 2)\n card_embed = self.cur_card_embed(cur)\n x = torch.cat((front_embed, mid_embed, back_embed, card_embed), 1)\n out = F.relu(self.fc1(x))\n out = self.dropout(out)\n for layer in self.layers:\n out = F.relu(layer(out))\n out = self.dropout(out)\n pi = self.policy(out)\n v = self.value(out)\n return F.log_softmax(pi, dim=1), torch.tanh(v)\n","sub_path":"ofcpoker/pytorch/OFCPokerNNet.py","file_name":"OFCPokerNNet.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"277050321","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n.. module:: recordation\n :platform: Unix\n :synopsis: the top-level submodule of T_System that contains the classes related to T_System's recording video and audio ability.\n\n.. moduleauthor:: Cem Baybars GÜÇLÜ \n\"\"\"\nimport os # Miscellaneous operating system interfaces\nimport datetime # Basic date and time types\nimport subprocess # Subprocess managements\nimport uuid # The random id generator\n\nfrom shutil import rmtree\nfrom tinydb import Query # TinyDB is a lightweight document oriented database\n\nfrom t_system.db_fetching import DBFetcher\n\nfrom t_system import dot_t_system_dir\nfrom t_system import log_manager\n\nlogger = log_manager.get_logger(__name__, \"DEBUG\")\n\n\nclass Recorder:\n \"\"\"Class to define a recording ability of tracking system.\n\n This class provides necessary initiations and functions named :func:`t_system.recordation.RecordManager.start`\n for creating a Record object and start recording by this object. :func:`t_system.recordation.RecordManager.merge_audio_and_video`\n for merging separate audio and video file to one.\n \"\"\"\n\n def __init__(self, record_formats, camera, hearer):\n \"\"\"Initialization method of :class:`t_system.recordation.Recorder` class.\n\n Args:\n record_formats (list): Formats of the records for video, audio and merged.\n camera: \t Camera object from PiCamera.\n hearer: \t Hearer object.\n \"\"\"\n\n self.current_video_file = \"\"\n self.current_audio_file = \"\"\n self.current_merged_file = \"\"\n\n self.record_formats = {\"video\": record_formats[0], \"audio\": record_formats[1], \"merged\": record_formats[2]}\n\n self.camera = camera\n self.hearer = hearer\n \n def start(self, mode=\"track\"):\n \"\"\"Method to start audio and video recording asynchronously.\n\n Args:\n mode: \t The running mode which is wants to set video name.\n \"\"\"\n logger.debug(\"Record starting...\")\n record = Record(datetime.datetime.now().strftime(\"%d_%m_%Y\"), datetime.datetime.now().strftime(\"%H_%M_%S\"), mode, self.record_formats)\n\n self.__set_record_params(record)\n\n self.camera.start_recording(self.current_video_file, self.record_formats[\"video\"])\n self.hearer.start_recording(self.current_audio_file, self.record_formats[\"audio\"])\n\n def stop(self):\n \"\"\"Method to stop audio and video recording\n \"\"\"\n\n self.camera.stop_recording()\n self.hearer.stop_recording()\n\n # Todo: This is disgusting way to merging audio and silent video. Fix this.\n self.merge_audio_and_video()\n\n def merge_audio_and_video(self):\n \"\"\"Method to merge recorded audio and video files.\n \"\"\"\n\n merge_cmd = f'ffmpeg -y -i {self.current_audio_file} -r 24 -i {self.current_video_file} -filter:a aresample=async=1 -c:a flac -strict -2 -c:v copy {self.current_merged_file}'\n\n subprocess.call(merge_cmd, shell=True)\n\n logger.info('Video and Audio Muxing Done')\n\n def __set_record_params(self, record):\n \"\"\"Method to setting current parameter by current recording.\n \"\"\"\n\n self.current_video_file = record.video_file\n self.current_audio_file = record.audio_file\n self.current_merged_file = record.merged_file\n\n\nclass RecordManager:\n \"\"\"Class to define Record manager for handling the recordation database of t_system's vision.\n\n This class provides necessary initiations and functions named :func:`t_system.recordation.RecordManager.get_records`\n for returning the Record objects of existing records with given table(date at the same time) parameter.\n \"\"\"\n\n def __init__(self):\n \"\"\"Initialization method of :class:`t_system.recordation.RecordManager` class.\n \"\"\"\n\n self.records_folder = f'{dot_t_system_dir}/records'\n\n if not os.path.exists(self.records_folder):\n os.mkdir(self.records_folder)\n\n self.db = DBFetcher(self.records_folder, \"db\").fetch()\n\n self.records = []\n\n self.__set_records()\n\n def __set_records(self):\n \"\"\"Method to set existing records.\n \"\"\"\n\n for record in self.db.all():\n self.records.append(Record(record[\"date\"], record[\"time\"], record[\"scope\"], record[\"record_formats\"], record[\"id\"], record[\"name\"], record[\"length\"]))\n\n def refresh_records(self):\n \"\"\"Method to refresh existing records on runtime alterations.\n \"\"\"\n\n self.records.clear()\n self.__set_records()\n\n def get_records(self, date=None):\n \"\"\"Method to get existing records in given date. If date is None it returns all records.\n\n Args:\n date (str): Parent date of the record. In day_mount_year format.\n \"\"\"\n records = []\n\n if date:\n for record in self.records:\n if record.date == date:\n records.append(record)\n return records\n\n return self.records\n\n def get_record(self, id):\n \"\"\"Method to get existing record in given id.\n\n Args:\n id (str): ID of the record.\n \"\"\"\n\n for record in self.records:\n if record.id == id:\n return record\n\n def get_record_dates(self):\n \"\"\"Method to get date list of existing records.\n \"\"\"\n dates = []\n for record in self.records:\n dates.append(record.date)\n\n dates = list(dict.fromkeys(dates)) # removes duplicated dates.\n\n return dates\n\n def delete_record(self, id):\n \"\"\"Method to get date list of existing records.\n\n Args:\n id (str): ID of the record.\n \"\"\"\n\n for record in self.records:\n if record.id == id:\n record.remove_self()\n self.records.remove(record) # for removing object from list\n return True\n return False\n\n def update_record(self, id, name):\n \"\"\"Method to updating record that has given id.\n\n Args:\n id (str): ID of the record.\n name (str): The name of the record.\n \"\"\"\n\n for record in self.records:\n if record.id == id:\n record.update_name(name)\n return True\n return False\n\n\nclass Record:\n \"\"\"Class to define records of t_systems vision.\n\n This class provides necessary initiations and functions named :func:`t_system.recordation.Record.__db_upsert`\n for saving records to the database safely.\n \"\"\"\n\n def __init__(self, d_m_y, h_m_s, scope, record_formats, id=None, name=None, length=None):\n \"\"\"Initialization method of :class:`t_system.recordation.Record` class.\n\n Args:\n d_m_y (str): Date that is day_mount_year format.\n h_m_s (str): Date that is hour_minute_second format.\n scope (str): The working type during recording.\n record_formats (dict): Formats of the records for video, audio and merged.\n id (str): The id of the record.\n name (str): The name of the record.\n length (str): The length of the record as m:s.\n \"\"\"\n\n self.id = id\n if not id:\n self.id = str(uuid.uuid1())\n\n self.name = name\n if not name:\n self.name = h_m_s\n\n self.date = d_m_y # table name at the same time\n self.time = h_m_s\n self.scope = scope\n self.record_formats = record_formats\n self.length = length\n\n self.records_folder = f'{dot_t_system_dir}/records'\n self.parent_folder = f'{self.records_folder}/{self.date}'\n self.folder = f'{self.parent_folder}/{self.time}'\n\n self.video_file = f'{self.folder}/{self.time}.{self.record_formats[\"video\"]}'\n self.audio_file = f'{self.folder}/{self.time}.{self.record_formats[\"audio\"]}'\n self.merged_file = f'{self.folder}/{self.time}.{self.record_formats[\"merged\"]}'\n\n self.db = DBFetcher(self.records_folder, \"db\").fetch()\n\n self.__check_folders()\n\n if length is None:\n self.length = self.__calc_length()\n\n self.__db_upsert()\n\n def __db_upsert(self, force_insert=False):\n \"\"\"Function to insert(or update) the record to the database.\n\n Args:\n force_insert (bool): Force insert flag.\n\n Returns:\n str: Response.\n \"\"\"\n\n if self.db.search((Query().id == self.id)):\n if force_insert:\n # self.already_exist = False\n self.db.update({'id': self.id, 'name': self.name, 'time': self.time, 'date': self.date, 'scope': self.scope, 'record_formats': self.record_formats, 'length': self.length}, Query().id == self.id)\n\n else:\n # self.already_exist = True\n return \"Already Exist\"\n else:\n self.db.insert({\n 'id': self.id,\n 'name': self.name,\n 'time': self.time,\n 'date': self.date,\n 'scope': self.scope,\n 'record_formats': self.record_formats,\n 'length': self.length\n }) # insert the given data\n\n return \"\"\n\n def update_name(self, name):\n \"\"\"Method to updating self name via by given parameter.\n\n Args:\n name (str): The name of the record.\n \"\"\"\n\n self.name = name\n self.__db_upsert(True)\n\n def remove_self(self):\n \"\"\"Method to remove face itself.\n \"\"\"\n\n rmtree(self.folder)\n\n self.db.remove((Query().id == self.id))\n\n def __calc_length(self):\n \"\"\"Method to calculating length of record with using OpenCV.\n \"\"\"\n if os.path.exists(self.merged_file):\n import cv2\n\n cap = cv2.VideoCapture(self.merged_file)\n\n fps = cap.get(cv2.CAP_PROP_FPS) # OpenCV2 version 2 used \"CV_CAP_PROP_FPS\"\n frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n duration = frame_count / fps\n\n minutes = int(duration / 60)\n seconds = round(duration % 60)\n length = f'{minutes}:{seconds}'\n\n cap.release()\n\n return length\n\n return None\n\n def __check_folders(self):\n \"\"\"Method to checking the necessary folders created before. If not created creates them.\n \"\"\"\n\n if not os.path.exists(self.parent_folder):\n os.mkdir(self.parent_folder)\n\n if not os.path.exists(self.folder):\n os.mkdir(self.folder)\n","sub_path":"t_system/recordation.py","file_name":"recordation.py","file_ext":"py","file_size_in_byte":10818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"141287778","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\n\nELU = \"elu\"\nRELU = \"relu\"\nTANH = \"tanh\"\nSIGMOID = \"sigmoid\"\nACTIVATIONS = [SIGMOID, TANH, RELU, ELU]\n\n\ndef print_subplot(i, j, x, y, title):\n a = axes[i, j]\n a.axvline(x=0, color='k')\n a.axhline(y=0, color='k')\n a.plot(x, y)\n a.set_title(title)\n\n\nstart = -10\nend = 10\nsize = 50\n\nx = np.linspace(start, end, size)\nys = {}\n\nfor activation_string in ACTIVATIONS:\n tf.reset_default_graph()\n activation_input = tf.placeholder(tf.float32)\n activation = getattr(tf.nn, activation_string)\n output = activation(activation_input)\n\n with tf.Session() as sess:\n y = sess.run(output, feed_dict={activation_input: x})\n ys[activation_string] = y\n\nfig, axes = plt.subplots(\n 2,\n 2,\n gridspec_kw={'width_ratios': [1, 1], 'height_ratios': [1, 1]},\n figsize=(16, 5))\nprint_subplot(0, 0, x, ys[SIGMOID], SIGMOID.title())\nprint_subplot(0, 1, x, ys[TANH], TANH.title())\nprint_subplot(1, 0, x, ys[RELU], RELU.title())\nprint_subplot(1, 1, x, ys[ELU], ELU.title())\n\nfig.tight_layout()\nplt.show()\n","sub_path":"model/src/images/activation_functions.py","file_name":"activation_functions.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"257845794","text":"import sys\nimport os\nfrom PySide2.QtCore import *\nfrom PySide2.QtWidgets import *\nfrom PySide2.QtGui import *\nfrom pyside_material import apply_stylesheet\n\nfrom ButtonTabWidget import ButtonWidget\nfrom TitleWidget import TitleLabel\nfrom Homepage import Homepage\nfrom Log import Log\n\nfrom Graph import Graph\nfrom ContainerStat import ContainerStat\nfrom Images import ListImages\nfrom VolumeList import VolumeList\nfrom Dashboard import Dashboard\nfrom Container import Container\nfrom Connection import Connection\n\nclass MainWindow(QWidget):\n def __init__(self):\n super(MainWindow, self).__init__()\n self.user = Connection()\n self.setMinimumSize(1200 ,800)\n\n base_dir = os.path.dirname(os.path.abspath(__file__))\n path = os.path.join(base_dir, 'images')\n\n self.home_path = os.path.join(path, 'docker_image_16.png')\n self.containers_path = os.path.join(path, 'containers_icon.png')\n self.images_path = os.path.join(path, 'images_icon.png')\n self.volumes_path = os.path.join(path, 'volumes_icon.png')\n self.dashboard_path = os.path.join(path, 'dashboard_icon.png')\n \n \n\n #create side menu \n self.listView = QListWidget()\n self.listView.setMaximumWidth(140)\n self.listView.itemSelectionChanged.connect(self.on_selection_changed)\n self.listView.ScrollMode(False)\n\n self.stack = QStackedWidget (self)\n \n # add widget of each page here\n # home dashboard stack service container images volume\n self.homepage = Homepage()\n self.dashboard = Dashboard(len(self.user.getContainersDetail()) , self.user.getNumberOfImageList(), self.user.getNumberOfVolumeList(), self.listView)\n \n self.container = Container(self.user)\n self.images = ListImages(self.user)\n self.volumes = VolumeList(self.user)\n\n # self.log = Log('text.txt')\n\n self.stack.addWidget (self.homepage)\n self.stack.addWidget (self.dashboard)\n self.stack.addWidget (self.container)\n self.stack.addWidget (self.images)\n self.stack.addWidget (self.volumes)\n\n self.layout = QHBoxLayout(self)\n self.layout.setAlignment(Qt.AlignTop)\n self.layout.addWidget(self.listView)\n self.layout.addWidget(self.stack)\n\n self.setLayout(self.layout)\n self.setupMenu()\n\n\n def setupMenu(self):\n imageList = [self.home_path,self.dashboard_path,self.containers_path,self.images_path,self.volumes_path]\n menuList = ['HOME', 'DASHBOARD', 'CONTAINERS', 'IMAGES', 'VOLUMES']\n for i in range (len(menuList)):\n itm = QListWidgetItem(menuList[i])\n itm.setIcon(QIcon(imageList[i]))\n self.listView.addItem(itm)\n\n\n\n def on_selection_changed(self):\n index = self.listView.currentRow()\n if index == 1:\n self.dashboard.setup(len(self.user.getContainersDetail()) , self.user.getNumberOfImageList(), self.user.getNumberOfVolumeList())\n\n self.stack.setCurrentIndex(index)\n \nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n window = MainWindow()\n apply_stylesheet(app, theme='dark_blue.xml', light_secondary = False)\n window.show()\n\n sys.exit(app.exec_())\n","sub_path":"MainWindow.py","file_name":"MainWindow.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"255588494","text":"from ppb.event import Tick\nfrom ppb.vmath import Vector2 as Vector\n\n\nclass View(object):\n\n def __init__(self, scene, display, fps, hardware):\n self.render_wait = 1 / fps\n self.countdown = self.render_wait\n scene.subscribe(Tick, self.tick)\n self.display = display\n self.layers = [set()]\n self.hw = hardware\n\n def render(self):\n for layer in self.layers:\n for sprite in layer:\n sprite.update()\n self.hw.render(layer)\n self.hw.draw_screen()\n\n def tick(self, event):\n self.countdown += -1 * event.sec\n if self.countdown <= 0:\n self.render()\n self.countdown = self.render_wait\n\n def add(self, sprite, layer=0):\n \"\"\"\n Add a sprite to the view.\n\n :param sprite: Sprite\n :param layer: Layer to render the sprite at.\n :return: None\n \"\"\"\n while len(self.layers) < layer + 1:\n self.layers.append(set())\n self.layers[layer].add(sprite)\n\n def remove(self, sprite):\n \"\"\"\n Remove a sprite from the view.\n\n :param sprite: Sprite\n :return: none\n \"\"\"\n\n for layer in self.layers:\n try:\n layer.remove(sprite)\n except ValueError:\n pass\n\n def change_layer(self, sprite, layer):\n self.remove(sprite)\n self.add(sprite, layer)\n\n\nclass Sprite(object):\n\n def __init__(self, image, model):\n self.image = image\n self.size = image.size\n self.pos = Vector(0, 0)\n self.model = model\n\n def update(self):\n self.pos = Vector(self.model.pos.x - self.size, self.model.pos.y - self.size)\n","sub_path":"ppb/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"575943540","text":"import pytest\n\n\n@pytest.fixture\ndef gopath(tmpdir_factory):\n return tmpdir_factory.mktemp(\"gopath\")\n\n\ndef test_env(cmd, project, gopath):\n cmd.run(f\"export GOPATH={gopath}\")\n\n project.write_devyml(\"\"\"\n up:\n - go: '1.5'\n \"\"\")\n\n cmd.run(\"bud up\")\n\n output = cmd.run(\"go version\")\n assert \"go version go1.5\" in output\n\n\ndef test_warn_gopath_missing(cmd, project, gopath):\n cmd.run(\"unset GOPATH\")\n\n project.write_devyml(\"\"\"\n up:\n - go: '1.5'\n \"\"\")\n\n output = cmd.run(\"bud up\", expect_exit_code=1)\n assert \"The GOPATH environment variable should be set\" in output\n\n\ndef test_with_modules(cmd, project, srcdir):\n # We want to support pre-modules and modules projects in the same environment\n # so we set a GOPATH as it would be for pre-modules setup\n # Devbuddy will set GO111MODULES=on to force-enable Go modules even if we are in the GOPATH\n cmd.run(f\"export GOPATH={srcdir}\")\n\n project.write_devyml(\"\"\"\n up:\n - go:\n version: '1.12'\n modules: true\n \"\"\")\n\n output = cmd.run(\"bud up\")\n\n project.write_file_dedent(\"main.go\", \"\"\"\n package main\n\n import (\n \"fmt\"\n \"github.com/spf13/pflag\"\n )\n\n func main() {\n pflag.Parse()\n fmt.Println(pflag.Arg(0))\n }\n \"\"\")\n\n project.write_file_dedent(\"go.mod\", \"\"\"\n module poipoi\n\n require github.com/spf13/pflag v1.0.3\n \"\"\")\n\n project.write_file_dedent(\"go.sum\", \"\"\"\n github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=\n github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=\n \"\"\")\n\n cmd.run(\"go mod tidy\")\n cmd.run(\"go mod download\")\n\n output = cmd.run(\"go run main.go Test1234\")\n assert output == \"Test1234\"\n","sub_path":"tests/test_task_go.py","file_name":"test_task_go.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"431193496","text":"# -*- coding: utf-8 -*-\n#\n# Python wrapper around the CMake build system\n#\n# Copyright (c) Honda Research Institute Europe GmbH\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n# IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n#\n\n\n#----------------------------------------------------------------------------\n# Includes\n#----------------------------------------------------------------------------\n\n\nimport collections\nimport glob\nimport logging\nimport os\nimport re\nimport shlex\n\nfrom ToolBOSCore.BuildSystem import Compilers\nfrom ToolBOSCore.Util import FastScript\nfrom ToolBOSCore.Util import Any\n\n\n#----------------------------------------------------------------------------\n# Public API\n#----------------------------------------------------------------------------\n\n\nSwitches = collections.namedtuple( 'Switches', [ 'c', 'cpp' ] )\n\n\ndef getIncludePathsAsString( targetPlatform, targetName ):\n \"\"\"\n Returns a long string with all include paths set for the package\n using include_directories() in CMakeLists.txt (in this package or\n included ones).\n\n This means all paths where the compiler would search for header\n files (beside system defaults), in the form \"-I/path1 -I/path2...\".\n\n If no additional paths are set, an empty string will be returned.\n\n NOTE: CMake supports that include directories may be different for\n various target platforms, and even per executable and/or\n library. Therefore you need to specify both of them.\n A rule of thumb is targetName='-global'.\n \"\"\"\n Any.requireIsTextNonEmpty( targetPlatform )\n Any.requireIsTextNonEmpty( targetName )\n\n fileName = os.path.join( 'build/%s/CMakeFiles/%s.dir/flags.make' %\n ( targetPlatform, targetName ) )\n\n Any.requireIsDirNonEmpty( 'build/%s' % targetPlatform )\n Any.requireIsFileNonEmpty( fileName )\n\n # read-in ground truth information\n logging.debug( 'parsing %s' % fileName )\n content = FastScript.getFileContent( fileName, splitLines=True )\n raw_C = ''\n raw_CPP = ''\n regexp_C = re.compile( '^(?:C_FLAGS|C_INCLUDES)\\s=\\s+(.*)$' )\n regexp_CPP = re.compile( '^(?:CXX_FLAGS|CXX_INCLUDES)\\s=\\s+(.*)$' )\n result = ''\n\n for line in content:\n tmp = regexp_C.search( line )\n\n if tmp:\n raw_C = tmp.group( 1 )\n # logging.debug( 'raw C flags: %s' % raw_C )\n\n tmp = regexp_CPP.search( line )\n\n if tmp:\n raw_CPP = tmp.group( 1 )\n # logging.debug( 'raw CPP flags: %s' % raw_CPP )\n\n for candidate in ( shlex.split( raw_C ) + shlex.split( raw_CPP ) ):\n if candidate.startswith( '-I' ):\n result += candidate + ' '\n\n return result\n\n\ndef getIncludePathsAsList( targetPlatform, targetName ):\n \"\"\"\n Returns a list with all include paths set for the package\n using include_directories() in CMakeLists.txt (in this package or\n included ones).\n\n This means all paths where the compiler would search for header\n files (beside system defaults).\n\n If no additional paths are set, an empty list will be returned.\n\n NOTE: CMake supports that include directories may be different for\n various target platforms, and even per executable and/or\n library. Therefore you need to specify both of them.\n A rule of thumb is targetName='-global'.\n \"\"\"\n Any.requireIsTextNonEmpty( targetPlatform )\n Any.requireIsTextNonEmpty( targetName )\n\n result = []\n\n # we are adding a trailing blank so that the \" -I\" replacement will\n # also work on the first element\n raw = getIncludePathsAsString( targetPlatform, targetName )\n tmp = (' ' + raw ).replace( ' -I', ' ' )\n\n for token in tmp.split():\n result.append( token.strip() )\n\n\n # remove empty entries (if present)\n try:\n result.remove( '' )\n except ValueError:\n pass\n\n return frozenset( result )\n\n\ndef getStdSwitches( targetPlatform, targetName ):\n \"\"\"\n Returns a string with the compiler std switch.\n\n NOTE: CMake supports that compiler definitions may be different for\n various target platforms, and even per executable and/or\n library. Therefore you need to specify both of them.\n A rule of thumb is targetName='-global'.\n \"\"\"\n Any.requireIsTextNonEmpty( targetPlatform )\n Any.requireIsTextNonEmpty( targetName )\n\n # We need defaults because the macro parser needs the switch to\n # correctly parse c++ code.\n\n\n fileName = os.path.join( 'build/%s/CMakeFiles/%s.dir/flags.make' %\n ( targetPlatform, targetName ) )\n\n Any.requireIsDirNonEmpty( 'build/%s' % targetPlatform )\n Any.requireIsFileNonEmpty( fileName )\n\n # read-in ground truth information\n logging.debug( 'parsing %s', fileName )\n content = FastScript.getFileContent( fileName, splitLines=True )\n raw_C_CFLAGS = ''\n raw_CPP_CFLAGS = ''\n regexp_C_CFLAGS = re.compile( r'^C_FLAGS\\s=\\s+(.*)$' )\n regexp_CPP_CFLAGS = re.compile( r'^CXX_FLAGS\\s=\\s+(.*)$' )\n\n for line in content:\n tmp = regexp_C_CFLAGS.search( line )\n\n if tmp:\n raw_C_CFLAGS = tmp.group( 1 )\n\n tmp = regexp_CPP_CFLAGS.search( line )\n\n if tmp:\n raw_CPP_CFLAGS = tmp.group( 1 )\n\n # get the default language standards\n standards = Compilers.getDefaultLanguageStandard(targetPlatform)\n cStdSwitch = '-std={}'.format( standards[ 'c' ] )\n cppStdSwitch = '-std={}'.format( standards[ 'c++' ] )\n\n # look if the user specified different standards in the C_FLAGS/CPP_FLAGS\n # CMake variables\n candidates = shlex.split( raw_C_CFLAGS )\n for candidate in candidates:\n if candidate.startswith( '-std=' ):\n cStdSwitch = candidate\n\n candidates = shlex.split( raw_CPP_CFLAGS )\n for candidate in candidates:\n if candidate.startswith( '-std=' ):\n cppStdSwitch = candidate\n\n return Switches( c=cStdSwitch, cpp=cppStdSwitch )\n\n\ndef getCDefinesAsString( targetPlatform, targetName ):\n \"\"\"\n Returns a long string with all compiler definitions set for the\n package using the addDefinitions() directive.\n\n This means all definitions passed to the compiler in the given path\n (beside system defaults), in the form \"-DDEFINE1 -DFOO=BAR...\".\n\n If no additional definitions are set, an empty string will be returned.\n\n NOTE: CMake supports that compiler definitions may be different for\n various target platforms, and even per executable and/or\n library. Therefore you need to specify both of them.\n A rule of thumb is targetName='-global'.\n \"\"\"\n Any.requireIsTextNonEmpty( targetPlatform )\n Any.requireIsTextNonEmpty( targetName )\n\n fileName = os.path.join( 'build/%s/CMakeFiles/%s.dir/flags.make' %\n ( targetPlatform, targetName ) )\n\n Any.requireIsDirNonEmpty( 'build/%s' % targetPlatform )\n Any.requireIsFileNonEmpty( fileName )\n\n # read-in ground truth information\n logging.debug( 'parsing %s' % fileName )\n content = FastScript.getFileContent( fileName, splitLines=True )\n raw_C = ''\n raw_CPP = ''\n raw_C_CFLAGS = ''\n raw_CPP_CFLAGS = ''\n regexp_C = re.compile( '^C_DEFINES\\s=\\s+(.*)$' )\n regexp_CPP = re.compile( '^CXX_DEFINES\\s=\\s+(.*)$' )\n regexp_C_CFLAGS = re.compile( '^C_FLAGS\\s=\\s+(.*)$' )\n regexp_CPP_CFLAGS = re.compile( '^CXX_FLAGS\\s=\\s+(.*)$' )\n result = ''\n\n for line in content:\n tmp = regexp_C.search( line )\n\n if tmp:\n raw_C = tmp.group( 1 )\n # logging.debug( 'raw C defines: %s' % raw_C )\n\n tmp = regexp_CPP.search( line )\n\n if tmp:\n raw_CPP = tmp.group( 1 )\n # logging.debug( 'raw CPP defines: %s' % raw_CPP )\n\n tmp = regexp_C_CFLAGS.search(line)\n\n if tmp:\n raw_C_CFLAGS = tmp.group(1)\n\n tmp = regexp_CPP_CFLAGS.search(line)\n\n if tmp:\n raw_CPP_CFLAGS = tmp.group(1)\n\n candidates = ( shlex.split( raw_C ) +\n shlex.split( raw_CPP ) +\n shlex.split( raw_C_CFLAGS ) +\n shlex.split( raw_CPP_CFLAGS ) )\n\n for candidate in candidates:\n if candidate.startswith( '-D' ):\n result += candidate + ' '\n\n return result\n\n\ndef getCDefinesAsList( targetPlatform, targetName ):\n \"\"\"\n Returns a list with all compiler definitions set for the\n package using the addDefinitions() directive.\n\n If no additional definitions are set, an empty list will be returned.\n\n NOTE: CMake supports that compiler definitions may be different for\n various target platforms, and even per executable and/or\n library. Therefore you need to specify both of them.\n A rule of thumb is targetName='-global'.\n \"\"\"\n Any.requireIsTextNonEmpty( targetPlatform )\n Any.requireIsTextNonEmpty( targetName )\n\n result = []\n regexp = re.compile( '-D\\s*(.*)' )\n\n for token in getCDefinesAsString( targetPlatform, targetName ).split():\n\n if token.startswith( '-D' ):\n tmp = regexp.search( token )\n item = (tmp.group(1)).strip()\n result.append( item )\n\n return frozenset(result)\n\n\ndef getHeaderAndLanguageMap( targetPlatform ):\n \"\"\"\n Returns a dictionary mapping header files to the set of language\n files that use it.\n \"\"\"\n platformBuildDir = os.path.join( 'build', targetPlatform )\n targetBuildDirsWildcard = os.path.join( platformBuildDir, 'CMakeFiles', '*.dir' )\n targetBuildDirs = glob.glob( targetBuildDirsWildcard )\n result = {}\n\n\n for buildDir in targetBuildDirs:\n\n try:\n result.update( _parseDependDotMake( buildDir, platformBuildDir ) )\n\n except IOError:\n # most likely the depend.make does not exist for this target,\n # this might happen if there are no dependencies by the target\n # or if this is a pseudo-target such as \"doc\" coming from\n # FindDoxygen.cmake\n logging.debug( 'ignoring target: %s', buildDir )\n\n return result\n\n\ndef _parseDependDotMake( targetBuildDir, platformBuildDir ):\n \"\"\"\n Returns a dictionary mapping header files to the set of language\n files that use it.\n\n The dictionary is obtained parsing the file\n build//CMakeFiles/.dir/depend.make\n \"\"\"\n Any.requireIsTextNonEmpty( targetBuildDir )\n Any.requireIsTextNonEmpty( platformBuildDir )\n\n dependDotMakePath = os.path.join( targetBuildDir, 'depend.make' )\n\n lines = FastScript.getFileContent( dependDotMakePath, splitLines=True )\n result = collections.defaultdict( set )\n\n languageNormalizationMap = {\n '.c' : 'c',\n '.C' : 'c++',\n '.CC' : 'c++',\n '.CPP': 'c++',\n '.CXX': 'c++',\n '.cc' : 'c++',\n '.cpp': 'c++',\n '.cxx': 'c++',\n }\n\n for l in lines:\n # skip comments and empty lines\n if Any.isTextNonEmpty( l ) and not l.startswith( '#' ):\n # lines are in the format\n # /path/to/obj/file.{c,cpp,cc,cxx}.o: /path/to/dependencyfile.{c,cpp,cc,cxx,h,hpp,hxx,hh}\n objFile, depFile = l.split( ':' )\n srcFile, objExt = os.path.splitext( objFile.strip( ) )\n srcName, srcExt = os.path.splitext( srcFile )\n depFile = depFile.strip( )\n _, depFileExt = os.path.splitext( depFile )\n language = languageNormalizationMap[ srcExt ]\n\n if depFileExt.lower( ) in ('.h', '.hxx', '.hpp', '.hh'):\n if not os.path.isabs( depFile ):\n relPath = os.path.join( platformBuildDir, depFile )\n absPath = os.path.abspath( relPath )\n else:\n absPath = depFile\n result[ absPath ].add( language )\n\n\n return result\n\n\n# EOF\n","sub_path":"include/ToolBOSCore/Tools/CMake.py","file_name":"CMake.py","file_ext":"py","file_size_in_byte":13714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"514805546","text":"#!/usr/bin/env python2\n\n##Here is a better example, an yes, the variable names suck. thats me\\.::\nimport pygame\nimport math\nimport sys \nimport random\n\nfrom pygame.time import Clock\nfrom pygame import Color, mouse\npygame.init()\n\ncircles = set()\n\ntspeed = 1\nspeed = tspeed\ncount = 0\nn_launchers = 3\n\ndef random_color(count):\n color = Color(\"white\")\n color.hsva = (count%360, 90, 80, 60)\n return color\n\nclass World(object):\n def __init__(self, x, y, x_accel=0, y_accel=0):\n self.x = x\n self.y = y\n self.center_x = self.x / 2\n self.center_y = self.y / 2\n self.mass = 2.0\n self.points = []\n self.lock = False\n self.color = random_color(60)\n\n def update(self):\n for x, y, signo in self.points:\n pygame.draw.circle(screen, self.color, (int(x), int(y)), int(10) )\n\n def calculate_gravity_for_particle(self, particle):\n\n for x, y, signo in self.points:\n if not particle.deleted:\n self._gravity_to_point(x, y, particle, signo)\n else:\n break\n\n def add_point(self):\n if not self.lock:\n x, y = pygame.mouse.get_pos()\n \n if pygame.mouse.get_pressed()[0]:\n signo = 1\n else:\n signo = -1\n\n self.points.append((x, y, signo))\n self.lock = True\n\n def unlock(self):\n self.lock = False\n\n\n def _gravity_to_point(self, x, y, particle, signo ):\n dx = particle.x - x\n dy = particle.y - y\n d = pow(dx, 2) + pow(dy, 2)\n ds = math.sqrt(d)\n force = self._calculate_gravity(d)\n if force is not None:\n force *= signo\n particle.x_accel += force * dx / ds\n particle.y_accel += force * dy / ds\n else:\n particle.delete()\n\n def _calculate_gravity(self, d):\n if d <= 10:\n force = None\n else:\n force = int( self.mass) / d\n #force = -1.0 * int( self.mass) / d\n return force\n\n\nclass Circle(object):\n def __init__(self, size, world, x=0, y=0, angle=0, speed=1, color = (0,0,0)):\n self.world = world\n self.color = color\n self.size = size/2\n self.speed_x = math.sin(angle) * speed\n self.speed_y = math.cos(angle) * speed\n self.x_accel = 0\n self.y_accel = 0\n self.x = x\n self.y = y #posicion inicial\n self.deleted=False\n\n def update(self, screen):\n x_size, y_size = screen.get_size()\n\n foo = self.world.calculate_gravity_for_particle(self)\n self.speed_x += self.x_accel\n self.speed_y += self.y_accel\n self.x += self.speed_x\n self.y += self.speed_y\n if not ( (0 < self.x and self.x < x_size) and (0 < self.y and self.y < y_size)):\n self.delete()\n return\n pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), int(self.size) )\n \n def delete(self):\n if not self.deleted:\n global circles\n circles.remove(self)\n self.deleted = True\n \n def __repr__(self):\n return \"\" % (self.x, self.y, self.angle)\n \n\n\nclass Launcher(object):\n \n def __init__(self, x, y, world, queue):\n self.x = x\n self.y = y\n self.world = world\n self.queue = queue\n self.cicles = 0\n self.rot_speed = 0\n self.mov_speed = 0\n self.q = 0\n self.rotation = 0\n self.counter = random.randint(0, 0xFFFFFF)\n self.color_change_speed = random.randint(1,3)\n\n def explode(self):\n for n in xrange(self.q):\n angle = ((n*360.0/self.q) + self.rotation) % 360\n color = random_color(self.counter)\n # self.counter += self.color_change_speed\n self.queue.add(Circle(4, self.world, x=self.x+random.randint(-20, 20), y=self.y, angle=angle, speed=self.mov_speed, color=color))\n \n def change(self):\n if not self.cicles:\n #self.rot_speed = random.uniform(-1, 1)\n self.mov_speed = 1 # random.uniform(1, 10)\n self.cicles = random.randint(500, 1000)\n self.q = 1 # random.randint(1, 6)\n self.rotation += (self.rot_speed % 360)\n self.cicles -= 1\n\n\nx , y = 800, 600 \nscreen = pygame.display.set_mode((x, y))\nclock = Clock()\nworld = World(x, y, 0, 0.1)\n\nlaunchers = []\n\nfor n in xrange(1, n_launchers + 1 ):\n launchers.append( Launcher(n * x/ (n_launchers+1), n * y /(n_launchers + 1), world, circles ))\n launchers.append( Launcher(n * x/ (n_launchers+1), n * y /(n_launchers + 1), world, circles ))\n launchers.append( Launcher(n * x/ (n_launchers+1), n * y /(n_launchers + 1), world, circles ))\n launchers.append( Launcher(n * x/ (n_launchers+1), n * y /(n_launchers + 1), world, circles ))\n launchers.append( Launcher(n * x/ (n_launchers+1), n * y /(n_launchers + 1), world, circles ))\n launchers.append( Launcher(n * x/ (n_launchers+1), n * y /(n_launchers + 1), world, circles ))\n\n\n\n\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT: \n sys.exit()\n elif event.type == pygame.MOUSEBUTTONDOWN:\n world.add_point()\n elif event.type == pygame.MOUSEBUTTONUP:\n world.unlock()\n\n screen.fill((0,0,0))\n circle_list = list(circles)\n world.update()\n for c in circle_list:\n c.update(screen)\n for launcher in launchers:\n launcher.change()\n if len(circles) < 5000: \n for launcher in launchers:\n launcher.explode()\n \n \n pygame.display.update()\n clock.tick(50)\n\n","sub_path":"mouse_repulsor.py","file_name":"mouse_repulsor.py","file_ext":"py","file_size_in_byte":5681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"352435218","text":"\n\n#calss header\nclass _PENLIGHT():\n\tdef __init__(self,): \n\t\tself.name = \"PENLIGHT\"\n\t\tself.definitions = [u'a small torch about the size and shape of a pen']\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/_penlight.py","file_name":"_penlight.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"462819964","text":"import numpy as np \r\n\r\n\r\n# NEURAL NETWORK PARAMETERS \r\nsizes= [2,2, 1] # vector representing number of nodes per layer\r\nepochs=1000\r\nlearningrate= 0.01\r\nseed=1\r\n\r\n\r\n# Barrier Function\r\ndef f_barrier(x):\r\n return abs(x)\r\n\r\n# SET PARAMETERS \r\n\r\n#Training\r\nN=1000 # number of points \r\nx= [-1,1] # domain\r\n\r\n\r\n#Testing\r\nN_test=1000 # number of points \r\nx_test= [-5,5] # domain \r\n\r\n# ACTIVATION FUNCTION \r\n# hyperbolic tangent: tanh \r\n# sigmoid: sig\r\n# sine: sin \r\n\r\nphi=\"tanh\"\r\n\r\n# graphic options\r\n\r\nresolution= 0.01\r\nN_runs= 100 # number of runs for histogram \r\n\r\nimport main_barrier \r\n","sub_path":"run_barrier.py","file_name":"run_barrier.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"617117439","text":"import pymongo\nimport pymysql\nimport time\nimport xlwt\nimport oss2\nimport config\n\n\nclass ExportMarkOrQualitySettle(object):\n def __init__(self):\n \"\"\"初始化\"\"\"\n # 1. 创建mysql连接\n self.db_mysql = pymysql.connect(**config.mysql_config)\n self.cursor = self.db_mysql.cursor()\n\n # 2. 创建mongo连接\n dict_mongo = config.mongo_config\n self.db_mongo = pymongo.MongoClient(dict_mongo[\"address\"], dict_mongo[\"port\"])\n # 1) mongo认证过程,要使用认证库admin!\n self.db_auth = self.db_mongo.admin\n self.db_auth.authenticate(dict_mongo[\"user\"], dict_mongo[\"password\"])\n # 2) 连接业务库crowd\n self.db_client = config.mongo_config[\"database\"]\n\n # 3. 创建oss连接\n self.dict_oss = config.oss_config\n self.auth = oss2.Auth(self.dict_oss[\"accessKeyId\"], self.dict_oss[\"accessKeySecret\"])\n self.bucket = oss2.Bucket(self.auth, self.dict_oss[\"endpoint\"], self.dict_oss[\"bucketName\"])\n\n def close_databases(self):\n \"\"\"关闭数据库连接\"\"\"\n # 关闭mysql连接\n self.cursor.close()\n self.db_mysql.close()\n # 关闭mongo连接\n self.db_mongo.close()\n\n def export_settle(self, taskid, accTaskId):\n \"\"\"结算主方法: 导出、上传、返回\"\"\"\n # 一、 数据导出过程\n # 结算主方法sql:查询用户ID, 用户名称, 总条数, 合格总框数\n sql_count = \"\"\"\n SELECT\n t.tagUser,\n tt.userName,\n count(DISTINCT dataId) AS cnt,\n sum(qualifiedBoxCount) AS qualifiedBoxCount\n FROM\n (\n SELECT\n tagUser,\n dataId,\n tagCount,\n (case when unqualifiedBoxCount > 0 then qualifiedBoxCount else tagCount end) qualifiedBoxCount\n FROM\n `task_datadetail_b_\"\"\"+taskid+\"\"\"` AS t3\n WHERE\n checkFlag = '1'\n AND EXISTS (\n SELECT\n 1\n FROM\n task_accept_b AS t1\n INNER JOIN `task_acceptdetail_b_\"\"\"+accTaskId+\"\"\"` AS t2 ON t1.taskId = t2.taskId\n AND t1.acceptId = t2.acceptId\n WHERE\n 1 = 1\n AND t2.dataId = t3.dataId\n AND (\n (\n t1.accResult = '0'\n AND t2.acceptStatus != '4'\n )\n OR (\n t1.accResult != '0'\n AND t2.acceptStatus = '1'\n )\n )\n )\n ) AS t\n INNER JOIN user_info_m AS tt\n on t.tagUser = tt.userId\n GROUP BY\n tagUser, tt.userName\n \"\"\"\n self.cursor.execute(sql_count)\n count_info = self.cursor.fetchall()\n # 关闭数据库连接\n self.close_databases()\n # excel处理\n workbook = xlwt.Workbook()\n sheet = workbook.add_sheet('sheet1', cell_overwrite_ok=True)\n # 表头\n sheet.write(0, 0, '用户ID')\n sheet.write(0, 1, '用户名称')\n sheet.write(0, 2, '总条数')\n sheet.write(0, 3, '合格总框数')\n # 数据行\n rowIdx = 1\n for ci in count_info:\n sheet.write(rowIdx, 0, ci[0]) # 'tagUser'\n sheet.write(rowIdx, 1, ci[1]) # 'userName'\n sheet.write(rowIdx, 2, ci[2]) # 'cnt'\n sheet.write(rowIdx, 3, ci[3]) # 'qualifiedBoxCount'\n rowIdx = rowIdx+1\n # 定义时间戳:time获取当前时间戳\n now_time = int(time.time())\n time_array = time.localtime(now_time)\n normal_time = time.strftime(\"%Y-%m-%d_%H_%M_%S\", time_array)\n # 输出的excel文件名一定是整个业务流程中的标注任务的任务ID加上时间戳\n fileName = ('%s' % taskid) + '_' + normal_time + '.xls'\n filePath = config.path\n workbook.save(\"%s%s\" % (filePath, fileName))\n\n # 二、 文件上传过程\n self.bucket.put_object_from_file(self.dict_oss[\"prefx\"] + fileName, filePath + fileName)\n upload_url = self.bucket.sign_url('GET', self.dict_oss[\"prefx\"] + fileName, 86400)\n\n # 三、 返回json过程\n json_obj = {\n \"type\": \"FILE\",\n \"file\": {\n \"name\": fileName,\n \"url\": upload_url\n }\n }\n\n return json_obj\n\n def task_judge(self, task_id):\n \"\"\"判断任务关系\"\"\"\n # 1. 查询当前任务类别\n sql_task = \"\"\"\n SELECT\n ti.checkTaskFlg AS taskType,\n ti.isAccept\n FROM\n `task_info_b` AS ti\n WHERE\n ti.taskId = %s\n \"\"\"\n self.cursor.execute(sql_task, task_id)\n results = self.cursor.fetchall()\n if len(results) > 0:\n taskType = results[0][0]\n isAccept = results[0][1]\n\n # 2. 如果当前任务的类别是标注任务(taskType == '0')并且该任务需要验收, 要向下查, 下一个任务一定是自检任务\n # 可以确定业务流程是 \"标注 → 自检 → 验收\";\n if taskType == '0' and isAccept == '1':\n sql_dest = \"\"\"\n SELECT\n ti.taskId\n FROM\n `task_info_b` AS ti\n WHERE\n ti.checkTaskId = %s\n \"\"\"\n self.cursor.execute(sql_dest, task_id)\n result = self.cursor.fetchall()\n accept_taskId = result[0][0]\n\n # 调用结算主方法\n rectData = self.export_settle(task_id, accept_taskId)\n return rectData\n\n # 3. 如果当前任务不需要验收, 就需要一直向下查, 直到查询无结果为止\n if taskType == '0' and isAccept == '0':\n sql_dest = \"\"\"\n SELECT\n ti.checkTaskFlg AS taskType,\n ti.taskId\n FROM\n `task_info_b` AS ti\n WHERE\n ti.checkTaskId = %s\n \"\"\"\n self.cursor.execute(sql_dest, task_id)\n result = self.cursor.fetchall()\n taskType_check = result[0][0]\n taskId_check = result[0][1]\n # 如果下一个任务是自检任务, 并且此时不需要验收, 即此任务是标注的自检任务\n if taskType_check == '4':\n self.cursor.execute(sql_dest, taskId_check)\n result_marselfcheck = self.cursor.fetchall()\n taskId_quacheck = result_marselfcheck[0][1]\n # 此时一定有下一个任务即质检任务, 所以再向下查一次\n self.cursor.execute(sql_dest, taskId_quacheck)\n result_quaselfcheck = self.cursor.fetchall()\n # 判断如果查询结果为空, 则无下一个任务\n if len(result_quaselfcheck) == 0:\n accept_taskId = taskId_quacheck\n # 如果结果不为空, 则存在下一个任务即质检的自检任务\n else:\n taskId_quaselfcheck = result_quaselfcheck[0][1]\n accept_taskId = taskId_quaselfcheck\n # 如果下一个任务是质检任务, 则需要判断是否还存在质检的自检任务\n else:\n self.cursor.execute(sql_dest, taskId_check)\n result_quaselfcheck = self.cursor.fetchall()\n if len(result_quaselfcheck) == 0:\n accept_taskId = taskId_check\n else:\n taskId_quaselfcheck = result_quaselfcheck[0][1]\n accept_taskId = taskId_quaselfcheck\n\n # 调用结算主方法\n rectData = self.export_settle(task_id, accept_taskId)\n return rectData\n\n # 4. 如果当前任务的类别是质检任务(taskType == '1')并且该任务需要验收, 首先要向下查, 并判断下一个任务是否有自检任务,\n # 如果有自检任务, 则accept_taskId = 下一个任务ID, 如果没有, 则accept_taskId = 当前任务的ID;\n # 其次要向上查, 使用递归, 直到查询的checkTaskFlg的值为空时, 当前的任务ID即为标注任务的ID\n if taskType == '1' and isAccept == '1':\n # ***查询下一个任务(不一定存在, 需做判断是否还有自检任务)***\n sql_dest = \"\"\"\n SELECT\n ti.taskId\n FROM\n `task_info_b` AS ti\n WHERE\n ti.checkTaskId = %s\n \"\"\"\n self.cursor.execute(sql_dest, task_id)\n result = self.cursor.fetchall()\n if len(result) == 0:\n accept_taskId = task_id\n else:\n taskId_dest = result[0][0]\n self.cursor.execute(sql_dest, taskId_dest)\n result_dest = self.cursor.fetchall()\n if len(result_dest) == 0:\n accept_taskId = taskId_dest\n # ***查询上一个任务(一定存在, 需要判断上一个任务是自检任务还是标注任务)***\n sql_source = \"\"\"\n SELECT\n ti.checkTaskId,\n ti.checkTaskFlg AS taskType\n FROM\n `task_info_b` AS ti\n WHERE\n ti.taskId = %s\n \"\"\"\n self.cursor.execute(sql_source, task_id)\n result_source = self.cursor.fetchall()\n taskId_source = result_source[0][0]\n taskType_source = result_source[0][1]\n if taskType_source == '0':\n taskId_mark = taskId_source\n elif taskType_source == '1':\n taskId_mark = taskId_source\n else:\n self.cursor.execute(sql_source, taskId_source)\n result_mark = self.cursor.fetchall()\n taskId_mark = result_mark[0][0]\n\n # 调用结算主方法\n rectData = self.export_settle(taskId_mark, accept_taskId)\n return rectData\n\n # 5. 如果当前任务的类别是自检任务(taskType == '4'), 并且不需要验收, 可以确定当前任务是标注的自检任务, 需要:\n # 1) 向上查一次, 确定标注任务的ID\n if taskType == '4' and isAccept == '0':\n sql_source = \"\"\"\n SELECT\n ti.checkTaskId\n FROM\n `task_info_b` AS ti\n WHERE\n ti.taskId = %s\n \"\"\"\n self.cursor.execute(sql_source, task_id)\n result_source_mark = self.cursor.fetchall()\n taskId_source_mark = result_source_mark[0][0]\n # 2) 向下查一次, 一定存在质检任务\n sql_dest = \"\"\"\n SELECT\n ti.taskId\n FROM\n `task_info_b` AS ti\n WHERE\n ti.checkTaskId = %s\n \"\"\"\n self.cursor.execute(sql_dest, task_id)\n dest = self.cursor.fetchall()\n # 如果查询结果为空, 则证明是中途开启的自检, 需要使用标注任务的ID即'taskId_source_mark'去查询质检任务的任务ID\n if len(dest) == 0:\n self.cursor.execute(sql_dest, taskId_source_mark)\n checkId = self.cursor.fetchall()\n quacheckId = checkId[0][0]\n # 查询质检任务的下一个任务(不一定存在, 需做判断是否还有质检的自检任务)\n sql_dest = \"\"\"\n SELECT\n ti.taskId\n FROM\n `task_info_b` AS ti\n WHERE\n ti.checkTaskId = %s\n \"\"\"\n self.cursor.execute(sql_dest, quacheckId)\n selfId = self.cursor.fetchall()\n if len(selfId) == 0:\n accept_taskId = quacheckId\n else:\n quaselfId = selfId[0][0]\n accept_taskId = quaselfId\n # 如果查询不为空, 说明质检任务关联的是标注的自检任务, 不是中途开启的自检任务\n else:\n quacheckId = dest[0][0]\n # 查询质检任务的下一个任务(不一定存在, 需做判断是否还有质检的自检任务)\n sql_dest = \"\"\"\n SELECT\n ti.taskId\n FROM\n `task_info_b` AS ti\n WHERE\n ti.checkTaskId = %s\n \"\"\"\n self.cursor.execute(sql_dest, quacheckId)\n selfId = self.cursor.fetchall()\n if len(selfId) == 0:\n accept_taskId = quacheckId\n else:\n quaselfId = selfId[0][0]\n accept_taskId = quaselfId\n\n # 调用结算主方法\n rectData = self.export_settle(taskId_source_mark, accept_taskId)\n return rectData\n\n # 6. 如果当前任务是自检任务, 并且需要验收, 需要向上查一次, 查询上一个任务是标注任务还是质检任务\n if taskType == '4' and isAccept == '1':\n # 向上查一次, 得到上一个任务的任务ID\n sql_source = \"\"\"\n SELECT\n ti.checkTaskId\n FROM\n `task_info_b` AS ti\n WHERE\n ti.taskId = %s\n \"\"\"\n self.cursor.execute(sql_source, task_id)\n result = self.cursor.fetchall()\n taskId_source = result[0][0]\n # 使用上一个任务ID查询出上一个任务的任务类别\n sql_source_type = \"\"\"\n SELECT\n ti.checkTaskFlg\n FROM\n `task_info_b` AS ti\n WHERE\n ti.taskId = %s\n \"\"\"\n self.cursor.execute(sql_source_type, taskId_source)\n result_type = self.cursor.fetchall()\n source_type = result_type[0][0]\n # source_type的结果不是'0',就是'1', 即不是标注任务, 就是质检任务\n # 如果上一个任务是标注任务, 且现在需要验收, 则业务流程是 \"标注 → 自检 → 验收\"\n if source_type == '0':\n taskId_mark = taskId_source\n accept_taskId = task_id\n # 如果上一个任务是质检任务, 继续向上查, 并判断质检的上一个任务是标注任务还是标注的自检任务\n else:\n sql_mark = \"\"\"\n SELECT\n ti.checkTaskId\n FROM\n `task_info_b` AS ti\n WHERE\n ti.taskId = %s\n \"\"\"\n self.cursor.execute(sql_mark, taskId_source)\n result_isMark = self.cursor.fetchall()\n taskId_isMark = result_isMark[0][0]\n # 根据此ID, 查询此任务的类别\n sql_mark_type = \"\"\"\n SELECT\n ti.checkTaskFlg\n FROM\n `task_info_b` AS ti\n WHERE\n ti.taskId = %s\n \"\"\"\n self.cursor.execute(sql_mark_type, taskId_isMark)\n result_mark_type = self.cursor.fetchall()\n taskType_isMark = result_mark_type[0][0]\n # 如果质检任务的上一个任务是自检任务, 则需要再向上查一次\n if taskType_isMark == '4':\n self.cursor.execute(sql_mark, taskId_isMark)\n rect = self.cursor.fetchall()\n markId = rect[0][0]\n taskId_mark = markId\n # 如果质检任务的上一个任务是标注任务, 则结束查询\n else:\n taskId_mark = taskId_isMark\n accept_taskId = task_id\n\n # 调用结算主方法\n rectData = self.export_settle(taskId_mark, accept_taskId)\n return rectData\n\n else:\n json_obj = {\n \"type\": \"FILE\",\n \"file\": {\n \"name\": None,\n \"url\": None\n }\n }\n\n return json_obj\n","sub_path":"restfulApi/markOrQualitySettle.py","file_name":"markOrQualitySettle.py","file_ext":"py","file_size_in_byte":18297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"51485543","text":"#! /usr/bin/env python\n# coding: utf-8\n\nimport os\nimport argparse\nfrom JYTools.JYWorker import RedisQueue\n\n# conf_dir = \"/public/JINGD/conf\"\n# conf_path = os.path.join(conf_dir, \"redis_worker.conf\")\nconf_path = os.environ.get(\"REDIS_WORKER_CONF_PATH\")\nr_queue = RedisQueue(conf_path=conf_path, work_tag=\"JYGroupDAG\")\n\n\n\ndef run_hotspot(normal_recal_bam, hotspot_vcf, sample_no):\n apply_pipeline = {\"task_list\": [{\"task_type\": \"app\", \"work_tag\": \"RunHotspot\",\n \"input_sample_no\": sample_no,\n \"input_hotspot_vcf\": hotspot_vcf,\n \"input_normal_recal_bam\": normal_recal_bam}],\n \"task_type\": \"pipeline\"}\n r_queue.push(sample_no, apply_pipeline)\n\n\ndef main():\n usage = \"Help message\"\n description = \"Run manta pipeline\"\n parser = argparse.ArgumentParser(usage=usage, description=description)\n\n parser.add_argument(\"-n\", \"--normal_recal_bam\", dest=\"normal_recal_bam\", help=\"normal recal bam path\")\n parser.add_argument(\"-v\", \"--hotspot_vcf\", dest=\"hotspot_vcf\", help=\"hot spot vcf path\")\n\n parser.add_argument(\"-s\", \"--sample-no\", dest=\"sample_no\", help=\"sample no\")\n args = parser.parse_args()\n normal_recal_bam = args.normal_recal_bam\n hotspot_vcf = args.hotspot_vcf\n sample_no = args.sample_no\n\n run_hotspot(normal_recal_bam, hotspot_vcf, sample_no)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"anzhen/branch_pipeline/test_hotspot.py","file_name":"test_hotspot.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"642382592","text":"class DotDesktopModel(object):\n \"\"\"\n This class models the .desktop file to be installed.\n \"\"\" \n\n INSTALL_DIR = \"/usr/share/applications/\"\n\n def __init__(self, name=\"\"):\n self.name = name\n self.tooltip = \"\"\n self.terminal = \"\"\n self.icon = \"\"\n self.exe = \"\"\n self.category = \"\"\n\n def __str__(self):\n return \"[Desktop Entry]\\n\" \\\n \"Version=1.0\\n\" \\\n \"Type=Application\\n\" \\\n \"Encoding=UTF-8\\n\" \\\n \"Name=\" + self.name + \"\\n\" \\\n \"Comment=\" + self.tooltip + \"\\n\" \\\n \"Icon=\" + self.icon + \"\\n\" \\\n \"Exec=\" + self.exe + \"\\n\" \\\n \"Terminal=\" + str(self.terminal) + \"\\n\" \\\n \"Categories=\" + self.category\n","sub_path":"model/dot_desktop_model.py","file_name":"dot_desktop_model.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"295427675","text":"import argparse\nimport re\n\nfrom codegen_outofplacebatching import deindent, get_signatures, gen_unwraps\n\n\ndef get_signature(op, path):\n signatures = get_signatures(path, include_op=True)\n result = [sig for sig in signatures if sig[0] == op]\n if len(result) != 1:\n raise ValueError(\"\")\n return result[0]\n\n\ndef gen_return_sig(return_t):\n if len(return_t) == 1:\n return return_t[0]\n return f'std::tuple<{\".\".join(return_t)}>'\n\n\ndef gen_args_sig(args_t):\n args = [f'{typ} {argname}' for typ, argname in args_t]\n return ', '.join(args)\n\n\ndef gen_args_list(args_t):\n args = [f'{argname}' for _, argname in args_t]\n return ', '.join(args)\n\n\ndef gen_plumbing(signature):\n # \"add.Tensor\"\n op, return_t, args_t = signature\n\n maybe_op_and_variant = op.split('.')\n if len(maybe_op_and_variant) == 1:\n op = maybe_op_and_variant[0]\n variant = ''\n opname = op\n else:\n op, variant = maybe_op_and_variant\n opname = f'{op}_{variant}'\n\n if op.endswith('_'):\n raise ValueError('Codegen doesn\\'t handle in-place ops')\n\n arg_types, arg_names = zip(*args_t)\n unwraps, _ = gen_unwraps(arg_types, arg_names)\n\n result = deindent(f\"\"\"\\\n {gen_return_sig(return_t)} {opname}_plumbing({gen_args_sig(args_t)}) {{\n auto maybe_layer = maybeCurrentDynamicLayer();\n TORCH_INTERNAL_ASSERT(maybe_layer.has_value());\n int64_t cur_level = maybe_layer->layerId();\n\n {unwraps}\n\n // Your logic here\n\n static auto op = c10::Dispatcher::singleton()\n .findSchemaOrThrow(\"aten::{op}\", \"{variant}\");\n return slow_fallback<{','.join(return_t)}>(op, {{ {gen_args_list(args_t)} }});\n }}\n \"\"\")\n return result\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description='Generate the batch rule plumbing for an op')\n parser.add_argument('op',\n help='the operator name (with overload name)')\n parser.add_argument('path',\n help='link to RegistrationDeclarations.h')\n\n # Sample usage:\n # gen_plumbing.py add.Tensor ~/pytorch/build/aten/src/ATen/RegistrationDeclarations.h\n args = parser.parse_args()\n signature = get_signature(args.op, args.path)\n result = gen_plumbing(signature)\n print(result)\n","sub_path":"codegen/gen_plumbing.py","file_name":"gen_plumbing.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"561296021","text":"import cv2 as cv\nimport numpy as np\nimport argparse\nfrom matplotlib import pyplot as plt\n\nparser = argparse.ArgumentParser(description='Code for Creating Bounding boxes around lego pieces.')\nparser.add_argument('--input', help='Path to input image.', default='IMG_6101.JPG')\nargs = parser.parse_args()\n\nsrc = cv.imread(cv.samples.findFile(args.input))\nif src is None:\n print('Could not open or find the image:', args.input)\n exit(0)\n\n# Convert image to gray and blur it\nsrc_gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)\nsrc_gray = cv.blur(src_gray, (3,3))\n\n# Calculate contours\ncanny_threshold = 50\ncanny_output = cv.Canny(src_gray, canny_threshold, canny_threshold * 3)\n\ncontours, _ = cv.findContours(canny_output, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)\n\ncontours_poly = [None]*len(contours)\nboundRect = [None]*len(contours)\nfor i, c in enumerate(contours):\n contours_poly[i] = cv.approxPolyDP(c, 3, True)\n boundRect[i] = cv.boundingRect(contours_poly[i])\n\n# Draw the contours\ncontours_drawing = np.zeros((canny_output.shape[0], canny_output.shape[1], 3), dtype=np.uint8)\nfor i in range(len(contours)):\n color = (255, 255, 255)\n cv.drawContours(contours_drawing, contours_poly, i, color)\n\n# Draw the original with bounding rectangle\nrectangle_drawing = src.copy()\nfor i in range(len(contours)):\n color = (255, 0, 0)\n cv.rectangle(rectangle_drawing, (int(boundRect[i][0]), int(boundRect[i][1])), \\\n (int(boundRect[i][0]+boundRect[i][2]), int(boundRect[i][1]+boundRect[i][3])), color, 2)\n\n\nplt.subplot(231)\nplt.imshow(src)\nplt.title('Original Image')\nplt.xticks([]), plt.yticks([])\n\nplt.subplot(232)\nplt.imshow(src_gray, cmap = 'gray')\nplt.title('Greyed and blured')\nplt.xticks([]), plt.yticks([])\n\nplt.subplot(233)\nplt.imshow(canny_output)\nplt.title('Canny output')\nplt.xticks([]), plt.yticks([])\n\nplt.subplot(234)\nplt.imshow(contours_drawing, cmap = 'gray')\nplt.title('Contours')\nplt.xticks([]), plt.yticks([])\n\nplt.subplot(235)\nplt.imshow(rectangle_drawing)\nplt.title('Contours with rectangles')\nplt.xticks([]), plt.yticks([])\n\nplt.show()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"577471574","text":"#! -*- coding:utf-8 -*-\nimport numpy as np\nfrom sklearn import linear_model\n\n# d <- read.csv(file='input/data-salary.txt')\n# res_lm <- lm(Y ~ X, data=d)\n# X_new <- data.frame(X=23:60)\n# conf_95 <- predict(res_lm, X_new, interval='confidence', level=0.95)\n# pred_95 <- predict(res_lm, X_new, interval='prediction', level=0.95)\n\nd = np.genfromtxt(fname='input/data-salary.txt', delimiter=',', names=True, dtype=np.float)\nlm = linear_model.LinearRegression()\nlm.fit(d['X'].reshape(d.size, 1), d['Y'])\n\nprint('Intercept: ' + str(lm.intercept_))\nprint('Coefficients: ' + str(lm.coef_[0]))\n# 一応p.38の1 行目の数値はとは一致した。\n# 信頼区間と予測区間については、まだ書いてない\n","sub_path":"chap04/lm.py","file_name":"lm.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"601197355","text":"import turtle\nfrom tkinter import PhotoImage\nfrom turtle import Turtle, Screen, Shape\nimport math\nimport random\n\nmyscreen = turtle.Screen()\nmyscreen.title(\"Turtle_Driver\")\nmyscreen.bgcolor(\"silver\")\nmyscreen.setup(1100,1000)\n\nclass Driver:\n def __init__(self):\n myscreen.tracer(0)\n self.xcor = 0\n self.ycor = 0 \n while True:\n myscreen.ontimer(self.Activity(), 300)\n \n\n def move_goal(self): \n Goal.goto(self.xcor,self.ycor) \n \n def robo_path_set(self): \n Robot.setheading(Robot.towards(Goal)) \n Robot.fd(20)\n\n def Output(self):\n r_y = int(Robot.ycor()) \n r_x = int(Robot.xcor())\n g_y = int(Goal.ycor()) \n g_x = int(Goal.xcor()) \n print (\"Turtle:\", int(r_x), int(r_y))\n print (\"Goal:\", int(g_x), int(g_y))\n self.dist = math.sqrt((g_x - r_x) **2 + (g_y - r_y) **2)\n print (\"Distance left:\", self.dist) \n \n def Update_goal(self): \n if self.dist <= 10: \n print(\"checkpoint successfully reached\") \n self.xcor = random.randint(-400,350)\n self.ycor = random.randint(-400,350)\n Goal.goto(self.xcor, self.ycor) \n \n def Activity(self):\n myscreen.update() \n self.robo_path_set()\n self.move_goal()\n self.Output() \n self.Update_goal() \n \nclass Robot(turtle.Turtle):\n def __init__(self):\n turtle.Turtle.__init__(self)\n self.shape(\"turtle\")\n self.shapesize(2)\n self.color(\"red\")\n self.penup()\n self.goto(-350,-400) \n\nRobot = Robot() \n \nclass Goal(turtle.Turtle):\n def __init__(self):\n turtle.Turtle.__init__(self)\n goal = PhotoImage(file=\"images/goal.png\").zoom(1,1) \n myscreen.addshape(\"goal\", Shape(\"image\", goal))\n self.shape(\"goal\")\n self.penup()\n self.speed(0)\n\nGoal = Goal()\n\n \n \nif __name__ == '__main__':\n Driver()\n","sub_path":"src/Examples/Goal_seeker.py","file_name":"Goal_seeker.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"388173261","text":"# (C) Datadog, Inc. 2019\n# All rights reserved\n# Licensed under a 3-clause BSD style license (see LICENSE)\nimport pytest\n\nfrom . import metrics\n\npytestmark = pytest.mark.e2e\n\n\n@pytest.mark.e2e\ndef test_check(dd_agent_check, instance):\n aggregator = dd_agent_check(instance, rate=True)\n\n for metric in metrics.STANDARD:\n aggregator.assert_metric_has_tag(metric, 'server:{}'.format(instance['server']))\n aggregator.assert_metric_has_tag(metric, 'port:{}'.format(instance['port']))\n\n aggregator.assert_all_metrics_covered()\n","sub_path":"sap_hana/tests/test_e2e.py","file_name":"test_e2e.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"456377726","text":"from typing import Any, Dict, List, cast\n\nimport torch\nfrom torchdata.datapipes.iter import IterDataPipe, Mapper, CSVDictParser\nfrom torchvision.prototype.datasets.utils import (\n Dataset,\n DatasetConfig,\n DatasetInfo,\n OnlineResource,\n KaggleDownloadResource,\n)\nfrom torchvision.prototype.datasets.utils._internal import (\n hint_sharding,\n hint_shuffling,\n)\nfrom torchvision.prototype.features import Label, Image\n\n\nclass FER2013(Dataset):\n def _make_info(self) -> DatasetInfo:\n return DatasetInfo(\n \"fer2013\",\n homepage=\"https://www.kaggle.com/c/challenges-in-representation-learning-facial-expression-recognition-challenge\",\n categories=(\"angry\", \"disgust\", \"fear\", \"happy\", \"sad\", \"surprise\", \"neutral\"),\n valid_options=dict(split=(\"train\", \"test\")),\n )\n\n _CHECKSUMS = {\n \"train\": \"a2b7c9360cc0b38d21187e5eece01c2799fce5426cdeecf746889cc96cda2d10\",\n \"test\": \"dec8dfe8021e30cd6704b85ec813042b4a5d99d81cb55e023291a94104f575c3\",\n }\n\n def resources(self, config: DatasetConfig) -> List[OnlineResource]:\n archive = KaggleDownloadResource(\n cast(str, self.info.homepage),\n file_name=f\"{config.split}.csv.zip\",\n sha256=self._CHECKSUMS[config.split],\n )\n return [archive]\n\n def _prepare_sample(self, data: Dict[str, Any]) -> Dict[str, Any]:\n label_id = data.get(\"emotion\")\n\n return dict(\n image=Image(torch.tensor([int(idx) for idx in data[\"pixels\"].split()], dtype=torch.uint8).reshape(48, 48)),\n label=Label(int(label_id), categories=self.categories) if label_id is not None else None,\n )\n\n def _make_datapipe(\n self,\n resource_dps: List[IterDataPipe],\n *,\n config: DatasetConfig,\n ) -> IterDataPipe[Dict[str, Any]]:\n dp = resource_dps[0]\n dp = CSVDictParser(dp)\n dp = hint_sharding(dp)\n dp = hint_shuffling(dp)\n return Mapper(dp, self._prepare_sample)\n","sub_path":"torchvision/prototype/datasets/_builtin/fer2013.py","file_name":"fer2013.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"631446847","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\n\nclass PPO():\n def __init__(self,\n actor_critic,\n clip_param,\n ppo_epoch,\n num_mini_batch,\n value_loss_coef,\n entropy_coef,\n lr=None,\n lr_beta=None,\n eps=None,\n N_recurrent=0,\n max_grad_norm=None,\n max_grad_norm_beta=None,\n delib_coef=0,\n weighted_loss=0,\n use_clipped_value_loss=True):\n\n self.actor_critic = actor_critic\n self.weighted_loss = weighted_loss\n self.clip_param = clip_param\n self.ppo_epoch = ppo_epoch\n self.num_mini_batch = num_mini_batch\n self.N_recurrent = N_recurrent\n self.value_loss_coef = value_loss_coef\n self.entropy_coef = entropy_coef\n\n self.max_grad_norm = max_grad_norm\n self.max_grad_norm_beta = max_grad_norm_beta\n self.use_clipped_value_loss = use_clipped_value_loss\n self.delib_coef = delib_coef\n\n self.param_beta = []\n self.param_list = []\n for name, param in actor_critic.named_parameters():\n if \"beta\" in name :\n self.param_beta.append(param)\n else:\n self.param_list.append(param)\n self.optimizer = optim.Adam(\n [{'params': self.param_list},{'params':self.param_beta,'lr':lr_beta}], lr, eps=eps)\n\n def update(self, rollouts):\n advantages = rollouts.returns[:-1] - rollouts.value_mixed[1:]\n advantages = (advantages - advantages.mean()) / (\n advantages.std() + 1e-5)\n\n value_loss_epoch = 0\n action_loss_epoch = 0\n dist_entropy_epoch = 0\n\n for e in range(self.ppo_epoch):\n if self.actor_critic.is_recurrent and self.N_recurrent == 0:\n data_generator = rollouts.recurrent_generator(\n advantages, self.num_mini_batch)\n else:\n data_generator = rollouts.feed_forward_generator(\n advantages, self.num_mini_batch)\n\n for sample in data_generator:\n obs_batch, recurrent_hidden_states_batch, actions_batch, \\\n value_preds_batch, return_batch, masks_batch, old_action_log_probs_batch, \\\n adv_targ,indices = sample\n\n # Reshape to do in a single forward pass for all steps\n values, action_log_probs, dist_entropy, _, mean_beta_v = self.actor_critic.evaluate_actions(\n rollouts.obs[:-1].view(-1, *rollouts.obs.size()[2:]),\n rollouts.recurrent_hidden_states[:-1].view(-1,rollouts.recurrent_hidden_states.size(-1)),\n rollouts.masks[:-1].view(-1, 1),\n rollouts.actions.view(-1, rollouts.actions.size(-1)),\n rollouts.value_mixed.view(-1,1),indices)\n\n #values, action_log_probs, dist_entropy, _, mean_beta_v = self.actor_critic.evaluate_actions(\n # rollouts.obs[:-1],\n # rollouts.recurrent_hidden_states[:-1],\n # rollouts.masks[:-1],\n # rollouts.actions,\n # rollouts.value_mixed,indices)\n ratio = torch.exp(action_log_probs -\n old_action_log_probs_batch)\n surr1 = ratio * adv_targ\n surr2 = torch.clamp(ratio, 1.0 - self.clip_param,\n 1.0 + self.clip_param) * adv_targ\n if self.weighted_loss:\n normalized_beta = ((mean_beta_v / mean_beta_v.sum()) * mean_beta_v.size()[0]).view(-1, 1)\n surr1 *= normalized_beta\n surr2 *= normalized_beta\n\n action_loss = (-torch.min(surr1, surr2)).mean()\n\n if self.use_clipped_value_loss:\n value_pred_clipped = value_preds_batch + \\\n (values - value_preds_batch).clamp(-self.clip_param, self.clip_param)\n value_losses = (values - return_batch).pow(2)\n\n value_losses_clipped = (\n value_pred_clipped - return_batch).pow(2)\n\n if self.weighted_loss:\n value_losses *= normalized_beta\n value_losses_clipped *= normalized_beta\n\n value_loss = 0.5 * torch.max(value_losses,\n value_losses_clipped).mean()\n else:\n value_loss = 0.5 * (return_batch - values).pow(2).mean()\n\n\n if self.delib_coef > 0:\n target_beta = torch.zeros_like(mean_beta_v).fill_(1)\n delib_loss = F.mse_loss(mean_beta_v, target_beta)*value_loss*self.value_loss_coef*self.delib_coef\n else:\n delib_loss = torch.zeros_like(value_loss)\n\n self.optimizer.zero_grad()\n (value_loss * self.value_loss_coef + action_loss -\n dist_entropy * self.entropy_coef).backward()\n nn.utils.clip_grad_norm_(self.actor_critic.parameters(),\n self.max_grad_norm)\n nn.utils.clip_grad_norm_(self.param_beta,self.max_grad_norm_beta)\n self.optimizer.step()\n\n\n value_loss_epoch += value_loss.item()\n action_loss_epoch += action_loss.item()\n dist_entropy_epoch += dist_entropy.item()\n\n num_updates = self.ppo_epoch * self.num_mini_batch\n\n value_loss_epoch /= num_updates\n action_loss_epoch /= num_updates\n dist_entropy_epoch /= num_updates\n\n return value_loss_epoch, action_loss_epoch, dist_entropy_epoch,delib_loss\n","sub_path":"a2c_ppo_acktr/algo/ppo.py","file_name":"ppo.py","file_ext":"py","file_size_in_byte":5928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"565047641","text":"import telebot\r\nimport extensions\r\nfrom config import TOKEN, keys\r\n\r\nbot = telebot.TeleBot(TOKEN)\r\n\r\n\r\n@bot.message_handler(commands=['start', 'help'])\r\ndef help(message: telebot.types.Message):\r\n text = \"Чтобы начать работу введите команду бота в следующем формате: \" \\\r\n \"\\n<имя валюты> <в какую валюту перевести> <количество переводимой валюты>\" \\\r\n \"\\nУвидеть список всех доступных валют: /values\"\r\n bot.reply_to(message, text)\r\n\r\n\r\n@bot.message_handler(commands=['values'])\r\ndef values(message: telebot.types.Message):\r\n text = \"Доступные валюты:\"\r\n for key in keys.keys():\r\n text = '\\n'.join((text, key, ))\r\n bot.reply_to(message, text)\r\n\r\n\r\n@bot.message_handler(content_types=['text', ])\r\ndef convert(message: telebot.types.Message):\r\n try:\r\n check_parametrs = message.text.split(' ')\r\n if len(check_parametrs) < 3:\r\n raise Exception('Введено параметров меньше необходимого')\r\n if len(check_parametrs) > 3:\r\n raise Exception('Введено параметров больше необходимого')\r\n except Exception as e:\r\n text = e\r\n else:\r\n quote_k, base_k, amount_k = message.text.strip().lower().split(' ')\r\n text = extensions.RequestAPI.get_price(quote_k, base_k, amount_k)\r\n bot.send_message(message.chat.id, text)\r\n\r\n\r\nbot.polling()\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"145923971","text":"import time\n\nstartTime = time.time()\ntermA = 1\ntermB = 2\nnextTerm = 0\nevenFibonacciSum = 2\n\nwhile True:\n nextTerm = termA + termB\n if nextTerm > 4000000:\n break\n if nextTerm % 2 == 0:\n evenFibonacciSum = evenFibonacciSum + nextTerm\n termA = termB\n termB = nextTerm\n\nprint(\"The sum of all even valued terms in the Fibonacci Sequence until 4 million is \" + str(evenFibonacciSum))\nprint(\"This solution took \" + str(time.time() - startTime) + \" seconds.\")","sub_path":"6 - Fibonacci Even Term Sum.py","file_name":"6 - Fibonacci Even Term Sum.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"505886577","text":"# My book is Dante's inferno (technically a poem)\nimport requests\nimport string\nimport random\nurl = 'https://www.gutenberg.org/files/1001/1001-h/1001-h.htm'\n\nfull_text = requests.get(url).text\n\nstart = 'Inferno: Canto I'\nend = 'End of the Project Gutenberg EBook'\n\n# Remove start and end material, newlines and punctuation\n\nfull_text = full_text[full_text.find(start):full_text.find(end)]\n\nfull_text = full_text.replace('\\n', ' ').replace('\\r', ' ')\nfor s in string.punctuation:\n full_text = full_text.replace(s, '')\n\nfull_text = full_text.split()\n\n\ndef generate_dict(txt):\n \"\"\"Create triplets dictionary in format (wd_one, wd_two):wd_three\"\"\"\n d = {}\n for idx in range(len(txt)-2):\n wd_one, wd_two, wd_three = txt[idx], txt[idx+1], txt[idx+2]\n d.setdefault((wd_one, wd_two), []).append(wd_three)\n return d\n\n\ndef generate_text(trigrams_dict, length):\n \"\"\"Generate text from trigrams dict with given number of words\"\"\"\n start_loc = random.randint(0, len(trigrams_dict))\n start_key = list(trigrams_dict.keys())[start_loc]\n results = [start_key[0], start_key[1]]\n for _ in range(length-2):\n next_word_choices = trigrams_dict[start_key]\n next_word = next_word_choices[random.randint(0,\n len(next_word_choices)-1)]\n start_key = (start_key[1], next_word)\n results.append(next_word)\n # Lines tend to be about 7 words long\n reshaped_results = []\n for i, j in enumerate(results):\n if i>0 and i % 7 == 0:\n reshaped_results.append('\\n')\n reshaped_results.append(j.title())\n else:\n reshaped_results.append(j.lower())\n return ' '.join(reshaped_results)\n\n\ndef print_chapter(length):\n \"\"\"Print chapter of inferno-like text with given length\"\"\"\n trigrams_dict = generate_dict(full_text)\n print(generate_text(trigrams_dict, length))\n\n\nif __name__ == '__main__':\n print_chapter(100)\n","sub_path":"students/kuhnbt/lesson4/kata_script.py","file_name":"kata_script.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"607871981","text":"import argparse\nimport sys\nfrom sklearn.preprocessing import LabelEncoder\nimport pandas as pd\nfrom utils import success_, get_deadline_year, preprocess\nfrom Models import LGBMModel\nfrom sklearn.metrics import accuracy_score\nimport numpy\n\nclass Application:\n \"\"\"\n Application\n ==========\n This class is runner class for the entire application. It accepts certain command line parameters, then invokes the\n methods of the class you will create.\n\n Example run command:\n python application.py -f file_path_to_data\n \"\"\"\n\n def __init__(self, file_path):\n \"\"\"\n :param file_path (str): the path of the csv to read in\n \"\"\"\n \n self.file_path = file_path\n if self.file_path is None:\n raise Exception(\"Must specify file path to the data\")\n\n def _read_data(self, file_path):\n \"\"\"\n Perform any removal of columns of data here\n\n :param file_path (str): the path of the csv to read in\n :return (obj:`(pd.DataFrame, list, pd.DataFrame, list`): a dataframe for the train data, train labels, \n a dataframe for the test data, test labels\n \"\"\"\n\n train_size = .75\n data_frame = pd.read_csv(file_path)\n \n #Feature Engineering an extra column\n data_frame['success_probability'] = success_(data_frame['usd_goal_real'].values, data_frame['usd_pledged_real'].values)\n data_frame['deadline_year'] = data_frame['deadline'].apply(lambda x: get_deadline_year(x))\n \n # Splitting the data into train set and test set\n split_size = int(data_frame.shape[0] * train_size)\n train_data_frame = data_frame[:split_size]\n test_data_frame = data_frame[split_size:]\n\n # Getting the labels\n train_labels = train_data_frame['state']\n test_labels = test_data_frame['state']\n\n return train_data_frame, train_labels, test_data_frame, test_labels\n\n def run(self):\n train_data_frame, train_labels, test_data_frame, test_labels = self._read_data(self.file_path)\n\n ######\n #label_encoder for encoding target labels\n label_encoder = LabelEncoder()\n label_encoder.fit(train_data_frame['state'].values)\n \n #Preprocess the data\n train_data, train_labels, test_data, test_labels = preprocess(train_data_frame,\n train_labels,\n test_data_frame,\n test_labels,\n label_encoder)\n \n # Here you put the model you will be using from the class you created\n model = LGBMModel()\n \n #training the model\n model.train(train_data, train_labels)\n \n #predicting the values for the test data\n predictions = model.predict(test_data)\n \n #Getting the original names of the labels\n prediction_names = label_encoder.inverse_transform(predictions)\n \n #Saving the error value in a text file\n model._save_predictions(test_data_frame['ID'].values, test_data_frame['name'].values, prediction_names)\n \n #Printing the error value\n print('\\nAccuracy = {}'.format(accuracy_score(test_labels, predictions)))\n\n\n\"\"\"\nEntrance point for execution\n\"\"\"\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='model trainer for starter project')\n parser.add_argument(\"-f\", \"--file_path\", help = \"where to read in the data\", default = None)\n args = parser.parse_args(sys.argv[1:])\n\n app = Application(\n file_path = args.file_path\n )\n app.run()\n","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":3794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"133365599","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author : YuLei Lan\n# @Software: PyCharm\n\nimport base64\nfrom .state import *\nfrom .lock import lock\nfrom app.task import models\n\n\nclass Task:\n def __init__(self, task_id='', script='', targets=[], timeout=0, parallel=1, fail_rate=0, fail_count=0):\n self.id = task_id\n self.script = script\n self.timeout = timeout\n self.parallel = parallel\n self.fail_rate = fail_rate\n self.fail_count = fail_count\n self.targets = {x: {'state': WAITING, 'output': ''} for x in targets}\n self._state = WAITING\n self.total = len(targets)\n self.tasks = {}\n\n def put_task(self, task, targets):\n if task['task_id'] in self.tasks:\n raise Exception('task {} exist'.format(task['task_id']))\n t = Task(**task, targets=targets)\n self.tasks[t.id] = t\n\n def get_tasks(self, states=[WAITING, RUNNING]):\n if states:\n task_all_list = models.TaskListModels.objects.filter(state__in=states)\n for task in task_all_list:\n targets = [agent_tuple[0] for agent_tuple in models.TaskToAgentModels.objects.filter(task_id=task.task_id).values_list(\"agent_id\")]\n task_dict = {\n \"task\": {\n \"task_id\": task.task_id,\n \"script\": task.content\n },\n \"targets\": targets\n }\n task_obj = Task(**task_dict[\"task\"], targets=targets)\n self.tasks[task_obj.id] = task_obj\n return self.tasks\n else:\n print(self.tasks.keys())\n\n def get_task(self, task_id):\n return self.tasks.get(task_id)\n\n def set_target_state(self, target_id, state, output=''):\n with lock:\n self.targets[target_id] = {\n 'state': state,\n 'output': output\n }\n\n failed = len([x for x in self.targets.values() if x['state'] == FAILED])\n if failed > self.fail_count >= 0:\n self._state = FAILED\n\n elif failed / self.total > self.fail_rate >= 0:\n self._state = FAILED\n\n elif len([x for x in self.targets.values() if x['state'] in {'WAITING', 'RUNNING'}]) == 0:\n self._state = SUCCEED\n\n models.TaskToAgentModels.objects.filter(agent_id=target_id, task_id=self.id).update(\n state=self._state,\n output=output\n )\n models.TaskListModels.objects.filter(task_id=self.id).update(\n state=self._state\n )\n\n return\n\n def state(self, state=None):\n with lock:\n if state is None:\n return self._state\n self._state = state\n return self._state\n\n def running(self):\n with lock:\n return len([x for x in self.targets.values() if x['state'] == RUNNING])\n","sub_path":"dispatch/service/master/core/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":2968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"432498683","text":"\"\"\"\nViews for the Environment objects.\nThis currently includes Wind and Tide objects.\n\"\"\"\nimport ujson\nimport logging\nimport zlib\nimport numpy as np\nfrom threading import current_thread\n\nfrom pyramid.settings import asbool\nfrom pyramid.response import Response\nfrom pyramid.view import view_config\nfrom pyramid.httpexceptions import HTTPNotFound, HTTPNotImplemented\n\nfrom gnome.environment.environment_objects import GridCurrent, GridWind\n\nfrom webgnome_api.common.views import (get_object,\n create_object,\n update_object,\n cors_policy,\n cors_response,\n cors_exception,\n process_upload,\n can_persist,\n switch_to_existing_session,\n activate_uploaded)\n\nfrom cornice import Service\n\nfrom ..common.session_management import (get_session_object,\n acquire_session_lock)\nlog = logging.getLogger(__name__)\n\nenv = Service(name='environment', path='/environment*obj_id',\n description=\"Environment API\",\n cors_policy=cors_policy,\n # accept='application/json+octet-stream',\n content_type=['application/json', 'binary'])\nimplemented_types = ('gnome.environment.Tide',\n 'gnome.environment.Wind',\n 'gnome.environment.Water',\n 'gnome.environment.Waves',\n 'gnome.environment.environment_objects.GridCurrent',\n 'gnome.environment.environment_objects.GridWind',\n )\n\n@env.get()\ndef get_environment(request):\n '''Returns an Gnome Environment object in JSON.'''\n content_requested = request.matchdict.get('obj_id')\n resp = Response(\n content_type='arraybuffer',\n content_encoding='deflate'\n )\n route = content_requested[1] if len(content_requested) > 1 else None\n if (len(content_requested) > 1):\n if route == 'grid':\n resp.body = get_grid(request)\n return cors_response(request, resp)\n if route == 'vectors':\n resp.body, dshape = get_vector_data(request)\n resp.headers.add('Access-Control-Expose-Headers', 'shape')\n resp.headers.add('shape', str(dshape))\n return cors_response(request, resp)\n if route == 'nodes':\n resp.body = get_nodes(request)\n return cors_response(request, resp)\n if route == 'centers':\n resp.body = get_centers(request)\n return cors_response(request, resp)\n if route == 'metadata':\n return get_metadata(request)\n else:\n return get_object(request, implemented_types)\n\n\n@env.post()\ndef create_environment(request):\n '''Creates an Environment object.'''\n return create_object(request, implemented_types)\n\n\n@env.put()\ndef update_environment(request):\n '''Updates an Environment object.'''\n return update_object(request, implemented_types)\n\n\n@view_config(route_name='environment_upload', request_method='OPTIONS')\ndef environment_upload_options(request):\n return cors_response(request, request.response)\n\n\n@view_config(route_name='environment_upload', request_method='POST')\ndef upload_environment(request):\n switch_to_existing_session(request)\n log_prefix = 'req({0}): upload_environment():'.format(id(request))\n log.info('>>{}'.format(log_prefix))\n\n\n file_list = request.POST['file_list']\n file_list = ujson.loads(file_list)\n name = request.POST['name']\n file_name = file_list[0]\n\n log.info(' {} file_name: {}, name: {}'\n .format(log_prefix, file_name, name))\n\n env_type = request.POST.get('obj_type', [])\n request.body = ujson.dumps({'obj_type': env_type,\n 'filename': file_name,\n 'name': name\n }).encode('utf-8')\n\n env_obj = create_environment(request)\n resp = Response(ujson.dumps(env_obj))\n\n log.info('<<{}'.format(log_prefix))\n return cors_response(request, resp)\n\n@view_config(route_name='environment_activate', request_method='OPTIONS')\ndef activate_environment_options(request):\n return cors_response(request, request.response)\n\n\n@view_config(route_name='environment_activate', request_method='POST')\n@can_persist\ndef activate_environment(request):\n '''\n Activate an environment file that has already been persistently\n uploaded.\n '''\n log_prefix = 'req({0}): activate_environment():'.format(id(request))\n log.info('>>{}'.format(log_prefix))\n\n file_name, name = activate_uploaded(request)\n resp = Response(ujson.dumps({'filename': file_name, 'name': name}))\n\n log.info('<<{}'.format(log_prefix))\n return cors_response(request, resp)\n\n\ndef get_grid(request):\n '''\n Outputs the object's grid cells in binary format\n '''\n log_prefix = 'req({0}): get_grid():'.format(id(request))\n log.info('>>' + log_prefix)\n\n session_lock = acquire_session_lock(request)\n log.info(' {} session lock acquired (sess:{}, thr_id: {})'\n .format(log_prefix, id(session_lock), current_thread().ident))\n try:\n obj_id = request.matchdict.get('obj_id')[0]\n obj = get_session_object(obj_id, request)\n\n if obj is not None and isinstance(obj, (GridCurrent, GridWind)):\n cells = obj.grid.get_cells()\n\n return zlib.compress(cells.astype(np.float32).tobytes())\n else:\n exc = cors_exception(request, HTTPNotFound)\n raise exc\n finally:\n session_lock.release()\n log.info(' {} session lock released (sess:{}, thr_id: {})'\n .format(log_prefix, id(session_lock), current_thread().ident))\n\n log.info('<<' + log_prefix)\n\n\ndef get_vector_data(request):\n log_prefix = 'req({0}): get_grid():'.format(id(request))\n log.info('>>' + log_prefix)\n\n session_lock = acquire_session_lock(request)\n log.info(' {} session lock acquired (sess:{}, thr_id: {})'\n .format(log_prefix, id(session_lock), current_thread().ident))\n try:\n obj_id = request.matchdict.get('obj_id')[0]\n obj = get_session_object(obj_id, request)\n\n if obj is not None and isinstance(obj, (GridCurrent, GridWind)):\n vec_data = obj.get_data_vectors()\n\n return zlib.compress(vec_data.tobytes()), vec_data.shape\n else:\n exc = cors_exception(request, HTTPNotFound)\n raise exc\n finally:\n session_lock.release()\n log.info(' {} session lock released (sess:{}, thr_id: {})'\n .format(log_prefix, id(session_lock), current_thread().ident))\n\n log.info('<<' + log_prefix)\n\n\ndef get_metadata(request):\n log_prefix = 'req({0}): get_current_info():'.format(id(request))\n log.info('>>' + log_prefix)\n\n session_lock = acquire_session_lock(request)\n log.info(' {} session lock acquired (sess:{}, thr_id: {})'\n .format(log_prefix, id(session_lock), current_thread().ident))\n try:\n obj_id = request.matchdict.get('obj_id')[0]\n obj = get_session_object(obj_id, request)\n if obj is not None:\n return obj.get_metadata()\n else:\n exc = cors_exception(request, HTTPNotFound)\n raise exc\n finally:\n session_lock.release()\n log.info(' {} session lock released (sess:{}, thr_id: {})'\n .format(log_prefix, id(session_lock), current_thread().ident))\n\n log.info('<<' + log_prefix)\n\n\ndef get_grid_signature(obj):\n '''\n Here we are trying to get an n-dimensional signature of our\n grid data.\n There may be a better way to do this, but for now we will get the\n euclidian distances between all sequential points and sum them.\n '''\n points = obj.get_points()\n\n dtype = points[0].dtype.descr\n raw_points = points.view(dtype='self.eps).sum()+(np.abs(B)>self.eps).sum() \n for W, B in self.parameters])\n \n def __getitem__(self, idx):\n return self.parameters[idx]\n\n def __setitem__(self, idx, value):\n self.parameters[idx] = value\n\n def __repr__(self):\n return str(self.parameters)\n \n def __str__(self):\n return str(self.parameters)\n\n def attributes_print(self):\n print('Depth: {}, Width: {}, Max: {}, #Parameters: {}, Connectivity: {}'.format(\n self.depth,self.width,self.pa_max, self.num_parameters,self.connectivity))\n\n# Parametrizations of simple functions\nSimpleParametrizations = {'abs': [(np.array([[1.,-1]]), np.array([0.,0.])), \n (np.array([[1.],[1.]]), np.array([0.]))],\n 'triangle': [(np.array([[1.,1.,1.]]), \n np.array([0.,-0.5,-1.])), \n (np.array([[2.],[-4.],[2.]]), \n np.array([0.]))]}\n\n\n# affine linear layer\n# e.g. Affine(W,B)(x)=xW+B\nclass Affine(layers.Layer):\n\n def __init__(self, W, B):\n super(Affine, self).__init__()\n self.w = tf.Variable(initial_value=tf.constant(W,dtype='float32'),\n trainable=True)\n self.b = tf.Variable(initial_value=tf.constant(B,dtype='float32'),\n trainable=True)\n\n def call(self, inputs):\n return tf.matmul(inputs, self.w) + self.b\n\n# realization map\nclass R(tf.keras.Model):\n\n def __init__(self, name_or_P, act=nn.relu):\n if isinstance(name_or_P, str):\n name_or_P=P(name_or_P)\n super(R, self).__init__(name=name_or_P.name)\n self.parametrization = name_or_P\n self.act = act\n self.affine_maps = [Affine(W, B) \n for W, B in self.parametrization.parameters]\n\n def call(self, input_tensor, training=False):\n\n x = input_tensor\n for affine in self.affine_maps[:-1]:\n x = affine(x)\n x = self.act(x)\n return self.affine_maps[-1](x)\n\n# derivative map (for now: only supports Pa with Pa.out_dim = 1) \n# dR(Pa)(x)/dx via automatic differentiation\ndef D(Pa, act=nn.relu):\n def der(x):\n with tf.GradientTape() as t:\n x = tf.convert_to_tensor(x)\n t.watch(x)\n y = R(Pa, act = act)(x)\n return t.gradient(y, x)\n return der\n\n# blockdiagonal matrix\ndef blockdiag(matrix_list):\n if len(matrix_list)==2:\n m1 = matrix_list[0]\n m2 = matrix_list[1]\n return np.block([[m1,np.zeros((m1.shape[0],m2.shape[1]))],\n [np.zeros((m2.shape[0],m1.shape[1])),m2]])\n else:\n return blockdiag([blockdiag(matrix_list[:-1]),matrix_list[-1]])\n\n# linear network\ndef Lin(W):\n zeros = np.zeros((W.shape[1],))\n return P([(W,zeros)])\n\n# network concatenation\n# e.g. Pa_list = [Pa1, Pa2, Pa3]\n# R(Conc(Pa_list))(x)=R(Pa3)(R(Pa2)(R(Pa1)(x)))\n# the order is reversed for easier usage\ndef Conc(Pa_list):\n if len(Pa_list)==1: #catch exceptional cases in other functions\n return Pa_list[0]\n if len(Pa_list)==2:\n Pa1=Pa_list[0]\n Pa2=Pa_list[1]\n W=np.matmul(Pa1.weights[-1],Pa2.weights[0])\n B=np.matmul(Pa1.biases[-1],Pa2.weights[0])+Pa2.biases[0]\n return P(Pa1.parameters[:-1]+[(W,B)]+Pa2.parameters[1:])\n else:\n return Conc([Conc(Pa_list[:-1]),Pa_list[-1]])\n\n# positive elongation (with factor) helper function\ndef _pos_elong(Pa, L, factor = 1):\n Pa_pos = Identity(Pa.out_dim, 1, scale = factor)\n return P(Pa.parameters+[Pa_pos.parameters[0] for _ in range(L-Pa.depth)])\n\n# (affine) linear combination\n# e.g. Pa_list = [P1,P2], coeff_list = [A,B]\n# then: R(Affine(Pa_list, coeff_list))(x)=A*R(P1)(x)+B*R(P2)(x))\n# see parallelization for explanation of ind_list\ndef Affine_Comb(coeff_list, Pa_list = None, ind_list = None, affine = None):\n block = np.block([coeff_list]).transpose()\n if affine == None:\n Pa_comb = Lin(block)\n else:\n Pa_comb = P([(block,affine)])\n if Pa_list == None:\n return Pa_comb\n else: \n return Conc([Par(Pa_list, ind_list=ind_list),Pa_comb])\n\n# identity network with possible efficient scaling\n# e.g. dim=2, L=4, scale = np.array([16,81]) \n# then R(Identity(dim, L, scale))(x)=(16x_1,81x_2)\n# efficient: coefficients with magnitude |scale_i|**(1/L)\ndef Identity(dim, L, scale = 1):\n id = np.eye(dim)\n if L==1:\n return Lin(scale*id)\n elif L>1:\n factor = np.abs(scale)**(1/L)\n Pa_list = [_pos_elong(Lin(m), L, factor=factor) \n for m in [factor*id, -factor*id]]\n ind = np.arange(dim)\n return Affine_Comb([np.sign(scale)*id, -np.sign(scale)*id], Pa_list=Pa_list, ind_list=[ind, ind])\n else:\n raise ValueError('L must be a natural number greater than 0.')\n\n# update SimpleParametrizations\nSimpleParametrizations.update({'identity': Identity(1,1).parameters})\n\n# parallelization helper function for same depth\ndef _par_same(Pa_list):\n if len(Pa_list)==2:\n return P([(blockdiag([W1,W2]),np.block([B1,B2])) \n for (W1, B1), (W2, B2) \n in zip(Pa_list[0].parameters,Pa_list[1].parameters)])\n else:\n return _par_same([_par_same(Pa_list[:-1]),Pa_list[-1]])\n\n# parallelization with indexed input\n# e.g. Pa_list = [P1,P2], ind_list = [(2,0),(1,3)]\n# then: R(Par(Pa_list, ind_list))(x_0,x_1,x_2,x_3)=(R(P1)(x_2,x_0),R(P2)(x_1,x_3))\ndef Par(Pa_list, ind_list = None, in_dim = None):\n L = max([Pa.depth for Pa in Pa_list])\n Pa = _par_same([Elongation(Pa, L) for Pa in Pa_list])\n if ind_list == None:\n return Pa\n else:\n if in_dim == None:\n in_dim = max([max(ind) for ind in ind_list])+1\n perms = [np.zeros((in_dim, Pa.in_dim)) for Pa in Pa_list]\n for perm, ind in zip(perms, ind_list):\n perm[ind,np.arange(len(ind))] = 1\n Pa_perms = Lin(np.block([perms]))\n return Conc([Pa_perms,Pa])\n\n# sparse network concatenation\ndef Sparse_Conc(Pa_list):\n if len(Pa_list)==2:\n Id = Identity(Pa_list[0].out_dim, 2)\n return Conc([Pa_list[0],Id,Pa_list[1]])\n else:\n return Sparse_Conc([Sparse_Conc(Pa_list[:-1]),Pa_list[-1]])\n\n# network elongation\ndef Elongation(Pa, L): \n if Pa.depth == L:\n return Pa\n else:\n return Conc([Pa,Identity(Pa.out_dim,L-Pa.depth+1)])\n\n# squaring helper function (interpolates the squaring function up to precision 4**(-k))\ndef _square(k):\n if isinstance(k,int):\n if k<=1 :\n return P('identity')\n else:\n Pa_triang = P('triangle')\n Pa_inp = _pos_elong(P('identity'), 2)\n Pa_sub_list = [_pos_elong(Affine_Comb([-2.**(-2*m),1]), 2) for m in range(1,k-1)]\n Pa_first = Par([Pa_triang, Pa_inp], ind_list=[[0],[0]])\n Pa_middle_list = [Par([Pa_triang, Pa_sub], ind_list=[[0],[0,1]]) \n for Pa_sub in Pa_sub_list]\n return Conc([Pa_first]+Pa_middle_list+[Affine_Comb([-2.**(-2*(k-1)),1])])\n else:\n raise ValueError('k must be a natural number.')\n\n# approximation of squaring function on [-B,B] \n# up to error eps in Sobolev W^{1,\\infty} norm\ndef Square(eps, B = 1.):\n k = int(np.ceil(2*np.log2(B/eps)+1))\n L = int(np.ceil(np.log2(B))) if B>1 else 1\n return Conc([Lin(np.array([[1/B]])),P('abs'),\n _square(k),Identity(1, L, scale=B**2)])\n \n# approximation of multiplication function on [-B,B]\n# up to error eps in Sobolev W^{1,\\infty} norm\ndef Mult(eps, B = 1.):\n Pa_list = [Conc([Affine_Comb([1., a]), Square(2*eps, B = 2*B)]) \n for a in [1.,-1.]]\n return Affine_Comb([0.25,-0.25], Pa_list=Pa_list, ind_list=[[0,1],[0,1]])\n\n# approximation of monomials function (x,x^2,...,x^(2^2)) on [-B,B]\n# up to error eps in Sobolev W^{1,\\infty} norm\ndef _Monomial(K, eps, B = 1.):\n Pa_list_all=[]\n Pa_id = P('identity')\n eta = eps/(4.**(K**2)*B**(2**(K+1)))\n eta_list = [4**(k**2)*eta for k in range(1,K+1)] \n E = 2*B**(2**K)\n for k in range(K):\n Pa_list=[]\n ind_list=[]\n Pa_square = Square(eta_list[k], B = E)\n Pa_mult = Mult(eta_list[k], B = E)\n for i in range(2**(k+1)):\n if i<=2**k-1:\n Pa_list.append(Pa_id)\n ind_list.append([i])\n elif i%2:\n Pa_list.append(Pa_square)\n ind_list.append([(i-1)//2])\n else:\n Pa_list.append(Pa_mult)\n ind_list.append([(i-2)//2,i//2])\n Pa_list_all.append(Par(Pa_list, ind_list=ind_list))\n return Conc(Pa_list_all)\n\n# Monomial extension: arbitrary degree deg, optional with constant 1\ndef Monomial(deg, eps, B=1.0, const=True):\n K = int(np.ceil(np.log2(deg)))\n if const:\n e = np.zeros((deg+1,))\n e[0] = 1\n Pa_zero = P([(np.block([np.zeros((2**K,1)),np.eye(2**K,deg)]),e)])\n else:\n Pa_zero = Lin(np.eye(2**K,deg))\n return Conc([_Monomial(K, eps, B), Pa_zero])\n\n# approximation of polynomial p[0]*x^(N-1)+ ... +p[N-1] on [-B,B]\n# up to error eps in Sobolev W^{1,\\infty} norm\ndef Poly(p, eps, B = 1.):\n p_len = len(p)\n coeff_sum = np.sum(np.abs(p))\n eta = eps/coeff_sum\n L = int(np.ceil(np.log2(coeff_sum)))\n Pa_scale = Identity(p_len, L, scale=p[::-1])\n return Conc([Monomial(p_len-1, eta, B), Pa_scale, \n Affine_Comb(np.ones((1,p_len)))])\n","sub_path":"helper_functions/NN_constructions.py","file_name":"NN_constructions.py","file_ext":"py","file_size_in_byte":10295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"595844696","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport json\nimport os.path\n\nPORT_NUMBER = None\n\nroot_dir = os.path.dirname(__file__) or '.'\n\nwith open('{}/configuration.json'.format(root_dir)) as data_file:\n data = json.load(data_file)\n PORT_NUMBER = data['port_number']\n","sub_path":"data_server/read_configuration.py","file_name":"read_configuration.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"168882819","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\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.macosx-10.15-x86_64/egg/foxylib/tools/google/youtube/tests/test_youtube_tool.py\n# Compiled at: 2020-01-08 12:53:55\n# Size of source mod 2**32: 1534 bytes\nimport logging, re\nfrom functools import lru_cache\nfrom unittest import TestCase\nfrom foxylib.tools.google.youtube.youtube_tool import YoutubeTool\nfrom foxylib.tools.log.foxylib_logger import FoxylibLogger\nfrom foxylib.tools.regex.regex_tool import MatchTool\n\nclass TestYoutubeTool(TestCase):\n\n @classmethod\n def setUpClass(cls):\n FoxylibLogger.attach_stderr2loggers(logging.DEBUG)\n\n def test_01(self):\n url = 'https://www.youtube.com/watch?v=4VYAaLh3XZg&t=33s'\n hyp = YoutubeTool.url2video_id(url)\n ref = '4VYAaLh3XZg'\n self.assertEqual(hyp, ref)\n\n def test_02(self):\n video_id = '4VYAaLh3XZg'\n hyp = YoutubeTool.video_id2url(video_id)\n ref = 'https://www.youtube.com/watch?v=4VYAaLh3XZg'\n self.assertEqual(hyp, ref)\n\n def test_03(self):\n url = 'https://www.youtube.com/watch?v=4VYAaLh3XZg'\n hyp = YoutubeTool.url2is_accessible(url)\n self.assertTrue(hyp)\n\n def test_04(self):\n p = YoutubeTool.pattern_url()\n url1 = 'http://youtu.be/5Y6HSHwhVlY'\n self.assertTrue(p.match(url1))\n self.assertEqual(YoutubeTool.url2video_id(url1), '5Y6HSHwhVlY')\n url2 = 'http://www.youtube.com/embed/5Y6HSHwhVlY?rel=0'\n self.assertTrue(p.match(url2))\n self.assertEqual(YoutubeTool.url2video_id(url2), '5Y6HSHwhVlY')\n url3 = 'http://www.youtube.com/watch?v=ZFqlHhCNBOI'\n self.assertTrue(p.match(url3))\n self.assertEqual(YoutubeTool.url2video_id(url3), 'ZFqlHhCNBOI')","sub_path":"pycfiles/foxylib-0.3.96-py3.7/test_youtube_tool.cpython-37.py","file_name":"test_youtube_tool.cpython-37.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"376657024","text":"\"\"\"\r\nTHIS CODE IS AN UPDATED VERSION FROM DR.REDA M. HUSSIEN - FACULTY OF COMPUTERS AND INFORMATION, KAFRELSHEIKH UNIVERSITY -\r\nFOR COMPUTER VISION COURSE.\r\n\"\"\"\r\n\r\nimport math\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nfrom PIL import Image\r\n\r\n\r\nNUM_OF_PIXEL_VALUES = 256\r\n\r\n\r\ndef histogram(img):\r\n row, col = img.shape\r\n hist = np.zeros(NUM_OF_PIXEL_VALUES)\r\n for i in range(0, row):\r\n for j in range(0, col):\r\n try:\r\n hist[int(img[i, j])] += 1\r\n except:\r\n print(img[i, j])\r\n return hist\r\n\r\n\r\ndef linear_histogram_equalization(img, hmin, hmax):\r\n # values_dict = {}\r\n row, col = img.shape\r\n y = np.zeros((row, col))\r\n m = 255.0 / (hmax - hmin)\r\n for i in range(0, row):\r\n for j in range(0, col):\r\n if hmin <= img[i, j] <= hmax:\r\n y[i, j] = math.floor(m * (img[i, j] - hmin))\r\n elif img[i, j] > hmax:\r\n y[i, j] = NUM_OF_PIXEL_VALUES - 1\r\n else:\r\n y[i, j] = 0\r\n y = y.astype(int)\r\n # Nicely print the dictionary of values\r\n # for key, item in values_dict.items():\r\n # print(str(key) + ' ' + str(int(item)))\r\n return y\r\n\r\n\r\ndef cumulative_histogram_equalization(img, hist=None):\r\n row, col = img.shape\r\n num_of_pixels = row * col\r\n if hist is None:\r\n hist = histogram(img)\r\n probability_of_pixels = [value / num_of_pixels for value in hist]\r\n cumulative_distribution = np.zeros(NUM_OF_PIXEL_VALUES)\r\n cumulative_distribution[0] = probability_of_pixels[0]\r\n for i in range(1, NUM_OF_PIXEL_VALUES):\r\n cumulative_distribution[i] = cumulative_distribution[i - 1] + probability_of_pixels[i]\r\n # Create new image\r\n new_image = np.zeros((row * col)).reshape((col, row))\r\n for i in range(0, row):\r\n for j in range(0, col):\r\n new_image[i, j] = math.floor((NUM_OF_PIXEL_VALUES - 1) * cumulative_distribution[img[i, j]])\r\n return new_image\r\n\r\n\r\n\r\n\r\n","sub_path":"computer_vision.py","file_name":"computer_vision.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"122144618","text":"'''\n请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。\n\n \n\n示例 1:\n\n输入: \"abcabcbb\"\n输出: 3 \n解释: 因为无重复字符的最长子串是 \"abc\",所以其长度为 3。\n示例 2:\n\n输入: \"bbbbb\"\n输出: 1\n解释: 因为无重复字符的最长子串是 \"b\",所以其长度为 1。\n示例 3:\n\n输入: \"pwwkew\"\n输出: 3\n解释: 因为无重复字符的最长子串是 \"wke\",所以其长度为 3。\n 请注意,你的答案必须是 子串 的长度,\"pwke\" 是一个子序列,不是子串。\n \n\n提示:\n\ns.length <= 40000\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/zui-chang-bu-han-zhong-fu-zi-fu-de-zi-zi-fu-chuan-lcof\n'''\n\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n #brute force O(n^2)\n # n = len(s)\n # res = 0\n # for i in range(n):\n # hash_table = {}\n # j = i\n # while j < n and s[j] not in hash_table:\n # hash_table[s[j]] = 1\n # j += 1\n # res = max(res, j-i)\n # return res\n\n #sliding-window + hash_table\n hash_table = {} #存储遍历过的元素以及它最后一次出现时的索引\n #siding window start-point: i end-point:j\n i, j = 0, 0 #每次都需要去确定i的位置, 而j从零开始一直到结束遍历\n res = 0\n for j in range(len(s)):\n #当出现重复元素时,更新i\n if s[j] in hash_table:\n #这里为什么要max,是怕i倒退。因为如果只让i = hash_table[s[j]] + 1 有可能会忽略\n #之前已经更新过的i,从而忽略之前遍历过出现的重复元素,只专注与当前元素,不可取\n i = max(i, hash_table[s[j]] + 1)\n #存储或更新当前元素索引\n hash_table[s[j]] = j\n #更新res j-i+1: 当前有效window的长度\n res = max(j- i + 1, res)\n return res","sub_path":"滑动窗口/最长不含重复字符的子字符串.py","file_name":"最长不含重复字符的子字符串.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"489283046","text":"# Copyright (c) 2015 by the parties listed in the AUTHORS file.\n# All rights reserved. Use of this source code is governed by \n# a BSD-style license that can be found in the LICENSE file.\n\n\nimport os\nimport unittest\nimport ctypes as ct\nfrom ctypes.util import find_library\n\nif 'TOAST_NO_MPI' in os.environ.keys():\n from .. import fakempi as MPI\nelse:\n from mpi4py import MPI\n\nimport healpy as hp\nimport numpy as np\nimport numpy.ctypeslib as npc\n\nfrom . import qarray as qa\nfrom ..dist import Comm, Data\nfrom ..operator import Operator\nfrom ..tod import TOD\nfrom ..tod import Interval\nfrom ..tod import quat2angle\n\n# Define portably the MPI communicator datatype\n\ntry:\n if MPI._sizeof(MPI.Comm) == ct.sizeof(ct.c_int):\n MPI_Comm = ct.c_int\n else:\n MPI_Comm = ct.c_void_p\nexcept Exception as e:\n raise Exception(\n 'Failed to set the portable MPI communicator datatype. MPI4py is '\n 'probably too old. You need to have at least version 2.0. ({})'\n ''.format(e))\n\nlibconviqt = None\nif 'TOAST_NO_MPI' not in os.environ.keys():\n try:\n libconviqt = ct.CDLL('libconviqt.so')\n except:\n path = find_library('conviqt')\n if path is not None:\n libconviqt = ct.CDLL(path)\n\nif libconviqt is not None:\n # Beam functions\n\n libconviqt.conviqt_beam_new.restype = ct.c_void_p\n libconviqt.conviqt_beam_new.argtypes = []\n\n libconviqt.conviqt_beam_del.restype = ct.c_int\n libconviqt.conviqt_beam_del.argtypes = [ct.c_void_p]\n\n libconviqt.conviqt_beam_read.restype = ct.c_int\n libconviqt.conviqt_beam_read.argtypes = [\n ct.c_void_p,\n ct.c_long,\n ct.c_long,\n ct.c_byte,\n ct.c_char_p,\n MPI_Comm\n ]\n\n libconviqt.conviqt_beam_lmax.restype = ct.c_int\n libconviqt.conviqt_beam_lmax.argtypes = [ct.c_void_p]\n\n libconviqt.conviqt_beam_mmax.restype = ct.c_int\n libconviqt.conviqt_beam_mmax.argtypes = [ct.c_void_p]\n\n # Sky functions\n\n libconviqt.conviqt_sky_new.restype = ct.c_void_p\n libconviqt.conviqt_sky_new.argtypes = []\n\n libconviqt.conviqt_sky_del.restype = ct.c_int\n libconviqt.conviqt_sky_del.argtypes = [ct.c_void_p]\n\n libconviqt.conviqt_sky_read.restype = ct.c_int\n libconviqt.conviqt_sky_read.argtypes = [\n ct.c_void_p,\n ct.c_long,\n ct.c_byte,\n ct.c_char_p,\n ct.c_double,\n MPI_Comm\n ]\n\n libconviqt.conviqt_sky_lmax.restype = ct.c_int\n libconviqt.conviqt_sky_lmax.argtypes = [ct.c_void_p]\n\n libconviqt.conviqt_sky_remove_monopole.restype = ct.c_int\n libconviqt.conviqt_sky_remove_monopole.argtypes = [ct.c_void_p]\n\n libconviqt.conviqt_sky_remove_dipole.restype = ct.c_int\n libconviqt.conviqt_sky_remove_dipole.argtypes = [ct.c_void_p]\n\n # Detector functions\n\n libconviqt.conviqt_detector_new.restype = ct.c_void_p\n libconviqt.conviqt_detector_new.argtypes = []\n\n libconviqt.conviqt_detector_new_with_id.restype = ct.c_void_p\n libconviqt.conviqt_detector_new_with_id.argtypes = [ct.c_char_p]\n\n libconviqt.conviqt_detector_del.restype = ct.c_int\n libconviqt.conviqt_detector_del.argtypes = [ct.c_void_p]\n\n libconviqt.conviqt_detector_set_epsilon.restype = ct.c_int\n libconviqt.conviqt_detector_set_epsilon.argtypes = [\n ct.c_void_p,\n ct.c_double\n ]\n\n libconviqt.conviqt_detector_get_epsilon.restype = ct.c_int\n libconviqt.conviqt_detector_get_epsilon.argtypes = [\n ct.c_void_p,\n ct.POINTER(ct.c_double)\n ]\n\n libconviqt.conviqt_detector_get_id.restype = ct.c_int\n libconviqt.conviqt_detector_get_id.argtypes = [\n ct.c_void_p,\n ct.c_char_p\n ]\n\n # Pointing functions\n\n libconviqt.conviqt_pointing_new.restype = ct.c_void_p\n libconviqt.conviqt_pointing_new.argtypes = []\n\n libconviqt.conviqt_pointing_del.restype = ct.c_int\n libconviqt.conviqt_pointing_del.argtypes = [ct.c_void_p]\n\n libconviqt.conviqt_pointing_alloc.restype = ct.c_int\n libconviqt.conviqt_pointing_alloc.argtypes = [\n ct.c_void_p,\n ct.c_long\n ]\n\n libconviqt.conviqt_pointing_data.restype = ct.POINTER(ct.c_double)\n libconviqt.conviqt_pointing_data.argtypes = [ct.c_void_p]\n\n # Convolver functions\n\n libconviqt.conviqt_convolver_new.restype = ct.c_void_p\n libconviqt.conviqt_convolver_new.argtypes = [\n ct.c_void_p,\n ct.c_void_p,\n ct.c_void_p,\n ct.c_byte,\n ct.c_long,\n ct.c_long,\n ct.c_long,\n MPI_Comm\n ]\n\n libconviqt.conviqt_convolver_convolve.restype = ct.c_int\n libconviqt.conviqt_convolver_convolve.argtypes = [\n ct.c_void_p,\n ct.c_void_p,\n ct.c_byte\n ]\n\n libconviqt.conviqt_convolver_del.restype = ct.c_int\n libconviqt.conviqt_convolver_del.argtypes = [ct.c_void_p]\n\n\nclass OpSimConviqt(Operator):\n \"\"\"\n Operator which uses libconviqt to generate beam-convolved timestreams.\n\n This passes through each observation and loops over each detector.\n For each detector, it produces the beam-convolved timestream.\n\n Args:\n lmax (int): Maximum ell (and m). Actual resolution in the Healpix FITS\n file may differ.\n beammmax (int): beam maximum m. Actual resolution in the Healpix FITS file\n may differ.\n detectordata (list): list of (detector_name, detector_sky_file,\n detector_beam_file, epsilon, psipol[radian]) tuples\n pol (bool) : boolean to determine if polarized simulation is needed\n fwhm (float) : width of a symmetric gaussian beam [in arcmin] already\n present in the skyfile (will be deconvolved away).\n order (int) : conviqt order parameter (expert mode)\n calibrate (bool) : Calibrate intensity to 1.0, rather than (1+epsilon)/2\n dxx (bool) : The beam frame is either Dxx or Pxx. Pxx includes the\n rotation to polarization sensitive basis, Dxx does not. When\n Dxx=True, detector orientation from attitude quaternions is\n corrected for the polarization angle.\n out (str): the name of the cache object (_) to\n use for output of the detector timestream.\n \"\"\"\n\n def __init__(\n self, lmax, beammmax, detectordata, pol=True, fwhm=4.0, order=13,\n calibrate=True, dxx=True, out='conviqt', quat_name=None,\n flag_name=None, flag_mask=255, common_flag_name=None,\n common_flag_mask=255, apply_flags=False,\n remove_monopole=False, remove_dipole=False):\n\n # We call the parent class constructor, which currently does nothing\n super().__init__()\n\n self._lmax = lmax\n self._beammmax = beammmax\n self._detectordata = {}\n for entry in detectordata:\n self._detectordata[entry[0]] = entry[1:]\n self._pol = pol\n self._fwhm = fwhm\n self._order = order\n self._calibrate = calibrate\n self._dxx = dxx\n self._quat_name = quat_name\n self._flag_name = flag_name\n self._flag_mask = flag_mask\n self._common_flag_name = common_flag_name\n self._common_flag_mask = common_flag_mask\n self._apply_flags = apply_flags\n self._remove_monopole = remove_monopole\n self._remove_dipole = remove_dipole\n\n self._out = out\n\n @property\n def available(self):\n \"\"\"\n (bool): True if libconviqt is found in the library search path.\n \"\"\"\n return (libconviqt is not None)\n\n def exec(self, data):\n \"\"\"\n Loop over all observations and perform the convolution.\n\n This is done one detector at a time. For each detector, all data\n products are read from disk.\n\n Args:\n data (toast.Data): The distributed data.\n \"\"\"\n if libconviqt is None:\n raise RuntimeError(\"The conviqt library was not found\")\n\n # the two-level pytoast communicator\n #comm = data.comm\n # the global communicator\n #cworld = comm.comm_world\n # the communicator within the group\n #cgroup = comm.comm_group\n # the communicator with all processes with\n # the same rank within their group\n #crank = comm.comm_rank\n\n xaxis, yaxis, zaxis = np.eye(3)\n nullquat = np.array([0, 0, 0, 1], dtype=np.float64)\n\n for obs in data.obs:\n tod = obs['tod']\n intrvl = obs['intervals']\n\n comm_ptr = MPI._addressof(tod.mpicomm)\n comm = MPI_Comm.from_address(comm_ptr)\n\n for det in tod.local_dets:\n try:\n skyfile, beamfile, epsilon, psipol = self._detectordata[det]\n except:\n raise Exception(\n 'ERROR: conviqt object not initialized to convolve '\n 'detector {}. Available detectors are {}'.format(\n det, self._detectordata.keys()))\n \n sky = libconviqt.conviqt_sky_new()\n err = libconviqt.conviqt_sky_read(\n sky, self._lmax, self._pol, skyfile.encode(), self._fwhm,\n comm)\n if err != 0:\n raise RuntimeError('Failed to load ' + skyfile)\n if self._remove_monopole:\n err = libconviqt.conviqt_sky_remove_monopole(sky)\n if err != 0: raise RuntimeError('Failed to remove monopole')\n if self._remove_dipole:\n err = libconviqt.conviqt_sky_remove_dipole(sky)\n if err != 0: raise RuntimeError('Failed to remove dipole')\n\n beam = libconviqt.conviqt_beam_new()\n err = libconviqt.conviqt_beam_read(\n beam, self._lmax, self._beammmax,\n self._pol, beamfile.encode(), comm)\n if err != 0:\n raise Exception('Failed to load ' + beamfile)\n\n detector = libconviqt.conviqt_detector_new_with_id(det.encode())\n libconviqt.conviqt_detector_set_epsilon(detector, epsilon)\n \n # We need the three pointing angles to describe the\n # pointing. read_pntg returns the attitude quaternions.\n if self._quat_name is not None:\n cachename = '{}_{}'.format(self._quat_name, det)\n pdata = tod.cache.reference(cachename).copy()\n else:\n pdata = tod.read_pntg(detector=det).copy()\n\n if self._apply_flags:\n common, flags = None, None\n if self._common_flag_name is not None:\n common = tod.cache.reference(self._common_flag_name)\n if self._flag_name is not None:\n cachename = '{}_{}'.format(self._flag_name, det)\n flags = tod.cache.reference(cachename)\n else:\n flags, common_temp = tod.read_flags(detector=det)\n if common is None: common = common_temp\n if common is None:\n common = tod.read_common_flags()\n common = (common & self._common_flag_mask)\n flags = (flags & self._flag_mask)\n totflags = np.copy(flags)\n totflags |= common\n pdata[totflags != 0] = nullquat\n\n theta, phi, psi = quat2angle(pdata)\n \n # Is the psi angle in Pxx or Dxx? Pxx will include the\n # detector polarization angle, Dxx will not.\n\n if self._dxx:\n psi -= psipol\n\n pnt = libconviqt.conviqt_pointing_new()\n\n err = libconviqt.conviqt_pointing_alloc(pnt,\n tod.local_samples[1]*5)\n if err != 0:\n raise Exception('Failed to allocate pointing array')\n\n ppnt = libconviqt.conviqt_pointing_data(pnt)\n\n for row in range(tod.local_samples[1]):\n ppnt[row*5 + 0] = phi[row]\n ppnt[row*5 + 1] = theta[row]\n ppnt[row*5 + 2] = psi[row]\n # This column will host the convolved data upon exit\n ppnt[row*5 + 3] = 0\n # libconviqt will assign the running indices to this column.\n ppnt[row*5 + 4] = 0\n\n convolver = libconviqt.conviqt_convolver_new(\n sky, beam, detector, self._pol, self._lmax, self._beammmax,\n self._order, comm)\n\n if convolver is None:\n raise Exception(\"Failed to instantiate convolver\")\n\n err = libconviqt.conviqt_convolver_convolve(convolver, pnt,\n self._calibrate)\n if err != 0:\n raise Exception('Convolution FAILED!')\n\n # The pointer to the data will have changed during\n # the convolution call ...\n\n ppnt = libconviqt.conviqt_pointing_data(pnt)\n\n convolved_data = np.zeros(tod.local_samples[1])\n for row in range(tod.local_samples[1]):\n convolved_data[row] = ppnt[row*5 + 3]\n\n libconviqt.conviqt_convolver_del(convolver)\n\n cachename = \"{}_{}\".format(self._out, det)\n if not tod.cache.exists(cachename):\n tod.cache.create(cachename, np.float64,\n (tod.local_samples[1],))\n ref = tod.cache.reference(cachename)\n if ref.size != convolved_data.size:\n raise RuntimeError(\n '{} already exists in tod.cache but has wrong size: {} '\n '!= {}'.format(cachename, ref.size, convolved_data.size))\n ref[:] += convolved_data\n\n libconviqt.conviqt_pointing_del(pnt)\n libconviqt.conviqt_detector_del(detector)\n libconviqt.conviqt_beam_del(beam)\n libconviqt.conviqt_sky_del(sky)\n\n return\n","sub_path":"toast/tod/conviqt.py","file_name":"conviqt.py","file_ext":"py","file_size_in_byte":14279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"527341734","text":"'''\ncat day_2_input.txt | pypy3 day_2_2.py\n'''\n\nimport sys\n\n# (y, x)\nkeypad_values = {\n (0, 2): \"1\",\n (1, 1): \"2\",\n (1, 2): \"3\",\n (1, 3): \"4\",\n (2, 0): \"5\",\n (2, 1): \"6\",\n (2, 2): \"7\",\n (2, 3): \"8\",\n (2, 4): \"9\",\n (3, 1): \"A\",\n (3, 2): \"B\",\n (3, 3): \"C\",\n (4, 2): \"D\"\n}\nstart = (1, 1)\n\nkeys = []\n\nl = -1\nfor line in sys.stdin.readlines():\n l += 1\n moves = list(line)\n position = list(start)\n\n i = -1\n for move in moves:\n i += 1\n prev_position = list(position)\n print(l, i, move)\n if move == \"L\":\n position[1] -= 1\n elif move == \"U\":\n position[0] -= 1\n elif move == \"R\":\n position[1] += 1\n elif move == \"D\":\n position[0] += 1\n else:\n print(\"Unknown move\", move)\n if tuple(position) not in keypad_values:\n print(\"Outside of keypad, reverting from\", position, \"to\", prev_position)\n position = prev_position\n print(l, i, position)\n\n end = tuple(position)\n key = keypad_values[end]\n print(\"Ended at\", end, \"which is key\", key)\n keys.append(key)\nprint(keys)\n\n'''\n1 0 0 = 0\n0 1 -1 -1\n\n0 1 0 = -1\n0 1 -1 -1\n\n1 1 0 = -1\n0 1 -1 -1\n\nleft\n 0 -1 0 1 0\n-1 0 1 0 -1\n'''\n","sub_path":"2016/day_2_2.py","file_name":"day_2_2.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"335016576","text":"\"\"\"\nmbed SDK\nCopyright (c) 2017 ARM Limited\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 unittest\nfrom mock import patch\n\nfrom mbed_greentea.mbed_report_api import exporter_html, \\\n exporter_memory_metrics_csv, exporter_testcase_junit, \\\n exporter_testcase_text, exporter_text, exporter_json\n\n\nclass ReportEmitting(unittest.TestCase):\n\n\n report_fns = [exporter_html, exporter_memory_metrics_csv,\n exporter_testcase_junit, exporter_testcase_text,\n exporter_text, exporter_json]\n def test_report_zero_tests(self):\n test_data = {}\n for report_fn in self.report_fns:\n report_fn(test_data)\n\n def test_report_zero_testcases(self):\n test_data = {\n 'k64f-gcc_arm': {\n 'garbage_test_suite' :{\n u'single_test_result': u'NOT_RAN',\n u'elapsed_time': 0.0,\n u'build_path': u'N/A',\n u'build_path_abs': u'N/A',\n u'copy_method': u'N/A',\n u'image_path': u'N/A',\n u'single_test_output': u'\\x80abc' ,\n u'platform_name': u'k64f',\n u'test_bin_name': u'N/A',\n u'testcase_result': {},\n }\n }\n }\n for report_fn in self.report_fns:\n report_fn(test_data)\n","sub_path":"packages/mbed-greentea/test/report_api.py","file_name":"report_api.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"246032405","text":"import torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\n\n# Copyright 2018 The Sonnet Authors. All Rights Reserved.\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\n# Borrowed from https://github.com/deepmind/sonnet and ported it to PyTorch\n\n\nclass Quantize(nn.Module):\n def __init__(self, dim, n_embed, decay=0.99, eps=1e-5):\n super().__init__()\n\n self.dim = dim\n self.n_embed = n_embed\n self.decay = decay\n self.eps = eps\n\n embed = torch.randn(dim, n_embed)\n self.register_buffer('embed', embed)\n self.register_buffer('cluster_size', torch.zeros(n_embed))\n self.register_buffer('embed_avg', embed.clone())\n\n def forward(self, input):\n flatten = input.reshape(-1, self.dim)\n dist = (\n flatten.pow(2).sum(1, keepdim=True)\n - 2 * flatten @ self.embed\n + self.embed.pow(2).sum(0, keepdim=True)\n )\n _, embed_ind = (-dist).max(1)\n embed_onehot = F.one_hot(embed_ind, self.n_embed).type(flatten.dtype)\n embed_ind = embed_ind.view(*input.shape[:-1])\n quantize = self.embed_code(embed_ind)\n\n if self.training:\n self.cluster_size.data.mul_(self.decay).add_(\n 1 - self.decay, embed_onehot.sum(0)\n )\n embed_sum = flatten.transpose(0, 1) @ embed_onehot\n self.embed_avg.data.mul_(self.decay).add_(1 - self.decay, embed_sum)\n n = self.cluster_size.sum()\n cluster_size = (\n (self.cluster_size + self.eps) / (n + self.n_embed * self.eps) * n\n )\n embed_normalized = self.embed_avg / cluster_size.unsqueeze(0)\n self.embed.data.copy_(embed_normalized)\n\n diff = (quantize.detach() - input).pow(2).mean()\n quantize = input + (quantize - input).detach()\n\n return quantize, diff, embed_ind\n\n def embed_code(self, embed_id):\n return F.embedding(embed_id, self.embed.transpose(0, 1))","sub_path":"code/networks/Quantize.py","file_name":"Quantize.py","file_ext":"py","file_size_in_byte":2570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"287631870","text":"import smtplib\nfrom email import encoders\nfrom email.mime.base import MIMEBase\nfrom email.mime.text import MIMEText\nfrom email.mime.image import MIMEImage\nfrom email.mime.message import MIMEMessage\nfrom email.mime.multipart import MIMEMultipart\nfrom email.utils import formatdate\nimport ssl\nimport magic\nimport os\n\nimport info\n\ndef create_message(from_addr, to_addr, cc_addrs, bcc_addrs, subject):\n msg = MIMEMultipart()\n msg['Subject'] = subject\n msg['From'] = from_addr\n msg['To'] = to_addr\n msg['Bcc'] = bcc_addrs\n msg['Cc'] = cc_addrs\n msg['Date'] = formatdate()\n return msg\n\ndef attach_file(msg, attach_dir):\n for file_name in os.listdir(attach_dir):\n path = os.path.join(attach_dir, file_name)\n with open(path, 'rb') as fp:\n types = get_mimetypes(path)\n attachment = MIMEBase(types['maintype'], types['subtype'])\n attachment.set_payload(fp.read())\n encoders.encode_base64(attachment)\n attachment.add_header(\n 'Content-Disposition', 'attachment',\n filename = file_name\n )\n msg.attach(attachment)\n\ndef add_text(msg, body):\n msg.attach(MIMEText(body))\n\ndef send_mail(from_addr, to_addrs, password, msg):\n sender = smtplib.SMTP_SSL('smtp.gmail.com', 465)\n sender.login(from_addr, password)\n sender.sendmail(from_addr, to_addrs, msg.as_string())\n sender.quit()\n\ndef get_mimetypes(path):\n m = magic.from_file(path, mime=True).split('/')\n types = dict(maintype = m[0], subtype = m[1])\n return types\n\n\n","sub_path":"client/send_mail.py","file_name":"send_mail.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"135535413","text":"#!/usr/bin/env python\r\n# -*- coding: iso-8859-1 -*-\r\n\r\n#\r\n# Copylefth (c) 2009, Grudejo:\r\n# Aline Grazielle Silva Reis\r\n# Julia Carmona Almeida Chaves\r\n# Luziany Maria de Oliveira\r\n# Joyce Karoline Dare\r\n# Prof. Douglas Machado Tavares\r\n#\r\n\r\nimport pygame, sys\r\nfrom pygame.constants import *\r\n\r\n\r\nclass Jogo:\r\n \"\"\" Classe Jogo \"\"\"\r\n\r\n def __init__(self):\r\n \"\"\" Construtor: __init__() -> instancia de jogo \"\"\"\r\n pygame.init()\r\n self.tela = pygame.display.set_mode((800, 600), DOUBLEBUF)\r\n\r\n\r\n def criar_atores(self):\r\n \"\"\" Cria os atores \"\"\"\r\n self.paola = pygame.image.load(\"paola.png\")\r\n self.x_paola, self.y_paola = 0, 100\r\n\r\n\r\n def atualizar_atores(self):\r\n \"\"\" Atualiza os atores \"\"\"\r\n ret_tela = self.tela.get_rect()\r\n ret_paola = self.paola.get_rect()\r\n if (self.x_paola < ret_tela.width - ret_paola.width):\r\n self.x_paola += 6\r\n\r\n\r\n def repintar_tela(self):\r\n \"\"\" Repinta a tela \"\"\"\r\n self.tela.fill((0, 0, 0))\r\n self.tela.blit(self.paola, (self.x_paola, self.y_paola))\r\n pygame.display.flip()\r\n\r\n\r\n def tratar_eventos_teclado(self, evento):\r\n \"\"\" Observa e trata os eventos \"\"\"\r\n tecla = evento.key\r\n if ((tecla == K_ESCAPE) or (tecla == K_q)):\r\n pygame.display.quit()\r\n sys.exit()\r\n\r\n\r\n def tratar_eventos(self):\r\n \"\"\" Observa e trata os eventos \"\"\"\r\n for evento in pygame.event.get():\r\n if (evento.type == QUIT):\r\n pygame.display.quit()\r\n sys.exit()\r\n if (evento.type == KEYDOWN):\r\n self.tratar_eventos_teclado(evento)\r\n\r\n\r\n def rodar(self):\r\n \"\"\" Roda o jogo \"\"\"\r\n self.criar_atores()\r\n while (True):\r\n self.tratar_eventos()\r\n self.atualizar_atores()\r\n self.repintar_tela()\r\n\r\n\r\nif (__name__ == \"__main__\"):\r\n jogo = Jogo()\r\n jogo.rodar()\r\n","sub_path":"src/etapa_02/jogo_v03.py","file_name":"jogo_v03.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"564909910","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the countSwaps function below.\ndef countSwaps(a):\n l = len(a)\n swaps = 0\n for i in range(l):\n for j in range(l-1):\n if(a[j]>a[j+1]):\n temp = a[j+1]\n a[j+1] = a[j]\n a[j] = temp\n swaps = swaps+1\n print(\"Array is sorted in\", swaps,\"swaps.\")\n print(\"First Element:\",a[0])\n print(\"Last Element:\",a[-1])\n return swaps\nif __name__ == '__main__':\n n = int(input())\n\n a = list(map(int, input().rstrip().split()))\n\n countSwaps(a)\n\n","sub_path":"hackerrank_solutions/count_swaps.py","file_name":"count_swaps.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"260548283","text":"# -*- coding: utf-8 -*-\n\nsenate = \"DRRDRDRDRDDRDRDR\"\nsenate = list(senate)\nn = len(senate)\nwhile \"D\" in senate and \"R\" in senate:\n for i in range(n):\n if senate[i] == \"0\":\n continue\n elif senate[i] == \"R\":\n if \"D\" in senate:\n if \"D\" in senate[i:]:\n senate[senate.index(\"D\", i, n)] = \"0\"\n else:\n senate[senate.index(\"D\")] = \"0\"\n else:\n break\n else:\n if \"R\" in senate:\n if \"R\" in senate[i:]:\n senate[senate.index(\"R\", i, n)] = \"0\"\n else:\n senate[senate.index(\"R\")] = \"0\"\n else:\n break\n\nif \"R\" in senate:\n print(\"R\")\nelse:\n print(\"D\")","sub_path":"LeeCode测试题/参议院.py","file_name":"参议院.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"491400134","text":"import urllib.request\nimport re\nimport socket\nheader = {\n \"Connection\": \"keep-alive\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36\",\n \"Accept\": \" text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"Accept-Language\": \"zh-CN,zh;q=0.8\"\n};\nnow = open('url.txt','r')\nnow_list = now.readlines()\nprint(now_list)\nlogfile = open('log.txt','w+')\nfor url in now_list:\n #if url in now_list and url:\n #pass\n try:\n\n#url = 'https://www.wandoujia.com/apps/net.luoo.LuooFM'\n my_request = urllib.request.Request(url,headers = header)\n response = urllib.request.urlopen(my_request)\n #response = urllib.request.urlopen('https://www.wandoujia.com/apps/net.luoo.LuooFM',headers =header)\n readd = response.read()\n test=readd.decode('utf-8')\n\n #print(response.read().decode('utf-8'))\n\n m1 = re.search('data-name=\"(.*?)\"',test)\n m2 = re.search('data-install=\"(.*?)\"',test)\n#(.*?) data-install=\"1220.8万\n name = m1.group(1) #apk文件名\n datainstall=m2.group(1)\n print(url.strip(),' ', name, ' ' , datainstall)\n #data = [url, nane, datainstall]\n logfile.writelines([url.strip(),',', name,',', datainstall, '\\r\\n'])\n logfile.flush()\n print(data)\n except Exception as e:\n print(url)\n logfile.writelines(url)\n pass\nclose(logfile)\nclose(now)\n","sub_path":"android_crawler/log_file/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"185645314","text":"from common.datatypes import Int32, Int8\n\n\ndef xor_encrypt_game(func):\n def xor(data, key):\n temp = Int32(0)\n\n for i in range(len(data)):\n temp2 = Int32(data[i] & 0xff)\n data[i] = Int8(temp2 ^ key[i & 15] ^ temp)\n temp = data[i]\n\n old = Int32(key[8] & 0xff)\n old |= Int32(key[9] << 0x08) & 0xff00\n old |= Int32(key[10] << 0x10) & 0xff0000\n old |= Int32(key[11] << 0x18) & 0xff000000\n\n old += Int32(len(data))\n\n key[8:12] = old\n\n return data\n\n def wrap(packet, client, *args, **kwargs):\n if client.encryption_enabled:\n result = xor(func(packet, client, *args, **kwargs), client.xor_key.outgoing_key)\n else:\n result = func(packet, client, *args, **kwargs)\n return result\n return wrap\n\n\ndef xor_decrypt_game(func):\n def dexor(data, key):\n temp1 = Int32(0)\n for i in range(len(data)):\n temp2 = Int32(data[i]) & 0xff\n data[i] = Int8(temp2 ^ key[i & 15] ^ temp1)\n temp1 = temp2\n\n old = (Int32(key[8]) & 0xff)\n old |= (Int32(key[9]) << 0x08) & 0xff00\n old |= (Int32(key[10]) << 0x10) & 0xff0000\n old |= (Int32(key[11]) << 0x18) & 0xff000000\n\n old += Int32(len(data))\n\n key[8:12] = old\n return data\n\n def wrap(packet_cls, data, client, *args, **kwargs):\n if client.encryption_enabled:\n decrypted = dexor(data, client.xor_key.incoming_key)\n return func(packet_cls, decrypted, client, *args, **kwargs)\n else:\n return func(packet_cls, data, client, *args, **kwargs)\n return wrap","sub_path":"gameserver/crypt/xor.py","file_name":"xor.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"473926602","text":"from __future__ import annotations\n\nfrom math import ceil\nimport logging\n\n\nfrom rich.color import Color\nfrom rich.style import Style\nfrom rich.console import Console, ConsoleOptions, RenderResult, RenderableType\nfrom rich.segment import Segment, Segments\nfrom rich.style import Style\n\nlog = logging.getLogger(\"rich\")\n\nfrom .widget import Widget\n\n\nclass VerticalBar:\n def __init__(\n self,\n lines: list[list[Segment]],\n height: int,\n virtual_height: int,\n position: float,\n overlay: bool = False,\n ) -> None:\n self.lines = lines\n self.height = height\n self.virtual_height = virtual_height\n self.position = position\n self.overlay = overlay\n\n def __rich_console__(\n self, console: Console, options: ConsoleOptions\n ) -> RenderResult:\n bar = render_bar(\n size=self.height,\n window_size=len(self.lines),\n virtual_size=self.virtual_height,\n position=self.position,\n )\n new_line = Segment.line()\n for line, bar_segment in zip(self.lines, bar):\n yield from line\n yield bar_segment\n yield new_line\n\n\nclass ScrollBar(Widget):\n def __init__(self, virtual_size: int = 100, window_size: int = 25) -> None:\n self.position = 0\n self.virtual_size = virtual_size\n self.window_size = window_size\n super().__init__()\n\n def render(self, console: Console, options: ConsoleOptions) -> RenderableType:\n\n height = options.height or console.height\n bar_segments = render_bar(\n height,\n window_size=self.window_size,\n virtual_size=self.virtual_size,\n position=self.position,\n depth=options.max_width,\n )\n return Segments(bar_segments, new_lines=True)\n\n\ndef render_bar(\n size: int = 25,\n virtual_size: float = 50,\n window_size: float = 20,\n position: float = 0,\n back_color: str = \"#555555\",\n bar_color: str = \"bright_magenta\",\n ascii_only: bool = False,\n depth: int = 1,\n vertical: bool = True,\n) -> list[Segment]:\n\n if ascii_only:\n bars = [\"|\", \"|\", \"|\", \"|\", \"|\", \"|\", \"|\", \"|\", \"|\"]\n else:\n bars = [\"▁\", \"▂\", \"▃\", \"▄\", \"▅\", \"▆\", \"▇\", \"█\"]\n\n back = Color.parse(back_color)\n bar = Color.parse(bar_color)\n\n _Segment = Segment\n _Style = Style\n blank = \" \" * depth\n segments = [_Segment(blank, _Style(bgcolor=back))] * int(size)\n\n step_size = virtual_size / size\n\n start = int(position / step_size * 8)\n end = start + max(8, int(window_size / step_size * 8))\n\n start_index, start_bar = divmod(start, 8)\n end_index, end_bar = divmod(end, 8)\n\n segments[start_index:end_index] = [_Segment(blank, _Style(bgcolor=bar))] * (\n end_index - start_index\n )\n\n if start_index < len(segments):\n segments[start_index] = _Segment(\n bars[7 - start_bar] * depth, _Style(bgcolor=back, color=bar)\n )\n if end_index < len(segments):\n segments[end_index] = _Segment(\n bars[7 - end_bar] * depth, _Style(color=back, bgcolor=bar)\n )\n\n return segments\n\n\nif __name__ == \"__main__\":\n from rich.console import Console\n from rich.segment import Segments\n\n console = Console()\n\n bar = render_bar(\n size=10,\n virtual_size=100,\n window_size=20,\n position=20,\n vertical=True,\n ascii_only=False,\n )\n\n console.print(Segments(bar, new_lines=True))\n","sub_path":"src/textual/scrollbar.py","file_name":"scrollbar.py","file_ext":"py","file_size_in_byte":3528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"345270184","text":"import csv\nimport os, sys, io\n\ndef configMaker(run_number,masks):\n\n\tminClusterSize = 1\n\tmaxClusterSize = 10\n\tmaxResidual = 5.0\n\ttrackChi2 = 3\n\ttrackResX = 0.3\n\ttrackResY = 0.3697\n\tMulSigmaOnWindow = 5\n\tminRecHitsPerTrack = 4\n\n\tconfigTablesPath = os.path.abspath(\"config_creator.py\").split('QC8Test')[0] + 'QC8Test/src/Analysis/GEMQC8/data/StandConfigurationTables/'\n\n\trunPath = os.path.abspath(\"config_creator.py\").split('QC8Test')[0] + 'QC8Test/src/Analysis/GEMQC8/test/'\n\n\tinfileName = configTablesPath + \"StandGeometryConfiguration_run\" + str(run_number) + \".csv\"\n\n\twith open(infileName) as infile:\n\t\tfor line in infile:\n\t\t\tline = line.split('\\n')[0]\n\t\t\tChID = line.split(',')[0]\n\t\t\tif (ChID!='CH_SERIAL_NUMBER'):\n\t\t\t\tif (int(line.split(',')[8])!=int(run_number)):\n\t\t\t\t\tsys.exit('StandGeometryConfiguration file has something wrong: run rumber not matching...')\n\n\tout_name = 'out_run_'\n\tfor i in range(6-len(str(run_number))):\n\t out_name = out_name + '0'\n\tout_name = out_name + str(run_number) + '.root'\n\n\toutfileName = runPath + \"configureRun_cfi.py\"\n\n\toutfile = open(outfileName,\"w\")\n\n\toutfile.write('RunNumber = ' + str(run_number) + '\\n\\n')\n\n\toutfile.write('# Output file name definition\\n')\n\toutfile.write('OutputFileName = \\'' + out_name + '\\'\\n\\n')\n\n\toutfile.write('# Parameters definition\\n')\n\toutfile.write('minClusterSize = {}\\n'.format(minClusterSize))\n\toutfile.write('maxClusterSize = {}\\n'.format(maxClusterSize))\n\toutfile.write('maxResidual = {} # cm\\n'.format(maxResidual))\n\toutfile.write('trackChi2 = {}\\n'.format(trackChi2))\n\toutfile.write('trackResX = {}\\n'.format(trackResX))\n\toutfile.write('trackResY = {}\\n'.format(trackResY))\n\toutfile.write('MulSigmaOnWindow = {}\\n'.format(MulSigmaOnWindow))\n\toutfile.write('minRecHitsPerTrack = {}\\n'.format(minRecHitsPerTrack))\n\tif (masks == \"yesMasks\"):\n\t\toutfile.write('applyMasks = True\\n')\n\tif (masks == \"noMasks\"):\n\t\toutfile.write('applyMasks = False\\n')\n\n\toutfile.write('# Stand configuration definition\\n')\n\tStandConfiguration = ['0']*15\n\tChamberIDs = ['0']*30\n\n\twith open(infileName) as infile:\n\t\tfor line in infile:\n\t\t\tline = line.split('\\n')[0]\n\t\t\tChID = line.split(',')[0]\n\t\t\tif (ChID!='CH_SERIAL_NUMBER'):\n\t\t\t\tposition = line.split(',')[2]\n\t\t\t\trow = int(position.split('/')[0])\n\t\t\t\tcolumn = int(position.split('/')[1])\n\t\t\t\tTB = str(position.split('/')[2])\n\t\t\t\tSCnumber = (5 * (column - 1)) + (row - 1)\n\t\t\t\tCHnumber = 2 * SCnumber # Good for the bottom, but if it's top, need to add 1\n\t\t\t\tif (TB == \"T\"):\n\t\t\t\t\tCHnumber += 1\n\t\t\t\tStandConfiguration[SCnumber] = (ChID)[8] # Eight character in the chamber ID is \"L\" or \"S\"\n\t\t\t\tChamberIDs[CHnumber] = ChID.split('/')[0]+ChID.split('/')[1]\n\n\toutfile.write('StandConfiguration = [\\\\\\n')\n\tfor entry in range(15):\n\t\tif (entry==4 or entry==9):\n\t\t\toutfile.write('\\'' + StandConfiguration[entry] + '\\',\\\\\\n')\n\t\telif (entry==14):\n\t\t\toutfile.write('\\'' + StandConfiguration[entry] + '\\']')\n\t\telse:\n\t\t\toutfile.write('\\'' + StandConfiguration[entry] + '\\',')\n\n\toutfile.write('\\n')\n\n\toutfile.write('ChamberIDs = [\\\\\\n')\n\tfor entry in range(30):\n\t\tif (entry==9 or entry==19):\n\t\t\toutfile.write('\\'' + ChamberIDs[entry] + '\\',\\\\\\n')\n\t\telif (entry==29):\n\t\t\toutfile.write('\\'' + ChamberIDs[entry] + '\\']')\n\t\telse:\n\t\t\toutfile.write('\\'' + ChamberIDs[entry] + '\\',')\n\n\toutfile.close()\n\n\tprint(\"\\n\")\n\tprint(\"Success: configuration file created for run \" + str(run_number))\n\tprint(\"\\n\")\n\nif __name__ == '__main__':\n\trun_num = sys.argv[1]\n\tmask = sys.argv[2]\n\tconfigMaker(run_num,mask)\n","sub_path":"Analysis/GEMQC8/python/config_creator.py","file_name":"config_creator.py","file_ext":"py","file_size_in_byte":3484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"645528168","text":"import os \nimport json\nimport numpy as np\nimport pandas as pd\nimport dill as pickle\nfrom sklearn.externals import joblib\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.ensemble import RandomForestClassifier\n\nfrom sklearn.pipeline import make_pipeline\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\ndef build_and_train():\n \n data = pd.read_csv('Titanic_dataset/train.csv')\n print('training')\n p = PreProcessing()\n Train_set,label = p.transform(data)\n rf = RandomForestClassifier()\n rf.fit(Train_set,label)\n return(rf)\n\nclass PreProcessing():\n \"\"\"Custom Pre-Processing estimator for our use-case\n \"\"\"\n\n def __init__(self):\n pass\n\n def transform(self, df):\n y_label = df['Survived']\n df = df.drop(['Ticket', 'Cabin','Survived'], axis=1)\n df = df.drop(['Ticket', 'Cabin'], axis=1)\n df['Title'] = df.Name.str.extract(' ([A-Za-z]+)\\.', expand=False)\n df['Title'] = df['Title'].replace(['Lady', 'Countess','Capt', 'Col', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')\n df['Title'] = df['Title'].replace('Mlle', 'Miss')\n df['Title'] = df['Title'].replace('Ms', 'Miss')\n df['Title'] = df['Title'].replace('Mme', 'Mrs')\n \n title_mapping = {\"Mr\": 1, \"Miss\": 2, \"Mrs\": 3, \"Master\": 4, \"Rare\": 5}\n df['Title'] = df['Title'].map(title_mapping)\n df['Title'] = df['Title'].fillna(0)\n df['Title'] = df['Title'].astype(int)\n \n df = df.drop(['Name', 'PassengerId'], axis=1)\n \n gender_mapping = {'female': 1, 'male': 0}\n df['Sex'] = df['Sex'].map(gender_mapping).astype(int)\n \n guess_ages = np.zeros((2,3))\n for i in range(0, 2):\n for j in range(0, 3):\n guess_df = df[(df['Sex'] == i) & \\\n (df['Pclass'] == j+1)]['Age'].dropna()\n age_guess = guess_df.median()\n guess_ages[i,j] = int( age_guess/0.5 + 0.5 ) * 0.5\n \n for i in range(0, 2):\n for j in range(0, 3):\n df.loc[ (df.Age.isnull()) & (df.Sex == i) & (df.Pclass == j+1),'Age'] = guess_ages[i,j]\n \n \n df['Age'] = df['Age'].astype(int)\n df['AgeBand'] = pd.cut(df['Age'], 5) \n df.loc[ df['Age'] <= 16, 'Age'] = 0\n df.loc[(df['Age'] > 16) & (df['Age'] <= 32), 'Age'] = 1\n df.loc[(df['Age'] > 32) & (df['Age'] <= 48), 'Age'] = 2\n df.loc[(df['Age'] > 48) & (df['Age'] <= 64), 'Age'] = 3\n df.loc[ df['Age'] > 64, 'Age'] \n df = df.drop(['AgeBand'], axis=1)\n \n df['FamilySize'] = df['SibSp'] + df['Parch'] + 1\n df['IsAlone'] = 0\n df.loc[df['FamilySize'] == 1, 'IsAlone'] = 1 \n df = df.drop(['Parch', 'SibSp', 'FamilySize'], axis=1)\n df['Age*Class'] = df.Age * df.Pclass\n \n freq_port = df.Embarked.dropna().mode()[0]\n df['Embarked'] = df['Embarked'].fillna(freq_port)\n df['Embarked'] = df['Embarked'].map( {'S': 0, 'C': 1, 'Q': 2} ).astype(int)\n \n df['FareBand'] = pd.qcut(df['Fare'], 4)\n df.loc[ df['Fare'] <= 7.91, 'Fare'] = 0\n df.loc[(df['Fare'] > 7.91) & (df['Fare'] <= 14.454), 'Fare'] = 1\n df.loc[(df['Fare'] > 14.454) & (df['Fare'] <= 31), 'Fare'] = 2\n df.loc[ df['Fare'] > 31, 'Fare'] = 3\n df['Fare'] = df['Fare'].astype(int)\n df = df.drop(['FareBand'], axis=1)\n \n return df.as_matrix(),y_label\n\nif __name__ == '__main__':\n\n model = build_and_train()\n print('Complete')\n filename = 'model_v2.pk'\n with open('model/'+filename, 'wb') as file:\n pickle.dump(model, file)","sub_path":"young-shore-49534/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"160687177","text":"#script: ex-polyfit.py\n#linear regression and polynomial regression\n#(using _polyreg module)\n#author: Luis Paris\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport _poly\nimport _polyreg\n\nx = [1, 2, 3, 4]\ny = [3, 5, 7, 11] #11, not 9, so the fit isn't perfect\n\n#estimate plot x,y border for plotting\nxgap = (min(x) + max(x)) / 20.\nygap = (min(y) + max(y)) / 20.\nxlo = min(x) - xgap\nxhi = max(x) + xgap\nylo = min(y) - ygap\nyhi = max(y) + ygap\n\nprint(\"Linear regression:\") #find polynomial coeffs for linear regression\npol = _polyreg.curvefit(x, y, order=1, debug=True)\n\nprint(\"pol = {}\\ny = {}\\n\".format(pol, _poly.tostr(pol)))\n\nxregr = np.linspace(min(x), max(x))\nyregr = np.array([_poly.eval(pol, xval) for xval in xregr])\n\nplt.plot(x, y, 'yo', xregr, yregr, '--k')\nplt.xlim(xlo, xhi)\nplt.ylim(ylo, yhi)\nplt.title(\"Linear Regression\")\nplt.show()\n\nprint(\"Quadratic regression:\") #find polynomial coeffs for quadratic regression\npol = _polyreg.curvefit(x, y, order=2, debug=True)\n\nprint(\"pol = {}\\ny = {}\\n\".format(pol, _poly.tostr(pol)))\n\nxregr = np.linspace(min(x), max(x))\nyregr = np.array([_poly.eval(pol, xval) for xval in xregr])\n\nplt.plot(x, y, 'yo', xregr, yregr, '--k')\nplt.xlim(xlo, xhi)\nplt.ylim(ylo, yhi)\nplt.title(\"Quadratic Regression\")\nplt.show()\n\nprint(\"Cubic regression:\") #find polynomial coeffs for cubic regression\npol = _polyreg.curvefit(x, y, order=3, debug=True)\n\nprint(\"pol = {}\\ny = {}\\n\".format(pol, _poly.tostr(pol)))\n\nxregr = np.linspace(min(x), max(x))\nyregr = np.array([_poly.eval(pol, xval) for xval in xregr])\n\nplt.plot(x, y, 'yo', xregr, yregr, '--k')\nplt.xlim(xlo, xhi)\nplt.ylim(ylo, yhi)\nplt.title(\"Cubic Regression\")\nplt.show()\n","sub_path":"Topic 9/ex-polyfit.py","file_name":"ex-polyfit.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"50612335","text":"import os\r\nimport pprint\r\nimport tensorflow as tf\r\nimport time\r\nfrom collections import defaultdict\r\nfrom model import MTL\r\nimport json\r\nimport random\r\nimport math\r\nimport numpy as np\r\npp = pprint.PrettyPrinter()\r\n\r\ndef main(_):\r\n paras_setting = {\r\n 'edim_u': 200, # 用户特征维度\r\n 'edim_v': 200, # 物品特征维度\r\n 'layers': [400,200,100,50], # layers[0] must equal to edim_u + edim_v\r\n 'batch_size': 128, # \"batch size to use during training [128,256,512,]\"\r\n 'nepoch': 200, # \"number of epoch to use during training [80]\"\r\n 'init_lr': 0.001, # \"initial learning rate [0.01]\"\r\n 'init_std': 0.01, # \"weight initialization std [0.05]\"\r\n 'max_grad_norm': 10, # \"clip gradients to this norm [50]\"\r\n 'negRatio': 1, # \"negative sampling ratio [5]\"\r\n 'cross_layers': 2, # cross between 1st & 2nd, and 2nd & 3rd layers\r\n #'merge_ui': 0, # \"merge embeddings of user and item: 0-add, 1-mult [1], 2-concat\"\r\n 'activation': 'relu', # \"0:relu, 1:tanh, 2:softmax\"\r\n 'learner': 'adam', # {adam, rmsprop, adagrad, sgd}\r\n 'objective': 'mse', # 0:cross, 1: hinge, 2:log\r\n #'carry_trans_alpha': [0.5, 0.5], # weight of carry/copy gate\r\n 'topK': 10,\r\n 'data_dir': 'data/amazon2/', # \"data directory [../data]\"\r\n 'data_name_app': 'movie', # \"user-info\", \"data state [user-info]\"\r\n 'data_name_news': 'music', # \"user-info\", \"data state [user-info]\"\r\n 'weights_app_news': [1, 1], # weights of each task [0.8,0.2], [0.5,0.5], [1,1]\r\n 'checkpoint_dir': 'checkpoints', # \"checkpoints\", \"checkpoint directory [checkpoints]\"\r\n 'show': True, # \"print progress [True]\"\r\n #'isDebug': True, # \"isDebug mode [True]\"\r\n 'isDebug': False, # \"isDebug mode [True]\"\r\n 'isOneBatch': False, # \"isOneBatch mode for quickly run through [True]\"\r\n }\r\n # setenv CUDA_VISIBLE_DEVICES 1\r\n isRandomSearch = False\r\n\r\n if not isRandomSearch: # 默认执行\r\n start_time = time.time()\r\n with tf.Session() as sess:\r\n model = MTL(paras_setting, sess)\r\n model.build_model() # 创建模型\r\n model.run() # 调用run()\r\n metrics = {\r\n 'bestrmse_app': model.bestrmse_app,\r\n 'bestrmse_epoch_app': model.bestrmse_epoch_app,\r\n 'bestrmse_news': model.bestrmse_news,\r\n 'bestrmse_epoch_news': model.bestrmse_epoch_news,\r\n }\r\n print('=' * 80)\r\n pp.pprint(metrics)\r\n print('total time {:.2f}m'.format((time.time() - start_time)/60))\r\n\r\nif __name__ == '__main__':\r\n tf.app.run() # 执行main函数\r\n","sub_path":"CoNet_new/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"362184854","text":"# encoding: utf-8\r\n\r\nimport re\r\nimport os\r\nimport sys\r\nimport tkinter\r\nfrom datetime import date\r\nfrom readjson import JsonReader\r\nfrom newdishdialog import NewDishDialog\r\nfrom newentrydialog import NewEntryDialog\r\nfrom newdishhtml import DishesHTMLReport\r\nfrom tkinter.ttk import Frame, Label, Button, Entry, Scrollbar, Treeview, Style, Checkbutton\r\nfrom tkinter import N, S, W, E, X, NO, RIGHT, CENTER, VERTICAL, END, messagebox, filedialog, PhotoImage, DISABLED, IntVar\r\nfrom autoentry import AutocompleteEntry\r\n\r\nDEFAULT_MINSIZE_WIDTH = 900\r\nDEFAULT_MINSIZE_HEIGHT = 750\r\n\r\njson_path = os.getcwd() + '\\\\files\\\\dishes.json'\r\nlogo_path = os.getcwd() + '\\\\images\\\\logo.png'\r\n\r\nclass Program(Frame):\r\n \"\"\"Class to represent a main window\"\"\"\r\n def __init__(self, parent):\r\n # Some top-level settings.\r\n Frame.__init__(self, parent)\r\n self.content = Frame(self, padding=(5, 5, 5, 20))\r\n self.parent = parent\r\n self.parent.title('Restaurant manager')\r\n self.parent.minsize(DEFAULT_MINSIZE_WIDTH, DEFAULT_MINSIZE_HEIGHT)\r\n self.parent.protocol('WM_DELETE_WINDOW', self.onQuit)\r\n\r\n # Some variables.\r\n self.track_weight = IntVar()\r\n self.custom_entries = []\r\n self.jsonReader = JsonReader(json_path)\r\n self.frames = []\r\n self.entries = {}\r\n self.dishes = self.jsonReader.getDishesDict()\r\n self.dishes_names = self.jsonReader.getDishesNames()\r\n self.parent.iconphoto(\r\n True,\r\n PhotoImage(\r\n file=os.path.join(\r\n sys.path[0], \r\n logo_path\r\n )\r\n )\r\n )\r\n\r\n # Initialize all widgets.\r\n self.initWidgets()\r\n\r\n def initWidgets(self):\r\n \"\"\"\r\n Initialize all widgets in window here.\r\n Entries are saved in [self.entries] list.\r\n ----------------------------------------------------------\r\n 5 frames are initialized and saved into [self.frames] list here:\r\n 1) [About frame] - Frame to contain all non-food entries.\r\n 2) [Separator frame] - Frame to contain a simple separator.\r\n 3) [New order frame] - Frame to contain entries for adding orders to the main table.\r\n 4) [Orders table frame] - Frame to contain table with list of added orders.\r\n 5) [Save report frame] - Frame to contain buttons, which save a report.\r\n ----------------------------------------------------------\r\n \"\"\"\r\n # Create 5 frames here.\r\n for i in range(5):\r\n self.frames.append(\r\n Frame(self.content)\r\n )\r\n # Set the weights of cols and rows in the grid.\r\n self.configureGrid()\r\n # Center a window.\r\n self.centerWindow()\r\n\r\n # Place 4 frames to the window.\r\n self.frames[0].grid(column=0, row=0, sticky=N+E+W, padx=5, pady=3)\r\n self.frames[1].grid(column=0, row=1, sticky=N+S+E+W, padx=5, pady=3)\r\n self.frames[2].grid(column=0, row=2, sticky=N+S+E+W, padx=5, pady=3)\r\n self.frames[3].grid(column=0, row=3, sticky=N+S+E+W, padx=5, pady=10)\r\n self.frames[4].grid(column=0, row=4, sticky=S+E+W, padx=5, pady=3)\r\n\r\n # About frame widgets.\r\n Label(self.frames[0], text='Заказчик').grid(row=0, column=0, sticky=E, pady=5)\r\n Label(self.frames[0], text='Менеджер').grid(row=0, column=2, sticky=E, pady=5)\r\n Label(self.frames[0], text='Вид мероприятия', justify=RIGHT, wraplength=90\r\n ).grid(row=0, column=4, sticky=E, pady=5)\r\n Label(self.frames[0], text='Дата').grid(row=1, column=0, sticky=E, pady=5)\r\n Label(self.frames[0], text='Время').grid(row=1, column=2, sticky=E, pady=5)\r\n Label(self.frames[0], text='Место проведения', justify=RIGHT, wraplength=90\r\n ).grid(row=1, column=4, sticky=E, pady=5)\r\n Label(self.frames[0], text='Количество персон', justify=RIGHT, wraplength=90\r\n ).grid(row=1, column=6, sticky=E, pady=5)\r\n\r\n self.entries['client'] = Entry(self.frames[0])\r\n self.entries['manager'] = Entry(self.frames[0])\r\n self.entries['type'] = Entry(self.frames[0], width=10)\r\n self.entries['date'] = Entry(self.frames[0])\r\n self.entries['time'] = Entry(self.frames[0])\r\n self.entries['location'] = Entry(self.frames[0], width=10)\r\n self.entries['persons'] = Entry(self.frames[0], width=10)\r\n\r\n self.entries['client'].focus_set()\r\n today = date.today().isoformat().split('-')[::-1]\r\n self.entries['date'].insert(0, '.'.join(today))\r\n\r\n self.entries['client'].grid(row=0, column=1, sticky=E+W, padx=(3, 13), pady=5)\r\n self.entries['manager'].grid(row=0, column=3, sticky=E+W, padx=(3, 13), pady=5)\r\n self.entries['type'].grid(row=0, column=5, columnspan=3, sticky=E+W, padx=(3, 13), pady=5)\r\n self.entries['date'].grid(row=1, column=1, sticky=E+W, padx=(3, 13), pady=5)\r\n self.entries['time'].grid(row=1, column=3, sticky=E+W, padx=(3, 13), pady=5)\r\n self.entries['location'].grid(row=1, column=5, sticky=E + W, padx=(3, 13), pady=5)\r\n self.entries['persons'].grid(row=1, column=7, sticky=E+W, padx=(3, 13), pady=5)\r\n\r\n # Add a separator between [about] and [new order] frames\r\n sep1 = Frame(self.frames[1], height=2, borderwidth=1, relief='sunken')\r\n sep1.pack(fill=X, padx=1, pady=10)\r\n\r\n # New Order frame widgets.\r\n Label(self.frames[2], text='Название', anchor=E).grid(row=0, column=0, sticky=E)\r\n Label(self.frames[2], text='Комментарий', anchor=E).grid(row=1, column=0, sticky=E)\r\n Label(self.frames[2], text='Количество', anchor=E).grid(row=2, column=0, sticky=E)\r\n self.sum_lbl = Label(self.frames[2], text='Текущая сумма заказа:\\n 0 грн', anchor=E, justify=RIGHT)\r\n\r\n self.entries['name'] = AutocompleteEntry(self.frames[2])\r\n self.entries['comment'] = Entry(self.frames[2])\r\n self.entries['amount'] = Entry(self.frames[2])\r\n addOrder_btn = Button(self.frames[2], text='Добавить блюдо в отчет')\r\n\r\n self.entries['name'].set_completion_list(self.dishes_names)\r\n self.entries['amount'].insert(0, '1')\r\n addOrder_btn['command'] = lambda: self.addDish()\r\n\r\n self.entries['name'].grid(row=0, column=1, columnspan=5, sticky=W+E, pady=3, padx=(3, 15))\r\n self.entries['comment'].grid(row=1, column=1, columnspan=5, sticky=W+E, pady=3, padx=(3, 15))\r\n self.entries['amount'].grid(row=2, column=1, columnspan=2, sticky=W+E, pady=3, padx=(3, 15))\r\n addOrder_btn.grid(row=3, column=1, sticky=W, pady=3, padx=3)\r\n self.sum_lbl.grid(row=4, column=5, pady=0, padx=(190, 0))\r\n\r\n customEntry_btn = Button(self.frames[2], text='Добавить собственную строку в отчет')\r\n customEntry_btn['command'] = lambda: self.addCustomEntry()\r\n customEntry_btn.grid(row=4, column=1, sticky=W, pady=3, padx=3)\r\n\r\n # Orders Table frame widgets.\r\n self.orders_view = Treeview(self.frames[3])\r\n self.orders_view['columns'] = ('Weight', 'Amount', 'Comment', 'Price', 'Sum')\r\n self.orders_view.bind('', lambda e: self.deleteEntry(e, self.orders_view))\r\n\r\n self.orders_view.heading('#0', text='Название')\r\n self.orders_view.column('#0', anchor='w', minwidth=307, width=307)\r\n self.orders_view.heading('Weight', text='Выход')\r\n self.orders_view.column('Weight', anchor=CENTER, minwidth=100, width=100, stretch=NO)\r\n self.orders_view.heading('Amount', text='Количество')\r\n self.orders_view.column('Amount', anchor=CENTER, minwidth=100, width=100, stretch=NO)\r\n self.orders_view.heading('Comment', text='Комментарий')\r\n self.orders_view.column('Comment', anchor='w', minwidth=130, width=130)\r\n self.orders_view.heading('Price', text='Цена, грн')\r\n self.orders_view.column('Price', anchor=CENTER, minwidth=110, width=110, stretch=NO)\r\n self.orders_view.heading('Sum', text='Сумма, грн')\r\n self.orders_view.column('Sum', anchor=CENTER, minwidth=108, width=108, stretch=NO)\r\n\r\n self.orders_view.grid(row=0, column=0, sticky=N+S+E+W, padx=3, pady=3)\r\n\r\n # NOTE: next [for] block is for testing purposes only.\r\n \"\"\"\r\n for dish in self.dishes:\r\n self.orders_view.insert('', 'end',\r\n text=dish,\r\n values=[\r\n self.dishes[dish]['weight'],\r\n 5, # [amount] column\r\n 'wats up?', # [comment] column\r\n self.dishes[dish]['price'],\r\n 5 * float(self.dishes[dish]['price'])\r\n ]\r\n )\r\n \"\"\"\r\n\r\n orders_scrlbar = Scrollbar(self.frames[3], orient=VERTICAL, command=self.orders_view.yview)\r\n self.orders_view['yscrollcommand'] = orders_scrlbar.set\r\n orders_scrlbar.grid(row=0, column=1, sticky=N+S)\r\n\r\n # Save Report frame widgets.\r\n saveWeb_btn = Button(self.frames[4], text='Сохранить отчет', width=20)\r\n trackweight_chkbox = Checkbutton(self.frames[4], text='Учитывать средний вес', variable=self.track_weight)\r\n\r\n saveWeb_btn['command'] = lambda: self.saveWeb()\r\n\r\n saveWeb_btn.pack(side='left', anchor=CENTER, padx=5, pady=3)\r\n trackweight_chkbox.pack(side='left', anchor=CENTER, pady=3, padx=3)\r\n\r\n def configureGrid(self):\r\n \"\"\"Configure weights of grids columns and rows\"\"\"\r\n # Top-level configuration.\r\n self.grid(sticky=N+S+E+W)\r\n top = self.winfo_toplevel()\r\n top.rowconfigure(0, weight=1)\r\n top.columnconfigure(0, weight=1)\r\n self.rowconfigure(0, weight=1)\r\n self.columnconfigure(0, weight=1)\r\n\r\n # Configuration of main content frame.\r\n self.configureFrame(self.content, [1], [0, 0, 0, 3, 0])\r\n # Configuration of about frame.\r\n self.configureFrame(self.frames[0], [0, 1, 0, 1, 0, 0, 0, 0], [0, 0, 0])\r\n # Configuration of new order frame.\r\n self.configureFrame(self.frames[2], [0, 1, 1, 1, 1, 1], [0, 0, 0, 0])\r\n # Configuration of orders table frame.\r\n self.configureFrame(self.frames[3], [1, 0], [1])\r\n\r\n def centerWindow(self):\r\n \"\"\"Place the main window in the center of screen\"\"\"\r\n window_w = DEFAULT_MINSIZE_WIDTH\r\n window_h = DEFAULT_MINSIZE_HEIGHT\r\n screen_w = self.winfo_screenwidth()\r\n screen_h = self.winfo_screenheight()\r\n x = (screen_w - window_w) / 2\r\n y = (screen_h - window_h) / 2\r\n self.parent.geometry('%dx%d+%d+%d' % (window_w, window_h, x, y))\r\n\r\n def onQuit(self):\r\n \"\"\"Before the program exits, ask user, if he really wants it\"\"\"\r\n if messagebox.askyesno('Выход из программы', 'Вы действительно хотите выйти из программы?'):\r\n self.quit()\r\n\r\n @staticmethod\r\n def deleteEntry(e, tree):\r\n \"\"\"Event to handle deletion in TreeView woth [Delete] button\"\"\"\r\n selected_item = tree.selection()[0] # get selected item\r\n tree.delete(selected_item)\r\n\r\n @staticmethod\r\n def configureFrame(frame, columns_wght, rows_wght):\r\n \"\"\"Function to organize frame configuration routine\"\"\"\r\n frame.grid(column=0, row=0, sticky=N + S + E + W)\r\n for i, weight in enumerate(columns_wght):\r\n frame.columnconfigure(i, weight=weight)\r\n for i, weight in enumerate(rows_wght):\r\n frame.rowconfigure(i, weight=weight)\r\n\r\n def saveWeb(self):\r\n \"\"\"Save data from the TreeView to the html report\"\"\"\r\n # Validation: if there is no items in tree_view\r\n if not self.orders_view.get_children():\r\n messagebox.showerror(\r\n 'Ошибка',\r\n 'Ошибка создания отчета: нет блюд.'\r\n )\r\n return\r\n\r\n # Open file dialog to choose saving path.\r\n file = filedialog.asksaveasfile(\r\n mode='w',\r\n defaultextension='.html',\r\n filetypes=[('Веб страница', '.html'), ('Все файлы', '.*')]\r\n )\r\n # If user pressed [Cancel] or closed a file dialog.\r\n if file is None:\r\n return\r\n\r\n # Pack files to send to HTML saver module.\r\n # Dictionary looks like: { name:{weight,amount,comment,price,total}, name:... }\r\n packed_dishes = {\r\n 'global': {\r\n 'trackw': self.track_weight.get(), # flag - is weight tracked\r\n 'totalsum': self.sum_lbl['text'][21:-4], # str - total sum of dishes\r\n 'centries': self.custom_entries # [5*str] - custom entries\r\n },\r\n 'about': {\r\n 'client': self.entries['client'].get(),\r\n 'manager': self.entries['manager'].get(),\r\n 'type': self.entries['type'].get(),\r\n 'date': self.entries['date'].get(),\r\n 'time': self.entries['time'].get(),\r\n 'location': self.entries['location'].get(),\r\n 'persons': self.entries['persons'].get()\r\n },\r\n 'dishes': {}\r\n }\r\n for child in self.orders_view.get_children():\r\n child_content = self.orders_view.item(child)\r\n child_values = child_content['values']\r\n child_name = child_content['text']\r\n child_type = self.dishes[child_name]['type']\r\n # Pack data about a certain dish.\r\n packed_child = {\r\n child_name: {\r\n 'weight': child_values[0],\r\n 'amount': child_values[1],\r\n 'comment': child_values[2],\r\n 'price': child_values[3],\r\n 'total': child_values[4],\r\n 'type': child_type\r\n }\r\n }\r\n packed_dishes['dishes'].update(packed_child)\r\n # Save the HTML report\r\n html_writer = DishesHTMLReport(file, data=packed_dishes)\r\n html_writer.create_html()\r\n messagebox.showinfo(\r\n 'Успешное сохранение',\r\n 'Данные были успешно сохранены.'\r\n )\r\n\r\n def addCustomEntry(self):\r\n \"\"\"This functions opens a window, which gives access for creating custom entries to report\"\"\"\r\n newentry_dialog = NewEntryDialog(self, title='Добавить собственную строку в отчет')\r\n if newentry_dialog.result:\r\n self.custom_entries.append(newentry_dialog.result)\r\n\r\n def addDish(self):\r\n \"\"\"This function adds an entry to the order_view TreeView widget.\"\"\"\r\n # Get packed_info as a dictionary.\r\n packed_info = self.packInfo()\r\n # If info packed successfully, add a new entry to orders TreeView.\r\n if not packed_info:\r\n return\r\n # Add a dish to the TreeView.\r\n self.orders_view.insert(\r\n '', 'end',\r\n text=packed_info['dish'],\r\n values=packed_info['values']\r\n )\r\n # Clear all entries.\r\n entries_toclear = ['name', 'comment', 'amount']\r\n for entry_key in entries_toclear:\r\n self.entries[entry_key].delete(0, END)\r\n self.entries[entry_key].insert(0, '')\r\n self.entries['amount'].insert(0, '1')\r\n # Change [sum] label.\r\n total_sum = float(self.sum_lbl['text'][21:-4]) + float(packed_info['values'][4])\r\n self.sum_lbl['text'] = 'Текущая сумма заказа:\\n %.2f грн' % total_sum\r\n # Set focus to ['name'] entry.\r\n self.entries['name'].focus_set()\r\n\r\n def packInfo(self):\r\n \"\"\"Pack values, that were inserted into Entries and Text, into dictionary\"\"\"\r\n msg = self.validateForm()\r\n if msg == 'OK':\r\n name = self.entries['name'].get()\r\n amount = self.entries['amount'].get()\r\n total_price = float(amount) * float(self.dishes[name]['price'])\r\n pack = {\r\n 'dish': name,\r\n 'values': [\r\n self.dishes[name]['weight'],\r\n str(amount),\r\n self.entries['comment'].get(),\r\n self.dishes[name]['price'],\r\n '%.2f' % total_price\r\n ]\r\n }\r\n return pack\r\n elif msg == 'NEWDISH_CANCELED':\r\n return False\r\n else:\r\n messagebox.showerror(\r\n 'Ошибка ввода',\r\n 'При вводе случились ошибки: \\n%s' % msg\r\n )\r\n return False\r\n\r\n def validateForm(self):\r\n \"\"\"Validate all Entry and Text Widgets\"\"\"\r\n msg = ''\r\n index = 1\r\n translations = {\r\n 'client': 'Клиент',\r\n 'manager': 'Менеджер',\r\n 'type': 'Вид мероприятия',\r\n 'date': 'Дата',\r\n 'time': 'Время',\r\n 'location': 'Место проведения',\r\n 'persons': 'Количество персон',\r\n 'name': 'Название',\r\n 'comment': 'Комментарий',\r\n 'amount': 'Количество',\r\n }\r\n\r\n for k in self.entries:\r\n # Check if some entry is empty.\r\n if self.entries[k].get() == '':\r\n if k == 'comment':\r\n continue\r\n msg += '%i) Поле [%s] пустое.\\n' % (index, translations[k])\r\n index += 1\r\n\r\n # Persons entry should contain only digits.\r\n if not all(letter.isdigit() for letter in self.entries['persons'].get()):\r\n msg += '%i) Поле [Количество персон] должно содержать только цифры.\\n' % index\r\n index += 1\r\n # Check date entry.\r\n match = re.search(r'(\\d{2})[.](\\d{2})[.](\\d{4})$', self.entries['date'].get())\r\n if not match:\r\n msg += '%i) Неправильный формат даты.\\nПравильный формат: дд.мм.гггг\\n' % index\r\n index += 1\r\n # Check amount entry.\r\n check = all(letter.isdigit() or letter == '.' for letter in self.entries['amount'].get())\r\n if not check:\r\n msg += '%i) Поле [Количество] должно содержать только цифры, или точки.\\n' % index\r\n index += 1\r\n\r\n # Ask about [name] entry only if there are no more errors left.\r\n if msg != '':\r\n return msg\r\n\r\n # Check name entry.\r\n if (self.entries['name'].get() not in self.dishes_names and self.entries['name'].get() != ''):\r\n if messagebox.askyesno('Добавление нового блюда', 'Блюда %s нет в списке. Добавить?' % self.entries['name'].get()):\r\n # Create a new window, which will contain a [result] dictionary {name,type,weight,price}\r\n newdish_dialog = NewDishDialog(self, self.entries['name'].get(), 'Добавить новое блюдо')\r\n if newdish_dialog.result:\r\n dishToJSON = {\r\n newdish_dialog.result['name']: {\r\n 'weight': newdish_dialog.result['weight'],\r\n 'price': newdish_dialog.result['price'],\r\n 'type': newdish_dialog.result['type']\r\n }\r\n }\r\n self.jsonReader.writeDish(dishToJSON)\r\n self.jsonReader.prepInformation()\r\n self.dishes = self.jsonReader.getDishesDict()\r\n self.dishes_names = self.jsonReader.getDishesNames()\r\n self.entries['name'].set_completion_list(self.dishes_names)\r\n else:\r\n # if [exit] was pressed\r\n return 'NEWDISH_CANCELED'\r\n else:\r\n return 'NEWDISH_CANCELED'\r\n # Check if the same dish is in the orderslist.\r\n for child in self.orders_view.get_children():\r\n child_content = self.orders_view.item(child)\r\n if self.entries['name'].get() == child_content['text']:\r\n msg += '%i) Ошибка в поле [Название] - такое блюдо уже есть в списке.' % index\r\n index += 1\r\n\r\n # If all tests passed correctly, msg is 'OK'\r\n if msg == '':\r\n msg = 'OK'\r\n return msg\r\n\r\n\r\ndef main():\r\n root = tkinter.Tk()\r\n app = Program(root)\r\n root.mainloop()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":21060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"413347800","text":"#encoding: utf-8\nfrom OpenOrange import *\nfrom Report import Report\n\nclass ItemStatusReport(Report):\n\n def run(self):\n self.getView().resize(600,350)\n from Stock import Stock\n self.record = self.getRecord()\n self.stock = Stock.getQty(self.record.ArtCode, self.record.StockDepo)\n\n self.so_ordered = 0.0\n self.so_initial = 0.0\n self.so_picking = 0.0\n self.so_finished = 0.0\n self.so_returned = 0.0\n self.so_compromised = 0.0\n\n self.po_ordered = 0.0\n self.po_initial = 0.0\n self.po_finished = 0.0\n self.po_returned = 0.0\n self.po_compromised = 0.0\n\n self.startTable()\n self.header(\"Item Status\",self.record.ArtCode)\n self.endTable()\n self.showSalesOrders()\n self.row(\" \")\n self.showPurchaseOrders()\n self.row(\" \")\n self.showTotals()\n\n def showSalesOrders(self):\n from SalesOrder import SalesOrder\n query = Query()\n query.sql = \"SELECT [so].{SerNr}, [sorw].{Qty}\\n\"\n query.sql += \"FROM [SalesOrder] [so]\\n\"\n query.sql += \"INNER JOIN [SalesOrderItemRow] [sorw] ON [sorw].{masterId} = [so].{internalId}\\n\"\n query.sql += \"LEFT JOIN [Delivery] [del] ON [del].{SONr} = [so].{SerNr} AND [del].{Status} = i|2| AND ([del].{Invalid} = i|0| OR [del].{Invalid} IS NULL)\\n\"\n query.sql += \"LEFT JOIN [DeliveryRow] [delrw] ON [delrw].{masterId} = [del].{internalId} AND [delrw].{OriginSerNr} = [so].{SerNr} AND [delrw].{OriginRowNr} = [sorw].{rowNr}\\n\"\n query.sql += \"WHERE?AND ([sorw].{ArtCode} = s|%s|)\\n\" % self.record.ArtCode\n query.sql += \"WHERE?AND ([so].{Closed} = i|0| OR [so].{Closed} IS NULL)\\n\"\n query.sql += \"WHERE?AND ([so].{Status} = i|1|)\\n\"\n query.sql += \"WHERE?AND ([so].{Invalid} = i|0| OR [so].{Invalid} IS NULL)\\n\"\n query.sql += \"GROUP BY [so].{SerNr}, [sorw].{rowNr}\\n\"\n query.sql += \"HAVING [sorw].{Qty} > SUM(IF([delrw].{Qty} IS NULL,0,[delrw].{Qty}))\\n\"\n\n self.startTable()\n self.header(\"Sales Orders\", \"Ordered\", \"Initial Delivery\", \"Delivery Picking\", \"Finished Delivery\",\"Returned\",\"Compromised\")\n if query.open():\n for rec in query:\n so = SalesOrder.bring(rec.SerNr)\n self.startRow()\n self.addValue(rec.SerNr, FieldName=\"SerNr\", Window=\"SalesOrderWindow\")\n itemsstatus = so.getItemsStatus()\n for rownr in itemsstatus:\n row = itemsstatus[rownr]\n if row['ArtCode'] == self.record.ArtCode:\n self.addValue(row['Ordered'])\n self.addValue(row['Delivery'][0])\n self.addValue(row['Delivery'][1])\n self.addValue(row['Delivery'][2])\n self.addValue(row['ReturnCustomer'][0])\n self.addValue(row['Ordered'] - row['Delivery'][2])\n self.so_ordered = row['Ordered']\n self.so_initial = row['Delivery'][0]\n self.so_picking = row['Delivery'][1]\n self.so_finished = row['Delivery'][2]\n self.so_returned = row['ReturnCustomer'][0]\n self.so_compromised += row['Ordered'] - row['Delivery'][2]\n self.endRow()\n self.startHeaderRow()\n self.addValue(\"Totales O.V.\")\n self.addValue(self.so_ordered)\n self.addValue(self.so_initial)\n self.addValue(self.so_picking)\n self.addValue(self.so_finished)\n self.addValue(self.so_returned)\n self.addValue(self.so_compromised)\n self.endHeaderRow()\n self.endTable()\n\n def showPurchaseOrders(self):\n from PurchaseOrder import PurchaseOrder\n query = Query()\n query.sql = \"SELECT [po].{SerNr}, [porw].{Qty}\\n\"\n query.sql += \"FROM [PurchaseOrder] [po]\\n\"\n query.sql += \"INNER JOIN [PurchaseOrderItemRow] [porw] ON [porw].{masterId} = [po].{internalId}\\n\"\n query.sql += \"LEFT JOIN [GoodsReceipt] [gr] ON [gr].{poNr} = [po].{SerNr} AND [gr].{Status} = i|1| AND ([gr].{Invalid} = i|0| OR [gr].{Invalid} IS NULL)\\n\"\n query.sql += \"LEFT JOIN [GoodsReceiptItemRow] [grrw] ON [grrw].{masterId} = [gr].{internalId} AND [grrw].{OriginSerNr} = [po].{SerNr} AND [grrw].{OriginRowNr} = [porw].{rowNr}\\n\"\n query.sql += \"WHERE?AND ([porw].{ArtCode} = s|%s|)\\n\" % self.record.ArtCode\n query.sql += \"WHERE?AND ([po].{Closed} = i|0| OR [po].{Closed} IS NULL)\\n\"\n query.sql += \"WHERE?AND ([po].{Status} = i|1|)\\n\"\n query.sql += \"WHERE?AND ([po].{Invalid} = i|0| OR [po].{Invalid} IS NULL)\\n\"\n query.sql += \"GROUP BY [po].{SerNr}, [porw].{rowNr}\\n\"\n query.sql += \"HAVING [porw].{Qty} > SUM(IF([grrw].{Qty} IS NULL,0,[grrw].{Qty}))\\n\"\n\n self.startTable()\n self.header(\"\", \"\", \"Goods Receipt\", \"Goods Receipt\", \"\",\"\")\n self.header(\"Purchase Orders\", \"Ordered\", \"Not Approved\", \"Approved\", \"Returned\",\"Compromised\")\n if query.open():\n for rec in query:\n po = PurchaseOrder.bring(rec.SerNr)\n self.startRow()\n self.addValue(rec.SerNr, FieldName=\"SerNr\", Window=\"PurchaseOrderWindow\")\n itemsstatus = po.getItemsStatus()\n for rownr in itemsstatus:\n row = itemsstatus[rownr]\n if row['ArtCode'] == self.record.ArtCode:\n self.addValue(row['Ordered'])\n self.addValue(row['GoodsReceipt'][0])\n self.addValue(row['GoodsReceipt'][1])\n self.addValue(row['ReturnSupplier'][0])\n self.addValue(row['Ordered'] - row['GoodsReceipt'][1])\n self.po_ordered = row['Ordered']\n self.po_initial = row['GoodsReceipt'][0]\n self.po_finished = row['GoodsReceipt'][1]\n self.po_returned = row['ReturnSupplier'][0]\n self.po_compromised += row['Ordered'] - row['GoodsReceipt'][1]\n self.endRow()\n self.startHeaderRow()\n self.addValue(\"Totales O.C.\")\n self.addValue(self.po_ordered)\n self.addValue(self.po_initial)\n self.addValue(self.po_finished)\n self.addValue(self.po_returned)\n self.addValue(self.po_compromised)\n self.endHeaderRow()\n self.endTable()\n\n def showTotals(self):\n self.startTable()\n self.header(\"Resumen\")\n self.startHeaderRow()\n self.addValue(\"Stock\")\n self.addValue(self.stock)\n self.endHeaderRow()\n self.startHeaderRow()\n self.addValue(\"Disponible Para Venta\")\n self.addValue(self.stock - self.so_compromised)\n self.endHeaderRow()\n self.startHeaderRow()\n self.addValue(\"Futuras Entradas de Mercaderia\")\n self.addValue(self.po_compromised)\n self.endHeaderRow()\n self.startHeaderRow()\n self.addValue(\"Stock Futuro\")\n self.addValue(self.stock + self.po_compromised - self.so_compromised)\n self.endHeaderRow()\n self.endTable()","sub_path":"standard/reports/ItemStatusReport.py","file_name":"ItemStatusReport.py","file_ext":"py","file_size_in_byte":7321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"464426054","text":"from __future__ import unicode_literals\nimport logging\nfrom django.template.defaultfilters import truncatewords, striptags\nfrom oscar_pesapal import exceptions\n\nlogger = logging.getLogger('oscar_pesapal')\n\ndef _format_description(description):\n if description:\n return truncatewords(striptags(description), 12)\n return ''\n\n\ndef get_txn_status(txn):\n \"\"\"\n Fetch transaction status from Pesapal\n \"\"\"\n params = {\n 'pesapal_merchant_reference': txn.pesapal_merchant_reference,\n 'pesapal_transaction_tracking_id': txn.pesapal_transaction_id,\n }\n\n # Print easy-to-read version of params for debugging\n\n logger.debug(\"Fetching payment status with params: \\n\"\n \"Transaction ID : %s\\n\"\n \"Merchant Reference : %s\",\n txn.pesapal_merchant_reference,\n txn.pesapal_transaction_id)\n\n response = get_payment_status(**params)\n if response['_comm_success']:\n txn.status = response['_payment_status']\n txn.raw_response = response['_raw_response']\n txn.response_time = response['_response_time']\n txn.save()\n\n logger.debug(\"Successful response :\\n%s\", response['_payment_status'])\n\n else:\n\n msg = \"Error retrieving status %s - %s\" % (txn.pesapal_merchant_reference,\n txn.pesapal_transaction_id)\n logger.error(msg)\n raise exceptions.PesaPalError(msg)\n","sub_path":"oscar_pesapal/gateway.py","file_name":"gateway.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"443792115","text":"from typing import Any, Callable, List, Optional, cast\r\nimport torch\r\nimport argparse\r\nimport numpy as np\r\nimport shutil\r\nimport glob\r\nimport time\r\nimport random\r\nimport os\r\nfrom torch import nn\r\nimport wandb\r\nimport pdb\r\nfrom perceptual_advex import evaluationdelta\r\nfrom perceptual_advex.utilities import add_dataset_model_arguments, \\\r\n get_dataset_model, calculate_accuracy\r\nfrom perceptual_advex.attacks import *\r\nfrom perceptual_advex.ci_attacks2 import *\r\nfrom perceptual_advex.models import FeatureModel\r\nfrom perceptual_advex.hidden_attacks import *\r\nfrom perceptual_advex.distances import L2Distance, LinfDistance\r\nfrom perceptual_advex.vae import *\r\nVAL_ITERS = 100\r\nfrom torch.optim.optimizer import Optimizer\r\nimport torchvision\r\nclass AdamW(Optimizer):\r\n \"\"\"Implements Adam algorithm.\r\n It has been proposed in `Adam: A Method for Stochastic Optimization`_.\r\n Arguments:\r\n params (iterable): iterable of parameters to optimize or dicts defining\r\n parameter groups\r\n lr (float, optional): learning rate (default: 1e-3)\r\n betas (Tuple[float, float], optional): coefficients used for computing\r\n running averages of gradient and its square (default: (0.9, 0.999))\r\n eps (float, optional): term added to the denominator to improve\r\n numerical stability (default: 1e-8)\r\n weight_decay (float, optional): weight decay (L2 penalty) (default: 0)\r\n amsgrad (boolean, optional): whether to use the AMSGrad variant of this\r\n algorithm from the paper `On the Convergence of Adam and Beyond`_\r\n .. _Adam\\: A Method for Stochastic Optimization:\r\n https://arxiv.org/abs/1412.6980\r\n .. _On the Convergence of Adam and Beyond:\r\n https://openreview.net/forum?id=ryQu7f-RZ\r\n \"\"\"\r\n\r\n def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8,\r\n weight_decay=0, amsgrad=False):\r\n if not 0.0 <= lr:\r\n raise ValueError(\"Invalid learning rate: {}\".format(lr))\r\n if not 0.0 <= eps:\r\n raise ValueError(\"Invalid epsilon value: {}\".format(eps))\r\n if not 0.0 <= betas[0] < 1.0:\r\n raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\r\n if not 0.0 <= betas[1] < 1.0:\r\n raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\r\n defaults = dict(lr=lr, betas=betas, eps=eps,\r\n weight_decay=weight_decay, amsgrad=amsgrad)\r\n super(AdamW, self).__init__(params, defaults)\r\n\r\n def __setstate__(self, state):\r\n super(AdamW, self).__setstate__(state)\r\n for group in self.param_groups:\r\n group.setdefault('amsgrad', False)\r\n\r\n def step(self, closure=None):\r\n \"\"\"Performs a single optimization step.\r\n Arguments:\r\n closure (callable, optional): A closure that reevaluates the model\r\n and returns the loss.\r\n \"\"\"\r\n loss = None\r\n if closure is not None:\r\n loss = closure()\r\n\r\n for group in self.param_groups:\r\n for p in group['params']:\r\n if p.grad is None:\r\n continue\r\n grad = p.grad.data\r\n if grad.is_sparse:\r\n raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead')\r\n amsgrad = group['amsgrad']\r\n\r\n state = self.state[p]\r\n\r\n # State initialization\r\n if len(state) == 0:\r\n state['step'] = 0\r\n # Exponential moving average of gradient values\r\n state['exp_avg'] = torch.zeros_like(p.data)\r\n # Exponential moving average of squared gradient values\r\n state['exp_avg_sq'] = torch.zeros_like(p.data)\r\n if amsgrad:\r\n # Maintains max of all exp. moving avg. of sq. grad. values\r\n state['max_exp_avg_sq'] = torch.zeros_like(p.data)\r\n\r\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\r\n if amsgrad:\r\n max_exp_avg_sq = state['max_exp_avg_sq']\r\n beta1, beta2 = group['betas']\r\n\r\n state['step'] += 1\r\n\r\n # if group['weight_decay'] != 0:\r\n # grad = grad.add(group['weight_decay'], p.data)\r\n\r\n # Decay the first and second moment running average coefficient\r\n exp_avg.mul_(beta1).add_(1 - beta1, grad)\r\n exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\r\n if amsgrad:\r\n # Maintains the maximum of all 2nd moment running avg. till now\r\n torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)\r\n # Use the max. for normalizing running avg. of gradient\r\n denom = max_exp_avg_sq.sqrt().add_(group['eps'])\r\n else:\r\n denom = exp_avg_sq.sqrt().add_(group['eps'])\r\n\r\n bias_correction1 = 1 - beta1 ** state['step']\r\n bias_correction2 = 1 - beta2 ** state['step']\r\n step_size = group['lr'] * math.sqrt(bias_correction2) / bias_correction1\r\n\r\n # p.data.addcdiv_(-step_size, exp_avg, denom)\r\n p.data.add_(-step_size, torch.mul(p.data, group['weight_decay']).addcdiv_(1, exp_avg, denom))\r\n\r\n return loss\r\n\r\nCIFAR_MEAN = [0.4914, 0.4822, 0.4465]\r\nCIFAR_STD = [0.2470, 0.2435, 0.2616]\r\n\r\ndef get_vae_template(vae_path, featured_dim, CNN_embed_dim):\r\n\r\n vae = CVAE_Normalize(d=featured_dim, z=CNN_embed_dim)\r\n vae = nn.DataParallel(vae)\r\n save_model = torch.load(vae_path)\r\n model_dict = vae.state_dict()\r\n state_dict = {k: v for k, v in save_model.items() if k in model_dict.keys()}\r\n print(state_dict.keys())\r\n model_dict.update(state_dict)\r\n vae.load_state_dict(model_dict)\r\n vae.eval()\r\n return vae\r\n\r\ndef get_eps_params(base_eps, resol):\r\n eps_list = []\r\n max_list = []\r\n min_list = []\r\n for i in range(3):\r\n eps_list.append(torch.full((resol, resol), base_eps, device='cuda'))\r\n min_list.append(torch.full((resol, resol), 0., device='cuda'))\r\n max_list.append(torch.full((resol, resol), 255., device='cuda'))\r\n\r\n eps_t = torch.unsqueeze(torch.stack(eps_list), 0)\r\n max_t = torch.unsqueeze(torch.stack(max_list), 0)\r\n min_t = torch.unsqueeze(torch.stack(min_list), 0)\r\n return eps_t, max_t, min_t\r\n\r\ndef get_cifar_params(resol):\r\n mean_list = []\r\n std_list = []\r\n for i in range(3):\r\n mean_list.append(torch.full((resol, resol), CIFAR_MEAN[i], device='cuda'))\r\n std_list.append(torch.full((resol, resol), CIFAR_STD[i], device='cuda'))\r\n return torch.unsqueeze(torch.stack(mean_list), 0), torch.unsqueeze(torch.stack(std_list), 0)\r\n\r\nclass CIFARNORMALIZE(nn.Module):\r\n def __init__(self, resol):\r\n super().__init__()\r\n self.mean, self.std = get_cifar_params(resol)\r\n\r\n def forward(self, x):\r\n '''\r\n Parameters:\r\n x: input image with pixels normalized to ([0, 1] - IMAGENET_MEAN) / IMAGENET_STD\r\n '''\r\n x = x.sub(self.mean)\r\n x = x.div(self.std)\r\n return x\r\n\r\nclass CIFARINNORMALIZE(nn.Module):\r\n def __init__(self, resol):\r\n super().__init__()\r\n self.mean, self.std = get_cifar_params(resol)\r\n\r\n def forward(self, x):\r\n '''\r\n Parameters:\r\n x: input image with pixels normalized to ([0, 1] - IMAGENET_MEAN) / IMAGENET_STD\r\n '''\r\n x = x.mul(self.std)\r\n x = x.add(*self.mean)\r\n return x\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n\r\n add_dataset_model_arguments(parser)\r\n\r\n parser.add_argument('--num_epochs', type=int, required=False,\r\n help='number of epochs trained')\r\n parser.add_argument('--batch_size', type=int, default=100,\r\n help='number of examples/minibatch')\r\n parser.add_argument('--val_batches', type=int, default=10,\r\n help='number of batches to validate on')\r\n parser.add_argument('--log_dir', type=str, default='data/logs')\r\n parser.add_argument('--parallel', type=int, default=1,\r\n help='number of GPUs to train on')\r\n\r\n\r\n parser.add_argument('--only_attack_correct', action='store_true',\r\n default=False, help='only attack examples that '\r\n 'are classified correctly')\r\n parser.add_argument('--randomize_attack', action='store_true',\r\n default=False,\r\n help='randomly choose an attack at each step')\r\n parser.add_argument('--maximize_attack', action='store_true',\r\n default=False,\r\n help='choose the attack with maximum loss')\r\n\r\n parser.add_argument('--seed', type=int, default=0, help='RNG seed')\r\n parser.add_argument('--continue', default=False, action='store_true',\r\n help='continue previous training')\r\n parser.add_argument('--keep_every', type=int, default=1,\r\n help='only keep a checkpoint every X epochs')\r\n\r\n parser.add_argument('--optim', type=str, default='sgd')\r\n parser.add_argument('--lr', type=float, metavar='LR', required=False,\r\n help='learning rate')\r\n parser.add_argument('--lr_schedule', type=str, required=False,\r\n help='comma-separated list of epochs when learning '\r\n 'rate should drop')\r\n parser.add_argument('--clip_grad', type=float, default=1.0,\r\n help='clip gradients to this value')\r\n\r\n parser.add_argument('--attack', type=str, action='append',\r\n help='attack(s) to harden against')\r\n parser.add_argument('--alpha', type=float, default=1.0,\r\n help='alpha')\r\n parser.add_argument('--re', type=float, default=1.0,\r\n help='reconstruction weight')\r\n parser.add_argument('--vae_dir', type=str, default='data/emb2048/model_epoch172.pth')\r\n args = parser.parse_args()\r\n wandb.init(config=args, name=args.log_dir.replace(\"data/\", ''))\r\n if args.optim == 'adam':\r\n if args.lr is None:\r\n args.lr = 1e-3\r\n if args.lr_schedule is None:\r\n args.lr_schedule = '50'\r\n if args.num_epochs is None:\r\n args.num_epochs = 100\r\n elif args.optim == 'sgd':\r\n if args.dataset.startswith('cifar'):\r\n if args.lr is None:\r\n args.lr = 1e-1\r\n if args.lr_schedule is None:\r\n args.lr_schedule = '75,90,100'\r\n if args.num_epochs is None:\r\n args.num_epochs = 100\r\n elif (\r\n args.dataset.startswith('imagenet')\r\n or args.dataset == 'bird_or_bicycle'\r\n ):\r\n if args.lr is None:\r\n args.lr = 1e-1\r\n if args.lr_schedule is None:\r\n args.lr_schedule = '30,60,80'\r\n if args.num_epochs is None:\r\n args.num_epochs = 90\r\n\r\n torch.manual_seed(args.seed)\r\n np.random.seed(args.seed)\r\n random.seed(args.seed)\r\n\r\n normalize = CIFARNORMALIZE(32)\r\n innormalize = CIFARINNORMALIZE(32)\r\n\r\n dataset, model = get_dataset_model(args)\r\n vae = get_vae_template(args.vae_dir, 32, 2048)\r\n\r\n if isinstance(model, FeatureModel):\r\n model.allow_train()\r\n if torch.cuda.is_available():\r\n model.cuda()\r\n vae.cuda()\r\n\r\n\r\n l2_distance = L2Distance()\r\n linf_distance = LinfDistance()\r\n l2_distance.cuda()\r\n linf_distance.cuda()\r\n\r\n train_loader, val_loader = dataset.make_loaders(\r\n workers=4, batch_size=args.batch_size)\r\n\r\n attacks = [eval(attack_str) for attack_str in args.attack]\r\n validation_attacks = [\r\n NoAttack(),\r\n DeltaAttack(model, vae, num_iterations=100, norm='linf',eps_max=8 / 255),\r\n DeltaAttack(model, vae, num_iterations=100, norm='l2',eps_max=1.0),\r\n XAttack(model, vae, num_iterations=100, norm='linf', eps_max=8 / 255),\r\n XAttack(model, vae, num_iterations=100, norm='l2', eps_max=1.0)\r\n ]\r\n\r\n iteration = 0\r\n log_dir = os.path.join(args.log_dir)\r\n if os.path.exists(log_dir):\r\n shutil.rmtree(log_dir)\r\n time.sleep(5)\r\n os.makedirs(log_dir)\r\n\r\n # optimizer\r\n optimizer: optim.Optimizer\r\n if args.optim == 'sgd':\r\n weight_decay = 1e-4 if (\r\n args.dataset.startswith('imagenet')\r\n or args.dataset == 'bird_or_bicycle'\r\n ) else 2e-4\r\n optimizer = optim.SGD([{'params': model.parameters()},\r\n {'params': vae.parameters(), 'lr': 0.1*args.lr}],\r\n lr=args.lr,\r\n momentum=0.9,\r\n weight_decay=weight_decay)\r\n elif args.optim == 'adam':\r\n optimizer = AdamW([{'params': model.parameters()},\r\n {'params': vae.parameters()}\r\n ], lr=args.lr, betas=(0.9, 0.999), weight_decay=1.e-6)\r\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=30, gamma=0.1)\r\n else:\r\n raise ValueError(f'invalid optimizer {args.optim}')\r\n\r\n # check for checkpoints\r\n def get_checkpoint_fnames():\r\n for checkpoint_fname in glob.glob(os.path.join(glob.escape(log_dir),\r\n '*.ckpt.pth')):\r\n epoch = int(os.path.basename(checkpoint_fname).split('.')[0])\r\n if epoch < args.num_epochs:\r\n yield epoch, checkpoint_fname\r\n\r\n start_epoch = 0\r\n\r\n # parallelize\r\n if torch.cuda.is_available():\r\n device_ids = list(range(args.parallel))\r\n model = nn.DataParallel(model, device_ids)\r\n vae = nn.DataParallel(vae, device_ids)\r\n attacks = [nn.DataParallel(attack, device_ids) for attack in attacks]\r\n validation_attacks = [nn.DataParallel(attack, device_ids)\r\n for attack in validation_attacks]\r\n\r\n\r\n def reconst_images(model, vae, val_loader, attacks, batch_num=2, num_samples=10):\r\n\r\n if isinstance(attacks[0], nn.DataParallel):\r\n attack_name = attacks[0].module.__class__.__name__\r\n else:\r\n attack_name = attacks[0].__class__.__name__\r\n for batch_idx, (inputs, y) in enumerate(val_loader):\r\n inputs = inputs.cuda()\r\n y = y.cuda()\r\n\r\n if batch_idx >= batch_num:\r\n break\r\n else:\r\n adv_inputs = attacks[0](inputs, y)\r\n _, _, adv_inputs_i = vae(adv_inputs)\r\n _, _, inputs_i = vae(inputs)\r\n successful_attacks = []\r\n successful_l2_distance = []\r\n successful_linf_distance = []\r\n successful_l2_distance.extend(l2_distance(\r\n inputs,\r\n adv_inputs,\r\n ).detach())\r\n successful_linf_distance.extend(linf_distance(\r\n inputs,\r\n adv_inputs,\r\n ).detach())\r\n\r\n for lpips_name, successful_lpips in [\r\n ('l2', successful_l2_distance),\r\n ('linf', successful_linf_distance)\r\n ]:\r\n wandb.log({f'train-{attack_name}-distance/{lpips_name}':\r\n wandb.Histogram(torch.stack(successful_lpips)\r\n .cpu().detach().numpy())}, commit=False)\r\n for idx in range(num_samples):\r\n successful_attacks.append(torch.cat([\r\n inputs[idx],\r\n adv_inputs[idx],\r\n torch.clamp((adv_inputs[idx] -\r\n inputs[idx]) * 3 + 0.5,\r\n 0, 1),\r\n adv_inputs_i[idx],\r\n inputs_i[idx],\r\n torch.clamp((adv_inputs_i[idx] -\r\n inputs_i[idx]) * 3 + 0.5,\r\n 0, 1),\r\n torch.clamp((inputs[idx] -\r\n inputs_i[idx]) * 3 + 0.5,\r\n 0, 1),\r\n torch.clamp((adv_inputs[idx] -\r\n adv_inputs_i[idx]) * 3 + 0.5,\r\n 0, 1),\r\n torch.clamp(((adv_inputs[idx] -\r\n adv_inputs_i[idx]) - (inputs[idx] -\r\n inputs_i[idx])) * 3 + 0.5,\r\n 0, 1),\r\n ], dim=1).detach())\r\n wandb.log({f'train-{attack_name}-images': [\r\n wandb.Image(torch.cat(successful_attacks, dim=2))]}, step=iteration)\r\n\r\n # necessary to put training loop in a function because otherwise we get\r\n # huge memory leaks\r\n def run_iter(\r\n inputs: torch.Tensor,\r\n labels: torch.Tensor,\r\n iteration: int,\r\n train: bool = True\r\n ):\r\n model.eval() # set model to eval to generate adversarial examples\r\n vae.eval()\r\n\r\n if torch.cuda.is_available():\r\n inputs = inputs.cuda()\r\n labels = labels.cuda()\r\n\r\n if args.only_attack_correct:\r\n with torch.no_grad():\r\n _, _, inputs_i = vae(inputs)\r\n orig_logits = model(inputs - inputs_i)\r\n to_attack = orig_logits.argmax(1) == labels\r\n else:\r\n to_attack = torch.ones_like(labels).bool()\r\n\r\n adv_inputs = inputs.clone()\r\n if to_attack.sum() > 0:\r\n adv_inputs[to_attack] = attacks[0](inputs[to_attack],\r\n labels[to_attack])\r\n # FORWARD PASS\r\n if train:\r\n optimizer.zero_grad()\r\n model.train() # now we set the model to train mode\r\n vae.train()\r\n\r\n mu, logvar, inputs_i = vae(inputs)\r\n adv_mu, adv_logvar, adv_inputs_i = vae(adv_inputs)\r\n output = model(torch.cat((inputs-inputs_i, inputs_i), dim=0))\r\n logits = output[0:inputs.size(0)]\r\n logits2 = output[inputs.size(0):]\r\n\r\n adv_output = model(torch.cat((adv_inputs - adv_inputs_i, adv_inputs_i), dim=0))\r\n adv_logits = adv_output[0:inputs.size(0)]\r\n adv_logits2 = adv_output[inputs.size(0):]\r\n\r\n # CONSTRUCT LOSS\r\n loss1 = F.mse_loss(normalize(adv_inputs_i), normalize(adv_inputs)) + \\\r\n F.mse_loss(normalize(inputs_i), normalize(inputs)) + \\\r\n F.mse_loss(normalize(adv_inputs_i), normalize(inputs_i)+normalize(adv_inputs)-normalize(inputs))\r\n cross_entropy = F.cross_entropy(logits, labels, reduction='none').mean() + F.cross_entropy(adv_logits, labels, reduction='none').mean()\r\n entropy = (F.softmax(logits2, dim=1) * F.log_softmax(logits2, dim=1)).sum(dim=1).mean() + (F.softmax(adv_logits2, dim=1) * F.log_softmax(adv_logits2, dim=1)).sum(dim=1).mean()\r\n loss2 = cross_entropy + entropy\r\n loss3 = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()) -0.5 * torch.sum(1 + adv_logvar - adv_mu.pow(2) - adv_logvar.exp())\r\n loss3 /= args.batch_size * 3 * 2048\r\n loss = args.re * loss1 + loss2 + loss3\r\n with torch.no_grad():\r\n norm = torch.norm(torch.abs( (normalize(adv_inputs)-normalize(inputs)+normalize(inputs_i)).view(inputs.size(0), -1)), p=2, dim=1)\r\n acc_adv = 1 - F.mse_loss(torch.div(normalize(adv_inputs)- normalize(inputs) + normalize(inputs_i), norm.unsqueeze(1).unsqueeze(2).unsqueeze(3)), \\\r\n torch.div(normalize(adv_inputs_i), norm.unsqueeze(1).unsqueeze(2).unsqueeze(3)), \\\r\n reduction = 'sum')/100\r\n # LOGGING\r\n orig_accuracy = calculate_accuracy(logits, labels)\r\n accuracy = calculate_accuracy(adv_logits, labels)\r\n wandb.log({'loss': loss.item()}, step=iteration)\r\n wandb.log({'loss1': loss1.item()}, step=iteration)\r\n wandb.log({'loss2': loss2.item()}, step=iteration)\r\n wandb.log({'loss3': loss3.item()}, step=iteration)\r\n wandb.log({'cross_entropy': cross_entropy.item()}, step=iteration)\r\n #wandb.log({'entropy': entropy.item()}, step=iteration)\r\n wandb.log({'accuracy': accuracy.item()}, step=iteration)\r\n wandb.log({'acc_adv': acc_adv.data.item()}, step=iteration)\r\n wandb.log({'orig_accuracy': orig_accuracy.item()}, step=iteration)\r\n\r\n\r\n if train:\r\n print(f'ITER {iteration:06d}',\r\n f'accuracy: {accuracy.item() * 100:5.1f}%',\r\n f'orig_accuracy: {orig_accuracy.item() * 100:5.1f}%',\r\n f'loss: {loss.item():.2f}',\r\n f'loss1: {loss1.item():.2f}',\r\n f'loss2: {loss2.item():.2f}',\r\n f'loss3: {loss3.item():.2f}',\r\n f'cross_entropy: {cross_entropy.item():.2f}',\r\n #f'entropy: {entropy.item():.2f}',\r\n f'acc_adv: {acc_adv.data.item():.2f}',\r\n sep='\\t')\r\n\r\n # OPTIMIZATION\r\n if train:\r\n loss.backward()\r\n\r\n # clip gradients and optimize\r\n nn.utils.clip_grad_value_(model.parameters(), args.clip_grad)\r\n nn.utils.clip_grad_value_(vae.parameters(), args.clip_grad)\r\n optimizer.step()\r\n\r\n for epoch in range(start_epoch, args.num_epochs):\r\n\r\n lr = optimizer.param_groups[0]['lr']\r\n print(f'START EPOCH {epoch:04d}(lr={lr:0e})')\r\n for batch_index, (inputs, labels) in enumerate(train_loader):\r\n # ramp-up learning rate for SGD\r\n run_iter(inputs, labels, iteration)\r\n iteration += 1\r\n print(f'END EPOCH {epoch:04d}')\r\n scheduler.step()\r\n if torch.cuda.is_available():\r\n torch.cuda.empty_cache()\r\n \r\n if epoch % 10 == 0:\r\n # VALIDATION\r\n print('BEGIN VALIDATION')\r\n model.eval()\r\n vae.eval()\r\n\r\n reconst_images(model, vae, val_loader, attacks)\r\n\r\n evaluationdelta.evaluate_against_attacks(\r\n model, vae, validation_attacks, val_loader, parallel=args.parallel,\r\n wandb=wandb, iteration=iteration, num_batches=args.val_batches,\r\n )\r\n\r\n checkpoint_fname = os.path.join(log_dir, f'{epoch:04d}.ckpt.pth')\r\n print(f'CHECKPOINT {checkpoint_fname}')\r\n checkpoint_model = model\r\n if isinstance(checkpoint_model, nn.DataParallel):\r\n checkpoint_model = checkpoint_model.module\r\n if isinstance(checkpoint_model, FeatureModel):\r\n checkpoint_model = checkpoint_model.model\r\n checkpoint_vae = vae\r\n if isinstance(checkpoint_vae, nn.DataParallel):\r\n checkpoint_vae = checkpoint_vae.module\r\n state = {\r\n 'model': checkpoint_model.state_dict(),\r\n 'vae': checkpoint_vae.state_dict(),\r\n 'optimizer': optimizer.state_dict(),\r\n 'iteration': iteration,\r\n 'arch': args.arch,\r\n }\r\n torch.save(state, checkpoint_fname)\r\n\r\n # delete extraneous checkpoints\r\n last_keep_checkpoint = (epoch // args.keep_every) * args.keep_every\r\n for epoch, checkpoint_fname in get_checkpoint_fnames():\r\n if epoch < last_keep_checkpoint and epoch % args.keep_every != 0:\r\n print(f' remove {checkpoint_fname}')\r\n os.remove(checkpoint_fname)\r\n\r\n print('BEGIN EVALUATION')\r\n model.eval()\r\n vae.eval()\r\n\r\n evaluationdelta.evaluate_against_attacks(\r\n model, vae, validation_attacks, val_loader, parallel=args.parallel,\r\n )\r\n print('END EVALUATION')\r\n","sub_path":"adv_disen.py","file_name":"adv_disen.py","file_ext":"py","file_size_in_byte":24192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"10802104","text":"from time import time\n\ndef check_left(s):\n\tif(s[1]!=s[0]):\n\t\tch = 0\n\t\tfor cz in range(len(s)):\n\t\t\tif(cz>ch):\n\t\t\t\tif(s[cz]!=s[ch]):\n\t\t\t\t\ts[cz] = s[ch]\n\t\t\t\telse:\n\t\t\t\t\tbreak\n\treturn s\n\ndef check_right(s):\n\tif(s[len(s)-2]!=s[len(s)-1]):\n\t\tch = len(s)-1\n\t\ti=len(s)-2\n\t\twhile(i>0):\n\t\t\tif(s[i]!=s[ch]):\n\t\t\t\ts[i] = s[ch]\n\t\t\telse:\n\t\t\t\tbreak\n\t\t\ti-=1\n\treturn s\n\n\n\nx = int(input()) \nfor e in range(x):\n\tt1 = time()\n\tnbToken = input()\n\ttoken_raw = input()\n\ttoken_list = [int(token) for token in token_raw]\n\ttoken = [None]*2\n\ttoken[0] = token_list.copy()\n\ttoken[1] = token_list.copy()\n\twhile True:\n\t\tres = 0\n\t\tr = token[0]\n\t\tl = token[1]\n\t\tr.append(0)\n\t\tl.insert(0,0)\n\t\tl = check_left(l)\n\t\tr = check_right(r)\n\t\tprint(l,r)\n\t\tif(r.count(1)==len(r) or r.count(0)==len(r)):\n\t\t\tres = r\n\t\t\tbreak\n\t\tif(l.count(1)==len(l) or l.count(0)==len(l)):\n\t\t\tres = l\n\t\t\tbreak\n\t\tr = token[0]\n\t\tl = token[1]\n\t\tr.append(1)\n\t\tl.insert(0,1)\n\t\tl = check_left(l)\n\t\tr = check_right(r)\n\t\tprint(l,r)\n\t\tif(res!=0):\n\t\t\t#print(res)\n\t\t\tbreak\n\tt2 = time()\n\tprint(t2-t1,token_list)","sub_path":"tryagain/moretour.py","file_name":"moretour.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"249635469","text":"import csv\nfrom Databases import Database\nimport re\n\ncsvData = []\n\n\ndef spamUpdate(tweet_id, spam, clear_text, training):\n Database.unTweeterizeTable.update_item(\n Key={'tweet_id': tweet_id},\n UpdateExpression=\"set is_spam=:s, clear_text=:c, is_training=:t\",\n ExpressionAttributeValues={\n ':s': spam,\n ':c': clear_text,\n ':t': training\n },\n ReturnValues=\"UPDATED_NEW\"\n )\n\nwith open('test.csv', 'rb') as f:\n reader = csv.DictReader(f)\n for row in reader:\n tweet_id = row[\"tweet_id\"].strip()\n\n spam = False\n\n if row[\"SPAM\"].strip() == 'x':\n spam = True\n\n # print(\"id: {} - s: {} | i: {}\".format(tweet_id, spam))\n csvData.append((tweet_id, spam))\n\n\nallTweets = Database.getAll(Database.unTweeterizeTable)\n\n\ndef remove_user(userTweet):\n userTweet = re.sub('@[^\\s]+', 'AT_USER', userTweet)\n return userTweet\n\n\nfor tweet in allTweets:\n\n tweetCsv = filter(lambda x: x[0] == tweet[\"tweet_id\"], csvData)\n\n if len(tweetCsv) == 1:\n tweet[\"is_spam\"] = tweetCsv[0][1]\n tweet[\"clear_text\"] = remove_user(tweet[\"clear_text\"])\n tweet[\"is_training\"] = True\n\n spamUpdate(tweet[\"tweet_id\"], tweet[\"is_spam\"], tweet[\"clear_text\"], tweet[\"is_training\"])\n\nprint(\"\\n\\nACABOU!!!\\n\\n\")","sub_path":"Scripts/CsvToTable.py","file_name":"CsvToTable.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"119765943","text":"######################################################################################\n# Copyright (c) muhanzhang, D-VAE, NeurIPS 2019 [GitHub D-VAE]\n# Modified by Hayeon Lee, Eunyoung Hyung, MetaD2A, ICLR2021, 2021. 03 [GitHub MetaD2A]\n######################################################################################\nimport math\nimport random\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\nimport numpy as np\nimport igraph\nimport pdb\nfrom set_encoder.setenc_models import SetPool\n\n\nclass GeneratorModel(nn.Module):\n def __init__(self, args, graph_config):\n super(GeneratorModel, self).__init__()\n self.max_n = graph_config['max_n'] # maximum number of vertices\n self.nvt = args.nvt # number of vertex types\n self.START_TYPE = graph_config['START_TYPE']\n self.END_TYPE = graph_config['END_TYPE']\n self.hs = args.hs # hidden state size of each vertex\n self.nz = args.nz # size of latent representation z\n self.gs = args.hs # size of graph state\n self.bidir = True # whether to use bidirectional encoding\n self.vid = True\n self.device = None\n self.num_sample = args.num_sample\n\n if self.vid:\n self.vs = self.hs + self.max_n # vertex state size = hidden state + vid\n else:\n self.vs = self.hs\n \n # 0. encoding-related\n self.grue_forward = nn.GRUCell(self.nvt, self.hs) # encoder GRU\n self.grue_backward = nn.GRUCell(self.nvt, self.hs) # backward encoder GRU\n self.enc_g_mu = nn.Linear(self.gs, self.nz) # latent mean\n self.enc_g_var = nn.Linear(self.gs, self.nz) # latent var\n self.fc1 = nn.Linear(self.gs, self.nz) # latent mean\n self.fc2 = nn.Linear(self.gs, self.nz) # latent logvar\n\n # 1. decoding-related\n self.grud = nn.GRUCell(self.nvt, self.hs) # decoder GRU\n self.fc3 = nn.Linear(self.nz, self.hs) # from latent z to initial hidden state h0\n self.add_vertex = nn.Sequential(\n nn.Linear(self.hs, self.hs * 2),\n nn.ReLU(),\n nn.Linear(self.hs * 2, self.nvt)\n ) # which type of new vertex to add f(h0, hg)\n self.add_edge = nn.Sequential(\n nn.Linear(self.hs * 2, self.hs * 4),\n nn.ReLU(),\n nn.Linear(self.hs * 4, 1)\n ) # whether to add edge between v_i and v_new, f(hvi, hnew)\n self.decoding_gate = nn.Sequential(\n nn.Linear(self.vs, self.hs),\n nn.Sigmoid()\n )\n self.decoding_mapper = nn.Sequential(\n nn.Linear(self.vs, self.hs, bias=False),\n ) # disable bias to ensure padded zeros also mapped to zeros\n\n # 2. gate-related\n self.gate_forward = nn.Sequential(\n nn.Linear(self.vs, self.hs),\n nn.Sigmoid()\n )\n self.gate_backward = nn.Sequential(\n nn.Linear(self.vs, self.hs),\n nn.Sigmoid()\n )\n self.mapper_forward = nn.Sequential(\n nn.Linear(self.vs, self.hs, bias=False),\n ) # disable bias to ensure padded zeros also mapped to zeros\n self.mapper_backward = nn.Sequential(\n nn.Linear(self.vs, self.hs, bias=False),\n )\n \n # 3. bidir-related, to unify sizes\n if self.bidir:\n self.hv_unify = nn.Sequential(\n nn.Linear(self.hs * 2, self.hs),\n )\n self.hg_unify = nn.Sequential(\n nn.Linear(self.gs * 2, self.gs),\n )\n\n # 4. other\n self.relu = nn.ReLU()\n self.sigmoid = nn.Sigmoid()\n self.tanh = nn.Tanh()\n self.logsoftmax1 = nn.LogSoftmax(1)\n \n # 6. predictor\n np = self.gs\n self.intra_setpool = SetPool(dim_input=512, \n num_outputs=1, \n dim_output=self.nz, \n dim_hidden=self.nz, \n mode='sabPF')\n self.inter_setpool = SetPool(dim_input=self.nz, \n num_outputs=1, \n dim_output=self.nz, \n dim_hidden=self.nz, \n mode='sabPF')\n self.set_fc = nn.Sequential(\n nn.Linear(512, self.nz),\n nn.ReLU())\n\n def get_device(self):\n if self.device is None:\n self.device = next(self.parameters()).device\n return self.device\n \n def _get_zeros(self, n, length):\n return torch.zeros(n, length).to(self.get_device()) # get a zero hidden state\n \n def _get_zero_hidden(self, n=1):\n return self._get_zeros(n, self.hs) # get a zero hidden state\n \n def _one_hot(self, idx, length):\n if type(idx) in [list, range]:\n if idx == []:\n return None\n idx = torch.LongTensor(idx).unsqueeze(0).t()\n x = torch.zeros((len(idx), length)\n ).scatter_(1, idx, 1).to(self.get_device())\n else:\n idx = torch.LongTensor([idx]).unsqueeze(0)\n x = torch.zeros((1, length)\n ).scatter_(1, idx, 1).to(self.get_device())\n return x\n \n def _gated(self, h, gate, mapper):\n return gate(h) * mapper(h)\n \n def _collate_fn(self, G):\n return [g.copy() for g in G]\n \n def _propagate_to(self, G, v, propagator, \n H=None, reverse=False, gate=None, mapper=None):\n # propagate messages to vertex index v for all graphs in G\n # return the new messages (states) at v\n G = [g for g in G if g.vcount() > v]\n if len(G) == 0:\n return\n if H is not None:\n idx = [i for i, g in enumerate(G) if g.vcount() > v]\n H = H[idx]\n v_types = [g.vs[v]['type'] for g in G]\n X = self._one_hot(v_types, self.nvt)\n H_name = 'H_forward' # name of the hidden states attribute\n H_pred = [[g.vs[x][H_name] for x in g.predecessors(v)] for g in G]\n if self.vid:\n vids = [self._one_hot(g.predecessors(v), self.max_n) for g in G]\n if reverse:\n H_name = 'H_backward' # name of the hidden states attribute\n H_pred = [[g.vs[x][H_name] for x in g.successors(v)] for g in G]\n if self.vid:\n vids = [self._one_hot(g.successors(v), self.max_n) for g in G]\n gate, mapper = self.gate_backward, self.mapper_backward\n else:\n H_name = 'H_forward' # name of the hidden states attribute\n H_pred = [\n [g.vs[x][H_name] for x in g.predecessors(v)] for g in G]\n if self.vid:\n vids = [\n self._one_hot(g.predecessors(v), self.max_n) for g in G]\n if gate is None:\n gate, mapper = self.gate_forward, self.mapper_forward\n if self.vid:\n H_pred = [[torch.cat(\n [x[i], y[i:i + 1]], 1) for i in range(len(x))\n ] for x, y in zip(H_pred, vids)]\n # if h is not provided, use gated sum of v's predecessors' states as the input hidden state\n if H is None:\n max_n_pred = max([len(x) for x in H_pred]) # maximum number of predecessors\n if max_n_pred == 0:\n H = self._get_zero_hidden(len(G))\n else:\n H_pred = [torch.cat(h_pred + \n [self._get_zeros(max_n_pred - len(h_pred), \n self.vs)], 0).unsqueeze(0)\n for h_pred in H_pred] # pad all to same length\n H_pred = torch.cat(H_pred, 0) # batch * max_n_pred * vs\n H = self._gated(H_pred, gate, mapper).sum(1) # batch * hs\n Hv = propagator(X, H)\n for i, g in enumerate(G):\n g.vs[v][H_name] = Hv[i:i + 1]\n return Hv\n \n def _propagate_from(self, G, v, propagator, H0=None, reverse=False):\n # perform a series of propagation_to steps starting from v following a topo order\n # assume the original vertex indices are in a topological order\n if reverse:\n prop_order = range(v, -1, -1)\n else:\n prop_order = range(v, self.max_n)\n Hv = self._propagate_to(G, v, propagator, H0, reverse=reverse) # the initial vertex\n for v_ in prop_order[1:]:\n self._propagate_to(G, v_, propagator, reverse=reverse)\n return Hv\n \n def _update_v(self, G, v, H0=None):\n # perform a forward propagation step at v when decoding to update v's state\n # self._propagate_to(G, v, self.grud, H0, reverse=False)\n self._propagate_to(G, v, self.grud, H0, \n reverse=False, gate=self.decoding_gate, \n mapper=self.decoding_mapper)\n return\n \n def _get_vertex_state(self, G, v):\n # get the vertex states at v\n Hv = []\n for g in G:\n if v >= g.vcount():\n hv = self._get_zero_hidden()\n else:\n hv = g.vs[v]['H_forward']\n Hv.append(hv)\n Hv = torch.cat(Hv, 0)\n return Hv\n\n def _get_graph_state(self, G, decode=False):\n # get the graph states\n # when decoding, use the last generated vertex's state as the graph state\n # when encoding, use the ending vertex state or unify the starting and ending vertex states\n Hg = []\n for g in G:\n hg = g.vs[g.vcount() - 1]['H_forward']\n if self.bidir and not decode: # decoding never uses backward propagation\n hg_b = g.vs[0]['H_backward']\n hg = torch.cat([hg, hg_b], 1)\n Hg.append(hg)\n Hg = torch.cat(Hg, 0)\n if self.bidir and not decode:\n Hg = self.hg_unify(Hg)\n return Hg\n\n def graph_encode(self, G):\n # encode graphs G into latent vectors\n if type(G) != list:\n G = [G]\n self._propagate_from(G, 0, self.grue_forward, \n H0=self._get_zero_hidden(len(G)), reverse=False)\n if self.bidir:\n self._propagate_from(G, self.max_n - 1, self.grue_backward,\n H0=self._get_zero_hidden(len(G)), reverse=True)\n Hg = self._get_graph_state(G)\n mu, logvar = self.enc_g_mu(Hg), self.enc_g_var(Hg)\n return mu, logvar\n\n\n def set_encode(self, X):\n proto_batch = []\n for x in X: # X.shape: [32, 400, 512]\n cls_protos = self.intra_setpool(\n x.view(-1, self.num_sample, 512)).squeeze(1)\n proto_batch.append(\n self.inter_setpool(cls_protos.unsqueeze(0)))\n v = torch.stack(proto_batch).squeeze()\n mu, logvar = self.fc1(v), self.fc2(v)\n return mu, logvar\n\n\n def reparameterize(self, mu, logvar, eps_scale=0.01):\n # return z ~ N(mu, std)\n if self.training:\n std = logvar.mul(0.5).exp_()\n eps = torch.randn_like(std) * eps_scale\n return eps.mul(std).add_(mu)\n else:\n return mu\n\n def _get_edge_score(self, Hvi, H, H0):\n # compute scores for edges from vi based on Hvi, H (current vertex) and H0\n # in most cases, H0 need not be explicitly included since Hvi and H contain its information\n return self.sigmoid(self.add_edge(torch.cat([Hvi, H], -1)))\n\n def graph_decode(self, z, stochastic=True):\n # decode latent vectors z back to graphs\n # if stochastic=True, stochastically sample each action from the predicted distribution;\n # otherwise, select argmax action deterministically.\n H0 = self.tanh(self.fc3(z)) # or relu activation, similar performance\n G = [igraph.Graph(directed=True) for _ in range(len(z))]\n for g in G:\n g.add_vertex(type=self.START_TYPE)\n self._update_v(G, 0, H0)\n finished = [False] * len(G)\n for idx in range(1, self.max_n):\n # decide the type of the next added vertex\n if idx == self.max_n - 1: # force the last node to be end_type\n new_types = [self.END_TYPE] * len(G)\n else:\n Hg = self._get_graph_state(G, decode=True)\n type_scores = self.add_vertex(Hg)\n if stochastic:\n type_probs = F.softmax(type_scores, 1\n ).cpu().detach().numpy()\n new_types = [np.random.choice(range(self.nvt), \n p=type_probs[i]) for i in range(len(G))]\n else:\n new_types = torch.argmax(type_scores, 1)\n new_types = new_types.flatten().tolist()\n for i, g in enumerate(G):\n if not finished[i]:\n g.add_vertex(type=new_types[i])\n self._update_v(G, idx)\n \n # decide connections\n edge_scores = []\n for vi in range(idx - 1, -1, -1):\n Hvi = self._get_vertex_state(G, vi)\n H = self._get_vertex_state(G, idx)\n ei_score = self._get_edge_score(Hvi, H, H0)\n if stochastic:\n random_score = torch.rand_like(ei_score)\n decisions = random_score < ei_score\n else:\n decisions = ei_score > 0.5\n for i, g in enumerate(G):\n if finished[i]:\n continue\n if new_types[i] == self.END_TYPE:\n # if new node is end_type, connect it to all loose-end vertices (out_degree==0)\n end_vertices = set([\n v.index for v in g.vs.select(_outdegree_eq=0)\n if v.index != g.vcount() - 1])\n for v in end_vertices:\n g.add_edge(v, g.vcount() - 1)\n finished[i] = True\n continue\n if decisions[i, 0]:\n g.add_edge(vi, g.vcount() - 1)\n self._update_v(G, idx)\n \n for g in G:\n del g.vs['H_forward'] # delete hidden states to save GPU memory\n return G\n \n\n def loss(self, mu, logvar, G_true, beta=0.005):\n # compute the loss of decoding mu and logvar to true graphs using teacher forcing\n # ensure when computing the loss of step i, steps 0 to i-1 are correct\n z = self.reparameterize(mu, logvar)\n H0 = self.tanh(self.fc3(z)) # or relu activation, similar performance\n G = [igraph.Graph(directed=True) for _ in range(len(z))]\n for g in G:\n g.add_vertex(type=self.START_TYPE)\n self._update_v(G, 0, H0)\n res = 0 # log likelihood\n for v_true in range(1, self.max_n):\n # calculate the likelihood of adding true types of nodes\n # use start type to denote padding vertices since start type only appears for vertex 0\n # and will never be a true type for later vertices, thus it's free to use\n true_types = [g_true.vs[v_true]['type'] \n if v_true < g_true.vcount()\n else self.START_TYPE for g_true in G_true]\n Hg = self._get_graph_state(G, decode=True)\n type_scores = self.add_vertex(Hg)\n # vertex log likelihood\n vll = self.logsoftmax1(type_scores)[\n np.arange(len(G)), true_types].sum()\n res = res + vll\n for i, g in enumerate(G):\n if true_types[i] != self.START_TYPE:\n g.add_vertex(type=true_types[i])\n self._update_v(G, v_true)\n \n # calculate the likelihood of adding true edges\n true_edges = []\n for i, g_true in enumerate(G_true):\n true_edges.append(g_true.get_adjlist(igraph.IN)[v_true] \n if v_true < g_true.vcount() else [])\n edge_scores = []\n for vi in range(v_true - 1, -1, -1):\n Hvi = self._get_vertex_state(G, vi)\n H = self._get_vertex_state(G, v_true)\n ei_score = self._get_edge_score(Hvi, H, H0)\n edge_scores.append(ei_score)\n for i, g in enumerate(G):\n if vi in true_edges[i]:\n g.add_edge(vi, v_true)\n self._update_v(G, v_true)\n edge_scores = torch.cat(edge_scores[::-1], 1)\n \n ground_truth = torch.zeros_like(edge_scores)\n idx1 = [i for i, x in enumerate(true_edges) \n for _ in range(len(x))]\n idx2 = [xx for x in true_edges for xx in x]\n ground_truth[idx1, idx2] = 1.0\n \n # edges log-likelihood\n ell = - F.binary_cross_entropy(\n edge_scores, ground_truth, reduction='sum')\n res = res + ell\n \n res = -res # convert likelihood to loss\n kld = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())\n return res + beta * kld, res, kld","sub_path":"MetaD2A_nas_bench_201/generator/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":15219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"102091827","text":"# 定義したクラスを含むモジュールを取り込む\nfrom car import Van\nfrom car import Camper\n\n# ワゴン車を作成\ncar1 = Van(\"Taro\")\ncar1.turn_left()\ncar1.show_status()\n\n# キャンピングカーを作成\ncar2 = Camper(\"Jiro\")\ncar2.turn_right()\ncar2.show_status()\ncar2.make_ice()\n","sub_path":"use-car.py","file_name":"use-car.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"419057550","text":"import logging\nimport json\n\nfrom alpaca_trade_api.stream import Stream\nfrom alpaca_trade_api.common import URL\n\n\nlog = logging.getLogger(__name__)\n\n\nasync def print_trade(t):\n print('trade', t)\n\n\nasync def print_quote(q):\n print('quote', q)\n\n\nasync def print_trade_update(tu):\n print('trade update', tu)\n\n\ndef main():\n logging.basicConfig(level=logging.INFO)\n \n with open(\"./config.json\",\"rb\") as file:\n config = json.load(file)\n \n feed = 'iex' # <- replace to SIP if you have PRO subscription\n stream = Stream(key_id=config['alpaca_key_id'],\n secret_key=config['alpaca_secret_key'],\n base_url=URL(config['alpaca_base_url']),\n data_feed=feed, raw_data=True)\n stream.subscribe_trade_updates(print_trade_update)\n stream.subscribe_trades(print_trade, 'AAPL')\n stream.subscribe_quotes(print_quote, 'IBM')\n\n @stream.on_bar('MSFT')\n async def _(bar):\n print('bar', bar)\n\n @stream.on_status(\"*\")\n async def _(status):\n print('status', status)\n\n stream.run()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"app/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"290056991","text":"##############################################################################\n\nimport FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"Digitze\")\n\nprocess.load('Configuration.StandardSequences.Services_cff')\nprocess.load('SimGeneral.HepPDTESSource.pythiapdt_cfi')\nprocess.load('FWCore.MessageService.MessageLogger_cfi')\nprocess.load('Configuration.EventContent.EventContent_cff')\nprocess.load('SimGeneral.MixingModule.mixNoPU_cfi')\nprocess.load('Configuration.Geometry.GeometryExtended2017Reco_cff')\nprocess.load('Configuration.StandardSequences.MagneticField_38T_PostLS1_cff')\nprocess.load('Configuration.StandardSequences.Digi_cff')\nprocess.load('Configuration.StandardSequences.SimL1Emulator_cff')\nprocess.load('Configuration.StandardSequences.DigiToRaw_cff')\nprocess.load('Configuration.StandardSequences.EndOfProcess_cff')\nprocess.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')\n\nprocess.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32(-1)\n)\n\nprocess.source = cms.Source(\"PoolSource\", \n fileNames = cms.untracked.vstring(\n# 'file:/afs/cern.ch/work/d/dkotlins/public//MC/mu/pt100/simhits/simHits1.root'\n 'file:simHits.root'\n# 'file:sims.root'\n ),\n dropDescendantsOfDroppedBranches = cms.untracked.bool(False),\n inputCommands = cms.untracked.vstring('keep *', \n 'drop *_genParticles_*_*', \n 'drop *_genParticlesForJets_*_*', \n 'drop *_kt4GenJets_*_*', \n 'drop *_kt6GenJets_*_*', \n 'drop *_iterativeCone5GenJets_*_*', \n 'drop *_ak4GenJets_*_*', \n 'drop *_ak7GenJets_*_*', \n 'drop *_ak8GenJets_*_*', \n 'drop *_ak4GenJetsNoNu_*_*', \n 'drop *_ak8GenJetsNoNu_*_*', \n 'drop *_genCandidatesForMET_*_*', \n 'drop *_genParticlesForMETAllVisible_*_*', \n 'drop *_genMetCalo_*_*', \n 'drop *_genMetCaloAndNonPrompt_*_*', \n 'drop *_genMetTrue_*_*', \n 'drop *_genMetIC5GenJs_*_*'),\n secondaryFileNames = cms.untracked.vstring()\n)\n\nfrom Configuration.AlCa.GlobalTag import GlobalTag\nprocess.GlobalTag = GlobalTag(process.GlobalTag, 'auto:upgrade2017', '')\n\nprocess.output = cms.OutputModule(\"PoolOutputModule\",\n dataset = cms.untracked.PSet(\n dataTier = cms.untracked.string('GEN-SIM-DIGI-RAW'),\n filterName = cms.untracked.string('')\n ),\n eventAutoFlushCompressedSize = cms.untracked.int32(1048576),\n outputCommands = process.FEVTDEBUGHLTEventContent.outputCommands,\n #outputCommands = cms.untracked.vstring('drop *','keep *_*_*_Test'),\n splitLevel = cms.untracked.int32(0),\n# fileName = cms.untracked.string('file:/afs/cern.ch/work/d/dkotlins/public/MC/mu/pt100/digis/digis1.root')\n fileName = cms.untracked.string('file:digis.root')\n\n)\n\n# Other statements\nprocess.mix.digitizers = cms.PSet(process.theDigitizersValid)\n\n# Path and EndPath definitions\nprocess.digitisation_step = cms.Path(process.pdigi_valid)\nprocess.L1simulation_step = cms.Path(process.SimL1Emulator)\nprocess.digi2raw_step = cms.Path(process.DigiToRaw)\nprocess.endjob_step = cms.EndPath(process.endOfProcess)\nprocess.output_step = cms.EndPath(process.output)\n\n# Schedule definition\n#process.schedule = cms.Schedule(process.digitisation_step,process.L1simulation_step,process.digi2raw_step,process.endjob_step,process.output_step)\nprocess.schedule = cms.Schedule(process.digitisation_step,process.endjob_step,process.output_step)\n\n# customisation of the process.\n\n# Automatic addition of the customisation function from SLHCUpgradeSimulations.Configuration.combinedCustoms\nfrom SLHCUpgradeSimulations.Configuration.combinedCustoms import cust_2017 \n\n#call to customisation function cust_2017 imported from SLHCUpgradeSimulations.Configuration.combinedCustoms\nprocess = cust_2017(process)\n\n# End of customisation functions\n\n\n\n\n#process.g4SimHits.Generator.HepMCProductLabel = 'source'\n# modify digitizer parameters\n#process.simSiPixelDigis.pixel.ThresholdInElectrons_BPix = 3500.0 \n#This process is to run the digitizer, pixel gitizer is now clled by the mix module\n#process.p1 = cms.Path(process.simSiPixelDigis)\n#process.outpath = cms.EndPath(process.o1)\n\n\n","sub_path":"HitAnalyzer/phase1/testDigitizer.py","file_name":"testDigitizer.py","file_ext":"py","file_size_in_byte":4133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"156861627","text":"#!/usr/bin/env python3\n \nimport socket # Needed for socket creation\nimport fcntl # Needed libraries\nimport os # Needed libraries\nimport ntplib # Needed for NCP time (syncronize the time between source and destination)\nfrom datetime import datetime # Needed for NCP time\n\nHOST = '10.10.3.2' # local adress (used with r1)\nHOST2 = '10.10.5.2' # local adress (used with r2)\nPORT = 31337 # port that message is received (if sent by r1)\nPORT2 = 31338 # port that message is received (if sent by r2)\n\n\nsocks = [] # list of sockets (sockets will be appended)\n\nsock1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nsock1.bind((HOST, PORT))\nfcntl.fcntl(sock1, fcntl.F_SETFL, os.O_NONBLOCK)\nsocks.append(sock1) # append the first socket to socks (socket with r1)\n\nsock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) \nsock2.bind((HOST2, PORT2))\nfcntl.fcntl(sock2, fcntl.F_SETFL, os.O_NONBLOCK)\nsocks.append(sock2) # append the second socket to socks (socket with r2)\n\nwhile True:\n for s in socks: # for every socket in socks\n try: \n msg = s.recv(1024) # receive message\n c = ntplib.NTPClient() # get the current time from time.google.com\n response = c.request('time.google.com', version=3) # get the current time from time.google.com\n time_d = datetime.fromtimestamp(response.orig_time) # get the current time from time.google.com\n time_s = datetime.strptime(str(msg), \"%Y-%m-%d %H:%M:%S.%f\") # get the source time from the message\n print(time_d-time_s) # print the time it takes for a message to get from source the destination \n # Compare with the time printed by the source\n except: # continue listening\n continue\n","sub_path":"TP_Part1_02/destination.py","file_name":"destination.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"169237364","text":"\"\"\"\n\"\"\"\nimport logging\nimport collections\n\nfrom PySide.QtCore import QObject, QEvent\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass AbstractEventDispatcher(QObject):\n \"\"\"Abstract dispatcher class.\n\n Attributes:\n events (list): Events to be tracked\n \"\"\"\n events = []\n\n def dispatch_events(self, event):\n raise NotImplementedError()\n\n def eventFilter(self, obj, event):\n raise NotImplementedError()\n\n\nclass BaseObserver(AbstractEventDispatcher):\n\n def __init__(self):\n super(BaseObserver, self).__init__()\n self.watches = dict()\n self.handlers = collections.defaultdict(set)\n\n def add_handler_for_watch(self, event_type, event_handler):\n logger.debug('Adding handler: {}, to watcher: {}'.format(event_type,\n event_handler))\n self.handlers[event_type].add(event_handler())\n\n def dispatch_events(self, event):\n for handler in self.handlers[event.type()]:\n result = handler.dispatch(event)\n logger.debug('event filter result: {} from: {}'.format(result, handler))\n return result\n\n def eventFilter(self, obj, event):\n # Adds the observer to new child windows created from the main application.\n if event.type() == QEvent.ChildAdded:\n self._temp_child = event.child()\n elif event.type() == QEvent.ChildPolished:\n if self._temp_child.objectName() not in self.watches:\n self.watches[self._temp_child.objectName()] = event.child()\n\n # Only work on events specified.\n if event.type() not in self.events:\n return False\n else:\n return self.dispatch_events(event)\n","sub_path":"mamqtkeys/qtkeys/observers.py","file_name":"observers.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"285296473","text":"def ask_ok(prompt, retries=4, reminder='Please try again!'):\n while True:\n ok = input(prompt)\n if ok in ('y', 'ye', 'yes'):\n return True\n if ok in ('n', 'no', 'nope'):\n return False\n retries -= 1\n if retries < 0:\n raise ValueError('Invalid user response')\n print(reminder)\n\n\n# ask_ok('wut')\n# ask_ok('wut', 2)\n# ask_ok('wut', 2, 'rumpa')\n\ni = [5]\n\n\ndef f(arg=i):\n print(arg)\n arg.append(2)\n\n\ni = 6\nf() # prints [5]\nf() # prints [5, 2]...\nf()\nf()\n\n\ndef g(n=1, acc=[]):\n acc.append(n)\n print(acc)\n\n\ng()\ng()\ng()\ng()\ng()\n","sub_path":"python3/4.7.1.default_function_argument.py","file_name":"4.7.1.default_function_argument.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"419624754","text":"from selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom components.base_component import BaseComponent\n\n\nclass KeySearchFormLocators:\n def __init__(self):\n self.root = '//div[@class=\"main-search-form\"]'\n self.keyword_selector = '//input[@class=\"keywords-search__input\"]'\n self.search_button = '//button[@class=\"main-search-form__btn\"]'\n self.search_check_box = '//div[@class=\"option-type\"]'\n self.search_check_box_input = 'option-type__checkbox'\n self.search_check_box_name = 'option-type__name'\n\n\nclass KeySearchForm(BaseComponent):\n def __init__(self, driver):\n super(KeySearchForm, self).__init__(driver)\n\n self.wait = WebDriverWait(self.driver, 20)\n self.locators = KeySearchFormLocators()\n\n def input_keyword(self, key: str) -> None:\n element = self.wait.until(\n EC.element_to_be_clickable((By.XPATH, self.locators.keyword_selector)))\n element.clear()\n\n element.send_keys(key)\n\n actions = ActionChains(self.driver)\n actions.move_to_element(element).perform()\n\n def click_on_search(self) -> None:\n element = self.wait.until(\n EC.element_to_be_clickable((By.XPATH, self.locators.search_button)))\n element.click()\n\n def click_on_search_checkbox(self) -> str:\n element = self.wait.until(\n EC.visibility_of_element_located((By.XPATH, self.locators.search_check_box)))\n\n checkBoxInput = element.find_element_by_class_name(self.locators.search_check_box_input)\n checkBoxInput.click()\n checkBoxName = element.find_element_by_class_name(self.locators.search_check_box_name)\n return checkBoxName.get_attribute('innerText')\n","sub_path":"components/key_search_form.py","file_name":"key_search_form.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"132510887","text":"import fsm\nimport select \nfrom time import sleep\nimport sys\nfrom key import isData , getKey\nfrom funct_file import *\n\n\nf = fsm.fsm(); # finite state machine\n\n \n##global deltat\ndeltat=1.0\n# functions (actions of the fsm)\n# example of a function doRun \ndef doRun():\n nao_run() # do some work\n sleep(deltat)\n newKey,val = getKey() # check if key pressed\n event=\"Wait\" # define the default event\n if newKey:\n if val==\"l\":\n event = \"Left\"\n if val == \"r\":\n event = \"Right\"\n if val == \"s\":\n event = \"Stop\"# new event if key \"w\" is pressed\n return event # return event to be able to define the transition\n# define here all the other functions (actions) of the fsm \n\n\ndef doStop():\n nao_pls() # do some work\n sleep(deltat)\n newKey,val = getKey() # check if key pressed\n event=\"Stop\" # define the default event\n if newKey:\n if val==\"u\":\n event = \"StandUp\"\n return event\n\ndef doStandUp():\n nao_stand_up()\n sleep(deltat)\n newKey , val = getKey()\n event = \"Wait\"\n if newKey:\n if val==\"s\":\n event=\"Stop\"\n if val==\"g\":\n event=\"Go\"\n if val==\"l\":\n event=\"Left\"\n if val==\"r\":\n event=\"Right\"\n return event\n \ndef doWait():\n## print(\"I m waiting for a keyboard input\") \n sleep(deltat)\n newKey , val = getKey()\n event = \"Wait\"\n if newKey:\n if val==\"s\":\n event=\"Stop\"\n if val==\"g\":\n event=\"Go\"\n if val==\"l\":\n event=\"Left\"\n if val==\"r\":\n event=\"Right\"\n return event\n \n \ndef doRight():\n nao_turn_right() # do some work\n sleep(deltat)\n newKey,val = getKey() # check if key pressed\n event=\"Wait\" # define the default event\n if newKey:\n if val == \"s\":\n event=\"Stop\"\n if val == \"g\":\n event = \"Go\"\n if val == \"l\":\n event = \"Left\"\n if val == \"r\":\n event = \"Right\"\n return event \n \ndef doLeft():\n nao_turn_left() # do some work\n sleep(deltat)\n newKey,val = getKey() # check if key pressed\n event=\"Wait\" # define the default event\n if newKey:\n if val == \"s\":\n event=\"Stop\"\n if val == \"g\":\n event = \"Go\"\n if val == \"l\":\n event = \"Left\"\n if val == \"r\":\n event = \"Right\"\n return event \n \n\nif __name__== \"__main__\":\n \n # define the states\n f.add_state (\"Idle\")\n f.add_state(\"Standing\")\n f.add_state (\"Running\")\n f.add_state (\"Turning_Left\")\n f.add_state (\"Turning_Right\")\n f.add_state (\"Waiting\")\n\n # defines the events \n f.add_event (\"Stop\")\n f.add_event(\"StandUp\")\n f.add_event (\"Go\")\n f.add_event (\"Left\")\n f.add_event (\"Right\")\n f.add_event (\"Wait\")\n \n f.add_transition (\"Idle\" , \"Idle\" , \"Stop\" , doStop)\n f.add_transition (\"Idle\" , \"Standing\" , \"StandUp\" , doStandUp)\n \n f.add_transition (\"Standing\",\"Idle\",\"Stop\",doStop)\n f.add_transition (\"Standing\",\"Running\",\"Go\",doRun)\n f.add_transition (\"Standing\",\"Turning_Left\",\"Left\",doLeft)\n f.add_transition (\"Standing\",\"Turning_Right\",\"Right\",doRight)\n f.add_transition (\"Standing\",\"Waiting\",\"Wait\",doWait)\n \n f.add_transition (\"Running\",\"Idle\",\"Stop\",doStop)\n f.add_transition (\"Running\",\"Running\",\"Go\",doRun)\n f.add_transition (\"Running\",\"Turning_Left\",\"Left\",doLeft)\n f.add_transition (\"Running\",\"Turning_Right\",\"Right\",doRight)\n f.add_transition (\"Running\",\"Waiting\",\"Wait\",doWait)\n \n f.add_transition (\"Turning_Left\",\"Idle\",\"Stop\",doStop)\n f.add_transition (\"Turning_Left\",\"Running\",\"Go\",doRun)\n f.add_transition (\"Tuning_Left\",\"Tuning_Left\",\"Left\",doLeft)\n f.add_transition (\"Turning_Left\",\"Turning_Right\",\"Right\",doRight)\n f.add_transition (\"Turning_Left\",\"Waiting\",\"Wait\",doWait)\n \n f.add_transition (\"Turning_Right\",\"Idle\",\"Stop\",doStop)\n f.add_transition (\"Turning_Right\",\"Running\",\"Go\",doRun)\n f.add_transition (\"Turning_Right\",\"Turning_Left\",\"Left\",doLeft)\n f.add_transition (\"Turning_Right\",\"Turning_Right\",\"Right\",doRight)\n f.add_transition (\"Turning_Right\",\"Waiting\",\"Wait\",doWait)\n \n f.add_transition (\"Waiting\",\"Idle\",\"Stop\",doStop)\n f.add_transition (\"Waiting\",\"Running\",\"Go\",doRun)\n f.add_transition (\"Waiting\",\"Turning_Left\",\"Left\",doLeft)\n f.add_transition (\"Waiting\",\"Turning_Right\",\"Right\",doRight)\n f.add_transition (\"Waiting\",\"Waiting\",\"Wait\",doWait)\n \n \n\n # initial state\n f.set_state (\"Idle\") # ... replace with your initial state\n # first event\n f.set_event (\"StandUp\") # ... replace with you first event \n # end state\n end_state = \"End\" # ... replace with your end state\n\n \n # fsm loop\n run = True \n while (run):\n funct = f.run () # function to be executed in the new state\n if f.curState != end_state:\n newEvent = funct() # new event when state action is finished\n## print(\"New Event : \",newEvent)\n f.set_event(newEvent) # set new event for next transition\n else:\n funct()\n run = False\n \n## print(\"End of the programm\")\n\n\n\n","sub_path":"py/team_onkhassTrobo/fsm_nao_virtuel.py","file_name":"fsm_nao_virtuel.py","file_ext":"py","file_size_in_byte":5235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"398126395","text":"from datetime import datetime\n\nanoatual = int(datetime.now().year)\nmaior = 0\nmenor = 0\nfor i in range(1, 8):\n nasc = int(input('Digite o ano de nascimento da {}° pessoa:'.format(i)))\n idade = anoatual - nasc\n if idade >= 18:\n maior += 1\n else:\n menor += 1\nprint('''Existem {} pessoas menores de idade.\nExistem {} pessoas maiores de idade.'''.format(menor,maior))\n","sub_path":"Exercicios_1/ex054.py","file_name":"ex054.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"144627836","text":"def pre_process(msg,round_key):\r\n data=dict()\r\n a=list(round_key)\r\n a.sort()\r\n # print(a)\r\n round_num={}\r\n cc=0\r\n for ele in enumerate(a):\r\n t=ele[1]\r\n try:\r\n if t in round_num.keys():\r\n raise TypeError()\r\n round_num[t]=ele[0]+1\r\n except :\r\n raise TypeError(\"Duplicate Character Key is not Allowed\")\r\n \r\n # print(round_num)\r\n for s in round_key:\r\n data[s]=round_num[s]\r\n# print(data) \r\n\r\n import math\r\n row=math.ceil(len(msg)/len(round_key))\r\n\r\n row=row+1\r\n column=len(round_key)\r\n# print(\"Rowsize : \",row)\r\n\r\n\r\n\r\n #populate matrix of size row*column\r\n table=[[\"$\"]*column for i in range(row)]\r\n idx=0\r\n val=list(data.values())\r\n # print(val)\r\n while idx1:\n good = [y for y in dups if len([x for x in y[1].num if x.isdigit()])>0]\n if good:\n others = [x for x in dups if x!=good[0]]\n for x in others:\n sets.remove(x)\n else:\n # just pick 1\n for x in dups[1:]:\n sets.remove(x)\n i+=1\n\n\n xidx = [x for x in sets if x[1].num=='x']\n if not xidx:\n problematic.write('no x :'+problem); continue\n\n #TODO look for 2 xes\n '''\n xidx = xidx[0][0]\n postx = [x for x in numbs if x[0]>=xidx]\n if len(postx)>1:\n # 2 vals to right\n twoToRight = True\n else:\n twoToRight = False\n '''\n\n \n\n\n\n numlist = [(cleannum(v.num),v) for k,v in sets]\n numlist = [x for x in numlist if x[0]!='']\n\n allnumbs = {str(k):v for k,v in numlist}\n \n\n objs = {k:(0,v) for k,v in numlist}\n answers = eqs[k]\n\n for j,eq in enumerate(answers):\n trips = []\n print(j,eq)\n l,r = [x.strip().split(' ') for x in eq.split('=')]\n \n compound = r if len(l)==1 else l\n simplex = l if len(l)==1 else r\n target = simplex[0]\n target = (target,objs[target])\n\n #find innermost parens?\n while len(compound)>1:\n if \"(\" in compound:\n rpidx = (len(compound) - 1) - compound[::-1].index('(')\n lpidx = rpidx+compound[rpidx:].index(\")\")\n subeq = compound[rpidx+1:lpidx]\n substr = \"(\"+''.join(subeq)+\")\"\n compound = compound[:rpidx]+[substr]+compound[lpidx+1:]\n else:\n subeq = compound[0:3]\n substr = \"(\"+''.join(subeq)+\")\"\n compound = [substr]+compound[3:]\n if True:\n p,op,e = subeq\n #print(p,op,e)\n p = objs[p]\n e = objs[e]\n op = op.strip()\n trips.append((op,p,e))\n pute = (0,makesets.combine(p[1],e[1],op))\n #print(\"OPERATION SELECTED: \",op)\n #p.details()\n #e.details()\n #print(substr,pute[1].num)\n objs[substr]=pute\n if pute == -1:\n exit()\n if simplex == l:\n trips.append((\"=\",objs[simplex[0]],objs[compound[0]]))\n else:\n trips.append((\"=\",objs[compound[0]],objs[simplex[0]]))\n t = training(trips,problem,target)\n for op in t:\n bigtexamples[op][0].extend(t[op][0])\n bigtexamples[op][1].extend(t[op][1])\n print(op,len(bigtexamples[op][0]))\n pickle.dump(bigtexamples,open('data/gold_training.pickle','wb'))\n\n\n\n\nif __name__==\"__main__\":\n q = sys.argv[1]\n make_eq(q)\n\n\n","sub_path":"no_lexo/make_gold_equations.py","file_name":"make_gold_equations.py","file_ext":"py","file_size_in_byte":4957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"527135831","text":"# benchmark \n#\tregister_binary\n#\tstack_binary\n#\t\tcodegen_1\n#\t\t\tstack_binary_annotated_1\n#\t\tcodegen_2\n#\t\t\tstack_binary_annotated_2\n\nclass Experiments:\n\tdef plot_state_usage(self):\n\t\tfor binary in self.binaries:\n\t\t\tstatic_trace = binary.static_trace()\n\t\t\tdynamic_trace = vm.StackVM.trace(binary)\n\n\t\t\tstatic_trace.get_channel(stackstate)\n\t\t\tdynamic_trace.get_channel(stackstate)\n\n\t\t\tpoint()\n\n\tdef plot_basic_block_lengths(self):\n\t\tfor binary in self.binaries:\n\t\t\tlengths = [0]\n\n\t\t\tfor block in binary.blocks:\n\t\t\t\tl = len(block)\n\t\t\t\tlengths += [0] * max(len(lengths)-l+1, 0)\n\t\t\t\tlengths[l] += 1\n\n\t\t\tfor x, y in enumerate(lengths):\n\t\t\t\tpoint(x, y)\n\n\tdef plot_implemention_count(self):\n\t\tfor codegen in self.codegen:\n\t\t\tpoint(codegen.name, codegen.fragments)\n\n\tdef plot_speedups(self):\n\t\tfor binary, (static_trace, dynamic_trace) in self.traces:\n\t\t\tpoint()\n\n\tdef main(self):\n\t\tself.benchmarks = load_benchmarks()\n\t\tself.codegen = [codegen.CodeGen(model) for model in models]\n\t\tself.binaries = [c(b) for c in self.codegen for b in self.benchmarks]\n\t\tself.plot_basic_block_lengths()\n\t\tself.plot_state_usage()\n\t\tself.plot_implemention_count()\n\t\tself.plot_speedups()\n\nif __name__ == '__main__':\n\tExperiments.main()\n","sub_path":"vin/experiments.py","file_name":"experiments.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"148755323","text":"import numpy as np\nimport argparse\n\nimport tensorflow as tf\nimport os\n\nfrom tensorflow.contrib import rnn\nfrom tensorflow.contrib.layers import l2_regularizer, xavier_initializer\n\nfrom data.tf_recorfd import build_inputs_from_cifar_tf_record_data, build_inputs_from_numpy_text_names_data\nfrom training.image_classification import build_model_specification, build_eval_model_specification, train\nfrom training.scripts.evaluate import evaluate\n\n\ndef build_rnn(samples):\n num_input = 27 # MNIST data input (img shape: 28*28)\n timesteps = 11 # timesteps\n num_hidden = 100 # hidden layer num of features\n num_classes = 2 # MNIST total classes (0-9 digits)\n\n weights = {\n 'out': tf.Variable(tf.random_normal([num_hidden, num_classes]))\n }\n biases = {\n 'out': tf.Variable(tf.random_normal([num_classes]))\n }\n x = tf.transpose(samples, [0, 2, 1])\n x = tf.unstack(samples, timesteps, 1)\n out = samples\n with tf.variable_scope('rnn'):\n lstm_cell = tf.nn.rnn_cell.BasicRNNCell(100)\n\n output, states = rnn.static_rnn(lstm_cell, x, dtype=tf.float32)\n out = tf.matmul(output[-1], weights['out']) + biases['out']\n\n with tf.variable_scope('fc1'):\n out = tf.layers.dense(inputs=out, units=2, activation=tf.nn.softmax)\n\n return out\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--batch_size\", required=True)\nparser.add_argument(\"--learning_rate\", required=True)\n\nargs = vars(parser.parse_args())\n\ntrain_path = '/home/piotr/Workspace/Projects/pokedex/data/train.npz'\ntest_path = '/home/piotr/Workspace/Projects/pokedex/data/test.npz'\n\nbatch_size = int(args[\"batch_size\"])\n\ntrain_inputs = build_inputs_from_numpy_text_names_data(train_path, batch_size)\ntest_inputs = build_inputs_from_numpy_text_names_data(test_path, batch_size)\n\n# print(train_inputs)\n# variable_init_op = tf.group(*[tf.global_variables_initializer(), tf.tables_initializer()])\n# with tf.Session() as sess:\n# sess.run(variable_init_op)\n# sess.run(train_inputs['iterator_init_op'])\n#\n# print(sess.run(train_inputs['labels']))\n\nimages = train_inputs['images']\nlabels = train_inputs['labels']\n\nTRAIN_SIZE = 22467\nEVAL_SIZE = 5617\n\ntrain_steps = TRAIN_SIZE // batch_size\ntest_steps = EVAL_SIZE // batch_size\n\nlearning_rate = float(args[\"learning_rate\"])\n\nreg = 'l2-0.1'\nopt = 'Adam'\n#model_dir = '/DATA/piotr/cifar/learning/{} op: {} lr: {} batch: {:03d} reg: {}'.format([500], opt, learning_rate, batch_size, reg)\nmodel_dir = '/DATA/piotr/cifar/sprawko/88888'\n# model_dir = '/DATA/piotr/cifar/learning/apaktest'\nif not os.path.exists(model_dir):\n os.makedirs(model_dir)\n\nloss_fn = tf.losses.sparse_softmax_cross_entropy\noptimizer = tf.train.AdamOptimizer()\nmodel_fn = build_rnn\ntrain_spec = build_model_specification(train_inputs, model_fn, loss_fn, optimizer)\neval_spec = build_eval_model_specification(test_inputs, model_fn, loss_fn)\ntrain(train_spec, eval_spec, model_dir, 30, train_steps, test_steps)\n\n# model_dir = '/DATA/piotr/cifar/learning/best'\n# evaluate(eval_spec, model_dir)","sub_path":"training/scripts/train_text_classification.py","file_name":"train_text_classification.py","file_ext":"py","file_size_in_byte":3046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"487382203","text":"import contextlib\nimport io\nimport unittest\nfrom pathlib import Path\nfrom unittest import mock\n\nfrom sr.comp.cli.for_each_match import (\n command,\n PlaceholderExpander,\n replace_placeholders,\n)\nfrom sr.comp.types import TLA\n\nfrom .factories import build_match\n\n\nclass ForEachMatchTests(unittest.TestCase):\n longMessage = True\n maxDiff = None\n\n def test_smoke(self) -> None:\n compstate_path = str(Path(__file__).parent / 'dummy')\n\n mock_settings = mock.Mock(\n compstate=compstate_path,\n arena=None,\n matches=set([0, 2, 3]),\n command=['spam', '{TYPE}:{ARENA}', '{NUMBER}|{TLAS}'],\n )\n\n with mock.patch('subprocess.check_call') as mock_check_call:\n command(mock_settings)\n\n mock_check_call.assert_has_calls([\n mock.call(['spam', 'league:A', '0|- CLY TTN -']),\n mock.call(['spam', 'league:B', '0|GRS QMC - -']),\n mock.call(['spam', 'league:A', '2|ICE MFG SWI BRN']),\n mock.call(['spam', 'league:B', '2|TBG EMM SGS GYG']),\n mock.call(['spam', 'league:A', '3|MAI2 HSO KDE CCR']),\n mock.call(['spam', 'league:B', '3|SCC LSS HZW MAI']),\n ])\n\n def test_validate_placeholders(self) -> None:\n with contextlib.redirect_stderr(io.StringIO()) as stderr:\n PlaceholderExpander.validate('fine')\n self.assertEqual(\"\", stderr.getvalue())\n\n with contextlib.redirect_stderr(io.StringIO()) as stderr:\n PlaceholderExpander.validate('@unknown')\n self.assertEqual(\n \"Warning: unrecognised value '@unknown'.\\n\",\n stderr.getvalue(),\n )\n\n with contextlib.redirect_stderr(io.StringIO()) as stderr:\n PlaceholderExpander.validate('@TLAS')\n self.assertEqual(\"\", stderr.getvalue())\n\n def test_replace_placeholders(self) -> None:\n match = build_match(num=42, teams=[TLA('ABC'), None])\n\n command = replace_placeholders(match, [\n 'spam',\n '{NUMBER}:{ARENA}',\n '{TLAS}',\n '@TLAS',\n '@TLAS|',\n ])\n\n self.assertEqual(\n ['spam', '42:main', 'ABC -', 'ABC', '-', '@TLAS|'],\n command,\n )\n","sub_path":"tests/test_for_each_match.py","file_name":"test_for_each_match.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"416438224","text":"from car.models import CarModel\nfrom rest_framework import viewsets, serializers, status\nfrom rest_framework.response import Response\nimport datetime\n\nfrom .fine import FineSerializer\nfrom ..models import Contract, Fine\n\n\nclass ContractSerializer(serializers.ModelSerializer):\n status = serializers.SerializerMethodField(method_name='get_status')\n status_color = serializers.SerializerMethodField(method_name='get_status_color')\n car = serializers.SlugRelatedField(slug_field='name', many=False, read_only=True)\n\n @staticmethod\n def get_status(obj):\n return obj.get_status_display()\n\n @staticmethod\n def get_status_color(obj):\n status_color_by_tag = {\n 'En proceso': 'blue',\n 'Activo': 'green',\n 'Finalizado': 'black',\n 'Cancelado': 'red',\n }\n return status_color_by_tag[obj.get_status_display()]\n\n class Meta:\n model = Contract\n fields = ['guid', 'monthly_cost', 'annual_mileage', 'duration', 'start_date', 'reject_date', 'bank_account',\n 'status', 'status_color', 'user', 'car', 'car_color', 'creation_datetime']\n\n\nclass ContractViewSet(viewsets.ModelViewSet):\n lookup_field = 'guid'\n queryset = Contract.objects.all()\n serializer_class = ContractSerializer\n http_method_names = ['get', 'post', 'put', 'delete']\n\n def create(self, request, *args, **kwargs):\n duration_increment = {12: 1.3, 24: 1.2, 36: 1.1, 48: 1, 60: 1}\n km_increment = {15000: 1, 20000: 1, 25000: 1.1, 30000: 1.2, 35000: 1.3, 40000: 1.4, 45000: 1.5}\n user = request.user\n car = CarModel.objects.get(guid=request.data['carGuid'])\n price = car.base_price * duration_increment[request.data['duration']] * km_increment[request.data['km']]\n Contract.objects.create(monthly_cost=price, duration=request.data['duration'],\n annual_mileage=request.data['km'], car_color=request.data['carColor'],\n car_id=car.id, user_id=user.id, status='E', bank_account=request.data['account'])\n return Response(status=status.HTTP_201_CREATED)\n\n def list(self, request, *args, **kwargs):\n user = request.user\n contracts = Contract.objects.filter(user__user_info__guid=user.user_info.guid)\n serializer = self.get_serializer(contracts, many=True)\n return Response(status=status.HTTP_200_OK, data=serializer.data)\n\n def destroy(self, request, *args, **kwargs):\n contract_to_delete = self.get_object()\n if contract_to_delete.status == 'E':\n contract_to_delete.delete()\n return Response(status=status.HTTP_200_OK)\n else:\n contract_to_delete.status = 'C'\n contract_to_delete.reject_date = datetime.date.today()\n today = datetime.date.today()\n duration_to_end = (today.year - contract_to_delete.start_date.year) * 12 \\\n + today.month - contract_to_delete.start_date.month\n fine_price = duration_to_end * contract_to_delete.monthly_cost * 0.75\n fine = Fine.objects.create(description=request.query_params['description'],\n contract_id=contract_to_delete.id,\n cost=fine_price)\n contract_to_delete.save()\n serializer = {\n 'description': fine.description,\n 'cost': fine.cost,\n 'creation_datetime': fine.creation_datetime,\n 'contract': fine.contract.guid,\n 'pay_date': ''\n }\n return Response(status=status.HTTP_200_OK, data=serializer)\n","sub_path":"backend/contract/rest/contract.py","file_name":"contract.py","file_ext":"py","file_size_in_byte":3689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"372553562","text":"import tensorflow as tf\nimport numpy as np\n\n\ndef preprocess_data(raw_data, need_norm_inputs=[], need_categorization_inputs=[]):\n symbolic_inputs = create_symbolic_input(raw_data)\n\n preprocessed_inputs = []\n feature_columns = []\n\n for key_name in symbolic_inputs:\n if not(key_name in need_norm_inputs) and not(key_name in need_categorization_inputs):\n feature_columns.append(tf.feature_column.numeric_column(\n key_name, dtype=tf.dtypes.float32))\n preprocessed_inputs.append(symbolic_inputs[key_name])\n\n normalized_inputs = normalize_numeric_input(symbolic_inputs, raw_data,\n need_norm_inputs, feature_columns)\n\n preprocessed_inputs.append(normalized_inputs['normalized_inputs'])\n\n feature_columns = normalized_inputs['feature_columns']\n\n preprocessed_inputs, feature_columns = string_input_to_encoding(\n symbolic_inputs, preprocessed_inputs, raw_data, need_categorization_inputs, feature_columns)\n\n preprocessed_inputs = tf.keras.layers.Concatenate()(preprocessed_inputs)\n\n return (\n symbolic_inputs,\n preprocessed_inputs,\n feature_columns\n )\n\n\ndef create_symbolic_input(raw_data):\n inputs = {}\n for name, column in raw_data.items():\n dtype = column.dtype\n\n if dtype == object:\n dtype = tf.string\n else:\n dtype = tf.float32\n\n inputs[name] = tf.keras.Input(shape=(1,), name=name, dtype=dtype)\n\n return inputs\n\n\ndef normalize_numeric_input(symbolic_inputs, raw_data, need_norm_inputs, feature_columns):\n numeric_inputs = {\n name: input for name, input in symbolic_inputs.items()\n if input.dtype == tf.float32 and name in need_norm_inputs\n }\n\n x = tf.keras.layers.Concatenate()(list(numeric_inputs.values()))\n norm = tf.keras.layers.experimental.preprocessing.Normalization()\n norm.adapt(np.array(raw_data[numeric_inputs.keys()]))\n\n for key_name in numeric_inputs:\n feature_columns.append(tf.feature_column.numeric_column(\n key_name, dtype=tf.dtypes.float32, normalizer_fn=tf.keras.layers.experimental.preprocessing.Normalization())\n )\n\n return {'normalized_inputs': norm(x), 'feature_columns': feature_columns}\n\n\ndef string_input_to_encoding(symbolic_inputs, preprocessed_inputs, raw_data, need_categorization_inputs, feature_columns):\n for name, input in symbolic_inputs.items():\n # Skip non-string column types since they should already be pre-processed in the normalize_numeric_input()\n if input.dtype == tf.float32 or not(name in need_categorization_inputs):\n continue\n\n # Maps strings from a vocabulary to integer indices https://www.tensorflow.org/api_docs/python/tf/keras/layers/experimental/preprocessing/StringLookup.\n lookup = tf.keras.layers.experimental.preprocessing.StringLookup(\n vocabulary=np.unique(raw_data[name]))\n # Created a one-hot vector categorizer with the size of the vocab from the lookup https://www.tensorflow.org/api_docs/python/tf/keras/layers/experimental/preprocessing/CategoryEncoding\n one_hot = tf.keras.layers.experimental.preprocessing.CategoryEncoding(\n max_tokens=lookup.vocab_size())\n\n # Lookup the indices from the input and populate the vocab\n x = lookup(input)\n # Convert the lookup indices into one-hor vector (Example: from a index 3 to [0, 0, 0, 1])\n x = one_hot(x)\n\n feature_columns.append(\n tf.feature_column.indicator_column(\n tf.feature_column.categorical_column_with_vocabulary_list(\n name, np.unique(raw_data[name])\n )\n )\n )\n preprocessed_inputs.append(x)\n\n return [preprocessed_inputs, feature_columns]\n","sub_path":"utils/pre_processing.py","file_name":"pre_processing.py","file_ext":"py","file_size_in_byte":3825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"304472198","text":"#!coding=utf-8\r\nfrom mvc import *\r\nfrom logic.utility import ActionHandler\r\nfrom bson import ObjectId\r\nfrom mvc import mysql_util\r\nimport hashlib\r\nfrom logic import manage\r\nfrom logic.define import *\r\nfrom mongo_util import MongoIns; mongo_util=MongoIns()\r\n\r\n\r\n@url(r\"/monitor/ERC\")\r\nclass MonitorERCHandler(ActionHandler):\r\n def get(self):\r\n code_name = self.get_argument('code_name')\r\n eu, t = mongo_util.m_list('auth_gateways', project = code_name)\r\n\r\n jqr_event = []\r\n for e in eu:\r\n euaddr = e.get('euaddr')\r\n fields = ['ERC_ID', 'EuAddr', 'UpdateTime', 'HappenTime', 'Note', 'Content']\r\n sql = \"select {} from JQR_EVENT_ERC where euaddr='{}' and DealWith=0 order by HappenTime DESC\".format(','.join(fields), euaddr)\r\n data, t = mysql_util.m_query(sql, fields, page_size = 2)\r\n\r\n for d in data:\r\n d['name'] = e.get('name')\r\n d['HappenTime'] = str(d.get('HappenTime'))\r\n\r\n jqr_event.extend(data)\r\n\r\n fields = [\"ERC_ID\", \"PointNum\", \"SubstID\", \"UpdateTime\", \"HappenTime\", \"DealWith\", \"Note\", \"Content\"]\r\n sql = \"select {} from YW_EVENT_ERC where SubstID='{}' and DealWith=0 order by HappenTime DESC\".format(','.join(fields), code_name)\r\n yw_event, t = mysql_util.m_query(sql, fields, page_size=7)\r\n\r\n for e in yw_event:\r\n e['PointID'] = e['PointNum']\r\n\r\n if not yw_event:\r\n yw_event = [{'PointID':'1', 'HappenTime': '2', 'Note': '5', 'Content':'4'}]\r\n\r\n self.write(dict(status = True, jqr_event = jqr_event, yw_event = yw_event))\r\n\r\n\r\n@url(r\"/monitor/eu\")\r\nclass MonitorTermHandler(ActionHandler):\r\n def get(self):\r\n code_name = self.get_argument('code_name')\r\n mapinfo, _ = mongo_util.m_list(\"sensors\", dbname = code_name, host = __conf__.DB_HOST, sensor_type = \"a_map\", findall = True)\r\n for d in mapinfo:\r\n d['mapx'] = d.get('position', [10, 10])[0]\r\n d['mapy'] = d.get('position', [10, 10])[1]\r\n\r\n mapinfo = dict((d.get('sensor_id'), d) for d in mapinfo)\r\n\r\n eu, t = mongo_util.m_list('auth_gateways', project = code_name, findall = True)\r\n\r\n data = []\r\n for e in eu:\r\n euaddr = e.get('euaddr')\r\n fields = ['EuAddr', 'CollectTime', 'SchemeNum', 'PlanNum', 'PointNum', 'JqrTime', 'BatteryCapat', 'BatteryVar', 'JqrConMode', 'LocalTemp', 'LocalHum', 'LocalWind', 'SysTemp', 'JqrSpeed', 'CurrentPoint', 'CurrentPointLog', 'FrontPoint', 'FrontPointLog']\r\n\r\n sql = \"select {} from TermRealTimeShowData where euaddr='{}'\".format(','.join(fields), euaddr)\r\n d, t = mysql_util.m_query(sql, fields, findall=True)\r\n for _d in d:\r\n _d['name'] = e.get('name')\r\n _d['LocalTemp'] = float(_d.get('LocalTemp') or 0) / 10\r\n _d['SysTemp'] = float(_d.get('SysTemp') or 0) / 10\r\n _d['JqrSpeed'] = float(_d.get('JqrSpeed') or 0) / 10\r\n _d['BatteryCapat'] = float(_d.get('BatteryCapat') or 0) / 10\r\n _d['BatteryVar'] = float(_d.get('BatteryVar') or 0) / 10\r\n _d['LocalHum'] = float(_d.get('LocalHum') or 0) / 10\r\n data.extend(d)\r\n\r\n self.write(dict(status = True, data = data, mapinfo = mapinfo))\r\n\r\n\r\n","sub_path":"web/action/erc.py","file_name":"erc.py","file_ext":"py","file_size_in_byte":3330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"359797222","text":"from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom .models import Idea\nfrom login_app.models import User\nfrom django.db.models import Count\n\ndef index(request):\n context = {\n 'ideas': Idea.objects.annotate(num_likes=Count('user_likes')).order_by('-num_likes'),\n }\n return render(request,'snack_index.html',context)\n\ndef create_idea(request):\n errors = Idea.objects.basic_validator(request.POST)\n if errors:\n for k, v in errors.items(): \n messages.error(request, v)\n return redirect('/snacks')\n else:\n user = User.objects.get(id = request.session['user_id'])\n idea = Idea.objects.create(\n title = request.POST['title'],\n description = request.POST['description'],\n user = user,\n )\n idea.user_likes.add(user)\n return redirect('/snacks')\n\ndef display_idea(request, idea_id):\n context = {\n 'snack': Idea.objects.get(id = idea_id),\n 'this_user': User.objects.get(id = request.session['user_id']),\n }\n return render(request, 'snack.html', context)\n\n\ndef like(request, idea_id):\n user = User.objects.get(id = request.session['user_id'])\n idea = Idea.objects.get(id = idea_id)\n idea.user_dislikes.remove(user)\n idea.user_likes.add(user)\n return redirect('/snacks')\n\ndef dislike(request, idea_id):\n user = User.objects.get(id = request.session['user_id'])\n idea = Idea.objects.get(id = idea_id)\n idea.user_likes.remove(user)\n idea.user_dislikes.add(user)\n return redirect('/snacks')\n\ndef delete(request, idea_id):\n idea = Idea.objects.get(id = idea_id)\n idea.delete()\n return redirect('/snacks')\n\n \n\n\n\n","sub_path":"snack_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"578695363","text":"\n\nfrom xai.brain.wordbase.nouns._palomino import _PALOMINO\n\n#calss header\nclass _PALOMINOS(_PALOMINO, ):\n\tdef __init__(self,): \n\t\t_PALOMINO.__init__(self)\n\t\tself.name = \"PALOMINOS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"palomino\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_palominos.py","file_name":"_palominos.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"519579021","text":"#!/usr/bin/env python3\n\nimport Disciplina, DisciplinaDAO\nfrom FormatData import FormatData\n\ndisciplina = Disciplina.Disciplina()\ndisciplinaDAO = DisciplinaDAO.DisciplinaDAO()\n\nprint(\"Content-type: text/html\")\nprint(\"\")\nprint(\n\"\"\"\n\n\n\t\n\t\t \n\t\n\t\n\t\tDisciplinas!!! \n\t\tNovo \n\"\"\")\n\nfor disciplina in disciplinaDAO.getLista():\n\n\tprint(\\\n\t\t\"\t\t{} \".format(\\\n\t\t\tdisciplina.getCOD_DISCIPLINA(),\\\n\t\t\tdisciplina.getDISCIPLINA()\n\t\t))\n\nprint(\n\"\"\"\n\n\n\"\"\")\n","sub_path":"cgi-bin/disciplinas.py","file_name":"disciplinas.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"576717805","text":"from django import forms\nfrom django.forms.fields import CharField\nfrom django.forms.models import ModelForm\nfrom adm.endereco.models import *\n__author__ = 'mattyws'\n\nclass EstadoForm(ModelForm):\n\n class Meta:\n model = Estado\n\nclass CidadeForm(ModelForm) :\n\n class Meta:\n model = Cidade\n\n def __init__(self, *args, **kwargs):\n super(CidadeForm, self).__init__(*args, **kwargs)\n self.fields['estado'].choices = [[x.id, x.sigla] for x in Estado.objects.all()]\n\nclass EnderecoForm(ModelForm) :\n\n class Meta:\n model = Endereco\n\n def __init__(self, *args, **kwargs):\n super(EnderecoForm, self).__init__(*args, **kwargs)\n self.fields['cidade'].choices = [[x.id, x.nome] for x in Cidade.objects.all()]","sub_path":"adm/endereco/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"260063933","text":"class Outcome:\n\n outcomes = dict()\n\n def __new__(cls, title, chance):\n if title in cls.outcomes.keys():\n return cls.outcomes[title]\n else:\n self = super(cls, Outcome).__new__(Outcome)\n return self\n\n def __init__(self, title, chance):\n self.title = title\n self.chance = chance\n if title not in self.outcomes.keys():\n self.outcomes[title] = self\n","sub_path":"outcome.py","file_name":"outcome.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"322847484","text":"import re\n\ndef ReadInput():\n with open('./InputData/Day_7.txt') as reader:\n return reader.read().splitlines()\n\ndef FindBags(input):\n returnData = {}\n for text in input:\n pos = text.find('bags contain')\n if pos == -1:\n break\n bag, content = text[:pos].strip(), text[pos+12:].strip().replace('.', '').split(',')\n subContent = {}\n for subBag in content:\n subBag = subBag.strip()\n if (subBag == 'no other bags'):\n break\n subBag = re.sub(r\" bag.*\", \"\", subBag)\n subContent.update({subBag[2:]: subBag[:1]})\n returnData.update({bag: subContent})\n return returnData\n\ndef RecursiveFindPart1(key, bags, target):\n if len(bags[key]) == 0:\n return False\n if target in bags[key]:\n return True\n else:\n for x in bags[key]:\n if RecursiveFindPart1(x, bags, target):\n return True\n\ndef RecursiveFindPart2(key, bags):\n if len(bags[key]) == 0:\n return 0\n\n sum = 0\n for x in bags[key]:\n value = int(bags[key][x])\n sum += value\n sum += value * RecursiveFindPart2(x, bags)\n return sum\n\nbags = FindBags(ReadInput())\n#part 1\ncounter = 0\nfor x in bags.keys():\n if RecursiveFindPart1(x, bags, 'shiny gold'):\n counter += 1\nprint(counter)\n\n#part2 \nprint(RecursiveFindPart2('shiny gold', bags))","sub_path":"Solutions/Day_7.py","file_name":"Day_7.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"92769375","text":"'''\nCreated on Jan 14, 2015\n\n@author: M\n'''\nfrom tkinter import *\n\nclass ImageDemo:\n def __init__(self):\n window = Tk()\n window.title(\"Image Demo\")\n \n myImage = PhotoImage(file = r\"C:\\Users\\Miguel\\Desktop\\dancingpeaks.gif\")\n otherImage = PhotoImage(file = r\"C:\\Users\\Miguel\\Desktop\\animation.gif\")\n \n # frame1 to contain lable and canvas\n frame1 = Frame(window)\n frame1.pack()\n Label(frame1, image = myImage).pack(side = LEFT)\n canvas = Canvas(frame1)\n canvas.create_image(90, 50, image = otherImage)\n canvas[\"width\"] = 200\n canvas[\"height\"] = 100\n canvas.pack(side = LEFT)\n \n window.mainloop()\n\n\nImageDemo()","sub_path":"ImageDemo.py","file_name":"ImageDemo.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"653899604","text":"from network.huawei import *\nfrom datetime import datetime\nimport argparse\nimport threading\nimport time\n\n# create parser\n# parser = argparse.ArgumentParser('Monitor Huawei E5576c')\n\n# # add arguments\n# parser.add_argument(\n# 'SessionID',\n# metavar='sid',\n# type=str,\n# help='SessionID used to access huaweu e5776c dashboard'\n# )\n\n# args = parser.parse_args()\n\n\n\ndef get_usage(api):\n while True:\n resp = api.get_traffic()\n if resp is not None:\n total_upload = int(resp.TotalUpload)\n total_download = int(resp.TotalDownload)\n\n ttotal_upload = total_upload\n ttotal_download = total_download\n\n udtype = 'B'\n if len(str(total_upload)) >= 7:\n ttotal_upload = total_upload/1024/1024\n udtype = 'MB'\n elif len(str(total_upload)) >= 4:\n ttotal_upload = total_upload/1024\n udtype = 'KB'\n\n ddtype = 'B'\n if len(str(total_download)) >= 7:\n ttotal_download = total_download/1024/1024\n ddtype = 'MB'\n elif len(str(total_download)) >= 4:\n ttotal_download = total_download/1024\n ddtype = 'KB'\n\n print(f'U{ttotal_upload:.2f}{udtype} : D{ttotal_download:.2f}{ddtype}\\n' + '*'*24)\n\n with open(f'traffic_{datetime.now().strftime(\"%d-%m-%Y\")}.log', 'at+') as f:\n f.write(f'{datetime.now()}:{total_upload}:{total_download}\\n')\n else: \n break\n time.sleep(30)\n\napi = HuaweiApi()\nthreading.Thread(target=get_usage, args=[api, ], daemon=True).start()\nwhile True:\n traffic_resp = api.get_traffic()\n\n if traffic_resp is not None:\n up_rate = int(traffic_resp.CurrentUploadRate)\n down_rate = int(traffic_resp.CurrentDownloadRate)\n\n udtype = 'B'\n if len(str(up_rate)) >= 7:\n up_rate = up_rate/1024/1024\n udtype = 'MB'\n elif len(str(up_rate)) >= 4:\n up_rate = up_rate/1024\n udtype = 'KB'\n\n ddtype = 'B'\n if len(str(down_rate)) >= 7:\n down_rate = down_rate/1024/1024\n ddtype = 'MB'\n elif len(str(down_rate)) >= 4:\n down_rate = down_rate/1024\n ddtype = 'KB'\n\n out = (\n f'{up_rate:.2f}{udtype}/s - {down_rate:.2f}{ddtype}/s{\" \"*12}'\n )\n print(out, end='\\r')\n time.sleep(1)\n# else:\n# api.session_id = input(f\"{HuaweiApi.BASE_URL}:SESSION_ID\")\n\n\n\n\n\n\n","sub_path":"monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"404220273","text":"# Echo server program\nimport socket, ssl\n\ncert=\"cert/\"\ncertfile = \"mycertfile.pem\"\nkeyfile=\"mykeyfile.pem\"\nmycertfile = cert + certfile\n\nmykeyfile = cert + keyfile\n\nHOST = '' # Symbolic name meaning all available interfaces\nPORT = 9980 # Arbitrary non-privileged port\n\ncontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\ncontext.load_cert_chain(certfile=mycertfile, keyfile=mykeyfile)\n\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind((HOST, PORT))\ns.listen(1)\nwhile True:\n conn, addr = s.accept()\n print('Connected by', addr)\n ssl_conn = context.wrap_socket(conn, server_side=True)\n while True:\n data = ssl_conn.recv(1024)\n print(\"recv data: \", repr(data))\n if not data: break\n ssl_conn.sendall(data)\n ssl_conn.close()\n","sub_path":"https/srv.py","file_name":"srv.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"517530024","text":"import spotify_client\r\nimport threading\r\nimport requests\r\nimport lxml\r\nfrom bs4 import BeautifulSoup\r\nimport re\r\nimport tkinter as tk\r\nfrom tkinter import ttk\r\n\r\n### Connect to Spotify API\r\n\r\nsp = spotify_client.SpotifyClient()\r\n\r\nif sp.refresh_token == \" \":\r\n sp.get_authentication_code()\r\n sp.get_access_token()\r\n\r\n\r\ndef auto_refresh_access_token():\r\n threading.Timer(3500, auto_refresh_access_token).start()\r\n sp.refresh_access_token()\r\n print (\"Access token was refreshed\")\r\n\r\nauto_refresh_access_token()\r\n\r\n\r\n### Get the artist and track name\r\n\r\ndef get_currently_playing_data():\r\n data = sp.get_currently_playing()\r\n if data == None:\r\n print (\"No music is currently playing\")\r\n return data\r\n \r\ncurrent_playing_data = get_currently_playing_data()\r\nprint (current_playing_data)\r\n\r\n\r\n### Scrape Genius' lyrics page\r\n\r\ndef get_lyrics(data):\r\n genius_artist = data[\"artist\"]\r\n genius_track = data[\"track\"]\r\n\r\n # String processing for genius \r\n if \"(\" in genius_track:\r\n indx = genius_track.find(\"(\")\r\n genius_track = genius_track[:indx-1]\r\n if \"-\" in genius_track:\r\n indx = genius_track.find(\"-\")\r\n genius_track = genius_track[:indx-1]\r\n print (genius_artist,genius_track) \r\n genius_artist = genius_artist.replace(\" \", \"-\").replace(\"/\", \"-\").replace(\"'\", \"\").replace(\"&\", \"and\")\r\n genius_track = genius_track.replace(\" \",\"-\").replace(\"/\", \"-\").replace(\"'\", \"\").replace(\",\",\"\").replace(\"&\", \"and\")\r\n\r\n res = requests.get(f\"https://genius.com/{genius_artist}-{genius_track}-lyrics\")\r\n if res.status_code not in range(200,299):\r\n raise Exception(\"Could not get lyrics\")\r\n pass\r\n soup = BeautifulSoup(res.text,\"lxml\")\r\n page_text = soup.find_all(\"div\", class_=\"Lyrics__Container-sc-1ynbvzw-2 jgQsqn\")\r\n text_with_spaces = \"\"\r\n for part in page_text:\r\n text_with_spaces = text_with_spaces + part.prettify()\r\n\r\n def remove_html_tags(text):\r\n\r\n \"\"\"Remove html tags from a string\"\"\"\r\n clean = re.compile('<.*?>')\r\n return re.sub(clean, '', text)\r\n \r\n lyrics = remove_html_tags(text_with_spaces)\r\n return lyrics\r\n\r\n\r\nlyrics = get_lyrics(current_playing_data)\r\n\r\n\r\n### Display lyrics with tkinter\r\n\r\ndef display_lyrics(lyrics):\r\n\r\n root = tk.Tk()\r\n root.title(\"Lyrics\")\r\n root.geometry(\"500x300\")\r\n\r\n main_frame = tk.Frame(root)\r\n main_frame.pack(fill=\"both\", expand=1)\r\n\r\n canvas = tk.Canvas(main_frame)\r\n canvas.pack(side=\"left\", fill=\"both\", expand= 1)\r\n\r\n scrollbar = ttk.Scrollbar(main_frame, orient= \"vertical\", command=canvas.yview)\r\n scrollbar.pack(side=\"right\", fill=\"y\")\r\n\r\n canvas.configure(yscrollcommand=scrollbar.set)\r\n canvas.bind(\"\", lambda e: canvas.configure(scrollregion=canvas.bbox(\"all\")))\r\n\r\n second_frame = tk.Frame(canvas)\r\n\r\n canvas.create_window((0,0), window=second_frame, anchor=\"nw\")\r\n\r\n def refresh_lyrics():\r\n refreshed_data = get_currently_playing_data()\r\n new_lyrics = get_lyrics(refreshed_data)\r\n str_var.set(new_lyrics)\r\n \r\n button = tk.Button(second_frame, text=\"Refresh lyrics\", command=refresh_lyrics).pack()\r\n \r\n str_var = tk.StringVar()\r\n str_var.set(lyrics)\r\n\r\n label = tk.Label(second_frame, textvariable=str_var).pack(padx=60)\r\n \r\n def _on_mousewheel(event):\r\n canvas.yview_scroll(int(-1*(event.delta/70)), \"units\")\r\n\r\n canvas.bind_all(\"\", _on_mousewheel)\r\n\r\n root.mainloop()\r\n \r\ndisplay_lyrics(lyrics)\r\n","sub_path":"spotify_lyrics/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"594519762","text":"\nimport open3d as o3d\nimport numpy as np\nimport pickle as pkl\nimport os\nimport shutil\n\ndef clean_info(filename):\n \"\"\"\n some fbx downloaded from the internet has strange pattern, clean that\n \"\"\"\n with open(filename, \"r\") as f:\n content = f.read().strip()\n start = content.find('mix')\n end = content.find(':')\n if start == -1 or end == -1:\n return\n pattern = content[start:end+1]\n # print(pattern)\n content = content.replace(pattern, \"\")\n new_filename = filename.replace(\".txt\",\"_clean.txt\")\n with open(new_filename, \"w\") as f:\n f.write(content)\n print('clean finished')\n\nsmpl_joint_names = [\n \"hips\",\n \"leftUpLeg\",\n \"rightUpLeg\",\n \"spine\",\n \"leftLeg\",\n \"rightLeg\",\n \"spine1\",\n \"leftFoot\",\n \"rightFoot\",\n \"spine2\",\n \"leftToeBase\",\n \"rightToeBase\",\n \"neck\",\n \"leftShoulder\",\n \"rightShoulder\",\n \"head\",\n \"leftArm\",\n \"rightArm\",\n \"leftForeArm\",\n \"rightForeArm\",\n \"leftHand\",\n \"rightHand\",\n \"leftHandIndex1\",\n \"rightHandIndex1\",\n]\n\ndef print_joint2(infoname,save = True):\n if not os.path.exists(infoname):\n clean_info(infoname.replace(\"_clean\",\"\"))\n\n\n lines = open(infoname).readlines()\n\n\n\n infoname = infoname.replace(\"_clean\",\"\")\n meshname = infoname.replace(\".txt\", \".obj\")\n inmesh = o3d.io.read_triangle_mesh(meshname)\n # v_posed = np.array(inmesh.vertices)\n\n hier = {}\n joint2index = {}\n index = 0\n # parse rig info file and obtain kinematic chain(hierarchical structure)\n for line in lines:\n line = line.strip('\\n').strip()\n if line[:4] != 'hier':\n continue\n splits = line.split(' ')\n parent_name = splits[1]\n child_name = splits[2]\n if parent_name not in joint2index:\n joint2index[parent_name] = index\n index += 1\n if child_name not in joint2index:\n joint2index[child_name] = index\n index += 1\n if parent_name not in hier:\n hier[parent_name] = [child_name]\n else:\n hier[parent_name].append(child_name)\n\n index2joint = {v: k for k, v in joint2index.items()}\n hier_index = {}\n for k, v in hier.items():\n hier_index[joint2index[k]] = [joint2index[vv] for vv in v]\n parents = list(hier_index.keys())\n children = []\n for v in hier_index.values():\n children.extend(v)\n root = [item for item in parents if item not in children]\n assert len(root) == 1\n root = root[0]\n\n # reorganize the index mapping to ensure that along each chain,\n # from root node to leaf node, the index number increases\n new_hier = {}\n new_joint2index = {index2joint[root]: 0}\n top_level = [root]\n index = 1\n for item in top_level:\n if item not in hier_index:\n # print('continue')\n continue\n for child in hier_index[item]:\n child_name = index2joint[child]\n if child_name not in new_joint2index:\n new_joint2index[child_name] = index\n index += 1\n if new_joint2index[index2joint[item]] not in new_hier:\n new_hier[new_joint2index[index2joint[item]]] = []\n new_hier[new_joint2index[index2joint[item]]].append(new_joint2index[child_name])\n top_level.append(child)\n if save:\n savejoint_dir = infoname.replace(\".txt\", \"_joint.txt\")\n savejoint_dir = os.path.join(\"model\", \"match_list\", os.path.split(savejoint_dir)[-1])\n if os.path.exists(savejoint_dir):\n print(\"It has been jointed!\")\n return\n names = [s.lower() for s in smpl_joint_names]\n count = 0\n with open(savejoint_dir, 'w') as f:\n for joint, id in new_joint2index.items():\n if joint.lower() in names:\n f.write(\"%s : %d:%d\\n\" % (joint, id, names.index(joint.lower())))\n count += 1\n else:\n f.write(\"%s : %d\\n\" % (joint, id))\n f.write(\"\\n[%d/%d] TO MATCH\" % (count, len(smpl_joint_names)))\n print(\"finish joint!\")\n return None\n else:\n return new_joint2index\n\ndef read_match(path:str):\n #clean\n path = path.replace(\"_clean\",'').replace('_intermediate','')\n # add joint\n path = path.replace(\".txt\",\"_joint.txt\")\n match_path = os.path.join(\"model\",\"match_list\",os.path.split(path)[-1])\n assert os.path.exists(match_path),\"match_file doesn't exist!\"\n match = {}\n with open(match_path,'r') as f:\n s = f.read().split('\\n')\n for line in s:\n if line == '':\n break\n line = line[line.find(':') + 1:]\n if ':' in line:\n i = line.find(':')\n match[int(line[:i])] = int(line[i + 1:])\n\n return match\n\ndef perfect_matching():\n path = os.path.join(\"model\",\"group_0\",\"fbx\")\n for file in os.listdir(path):\n if 'txt' in file:\n s = print_joint2(os.path.join(path,file),False)\n count = 0\n for joint, id in s.items():\n if joint.lower() == 'spine':\n count +=1\n if joint.lower() == 'spine1':\n count +=1\n if joint.lower() == 'spine2':\n count +=1\n if count >= 3:\n print(file)\n\ndef load_pkl(path):\n with open(path,'rb') as f:\n m = pkl.load(f)\n print(m['model2smpl'])\n\ndef save_result(good_match_list):\n if not os.path.exists(\"submit_results\"):\n os.mkdir(\"submit_results\")\n for good_match in good_match_list:\n if not os.path.exists(os.path.join(\"submit_results\",good_match)):\n os.mkdir(os.path.join(\"submit_results\",good_match))\n else:\n pass\n path_obj = os.path.join(\"model\",\"group_0\",\"fbx\",good_match+\".obj\")\n path_fbx = os.path.join(\"model\", \"group_0\", \"fbx\", good_match + \".fbx\")\n path_txt = os.path.join(\"model\", \"group_0\", \"fbx\", good_match + \".txt\")\n path_vis = os.path.join(\"results\",good_match,\"vis.mp4\")\n for file in os.listdir(os.path.join(\"results\",good_match)):\n if 'pkl' in file:\n pkl_name = file\n break\n path_pkl = os.path.join(\"results\", good_match, pkl_name)\n shutil.copy(path_obj,os.path.join(\"submit_results\",good_match,good_match+\".obj\"))\n shutil.copy(path_fbx, os.path.join(\"submit_results\", good_match, good_match + \".fbx\"))\n shutil.copy(path_txt, os.path.join(\"submit_results\", good_match, good_match + \".txt\"))\n shutil.copy(path_vis, os.path.join(\"submit_results\", good_match, \"vis.mp4\"))\n shutil.copy(path_pkl, os.path.join(\"submit_results\", good_match,pkl_name))\n\ndef add_mtl():\n for file in os.listdir(\"model/obj_seq_5_3dmodel\"):\n if \"obj\" in file:\n with open(os.path.join(\"model\",\"obj_seq_5_3dmodel\",file),'r') as f:\n record = f.readlines()\n with open(os.path.join(\"model\",\"obj_seq_5_3dmodel\",file),'w') as f:\n f.write(record[0])\n f.write(\"g skinCluster1Set tweakSet1\\n\")\n f.writelines(record[1:])","sub_path":"util_cat.py","file_name":"util_cat.py","file_ext":"py","file_size_in_byte":7158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"85549034","text":"# import ptvsd\n# ptvsd.enable_attach(address = ('0.0.0.0', 5678))\n# ptvsd.wait_for_attach()\nimport os\nimport compress_model as cm\nimport argparse\nimport numpy as np\n\ndef get_opt():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--compress_layer\", type=int, nargs='+', default = [0,1,2,3,4])\n parser.add_argument(\"--compress_block\", type=int, nargs='+', default = [1,2], help='range from 1 to 2')\n parser.add_argument(\"--compress_rate\", type=float, nargs='+', default = [0.5, 0.5])\n parser.add_argument(\"--gpu\", type=int, default = 4)\n parser.add_argument('--method', type=str, default='single')\n\n opt = parser.parse_args()\n return opt\n\nif __name__ == '__main__':\n gpu = 0\n while True:\n os.system('nvidia-smi -q -d Memory |grep -A4 GPU|grep Free >tmp')\n memory_gpu=[int(x.split()[2]) for x in open('tmp','r').readlines()]\n memory_max = max(memory_gpu)\n if memory_max>5000:\n gpu = np.argmax(memory_gpu)\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(np.argmax(memory_gpu))\n os.system('rm tmp')\n print('Find vacant GPU: %d' % gpu)\n break\n opt = get_opt()\n opt.gpu = int(gpu)\n cm.pipeline(opt)\n\n model_dir = os.path.join('/ssd/yqian/prune/model/ResNet50', '-'.join([str(i) for i in opt.compress_layer])+'_'+'-'.join([str(i) for i in opt.compress_block])+'_'+'-'.join([str(i) for i in opt.compress_rate]))\n os.system('/root/caffe/build/tools/caffe_parallel train --solver %s/solver.prototxt --weights=%s/prune.caffemodel' % (model_dir, model_dir))\n os.system('/root/caffe/build/tools/caffe_parallel test --model %s/trainval.prototxt --weights=%s/snapshot/_iter_10000.caffemodel.h5' % (model_dir, model_dir))\n os.system('python ThiNet_Code/ToolKit/FLOPs_and_size.py %s/trainval.prototxt' % model_dir)\n ","sub_path":"ThiNet_TPAMI/ResNet50/prune_finetune.py","file_name":"prune_finetune.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"55197206","text":"from keras import layers\nfrom keras import models\nfrom keras import optimizers\nfrom keras import backend as K\n\n\nimport tensorflow as tf\n\nimport numpy as np\nimport os\n\n\nclass ActorCriticAgent(object):\n \"\"\"\n Actor Critic model with continuous action space\n Input: \n N-dimensional continuous state with dimensions normalized in the range[-1,1]\n 1-dimensional reward normalized in the range [0, 1]\n Output: \n M-dimensional continuous action with dimensions normalized in the range[-1,1]\n \"\"\"\n _use_K_actor_update_function = False\n\n def __init__(self,\n state_dim,\n action_dim,\n discount_rate,\n hidden_dims,\n learning_rate,\n replay_memory_sz,\n batch_sz):\n \"\"\"\n\n :param state_dim:\n :param action_dim:\n :param discount_rate:\n :param hidden_dims:\n :param learning_rate:\n \"\"\"\n self.state_dim = state_dim\n self.action_dim = action_dim\n self.discount_rate = discount_rate\n self.replay_memory_sz = replay_memory_sz\n self.batch_size = batch_sz\n self.state_memory = np.zeros(shape=(self.replay_memory_sz, self.state_dim), dtype=float)\n self.action_memory = np.zeros(shape=(self.replay_memory_sz, self.action_dim), dtype=float)\n self.reward_memory = np.zeros(shape=self.replay_memory_sz, dtype=float)\n self.memory_index = 0\n self.step_index = 0\n # build models\n if ActorCriticAgent._use_K_actor_update_function:\n self.policy, self.critic, self.policy_training_function, self.state_ph = self._build_models(hidden_dims, learning_rate)\n else:\n self.policy, self.critic, self.actor, self.advantage_ph = self._build_models(hidden_dims, learning_rate)\n\n self.critic_training_memory = list()\n\n def _build_models(self, hidden_dims, learning_rate):\n #\n # build policy\n state_ph = layers.Input(shape=(self.state_dim,))\n hidden = layers.Dense(units=hidden_dims[0], activation='relu')(state_ph)\n for jh in np.arange(1, len(hidden_dims)):\n hidden = layers.Dense(units=hidden_dims[jh], activation='relu')(hidden)\n action = layers.Dense(units=self.action_dim, activation='tanh', use_bias=False)(hidden)\n policy_model = models.Model(input=[state_ph], output=[action], name=\"policy_model\")\n policy_model.summary()\n #\n # build critic\n action_ph = layers.Input(shape=(self.action_dim,))\n state_action = layers.concatenate([state_ph, action_ph])\n hidden = layers.Dense(units=hidden_dims[0], activation='relu')(state_action)\n for jh in np.arange(1, len(hidden_dims)):\n hidden = layers.Dense(units=hidden_dims[jh], activation='relu')(hidden)\n value = layers.Dense(units=1, activation='sigmoid', name=\"value_l\", use_bias=False)(hidden)\n critic_model = models.Model(input=[state_ph, action_ph], output=[value], name='critic_model')\n critic_model.compile(optimizer=optimizers.Adam(learning_rate=learning_rate), loss='mse')\n critic_model.summary()\n #\n # build actor\n if ActorCriticAgent._use_K_actor_update_function:\n value_ = critic_model([state_ph, action])\n policy_learn_loss = -K.log(K.clip(value_, 1e-8, 1.0))\n actor_gradients = K.gradients(loss=policy_learn_loss, variables=policy_model.trainable_weights)\n opt = tf.keras.optimizers.Adam(learning_rate=learning_rate)\n policy_train_function = opt.apply_gradients(zip(actor_gradients, policy_model.trainable_weights))\n return policy_model, critic_model, policy_train_function, state_ph\n else:\n advantage_ph = layers.Input(shape=(1,), name=\"advantage\")\n\n def custom_loss(y_true, y_pred):\n learn_loss = K.mean(K.square(y_true - y_pred)) * advantage_ph\n return learn_loss\n\n actor_model = models.Model(input=[state_ph, advantage_ph], output=[action], name='actor_model')\n actor_model.compile(optimizer=optimizers.Adam(learning_rate=learning_rate), loss=custom_loss)\n actor_model.summary()\n return policy_model, critic_model, actor_model, advantage_ph\n\n def choose_action(self, state: np.array):\n j = (self.memory_index - 1) % self.replay_memory_sz\n current_value = self.reward_memory[j]\n value_th = current_value + (1.0 - current_value) / 3.0 # I want to make at least 1/3 of my way to 1\n # try policy\n action = self.policy.predict(x=state[np.newaxis, :])[0]\n expected_value = self.critic.predict(x=[state[np.newaxis, :], action[np.newaxis, :]])[0]\n if expected_value >= value_th:\n return action\n # try random action\n action = np.array(np.random.uniform(-1.0, +1.0, size=self.action_dim))\n #\n return action\n\n def train(self, state: np.array, action: np.array, reward: np.float):\n \"\"\"\n\n :type reward: object\n \"\"\"\n # update memory and apply discount\n j = self.memory_index\n assert self.step_index % self.replay_memory_sz == j\n self.state_memory[j, :] = np.copy(state)\n self.action_memory[j, :] = np.copy(action)\n self.reward_memory[j] = 0\n discounted_reward = reward\n while discounted_reward > 1e-2:\n self.reward_memory[j] = discounted_reward\n discounted_reward *= self.discount_rate\n j = (j - 1) % self.replay_memory_sz\n if j == self.memory_index or discounted_reward < self.reward_memory[j]:\n break\n # training\n if self.step_index >= self.batch_size:\n # select training batch\n js = np.random.uniform(\n low=0,\n high=self.step_index,\n size=self.batch_size).astype(int) % self.replay_memory_sz\n state_batch = self.state_memory[js, :]\n action_batch = self.action_memory[js, :]\n reward_batch = self.reward_memory[js]\n # train critic\n cost = self.critic.train_on_batch(x=[state_batch, action_batch], y=reward_batch)\n self.critic_training_memory.append(cost)\n # train actor based on actual gain\n if ActorCriticAgent._use_K_actor_update_function:\n K.get_session().run(fetches=[self.policy_training_function], feed_dict={self.state_ph: state_batch})\n else:\n cost = self.actor.train_on_batch(x=[state_batch, reward_batch], y=action_batch)\n #predicted_value = self.critic.predict(x=[state[np.newaxis, :], action[np.newaxis, :]])[0]\n #if predicted_value >= reward:\n # advantage = np.divide(predicted_value, (1.0 - reward + 1e-8))\n # cost = self.actor.train_on_batch(x=[state[np.newaxis, :], advantage[np.newaxis, :]], y=action[np.newaxis, :])\n #\n self.memory_index = (self.memory_index + 1) % self.replay_memory_sz\n self.step_index += 1\n\n def save(self, folder, game_name):\n os.makedirs(folder, exist_ok=True)\n filename = os.path.join(folder, game_name + '_critic.h5')\n self.critic.save(filename)\n print('saved model({})'.format(filename))\n filename = os.path.join(folder, game_name + '_actor.h5')\n self.actor.save(filename)\n print('saved model({})'.format(filename))\n\n\n def load(self, folder, game_name):\n filename = os.path.join(folder, game_name + '_critic.h5')\n if os.path.exists(filename):\n self.critic.load_weights(filename)\n print('loaded model({})'.format(filename))\n filename = os.path.join(folder, game_name + '_actor.h5')\n if os.path.exists(filename):\n self.actor.load_weights(filename)\n print('loaded model({})'.format(filename))\n\n def reset(self):\n self.state_memory = np.zeros(shape=(self.replay_memory_sz, self.state_dim), dtype=float)\n self.action_memory = np.zeros(shape=(self.replay_memory_sz, self.action_dim), dtype=float)\n self.reward_memory = np.zeros(shape=self.replay_memory_sz, dtype=float)\n self.memory_index = 0\n self.step_index = 0\n","sub_path":"openai_gym/actor_critic_agent.py","file_name":"actor_critic_agent.py","file_ext":"py","file_size_in_byte":8391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"71213311","text":"from functools import reduce\n\nimport datajoint as dj\nimport numpy as np\nimport scipy.stats as stats\nimport warnings\nimport spikeinterface as si\nfrom spikeinterface.core.segmentutils import AppendSegmentRecording\n\nfrom .common_interval import IntervalList\nfrom .common_spikesorting import SpikeSortingRecording\nfrom .common_session import Session\nfrom .nwb_helper_fn import get_valid_intervals\n\nschema = dj.schema('common_artifact')\n\n@schema\nclass ArtifactDetectionParameters(dj.Manual):\n definition = \"\"\"\n # Parameters for detecting artifact times within a sort group.\n artifact_params_name: varchar(200)\n ---\n artifact_params: blob # dictionary of parameters\n \"\"\"\n def insert_default(self):\n \"\"\"Insert the default artifact parameters with an appropriate parameter dict.\n \"\"\"\n artifact_params = {}\n artifact_params['zscore_thresh'] = None # must be None or >= 0\n artifact_params['amplitude_thresh'] = 3000 # must be None or >= 0\n artifact_params['proportion_above_thresh'] = 1.0 # all electrodes of sort group\n artifact_params['removal_window_ms'] = 1.0 # in milliseconds\n self.insert1(['default', artifact_params], skip_duplicates=True) \n\n artifact_params_none = {}\n artifact_params_none['zscore_thresh'] = None \n artifact_params_none['amplitude_thresh'] = None \n self.insert1(['none', artifact_params_none], skip_duplicates=True) \n\n@schema\nclass ArtifactDetectionSelection(dj.Manual):\n definition = \"\"\"\n # Specifies artifact detection parameters to apply to a sort group's recording.\n -> SpikeSortingRecording\n -> ArtifactDetectionParameters\n ---\n \"\"\"\n\n@schema\nclass ArtifactDetection(dj.Computed):\n definition = \"\"\"\n # Stores artifact times and valid no-artifact times as intervals.\n -> ArtifactDetectionSelection\n ---\n artifact_times: longblob # np array of artifact intervals\n artifact_removed_valid_times: longblob # np array of valid no-artifact intervals\n artifact_removed_interval_list_name: varchar(200) # name of the array of no-artifact valid time intervals\n \"\"\"\n\n def make(self, key):\n # get the dict of artifact params associated with this artifact_params_name\n artifact_params = (ArtifactDetectionParameters & key).fetch1(\"artifact_params\")\n \n recording_path = (SpikeSortingRecording & key).fetch1('recording_path')\n recording = si.load_extractor(recording_path) \n \n artifact_removed_valid_times, artifact_times = _get_artifact_times(recording, **artifact_params)\n \n # NOTE: decided not to do this but to just create a single long segment; keep for now\n # get artifact times by segment\n # if AppendSegmentRecording, get artifact times for each segment\n # if isinstance(recording, AppendSegmentRecording):\n # artifact_removed_valid_times = []\n # artifact_times = []\n # for rec in recording.recording_list:\n # rec_valid_times, rec_artifact_times = _get_artifact_times(rec, **artifact_params)\n # for valid_times in rec_valid_times:\n # artifact_removed_valid_times.append(valid_times)\n # for artifact_times in rec_artifact_times:\n # artifact_times.append(artifact_times)\n # artifact_removed_valid_times = np.asarray(artifact_removed_valid_times)\n # artifact_times = np.asarray(artifact_times)\n # else:\n # artifact_removed_valid_times, artifact_times = _get_artifact_times(recording, **artifact_params)\n\n key['artifact_times'] = artifact_times\n key['artifact_removed_valid_times'] = artifact_removed_valid_times\n \n # set up a name for no-artifact times using recording id\n key['artifact_removed_interval_list_name'] = key['recording_id'] + '_' + key['artifact_params_name'] + '_artifact_removed_valid_times'\n \n # insert artifact times and valid times into ArtifactRemovedIntervalList with an appropriate name\n tmp_key = {}\n tmp_key['nwb_file_name'] = key['nwb_file_name']\n tmp_key['artifact_removed_interval_list_name'] = key['artifact_removed_interval_list_name']\n tmp_key['artifact_removed_valid_times'] = key['artifact_removed_valid_times']\n tmp_key['artifact_times'] = key['artifact_times']\n ArtifactRemovedIntervalList.insert1(tmp_key, skip_duplicates = True)\n \n # also insert into IntervalList\n tmp_key = {}\n tmp_key['nwb_file_name'] = key['nwb_file_name']\n tmp_key['interval_list_name'] = key['artifact_removed_interval_list_name']\n tmp_key['valid_times'] = key['artifact_removed_valid_times']\n IntervalList.insert1(tmp_key, skip_duplicates=True)\n \n # insert into computed table\n self.insert1(key)\n\n@schema\nclass ArtifactRemovedIntervalList(dj.Manual):\n definition = \"\"\"\n # Stores intervals without detected artifacts.\n # Note that entries can come from either ArtifactDetection() or alternative artifact removal analyses.\n -> Session\n artifact_removed_interval_list_name: varchar(200)\n ---\n artifact_removed_valid_times: longblob\n artifact_times: longblob # np array of artifact intervals\n \"\"\"\n \ndef _get_artifact_times(recording, zscore_thresh=None, amplitude_thresh=None,\n proportion_above_thresh=1.0, removal_window_ms=1.0):\n \"\"\"Detects times during which artifacts do and do not occur.\n Artifacts are defined as periods where the absolute value of the recording signal exceeds one\n OR both specified amplitude or zscore thresholds on the proportion of channels specified,\n with the period extended by the removal_window_ms/2 on each side. Z-score and amplitude\n threshold values of None are ignored.\n\n Parameters\n ----------\n recording : si.Recording\n zscore_thresh : float, optional\n Stdev threshold for exclusion, should be >=0, defaults to None\n amplitude_thresh : float, optional\n Amplitude threshold for exclusion, should be >=0, defaults to None\n proportion_above_thresh : float, optional, should be>0 and <=1\n Proportion of electrodes that need to have threshold crossings, defaults to 1 \n removal_window_ms : float, optional\n Width of the window in milliseconds to mask out per artifact (window/2 removed on each side of threshold crossing), defaults to 1 ms\n \n Returns\n ------_\n artifact_intervals : np.ndarray\n Intervals in which artifacts are detected (including removal windows), unit: seconds\n artifact_removed_valid_times : np.ndarray\n Intervals of valid times where artifacts were not detected, unit: seconds\n \"\"\"\n \n valid_timestamps = SpikeSortingRecording._get_recording_timestamps(recording)\n if recording.get_num_segments()>1:\n recording = si.concatenate_recordings(recording.recording_list)\n \n # if both thresholds are None, we essentially skip artifract detection and\n # return an array with the times of the first and last samples of the recording\n if (amplitude_thresh is None) and (zscore_thresh is None):\n recording_interval = np.asarray([valid_timestamps[0], valid_timestamps[-1]])\n artifact_times_empty = np.asarray([])\n print(\"Amplitude and zscore thresholds are both None, skipping artifact detection\")\n return recording_interval, artifact_times_empty\n \n # verify threshold parameters\n amplitude_thresh, zscore_thresh, proportion_above_thresh = _check_artifact_thresholds(amplitude_thresh, zscore_thresh, proportion_above_thresh)\n\n # turn ms to remove total into s to remove from either side of each detected artifact\n half_removal_window_s = removal_window_ms * (1/1000) * (1/2)\n \n # TODO: load by chunk to avoid memory problems\n data = recording.get_traces()\n\n # compute the number of electrodes that have to be above threshold\n nelect_above = np.ceil(proportion_above_thresh * len(recording.get_channel_ids()))\n\n # find the artifact occurrences using one or both thresholds, across channels\n if ((amplitude_thresh is not None) and (zscore_thresh is None)):\n above_a = np.abs(data) > amplitude_thresh\n above_thresh = np.ravel(np.argwhere(np.sum(above_a, axis=0) >= nelect_above))\n elif ((amplitude_thresh is None) and (zscore_thresh is not None)):\n dataz = np.abs(stats.zscore(data, axis=1))\n above_z = dataz > zscore_thresh\n above_thresh = np.ravel(np.argwhere(np.sum(above_z, axis=0) >= nelect_above))\n else:\n above_a = np.abs(data) > amplitude_thresh\n dataz = np.abs(stats.zscore(data, axis=1))\n above_z = dataz > zscore_thresh\n above_thresh = np.ravel(np.argwhere(\n np.sum(np.logical_or(above_z, above_a), axis=0) >= nelect_above))\n \n if len(above_thresh) == 0:\n recording_interval = np.asarray([[valid_timestamps[0], valid_timestamps[-1]]])\n artifact_times_empty = np.asarray([])\n print(\"No artifacts detected.\")\n return recording_interval, artifact_times_empty\n\n above_thresh_times = valid_timestamps[above_thresh] # find timestamps of initial artifact threshold crossings\n \n # keep track of all the artifact timestamps within each artifact removal window and the indices of those timestamps\n artifact_times = []\n artifact_indices = []\n for a in above_thresh_times:\n a_times = np.copy(valid_timestamps[(valid_timestamps > (a - half_removal_window_s)) & (valid_timestamps <= (a + half_removal_window_s))])\n a_indices = np.argwhere((valid_timestamps > (a - half_removal_window_s)) & (valid_timestamps <= (a + half_removal_window_s)))\n artifact_times.append(a_times)\n artifact_indices.append(a_indices)\n all_artifact_times = reduce(np.union1d, artifact_times)\n all_artifact_indices = reduce(np.union1d, artifact_indices)\n # turn artifact detected times into intervals\n if not np.all(all_artifact_times[:-1] <= all_artifact_times[1:]): #should be faster than diffing and comparing to zero\n warnings.warn(\"Warning: sorting artifact timestamps; all_artifact_times was not strictly increasing\")\n all_artifact_times = np.sort(all_artifact_times)\n artifact_intervals = get_valid_intervals(all_artifact_times, recording.get_sampling_frequency(), 1.5, .000001)\n\n artifact_percent_of_times = 100 * len(all_artifact_times) / len(valid_timestamps)\n print(f\"{len(artifact_intervals)} artifact intervals detected;\\\n {artifact_percent_of_times} % of the recording's valid_timestamps removed as artifact\")\n \n # turn all artifact detected times into -1 to easily find non-artifact intervals\n valid_timestamps[all_artifact_indices] = -1\n artifact_removed_valid_times = get_valid_intervals(valid_timestamps[valid_timestamps != -1], \n recording.get_sampling_frequency(), 1.5, 0.000001) \n \n return artifact_removed_valid_times, artifact_intervals\n\ndef _check_artifact_thresholds(amplitude_thresh, zscore_thresh, proportion_above_thresh):\n \"\"\"Alerts user to likely unintended parameters. Not an exhaustive verification.\n\n Parameters\n ----------\n zscore_thresh: float\n amplitude_thresh: float\n proportion_above_thresh: float\n\n Return\n ------\n zscore_thresh: float\n amplitude_thresh: float\n proportion_above_thresh: float\n\n Raise\n ------\n ValueError: if signal thresholds are negative \n \"\"\"\n # amplitude or zscore thresholds should be negative, as they are applied to an absolute signal\n signal_thresholds = [t for t in [amplitude_thresh, zscore_thresh] if t is not None]\n for t in signal_thresholds:\n if t < 0:\n raise ValueError(\"Amplitude and Z-Score thresholds must be >= 0, or None\")\n \n # proportion_above_threshold should be in [0:1] inclusive\n if proportion_above_thresh < 0:\n warnings.warn(\"Warning: proportion_above_thresh must be a proportion >0 and <=1. Using proportion_above_thresh = 0.01 instead of \"+str(proportion_above_thresh))\n proportion_above_thresh = 0.01\n elif proportion_above_thresh > 1:\n warnings.warn(\"Warning: proportion_above_thresh must be a proportion >0 and <=1. Using proportion_above_thresh = 1 instead of \"+str(proportion_above_thresh))\n proportion_above_thresh = 1\n return amplitude_thresh, zscore_thresh, proportion_above_thresh\n","sub_path":"src/nwb_datajoint/common/common_artifact.py","file_name":"common_artifact.py","file_ext":"py","file_size_in_byte":12488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"313999062","text":"# -*- coding: utf-8 -*-\nfrom conta import Conta\n\ntry:\n\traw_input\nexcept NameError:\n\traw_input = input\n\nusuario = raw_input(\"Proprietário da conta: \")\nsaldo = float(raw_input(\"Saldo do proprietário: \"))\n\nconta_usuario = Conta(usuario, saldo)\n\nwhile True:\n\tprint(\"\"\"\n\t1) Consultar saldo atual\n\t2) Realizar depósito\n\t3) Realizar saque\n\t\"\"\")\n\n\tescolha = raw_input(\"\\033[0;36m Escolha: \\033[0m\")\n\n\tif escolha == '1':\n\t\tprint(\"Saldo Atual: \\033[0;33m R$ %.2f\\033[0m\\n\\n\"%conta_usuario.saldo)\n\t\n\telif escolha == '2':\n\t\tdeposito = float(raw_input(\"Valor a ser depositado: \\033[0;32m\"))\n\t\tprint(\"\\033[0m\")\n\t\tconta_usuario.depositar(deposito)\n\t\n\telif escolha == '3':\n\t\tsaque = float(raw_input(\"Valor a ser sacado: \\033[0;31m\"))\n\t\tprint(\"\\033[0m\")\n\t\tconta_usuario.sacar(saque)\n","sub_path":"python/banco/python3/banco.py","file_name":"banco.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"362785562","text":"#helpful code: http://brianfarris.me/static/digit_recognizer.html\nfrom __future__ import print_function\nimport numpy as np\nimport time\nimport psutil\nimport sklearn\nfrom sklearn import cross_validation\nfrom sklearn.svm import LinearSVC\nfrom sklearn.metrics import accuracy_score\nimport keras\nfrom keras.datasets import fashion_mnist\nfrom sklearn.model_selection import StratifiedShuffleSplit\n\nstart_time=time.time()\n\n# load the MNIST digits dataset\n(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()\n\n#format data\nx_train = x_train.reshape(60000, 784)\nx_test = x_test.reshape(10000, 784)\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train /= 255\nx_test /= 255\nprint(\"Training matrix shape\", x_train.shape)\nprint(\"Testing matrix shape\", x_test.shape)\n\nresults=[]\nlist1=[] \nlist2=[] \nlist3=[]\n\nfor q in range(0,7):\n\trng = [2,3,4,5,10,20,40,60,80,100,200,400,600,800,1000,2000,3000,4000,5000] #limit is 5000: 50000 train, 10000 valid\t\n\tfor i in rng:\n\t\t################ CREATING TRAIN AND VAL SETS #################\n\t\tprint(\"########################\")\t\t\n\n\t\t#TRAINING DATA: Creating i instances of each class, VAL DATA: taking 20% of Train\n\t\tnum_train=i*10\n\t\tif(i>=5):\t\t\t\n\t\t\tnum_test=int(0.2*num_train)\n\t\telse:\n\t\t\tnum_test=10\n\n\t\ttrain_sss = StratifiedShuffleSplit(n_splits=5, \n test_size=num_test, train_size=num_train, random_state=0) \n\t\tfor train_index, test_index in train_sss.split(x_train, y_train):\n\t\t tempx_train, tempx_val = x_train[train_index], x_train[test_index]\n\t\t tempy_train, tempy_val = y_train[train_index], y_train[test_index]\n\t\tprint(\"size of svm balanced training set:\", len(tempx_train))\n\t\tprint(\"size of svm balanced val set:\", len(tempx_val))\n\t\n\t\t#verifying correct numbers\n\t\tprint(tempx_train.shape[0], 'train samples')\n\t\tprint(tempx_val.shape[0], 'valid samples')\n\t\tprint(x_test.shape[0], 'test samples')\n\t\t#################################################################\n\n\t\tprint(\"EVALUATION ON TESTING DATA FOR\", num_train, \"TRAINING DATA POINTS\")\n\t\tclf_svm = LinearSVC()\n\t\tclf_svm.fit(tempx_train, tempy_train)\n\t\ty_pred_svm = clf_svm.predict(x_test)\n\t\tacc_svm = accuracy_score(y_test, y_pred_svm)\n\t\tprint(\"Linear SVM accuracy: \",acc_svm)\n\t\tresults=[i,acc_svm]\n\t\tif(q==0):\n\t\t\tlist1.append(results)\n\t\telif(q==1):\n\t\t\tlist2.append(results)\n\t\telse:\n\t\t\tlist3.append(results)\n\ndatapoints=len(list1)\n######finding the variance of three tests#######\nvariance=np.zeros((datapoints,2))\neach_pt=np.zeros((3,2))\nfor num in range(0,datapoints):\n\tvariance[num][0]=list1[num][0]\n\teach_pt[0][0]=list1[num][0]\n\teach_pt[0][1]=list1[num][1]\n\teach_pt[1][0]=list2[num][0]\n\teach_pt[1][1]=list2[num][1]\n\teach_pt[2][0]=list3[num][0]\n\teach_pt[2][1]=list3[num][1]\n\teach_var=np.var(each_pt,axis=0)\n\tvariance[num][1]=each_var[1]\nprint(variance)\n\n######finding the average of three tests########\noverall=np.zeros((datapoints,2))\t\t\nfor num in range(0,datapoints):\n\toverall[num][0]=list1[num][0]\t\n\toverall[num][1]=list1[num][1]+list2[num][1]+list3[num][1]\nfor num in range(0,datapoints):\n\toverall[num][1]=(overall[num][1])/3.0\n\nprint(overall)\n\n######finding the change in accuracy############\nacc_change=np.zeros((datapoints-1,2))\nfor num in range(1,datapoints):\n\tacc_change[num-1][0]=num-1\n\tacc_change[num-1][1]=overall[num][1]-overall[num-1][1]\nprint(acc_change)\n\nnp.savetxt(\"svm_VariableTrainSet.csv\",overall,delimiter=\",\")\nnp.savetxt(\"svm_Variance.csv\",variance,delimiter=\",\")\nnp.savetxt(\"svm_AccuracyChange.csv\",acc_change,delimiter=\",\")\n\nprint(\"Total Time Elapsed: \", round(time.time()-start_time,1), \"seconds\")\nprint(psutil.virtual_memory())\n","sub_path":"mnist_fashion_svm.py","file_name":"mnist_fashion_svm.py","file_ext":"py","file_size_in_byte":3616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"109136351","text":"from sunpy.extern.sunkit_instruments.lyra import (\n get_lytaf_event_types,\n get_lytaf_events,\n remove_lytaf_events_from_timeseries,\n split_series_using_lytaf,\n)\n\n__all__ = ['remove_lytaf_events_from_timeseries',\n 'get_lytaf_events',\n 'get_lytaf_event_types',\n 'split_series_using_lytaf']\n\n# Trick the docs into thinking these functions are defined in here.\nfor _a in (get_lytaf_event_types,\n get_lytaf_events,\n remove_lytaf_events_from_timeseries,\n split_series_using_lytaf):\n _a.__module__ = __name__\n","sub_path":"sunpy/instr/lyra.py","file_name":"lyra.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"96084023","text":"from fastapi import FastAPI\r\nfrom books_route import router as books_router\r\n\r\napp = FastAPI()\r\n\r\napp.include_router(books_router)\r\n\r\n@app.get(\"/\")\r\nasync def read_main():\r\n return {\"message\": \"Hello Bigger Applications!\"}","sub_path":"mongodb app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"504437823","text":"from random import random\n\ndef main():\n\tprint(\"e = %.16f\\n\" % calc_e())\n\tprint(\"Average number of choices: %f\" % sum_randoms_simulation())\n\n\n# Test sum_randoms; it should converge to e (2.718281828)\ndef sum_randoms_simulation():\n sum = 0\n num_trials = 1000000\n for i in range(num_trials):\n sum += sum_randoms()\n\n return float(sum) / num_trials\n\n\n# Sum random numbers until the sum exceeds 1.0. Return the number of choices.\ndef sum_randoms():\n sum = 0.0\n n = 0\n while sum <= 1.0:\n x = random() \n sum += x\n n += 1\n\n return n\n\n\n# Calculate the number e up to a specified precision.\ndef calc_e():\n\n\tPRECISION = 0.000000001\n\te = 1\n\tn = 1\n\tprev = 0\n\n\twhile (e - prev) > PRECISION:\n\t\tprev = e\n\t\te += 1.0 / factorial(n)\n\t\tprint(\"n = %d; e = %f\\t\" % (n, e)),\n\t\tn += 1\n\n\treturn e\n\n\n# Calculate factorial of a given number.\ndef factorial(n):\n\tr = 1\n\tfor i in range(1, n+1):\n\t\tr *= i\n\treturn r\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"e.py","file_name":"e.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"94130162","text":"def transform_int_from(value: str, base: int):\n \"\"\"\n transform int string\n :param value: string like \"b9\"\n :param base: int like 90\n :return: int like 999\n \"\"\"\n if base < 2 or base > 90:\n return None\n\n value = value.strip()\n\n base_str = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$%^&*()-_=+|;:,<.>/?`~[]{}\"\n list_value = list(value)\n result_value = 0\n while len(list_value) > 0:\n result_value += base_str.find(list_value[0]) * (base ** (len(list_value) - 1))\n del list_value[0]\n return result_value\n\n\ndef transform_int_to(value: int, base: int):\n \"\"\"\n transform int\n :param value: int like 999\n :param base: int like 90\n :return: string like \"b9\"\n \"\"\"\n if base < 2 or base > 90:\n return None\n\n base_str = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$%^&*()-_=+|;:,<.>/?`~[]{}\"\n list_value = []\n while value != 0:\n list_value.append(base_str[value % base])\n value = int(value / base)\n list_value.reverse()\n return \"\".join(list_value)\n","sub_path":"src/common/IntegerTransform.py","file_name":"IntegerTransform.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"654420260","text":"import os\nfrom fd.file import File\n\n\nclass Dir:\n \"\"\"\n Handle a directory's contents\n \"\"\"\n def __init__(self, rel_path: str):\n \"\"\"\n :param rel_path: relative path to the directory\n \"\"\"\n self.path: str = rel_path\n self.dirs: [Dir] = self.__resolve_path(os.path.isdir, Dir)\n self.files: [File] = self.__resolve_path(lambda x: os.path.isfile(x) and x.endswith(\".csv\"), File)\n\n def get_files_recursively(self, all_files) -> list:\n \"\"\"\n Retrieve all files from the parent and child directories\n\n :param list all_files: iterable; write the results\n :return: list of files from the current directory\n :rtype: list\n \"\"\"\n if len(self.dirs) < 1:\n all_files.extend(self.files)\n return all_files\n\n all_files.extend(self.files)\n [d.get_files_recursively(all_files) for d in self.dirs]\n\n return all_files\n\n def __resolve_path(self, check, instance) -> list:\n \"\"\"\n Resolve the contents of the given path\n\n :param callable check: Filter for which files to add\n :param callable instance: What instance must be created\n :return: list of instances\n \"\"\"\n tmp = list()\n for f in os.listdir(self.path):\n _path = os.path.join(self.path, f)\n\n if check(_path):\n tmp.append(instance(_path))\n return tmp\n\n def __str__(self):\n res = \"\"\n _dirs = [x.path for x in self.dirs]\n _files = [x.path for x in self.files]\n\n if len(_dirs) > 0:\n res += \"Directories\\n\"\\\n \"-----------\\n\"\n for x in _dirs:\n res += x + \"\\n\"\n res += \"\\n\"\n\n if len(_files) > 0:\n res += \"Files\\n\"\\\n \"-----\\n\"\n for x in _files:\n res += x + \"\\n\"\n\n return res\n","sub_path":"src/fd/dir.py","file_name":"dir.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"632881483","text":"\n\nfrom xai.brain.wordbase.nouns._tomfoolery import _TOMFOOLERY\n\n#calss header\nclass _TOMFOOLERIES(_TOMFOOLERY, ):\n\tdef __init__(self,): \n\t\t_TOMFOOLERY.__init__(self)\n\t\tself.name = \"TOMFOOLERIES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"tomfoolery\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_tomfooleries.py","file_name":"_tomfooleries.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"565146079","text":"#!/usr/bin/env python2.7\n#coding:utf-8\n\nimport sys\nimport time\nimport socket\nimport logging\nimport subprocess\nfrom StringIO import StringIO\nfrom daemonize import Daemonize\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n\nclass CheckAdmin(object):\n def __init__(self):\n self.address = '127.0.0.1' \n self.port = 9090\n self.request = 'GET /login HTTP/1.1\\r\\nHost:127.0.0.1\\r\\n\\r\\n'\n \n def check(self, logger):\n try:\n s = socket.socket()\n s.connect((self.address, self.port))\n s.send(self.request)\n line = s.recv(100)\n status = line.split()[1]\n except Exception as e:\n logger.info(str(e))\n return\n else:\n if status != '200':\n logger.info('admin down {0:=<{1}} '.format(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(int(time.time()))), 50))\n cmd = '''\n cd /data/www/center-new/http/ ;\n sh shutdown.sh ;\n sh startup.sh\n '''\n logger.info(subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate())\n finally:\n s.close()\n return\n\n __call__ = check \n\ndef main():\n logger.info('check admin up/down')\n while True:\n time.sleep(120)\n check_admin(logger)\n\npid = \"/data/tmp/check_admin.pid\"\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nlogger.propagate = False\nfh = logging.FileHandler(\"/data/tmp/check_admin.log\", \"w\")\nfh.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(asctime)-8s: %(message)s')\nfh.setFormatter(formatter)\nlogger.addHandler(fh)\nkeep_fds = [fh.stream.fileno()]\n\ncheck_admin = CheckAdmin()\ndaemon = Daemonize(app='check_admin', pid=pid, action=main, keep_fds=keep_fds)\ndaemon.start()\n","sub_path":"check_admin.py","file_name":"check_admin.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"29773191","text":"\nfrom sample_players import DataPlayer\n\n\nclass CustomPlayer(DataPlayer):\n \"\"\" Implement your own agent to play knight's Isolation\n\n The get_action() method is the only *required* method. You can modify\n the interface for get_action by adding named parameters with default\n values, but the function MUST remain compatible with the default\n interface.\n\n **********************************************************************\n NOTES:\n - You should **ONLY** call methods defined on your agent class during\n search; do **NOT** add or call functions outside the player class.\n The isolation library wraps each method of this class to interrupt\n search when the time limit expires, but the wrapper only affects\n methods defined on this class.\n\n - The test cases will NOT be run on a machine with GPU access, nor be\n suitable for using any other machine learning techniques.\n **********************************************************************\n \"\"\"\n def get_action(self, state):\n \"\"\" Employ an adversarial search technique to choose an action\n available in the current state calls self.queue.put(ACTION) at least\n\n This method must call self.queue.put(ACTION) at least once, and may\n call it as many times as you want; the caller is responsible for\n cutting off the function after the search time limit has expired. \n\n See RandomPlayer and GreedyPlayer in sample_players for more examples.\n\n **********************************************************************\n NOTE: \n - The caller is responsible for cutting off search, so calling\n get_action() from your own code will create an infinite loop!\n Refer to (and use!) the Isolation.play() function to run games.\n **********************************************************************\n \"\"\"\n # TODO: Replace the example implementation below with your own search\n # method by combining techniques from lecture\n #\n # EXAMPLE: choose a random move without any search--this function MUST\n # call self.queue.put(ACTION) at least once before time expires\n # (the timer is automatically managed for you)\n import random\n # randomly select a move as player 1 or 2 on an empty board, otherwise\n # return the optimal alphabeta move at a fixed search depth \n if state.ply_count < 2: self.queue.put(random.choice(state.actions()))\n self.queue.put(self.alphabeta(state, depth = 3))\n \n def alphabeta(self, gameState, depth, alpha = float(\"-inf\"), beta = float('inf')):\n \"\"\" Return the move along a branch of the game tree that\n has the best possible value. A move is a pair of coordinates\n in (column, row) order corresponding to a legal move for\n the searching player.\n \n You can ignore the special case of calling this function\n from a terminal state.\n \"\"\"\n alpha = float(\"-inf\")\n beta = float('inf')\n best_score = float(\"-inf\")\n best_move = None\n\n def max_value(gameState, depth, alpha, beta):\n \"\"\" Return the value for a loss (-1) if the game is over,\n otherwise return the maximum value over all legal child\n nodes.\n \"\"\"\n if gameState.terminal_test() or depth <= 0: \n return self.score_alpha_beta(gameState)\n v = float('-inf')\n for action in gameState.actions():\n # the depth should be decremented by 1 on each call\n v = max(v, min_value(gameState.result(action), depth - 1, alpha, beta))\n if v >= beta:\n return v\n alpha = max(alpha, v)\n \n return v\n def min_value(gameState, depth, alpha, beta):\n \"\"\" Return the value for a win (+1) if the game is over,\n otherwise return the minimum value over all legal child\n nodes.\n \"\"\"\n if gameState.terminal_test() or depth <= 0: \n return self.score_alpha_beta(gameState)\n v = float('inf')\n for action in gameState.actions():\n # the depth should be decremented by 1 on each call\n v = min(v, max_value(gameState.result(action), depth - 1, alpha, beta))\n if v <= alpha:\n return v\n beta = min(beta, v)\n \n return v\n for action in gameState.actions():\n # call has been updated with a depth limit\n value = min_value(gameState.result(action), depth - 1, alpha, beta)\n alpha = max(alpha, value)\n if value > best_score:\n best_score = value\n best_move = action\n return best_move\n \n def score_alpha_beta(self, state):\n own_loc = state.locs[self.player_id]\n opp_loc = state.locs[1 - self.player_id]\n own_liberties = state.liberties(own_loc)\n opp_liberties = state.liberties(opp_loc)\n if len(own_liberties) < len(opp_liberties):\n return 2*len(own_liberties) - len(opp_liberties)\n else:\n return len(own_liberties) - 2*len(opp_liberties)","sub_path":"Projects/3_Adversarial Search/my_custom_player.py","file_name":"my_custom_player.py","file_ext":"py","file_size_in_byte":5309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"512334895","text":"import math\nimport pygame\n\natraction = 0.02\n\nclass Link(object):\n def __init__(self, node1, node2, strength=1):\n self.node1 = node1\n self.node2 = node2\n self.strength = strength\n node1.add_link(self)\n node2.add_link(self)\n\n def update(self):\n if self.node1.pos != None and self.node2.pos != None:\n rel = (self.node2.pos[0]-self.node1.pos[0], self.node2.pos[1]-self.node1.pos[1])\n self.node1.velocity = (self.node1.velocity[0]+(rel[0]*atraction*self.strength), self.node1.velocity[1]+(rel[1]*atraction*self.strength))\n self.node2.velocity = (self.node2.velocity[0]-(rel[0]*atraction*self.strength), self.node2.velocity[1]-(rel[1]*atraction*self.strength))\n\n def draw(self, surface):\n rel = (self.node2.pos[0]-self.node1.pos[0], self.node2.pos[1]-self.node1.pos[1])\n distance = math.sqrt(rel[0]**2 + rel[1]**2)\n rel_distance1 = (self.node1.radius if not (self.node1.selected or self.node1.hovering) else self.node1.selected_radius) / (distance+1)\n rel_distance2 = (self.node2.radius if not (self.node2.selected or self.node2.hovering) else self.node2.selected_radius) / (distance+1)\n start_point = (self.node1.pos[0]+(rel[0]*rel_distance1), self.node1.pos[1]+(rel[1]*rel_distance1))\n end_point = (self.node2.pos[0]-(rel[0]*rel_distance2), self.node2.pos[1]-(rel[1]*rel_distance2))\n pygame.draw.line(surface, (0, 0, 0), start_point, end_point, int(self.strength))\n","sub_path":"link.py","file_name":"link.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"366275708","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('movies', '0005_movie_image1'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='movie',\n name='image1',\n field=models.ImageField(upload_to=b'movies/images/icons/', blank=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"movies/migrations/0006_auto_20161018_1712.py","file_name":"0006_auto_20161018_1712.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"60348044","text":"import os\nimport numpy as np\nimport struct\nimport matplotlib.pyplot as plt\n\nX_SIZE = 5\nY_SIZE = 1\nN = 50000\n\nnp.random.seed(2018)\n\nsample_in_bytes = bytearray()\nsample_out_bytes = bytearray()\nsample_in_head = np.zeros(8).astype(\"int32\")\nsample_out_head = np.zeros(8).astype(\"int32\")\n\nsample_in_head[1:4] = [1, 1, X_SIZE]\nsample_out_head[1:4] = [1, 1, Y_SIZE]\n\nsample_in_bytes += sample_in_head.tobytes()\nsample_out_bytes += sample_out_head.tobytes()\n\nX = np.random.rand(N, X_SIZE).astype(\"float32\")\n\nY = 50*(X[:,0]**3) + 20*(X[:,1]**2) + 2*X[:,2] + 1*X[:,3] + 0*X[:,4]\nY = (Y - Y.min()) / (Y.max() - Y.min()) - 0.5\nprint(X.max(), X.min(), X.shape, Y.shape)\n\nsample_in_bytes += X.tobytes()\nsample_out_bytes += Y.tobytes()\n\nwith open(\"train_in.smpl\", \"wb\") as file:\n\tfile.write(sample_in_bytes)\n\nwith open(\"train_out.smpl\", \"wb\") as file:\n\tfile.write(sample_out_bytes)","sub_path":"examples/sensitivity_analysis/get_sample.py","file_name":"get_sample.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"267529914","text":"#!/usr/bin/env python3\n\"\"\"File that contains the function posterior\"\"\"\nimport numpy as np\n\n\ndef posterior(x, n, P, Pr):\n \"\"\"\n x is the number of patients that develop severe side effects\n n is the total number of patients observed\n P is a 1D numpy.ndarray containing the various hypothetical\n probabilities of developing severe side effects\n Pr is a 1D numpy.ndarray containing the prior beliefs of P\n \"\"\"\n if type(n) is not int or n <= 0:\n raise ValueError(\"n must be a positive integer\")\n if type(x) is not int or x < 0:\n raise ValueError(\n \"x must be an integer that is greater than or equal to 0\")\n if x > n:\n raise ValueError(\"x cannot be greater than n\")\n if type(P) is not np.ndarray or len(P.shape) != 1:\n raise TypeError(\"P must be a 1D numpy.ndarray\")\n if type(Pr) is not np.ndarray or Pr.shape != P.shape:\n raise TypeError(\"Pr must be a numpy.ndarray with the same shape as P\")\n for value in range(P.shape[0]):\n if P[value] > 1 or P[value] < 0:\n raise ValueError(\"All values in P must be in the range [0, 1]\")\n if Pr[value] > 1 or Pr[value] < 0:\n raise ValueError(\"All values in Pr must be in the range [0, 1]\")\n if np.isclose([np.sum(Pr)], [1]) == [False]:\n raise ValueError(\"Pr must sum to 1\")\n\n factorial = np.math.factorial\n fact_coefficient = factorial(n) / (factorial(n - x) * factorial(x))\n likelihood = fact_coefficient * (P ** x) * ((1 - P) ** (n - x))\n\n intersection = likelihood * Pr\n\n marginal = np.sum(intersection)\n\n posterior = intersection / marginal\n return posterior\n","sub_path":"math/0x07-bayesian_prob/3-posterior.py","file_name":"3-posterior.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"281175453","text":"#!/usr/bin/python3\n\nimport pytest\n\nfrom brownie import accounts\n\n\n@pytest.fixture(scope=\"module\", autouse=True)\ndef setup(approve_many, issuer, token):\n token.mint(issuer, 100000, {'from': accounts[0]})\n token.transfer(accounts[1], 1000, {'from': accounts[0]})\n\n\ndef test_transfer_from(token):\n '''investor transferFrom - approved'''\n token.approve(accounts[3], 500, {'from': accounts[1]})\n assert token.allowance(accounts[1], accounts[3]) == 500\n token.transferFrom(accounts[1], accounts[2], 400, {'from': accounts[3]})\n assert token.allowance(accounts[1], accounts[3]) == 100\n token.transferFrom(accounts[1], accounts[2], 100, {'from': accounts[3]})\n assert token.allowance(accounts[1], accounts[3]) == 0\n\n\ndef test_transfer_from_investor_no_approval(token):\n '''transferFrom - no approval'''\n with pytest.reverts(\"Insufficient allowance\"):\n token.transferFrom(accounts[1], accounts[2], 1000, {'from': accounts[3]})\n\n\ndef test_transfer_from_investor_insufficient_approval(token):\n '''transferFrom - insufficient approval'''\n token.approve(accounts[3], 500, {'from': accounts[1]})\n with pytest.reverts(\"Insufficient allowance\"):\n token.transferFrom(accounts[1], accounts[2], 1000, {'from': accounts[3]})\n\n\ndef test_transfer_from_same_id(kyc, token):\n '''transferFrom - same investor ID'''\n kyc.registerAddresses(kyc.getID(accounts[1]), [accounts[-1]], {'from': accounts[0]})\n token.transferFrom(accounts[1], accounts[2], 500, {'from': accounts[-1]})\n\n\ndef test_transfer_from_issuer(token):\n '''issuer transferFrom'''\n token.transferFrom(accounts[1], accounts[2], 1000, {'from': accounts[0]})\n\n\ndef test_authority_permission(issuer, token):\n '''authority transferFrom permission'''\n issuer.addAuthority([accounts[-1]], [\"0x23b872dd\"], 2000000000, 1, {'from': accounts[0]})\n token.transferFrom(accounts[1], accounts[2], 500, {'from': accounts[-1]})\n issuer.setAuthoritySignatures(\n issuer.getID(accounts[-1]),\n [\"0x23b872dd\"],\n False,\n {'from': accounts[0]}\n )\n with pytest.reverts(\"Authority not permitted\"):\n token.transferFrom(accounts[1], accounts[2], 500, {'from': accounts[-1]})\n","sub_path":"tests/SecurityToken/transfer/test_token_transfer_from.py","file_name":"test_token_transfer_from.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"483153949","text":"\"\"\"\nRRT* for simulations\nAuthor: Ellie Cho\nEditor: Yashwanth Nakka\n\"\"\"\n\n\nimport math\nimport os\nimport random\nimport sys\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom RRT import RRT\nfrom Node import Node\n\nshow_animation = True\nshow_graph = False\n\n\nclass RRTStar(RRT):\n \"\"\"\n Class for RRT Star planning\n \"\"\"\n def __init__(self, start, goal, obstacle_list, rand_area, rand_angle, vrange,\n expand_dis=3.0, path_resolution=0.5, goal_sample_rate=5, max_iter=500,\n connect_circle_dist=50.0\n ):\n \"\"\"\n Setting Parameter\n start:Start Position [x,y,0,0,0,0]\n goal:Goal Position [x,y,0,0,0,0]\n obstacleList:obstacle Positions [[x,y,size],...]\n randArea:Random Sampling Area [min,max]\n \"\"\"\n self.start = Node([start[0], start[1], 0, 0, 0, 0])\n self.end = Node([goal[0], goal[1], 0, 0, 0, 0])\n self.min_rand = rand_area[0]\n self.max_rand = rand_area[1]\n self.expand_dis = expand_dis\n self.path_resolution = path_resolution\n self.goal_sample_rate = goal_sample_rate\n self.max_iter = max_iter\n self.obstacle_list = obstacle_list\n self.node_list = []\n \n \n self.connect_circle_dist = connect_circle_dist\n self.goal_node = Node([goal[0], goal[1], 0, 0, 0, 0])\n\n def planning(self, animation=True, search_until_max_iter=True):\n \"\"\"\n rrt star path planning\n animation: flag for animation on or off\n search_until_max_iter: search until max iteration for path improving or not\n \"\"\"\n\n self.node_list = [self.start]\n for i in range(self.max_iter):\n print(\"Iter:\", i, \", number of nodes:\", len(self.node_list))\n rnd_node = self.get_random_node()\n nearest_ind = self.get_nearest_node_index(self.node_list, rnd_node)\n nearest_node = self.node_list[nearest_ind]\n new_node = self.steer(nearest_node, rnd_node, self.expand_dis)\n #print(\"x:\", new_node.x[0], \"y:\", new_node.x[1])\n if self.check_collision(new_node, self.obstacle_list):\n near_inds = self.find_near_nodes(new_node)\n new_node = self.choose_parent(new_node, near_inds)\n if new_node:\n self.node_list.append(new_node)\n self.rewire(new_node, near_inds)\n # print(\"x:\", new_node.x[0], \"y:\", new_node.x[1])\n\n if animation and i % 5 == 0:\n self.draw_graph1(rnd_node)\n\n if (not search_until_max_iter) and new_node: # check reaching the goal\n last_index = self.search_best_goal_node()\n if last_index:\n print (\"last\")\n return self.generate_final_course(last_index)\n\n\n print(\"reached max iteration\")\n\n\n last_index = self.search_best_goal_node()\n if last_index:\n print (\"last\")\n return self.generate_final_course(last_index)\n\n return None\n\n def choose_parent(self, new_node, near_inds):\n \"\"\"\n chooses the parent with minimum cost and returns the node\n \n \"\"\"\n\n\n if not near_inds:\n return None\n\n # search nearest cost in near_inds\n costs = []\n for i in near_inds:\n near_node = self.node_list[i]\n t_node = self.steer(near_node, new_node)\n if t_node and self.check_collision(t_node, self.obstacle_list):\n costs.append(self.calc_new_cost(near_node, new_node))\n else:\n costs.append(float(\"inf\")) # the cost of collision node\n min_cost = min(costs)\n # print(\"min cost:\", min_cost)\n\n if min_cost == float(\"inf\"):\n print(\"There is no good path.(min_cost is inf)\")\n return None\n\n min_ind = near_inds[costs.index(min_cost)]\n new_node = self.steer(self.node_list[min_ind], new_node)\n new_node.parent = self.node_list[min_ind]\n new_node.cost = min_cost\n\n return new_node\n def search_best_goal_node(self):\n \"\"\"\n searches for the goal node with the least cost and returns the index\n\n \"\"\"\n dist_to_goal_list = [self.calc_dist_to_goal(n.x[0], n.x[1]) for n in self.node_list]\n goal_inds = [dist_to_goal_list.index(i) for i in dist_to_goal_list if i <= self.expand_dis]\n\n safe_goal_inds = []\n for goal_ind in goal_inds:\n t_node = self.steer(self.node_list[goal_ind], self.goal_node)\n if self.check_collision(t_node, self.obstacle_list):\n safe_goal_inds.append(goal_ind)\n\n if not safe_goal_inds:\n return None\n\n min_cost = min([self.node_list[i].cost for i in safe_goal_inds])\n for i in safe_goal_inds:\n if self.node_list[i].cost == min_cost:\n return i\n\n\n return None\n\n def find_near_nodes(self, new_node):\n \"\"\"\n finds nodes near the new node\n \n \"\"\"\n \n nnode = len(self.node_list) + 1\n r = self.connect_circle_dist * math.sqrt((math.log(nnode) / nnode))\n # if expand_dist exists, search vertices in a range no more than expand_dist\n if hasattr(self, 'expand_dis'): \n r = min(r, self.expand_dis)\n dist_list = [(node.x[0] - new_node.x[0]) ** 2 +\n (node.x[1] - new_node.x[1]) ** 2 +\n (node.x[2] - new_node.x[2]) ** 2 for node in self.node_list]\n near_inds = [dist_list.index(i) for i in dist_list if i <= r ** 2]\n return near_inds\n\n\n def rewire(self, new_node, near_inds):\n \n \n for i in near_inds:\n near_node = self.node_list[i]\n edge_node = self.steer(new_node, near_node)\n if not edge_node:\n continue\n edge_node.cost = self.calc_new_cost(new_node, near_node)\n\n no_collision = self.check_collision(edge_node, self.obstacle_list)\n improved_cost = near_node.cost > edge_node.cost\n\n if no_collision and improved_cost:\n self.node_list[i] = edge_node\n self.propagate_cost_to_leaves(new_node)\n\n def calc_new_cost(self, from_node, to_node):\n \"\"\"\n calculates cost from node to node\n \n \"\"\"\n\n d, _ = self.calc_distance_and_angle(from_node, to_node)\n # print(\"d:\", d)\n return (from_node.cost + d)\n\n def propagate_cost_to_leaves(self, parent_node):\n \"\"\"\n gives cost to nodes in tree\n \n \"\"\"\n \n for node in self.node_list:\n if node.parent == parent_node:\n node.cost = self.calc_new_cost(parent_node, node)\n self.propagate_cost_to_leaves(node)\n\n\ndef main(gx=8.0, gy=4.0):\n print(\"Start \" + __file__)\n\n # ====Search Path with RRT====\n obstacleList = [\n (2, 0, 2),\n (7, 0, 2),\n (4, 5, 2)\n ] # [x, y, radius]\n\n # Set Initial parameters\n rrt_star = RRTStar(start=[0, 2],\n goal=[gx, gy],\n rand_area=[-2, 15],\n rand_angle=[-3, 3],\n vrange=[0, 5, -.5, .5],\n obstacle_list=obstacleList)\n path = rrt_star.planning(animation=show_animation)\n\n if path is None:\n print(\"Cannot find path\")\n else:\n print(\"found path!!\")\n\n # Draw final path\n if show_animation:\n rrt_star.draw_graph1()\n plt.plot([x for (x, y) in path], [y for (x, y) in path], '-r')\n plt.grid(True)\n plt.pause(0.01) # Need for Mac\n plt.show()\n if show_graph:\n rrt_star.draw_graph2()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n \n\n\n\n\n\n","sub_path":"src/mstar_guidance/src/rrt_mstar/RRT_Star.py","file_name":"RRT_Star.py","file_ext":"py","file_size_in_byte":7808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"585140772","text":"import argparse\nimport RaceRandom as random\nimport os\nfrom pathlib import Path\n\nimport urllib.request\nimport urllib.parse\nimport yaml\n\n\ndef get_weights(path):\n if os.path.exists(Path(path)):\n with open(path, \"r\", encoding=\"utf-8\") as f:\n return yaml.load(f, Loader=yaml.SafeLoader)\n elif urllib.parse.urlparse(path).scheme in ['http', 'https']:\n return yaml.load(urllib.request.urlopen(path), Loader=yaml.FullLoader)\n\ndef roll_settings(weights):\n def get_choice(option, root=None):\n root = weights if root is None else root\n if option not in root:\n return None\n if type(root[option]) is not dict:\n return root[option]\n if not root[option]:\n return None\n return random.choices(list(root[option].keys()), weights=list(map(int, root[option].values())))[0]\n\n def get_choice_default(option, root=weights, default=None):\n choice = get_choice(option, root)\n if choice is None and default is not None:\n return default\n return choice\n\n while True:\n subweights = weights.get('subweights', {})\n if len(subweights) == 0:\n break\n chances = ({k: int(v['chance']) for (k, v) in subweights.items()})\n subweight_name = random.choices(list(chances.keys()), weights=list(chances.values()))[0]\n subweights = weights.get('subweights', {}).get(subweight_name, {}).get('weights', {})\n subweights['subweights'] = subweights.get('subweights', {})\n weights = {**weights, **subweights}\n\n ret = argparse.Namespace()\n\n ret.algorithm = get_choice('algorithm')\n\n glitch_map = {'none': 'noglitches', 'no_logic': 'nologic', 'owglitches': 'owglitches',\n 'owg': 'owglitches', 'minorglitches': 'minorglitches'}\n glitches_required = get_choice('glitches_required')\n if glitches_required is not None:\n if glitches_required not in glitch_map.keys():\n print(f'Logic did not match one of: {\", \".join(glitch_map.keys())}')\n glitches_required = 'none'\n ret.logic = glitch_map[glitches_required]\n\n # item_placement = get_choice('item_placement')\n # not supported in ER\n\n dungeon_items = get_choice('dungeon_items')\n dungeon_items = '' if dungeon_items == 'standard' or dungeon_items is None else dungeon_items\n dungeon_items = 'mcsb' if dungeon_items == 'full' else dungeon_items\n ret.mapshuffle = get_choice('map_shuffle') == 'on' if 'map_shuffle' in weights else 'm' in dungeon_items\n ret.compassshuffle = get_choice('compass_shuffle') == 'on' if 'compass_shuffle' in weights else 'c' in dungeon_items\n if 'smallkey_shuffle' in weights:\n ret.keyshuffle = get_choice('smallkey_shuffle')\n else:\n if 's' in dungeon_items:\n ret.keyshuffle = 'wild'\n if 'u' in dungeon_items:\n ret.keyshuffle = 'universal'\n ret.bigkeyshuffle = get_choice('bigkey_shuffle') == 'on' if 'bigkey_shuffle' in weights else 'b' in dungeon_items\n\n ret.accessibility = get_choice('accessibility')\n ret.restrict_boss_items = get_choice('restrict_boss_items')\n\n overworld_shuffle = get_choice('overworld_shuffle')\n ret.ow_shuffle = overworld_shuffle if overworld_shuffle != 'none' else 'vanilla'\n ret.ow_terrain = get_choice('overworld_terrain') == 'on'\n valid_options = {'none', 'polar', 'grouped', 'limited', 'chaos'}\n ret.ow_crossed = get_choice('overworld_crossed')\n ret.ow_crossed = ret.ow_crossed if ret.ow_crossed in valid_options else 'none'\n ret.ow_keepsimilar = get_choice('overworld_keepsimilar') == 'on'\n ret.ow_mixed = get_choice('overworld_swap') == 'on'\n ret.ow_whirlpool = get_choice('whirlpool_shuffle') == 'on'\n overworld_flute = get_choice('flute_shuffle')\n ret.ow_fluteshuffle = overworld_flute if overworld_flute != 'none' else 'vanilla'\n ret.bonk_drops = get_choice('bonk_drops') == 'on'\n entrance_shuffle = get_choice('entrance_shuffle')\n ret.shuffle = entrance_shuffle if entrance_shuffle != 'none' else 'vanilla'\n overworld_map = get_choice('overworld_map')\n ret.overworld_map = overworld_map if overworld_map != 'default' else 'default'\n door_shuffle = get_choice('door_shuffle')\n ret.door_shuffle = door_shuffle if door_shuffle != 'none' else 'vanilla'\n ret.intensity = get_choice('intensity')\n ret.door_type_mode = get_choice('door_type_mode')\n ret.trap_door_mode = get_choice('trap_door_mode')\n ret.key_logic_algorithm = get_choice('key_logic_algorithm')\n ret.decoupledoors = get_choice('decoupledoors') == 'on'\n ret.door_self_loops = get_choice('door_self_loops') == 'on'\n ret.experimental = get_choice('experimental') == 'on'\n ret.collection_rate = get_choice('collection_rate') == 'on'\n\n ret.dungeon_counters = get_choice('dungeon_counters') if 'dungeon_counters' in weights else 'default'\n if ret.dungeon_counters == 'default':\n ret.dungeon_counters = 'pickup' if ret.door_shuffle != 'vanilla' or ret.compassshuffle == 'on' else 'off'\n\n ret.pseudoboots = get_choice('pseudoboots') == 'on'\n ret.shopsanity = get_choice('shopsanity') == 'on'\n keydropshuffle = get_choice('keydropshuffle') == 'on'\n ret.dropshuffle = get_choice('dropshuffle') == 'on' or keydropshuffle\n ret.pottery = get_choice('pottery') if 'pottery' in weights else 'none'\n ret.pottery = 'keys' if ret.pottery == 'none' and keydropshuffle else ret.pottery\n ret.colorizepots = get_choice_default('colorizepots', default='on') == 'on'\n ret.shufflepots = get_choice('pot_shuffle') == 'on'\n ret.mixed_travel = get_choice('mixed_travel') if 'mixed_travel' in weights else 'prevent'\n ret.standardize_palettes = (get_choice('standardize_palettes') if 'standardize_palettes' in weights\n else 'standardize')\n\n goal = get_choice('goals')\n if goal is not None:\n ret.goal = {'ganon': 'ganon',\n 'fast_ganon': 'crystals',\n 'dungeons': 'dungeons',\n 'pedestal': 'pedestal',\n 'triforce-hunt': 'triforcehunt',\n 'trinity': 'trinity',\n 'ganonhunt': 'ganonhunt',\n 'completionist': 'completionist'\n }[goal]\n\n ret.openpyramid = get_choice('open_pyramid') if 'open_pyramid' in weights else 'auto'\n\n ret.shuffleganon = get_choice('shuffleganon') == 'on'\n ret.shufflelinks = get_choice('shufflelinks') == 'on'\n ret.shuffletavern = get_choice('shuffletavern') == 'on'\n \n ret.crystals_gt = get_choice('tower_open')\n ret.crystals_ganon = get_choice('ganon_open')\n\n ret.triforce_pool = get_choice_default('triforce_pool', default=0)\n ret.triforce_goal = get_choice_default('triforce_goal', default=0)\n ret.triforce_pool_min = get_choice_default('triforce_pool_min', default=0)\n ret.triforce_pool_max = get_choice_default('triforce_pool_max', default=0)\n ret.triforce_goal_min = get_choice_default('triforce_goal_min', default=0)\n ret.triforce_goal_max = get_choice_default('triforce_goal_max', default=0)\n ret.triforce_min_difference = get_choice_default('triforce_min_difference', default=0)\n ret.triforce_max_difference = get_choice_default('triforce_max_difference', default=10000)\n\n ret.mode = get_choice('world_state')\n if ret.mode == 'retro':\n ret.mode = 'open'\n ret.retro = True\n ret.retro = get_choice('retro') == 'on' # this overrides world_state if used\n ret.take_any = get_choice_default('take_any', default='none')\n\n ret.bombbag = get_choice('bombbag') == 'on'\n\n ret.hints = get_choice('hints') == 'on'\n\n swords = get_choice('weapons')\n if swords is not None:\n ret.swords = {'randomized': 'random',\n 'assured': 'assured',\n 'vanilla': 'vanilla',\n 'swordless': 'swordless'\n }[swords]\n\n ret.difficulty = get_choice('item_pool')\n ret.flute_mode = get_choice_default('flute_mode', default='normal')\n ret.bow_mode = get_choice_default('bow_mode', default='progressive')\n\n ret.item_functionality = get_choice('item_functionality')\n\n old_style_bosses = {'basic': 'simple',\n 'normal': 'full',\n 'chaos': 'random'}\n boss_choice = get_choice('boss_shuffle')\n if boss_choice in old_style_bosses.keys():\n boss_choice = old_style_bosses[boss_choice]\n ret.shufflebosses = boss_choice\n\n enemy_choice = get_choice('enemy_shuffle')\n if enemy_choice == 'chaos':\n enemy_choice = 'random'\n ret.shuffleenemies = enemy_choice\n\n old_style_damage = {'none': 'default',\n 'chaos': 'random'}\n damage_choice = get_choice('enemy_damage')\n if damage_choice in old_style_damage:\n damage_choice = old_style_damage[damage_choice]\n ret.enemy_damage = damage_choice\n\n ret.enemy_health = get_choice('enemy_health')\n\n ret.beemizer = get_choice('beemizer') if 'beemizer' in weights else '0'\n\n inventoryweights = weights.get('startinventory', {})\n startitems = []\n for item in inventoryweights.keys():\n if get_choice(item, inventoryweights) == 'on':\n startitems.append(item)\n ret.startinventory = ','.join(startitems)\n if len(startitems) > 0:\n ret.usestartinventory = True\n\n if 'rom' in weights:\n romweights = weights['rom']\n ret.sprite = get_choice('sprite', romweights)\n ret.disablemusic = get_choice('disablemusic', romweights) == 'on'\n ret.quickswap = get_choice('quickswap', romweights) == 'on'\n ret.reduce_flashing = get_choice('reduce_flashing', romweights) == 'on'\n ret.msu_resume = get_choice('msu_resume', romweights) == 'on'\n ret.fastmenu = get_choice('menuspeed', romweights)\n ret.heartcolor = get_choice('heartcolor', romweights)\n ret.heartbeep = get_choice('heartbeep', romweights)\n ret.ow_palettes = get_choice('ow_palettes', romweights)\n ret.uw_palettes = get_choice('uw_palettes', romweights)\n ret.shuffle_sfx = get_choice('shuffle_sfx', romweights) == 'on'\n ret.msu_resume = get_choice('msu_resume', romweights) == 'on'\n\n return ret\n","sub_path":"source/tools/MysteryUtils.py","file_name":"MysteryUtils.py","file_ext":"py","file_size_in_byte":10232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"347806228","text":"# PythonDraw.py\n# 四叶草\nimport math as m\nimport turtle as t\n\nt.setup(1280, 720)\nt.penup()\nt.fd(-100)\nt.pendown()\nt.pensize(10)\nt.pencolor(\"red\")\nt.right(135)\nfor i in range(4):\n t.left(90)\n t.circle(50 * (m.sqrt(2)), 180)\n","sub_path":"wxz02/src/test/clover.py","file_name":"clover.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"402650195","text":"#!/usr/bin/python3\n\nimport argparse\nimport sys\n\nimport base64\nimport requests\n\nimport imghdr\nfrom PIL import Image\nfrom io import BytesIO\n\n\ndef encode_image(img_path: str) -> str:\n try:\n with open(img_path, \"rb\") as image_file:\n return base64.b64encode(image_file.read()).decode()\n except Exception as e:\n sys.stderr.write('ERROR: %s\\n\\n' % str(e))\n sys.exit(2)\n\ndef send_request(url: str, data: dict) -> str:\n try:\n response = requests.get(url, json=data)\n response.raise_for_status()\n return response.json()['image']\n except Exception as e:\n sys.stderr.write('ERROR: %s\\n\\n' % str(e))\n sys.exit(2)\n\ndef save_image(encoded_img: str, img_path: str) -> None:\n try:\n decoded_file = base64.b64decode(encoded_img)\n file_format = imghdr.what(None, h=decoded_file)\n img = Image.open(BytesIO(decoded_file))\n img.save(img_path, file_format)\n except Exception as e:\n sys.stderr.write('ERROR: %s\\n\\n' % str(e))\n sys.exit(2)\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-i\", \"--input\", metavar='PATH', help=\"input image\", required=True)\nparser.add_argument(\"-o\", \"--output\", metavar='PATH', help=\"output image\", required=True)\nparser.add_argument(\"-u\", \"--url\", metavar='URL', help=\"URL to REST API\", required=True)\nparser.add_argument(\"--resize\", nargs=2, metavar=('WIDTH', 'HEIGHT'), type=int)\nparser.add_argument(\"--interpolation\", help=\"if resize is selected\")\nparser.add_argument(\"--crop\", nargs=4, metavar=('X_BEGIN', 'X_END', 'Y_BEGIN', 'Y_END'), type=int)\nparser.add_argument(\"--rotate\", metavar='ANGLE_IN_DEGREES', type=int)\nparser.add_argument(\"--scale\", help=\"if rotate is selected\", type=float)\nparser.add_argument(\"--negative\", action=\"store_true\")\nargs = parser.parse_args()\n\nif args.resize:\n url_augmentation = f\"resize?width={args.resize[0]}&height={args.resize[1]}\"\n if args.interpolation:\n url_augmentation += f\"&interpolation={args.interpolation}\"\nelif args.crop:\n url_augmentation = f\"crop?xBegin={args.crop[0]}&xEnd={args.crop[1]}&yBegin={args.crop[2]}&yEnd={args.crop[3]}\"\nelif args.rotate:\n url_augmentation = f\"rotate?angle={args.rotate}\"\n if args.scale:\n url_augmentation += f\"&scale={args.scale}\"\nelif args.negative:\n url_augmentation = \"negative\"\nelse:\n message = 'You need to choose one of the following: --resize, --crop, --rotate, --negative'\n sys.stderr.write('ERROR: %s\\n\\n' % message)\n parser.print_help()\n sys.exit(2)\n\nencoded_img = encode_image(args.input)\n\ndata = {'image': encoded_img}\nurl = f\"{args.url}/augmentation/{url_augmentation}\"\n\nencoded_img = send_request(url, data)\nsave_image(encoded_img, args.output)\n","sub_path":"testing_script/get_augmentation.py","file_name":"get_augmentation.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"156202646","text":"# -*- coding: utf-8 -*-\nfrom io import BytesIO\nfrom os import SEEK_SET\nfrom os.path import splitext\nfrom typing import Any, Dict, IO, List\nfrom unicodedata import normalize\n\nimport pandas as pd\nimport platiagro\nfrom chardet.universaldetector import UniversalDetector\nfrom pandas.io.common import infer_compression\nfrom platiagro import save_dataset, stat_dataset\nfrom platiagro.featuretypes import infer_featuretypes, validate_featuretypes\nfrom werkzeug.exceptions import BadRequest, NotFound\n\n\ndef list_datasets() -> List[Dict[str, Any]]:\n \"\"\"Lists all datasets from our object storage.\n\n Returns:\n A list of all datasets.\n \"\"\"\n datasets = platiagro.list_datasets()\n return [get_dataset(name) for name in datasets]\n\n\ndef create_dataset(files: Dict[str, IO]) -> Dict[str, Any]:\n \"\"\"Creates a new dataset in our object storage.\n\n Args:\n files (dict): file objects.\n\n Returns:\n The dataset details: name, columns, and filename.\n\n Raises:\n BadRequest: when incoming files are missing or valid.\n \"\"\"\n # checks if the post request has the file part\n if \"file\" not in files:\n raise BadRequest(\"No file part\")\n file = files[\"file\"]\n\n # if user does not select file, the browser also\n # submits an empty part without filename\n if file.filename == \"\":\n raise BadRequest(\"No selected file\")\n\n # generate a dataset name from filename\n name = generate_name(file.filename)\n\n try:\n # reads file into a DataFrame\n df = read_into_dataframe(file, file.filename)\n except Exception as e:\n # if read fails, then uploads raw file\n save_dataset(name, file)\n return {\"name\": name, \"filename\": file.filename}\n\n columns = df.columns.values.tolist()\n\n # checks if the post request has the 'featuretypes' part\n if \"featuretypes\" in files:\n try:\n ftype_file = files[\"featuretypes\"]\n featuretypes = list(map(lambda s: s.strip().decode(\"utf8\"), ftype_file.readlines()))\n validate_featuretypes(featuretypes)\n except ValueError as e:\n raise BadRequest(str(e))\n\n if len(columns) != len(featuretypes):\n raise BadRequest(\"featuretypes must be the same length as the DataFrame columns\")\n else:\n featuretypes = infer_featuretypes(df)\n\n metadata = {\n \"featuretypes\": featuretypes,\n \"original-filename\": file.filename,\n }\n\n # uses PlatIAgro SDK to save the dataset\n save_dataset(name, df, metadata=metadata)\n\n columns = [{\"name\": col, \"featuretype\": ftype} for col, ftype in zip(columns, featuretypes)]\n return {\"name\": name, \"columns\": columns, \"filename\": file.filename}\n\n\ndef get_dataset(name: str) -> Dict[str, Any]:\n \"\"\"Details a dataset from our object storage.\n\n Args:\n name (str): the dataset name to look for in our object storage.\n\n Returns:\n The dataset details: name, columns, and filename.\n\n Raises:\n NotFound: when the dataset does not exist.\n \"\"\"\n try:\n metadata = stat_dataset(name)\n\n filename = metadata.get(\"original-filename\")\n\n if \"columns\" in metadata and \"featuretypes\" in metadata:\n columns = metadata[\"columns\"]\n featuretypes = metadata[\"featuretypes\"]\n columns = [{\"name\": col, \"featuretype\": ftype} for col, ftype in zip(columns, featuretypes)]\n return {\"name\": name, \"columns\": columns, \"filename\": filename}\n\n return {\"name\": name, \"filename\": filename}\n except FileNotFoundError:\n raise NotFound(\"The specified dataset does not exist\")\n\n\ndef read_into_dataframe(file: IO, filename: str = \"\", nrows: int = 100,max_characters: int = 50) -> pd.DataFrame:\n \"\"\"Reads a file into a DataFrame.\n Infers the file encoding and whether a header column exists\n Args:\n file (IO): file buffer.\n filename (str): filename. Used to infer compression.\n nrows (int, optional): number of rows to peek. Default: 100.\n max_characters (int, optional): max characters a column name can have to be distinguished from a real text value\n Returns:\n A pandas.DataFrame.\n \"\"\"\n detector = UniversalDetector()\n for line, text in enumerate(file):\n detector.feed(text)\n if detector.done or line > nrows:\n break\n detector.close()\n encoding = detector.result.get(\"encoding\")\n\n compression = infer_compression(filename, \"infer\")\n\n file.seek(0, SEEK_SET)\n contents = file.read()\n\n with BytesIO(contents) as file:\n df0 = pd.read_csv(\n file,\n encoding=encoding,\n compression=compression,\n sep=None,\n engine=\"python\",\n header=\"infer\",\n nrows=nrows,\n )\n \n df0_cols = list(df0.columns)\n \n #Check if all columns are strins and short strings(text values tend to be long)\n column_names_checker = all([type(item) == str for item in df0_cols])\n if column_names_checker:\n column_names_checker = all([len(item) < max_characters for item in df0_cols]) \n \n \n #Check if any column can be turned to float\n conversion_checker= True\n for item in df0_cols:\n try:\n item = float(item)\n conversion_checker = False\n break\n except:\n pass\n \n\n #Prefix and header \n final_checker = True if (column_names_checker and conversion_checker) else False\n header = \"infer\" if final_checker else None\n prefix = None if header else \"col\"\n\n with BytesIO(contents) as file:\n df = pd.read_csv(\n file,\n encoding=encoding,\n compression=compression,\n sep=None,\n engine=\"python\",\n header=header,\n prefix=prefix,\n )\n return df\n\n\n\n\n\ndef generate_name(filename: str, attempt: int = 1) -> str:\n \"\"\"Generates a dataset name from a given filename.\n\n Args:\n filename (str): source filename.\n attempt (int): the current attempt of generating a new name.\n\n Return:\n str: new generated dataset name.\n \"\"\"\n # normalize filename to ASCII characters\n # replace spaces by dashes\n name = normalize('NFKD', filename) \\\n .encode('ASCII', 'ignore') \\\n .replace(b' ', b'-') \\\n .decode()\n\n if attempt > 1:\n # adds a suffix '-NUMBER' to filename\n name, extension = splitext(name)\n name = f\"{name}-{attempt}{extension}\"\n\n try:\n # check if final_name is already in use\n stat_dataset(name)\n except FileNotFoundError:\n return name\n\n # if it is already in use,\n return generate_name(filename, attempt + 1)\n","sub_path":"datasets/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":6701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"278995450","text":"import math\nimport csv\nTMopen0 = open(\"TM90_100T_9x9Aya_0310-1342-clauses0.csv\",'r')\nTMopen1 = open(\"TM90_100T_9x9Aya_0310-1342-clauses1.csv\",'r')\nTMopen2 = open(\"TM90_100T_9x9Aya_0310-1342-clauses2.csv\",'r')\nTMr0 = TMopen0.readlines()\nTMr1 = TMopen1.readlines()\nTMr2 = TMopen2.readlines()\n\n#rows = \"0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1\"\ndef returnValue(t1,t2):\n if (t1 == \"1\"):\n return \"X\"\n elif (t2 == \"1\"):\n return \"O\"\n elif (t1 == \",\"):\n return \" \"\n else:\n return \"#\"\n#print(rows[:83])\n#print(rows[84:167])\n#b,b,b,b,b,b,b,b,b,b,b,b,x,o,b,b,b,b,x,o,x,o,x,o,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,win\n#i = 0\n#newline = rows[:83]\n#newline2 = rows[84:167]\n#print(newline)\n#print(newline2)\ndef makeBoard2(input, rows, columns):\n input = input[:-1]\n input = input.split(\",\")\n outcome = input[-1]\n inputx = input[:81]\n inputo = input[81:162]\n #print(input)\n #print(inputx)\n #print(inputo)\n i=0\n for column in range(columns):\n outline = \"\"\n for row in range(rows):\n output = \"\"\n if(inputx[i] == inputo[i]):\n output = \"_\"\n elif(inputx[i] == \"1\"):\n output = \"X\"\n elif(inputo[i] == \"1\"):\n output = \"O\"\n outline = outline + \",\"+output\n i=i+1\n print(outline)\n #print(outcome)\n#for i in range(0,5,1):\n# makeBoard2(win[i],7,6)\n #print(\"---------------------\")\n#print(\"--------------------------\")\n#for i in range(9998,10003,1):\n# makeBoard2(win[i],7,6)\n #print(\"---------------------\")\n#print(\"--------------------------\")\n#for i in range(24000,24005,1):\n# makeBoard2(win[i],7,6)\n #print(\"---------------------\")\ndef makeBoard(input, rows, columns):\n mellomrom = \" \"\n one = \" \"\n uLine = \" \"\n underline = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\"]\n input = input[:-1]\n input = input.split(\",\")\n #print(input)\n i=0\n for column in range(columns):\n outline = str(rows-column)\n for row in range(rows):\n outline = outline + mellomrom+transform(input[i])\n i=i+1\n print(outline)\n for i in range(rows):\n uLine +=one+underline[i] + mellomrom\n print(uLine)\ndef transform(input):\n # print(input)\n if (int(input[0])==1 and int(input[2])==1) or (int(input[1])==1 and int(input[3])==1):\n return \"Fa\"\n elif (int(input[0])==1 and int(input[1])==1):\n return \"+#\"\n elif (int(input[2])==1 and int(input[3])==1):\n return \"-#\"\n elif int(input[0])==1:\n return \"+B\"\n elif int(input[1])==1:\n return \"+W\"\n elif int(input[2])==1:\n return \"-b\"\n elif int(input[3])==1:\n return \"-w\"\n else:\n return \" \"\n #return \"?#\"\ndef prints(status,clause, posneg,truefalse):\n if status == \"Win\":\n board = TMr1[clause]\n else:\n board = TMr0[clause]\n print(\"%s Clause %s %s %s\"%(status,clause,truefalse,posneg))\n makeBoard(board, 9, 9)\nprints(\"Loss\",250,\"Positive\", \"True\")\n#prints(\"Loss\",880,\"Positive\", \"True\")\nprints(\"Loss\",468,\"Positive\",\"False\")\nprints(\"Win\",208,\"Positive\", \"True\")\nprints(\"Win\",856,\"Positive\",\"False\")\n\nprints(\"Loss\",591,\"Negative\", \"True\")\n#prints(\"Loss\",39,\"Negative\", \"True\")\nprints(\"Loss\",377,\"Negative\",\"False\")\n#prints(\"Loss\",99,\"Negative\",\"False\")\nprints(\"Win\",905,\"Negative\", \"True\")\n#prints(\"Win\",235,\"Negative\", \"True\")\nprints(\"Win\",503,\"Negative\",\"False\")\n#prints(\"Win\",95,\"Negative\",\"False\")\n\n\n\n","sub_path":"Clauses_visualizer.py","file_name":"Clauses_visualizer.py","file_ext":"py","file_size_in_byte":3629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"170999609","text":"#164 - Ultrapassando Z\n\nX = int(input(''))\nZ = 0\ncont = 0\nsoma = 0\n\nwhile Z <= X:\n Z = int(input(''))\n if Z > X:\n break\n\nwhile X < Z:\n X += 1\n soma += X\n cont += 1\n if soma > Z:\n break\n\nprint(cont)\n","sub_path":"Exercícios Gerais/164[URI 1150] - Ultrapassando Z.py","file_name":"164[URI 1150] - Ultrapassando Z.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"410714201","text":"import pokebase as pb\r\n\r\n\r\nclass Move:\r\n def __init__(self, move_name):\r\n pb_move = pb.move(move_name)\r\n\r\n self.name = pb_move.name\r\n self.power = pb_move.power\r\n self.accuracy = pb_move.accuracy\r\n self.damage_class = pb_move.damage_class.name\r\n self.pp = pb_move.pp\r\n self.priority = pb_move.priority\r\n self.type = pb_move.type.name\r\n\r\n def serialize(self):\r\n return {\r\n 'name': self.name,\r\n 'power': self.power,\r\n 'accuracy': self.accuracy,\r\n 'damage_class': self.damage_class,\r\n 'pp': self.pp,\r\n 'priority': self.priority,\r\n 'type': self.type\r\n }\r\n\r\n","sub_path":"Model/Move.py","file_name":"Move.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"423045709","text":"#!/usr/bin/python3\n\ndataFile = open(input(\"Enter filepath to data array(s) here:\"), \"r\")\noutputFile = open(input(\"Enter filepath to write normalized data:\"), \"w\")\n\nfor line in dataFile:\n dataList = [float(i) for i in line.split(\",\")]\n\n minimum = min(dataList)\n domain = max(dataList) - minimum\n\n if domain == 0: continue\n\n normedDataList = [(i-minimum)/(domain) for i in dataList]\n\n outputFile.write(\"{0}\\n\".format(\",\".join([str(i) for i in normedDataList])))\n\ndataFile.close()\noutputFile.close()","sub_path":"datasets/normalization.py","file_name":"normalization.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"413759432","text":"\n# -*- coding:utf-8 -*- \n# 设置中文utf-8解释环境标识\n# No例1:气象站长期年平均风速的条形图绘制方法示例及代码详解\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport pandas as pd #导入pandas包\nimport pylab as pl\nimport numpy as np\n\nmpl.rcParams[\"font.sans-serif\"]=[\"SimHei\"] # 设置坐标轴标识字符串中的中文标识的字体为黑体\nmpl.rcParams['axes.unicode_minus'] = False # 不使用默认的unicode minus模式来处理坐标轴轴线的刻度标签为负数的情况。\n \ndata = pd.read_csv(\"no1_anex_bar.csv\") #pandas 中输入EXCEL表格数据CSV的方法\nprint(data)#测试数据输入是否成功\nprint(\"===================================\")\n\nprint(data[\"year\"])#测试数据框的以头标识为year的一维向量的数值调用方法\nprint(\"===================================\")\nXyear=data[\"year\"] #将年数值向量附值给Xyear\n\nYspeed=data[\"speed\"] #将风速向量附值给Yspeed\n\nplt.figure(figsize=(9, 6)) #创建figure窗口画布大小\npl.xticks(rotation=45) #设置条形图X轴的刻度标签的旋转方向\n# 绘制BAR图\nplt.bar(Xyear,Yspeed,align=\"center\",color=\"lightsteelblue\",tick_label=Xyear,hatch=\"\",alpha=0.9,width=0.4,label=\"气象站年平均风速A\")\n# 条形图的各参数请参加bar 参数设置手册\n\n#绘制气象站风速平均值水平参考线\navg=np.mean(Yspeed)\nplt.axhline(y=avg,C=\"r\",ls=\"--\",lw=2)\n#绘制图纸区域的指向性文本描述,如:多年平均风速值\nx1=2003.5\ny1=avg+0.05\nplt.text(x1,y1,\"多年平均风速值\",weight=\"bold\",color=\"black\",fontsize=12)\n#设置XY坐标轴的中文标签\nplt.xlabel(\"年份\",fontsize=12)\nplt.ylabel(\"风速\",fontsize=12)\n\n\n#设置Y轴在网格线\nplt.grid(True,axis=\"y\",ls=\":\",color=\"green\",alpha=0.3) #注意这里\"y\"指Y坐标轴,不能采用变量Yspeed写入。\n#设置Y轴的坐标取值范围\nplt.ylim(1,3) #Y轴起点1,终点3.\n#设置图例标签\nplt.title(\"气象站多年年平均风速分布图\")\n\n# 关于人工站与自动站数据的叠加分析,图形叠加分析\ndata1 = pd.read_csv(\"no1_anex_bar2.csv\") #pandas 中输入EXCEL表格后10年自动站数据CSV的方法\nXyear1=data1[\"year\"] #将年数值向量附值给Xyear1\nYspeed1=data1[\"speed\"] #将风速向量附值给Yspeed1\nwidth=0.4 #设定后10年柱状图与原来柱状图在X的位置偏移量\nplt.bar(Xyear1+width,Yspeed1,width,align=\"center\",color=\"#FFA500\",hatch=\"\",alpha=0.9,label=\"气象站年平均风速B\")\n\n# 设置X轴的不同情况的刻度位置及刻度标签\n\n#plt.xticks([index+(width/2) for index in Xyear],Xyear)\n\t\nplt.legend() #设定不同线条的标签标识\n#显示图形\nplt.show()\n","sub_path":"test/出图/no1_anex_bar.py","file_name":"no1_anex_bar.py","file_ext":"py","file_size_in_byte":2673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"560619993","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nTest power plants and chp.\n\nSPDX-FileCopyrightText: 2016-2019 Uwe Krien \n\nSPDX-License-Identifier: MIT\n\"\"\"\n__copyright__ = \"Uwe Krien \"\n__license__ = \"MIT\"\n\nfrom nose.tools import eq_, assert_raises_regexp\nfrom deflex import basic_scenario, geometries, powerplants, config as cfg\n\n\nclass TestScenarioPowerplantsAndCHP:\n @classmethod\n def setUpClass(cls):\n cls.regions = geometries.deflex_regions(rmap=\"de21\")\n cls.pp = basic_scenario.scenario_powerplants(\n dict(), cls.regions, 2014, \"de21\", 1\n )\n\n def test_01_deflex_power_plants_by_year(self):\n pp = powerplants.get_deflex_pp_by_year(\n self.regions, 2014, \"de21\", overwrite_capacity=True\n )\n eq_(int(pp[\"capacity\"].sum()), 181489)\n\n def scenario_pp_test(self):\n eq_(float(self.pp[\"volatile_source\"][\"DE03\", \"wind\"]), 3052.8)\n eq_(\n float(self.pp[\"transformer\"].loc[\"capacity\", (\"DE03\", \"lignite\")]),\n 1135.6,\n )\n\n def test_scenario_transmission(self):\n lines = basic_scenario.scenario_transmission(\n self.pp, self.regions, \"de22\"\n )\n eq_(int(lines.loc[\"DE07-DE05\", (\"electrical\", \"capacity\")]), 1978)\n eq_(int(lines.loc[\"DE07-DE05\", (\"electrical\", \"distance\")]), 199)\n eq_(float(lines.loc[\"DE07-DE05\", (\"electrical\", \"efficiency\")]), 0.9)\n lines = basic_scenario.scenario_transmission(\n self.pp, self.regions, \"de22\", copperplate=True\n )\n eq_(\n float(lines.loc[\"DE07-DE05\", (\"electrical\", \"capacity\")]),\n float(\"inf\"),\n )\n eq_(str(lines.loc[\"DE07-DE05\", (\"electrical\", \"distance\")]), \"nan\")\n eq_(float(lines.loc[\"DE07-DE05\", (\"electrical\", \"efficiency\")]), 1.0)\n\n def test_scenario_transmisson_error(self):\n old_value = cfg.get(\"transmission\", \"general_efficiency\")\n cfg.tmp_set(\"transmission\", \"general_efficiency\", \"None\")\n msg = \"The calculation of the efficiency by distance is not yet\"\n with assert_raises_regexp(NotImplementedError, msg):\n basic_scenario.scenario_transmission(self.pp, self.regions, \"de22\")\n cfg.tmp_set(\"transmission\", \"general_efficiency\", old_value)\n\n def test_scenario_commodity_sources(self):\n src = basic_scenario.scenario_commodity_sources(self.pp, 2013)[\n \"commodity_source\"\n ]\n eq_(round(src.loc[\"costs\", (\"DE\", \"hard coal\")], 2), 9.71)\n eq_(round(src.loc[\"emission\", (\"DE\", \"natural gas\")], 2), 201.24)\n\n def test_chp(self):\n eq_(\n int(self.pp[\"transformer\"].loc[\"capacity\", (\"DE01\", \"hard coal\")]),\n 1291,\n )\n transf = basic_scenario.scenario_chp(\n self.pp, self.regions, 2014, \"de21\"\n )[\"transformer\"]\n eq_(int(transf.loc[\"capacity\", (\"DE01\", \"hard coal\")]), 623)\n eq_(int(transf.loc[\"capacity_elec_chp\", (\"DE01\", \"hard coal\")]), 667)\n","sub_path":"tests/test_scenario_powerplant_and_chp.py","file_name":"test_scenario_powerplant_and_chp.py","file_ext":"py","file_size_in_byte":3005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"194507866","text":"import os\nimport sys\nimport glob\nimport nltk\nimport sqlite3\nimport unittest\n\n\nconnection = None\n\n'''\n# In this unit test file, we have three test functions:\n\n# 1. check if all words in database been printed\n# 2. check if the word \"angle\" is printed correctly\n# 3. check if the word \"year\" is printed correctly\n'''\nclass TestStringMethods(unittest.TestCase):\n\n\tdef test_totalNum(self):\n\t\tfp = open(\"./output.txt\")\n\t\tcount = 0\n\t\tfor line in fp:\n\t\t\tcount +=1\n\t\tfp.close()\n\t\tquery = \"select count(distinct word) from posting \"\t\t\n\t\tself.assertEqual(executeQuery(query)[0][0],count)\n\n\tdef test_angle_info(self):\t\n\t\tfp = open(\"./output.txt\")\n\t\tangle_list = None\n\t\tfor line in fp:\n\t\t\ta_list = line.split(\"\t\")\n\t\t\tif a_list[0] == \"angle\":\n\t\t\t\tangle_list = a_list[1].split(\";\")[:-1]\t\n\t\tfp.close()\n\t\tself.assertTrue((angle_list)!= None)\n\t\tself.assertEqual(len(angle_list), 1)\n\t\tself.assertEqual(int(angle_list[0].split(\":\")[0]),1971)\n\t\tself.assertEqual(int(angle_list[0].split(\":\")[1]),250)\n\n\tdef test_years_info(self):\t\n\t\tfp = open(\"./output.txt\")\n\t\tyear_list = None\n\t\tfor line in fp:\n\t\t\ta_list = line.split(\"\t\")\n\t\t\tif a_list[0] == \"year\":\n\t\t\t\tyear_list = a_list[1].split(\";\")[:-1]\t\n\t\tfp.close()\n\t\tself.assertTrue((year_list)!= None)\n\t\tself.assertEqual(len(year_list), 2)\n\t\tself.assertTrue( \"1972:5\" in year_list)\n\t\tself.assertTrue(\"1971:1\" in year_list)\n\n\n'''\n# this function is to execute query\n'''\ndef executeQuery(query):\n\tcur = connection.cursor() #get cursor\n\treturn [i for i in cur.execute(query)]\n\n\n'''\n# this function is to connect to database\n'''\ndef connectionDataBase(data_file_name):\n\tglobal connection\n\t#create a connection to database with file name \"data_file_name\", if error print it out\n\ttry:\n\t\tconnection = sqlite3.connect(data_file_name)\n\t\treturn connection\n\texcept Exception as e:\n\t\tprint(e)\n\t\texit(\"Error,unit_test file can not connect database\")\n\n\n'''\n# this function is to check if create_index.py exist\n# check if Documents contains correct docuemnts\n'''\ndef checkFiles():\n\tif len(sys.argv) != 1:\n\t\texit(\"Error, command line error..\")\n\telse:\n\t\tif not os.path.isfile(\"./../create_index.py\") or not os.path.isfile(\"../print_index.py\"):\n\t\t\texit(\"Error, create_index.py or print_index.py does not exit..\") \n\ttry:\n\t\tfor filepath in glob.glob(os.path.join(\"./Documents\", '*.txt')):\n\t\t\tif int(filepath.split(\"_\")[1]) != 1971 and int(filepath.split(\"_\")[1]) != 1972:\n\t\t\t\texit(\"Error, Document not correct\")\n\texcept Exception:\n\t\traise\n\t\texit(\"Error, Documents' files not correct\")\n\n\n\tprint(\"The documents and python script are correct...\\nchecking...\")\n\n\nif __name__ == '__main__':\n\tcheckFiles()\n\tos.system(\"python3 ./../print_index.py Documents > output.txt\")\n\tconnection = connectionDataBase(\"./Documents/data.db\")\n\tunittest.main(verbosity=2)\n","sub_path":"assignment1/Part1/Part1_test/print_index_unit_test.py","file_name":"print_index_unit_test.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"221922067","text":"class Solution(object):\n def getMinimumDifference(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n if root == None:\n return float('inf')\n # left\n if root.left != None:\n temp = root.left\n l_min = abs(temp.val-root.val)\n while temp.right != None:\n l_min = min(l_min,abs(temp.right.val-root.val))\n temp = temp.right\n else:\n l_min = float('inf')\n\n # right\n if root.right != None:\n temp = root.right\n r_min = abs(temp.val-root.val)\n while temp.left != None:\n r_min = min(r_min,abs(temp.left.val-root.val))\n temp = temp.left\n else:\n r_min = float('inf')\n\n return min(l_min, r_min ,self.getMinimumDifference(root.left),self.getMinimumDifference(root.right))\n","sub_path":"Python/530.py","file_name":"530.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"79742813","text":"import os\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql import DataFrame\nfrom time import sleep\n\ndef main():\n print(\"Started aggregation example\")\n spark = get_spark_session()\n\n dfHeights: DataFrame = spark.read.option(\"header\", \"true\")\\\n .csv(\"./sample_datasets/heights.csv\").alias(\"heights\")\n dfNames: DataFrame = spark.read.option(\"header\", \"true\")\\\n .csv(\"./sample_datasets/names.csv\").alias(\"names\")\n joined_df: DataFrame = dfHeights.join(dfNames, \"id\")\n joined_df.show()\n\n print(\"Finished aggregation example\")\n\ndef get_spark_session():\n return SparkSession\\\n .builder.master(\"local\")\\\n .appName('SparkMapReduceExample')\\\n .getOrCreate()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"HeightsExampleJoin.py","file_name":"HeightsExampleJoin.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"602308161","text":"from .base import FunctionalTest\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport time\n\n\nTEST_EMAIL = 'astinchoi@mockmyid.com'\n\nclass LoginTest(FunctionalTest):\n\n def switch_to_new_window(self, text_in_title):\n retries = 60\n while retries > 0:\n for handle in self.browser.window_handles:\n self.browser.switch_to_window(handle)\n if text_in_title in self.browser.title:\n return\n retries -= 1\n time.sleep(0.5)\n self.fail('could not find window')\n\n def wait_for_element_with_id(self, element_id):\n WebDriverWait(self.browser, timeout=30).until(\n lambda b: b.find_element_by_id(element_id),\n 'Could not find element with id {}. Page text was {}'.format(\n element_id, self.browser.find_element_by_tag_name('body').text\n )\n )\n\n # def wait_to_be_logged_in(self):\n # self.wait_for_element_with_id('id_logout')\n # navbar = self.browser.find_element_by_css_selector('.navbar')\n # self.assertIn('astinchoi@mockmyid.com', navbar.text)\n\n # def wait_to_be_logged_out(self):\n # self.wait_for_element_with_id('id_login')\n # navbar = self.browser.find_element_by_css_selector('.navbar')\n # self.assertNotIn('astinchoi@mockmyid.com', navbar.text) \n\n def test_login_with_persona(self):\n self.browser.get(self.server_url)\n self.browser.find_element_by_id('id_login').click()\n\n self.switch_to_new_window('Mozilla Persona')\n\n self.browser.find_element_by_id(\n 'authentication_email'\n ).send_keys(TEST_EMAIL)\n self.browser.find_element_by_tag_name('button').click()\n\n self.switch_to_new_window('To-Do')\n\n # self.wait_for_element_with_id('id_logout')\n # navbar = self.browser.find_element_by_css_selector('.navbar')\n # self.assertIn('astinchoi@mockmyid.com', navbar.text)\n self.wait_to_be_logged_in(email=TEST_EMAIL)\n\n self.browser.refresh()\n self.wait_to_be_logged_in(email=TEST_EMAIL)\n\n self.browser.find_element_by_id('id_logout').click()\n self.wait_to_be_logged_out(email=TEST_EMAIL)\n\n self.browser.refresh()\n self.wait_to_be_logged_out(email=TEST_EMAIL)","sub_path":"functional_tests/test_login.py","file_name":"test_login.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"29552955","text":"'''\r\n771. Jewels and Stones\r\nYou're given strings J representing the types of stones\r\nthat are jewels, and S representing the stones you have.\r\nEach character in S is a type of stone you have.\r\nYou want to know how many of the stones you have are also jewels.\r\n'''\r\n\r\nclass Solution(object):\r\n def numJewelsInStones(self, J, S):\r\n \"\"\"\r\n :type J: str\r\n :type S: str\r\n :rtype: int\r\n \"\"\"\r\n c=0\r\n for i in S:\r\n for j in J:\r\n if i == j:\r\n c+=1\r\n return c\r\n","sub_path":"leetcode/771.jewels-and-stones.py","file_name":"771.jewels-and-stones.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"98947850","text":"import importlib\nimport os\nimport sys\nimport getopt\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport random\nimport ast\n\nargs,_ = getopt.getopt(sys.argv[1:], \"i:t:m:a:p:o:\")\nargs = dict(args)\nif not (\"-i\" in args and \"-m\" in args and \"-t\" in args):\n\tprint(\"USAGE : train.py -i inputFile -t target -m model\")\n\tquit()\n\n\n\ntarget = args[\"-t\"]\npreprocessing = args[\"-p\"]\nmodelParameters = ast.literal_eval(args[\"-a\"])\nmodel = getattr(importlib.import_module(\"Models.\"+args[\"-m\"]), args[\"-m\"])(**modelParameters)\npre = getattr(importlib.import_module(\"Preprocessing.\"+args[\"-p\"]), \"preprocess\")\ndata = pre(pd.read_csv(args[\"-i\"]))\noutputFile = args[\"-o\"]\n\nos.system(\"clear\")\n\n\nprint(\"\\nInput file : \"+args[\"-i\"])\nprint(\"Target : \"+args[\"-t\"])\nprint(\"Model : \"+args[\"-m\"])\nprint(\"Models parameters : \"+args[\"-a\"])\nprint(\"Preprocessing method : \"+args[\"-p\"])\nprint(\"Output file : \"+args[\"-o\"])\n\nY = data[target]\nX = data.drop(target, axis=1)\n\nmsk = np.random.rand(len(X)) < 0.5\n\ntrainX = X[msk]\ntestX = X[~msk]\ntrainY = Y[msk]\ntestY = Y[~msk]\n\nmodel.fit(trainX, trainY)\n\nprint(\"Train score = \" + str(model.score(trainX, trainY)))\nprint(\"Test score = \" + str(model.score(testX, testY)))\n\npd.DataFrame(model.predict(X), columns=[target]).to_csv(outputFile)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"132568366","text":"\"\"\"\nDefinition of views.\n\"\"\"\n\nfrom app.models import Choice, Poll\nfrom datetime import datetime\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpRequest, HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404, render\nfrom django.template import RequestContext\nfrom django.utils import timezone\nfrom django.views.generic import ListView, DetailView\nfrom os import path\n\nimport json\n\nfrom .forms import ActorForm\n\nif form.is_valid():\n actor = form.cleaned_data['actor']\n\n\n\ndef get_actor(request):\n # if this is a POST request we need to process the form data\n if request.method == 'POST':\n # create a form instance and populate it with data from the request:\n form = ActorForm(request.POST)\n # check whether it's valid:\n if form.is_valid():\n # process the data in form.cleaned_data as required\n # ...\n # redirect to a new URL:\n return HttpResponseRedirect('/answer')\n\n # if a GET (or any other method) we'll create a blank form\n else:\n form = ActorForm()\n\n return render(request, 'answer.html', {'form': form})\n\nclass PollListView(ListView):\n \"\"\"Renders the home page, with a list of all polls.\"\"\"\n model = Poll\n\n def get_context_data(self, **kwargs):\n context = super(PollListView, self).get_context_data(**kwargs)\n context['title'] = 'Polls'\n context['year'] = datetime.now().year\n return context\n\nclass PollDetailView(DetailView):\n \"\"\"Renders the poll details page.\"\"\"\n model = Poll\n\n def get_context_data(self, **kwargs):\n context = super(PollDetailView, self).get_context_data(**kwargs)\n context['title'] = 'Poll'\n context['year'] = datetime.now().year\n return context\n\nclass PollResultsView(DetailView):\n \"\"\"Renders the results page.\"\"\"\n model = Poll\n\n def get_context_data(self, **kwargs):\n context = super(PollResultsView, self).get_context_data(**kwargs)\n context['title'] = 'Results'\n context['year'] = datetime.now().year\n return context\n\ndef contact(request):\n \"\"\"Renders the contact page.\"\"\"\n assert isinstance(request, HttpRequest)\n return render(\n request,\n 'app/contact.html',\n {\n 'title':'Contact',\n 'message':'Your contact page.',\n 'year':datetime.now().year,\n \n }\n )\n\ndef about(request):\n \"\"\"Renders the about page.\"\"\"\n assert isinstance(request, HttpRequest)\n return render(\n request,\n 'app/about.html',\n {\n 'title':'About',\n 'message':'Your application description page.',\n 'year':datetime.now().year,\n }\n )\n\ndef vote(request, poll_id):\n \"\"\"Handles voting. Validates input and updates the repository.\"\"\"\n poll = get_object_or_404(Poll, pk=poll_id)\n try:\n selected_choice = poll.choice_set.get(pk=request.POST['choice'])\n except (KeyError, Choice.DoesNotExist):\n return render(request, 'app/details.html', {\n 'title': 'Poll',\n 'year': datetime.now().year,\n 'poll': poll,\n 'error_message': \"Please make a selection.\",\n })\n else:\n selected_choice.votes += 1\n selected_choice.save()\n return HttpResponseRedirect(reverse('app:results', args=(poll.id,)))\n\n@login_required\ndef seed(request):\n \"\"\"Seeds the database with sample polls.\"\"\"\n samples_path = path.join(path.dirname(__file__), 'samples.json')\n with open(samples_path, 'r') as samples_file:\n samples_polls = json.load(samples_file)\n\n for sample_poll in samples_polls:\n poll = Poll()\n poll.text = sample_poll['text']\n poll.pub_date = timezone.now()\n poll.save()\n\n for sample_choice in sample_poll['choices']:\n choice = Choice()\n choice.poll = poll\n choice.text = sample_choice\n choice.votes = 0\n choice.save()\n\n return HttpResponseRedirect(reverse('app:home'))\n\ndef answer(request):\n \"\"\"Renders the answer page.\"\"\"\n assert isinstance(request, HttpRequest)\n return render(\n request,\n 'app/answer.html',\n {\n 'title':'Answer',\n 'message':'ANSWER:',\n 'year':datetime.now().year,\n }\n )","sub_path":"KevinBaconFrontEnd/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"336001651","text":"#! python\n# coding:utf-8\n# Author:VChao\n# Date: 2019/05/16\n\nimport random\nimport copy\nimport math\n\nX_nums = 12\nY_nums = 12\n\nkey_map = {\n 'LEFT': 1,\n 'RIGHT': 2,\n 'DOWN': 3,\n 'UP': 4\n}\n\nactions = [\n [1, 3, 4],\n [2, 3, 4],\n [1, 2, 3],\n [1, 2, 4]\n]\n\n\nclass SnakeState(object):\n def __init__(self, snake=[], direction=0, food=[], grow=False):\n self.snake = copy.deepcopy(snake)\n self.food = copy.deepcopy(food)\n self.direction = direction\n self.grow = grow\n self.pong = [-1, -1]\n\n def __str__(self):\n return str(self.snake[0])\n\n def init_by_game(self):\n direction = random.randint(1, 4)\n x = random.randint(0, X_nums - 1)\n y = random.randint(0, Y_nums - 1)\n\n self.snake = [[x, y]]\n self.direction = direction\n self.grow = True\n self.next_state_for_game(self.direction)\n self.drop_food()\n\n def status_str(self):\n return str(\n \"score:%d,head_x:%d,head_y:%d,food_x:%d,food_y:%d\" % (\n len(self.snake) - 2,\n self.snake[0][0],\n self.snake[0][1],\n self.food[0][0],\n self.food[0][1]\n )\n )\n\n def get_actions(self):\n return actions[self.direction - 1]\n\n def get_state_by_game(self):\n return self.snake, self.food, self.pong\n\n @staticmethod\n def head_change(current_x_head, current_y_head, action):\n\n if action == key_map['LEFT']:\n current_x_head, current_y_head = current_x_head - 1, current_y_head\n if current_x_head < 0:\n current_x_head = X_nums - 1\n\n if action == key_map['RIGHT']:\n current_x_head, current_y_head = current_x_head + 1, current_y_head\n if current_x_head >= X_nums:\n current_x_head = 0\n\n if action == key_map['DOWN']:\n current_x_head, current_y_head = current_x_head, current_y_head + 1\n if current_y_head >= Y_nums:\n current_y_head = 0\n\n if action == key_map['UP']:\n current_x_head, current_y_head = current_x_head, current_y_head - 1\n if current_y_head < 0:\n current_y_head = Y_nums - 1\n\n head = [current_x_head, current_y_head]\n return head\n\n def drop_food(self):\n x = random.randint(0, X_nums - 1)\n y = random.randint(0, Y_nums - 1)\n # Do not drop food on snake\n for pos in self.snake:\n if pos == [x, y]:\n self.drop_food()\n return\n self.food.append([x, y])\n\n def is_success(self):\n for pos in self.food:\n if pos == self.snake[0]:\n return True\n return False\n\n def is_success_for_game(self):\n if self.is_success():\n self.food.pop()\n self.drop_food()\n self.grow = True\n\n def change_direction_for_game(self, key):\n if key == key_map['LEFT']:\n if self.direction != key_map['RIGHT']:\n self.direction = key_map['LEFT']\n elif key == key_map['RIGHT']:\n if self.direction != key_map['LEFT']:\n self.direction = key_map['RIGHT']\n elif key == key_map['DOWN']:\n if self.direction != key_map['UP']:\n self.direction = key_map['DOWN']\n elif key == key_map['UP']:\n if self.direction != key_map['DOWN']:\n self.direction = key_map['UP']\n\n def next_state_for_game(self, action):\n\n head = self.head_change(self.snake[0][0], self.snake[0][1], action)\n self.snake.insert(0, head)\n if not self.grow:\n self.snake.pop()\n else:\n self.grow = False\n\n def state_change(self, action):\n\n snake = copy.deepcopy(self.snake)\n food = copy.deepcopy(self.food)\n\n head = self.head_change(snake[0][0], snake[0][1], action)\n\n snake.insert(0, head)\n if not self.grow:\n snake.pop()\n\n return SnakeState(snake, action, food)\n\n def is_normal(self):\n for i in range(1, len(self.snake)):\n if self.snake[i] == self.snake[0]:\n self.pong = self.snake[i]\n return False\n return True\n\n def distance_function(self):\n return math.sqrt(\n (self.snake[0][0] - self.food[0][0]) ** 2 +\n (self.snake[0][1] - self.food[0][1]) ** 2\n )\n","sub_path":"snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":4445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"238803972","text":"import numpy as np\nimport time\nimport datetime\nimport pandas as pd\nimport pdb\nfrom tqdm import tqdm\n\nclass OuterRadiation:\n\n def __init__(self,\n # ex) around Tokyo\n latitude = np.array([35.695, 35.705, 35.715]), \n longitude = np.array([139.725, 139.735, 139.745]), \n date = np.array([2016,1,1,12,0])\n # [year, month, day, hoor, second]\n ):\n\n self.rownames = list(map(str, latitude[::-1]))\n self.colnames = list(map(str, longitude))\n self.dp = pd.Panel(major_axis = self.rownames, minor_axis = self.colnames)\n \n self.latitude = np.radians(latitude)\n self.longitude = np.radians(longitude)\n\n \n\n self.y, self.m, self.d, self.h, self.s = date\n\n days = datetime.datetime(self.y, self.m, self.d) - \\\n datetime.datetime(self.y, 1, 1)\n self.dn = days.days + 1\n\n self.theta = 2 * np.pi * (self.dn - 1)/365\n\n # sun declination\n self.delta = 0.006918 - 0.399912 * np.cos(self.theta) \\\n + 0.070257 * np.sin(self.theta) \\\n - 0.006758 * np.cos(2 * self.theta) \\\n + 0.000907 * np.sin(2 * self.theta) \\\n - 0.002697 * np.cos(3 * self.theta) \\\n + 0.001480 * np.sin(3 * self.theta)\n\n # Geocentric solar distance\n self.r = 1 / np.sqrt(1.000110 + 0.034221 * np.cos(self.theta) \\\n + 0.001280 * np.sin(self.theta) \\\n + 0.000719 * np.cos(2 * self.theta) \\\n + 0.000077 * np.sin(2 * self.theta))\n\n # Uniform time difference\n \n self.Eq = - 0.0002786049 + 0.1227715 * np.cos(self.theta + 1.498311) \\\n - 0.1654575 * np.cos(2 * self.theta - 1.261546) \\\n - 0.0053538 * np.cos(3 * self.theta - 1.1571)\n\n self.StandardLatitude = np.radians(135.0)\n\n # tenmoral solar angle\n self.angle = None\n\n # sun orientation\n self.psi = None\n # sun altitude\n self.alpha = None\n\n # radiation out of air\n self.Q = None\n\n def compute(self, interval = 2.5, number = 10, save = False):\n\n yname = str(self.y)\n if(self.m < 10):\n mname = '0' + str(self.m)\n elif():\n mname = str(self.m)\n if(self.d < 10):\n dname = '0' + str(self.d)\n elif():\n dname = str(self.d)\n \n\n # for each time\n for i in tqdm(range(number)):\n\n df = pd.DataFrame(index = self.latitude[::-1])\n\n interval_sum = interval * i\n \n h = self.h + (self.s + interval_sum)//60\n if(h < 10):\n hname = '0' + str(h)\n elif():\n hname = str(h)\n\n s = (10 * interval_sum//10)%60\n if(s < 10):\n sname = '0' + str(s)\n elif():\n sname = str(s)\n\n a = 1 + i%4\n aname = '0' + str(a)\n \n # for each longtitude\n for lon in self.longitude:\n \n self.angle = (self.h + (self.s + interval * i)/60 - 12) \\\n * np.pi / 12 \\\n + (lon - self.StandardLatitude) \\\n + self.Eq * np.pi / 12\n\n Qseries = []\n # for each latitude\n for lat in self.latitude:\n \n self.alpha = np.arcsin(np.sin(lat) * np.sin(self.delta) \\\n + np.cos(lat) \\\n * np.cos(self.delta) \\\n * np.cos(self.angle))\n self.psi = np.arctan(np.cos(lat) * np.cos(self.delta) \\\n * np.sin(self.angle) \\\n / (np.sin(lat) * np.sin(self.alpha))\\\n - np.sin(self.delta))\n self.Q = 1367 * self.r**2 * np.sin(self.alpha)\n\n Qseries.append(self.Q)\n \n Qseries = Qseries[::-1]\n\n df[str(np.rad2deg(lon))] = Qseries\n\n index = [str(np.rad2deg(l)) for l in self.latitude[::-1]]\n df.index = index\n # pdb.set_trace()\n\n self.dp[i] = df\n\n return self.dp\n","sub_path":"datautil/OuterRadiation.py","file_name":"OuterRadiation.py","file_ext":"py","file_size_in_byte":4503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"558765098","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn import datasets, linear_model\nfrom sklearn.metrics import mean_squared_error, r2_score\n\n\n# Load the diabetes dataset\ndiabetes = datasets.load_diabetes()\n# Use only one feature\ndiabetes_X = diabetes.data[:, np.newaxis, 2]\n\n# 데이터 설정\nX_train, X_test = diabetes_X[:-20],diabetes_X[-20:]\ny_train, y_test = diabetes.target[:-20], diabetes.target[-20:]\n\nprint(X_train, '----------',X_test)\nprint()\nprint(y_train, '-------------',y_test)\ndef Linear_model_def(X_train,y_train,X_test):\n Linear_model = linear_model.LinearRegression() # Linear 모델 선언\n Linear_model.fit(X_train, y_train) # 학습 데이터 fit\n y_pred = Linear_model.predict(X_test) # 예측 데이터\n # # The coefficients\n # print('Coefficients: \\n', Linear_model.coef_)\n # # The mean squared error\n # print(\"Mean squared error: %.2f\" %mean_squared_error(y_test, y_pred))\n # # Explained variance score: 1 is perfect prediction\n # print('Variance score: %.2f' %r2_score(y_test, y_pred))\n # Plot outputs\n plt.scatter(X_test, y_test, color='red')\n plt.plot(X_test, y_pred, color='blue', linewidth=6)\n plt.scatter(X_train, y_train, color='black')\n plt.plot(X_train, Linear_model.predict(X_train), color='blue', linewidth=3)\n plt.xticks(())\n plt.yticks(())\n\nLinear_model_def(X_train,y_train,X_test)\nplt.show()","sub_path":"Bigcon_package/temp/lin.py","file_name":"lin.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}