diff --git "a/4709.jsonl" "b/4709.jsonl" new file mode 100644--- /dev/null +++ "b/4709.jsonl" @@ -0,0 +1,679 @@ +{"seq_id":"83723868","text":"from upscaler.data import load_images_from_dir, split_images_train_test, downscale_images, crop_images_cgc\nfrom upscaler.data import select_random_rows, convert_image_series_to_array, convert_array_to_image\nfrom upscaler.data import save_img_orig, save_img_resize, save_img_predict\nfrom upscaler.model import make_upscaler_skip_con, make_upscaler_orig, make_upscaler_unetish, make_upscaler_unetish_add, make_upscaler_attention\nfrom upscaler.model import make_discriminator_simple_512\nfrom upscaler.model import VGG_LOSS, VGG_MSE_LOSS, VGG_MAE_LOSS, wasserstein_loss\nfrom upscaler.model import make_and_compile_gan\nfrom upscaler.json import PandasEncoder\nfrom keras.utils.vis_utils import plot_model\n\nimport math\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nimport os\nimport sys\nimport argparse\nimport json\n\nif __name__== \"__main__\":\n \n ###########################################################\n ## Preparing call arguments parsing\n ###########################################################\n \n parser = argparse.ArgumentParser()\n \n parser.add_argument('-i', '--image_input_dir', action='store', dest='image_input_dir', default='ukiyo-e_fullhd', help='Path to load images from (subdir of \"../images/\")')\n \n parser.add_argument('-i1g', '--image_input_dir_1gen', action='store', dest='image_input_dir_1gen', default='ukiyo-e_1gen', help='Path to load images 1 generator converted messages from (subdir of \"../images/\")')\n \n parser.add_argument('-i2g', '--image_input_dir_2gen', action='store', dest='image_input_dir_2gen', default='ukiyo-e_2gen', help='Path to load images 2 generator converted messages from (subdir of \"../images/\")')\n \n parser.add_argument('-s', '--subdir', action='store', dest='subdir', default='ukiyo', help='Subdir to put generated images, trained models, etc to')\n \n parser.add_argument('-p', '--output_prefix', action='store', dest='output_prefix', default='auto', help='Prefix to put in names of generated files (and sometimes also a subdir). Default value \\'auto\\' means generate it automatically')\n \n parser.add_argument('-ic', '--image_count', action='store', dest='image_count', default='3000', help='Number of images to be used (and split into training and test sets)', type=int)\n \n parser.add_argument('-tr', '--train_test_ratio', action='store', dest='train_test_ratio', default='0.95', help='Ratio of splitting images into the test and train sets', type=float)\n \n parser.add_argument('-gm', '--generator_model', action='store', dest='generator_model', default='resnet-att', choices=['orig','skip-con','resnet-att','unetish','unetish-add'], help='Generator model to be used')\n \n parser.add_argument('-dm', '--discriminator_model', action='store', dest='discriminator_model', default='simple-512', choices=['simple-512'], help='Discriminator model to be used')\n \n parser.add_argument('-da', '--discriminator_activation', action='store', dest='discriminator_activation', default='log', choices=['none', 'sigmoid', 'tanh', 'log'], help='Activation to use for the discriminator')\n \n parser.add_argument('-cl', '--content_loss', action='store', dest='content_loss', default='vgg-only', choices=['vgg-only','vgg-mae','vgg-mse'], help='Content loss function to be used for the training')\n \n parser.add_argument('-dl', '--discriminator_loss', action='store', dest='discriminator_loss', default='wasserstein', choices=['wasserstein'], help='Discriminator loss function to be used for the training')\n \n parser.add_argument('-dlw', '--discriminator_loss_weight', action='store', dest='discriminator_loss_weight', default='1e-10', type=float, help='Weight of the discriminator loss function to be used for the training GAN. Generator loss weight is considered to be equal 1')\n \n parser.add_argument('-lw', '--non_vgg_loss_weight', action='store', dest='non_vgg_loss_weight', default='0.001', help='Weight of the loss other than VGG (if there is any)', type=float)\n \n parser.add_argument('-msf', '--model_save_freq', action='store', dest='model_save_freq', default='500', help='How frequently a model should be saved? (number of batches)', type=int)\n \n parser.add_argument('-bs', '--batch_size', action='store', dest='batch_size', default='2', help='Number of examples to be put in the batch', type=int)\n \n parser.add_argument('-oh', '--output_height', action='store', dest='output_height', default='512', help='Height of the output during training', type=int)\n \n parser.add_argument('-ow', '--output_width', action='store', dest='output_width', default='512', help='Width of the output during training', type=int)\n \n parser.add_argument('-nb', '--number_of_batches', action='store', dest='number_of_batches', default='400001', help='Number batches to be run', type=int)\n \n parser.add_argument('-d', '--downscale_factor', action='store', dest='downscale_factor', default='4', help='Downscale factor', type=int)\n \n parser.add_argument('-ks', '--kernel_size', action='store', dest='kernel_size', default='5', help='Kernel size', type=int)\n \n parser.add_argument('-dr', '--dropout_rate', action='store', dest='dropout_rate', default='0.0', help='Dropout rate to be used (if supported by given model)', type=float)\n\n parser.add_argument('-ss', '--split_seed', action='store', dest='split_seed', default='42', help='Dropout rate to be used (if supported by given model)', type=int)\n \n values = parser.parse_args()\n \n \n ###########################################################\n ## Parameters of input and output images\n ###########################################################\n \n downscale_factor = values.downscale_factor\n kernel_size = values.kernel_size\n # upscale_times = int(math.log(downscale_factor,2))\n output_image_shape = (values.output_height, values.output_width,3)\n input_image_shape = (\n output_image_shape[0] // downscale_factor,\n output_image_shape[1] // downscale_factor,\n output_image_shape[2]\n )\n target_shape = (\n output_image_shape[1],\n output_image_shape[0]\n )\n if int(math.log(downscale_factor,2)) != math.log(downscale_factor,2):\n print(\"Downscale factor needs to be a power of 2. It was %d.\" % downscale_factor)\n sys.exit(0)\n \n \n ###########################################################\n ## Reading call arguments and setting up paths\n ###########################################################\n \n script_dirname = os.path.dirname(sys.argv[0])\n if script_dirname == '':\n script_dirname = '.'\n input_dir = script_dirname + '/../images/' + values.image_input_dir\n input_dir_1gen = script_dirname + '/../images/' + values.image_input_dir_1gen\n input_dir_2gen = script_dirname + '/../images/' + values.image_input_dir_2gen\n model_save_dir = script_dirname + '/' + 'trained_model'\n loss_save_dir = script_dirname + '/' + 'losses'\n images_dir = script_dirname + '/' + 'example_images'\n subdir = values.subdir\n #model_prefix = \"orig_vgg-mse\"\n model_prefix = values.output_prefix\n if model_prefix == 'auto':\n model_prefix = \"gan_\" + values.generator_model + \"_\" + values.content_loss + \"_\" + values.discriminator_model + \"_\" + values.discriminator_loss + '_' + values.discriminator_activation + (\"_x%d\" % downscale_factor)\n print(\"Prefix generated automatically: '\" + model_prefix + \"'\")\n \n number_of_images = values.image_count\n train_test_ratio = values.train_test_ratio\n\n # where the examples of images will be saved\n image_path = images_dir + '/' + subdir + '/' + model_prefix\n if not os.path.exists(image_path):\n os.makedirs(image_path)\n print(\"Generated images will be saved to: '\" + image_path + \"'\")\n\n # where models and loss values will be saved\n model_path = model_save_dir + '/' + subdir + '/' + model_prefix\n if not os.path.exists(model_path):\n os.makedirs(model_path)\n print(\"Trained models will be saved to: '\" + model_path + \"'\")\n upscaler_model_file_name_tpl = model_path + '/' + 'model_upscaler_' + model_prefix + '_%06db.h5'\n discriminator_model_file_name_tpl = model_path + '/' + 'model_discriminator_' + model_prefix + '_%06db.h5'\n upscaler_model_file_name_best = model_path + '/' + 'model_upscaler_' + model_prefix + '_best.h5'\n discriminator_model_file_name_best = model_path + '/' + 'model_discriminator_' + model_prefix + '_best.h5'\n \n loss_path = loss_save_dir + '/' + subdir + '/' + model_prefix\n if not os.path.exists(loss_path):\n os.makedirs(loss_path)\n print(\"Loss values and training parameters will be saved to: '\" + loss_path + \"'\")\n loss_file_name = loss_path + '/' + 'losses_upscaler_' + model_prefix + '.txt'\n best_loss_file_name = loss_path + '/' + 'losses_upscaler_' + model_prefix + '_best.txt'\n param_file_path = loss_path + '/' + 'parameters.json'\n progress_file_path = loss_path + '/' + 'progress.json'\n\n ###########################################################\n ## Loading the data\n ###########################################################\n \n images_fullhd = load_images_from_dir(\n input_dir,\n '.jpg',\n limit = number_of_images,\n prog_func = tqdm\n )\n images_fullhd = downscale_images(\n images_fullhd,\n prog_func = tqdm,\n downscale_ratio = downscale_factor\n )\n images_fullhd = images_fullhd.rename(columns={'image_hr': 'fullhd', 'downscaled' : 'scaled'})\n \n images_1gen = load_images_from_dir(\n input_dir_1gen,\n '.jpg',\n limit = number_of_images * 10000,\n prog_func = tqdm\n )\n images_1gen = images_1gen.rename(columns={'image_hr': 'gen1'}).drop(columns='image_size')\n \n images_2gen = load_images_from_dir(\n input_dir_2gen,\n '.jpg',\n limit = number_of_images * 10000,\n prog_func = tqdm\n )\n images_2gen = images_2gen.rename(columns={'image_hr': 'gen2'}).drop(columns='image_size')\n \n \n images_all = (images_fullhd\n .join(images_1gen.set_index('filename'), on = 'filename', how = 'inner')\n .join(images_2gen.set_index('filename'), on = 'filename', how = 'inner')\n )\n \n images_all = crop_images_cgc(images_all, target_shape = target_shape, seed = values.split_seed, downscale_ratio = downscale_factor)\n \n images_train, images_test = split_images_train_test(images_all, train_test_ratio, seed = values.split_seed)\n \n ###########################################################\n ## Saving train parameters file\n ###########################################################\n \n parameters = vars(values)\n parameters['model_prefix'] = model_prefix\n parameters['train_set'] = images_train.filename\n parameters['test_set'] = images_test.filename\n \n with open(param_file_path, 'w+') as param_file:\n json.dump(parameters, param_file, indent = 4, cls = PandasEncoder)\n\n \n ###########################################################\n ## Setting up the model for training\n ###########################################################\n \n # create the generator instance\n if values.generator_model == 'orig':\n upscaler = make_upscaler_orig(output_image_shape, kernel_size = kernel_size, upscale_factor = downscale_factor)\n elif values.generator_model == 'skip-con':\n upscaler = make_upscaler_skip_con(output_image_shape, kernel_size = kernel_size, upscale_factor = downscale_factor)\n elif values.generator_model == 'resnet-att':\n upscaler = make_upscaler_attention(output_image_shape, kernel_size = kernel_size, upscale_factor = downscale_factor)\n elif values.generator_model == 'unetish':\n upscaler = make_upscaler_unetish(output_image_shape, kernel_size = kernel_size, upscale_factor = downscale_factor, dropout_rate=values.dropout_rate)\n elif values.generator_model == 'unetish-add':\n upscaler = make_upscaler_unetish_add(output_image_shape, kernel_size = kernel_size, upscale_factor = downscale_factor, dropout_rate=values.dropout_rate)\n \n plot_model(upscaler, to_file=loss_path+'/model_plot.png', show_shapes=True, show_layer_names=True)\n #upscaler.summary(line_length=200)\n #sys.exit(0)\n \n # create the discriminator instance\n if values.discriminator_model == 'simple-512':\n discriminator = make_discriminator_simple_512(output_image_shape, activation = values.discriminator_activation)\n \n # create the content loss\n if values.content_loss == 'vgg-only':\n content_loss = VGG_LOSS(output_image_shape).loss\n elif values.content_loss == 'vgg-mae':\n content_loss = VGG_MAE_LOSS(output_image_shape, values.non_vgg_loss_weight).loss\n elif values.content_loss == 'vgg-mse':\n content_loss = VGG_MSE_LOSS(output_image_shape, values.non_vgg_loss_weight).loss\n \n # create the discriminator loss\n if values.discriminator_loss == 'wasserstein':\n discriminator_loss = wasserstein_loss\n \n # setting up the model for training\n gen_train, disc_train, gan_train = make_and_compile_gan(\n generator = upscaler, discriminator = discriminator,\n input_shape = input_image_shape, output_shape = output_image_shape,\n content_loss = content_loss, content_loss_weight = 1,\n discriminator_loss = discriminator_loss, discriminator_loss_weight = values.discriminator_loss_weight\n )\n \n ###########################################################\n ## Model training\n ###########################################################\n \n agg_loss_disc = 0.0\n agg_loss_gan_gen = 0.0\n agg_loss_gan_disc = 0.0\n loss_update_rate = 0.01\n best_loss = np.inf\n \n # progress log initialisation\n progress = {\n 'best_model': None,\n 'saved_models': None\n }\n \n saved_models = pd.DataFrame({\n 'batch': [],\n 'loss_disc': [],\n 'agg_loss_disc': [],\n 'loss_gan_gen': [],\n 'agg_loss_gan_gen': [],\n 'loss_gan_disc': [],\n 'agg_loss_gan_disc': [],\n 'path_upscaler': [],\n 'path_discriminator': []\n })\n \n # loss logs initialisations\n with open(loss_file_name, 'w+') as loss_file:\n loss_file.write('batch\\tloss_disc\\tagg_loss_disc\\tloss_gan_gen\\tagg_loss_gan_gen\\tloss_gan_disc\\tagg_loss_gan_disc\\n')\n\n with open(best_loss_file_name, 'w+') as loss_file:\n loss_file.write('batch\\tloss_disc\\tagg_loss_disc\\tloss_gan_gen\\tagg_loss_gan_gen\\tloss_gan_disc\\tagg_loss_gan_disc\\n')\n \n \n # saving lowres and highres examples\n save_img_orig(images_train.cropped_hd[0:10], image_path, model_prefix + '_train', quality = 95)\n save_img_resize(images_train.cropped_gen1[0:10], image_path, model_prefix + '_train', sufix = '_1gen', target_size = target_shape, quality = 95)\n save_img_resize(images_train.cropped_gen2[0:10], image_path, model_prefix + '_train', sufix = '_2gen', target_size = target_shape, quality = 95)\n save_img_resize(images_train.cropped_scaled[0:10], image_path, model_prefix + '_train', sufix = '_scal', target_size = target_shape, quality = 95)\n \n save_img_orig(images_test.cropped_hd[0:10], image_path, model_prefix + '_test', quality = 95)\n save_img_resize(images_test.cropped_gen1[0:10], image_path, model_prefix + '_test', sufix = '_1gen', target_size = target_shape, quality = 95)\n save_img_resize(images_test.cropped_gen2[0:10], image_path, model_prefix + '_test', sufix = '_2gen', target_size = target_shape, quality = 95)\n save_img_resize(images_test.cropped_scaled[0:10], image_path, model_prefix + '_test', sufix = '_scal', target_size = target_shape, quality = 95)\n \n \n # actual training loop\n for b in tqdm(range(values.number_of_batches), desc = 'Batch'):\n\n batch_df = select_random_rows(images_train, n=values.batch_size)\n \n batch_hr = pd.concat([batch_df.cropped_hd, batch_df.cropped_hd, batch_df.cropped_hd], ignore_index=True)\n batch_lr = pd.concat([batch_df.cropped_gen1, batch_df.cropped_gen2, batch_df.cropped_scaled], ignore_index=True)\n \n image_batch_hr = convert_image_series_to_array(batch_hr)\n image_batch_lr = convert_image_series_to_array(batch_lr)\n image_batch_gen = gen_train.predict(image_batch_lr)\n # batch provided on the input of the discriminator training\n image_batch_disc = np.concatenate((image_batch_hr, image_batch_gen), axis=0)\n \n # expected discriminator outputs: 1 - original image, -1 - upscaled\n disc_real_y = np.ones(3 * values.batch_size)\n disc_fake_y = -disc_real_y\n # expected output provided for the discriminator training\n image_batch_y = np.concatenate((disc_real_y, disc_fake_y), axis=0)\n \n # training\n loss_disc = disc_train.train_on_batch(image_batch_disc, image_batch_y)\n loss_gan, loss_gan_gen, loss_gan_disc = gan_train.train_on_batch(image_batch_lr, [image_batch_hr,disc_real_y])\n \n agg_loss_disc = (1 - loss_update_rate) * agg_loss_disc + loss_update_rate * loss_disc\n agg_loss_gan_gen = (1 - loss_update_rate) * agg_loss_gan_gen + loss_update_rate * loss_gan_gen\n agg_loss_gan_disc = (1 - loss_update_rate) * agg_loss_gan_disc + loss_update_rate * loss_gan_disc\n\n with open(loss_file_name, 'a') as loss_file:\n loss_file.write('%d\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n' %(b, loss_disc, agg_loss_disc, loss_gan_gen, agg_loss_gan_gen, loss_gan_disc, agg_loss_gan_disc))\n \n # update progress log with best model\n if b > values.model_save_freq and agg_loss_gan_gen < best_loss:\n best_loss = agg_loss_gan_gen\n\n upscaler.save(upscaler_model_file_name_best)\n discriminator.save(discriminator_model_file_name_best)\n\n with open(best_loss_file_name, 'a') as loss_file:\n loss_file.write('%d\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n' %(b, loss_disc, agg_loss_disc, loss_gan_gen, agg_loss_gan_gen, loss_gan_disc, agg_loss_gan_disc))\n \n best_model_progress = {\n 'batch': b,\n 'loss_disc': float(loss_disc),\n 'agg_loss_disc': float(agg_loss_disc),\n 'loss_gan_gen': float(loss_gan_gen),\n 'agg_loss_gan_gen': float(agg_loss_gan_gen),\n 'loss_gan_disc': float(loss_gan_disc),\n 'agg_loss_gan_disc': float(agg_loss_gan_disc),\n 'saved_upscaler': upscaler_model_file_name_best,\n 'saved_discriminator': discriminator_model_file_name_best\n }\n progress['best_model'] = best_model_progress\n \n with open(progress_file_path, 'w+') as progress_file:\n json.dump(progress, progress_file, indent = 4, cls = PandasEncoder)\n\n # saving a next state of the model\n if(b % values.model_save_freq == 0):\n upscaler_model_file_name = upscaler_model_file_name_tpl % b\n upscaler.save(upscaler_model_file_name)\n \n discriminator_model_file_name = discriminator_model_file_name_tpl % b\n discriminator.save(discriminator_model_file_name)\n \n # update progress log with next model saved\n saved_models = saved_models.append({\n 'batch': b,\n 'loss_disc': float(loss_disc),\n 'agg_loss_disc': float(agg_loss_disc),\n 'loss_gan_gen': float(loss_gan_gen),\n 'agg_loss_gan_gen': float(agg_loss_gan_gen),\n 'loss_gan_disc': float(loss_gan_disc),\n 'agg_loss_gan_disc': float(agg_loss_gan_disc),\n 'path_upscaler': upscaler_model_file_name,\n 'path_discriminator': discriminator_model_file_name\n }, ignore_index=True)\n \n progress['saved_models'] = saved_models\n \n with open(progress_file_path, 'w+') as progress_file:\n json.dump(progress, progress_file, indent = 4, cls = PandasEncoder)\n \n save_img_predict(images_train.cropped_gen1[0:10], upscaler, image_path, model_prefix + '_train', b, sufix = '_1gen', quality = 95)\n save_img_predict(images_train.cropped_gen2[0:10], upscaler, image_path, model_prefix + '_train', b, sufix = '_2gen', quality = 95)\n save_img_predict(images_train.cropped_scaled[0:10], upscaler, image_path, model_prefix + '_train', b, sufix = '_scal', quality = 95)\n save_img_predict(images_test.cropped_gen1[0:10], upscaler, image_path, model_prefix + '_test', b, sufix = '_1gen', quality = 95)\n save_img_predict(images_test.cropped_gen2[0:10], upscaler, image_path, model_prefix + '_test', b, sufix = '_2gen', quality = 95)\n save_img_predict(images_test.cropped_scaled[0:10], upscaler, image_path, model_prefix + '_test', b, sufix = '_scal', quality = 95)\n \n","sub_path":"upscaling/train_gan.py","file_name":"train_gan.py","file_ext":"py","file_size_in_byte":21057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"388606011","text":"\n\nprogram = [1,2,3,4]\narrival_time = [4,2,5,0]\nburst_time = [4,6,7,5]\npriority = [3,1,4,2]\n\n\ndef shortestJobFirstNonPremptive():\n t = 0\n ans = []\n while(len(program) != 0):\n p = getNextProgram(t)\n if(p == -1):\n t = t + 1\n continue\n ans.append([program[p],t])\n t = t + burst_time[p]\n delProcess(p)\n return [ans,t]\n\n\ndef swap(i,j):\n tp,ta,tb,tpri = program[i],arrival_time[i],burst_time[i],priority[i]\n program[i],arrival_time[i],burst_time[i],priority[i] = program[j],arrival_time[j],burst_time[j],priority[j] \n program[j],arrival_time[j],burst_time[j],priority[j] = tp,ta,tb,tpri\n\ndef printProcesses():\n n = len(program)\n print(\"LIST OF PROCESSES WITH INFO\") \n print(\"id \",end=\"\")\n for i in range(n):\n print(\"%5d\"%program[i],end=\"\")\n \n print(\"\\narrival Time\",end=\"\")\n for i in range(n):\n print(\"%5d\"%arrival_time[i],end=\"\")\n\n print(\"\\nburst time \",end=\"\")\n for i in range(n):\n print(\"%5d\"%burst_time[i],end=\"\")\n \n print(\"\\npriority \",end=\"\")\n for i in range(n):\n print(\"%5d\"%priority[i],end=\"\")\n \n print(\"\\nEND\")\n\n\ndef sortByBurstTime():\n for i in range(len(program)):\n for j in range(len(program) - 1 - i):\n if(burst_time[j] > burst_time[j + 1]):\n swap(j,j+1)\n\ndef delProcess(i):\n program.pop(i)\n arrival_time.pop(i)\n burst_time.pop(i)\n priority.pop(i)\n\ndef getNextProgram(t):\n i = 0\n while(arrival_time[i] > t):\n i = i + 1\n if(i == len(program)):\n return -1\n return i\n\ndef printAns(ans,t):\n print(\"Process id :\",end=\"\")\n for i in range(len(ans)):\n print(\"%3d\"%ans[i][0],end=\"\")\n print(\"\\nExecution Time :\",end=\"\")\n for i in range(len(ans)):\n print(\"%3d\"%ans[i][1],end=\"\")\n print(\"\\nLast Process finished at\",t)\n\n\nprintProcesses() \nsortByBurstTime()\nprintProcesses()\nans = shortestJobFirstNonPremptive()\nprintAns(ans[0],ans[1])","sub_path":"Practical4/ShortestJobFirstNonPremptive.py","file_name":"ShortestJobFirstNonPremptive.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"313611471","text":"# -*- coding: utf-8 -*-\nimport re, string, collections, codecs\nimport pandas as pd\nfrom nltk.tokenize.punkt import PunktSentenceTokenizer, PunktParameters, PunktLanguageVars\n\n\ndef split_texts_by_sentences(path_in, path_out):\n text_count = 0\n sentence_count = 0\n output = codecs.open(path_out, \"w\", 'utf-8')\n for line in codecs.open(path_in, 'r', 'utf-8'):\n text_count += 1\n sentences = split(line)\n if len(sentences) > 0:\n for sentence in sentences:\n output.write(sentence + \"\\n\")\n sentence_count += 1\n else:\n output.write(\"\\n\")\n print(\"Wrote %d lines from %d texts from file %s\" % (sentence_count, text_count, path_in))\n output.close()\n\n\nclass CustomVars(PunktLanguageVars):\n sent_end_chars = ('.', '?', '!', ';')\n\n\npunkt_param = PunktParameters()\npunkt_param.abbrev_types = set(pd.read_csv('https://s3.amazonaws.com/datalawyer-models/datalawyer/lista_abreviacoes_lower.csv', header=None)[0].values)\nregex = re.compile('[%s]' % re.escape(string.punctuation))\nreplacements = {\"Dr(a)\": \"Dr_a_\", \"Sr(a)\": \"Sr_a_\", \"Exmo(a)\": \"Exmo_a_\"}\nreplacements_rev = {value: key for (key, value) in replacements.items()}\n\n\ndef sentence_tokenize(sentence_tokenizer, text):\n return [multi_replace(sentence, replacements_rev, ignore_case=True) for sentence in sentence_tokenizer.tokenize(\n multi_replace(text, replacements, ignore_case=True))]\n\n\ndef multi_replace(string, replacements, ignore_case=False):\n \"\"\"\n Given a string and a dict, replaces occurrences of the dict keys found in the\n string, with their corresponding values. The replacements will occur in \"one pass\",\n i.e. there should be no clashes.\n :param str string: string to perform replacements on\n :param dict replacements: replacement dictionary {str_to_find: str_to_replace_with}\n :param bool ignore_case: whether to ignore case when looking for matches\n :rtype: str the replaced string\n \"\"\"\n if ignore_case:\n replacements = dict((pair[0].lower(), pair[1]) for pair in sorted(replacements.items()))\n rep_sorted = sorted(replacements, key=lambda s: (len(s), s), reverse=True)\n rep_escaped = [re.escape(replacement) for replacement in rep_sorted]\n pattern = re.compile(\"|\".join(rep_escaped), re.I if ignore_case else 0)\n return pattern.sub(lambda match: replacements[match.group(0).lower() if ignore_case else match.group(0)], string)\n\n\ndef split_by_break(text):\n text = re.sub(r'[“”]', '\"', text)\n return [sentence.strip() for sentence in text.splitlines()]\n\n\ndef starts_with(quote_char, starting_text, text):\n return text.startswith(quote_char + starting_text)\n\n\ndef sanitize_segment(text, quote_chars=None, segments=None):\n if quote_chars is None:\n quote_chars = ['\"', '\\'']\n if segments is None:\n segments = [' (...),', ' (...);', ' (...)', '(...)', '[...]', ' ...', '...', '()', '),', ');', ')', ' ,', ' ;',\n ' -', '•', ',', ';']\n text = text.strip()\n for quote_char in quote_chars:\n for segment in segments:\n if text.count(quote_char) == 1:\n if starts_with(quote_char, segment, text):\n text = text.replace(quote_char + segment, '')\n elif text.count(quote_char) == 2:\n if text.startswith(quote_char):\n if text.endswith(quote_char):\n text = text[1:-1]\n assert text.count(quote_char) == 0\n text = text.replace(segment, '')\n elif text.endswith(quote_char + '.'):\n text = text[1:-2]\n assert text.count(quote_char) == 0\n text = text.replace(segment, '')\n if text.startswith(quote_char):\n patterns = ['\\d+\\.*', '^(\\-*\\d\\s*\\.*)*\\-*\\)*']\n for pattern in patterns:\n if re.fullmatch(pattern, text[1:]):\n text = re.sub(pattern, '', text)[1:]\n return text.strip()\n\n\ndef split_by_sentence(text, use_semicolon=False):\n if use_semicolon:\n sentence_tokenizer = PunktSentenceTokenizer(punkt_param, lang_vars=CustomVars())\n else:\n sentence_tokenizer = PunktSentenceTokenizer(punkt_param)\n if type(text) == str:\n text = re.sub(r'[“”]', '\"', text)\n return [sanitize_segment(paragraph) for paragraph in sentence_tokenize(sentence_tokenizer, text)]\n elif isinstance(text, collections.Iterable):\n result = []\n for subtext in text:\n subtext = re.sub(r'[“”]', '\"', subtext)\n result.extend(split_by_sentence(subtext, use_semicolon))\n return result\n\n\ndef split(text, use_semicolon=False):\n segments_by_break = split_by_break(text)\n return split_by_sentence(segments_by_break, use_semicolon)\n","sub_path":"scripts/split_text.py","file_name":"split_text.py","file_ext":"py","file_size_in_byte":4854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"442690141","text":"#! usr/bin/python\n#coding=utf-8\n\nfrom django.http import HttpResponse\nfrom django.shortcuts import render_to_response,render\nfrom django.shortcuts import HttpResponseRedirect\nimport os\nimport datetime,time\nimport sys\nsys.path.append(\"..\")\nfrom common.api.log2mysql import Log2mysql\nfrom common.api.db import MySqlconn\nfrom common.api.login_ldap import login_check\nfrom allup.dllup_v2 import alluplistget\nimport json,yaml\nfrom logwrite import AutoupLog\nimport zipfile\nimport redis\nfrom upfun import file_backup\nimport random\n\nfrom common.api.config import GetConfig\n\nconfigget = GetConfig()\nlogininfo = configget.get_config('/home/saltoneops-1.0.0/common/conf/beisencorp.conf','beisencorp',section='')\n#域认证账号\nusername = logininfo['user']\npassword = logininfo['passwd']\n\n#打开发布申请页面\n#顶方为选择产品及项目,添加发布申请\n#下面为所有申请列表,提供详细信息查询按钮\n#20160519 重写\n\n#备份机及路径\nbackup_path = '\\\\\\\\10.22.2.208\\\\e$\\\\saltup_backup\\\\'\n#回滚机及路径\nrollback_path = '\\\\\\\\10.22.2.208\\\\e$\\\\saltup_rollback\\\\'\n\n#备份机及路径\nbackup_ip = '10.22.2.208'\nnetuse_disk = 'e'\n\n\nr = redis.Redis(host='10.22.2.202',port=6379,db=2)\nfuntiondic = {\n 'website':'站点',\n 'service':'服务',\n 'esb':'ESB组件',\n 'other':'其他(如模板)',\n 'static':'静态文件集',\n 'newci':'新前端ci.beisen.co',\n 'remoteconf':'远程配置',\n 'regiest':'功能注册',\n 'sql':'数据库脚本',\n 'webconfig':'webconfig配置',\n 'relay':'缓存数据处理',\n 'othertool':'其他工具处理'\n}\n\n\ndef project_get(request):\n role = request.GET.get('rolename')\n product_id = request.GET.get('production_name')\n a = MySqlconn()\n if role == 'website':\n result_c = a.get_results('opsapp_appname', ['name', 'group_id'], {'type': 'WebSite','group_id':product_id}, False, False, False)\n elif role == 'esb':\n result_c = a.get_results('opsapp_appname', ['name', 'group_id'], {'type': 'Component','group_id':product_id}, False, False, False)\n elif role == 'service':\n result_c = a.get_results('opsapp_appname', ['name', 'group_id'], {'type': 'Service','group_id':product_id}, False, False, False)\n elif role == 'other':\n result_c = a.get_results('opsapp_appname', ['name', 'group_id'], {'type': 'Other','group_id':product_id}, False, False, False)\n else:\n result_c = a.get_results('opsapp_appname', ['name', 'group_id'], False, False, False, False)\n\n result_web = []\n\n for m in result_c:\n dictb = {\"project\": m['name'].encode('utf-8'), \"value\": int(m['group_id'])}\n result_web.append(dictb)\n return HttpResponse(json.dumps(result_web), content_type=\"application/json\")\n\n\n#hotfix 发布子页面(处理dll类hotfix)\n@login_check('/allup/hotfix/')\ndef publish_apply(request,funcation,role):\n username = request.session.get('info', None)['cn']\n status = {'0': '未发布', '1': '发布完成'}\n result_pro = []\n a = MySqlconn()\n#查询所有产品与id对应信息\n result_b = a.get_results('opsapp_appgroup',['ID','NAME'],False,False,False,False)\n for i in result_b:\n dicta = {'product_name':i['NAME'].encode('utf-8'),'value':int(i['ID'])}\n #dicta = {'text':i['NAME'].encode('utf-8'),'value':i['NAME'].encode('utf-8'),'extendAttr':{'id':int(i['ID'])}}\n result_pro.append(dicta)\n#查询所有站点与id队形信息\n\n#查询发布列表\n result_html = []\n if request.method == 'POST':\n hotfixid = time.mktime(datetime.datetime.now().timetuple())\n\n if not r.get(username):\n r.set(username,hotfixid)\n else:\n return render(request,'allup_dllhotfix/hotfix_apply_double.html')\n\n data = {}\n data['hotfixid'] = hotfixid\n data['hotfixcontain'] = request.POST.get('info')\n data['createtime'] = int(time.mktime(datetime.datetime.now().timetuple()))\n data['createuser'] = username\n data['hotfixstatus'] = 0\n data['enabled'] = 1\n data['publishteam'] = request.POST.get('product_name')\n\n a.execute_insert_sql('allup_info',data)\n b = Log2mysql()\n b.log2mysql(request.META['REMOTE_ADDR'], 'publish_apply', username,\n '发布编号为%s的hotfix申请' % (hotfixid))\n\n return render(request, 'allup_dllhotfix/publish_apply.html',\n {'production': result_pro, 'result': result_html, 'role': role,role:'active',funcation:'active'})\n else:\n result_html = alluplistget(username)\n\n return render(request,'allup_dllhotfix/publish_apply.html',\n {'production':result_pro,'result':result_html,'role':role,role:'active',funcation:'active'})\n\n\n#发布申请页面查看详情触发\n#打开查看发布详情页面\ndef publish_info(request,jobid):\n username = request.session.get('info', None)['cn']\n if request.method == 'GET':\n a = MySqlconn()\n if request.GET.has_key('jobup'):\n projectlist = request.GET.getlist('project')\n product = request.GET.get('product')\n updateinfo = request.GET.get('xiangxi')\n role = request.GET.get('role')\n for project in projectlist:\n publish_id = str(int(time.mktime(datetime.datetime.now().timetuple()))) + str(random.randint(1000,9999))\n name = os.popen('cd /srv/salt/%s/;find -type f ' % (jobid)).readlines()\n os.system('cp -r /srv/salt/%s/ /srv/salt/%s/'%(jobid,publish_id))\n if name == '' or project == '' or product == '':\n ip = request.META['REMOTE_ADDR']\n filelist = ''\n for filename in name:\n filelist = filelist + filename.strip() + '
'\n data = {'publish_succ':'申请发布失败','publish_time':publish_id[0:-4],'publish_id':publish_id,'publish_ip':ip,'publish_user':username,'publish_product':product,'publish_website':project,'publish_tmppath':'/srv/salt/%s'%jobid,'publish_contain':filelist,'publish_status':0,'publish_info':'
'.join(updateinfo.split()),'publish_role':role}\n data['hotfix_id'] = r.get(username)\n #a.execute_insert_sql('publish_info',data)\n data['publish_time']=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(int(publish_id[0:-4])))\n data.pop('publish_status')\n data['jobid']=publish_id\n #return render_to_response('dllup/publish_info.html',data)\n else:\n ip = request.META['REMOTE_ADDR']\n username = request.session.get('info',None)['cn']\n filelist = ''\n for filename in name:\n filelist = filelist + filename.strip() + '
'\n data = {'publish_succ':'申请发布成功','publish_time':publish_id[0:-4],'publish_id':publish_id,'publish_ip':ip,'publish_user':username,'publish_product':product,'publish_website':project,'publish_tmppath':'/srv/salt/%s'%jobid,'publish_contain':filelist,'publish_status':0,'publish_info':'
'.join(updateinfo.split()),'publish_role':role}\n data['hotfix_id'] = r.get(username)\n f = open('/srv/salt/%s/jobid_version')\n\n data['other1'] = f.read()\n f.close()\n a.execute_insert_sql('publishall_info',data)\n b = Log2mysql()\n b.log2mysql(request.META['REMOTE_ADDR'], 'publish_apply', username,\n '发布编号为%s的子hotfix申请' % (publish_id))\n data['publish_time']=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(int(publish_id[0:-4])))\n data['jobid']=publish_id\n data.pop('publish_status')\n\n publish_conf(data,publish_id)\n #init_check(jobid)\n #return render_to_response('dllup/publish_info.html',data)\n return render_to_response('allup_dllhotfix/publish_info.html', data)\n else:\n result_a = a.get_one_result('publishall_info',['publish_tmppath','publish_ip','publish_contain','publish_time','publish_user','publish_product','publish_website','publish_info','publish_id','other1'],{'publish_id':jobid},False,False,False)\n result_a['publish_time'] = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(int(result_a['publish_time'])))\n result_a['publish_info']=result_a['publish_info'].split('!#%@')\n return render_to_response('allup_dllhotfix/publish_info.html',result_a)\n\n#查看发布内容 不继承模板,用于在iframe里输出\n@login_check('/allup/hotfix/')\ndef publish_2info(request,jobid):\n username = request.session.get('info', None)['cn']\n if request.method == 'GET':\n a = MySqlconn()\n if request.GET.has_key('jobup'):\n projectlist = request.GET.get('project').split(',')\n product = request.GET.get('product')\n updateinfo = request.GET.get('xiangxi')\n role = request.GET.get('role')\n name = os.popen('cd /srv/salt/%s/;find -type f ' % (jobid)).readlines()\n publish_ids = []\n name.remove('./jobid_version\\n')\n\n\n for project in projectlist:\n publish_id = str(int(time.mktime(datetime.datetime.now().timetuple()))) + str(random.randint(1000, 9999))\n publish_ids.append(publish_id)\n os.system('cp -r /srv/salt/%s/ /srv/salt/%s/' % (jobid, publish_id))\n if name == '' or project == '' or product == '':\n ip = request.META['REMOTE_ADDR']\n filelist = ''\n for filename in name:\n filelist = filelist + filename.strip() + '
'\n data = {'publish_succ':'申请发布失败','publish_time':publish_id[0:-4],'publish_id':publish_id,'publish_ip':ip,'publish_user':username,'publish_product':product,'publish_website':project,'publish_tmppath':'/srv/salt/%s'%jobid,'publish_contain':filelist,'publish_status':0,'publish_info':'
'.join(updateinfo.replace('\\n','').split()),'publish_role':role}\n data['hotfix_id'] = r.get(username)\n #a.execute_insert_sql('publish_info',data)\n data['publish_time']=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(int(publish_id[0:-4])))\n data.pop('publish_status')\n data['jobid']=publish_id\n #return render_to_response('dllup/publish_2info.html',data)\n else:\n ip = request.META['REMOTE_ADDR']\n username = request.session.get('info',None)['cn']\n filelist = ''\n for filename in name:\n filelist = filelist + filename.strip() + '
'\n data = {\n 'publish_succ':'申请发布成功',\n 'publish_time':publish_id[0:-4],\n 'publish_id':publish_id,\n 'publish_ip':ip,\n 'publish_user':username,\n 'publish_product':product,\n 'publish_website':project,\n 'publish_tmppath':'/srv/salt/%s'%jobid,\n 'publish_contain':filelist,\n 'publish_status':0,\n 'publish_info':'
'.join(updateinfo.replace('\\n','').split()),\n 'publish_role':role,\n 'other2':'dllup'\n }\n data['hotfix_id'] = r.get(username)\n f = open('/srv/salt/%s/jobid_version'%jobid)\n\n data['other1'] = f.read()\n f.close()\n a.execute_insert_sql('publishall_info',data)\n b = Log2mysql()\n b.log2mysql(request.META['REMOTE_ADDR'], 'publish_apply', username,\n '发布编号为%s的子hotfix申请' % (publish_id))\n data['publish_time']=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(int(publish_id[0:-4])))\n data['jobid']=publish_id\n data.pop('publish_status')\n\n publish_conf(data,publish_id)\n backup_conf(data,publish_id)\n rollback_conf(data,publish_id)\n check_conf(data, publish_id)\n\n\n file_backup(publish_ids,username)\n #init_check(jobid)\n return render_to_response('allup_dllhotfix/publish_2info.html',data)\n\n#netuse认证配置\ndef netuse_login(ip,disk,username,password):\n netuse_data = []\n netusecmd = r'net use \\\\%s\\%s$ %s /user:beisencorp\\%s' % (ip, disk, password, username)\n netuse_data.append({'name': netusecmd})\n netuseover_data = {'cmd.run': netuse_data}\n return netuseover_data\n\n#netusedelete配置文件\ndef netuse_logout(ip,disk):\n netdel_data = []\n netdelcmd = r'net use \\\\%s\\%s$ /delete' % (backup_ip, netuse_disk)\n netdel_data.append({'name': netdelcmd})\n netdelover_data = {'cmd.run': netdel_data}\n return netdelover_data\n\n\n#提交成功时生成发布的配置文件\ndef publish_conf(data,jobid):\n a = MySqlconn()\n #sql = 'select b.filepath from dllout_server a,dllout_role b,dllout_product c where c.domainname = \\\"%s\\\" and b.ippid = c.id and a.id = b.serverid order by domainname'%data['publish_website']\n sql = 'select t1.app_path from opsapp_apps t1 \\\n INNER JOIN opsapp_appname t2 on t1.name_id=t2.id \\\n WHERE t2.name=\\'%s\\'' % data['publish_website']\n website_path = a.query(sql)[0]\n sls_json = {}\n m = 1\n for i in data['publish_contain'].split('
')[:-1]:\n sls_data = []\n result = i.split('/')\n del result[0]\n del result[0]\n name = website_path[0] + '\\\\'.join(result)\n sls_data.append({'name': name.encode('utf-8')})\n source = 'salt://' + str(data['publish_id']) + i[1:]\n sls_data.append({'source': source.encode('utf-8')})\n sls_data.append({'makedirs': 'True'})\n file_data = {'file.managed': sls_data}\n sls_json['fileup' + str(m)] = file_data\n m = m + 1\n os.system('touch /srv/salt/%s/sls%s.sls' % (jobid, jobid))\n f = open('/srv/salt/%s/sls%s.sls' % (jobid, jobid), 'w')\n f.write(yaml.dump(sls_json))\n f.close()\n os.system('sed -i \\'s#{##g\\' /srv/salt/%s/sls%s.sls' % (jobid, jobid))\n os.system('sed -i \\'s#}##g\\' /srv/salt/%s/sls%s.sls' % (jobid, jobid))\n os.system('sed -i \\'s# -# -#g\\' /srv/salt/%s/sls%s.sls' % (jobid, jobid))\n conf_sls = open('/srv/salt/%s/sls%s.sls' % (jobid, jobid), 'r')\n conf_view = conf_sls.readlines()\n conf_sls.close()\n result_conf = ''.join(conf_view)\n log_write = AutoupLog()\n log_write.autolog_write('warning', '生成更新的配置文件,内容为%s' % result_conf, jobid)\n\n\n#生成备份配置文件\ndef backup_conf(data,jobid):\n a = MySqlconn()\n #sql = 'select b.filepath from dllout_server a,dllout_role b,dllout_product c where c.domainname = \\\"%s\\\" and b.ippid = c.id and a.id = b.serverid order by domainname'%data['publish_website']\n sql = 'select t1.app_path from opsapp_apps t1 \\\n INNER JOIN opsapp_appname t2 on t1.name_id=t2.id \\\n WHERE t2.name=\\'%s\\'' % data['publish_website']\n website_path = a.query(sql)[0]\n sls_json = {}\n\n #netuse认证\n sls_json['a_netuse' ] = netuse_login(backup_ip,netuse_disk,username,password)\n\n m = 1\n for i in data['publish_contain'].split('
')[:-1]:\n sls_data = []\n result = i.split('/')\n del result[0]\n del result[0]\n name = website_path[0] + '\\\\'.join(result)\n if not result[:-1]:\n back = backup_path + str(data['publish_id']) + '\\\\{{grains.id}}\\\\'\n else:\n back = backup_path + str(data['publish_id']) + '\\\\{{grains.id}}\\\\' + '\\\\'.join(result[:-1]) + '\\\\'\n cmd = 'xcopy /y %s %s' %(name.encode('utf-8'),back)\n sls_data.append({'name': cmd})\n file_data = {'cmd.run': sls_data}\n sls_json['backup' + str(m)] = file_data\n m = m + 1\n\n # netusedelete\n sls_json['z_netdel'] = netuse_logout(backup_ip,netuse_disk)\n\n os.system('touch /srv/salt/%s/backup%s.sls' % (jobid, jobid))\n f = open('/srv/salt/%s/backup%s.sls' % (jobid, jobid), 'w')\n f.write(yaml.dump(sls_json))\n f.close()\n os.system('sed -i \\'s#{##g\\' /srv/salt/%s/backup%s.sls' % (jobid, jobid))\n os.system('sed -i \\'s#}##g\\' /srv/salt/%s/backup%s.sls' % (jobid, jobid))\n os.system('sed -i \\'s# -# -#g\\' /srv/salt/%s/backup%s.sls' % (jobid, jobid))\n os.system('sed -i \\'s#grains.id#{{grains.id}}#g\\' /srv/salt/%s/backup%s.sls' % (jobid, jobid))\n conf_sls = open('/srv/salt/%s/backup%s.sls' % (jobid, jobid), 'r')\n conf_view = conf_sls.readlines()\n conf_sls.close()\n result_conf = ''.join(conf_view)\n log_write = AutoupLog()\n log_write.autolog_write('warning', '生成备份配置文件,内容为%s' % result_conf, jobid)\n\n\n\n\n#生成回滚配置文件\ndef rollback_conf(data,jobid):\n a = MySqlconn()\n #sql = 'select b.filepath from dllout_server a,dllout_role b,dllout_product c where c.domainname = \\\"%s\\\" and b.ippid = c.id and a.id = b.serverid order by domainname'%data['publish_website']\n sql = 'select t1.app_path from opsapp_apps t1 \\\n INNER JOIN opsapp_appname t2 on t1.name_id=t2.id \\\n WHERE t2.name=\\'%s\\'' % data['publish_website']\n website_path = a.query(sql)[0]\n sls_json = {}\n\n # netuse认证\n sls_json['a_netuse'] = netuse_login(backup_ip, netuse_disk, username, password)\n\n m = 1\n for i in data['publish_contain'].split('
')[:-1]:\n\n result = i.split('/')\n del result[0]\n del result[0]\n name = website_path[0] + '\\\\'.join(result)\n\n if not result[:-1]:\n back = rollback_path + str(data['publish_id']) + '\\\\{{grains.id}}\\\\'\n else:\n back = rollback_path + str(data['publish_id']) + '\\\\{{grains.id}}\\\\' + '\\\\'.join(result[:-1]) + '\\\\'\n\n #创建回滚备份目录\n sls_mkdir = []\n movecmd = 'mkdir %s' % back\n sls_mkdir.append({'name': movecmd})\n back_mkdir = {'cmd.run': sls_mkdir}\n sls_json['back_mkdir' + str(m)] = back_mkdir\n\n #回滚前备份\n sls_data = []\n movecmd = 'move /y %s %s' %(name.encode('utf-8'),back)\n sls_data.append({'name': movecmd})\n file_data = {'cmd.run': sls_data}\n sls_json['delete_rollback' + str(m)] = file_data\n\n #回滚\n roll_data = []\n if not result[:-1]:\n backupname = backup_path + str(data['publish_id']) + '\\\\{{grains.id}}\\\\' + result[-1]\n else:\n backupname = backup_path + str(data['publish_id']) + '\\\\{{grains.id}}\\\\' + '\\\\'.join(result[:-1]) + '\\\\' + result[-1]\n rollback_realpath = '\\\\'.join(name.encode('utf-8').split('\\\\')[:-1]) + '\\\\'\n rollcmd = 'xcopy /y %s %s' % (backupname, rollback_realpath)\n #rollcmd = 'xcopy /y %s %s' %(backupname,name.encode('utf-8'))\n roll_data.append({'name': rollcmd})\n rollback_data = {'cmd.run': roll_data}\n sls_json['rollback' + str(m)] = rollback_data\n\n m = m + 1\n\n # netusedelete\n sls_json['z_netdel'] = netuse_logout(backup_ip, netuse_disk)\n\n os.system('touch /srv/salt/%s/rollback%s.sls' % (jobid, jobid))\n f = open('/srv/salt/%s/rollback%s.sls' % (jobid, jobid), 'w')\n f.write(yaml.dump(sls_json))\n f.close()\n os.system('sed -i \\'s#{##g\\' /srv/salt/%s/rollback%s.sls' % (jobid, jobid))\n os.system('sed -i \\'s#}##g\\' /srv/salt/%s/rollback%s.sls' % (jobid, jobid))\n os.system('sed -i \\'s# -# -#g\\' /srv/salt/%s/rollback%s.sls' % (jobid, jobid))\n os.system('sed -i \\'s#grains.id#{{grains.id}}#g\\' /srv/salt/%s/rollback%s.sls' % (jobid, jobid))\n conf_sls = open('/srv/salt/%s/rollback%s.sls' % (jobid, jobid), 'r')\n conf_view = conf_sls.readlines()\n conf_sls.close()\n result_conf = ''.join(conf_view)\n log_write = AutoupLog()\n log_write.autolog_write('warning', '生成回滚配置文件,内容为%s' % result_conf, jobid)\n\n\n\n#提交成功时生成校验的配置文件\ndef check_conf(data,jobid):\n a = MySqlconn()\n #sql = 'select b.filepath from dllout_server a,dllout_role b,dllout_product c where c.domainname = \\\"%s\\\" and b.ippid = c.id and a.id = b.serverid order by domainname'%data['publish_website']\n sql = 'select t1.app_path from opsapp_apps t1 \\\n INNER JOIN opsapp_appname t2 on t1.name_id=t2.id \\\n WHERE t2.name=\\'%s\\'' % data['publish_website']\n website_path = a.query(sql)[0]\n sls_json = {}\n m = 1\n for i in data['publish_contain'].split('
')[:-1]:\n sls_data = []\n result = i.split('/')\n del result[0]\n del result[0]\n\n name = website_path[0] + '\\\\'.join(result)\n powershell_cmd = ' Get-Date ([System.IO.FileInfo](\\'%s\\')).LastWriteTime -Format \\'MM/dd/yyyy HH:mm:ss\\' ' % (name.encode('utf-8'))\n sls_data.append({'name': powershell_cmd.encode('utf-8')})\n shellcmd = {'shell': 'powershell'}\n powershelltag = [shellcmd]\n sls_data.append({'kwarg': powershelltag})\n file_unzip_new = {'cmd.run': sls_data}\n sls_json[name.encode('utf-8')] = file_unzip_new\n\n\n #name = website_path[0] + '\\\\'.join(result)\n #sls_data.append({'name': name.encode('utf-8')})\n #source = 'salt://' + str(data['publish_id']) + i[1:]\n #sls_data.append({'source': source.encode('utf-8')})\n #sls_data.append({'makedirs': 'True'})\n #file_data = {'file.managed': sls_data}\n #sls_json['fileup' + str(m)] = file_data\n m = m + 1\n os.system('touch /srv/salt/%s/check%s.sls' % (jobid, jobid))\n f = open('/srv/salt/%s/check%s.sls' % (jobid, jobid), 'w')\n f.write(yaml.dump(sls_json))\n f.close()\n os.system('sed -i \\'s#{##g\\' /srv/salt/%s/check%s.sls' % (jobid, jobid))\n os.system('sed -i \\'s#}##g\\' /srv/salt/%s/check%s.sls' % (jobid, jobid))\n os.system('sed -i \\'s# -# -#g\\' /srv/salt/%s/check%s.sls' % (jobid, jobid))\n os.system('sed -i \\'s#- shell#shell#g\\' /srv/salt/%s/check%s.sls' % (jobid, jobid))\n os.system('sed -i \\'s#grains.id#{{grains.id}}#g\\' /srv/salt/%s/check%s.sls' % (jobid, jobid))\n conf_sls = open('/srv/salt/%s/check%s.sls' % (jobid, jobid), 'r')\n conf_view = conf_sls.readlines()\n conf_sls.close()\n result_conf = ''.join(conf_view)\n log_write = AutoupLog()\n log_write.autolog_write('warning', '生成更新的配置文件,内容为%s' % result_conf, jobid)\n\n\n#点击申请发布按钮后打开\n#该页面用来记录发布详情及选择发布文件\n#生成发布计划,获取发布id,生成发布路径(发布id目前用当前绝对时间定义/秒级)\ndef publish_filesearch(request):\n a = MySqlconn()\n if request.method == 'GET':\n project = request.GET.getlist('project_name')\n product = request.GET.get('product_name')\n productname = a.get_one_result('opsapp_appgroup',['name'],{'id':product},None,None,None)['name']\n role = request.GET.get('role')\n jobid = str(int(time.mktime(datetime.datetime.now().timetuple()))) + str(random.randint(1000,9999))\n os.mkdir(\"/srv/salt/%s\" % (str(jobid)))\n if request.GET.has_key('select'):\n return render_to_response('allup_dllhotfix/publish_filesearch.html',{'jobid':jobid,'project':','.join(project),'product':productname,'role':role})\n if request.GET.has_key('write'):\n return render_to_response('allup_dllhotfix/publish_filewrite.html',{'jobid': jobid, 'project': ','.join(project), 'product': productname,'role':role})\n\n#打开选择版本信息页面\n\ndef publish_versionsearch(request,jobid):\n\n b = MySqlconn()\n result = b.get_results('production_version',['production','production_version'],False,False,False,False)\n result_html=[]\n for i in result:\n result_str = '%s%s '%(i['production'],i['production_version'],i['production_version'],jobid)\n result_html.append(result_str)\n return render_to_response('allup_dllhotfix/publish_versionsearch.html',{'result':result_html})\n\n\ndef publish_versionfind(request,jobid):\n if request.method == 'GET':\n if request.GET.has_key('filefind'):\n rootpath = '/root/path/'\n version = request.GET.get('version','')\n filename = request.GET.get('filename','')\n if version == '' or filename == '':\n return HttpResponse('')\n version = version.strip()\n filename = filename.split()\n path = os.path.join(rootpath, version.split('-')[0],version,'%s.zip'%version)\n try:\n zfile = zipfile.ZipFile(path, 'r')\n except:\n return HttpResponse('')\n\n result = []\n\n for zipname in zfile.namelist():\n for i in filename:\n if i in zipname.decode('gbk').lower():\n result.append(zipname)\n elif i in zipname.decode('gbk'):\n result.append(zipname)\n else:\n continue\n return render_to_response('allup_dllhotfix/publish_findfileresult.html', {'info3': result, 'jobid': jobid,'path':path})\n\n else:\n return render_to_response('allup_dllhotfix/publish_versionfind.html',{'jobid': jobid})\n\ndef publish_versionall(request,jobid):\n b = MySqlconn()\n result = b.get_results('production_version',['production','production_version'],False,False,False,False)\n result_html=[]\n for i in result:\n result_str = '%s%s '%(i['production'],i['production_version'],i['production_version'],jobid)\n result_html.append(result_str)\n return render_to_response('allup_dllhotfix/publish_versionall.html',{'result':result_html})\n#\n\ndef publish_fileselect(request,path):\n a = path.split('$$')\n return render_to_response('allup_dllhotfix/publish_fileselect.html',{'path':a[0].strip(),'jobid':a[1].strip()})\n\n#模糊搜索文件名,生成文件选择页面\n\ndef publish_fileresult(request):\n if request.method == 'GET':\n path = request.GET.get('path','')\n jobid = request.GET.get('jobid','')\n b = MySqlconn()\n product = b.get_results('production_version',['production'],{'production_version':path},False,False,False)\n path1 = '/root/path/%s/%s/%s.zip'%(product[0]['production'],path,path)\n zfile = zipfile.ZipFile(path1,'r')\n filename = request.GET.get('filename','').split()\n result = []\n\n for zipname in zfile.namelist():\n for i in filename:\n if i in zipname.decode('gbk').lower():\n result.append(zipname)\n elif i in zipname.decode('gbk'):\n result.append(zipname)\n else:\n continue\n\n #cmd = '\\|'.join(filename.split())\n #result = os.popen('cd %s ;find |grep -i \\'%s\\''%(path1,cmd)).readlines()\n return render_to_response('allup_dllhotfix/publish_fileresult.html',{'info3':result,'jobid':jobid,'path':path1})\n\n\n\n#拷贝文件到指定目录\n\ndef publish_filecopy(request,funac):\n if request.method == 'GET':\n\n jobid = request.GET.get('jobid','')\n path = request.GET.get('path','')\n filename = request.GET.getlist('filename','')\n\n output_dir = '/srv/salt/%s'%jobid\n f = open(os.path.join(output_dir, 'jobid_version'),'a+')\n f.write(path.split('/')[-1] + '\\n')\n f.close()\n zfile = zipfile.ZipFile(path, 'r')\n\n\n if request.GET.get('auto',None) == 'auto':\n for zipname in zfile.namelist():\n for i in filename:\n if i == zipname.decode('gbk'):\n if '\\\\' in i:\n m = i.split('\\\\')\n destpath = os.path.join(output_dir, 'project','/'.join(m[0:-1]))\n\n zfile.extract(i, destpath)\n os.rename('%s/%s'%(destpath,i),'%s/%s'%(destpath,m[-1]))\n else:\n zfile.extract(i,os.path.join(output_dir, 'project'))\n #for i in filename:\n #cmd = 'cd %s;cp -p --parents %s /srv/salt/%s'%(path,i,jobid)\n #os.system(cmd)\n if request.GET.get('auto',None) == 'select':\n uppath = request.GET.get('uppath', '')\n\n destpath = os.path.join(output_dir, 'project' ,uppath)\n\n for zipname in zfile.namelist():\n for i in filename:\n if i == zipname.decode('gbk'):\n m = i.split('\\\\')\n zfile.extract(i, destpath)\n os.rename('%s/%s' % (destpath, i), '%s/%s' % (destpath, m[-1]))\n\n\n #for i in filename:\n #uppath = request.GET.get('uppath','')\n #tmppath = '/srv/salt/%s/%s/%s'%(jobid,i.split('/')[1],uppath)\n #os.system('mkdir -p %s'%tmppath)\n #cmd = 'cd %s;cp -p %s %s'%(path,i,tmppath)\n #os.system(cmd)\n if funac == 'select':\n return HttpResponseRedirect('/allup_dllhotfix/publish_versionsearch/%s'%jobid)\n elif funac == 'find':\n return HttpResponseRedirect('/allup_dllhotfix/publish_versionfind/%s' % jobid)\n else:\n return HttpResponseRedirect('/allup_dllhotfix/publish_versionsearch/%s' % jobid)\n\ndef publish_filename(request,jobid):\n result = os.popen('cd /srv/salt/%s/;find -type f |grep -v \\'jobid_version\\''%(jobid)).readlines()\n result_a = [{'a' + jobid:''.join(result).replace('\\n','
')}]\n rjson = json.dumps(result_a)\n response = HttpResponse()\n response['Content-Type'] = \"text/javascript\"\n response.write(rjson)\n return response\n\n","sub_path":"allup_dllhotfix/dllup_v2.py","file_name":"dllup_v2.py","file_ext":"py","file_size_in_byte":30759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"20838879","text":"import tkinter as tk\nfrom tkinter import *\n\nwindow=tk.Tk()\nwindow.geometry('575x200')\n\ndogp = PhotoImage(file='dog.png')\np=tk.Label(window,image=dogp)\n\n\nentry1=tk.Entry(window,width=17,borderwidth=1)\n\nentry2=tk.Entry(window,width=17,borderwidth=1)\n\nentry3=tk.Entry(window,width=17,borderwidth=1)\n\nentry4=tk.Entry(window,width=17,borderwidth=1)\n\nentry5=tk.Entry(window,width=17,borderwidth=1)\n\nname=tk.Label(window,text='Name')\n\ntyp=tk.Label(window,text='Type')\n\nbreed=tk.Label(window,text='Breed')\n\nowner=tk.Label(window,text='Owner')\n\nbirth=tk.Label(window,text='Birthdate')\n\ncldat=tk.Label(window,text='Client Database')\n\nsearch=tk.Button(window,text='Search by Name')\n\nsav=tk.Button(window,text='Save Entry',height=2,width=10)\n\npre=tk.Button(window,text='< Previous',height=1)\n\nnex=tk.Button(window,text='Next >',height=1)\n\nsearch2=tk.Entry(window,width=25)\n\n\np.grid(row=1,column=1)\n\ncldat.grid(row=1,column=3)\n\nname.grid(row=2,column=1)\n\ntyp.grid(row=2,column=2)\n\nbreed.grid(row=2,column=3)\n\nowner.grid(row=2,column=4)\n\nbirth.grid(row=2,column=5)\n\nentry1.grid(row=3,column=1)\n\nentry2.grid(row=3,column=2)\n\nentry3.grid(row=3,column=3)\n\nentry4.grid(row=3,column=4)\n\nentry5.grid(row=3,column=5)\n\npre.place(x=0,y=160)\n\nsav.place(x=250,y=150)\n\nnex.place(x=520,y=160)\n\nsearch.place(x=315,y=0)\n\nsearch2.place(x=415,y=5)\n\nwindow.mainloop()\n","sub_path":"task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"167793526","text":"#coding:utf-8\nimport os\nimport jieba #支持中文分词\nimport numpy as np\nfrom PIL import Image\nfrom os import path\nimport matplotlib.pyplot as plt\nfrom wordcloud import WordCloud,ImageColorGenerator,STOPWORDS\n\n#d=\"E:\\\\A_WORK\\\\wordcloud_study\\\\\"\nd = os.getcwd()\nabel_mask = np.array(Image.open(path.join(d,\"anne.png\")))\ntext_from_file_with_apath = open(path.join(d,'report.txt')).read()\n\nwordlist_after_jieba = jieba.cut(text_from_file_with_apath, cut_all = True)\nwl_space_split = \" \".join(wordlist_after_jieba)\n#my_wordcloud = WordCloud().generate(wl_space_split)\nmy_wordcloud = WordCloud(\n background_color='white', \n mask = abel_mask, \n max_words = 200, \n stopwords = STOPWORDS, \n font_path = path.join(d,'simhei.ttf'),\n max_font_size = 50,\n random_state = 30).generate(wl_space_split)\n\nimage_colors = ImageColorGenerator(abel_mask)\n#my_wordcloud.recolor(color_func=image_colors)\n\nplt.imshow(my_wordcloud, interpolation=\"bilinear\")\nplt.axis(\"off\")\n#plt.figure()\nplt.show()\n\n#写文件\nmy_wordcloud.to_file(path.join(d,\"result_c.jpg\"))\n","sub_path":"No6_Chinese.py","file_name":"No6_Chinese.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"139865231","text":"import requests\nimport sys\nimport json\nimport configure\nimport re\nimport argparse\n\nKEY = configure.APIKEY\nurl = 'http://www.omdbapi.com/'\n\ndef getmovieinfo(infos):\n\n\tmovieinfo = requests.get(infos)\n\tdataload = json.loads(movieinfo.text)\n\n\tdatadump = json.dumps(dataload, indent=0)\n\n\tshapedata = re.sub('\\n.\\n|\"|{|}|\\[|\\]', \"\", datadump)\n\tshapedata = re.sub(',\\n', \"\\n\", shapedata)\n\n\treturn shapedata\n\ndef main():\n\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('--title', nargs='+', help='Input movie title', required=True)\n\tparser.add_argument('--year',type=int, help='Specify released year')\n\targs = parser.parse_args()\n\n\tgettitle = '+'.join(args.title)\n\tgetinfo = ''.join([url, '?apikey=', KEY, '&t=', gettitle])\n\n\tif args.year:\n\t\tgetinfo_y = ''.join([url, '?apikey=', KEY, '&t=', gettitle, '&y={}'.format(args.year)])\n\t\ti = getmovieinfo(getinfo_y)\n\telse:\n\t\ti = getmovieinfo(getinfo)\n\n\tprint(i)\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"getinfo.py","file_name":"getinfo.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"620583792","text":"import socket\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ndef createsocket(PortMake,TCP_IP = socket.gethostname()): \n print(\"Attempting connection...\")\n createsocket.PortMake = PortMake\n createsocket.TCP_IP = TCP_IP\n try:\n s.bind((TCP_IP, PortMake))\n except error:\n print(\"Error \" + error)\n print(\"Socket Created On Port \" + str(PortMake))\ndef connectSocket(IP,PORT):\n s.connect((IP,PORT))\n","sub_path":"Python/PythonApplication1/PythonApplication1/ForConvSake.py","file_name":"ForConvSake.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"352030551","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nShell Generator\nCopyright (C) 2012-2013 Matthias Bolte \nCopyright (C) 2011-2013 Olaf Lüke \n\nshell_common.py: Common Library for generation of Shell bindings and documentation\n\nThis program is free software; you can redistribute it and/or\nmodify it under the terms of the GNU General Public License\nas published by the Free Software Foundation; either version 2\nof the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nGeneral Public License for more details.\n\nYou should have received a copy of the GNU General Public\nLicense along with this program; if not, write to the\nFree Software Foundation, Inc., 59 Temple Place - Suite 330,\nBoston, MA 02111-1307, USA.\n\"\"\"\n\nimport sys\nimport os\n\nsys.path.append(os.path.split(os.getcwd())[0])\nimport common\n\nclass ShellDevice(common.Device):\n def get_shell_class_name(self):\n return self.get_camel_case_name() + self.get_category()\n\n def get_shell_device_name(self):\n return self.get_dash_name() + '-' + self.get_category().lower()\n\nclass ShellPacket(common.Packet):\n def get_shell_parameter_list(self):\n params = []\n\n for element in self.get_elements('in'):\n params.append('<{0}>'.format(element.get_dash_name()))\n\n return ' '.join(params)\n\nclass ShellElement(common.Element):\n shell_types = {\n 'int8': 'int',\n 'uint8': 'int',\n 'int16': 'int',\n 'uint16': 'int',\n 'int32': 'int',\n 'uint32': 'int',\n 'int64': 'int',\n 'uint64': 'int',\n 'float': 'float',\n 'bool': 'bool',\n 'char': 'char',\n 'string': 'string'\n }\n\n shell_struct_formats = {\n 'int8': 'b',\n 'uint8': 'B',\n 'int16': 'h',\n 'uint16': 'H',\n 'int32': 'i',\n 'uint32': 'I',\n 'int64': 'q',\n 'uint64': 'Q',\n 'float': 'f',\n 'bool': '?',\n 'char': 'c',\n 'string': 's'\n }\n\n shell_type_converters = {\n 'int8': 'convert_int',\n 'uint8': 'convert_int',\n 'int16': 'convert_int',\n 'uint16': 'convert_int',\n 'int32': 'convert_int',\n 'uint32': 'convert_int',\n 'int64': 'convert_int',\n 'uint64': 'convert_int',\n 'float': 'float',\n 'bool': 'convert_bool',\n 'char': 'check_char',\n 'string': 'string'\n }\n\n def get_shell_type(self):\n t = ShellElement.shell_types[self.get_type()]\n\n if self.get_cardinality() == 1 or t == 'string':\n return t\n\n return ','.join([t]*self.get_cardinality())\n\n def get_shell_struct_format(self):\n f = ShellElement.shell_struct_formats[self.get_type()]\n c = self.get_cardinality()\n\n if c > 1:\n f = str(c) + f\n\n return f\n\n def get_shell_help(self):\n symbols_doc = ''\n\n if self.get_constant_group() is not None:\n symbols = []\n\n for constant_item in self.get_constant_group().get_items():\n symbols.append('{0}: {1}'.format(constant_item.get_dash_name(), constant_item.get_value()))\n\n symbols_doc = ' (' + ', '.join(symbols) + ')'\n\n t = ShellElement.shell_types[self.get_type()]\n\n if self.get_cardinality() == 1 or t == 'string':\n help = \"'{0}{1}'\".format(t, symbols_doc)\n else:\n help = \"get_array_type_name(ctx, '{0}', {1})\".format(t, self.get_cardinality())\n\n if len(symbols_doc) > 0:\n help += \"+ '{0}'\".format(symbols_doc)\n\n return help\n\n def get_shell_type_converter(self):\n t = ShellElement.shell_type_converters[self.get_type()]\n\n if self.get_constant_group() is not None:\n symbols = {}\n\n for constant_item in self.get_constant_group().get_items():\n symbols[constant_item.get_dash_name()] = constant_item.get_value()\n\n if self.get_cardinality() > 1 and t != 'string':\n return 'create_array_converter(ctx, create_symbol_converter(ctx, {0}, {1}), {2})'.format(t, symbols, self.get_cardinality())\n elif t == 'string':\n return 'create_string_checker(create_symbol_converter(ctx, str, {0}), {1})'.format(symbols, self.get_cardinality())\n else:\n return 'create_symbol_converter(ctx, {0}, {1})'.format(t, symbols)\n else:\n if self.get_cardinality() > 1 and t != 'string':\n return 'create_array_converter(ctx, {0}, {1})'.format(t, self.get_cardinality())\n elif t == 'string':\n return 'create_string_checker(str, {0})'.format(self.get_cardinality())\n else:\n return t\n","sub_path":"shell/shell_common.py","file_name":"shell_common.py","file_ext":"py","file_size_in_byte":4946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"408013644","text":"\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# import data\ndf = pd.read_csv('../../Results/Sobol_ST.txt', sep = ',', index_col = 0)\ndf = df.drop(['g1'], axis=1)\n\n# figure\nfig = df.plot(figsize = (8, 6))\nplt.xlim([0, 200])\nplt.ylim([0, 1])\nfig.tick_params(labelsize = 20)\nfig.set_xlabel(\"Days\", fontsize = 20)\nfig.set_ylabel(\"Sobol's total index\", fontsize = 20)\nplt.subplots_adjust(top = 0.95, bottom = 0.13)\nplt.tight_layout\nparas = ['$\\mathit{c}$', '$\\mathit{L}$', '$\\mathit{\\psi_{x50}}$', '$\\mathit{\\psi_s}$']\nplt.legend(paras)\n#plt.savefig('../Figures/Figure Sobol_day.png')\n","sub_path":"Figure_script/UMB/Figure_UMB_sobol_day.py","file_name":"Figure_UMB_sobol_day.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"600154564","text":"# -*- coding: utf-8 -*-\n#\n# main.py\n#\n\nimport web\n\nfrom msgpost.msgpost import *\n\n\nurls = ('/', 'index',\n '/add', 'add',\n '/del', 'delpost',\n '/post', 'post')\n\napp = web.application(urls, globals())\n\nrender = web.template.render(\"templates\", base=\"layout\")\n\ndb = web.database(dbn=\"mysql\", user=\"root\", pw=\"6934\", db=\"pony\")\n\nclass index:\n def GET(self):\n name = \"推送消息列表\"\n\n post_list = db.select(\"pushmsg\")\n \n return render.index(name, post_list)\n\nclass add:\n def GET(self):\n title = \"创建推送消息\"\n return render.add(title)\n\n def POST(self):\n i = web.input()\n n = db.insert(\"pushmsg\", title=i.title, content=i.content)\n\n title = i.title\n content = i.content\n\n if True == msg_post(title, content):\n print(\"push successful!!!\")\n\n else:\n print(\"push failed!!!\")\n\n return web.seeother(\"/\")\n\nclass delpost:\n def GET(self):\n print(web.input())\n\n i = web.input()\n\n post_id = i['post_id']\n\n db.delete('pushmsg', where=\"id=\" + post_id)\n \n return web.seeother(\"/\")\n\nclass post:\n def GET(self):\n return \"post message ....\"\n \nif __name__ == '__main__':\n web.config.debug = True\n app.run()\n","sub_path":"web/pony/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"231709882","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 ('transaksi', '0055_remove_permodalan_total_laba'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='permodalan',\n name='persentase',\n field=models.DecimalField(default=0, max_digits=20, decimal_places=2),\n ),\n ]\n","sub_path":"transaksi/migrations/0056_auto_20170914_1421.py","file_name":"0056_auto_20170914_1421.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"107001785","text":"import sys\nfrom os.path import isfile\nimport numpy as np\nimport json\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom matplotlib.patches import Circle\n\n\n\n\n# -----------------------------------------------------------------------------\nclass Missile(object):\n\n axes = None\n\n def __init__(self, name):\n self.x = self.y = self.z = None\n self.t = None\n \n self.vx = self.vy = self.vz = None\n self.v = None\n\n self.name = name\n\n self.annot_text_pos = [5000, 5000] if name == 'threat' else [-15000, 5000]\n\n # Draw object\n def draw(self, x, y):\n\n # Draw current location as empty circle\n self.pos_indicator = self.axes.scatter(x, y, \n marker='o', s=50,\n facecolors='none',\n edgecolors='black')\n \n # Annotation -- initialized when moving\n self.annot = None\n\n # Intercept position\n self.intercept = None\n\n # Initialize the trajectory line\n self.trajectory = self.axes.plot([], [])\n\n # Initialize the projected trajectory line\n self.projection = self.axes.plot([], [], linestyle='solid', color='black')\n\n\n # Update given x, y, z, t\n def update_xyzt(self, x, y, z, t):\n\n # Compute velocity\n if all(v is not None for v in [self.x, self.y, self.z, self.t]) and self.t > 0.0:\n timestep = float(t - self.t)\n self.vx = (x - self.x)/timestep\n self.vy = (y - self.y)/timestep\n self.vz = (z - self.z)/timestep\n self.v = np.sqrt(self.vx**2 + self.vy**2) # TODO only longitudinal\n\n # Update new position\n self.x = x\n self.y = y\n self.z = z\n self.t = t\n\n self.update_drawables()\n\n \n \n # Update direction towards target position (i.e. intercept position)\n def update_direction(self, pos_x, pos_y, pos_z, dt):\n\n # Unit vector towards target\n dist = np.sqrt((pos_x - self.x)**2 + (pos_y - self.y)**2 + (pos_z - self.z)**2)\n ux = (pos_x - self.x)/dist\n uy = (pos_y - self.y)/dist\n uz = (pos_z - self.z)/dist\n\n # Scale by velocity magnitude\n self.vx = ux * self.v\n self.vy = uy * self.v\n self.vz = uz * self.v\n\n # Make a step in position\n self.x = self.x + self.vx*dt\n self.y = self.y + self.vy*dt\n self.z = self.z + self.vz*dt\n\n self.update_drawables()\n\n \n def update_drawables(self):\n \n # Draw the current position\n self.pos_indicator.set_offsets([[self.x, self.y]])\n\n # Uptate annotation\n if self.v:\n self.annot = self.axes.annotate(\n s='x = %.0f\\ny = %.0f\\nz = %.0f\\nv = %.0f' % (\n self.x, self.y, self.z, self.v),\n xy=(self.x, self.y+1000),\n xycoords='data',\n xytext=(self.x + self.annot_text_pos[0], self.y + self.annot_text_pos[1]),\n arrowprops={'arrowstyle': '-'},\n transform=self.axes.transData)\n\n # Draw the present trajectory\n history = self.trajectory[0].get_data()\n if len(history[0]) == 0:\n updated_x = np.array([self.x])\n updated_y = np.array([self.y])\n else:\n updated_x = np.vstack((history[0], np.array([self.x])))\n updated_y = np.vstack((history[1], np.array([self.y])))\n self.trajectory[0].set_data(updated_x, updated_y)\n\n # Draw the projected trajectory\n if self.vx is not None and self.vy is not None:\n self.projection[0].set_data(\n [self.x, self.x+self.vx*4], [self.y, self.y+self.vy*4])\n\n\n def get_drawn_objects(self):\n objs = [self.pos_indicator]\n if self.trajectory:\n objs.append(self.trajectory)\n if self.projection:\n objs.append(self.projection)\n if self.annot:\n objs.append(self.annot)\n\n return objs\n\n\n\n \n# -----------------------------------------------------------------------------\nclass Command(object):\n\n def __init__(self, axes, vis_range, defence_range, pauser):\n \n self.axes = axes\n\n self._time = 0.0\n self._timestep = 0.0\n self.time_text = self.axes.annotate(\n 'time: %.1f s' % self._time,\n xy=(0.8, 0.9),\n xycoords='axes fraction',\n )\n\n self.visible_range = vis_range\n self.defence_range = defence_range\n\n self.visible_perimeter = None\n self.visible_perimeter_label = None\n self.defence_perimeter = None\n self.defence_perimeter_label = None\n\n self.threat_in_vis_range = False\n self.threat_in_defence_range = False\n self.intercept_within_defence_range = False\n\n self.intercept_pos = None\n self.intercept_indicator = None\n \n self.intercept_text = 'Intercept at:\\nx = -\\ny = -\\nz = -\\nt = -'\n self.intercept_text_label = self.axes.text(\n x=0.8, y=0.75,\n s=self.intercept_text,\n horizontalalignment='left',\n transform=self.axes.transAxes\n )\n\n # Commander may pause the simulation\n self.pauser = pauser\n\n \n @property\n def t(self):\n return self._time\n \n @t.setter\n def t(self, time):\n self._timestep = time - self._time\n self._time = time\n\n @property\n def dt(self):\n return self._timestep\n\n\n def compute_intercept(self, interceptor, target):\n \n def quad(a, b, c):\n solution = None\n if np.abs(a) < 1e-6:\n if np.abs(b) < 1e-6:\n if np.abs(c) < 1e-6:\n solution = [0, 0]\n else:\n return None # ?\n else:\n solution = [-c/b, -c/b]\n else:\n disc = b**2 - 4*a*c\n if disc >= 0:\n disc = np.sqrt(disc)\n a = 2*a\n solution = [(-b-disc)/a, (-b+disc)/a]\n \n return solution\n\n tx = target.x - interceptor.x\n ty = target.y - interceptor.y\n tz = target.z - interceptor.z\n tvx = target.vx\n tvy = target.vy\n tvz = target.vz\n\n a = tvx**2 + tvy**2 + tvz**2 - interceptor.v**2\n b = 2 * (tvx*tx + tvy*ty + tvz*tz)\n c = tx**2 + ty**2 + tz**2\n\n ts = quad(a, b, c)\n\n sol = None\n if ts:\n t0 = ts[0]\n t1 = ts[1]\n t = min(t0, t1)\n if t < 0:\n t = max(t0, t1)\n if t > 0:\n sol = [\n target.x + target.vx*t,\n target.y + target.vy*t,\n target.z + target.vz*t,\n t\n ]\n \n return sol\n\n\n def draw_visual_perimeter(self):\n\n color = 'green'\n\n self.visible_perimeter = Circle([0, 0],\n radius=self.visible_range,\n fill=False, color=color)\n self.axes.add_artist(self.visible_perimeter)\n\n self.visible_perimeter_label = self.axes.text(\n x=0.0, y=self.visible_range+1000,\n ha='center', color=color,\n s='Visible range')\n self.axes.add_artist(self.visible_perimeter_label)\n\n \n \n\n def draw_defence_perimeter(self):\n\n color = 'red'\n\n self.defence_perimeter = Circle([0, 0],\n self.defence_range,\n fill=False, color=color)\n self.axes.add_artist(self.defence_perimeter)\n \n self.defence_perimeter_label = self.axes.text(\n x=0.0, y=self.defence_range+1000,\n ha='center', color=color,\n s='Missile range')\n self.axes.add_artist(self.defence_perimeter_label)\n\n\n def get_drawn_objects(self):\n\n objs = [self.time_text]\n\n if self.visible_perimeter is not None:\n objs.append(self.visible_perimeter)\n if self.visible_perimeter_label is not None:\n objs.append(self.visible_perimeter_label)\n\n if self.defence_perimeter is not None:\n objs.append(self.defence_perimeter)\n if self.defence_perimeter_label is not None:\n objs.append(self.defence_perimeter_label)\n\n if self.intercept_indicator is not None:\n objs.append(self.intercept_indicator)\n if self.intercept_text_label is not None:\n objs.append(self.intercept_text_label)\n return objs\n\n\n def update(self, threat_missile, defence_missile):\n\n self.time_text.set_text('time: %.1f s' % self._time)\n \n # Check if threat within range\n threat_dist = np.sqrt(threat_missile.x**2 + threat_missile.y**2)\n \n if threat_dist <= self.visible_range:\n self.threat_in_vis_range = True\n if not self.visible_perimeter.get_fill():\n self.visible_perimeter.set_fill(True)\n self.visible_perimeter.set_alpha(0.1)\n \n # Compute intercept position\n if self.threat_in_vis_range:\n self.intercept_pos = self.compute_intercept(defence_missile, threat_missile)\n \n intercept_dist = np.sqrt(self.intercept_pos[0]**2 + self.intercept_pos[1]**2)\n if intercept_dist <= self.defence_range:\n if not self.intercept_within_defence_range: # Pause when launching\n self.pauser.pause()\n self.intercept_within_defence_range = True\n else:\n self.intercept_pos = None\n \n # Update intercept indicator\n if self.intercept_pos is not None:\n\n self.intercept_text = 'Intercept at:\\nx = %.0f\\ny = %.0f\\nz = %.1f\\nt = %.1f' % (\n self.intercept_pos[0], self.intercept_pos[1], self.intercept_pos[2], self.intercept_pos[3])\n self.intercept_text_label.set_text(self.intercept_text)\n\n\n # Draw indicator for the first time\n if self.intercept_indicator is None:\n \n self.intercept_indicator = self.axes.scatter(\n self.intercept_pos[0], self.intercept_pos[1], \n marker='x', s=50)\n\n # Pause the simulation if first time obtaining an intercept\n self.pauser.pause()\n\n # Update existing\n else:\n self.intercept_indicator.set_offsets([[\n self.intercept_pos[0],\n self.intercept_pos[1]]])\n \n\n \n # Delete the indicator if intercept disappeared\n else:\n if self.intercept_indicator is not None:\n self.intercept_indicator.set_offsets([[]])\n \n\n # Launch self-defence missile, or update its direction\n if self.intercept_pos is not None and self.intercept_within_defence_range:\n\n defence_missile.update_direction(\n self.intercept_pos[0],\n self.intercept_pos[1],\n self.intercept_pos[2],\n self.dt)\n\n # If missiles have met, end simulation\n if self.intercept_pos is not None:\n if self.intercept_pos[3] < 0.1:\n self.pauser.end()\n\n\n\n# -----------------------------------------------------------------------------\ndef read_trajectory(filename):\n\n data = []\n \n with open(filename) as fin:\n for line in fin:\n pos = [float(value) for value in line.split()]\n data.append(pos)\n \n #print('%s: read %d positions' % (filename, len(data)))\n return np.array(data)\n\n\n\n\n# -----------------------------------------------------------------------------\n# Simulation loop\ndef update(frame_num, objects, data, update_interval):\n\n\n # Update the threat position\n t, tr_x, tr_y, tr_z = data[frame_num]\n #print('t = %.1f: %.0f %.0f %.0f' % (t, tr_x, tr_y, tr_z), end='\\r')\n \n \n threat = objects['threat']\n defence = objects['defence']\n cmnd = objects['command']\n\n prev_t = threat.t if threat.t is not None else -999\n\n # Update command\n if t - prev_t >= update_interval: \n threat.update_xyzt(tr_x, tr_y, tr_z, t)\n cmnd.t = t\n cmnd.update(threat, defence)\n\n # Return all drawables\n drawables = []\n drawables += threat.get_drawn_objects()\n drawables += defence.get_drawn_objects()\n drawables += cmnd.get_drawn_objects()\n\n # Flatten a list of arbitrary number of lists\n def unnest(lst):\n new_list = []\n for elem in lst:\n if isinstance(elem, list):\n new_list += unnest(elem)\n else:\n new_list.append(elem)\n return new_list\n \n drawables = unnest(drawables)\n \n return drawables\n\n\n\n\n\n\n# -----------------------------------------------------------------------------\ndef run(filename):\n\n # Pause animation\n class Pause(object):\n\n def __init__(self):\n self.paused = False\n self.ended = False\n \n def pause(self):\n if not self.paused:\n simulation.event_source.stop()\n self.paused = True\n \n def unpause(self):\n if self.paused and not self.ended:\n simulation.event_source.start()\n self.paused = False\n \n def onclick(self, event):\n if self.paused:\n self.unpause()\n else:\n self.pause()\n \n def end(self):\n simulation.event_source.stop()\n self.ended = True\n\n \n p = Pause()\n\n # Read input\n threat_trajectory = read_trajectory(filename)\n threat_height = threat_trajectory[0, 3] # NOTE assuming it doesn't change\n\n # Get paramters \n with open('sim_params.json') as param_file:\n params = json.load(param_file)\n \n\n visual_range = 3570.0*(np.sqrt(params['radar_height'])\n + np.sqrt(threat_height))\n\n # Set up figure\n fig = plt.figure(figsize=(12,9))\n fig.subplots_adjust(left=0.1, right=0.99, top=0.99, bottom=0.1)\n\n ax = fig.gca()\n ax.set_xlim(params['plot']['xmin'], params['plot']['xmax'])\n ax.set_xlabel('X')\n ax.set_ylim(params['plot']['ymin'], params['plot']['ymax'])\n ax.set_ylabel('Y')\n plt.grid(which='major', linestyle='--')\n plt.grid(which='minor', linestyle='-')\n\n # Keep track of all drawn objects\n objs = {} # TODO rename\n\n # Set up the command central\n # Visible range depends on threat heigth, ignore this for now knowing that\n # it's always the same\n command = Command(ax,\n visual_range,\n params['selfdefence_missile']['range']*1852.0, # nm to m\n p)\n\n\n # Draw perimeters\n command.draw_visual_perimeter()\n command.draw_defence_perimeter()\n objs['command'] = command\n\n # Define target and self-defence missiles\n Missile.axes = ax\n\n threat = Missile('threat')\n threat.draw([], [])\n objs['threat'] = threat\n\n defence = Missile('self-defence')\n defence.x = defence.y = defence.z = 0.0\n defence.t = 0.0\n defence.v = params['selfdefence_missile']['speed']\n defence.draw([0], [0])\n objs['defence'] = defence\n\n # Pause simulation by clicking\n fig.canvas.mpl_connect('button_press_event', p.onclick)\n\n\n simulation = animation.FuncAnimation(fig, update, frames=len(threat_trajectory),\n fargs=(objs, threat_trajectory, params['animation']['update_interval']),\n interval=params['animation']['ms_between_frames'],\n repeat=False, blit=True)\n\n\n plt.show()\n\n\n\n# -----------------------------------------------------------------------------\nassert len(sys.argv) == 2, 'Wrong number of arguments (%d)' % len(sys.argv)\nassert isfile(sys.argv[1]), 'No such file: %s' % sys.argv[1]\nrun(sys.argv[1])","sub_path":"simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":15867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"333360277","text":"\n# begin importing of standard modules\nimport re\nimport random\nimport os\nimport tkinter as tk\nfrom tkinter import messagebox\nimport pandas as pd\nimport pprint as pp\nimport sys\n# end importing of standard modules\n\n# begin setting of home path variable and adding data directory to path import list\nif 'Step_1.ipynb' or 'Step_1.py' or 'Step_1.exe' in os.listdir():\n home = os.getcwd() \nsys.path.append(os.path.join(home, 'data')) #This will add the data folder to the path variable so modules can be imported \n# end setting of home path variable and adding data directory to path import list\n\n# begin creation Regular Expression that will check that a folder has been sanitized\nvalidHash = re.compile(r'#\\d{0,3}')\n# end creation Regular Expression that will check that a folder has been sanitized\n\n# begin import of created modules\ntry: \n import ds\n import mypath\n input('''Success!!!\n\ndata.csv in the data directory now contains the path to all the Core folders of students.\n\nPress any key to exit...''')\nexcept ModuleNotFoundError:\n input('''Before Step_2 can be run, Step_1 must be run to success first.\nThis will ensure that the needed python modules are created in the data directory!\n\nPlease run Step_1 till a success message is displayed, and then Step_2 again\n\nPress any key to exit...''')\n# begin import of created modules\n\n# begin recursive function defintion to find the Core path\ndef findDrivers2(filepath):\n# import ipdb; ipdb.set_trace()\n for i in os.listdir(filepath):\n newPath = os.path.join(filepath , i)\n if i in ['.git','.settings','Driver','Debug','.metadata']:\n pass\n elif i == 'Core':\n df.loc[df['hsh'] == validHash.findall(newPath)[0], ['CorePath']] = newPath\n elif os.path.isdir(newPath) == False:\n pass\n elif os.path.isdir(newPath) and i != 'Core': \n findDrivers2(newPath)\n# end recursive function defintion to find the Core path\n\n# begin importing and creation of a data frame\nos.chdir(mypath.data)\ndf = pd.read_csv('data.csv')\n# end importing and creation of a data frame\n\n# begin creation of the drivers path column in dataDrame\ndf['CorePath'] = 'Invalid Repository'\n# end creation of the drivers path column in dataDrame\n\n# begin going into each repo and identify the path to the Core folder per student\nos.chdir(mypath.repos)\nfilepath = mypath.repos\nfindDrivers2(filepath) #This is the recursive function that does the work\n# end going into each repo and identify the path to the Core folder per student\n\n# begin setting the dataframe to display well\npd.set_option('max_colwidth', 200)\n# end setting the dataframe to display well\n\n# begin saving the dataframe into the csv file again\nos.chdir(mypath.data)\ndf.to_csv('data.csv', index = False)\n# end saving the dataframe into the csv file again\n","sub_path":"Step_2.py","file_name":"Step_2.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"32400592","text":"\"\"\"\n__title__ = ''\n__author__ = 'Thompson'\n__mtime__ = '2019/1/10'\n# code is far away from bugs with the god animal protecting\n I love animals. They taste delicious.\n ┏┓ ┏┓\n ┏┛┻━━━┛┻┓\n ┃ ☃ ┃\n ┃ ┳┛ ┗┳ ┃\n ┃ ┻ ┃\n ┗━┓ ┏━┛\n ┃ ┗━━━┓\n ┃ 神兽保佑 ┣┓\n ┃ 永无BUG! ┏┛\n ┗┓┓┏━┳┓┏┛\n ┃┫┫ ┃┫┫\n ┗┻┛ ┗┻┛\n\"\"\"\n'''\n需求:\n知网爬虫:\n爬取作者,链接,标题,期刊等\n存储到mysql数据库中\n'''\n\nimport requests\nimport pymysql\nfrom lxml import etree\n\ndef get_html(url,para_data):\n headers ={\"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36\"}\n content = requests.get(url,params=para_data)\n return content\n\n\nif __name__ == \"__main__\":\n keyword =\"人工智能\" #要查找的关键字\n base_url = 'https://www.cn-ki.net'\n max_page = 2 #最大爬取的页数\n page = 1\n data = {\n 'keyword':keyword,\n 'db':'SCDB'\n }\n\n #链接数据库\n conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123456', db='dbcnki1809', charset='utf8')\n cursor = conn.cursor()\n\n content = get_html(base_url+'/search',data)\n\n while page<=max_page:\n print('page:',page)\n tree = etree.HTML(content.text)\n ls = tree.xpath('//div[@class=\"mdui-col-xs-12 mdui-col-md-9 mdui-typo\"]')\n print(len(ls))\n for item in ls:\n detail_url = item.xpath('./h3/a/@href')[0]\n detail_url = base_url + detail_url\n print('detail_url:',detail_url)\n con = get_html(detail_url,None).text\n h = etree.HTML(con)\n print('test:',con)\n print('test:', h.xpath('//span[@class=\"headline\"]/text()')[0])\n print('test:', h.xpath('//v-container[@class=\"body-1 grey--text text--darken-2\"]/v-layout/v-flex[2]/text()')[0].strip())\n\n title = item.xpath('./h3/a//text()')\n title = ''.join(title)\n print('title:',title)\n\n author = item.xpath('./div[1]/span[1]/text()')[0]\n print('author:',author)\n\n periodal= item.xpath('./div[1]/span[3]/text()')[0]\n print('periodal:',periodal)\n\n pub_date = item.xpath('./div[1]/span[4]/text()')[0]\n print('pub_date:',pub_date)\n\n type = item.xpath('./div[1]/span[5]/text()')[0]\n print('type:',type)\n\n summary = item.xpath('./div[@class=\"mdui-col-xs-12 mdui-typo\"]/p//text()')\n if len(summary)>0:\n summary = ''.join(summary)\n summary = summary.strip()\n else:\n summary = '空'\n print('summary:',summary)\n print('='*60)\n\n strsql='Insert into tb_cnki VALUES (0,%s,%s,%s,%s,%s,%s,%s)'\n parmams = [detail_url,title,author,periodal,pub_date,type,summary]\n cursor.execute(strsql,parmams)\n conn.commit()\n\n page+=1\n if page <= max_page:\n nextbtn=tree.xpath('//div[@class=\"mdui-col-xs-9 TitleLeftCell mdui-valign\"]/a[last()]')\n if len(nextbtn)>0:\n if nextbtn[0].text == '下一页':\n page_url = nextbtn[0].attrib['href']\n page_url = base_url +'/'+ page_url\n print(page_url)\n content = get_html(page_url,'')\n\n #关闭数据库\n cursor.close()\n conn.close()\n\n\n\n\n","sub_path":"20190110/案例:知网爬虫.py","file_name":"案例:知网爬虫.py","file_ext":"py","file_size_in_byte":3695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"400966996","text":"# 02-random-seed.py\n# written by montoyamoraga\n# runs with Python3\n# date: 2019-01-11\n\n# script that outputs three random numbers using a seed\n\n# import Python modules\n# random module documentation\n# https://docs.python.org/3.7/library/random.html\nimport random\n\n# set random seed\n# check what happens when you comment it out\n# random.seed() initializes the random number generator.\n# https://en.wikipedia.org/wiki/Random_seed\nrandom.seed(11)\n\n# declare three variables\n# and assign random numbers to them\n# use the random() function of the random module\n# random() returns the next random floating point number in the range [0.0, 1.0).\nnumber0 = random.random()\nnumber1 = random.random()\nnumber2 = random.random()\n\n# print numbers on the command-line\nprint(number0)\nprint(number1)\nprint(number2)\n","sub_path":"code/week1/02-random-seed.py","file_name":"02-random-seed.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"98782883","text":"from evalml.data_checks import DataCheck, DataCheckError, DataCheckMessageCode\nfrom evalml.utils.woodwork_utils import infer_feature_types\n\nerror_contains_nan = \"Input datetime column(s) ({}) contains NaN values. Please impute NaN values or drop these rows or columns.\"\n\n\nclass DateTimeNaNDataCheck(DataCheck):\n \"\"\"Checks each column in the input for datetime features and will issue an error if NaN values are present.\"\"\"\n\n def validate(self, X, y=None):\n \"\"\"Checks if any datetime columns contain NaN values.\n\n Arguments:\n X (pd.DataFrame, np.ndarray): Features.\n y (pd.Series, np.ndarray): Ignored. Defaults to None.\n\n Returns:\n dict: dict with a DataCheckError if NaN values are present in datetime columns.\n\n Example:\n >>> import pandas as pd\n >>> import woodwork as ww\n >>> import numpy as np\n >>> dates = np.arange(np.datetime64('2017-01-01'), np.datetime64('2017-01-08'))\n >>> dates[0] = np.datetime64('NaT')\n >>> df = pd.DataFrame(dates, columns=['index'])\n >>> df.ww.init()\n >>> dt_nan_check = DateTimeNaNDataCheck()\n >>> assert dt_nan_check.validate(df) == {\"warnings\": [],\n ... \"actions\": [],\n ... \"errors\": [DataCheckError(message='Input datetime column(s) (index) contains NaN values. Please impute NaN values or drop these rows or columns.',\n ... data_check_name=DateTimeNaNDataCheck.name,\n ... message_code=DataCheckMessageCode.DATETIME_HAS_NAN,\n ... details={\"columns\": 'index'}).to_dict()]}\n \"\"\"\n results = {\"warnings\": [], \"errors\": [], \"actions\": []}\n\n X = infer_feature_types(X)\n datetime_cols = X.ww.select(\"datetime\")\n nan_columns = datetime_cols.columns[datetime_cols.isna().any()].tolist()\n if len(nan_columns) > 0:\n nan_columns = [str(col) for col in nan_columns]\n cols_str = (\n \", \".join(nan_columns) if len(nan_columns) > 1 else nan_columns[0]\n )\n results[\"errors\"].append(\n DataCheckError(\n message=error_contains_nan.format(cols_str),\n data_check_name=self.name,\n message_code=DataCheckMessageCode.DATETIME_HAS_NAN,\n details={\"columns\": cols_str},\n ).to_dict()\n )\n return results\n","sub_path":"evalml/data_checks/datetime_nan_data_check.py","file_name":"datetime_nan_data_check.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"94590188","text":"# Copyright 2020 The Cirq Developers\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# https://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.\nimport dataclasses\nimport datetime\nfrom typing import Optional\nfrom google.protobuf import timestamp_pb2\nfrom cirq.google.engine.client.quantum import enums as qenums\nfrom cirq.google.engine.client.quantum import types as qtypes\n\n_DEFAULT_TYPE = qenums.QuantumTimeSlot.TimeSlotType.TIME_SLOT_TYPE_UNSPECIFIED\n\n\ndef _to_timestamp(dt: datetime.datetime):\n return timestamp_pb2.Timestamp(seconds=int(dt.timestamp()))\n\n\n@dataclasses.dataclass(frozen=True)\nclass EngineTimeSlot:\n \"\"\"A python wrapping of a Quantum Engine timeslot.\n\n Args:\n processor_id: The processor whose schedule the time slot exists on.\n start_time: starting datetime of the time slot, usually in local time.\n end_time: ending datetime of the time slot, usually in local time.\n slot_type: type of time slot (reservation, open swim, etc)\n project_id: Google Cloud Platform id of the project, as a string\n maintenance_title: If a MAINTENANCE period, a string title describing the\n type of maintenance being done.\n maintenance_description: If a MAINTENANCE period, a string describing the\n particulars of the maintenancethe title of the slot\n \"\"\"\n processor_id: str\n start_time: datetime.datetime\n end_time: datetime.datetime\n slot_type: qenums.QuantumTimeSlot.TimeSlotType = _DEFAULT_TYPE\n project_id: Optional[str] = None\n maintenance_title: Optional[str] = None\n maintenance_description: Optional[str] = None\n\n @classmethod\n def from_proto(cls, proto: qtypes.QuantumTimeSlot):\n slot_type = qenums.QuantumTimeSlot.TimeSlotType(proto.slot_type)\n if proto.HasField('reservation_config'):\n return cls(processor_id=proto.processor_name,\n start_time=datetime.datetime.fromtimestamp(\n proto.start_time.seconds),\n end_time=datetime.datetime.fromtimestamp(\n proto.end_time.seconds),\n slot_type=slot_type,\n project_id=proto.reservation_config.project_id)\n if proto.HasField('maintenance_config'):\n return cls(\n processor_id=proto.processor_name,\n start_time=datetime.datetime.fromtimestamp(\n proto.start_time.seconds),\n end_time=datetime.datetime.fromtimestamp(\n proto.end_time.seconds),\n slot_type=slot_type,\n maintenance_title=proto.maintenance_config.title,\n maintenance_description=proto.maintenance_config.description)\n return cls(processor_id=proto.processor_name,\n start_time=datetime.datetime.fromtimestamp(\n proto.start_time.seconds),\n end_time=datetime.datetime.fromtimestamp(\n proto.end_time.seconds),\n slot_type=slot_type)\n\n def to_proto(self):\n time_slot = qtypes.QuantumTimeSlot(\n processor_name=self.processor_id,\n start_time=_to_timestamp(self.start_time),\n end_time=_to_timestamp(self.end_time),\n slot_type=self.slot_type,\n )\n if self.project_id:\n time_slot.reservation_config.project_id = self.project_id\n config = time_slot.maintenance_config\n if self.maintenance_title:\n config.title = self.maintenance_title\n if self.maintenance_description:\n config.description = self.maintenance_description\n return time_slot\n","sub_path":"cirq/google/engine/engine_timeslot.py","file_name":"engine_timeslot.py","file_ext":"py","file_size_in_byte":4116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"574757248","text":"\n#####################################################################\n### Assignment skeleton\n### You can alter the below code to make your own dynamic website.\n### The landing page for assignment 3 should be at /\n#####################################################################\n\nfrom bottle import route, run,request, default_app,post, debug,static_file,template,get,redirect\nimport json\nfrom pymongo import MongoClient\nclient = MongoClient('mongodb://cashkl:deneme@itu-shard-00-00-h8wyf.mongodb.net:27017,itu-shard-00-01-h8wyf.mongodb.net:27017,itu-shard-00-02-h8wyf.mongodb.net:27017/test?ssl=true&replicaSet=itu-shard-0&authSource=admin&retryWrites=true')\n\n\n\n\n\n \n\ndef getAnonim(name):\n if(name==''):\n name='anonym'\n return name\ndef textAnonim(text):\n if text == '':\n text = 'This site is Superrrrrr'\n return text\ndef getInfo(info):\n print(info)\n if(info=='yes'):\n return '1'\n else:\n return '0'\n\n@route('/')\ndef static_file_callback(filepath):\n print(static_file(filepath, root='./static/'))\n return static_file(filepath, root='./static/')\n\n\n# @route('/')\ndef goToPage(page):\n print(page)\n db = client.testdb\n data = db.comments.find({}, {'_id': 0})\n if page=='index':\n data = db.comments.index.find({}, {'_id': 0})\n elif page=='galeri':\n data = db.comments.galeri.find({}, {'_id': 0})\n elif page=='albums':\n data = db.comments.albums.find({}, {'_id': 0}) \n elif page=='song-lyrics':\n data = db.comments.lyrics.find({}, {'_id': 0})\n\n if data: \n return template(page, comments=data)\n else: \n return template(page, comments=[])\n\n@route('/')\ndef getMainPage():\n return goToPage('index')\n\n@route('/index')\ndef getIndex():\n return goToPage('index')\n \n@route('/gallery')\ndef getIndex():\n\n return goToPage('galeri')\n\n@route('/albums')\ndef getIndex():\n\n return goToPage('albums')\n\n@route('/song-lyrics')\ndef getIndex():\n\n\n return goToPage('song-lyrics')\n\n\n@post('/commentToIndex/',method='POST')\ndef comment(page='index'):\n # console.log(\"post\")\n name = request.forms.get('name')\n surname = request.forms.get('surname')\n website = request.forms.get('domain')\n text=request.forms.get('comment')\n showInfo=request.forms.get('showInfo')\n data={}\n data['name']=getAnonim(name)\n data['surname']=getAnonim(surname)\n data['website']=getAnonim(website)\n data['text']=textAnonim(text)\n data['showInfo']=getInfo(showInfo)\n\n print('wlkwwerwek;wkltelkrtkertertertle' + data['showInfo'] + ' -->' )\n with client:\n if page=='index':\n db = client.testdb\n db.comments.index.insert_one(data)\n elif page=='gallery':\n db = client.testdb\n db.comments.galeri.insert_one(data)\n elif page=='albums':\n db = client.testdb\n db.comments.albums.insert_one(data) \n elif page=='song-lyrics':\n db = client.testdb\n db.comments.lyrics.insert_one(data)\n # print(page + ' is the index')\n \n return redirect('/'+page)\n\n#####################################################################\n### Don't alter the below code.\n### It allows this website to be hosted on Heroku\n### OR run on your computer.\n#####################################################################\n\n# This line makes bottle give nicer error messages\ndebug(True)\n# This line is necessary for running on Heroku\napp = default_app()\n# The below code is necessary for running this bottle app standalone on your computer.\nif __name__ == \"__main__\":\n run(reloader=True, port=8000,debug=True)\n\n","sub_path":"bottle_app.py","file_name":"bottle_app.py","file_ext":"py","file_size_in_byte":3689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"167127126","text":"'''\n@Author: Shihan Ran\n@Date: 2019-11-02 11:29:23\n@LastEditors: Shihan Ran\n@LastEditTime: 2019-11-10 16:34:23\n@Email: rshcaroline@gmail.com\n@Software: VSCode\n@License: Copyright(C), UCSD\n@Description: \n'''\n\nimport sys\nfrom collections import defaultdict\nimport math\nimport itertools\nimport string\n\n\ndef read_counts(counts_file, word_tag, word_dict, ngram_tag):\n for l in counts_file:\n line = l.strip().split(' ')\n if line[1] == 'WORDTAG':\n word_tag[(line[3], line[2])] = int(line[0])\n word_dict.append(line[3])\n else:\n ngram_tag[tuple(line[2:])] = int(line[0])\n\ndef efunc(word_tag, word_dict, ngram_tag, x, y):\n \"\"\"\n e(x|y) = p(x, y) / p(y)\n \"\"\"\n if x not in word_dict:\n # if all(c in string.punctuation for c in x):\n # x = '_ALL_PUNCTUATION_'\n # if all(c.isdigit() for c in x):\n # x = '_ALL_NUMERIC_'\n if any(c.isdigit() for c in x):\n x = '_CONTAIN_NUMERIC_'\n # if x.isupper():\n # x = '_ALL_CAP_'\n if x[0].isupper():\n x = '_FIRST_CAP_'\n if x[-1].isupper():\n x = '_LAST_CAP_'\n else:\n x = '_RARE_'\n return word_tag[(x, y)] / float(ngram_tag[(y,)])\n\ndef qfunc(ngram_tag, v, w, u, z):\n \"\"\"\n q(z|w, u, v)\n \"\"\"\n return ngram_tag[w, u, v, z] / float(ngram_tag[w, u, v])\n\ndef viterbi(word_tag, word_dict, ngram_tag, word_list):\n word_list = ['*', '*', '*'] + word_list\n tag_set = ('O', 'I-GENE')\n bp_dict = {}\n pi_dict = {(1, '*', '*', '*'): 1}\n \n # solve pi_dict and bp_dict\n for k in range(2, len(word_list)):\n u_set = tag_set\n v_set = tag_set\n w_set = tag_set\n z_set = tag_set\n if k == 2:\n v_set = ('*', )\n u_set = ('*', )\n w_set = ('*', )\n elif k == 3:\n u_set = ('*', )\n w_set = ('*', )\n elif k == 4:\n w_set = ('*', )\n \n # for different (u, v, z), find the optimal w\n for u, v, z in itertools.product(u_set, v_set, z_set):\n e = efunc(word_tag, word_dict, ngram_tag, word_list[k], z)\n candi_list = [((pi_dict[k - 1, w, u, v] * qfunc(ngram_tag, v, w, u, z) * e), w) for w in w_set]\n pi, bp = max(candi_list, key = lambda x: x[0])\n pi_dict[k, u, v, z] = pi\n bp_dict[k, u, v, z] = bp\n\n # 'STOP' is the last one\n uvz_list = [(pi_dict[len(word_list) - 1, u, v, z] * qfunc(ngram_tag, 'STOP', u, v, z), (u, v, z)) \\\n for (u, v, z) in itertools.product(tag_set, tag_set, tag_set)]\n \n tagn_1, tagn_2, tagn = max(uvz_list, key=lambda x:x[0])[1]\n tag_list = [0] * len(word_list)\n tag_list[-3] = tagn_1\n tag_list[-2] = tagn_2\n tag_list[-1] = tagn\n for i in reversed(range(len(tag_list) - 3)):\n tag_list[i] = bp_dict[i + 3, tag_list[i + 1], tag_list[i + 2], tag_list[i + 3]]\n return tag_list[3:]\n\ndef tag_gene(word_tag, word_dict, ngram_tag, out_f, dev_file):\n word_list = []\n for l in dev_file:\n line = l.strip()\n if line:\n word_list.append(line)\n else:\n tag_list = viterbi(word_tag, word_dict, ngram_tag, word_list)\n for word, tag in zip(word_list, tag_list):\n out_f.write(\"%s %s\\n\" % (word, tag))\n out_f.write('\\n')\n word_list = []\n\ndef usage():\n print (\"\"\"\n python baseline.py [input_train_counts] [input_dev_file] > [output_file]\n Read in counts file and dev file, produce tagging results.\n \"\"\")\n\n\nif __name__ == \"__main__\":\n\n # if len(sys.argv)!=4: # Expect exactly one argument: the training data file\n if len(sys.argv)!=3:\n usage()\n sys.exit(2)\n\n try:\n counts_file = open(sys.argv[1], \"r\")\n dev_file = open(sys.argv[2], 'r')\n # out_file = open(sys.argv[3], 'w')\n except IOError:\n sys.stderr.write(\"ERROR: Cannot read inputfile %s.\\n\" % arg)\n sys.exit(1)\n \n word_tag, ngram_tag = defaultdict(int), defaultdict(int)\n word_dict = []\n\n read_counts(counts_file, word_tag, word_dict, ngram_tag)\n counts_file.close()\n tag_gene(word_tag, word_dict, ngram_tag, sys.stdout, dev_file)\n # tag_gene(word_tag, word_dict, ngram_tag, out_file, dev_file)\n dev_file.close()","sub_path":"Assignment 3/P3_Extensions/p2/viterbi.py","file_name":"viterbi.py","file_ext":"py","file_size_in_byte":4319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"535405040","text":"from torch_lib.dataset_posenet import *\nfrom torch_lib.posenet import Model, OrientationLoss\nfrom torch_lib.mobilenetv3_old import MobileNetV3_Large\nfrom collections import OrderedDict\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torchvision.models import vgg, resnet, densenet, mobilenet\nfrom torch.utils import data\n\nfrom tensorboardX import SummaryWriter\n\nimport os\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\n# 获取mobilenetv_3的预训练模型参数。去掉'module'\ndef model_dict():\n model = torch.load(\"/home/lab/Desktop/wzndeep/posenet-build--eular/torch_lib/mbv3_large.old.pth.tar\", map_location='cpu')\n weight = model[\"state_dict\"]\n new_state_dict = OrderedDict()\n for k,v in weight.items():\n name = k[7:]\n new_state_dict[name] = v\n return new_state_dict\n\n\ndef main():\n\n # hyper parameters\n epochs = 200\n batch_size = 8\n w = 1\n alpha = 1\n\n print(\"Loading all detected objects in dataset...\")\n\n train_path = \"/media/lab/TOSHIBAEXT/BuildingData/training\"\n dataset = Dataset(train_path) # 自定义的数据集\n\n params = {\"batch_size\": batch_size, \"shuffle\": True, \"num_workers\": 6}\n\n generator = data.DataLoader(dataset, **params) # 读取Dataset中的数据\n\n base_model = mobilenet.mobilenet_v2(pretrained=True) # 加载模型并设置为预训练模式\n # base_model = MobileNetV3_Large()\n # state_dict = model_dict()\n # base_model.load_state_dict(state_dict)\n\n model = Model(features=base_model).cuda()\n\n # 选择不同的优化方法\n opt_Momentum = torch.optim.SGD(model.parameters(), lr = 0.0001, momentum = 0.9)\n opt_RMSprop = torch.optim.RMSprop(model.parameters(), lr = 0.0001, alpha = 0.9)\n opt_Adam = torch.optim.Adam(model.parameters(), lr = 0.0001, betas= (0.9, 0.99))\n opt_SGD = torch.optim.SGD(model.parameters(), lr=0.0001, momentum=0.9)\n\n conf_loss_func = nn.CrossEntropyLoss().cuda()\n orient_loss_func = OrientationLoss\n\n # load any previous weights\n model_path = (\"/home/lab/Desktop/wzndeep/posenet-build--eular/weights/\")\n latest_model = None\n first_epoch = 0\n if not os.path.isdir(model_path):\n os.mkdir(model_path)\n else:\n try:\n latest_model = [\n x for x in sorted(os.listdir(model_path)) if x.endswith(\".pkl\")\n ][-1]\n except:\n pass\n\n if latest_model is not None:\n # 解序列化一个pickled对象并加载到内存中\n checkpoint = torch.load(model_path + latest_model)\n # 加载一个state_dict对象,加载模型用于训练或验证\n model.load_state_dict(checkpoint[\"model_state_dict\"])\n opt_SGD.load_state_dict(checkpoint[\"optimizer_state_dict\"]) # 同上\n first_epoch = checkpoint[\"epoch\"]\n loss = checkpoint[\"loss\"]\n\n print(\"Found previous checkpoint: %s at epoch %s\" %\n (latest_model, first_epoch))\n print(\"Resuming training....\")\n\n # 训练网络\n\n total_num_batches = int(len(dataset) / batch_size)\n\n writer = SummaryWriter(\n \"/home/lab/Desktop/wzndeep/posenet-build--eular/runs/\")\n\n for epoch in range(first_epoch + 1, epochs + 1): # 多批次循环\n curr_batch = 0\n passes = 0\n for local_batch, local_labels in generator: # 获取输入数据\n\n truth_orient_patch = local_labels[\"Orientation_patch\"].float(\n ).cuda()\n truth_conf_patch = local_labels[\"Confidence_patch\"].long().cuda()\n truth_orient_yaw = local_labels[\"Orientation_yaw\"].float().cuda()\n truth_conf_yaw = local_labels[\"Confidence_yaw\"].long().cuda()\n\n local_batch = local_batch.float().cuda()\n [orient_patch, conf_patch, orient_yaw,\n conf_yaw] = model(local_batch)\n\n orient_patch_loss = orient_loss_func(orient_patch,\n truth_orient_patch,\n truth_conf_patch)\n\n # softmax函数的输出值进行操作,每行——>返回每行最大值的索引\n truth_conf_patch = torch.max(truth_conf_patch, dim=1)[1]\n conf_patch_loss = conf_loss_func(conf_patch, truth_conf_patch)\n\n loss_patch = conf_patch_loss + w * orient_patch_loss\n\n orient_yaw_loss = orient_loss_func(orient_yaw, truth_orient_yaw,\n truth_conf_yaw)\n\n # softmax函数的输出值进行操作,每行——>返回每行最大值的索引\n truth_conf_yaw = torch.max(truth_conf_yaw, dim=1)[1]\n conf_yaw_loss = conf_loss_func(conf_yaw, truth_conf_yaw)\n\n loss_yaw = conf_yaw_loss + w * orient_yaw_loss\n\n total_loss = alpha * loss_patch + loss_yaw\n\n opt_RMSprop.zero_grad() # 梯度置0\n total_loss.backward() # 反向传播\n opt_RMSprop.step() # 优化\n\n if passes % 10 == 0: # 10轮显示一次,打印状态信息\n print(\n \"--- epoch %s | batch %s/%s --- [loss_patch: %s] | [loss_yaw: %s] | [total_loss: %s]\"\n % (\n epoch,\n curr_batch,\n total_num_batches,\n loss_patch.item(),\n loss_yaw.item(),\n total_loss.item(),\n ))\n passes = 0\n\n passes += 1\n curr_batch += 1\n writer.add_scalar(\"loss_total\", total_loss, epoch)\n writer.add_scalar(\"loss_patch\", loss_patch, epoch)\n writer.add_scalar(\"orient_patch_loss\", orient_patch_loss, epoch)\n writer.add_scalar(\"conf_patch_loss\", conf_patch_loss, epoch)\n\n # save after every 10 epochs\n if epoch % 20 == 0:\n name = model_path + \"epoch_%s.pkl\" % epoch\n print(\"====================\")\n print(\"Done with epoch %s!\" % epoch)\n print(\"Saving weights as %s ...\" % name)\n torch.save(\n {\n \"epoch\": epoch,\n \"model_state_dict\": model.state_dict(),\n \"optimizer_state_dict\": opt_SGD.state_dict(),\n \"loss\": total_loss,\n },\n name,\n )\n print(\"====================\")\n\n writer.close()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"Train.py","file_name":"Train.py","file_ext":"py","file_size_in_byte":6471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"394678470","text":"class Data:\n def __init__(self, value):\n self.value = value\n self.next = None\n\n\nclass Queue:\n def __init__(self):\n self.head = None\n\n def push(self, value):\n if self.head is None:\n self.head = Data(value)\n else:\n q = Data(value)\n\n temp = self.head\n self.head = q\n self.head.next = temp\n\n def pop(self):\n if self.head is None:\n raise Exception('Stack is empty')\n\n elem = self.head\n prev_elem = None\n buf = None\n while elem is not None:\n if elem.next is None:\n buf = elem.value\n if prev_elem is not None:\n prev_elem.next = None\n else: # stack contain only one element ( head )\n self.head = None\n break\n\n prev_elem = elem\n elem = elem.next\n\n return buf\n\n def __str__(self):\n text = ''\n elem = self.head\n\n if elem is None:\n return ''\n\n while elem is not None:\n text += str(elem.value) + ' '\n elem = elem.next\n\n return text\n\n def __len__(self):\n if self.head is None:\n return 0\n\n elem = self.head\n count = 1\n\n while elem is not None:\n if elem.next is None:\n break\n count += 1\n elem = elem.next\n\n return count\n\n\nq = Queue()\n\nq.push(10)\nq.push(20)\nq.push(30)\n# s.push(4)\n# s.push(5)\n\nprint(f'stack: {q}')\nprint(f'stack len: {len(q)}')\ntry:\n print(f'stack pop: {q.pop()}')\n print(f'stack: {q}')\n print(f'stack len: {len(q)}')\n\n print(f'stack pop: {q.pop()}')\n print(f'stack: {q}')\n print(f'stack len: {len(q)}')\n\n print(f'stack pop: {q.pop()}')\n print(f'stack: {q}')\n print(f'stack len: {len(q)}')\n\n print(f'stack pop: {q.pop()}')\n print(f'stack: {q}')\n print(f'stack len: {len(q)}')\nexcept Exception as e:\n print(e)\n\n# print(s.pop())\n# print(s)","sub_path":"homework1/task_2.py","file_name":"task_2.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"495285747","text":"# amazonの漫画の売り上げランキングを表示するプログラム\n\n\nimport datetime, os, requests, bs4, sys\n\n\nclass Amazon:\n\n def makeWishList(self, ans):\n # ほしいものリストを作成する場合はrinfo 作成しない場合はinfo\n if ans.upper() == 'Y' or ans.upper() == 'YES':\n self.rinfo()\n elif ans.upper() == 'N' or ans.upper() == 'NO':\n self.info()\n else:\n print('Error')\n\n\n\n def editFile(self, book):\n # ほしいものリストを保存する場所\n today = datetime.date.today()\n fileName = str(today) + 'wish_list'\n os.makedirs(fileName, exist_ok=True)\n wish_file = open('{}/wishList.text'.format(fileName), 'a')\n wish_file.write(book)\n wish_file.close()\n\n\n\n def getURL(self):\n # ランキングは20個ずつ5ページあるため、それらのURLを取ってくる\n url = 'https://www.amazon.co.jp/gp/bestsellers/books/2501045051/ref=zg_bs_2501045051_pg_1?ie=UTF8&pg=1'\n html = requests.get(url)\n soup = bs4.BeautifulSoup(html.text, 'lxml')\n\n url_list = []\n\n p = 1\n for page in soup.find_all('li', class_='zg_page'):\n if p > 5:\n break\n else:\n page = page.find('a').get('href')\n url_list.append(page)\n p += 1\n return url_list\n\n\n\n\n def info(self):\n # ランキングの情報を取ってくる\n p = 1\n for page in self.getURL():\n url = page\n html = requests.get(url)\n soup = bs4.BeautifulSoup(html.text, 'lxml')\n\n if p >= 2:\n nextURL = input('次のランキングを表示しますか?(Y/N): ')\n if nextURL.upper() == 'N' or nextURL.upper() == 'NO':\n break\n\n\n for elem in soup.find_all('div', class_='zg_itemRow'):\n rank = elem.find('span', class_='zg_rankNumber').string.strip()\n name = elem.find_all('div', class_='p13n-sc-truncate')[0].string.strip()\n price = elem.find('span', class_='p13n-sc-price').string.strip()\n\n print('{} {} {}'.format(rank, price, name))\n p += 1\n\n\n\n def rinfo(self):\n # ランキングの情報を取ってきて、1つずつほしいものリストに追加するか問う\n p = 1\n for pages in self.getURL():\n url = pages\n html = requests.get(url)\n soup = bs4.BeautifulSoup(html.text, 'lxml')\n\n if p >= 2:\n nextURL = input('次のランキングを表示しますか?(Y/N): ')\n if nextURL.upper() == 'N' or nextURL.upper() == 'NO':\n break\n\n for elem in soup.find_all('div', class_='zg_itemRow'):\n rank = elem.find('span', class_='zg_rankNumber').string.strip()\n name = elem.find_all('div', class_='p13n-sc-truncate')[0].string.strip()\n price = elem.find('span', class_='p13n-sc-price').string.strip()\n goods = '{} {} {}'.format(rank, price, name)\n print(goods)\n p += 1\n check = input('この商品をリストに追加しますか?(Y/N): ')\n\n if check.upper() == 'Y' or check.upper() == 'YES':\n self.editFile(goods + '\\n')\n elif check.upper() == 'N' or check.upper() == 'NO':\n continue\n else:\n print('終了します')\n sys.exit()\n\n\nif __name__ == '__main__':\n user = Amazon()\n user.makeWishList(input('ほしいものリストを作成しますか?(Y/N): '))\n","sub_path":"amazon/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"408189977","text":"\"\"\"Add categories to Rules\n\nRevision ID: 10f16e5e360b\nRevises: 9a1191ea972d\nCreate Date: 2018-09-20 13:48:25.916761\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '10f16e5e360b'\ndown_revision = '9a1191ea972d'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('rule', sa.Column('category', sa.String(length=140), nullable=True))\n op.add_column('rule', sa.Column('sub_category', sa.String(length=140), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('rule', 'sub_category')\n op.drop_column('rule', 'category')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/10f16e5e360b_add_categories_to_rules.py","file_name":"10f16e5e360b_add_categories_to_rules.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"22669690","text":"#!/usr/bin/env python3\n\nfrom os import pipe, fdopen\nfrom threading import Thread\n\ndef main():\n def rdr(r):\n print(r.read())\n def wtr(w):\n w.write('a')\n w.close()\n r, w = pipe()\n r, w = fdopen(r, 'r'), fdopen(w, 'w')\n r, w = Thread(target=rdr, args=(r,)), Thread(target=wtr, args=(w,))\n r.start()\n w.start()\n r.join()\n w.join()\n\nif __name__ == '__main__':\n main()\n","sub_path":"deadlock-is-not-easy.py","file_name":"deadlock-is-not-easy.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"450604239","text":"# imported libraries\nimport urllib.request\nimport urllib.error\nfrom bs4 import BeautifulSoup\nimport math\nimport time\nimport xlsxwriter\n\n\n# Listing Class, Each object represents a single listing\nclass Listing:\n def __init__(self, number, url_listing, title):\n self.number = number\n self.url_listing = url_listing\n self.title = title\n\n def show_url(self):\n return self.url_listing\n\n def settitle(self, title):\n self.title = title\n\n def show_title(self):\n return self.title\n\n\n# Defines an empty list in order to fill with instances of \"Listing\"\nlistings = []\n\n\ndef run(page_number, total):\n print(\"Scraping Page # {} out of {}\".format(page_number + 1, total))\n\n # define a url\n quote_page = \"https://vancouver.craigslist.ca/search/cps?s={}\".format(page_number*120)\n\n # query and return html\n page = urllib.request.urlopen(quote_page)\n\n # parse the html and store in 'soup'\n soup = BeautifulSoup(page, 'html.parser')\n\n # Puts URL of all listings into 'url_listings'\n url_listings = [a['href'] for a in soup.findAll('a', attrs={'class': 'result-title'})]\n\n print(\"Creating Instances!\")\n # Creates instances of Listing and adds an URL\n for i in range(len(url_listings)):\n listings.append(Listing(i, url_listings[i], None))\n\n print(\"Finished creating instances!\")\n # Adds titles to each instance of Listing\n for i in range(len(listings)):\n quote_page = listings[i].url_listing\n\n # query and return html\n page = urllib.request.urlopen(quote_page)\n\n # parse the html and store in 'soup'\n soup = BeautifulSoup(page, 'html.parser')\n\n title_listing = soup.title.extract()\n title_listing = title_listing.string\n\n listings[i].settitle(title_listing)\n\n completion = (i+1) / len(listings)\n completion = math.ceil(completion * 100)\n print(\"{}% finished... ({} out of {})\".format(completion, (i+1), len(listings)))\n\n print(\"Finished!\")\n\n book = xlsxwriter.Workbook(\"page{}.xlsx\".format(page_number + 1))\n sheet = book.add_worksheet()\n bold = book.add_format({'bold': True})\n\n print(\"Dumping Data!\")\n for i in range(len(listings)):\n print(\"[Title]:{} [URL]:{}\".format(listings[i].show_title(), listings[i].show_url()))\n sheet.write(i, 0, listings[i].show_title())\n sheet.write(i, 6, listings[i].show_url())\n sheet.set_column(i, i, 10)\n\n\nprint(\"Craigslist Computer Services Web Scraper by Kevin Zhao\")\ntime.sleep(1)\nnumber_of_pages = int(input(\"How many pages would you like to scrape?\"))\nnumber_of_pages = number_of_pages - 1\n\nfor i in range(number_of_pages + 1):\n run(i, number_of_pages + 1)\n\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"214743435","text":"import FWCore.ParameterSet.Config as cms\n\n#-----------------\n#\tHCAL DQM Offline Source Sequence Definition for Cosmics\n#\tTo be used for Offline DQM importing\n#-----------------\n\n#\timport the tasks\nfrom DQM.HcalTasks.DigiTask import digiTask\nfrom DQM.HcalTasks.RawTask import rawTask\nfrom DQM.HcalTasks.TPTask import tpTask\nfrom DQM.HcalTasks.RecHitTask import recHitTask\n\n#\tset processing type to Offine\ndigiTask.ptype = cms.untracked.int32(1)\ntpTask.ptype = cms.untracked.int32(1)\nrecHitTask.ptype = cms.untracked.int32(1)\nrawTask.ptype = cms.untracked.int32(1)\n\n#\tset the run key(value and name)\ndigiTask.runkeyVal = cms.untracked.int32(2)\ntpTask.runkeyVal = cms.untracked.int32(2)\nrecHitTask.runkeyVal = cms.untracked.int32(2)\nrawTask.runkeyVal = cms.untracked.int32(2)\n\ndigiTask.runkeyName = cms.untracked.string(\"cosmic_run\")\ntpTask.runkeyName = cms.untracked.string(\"cosmic_run\")\nrecHitTask.runkeyName = cms.untracked.string(\"cosmic_run\")\nrawTask.runkeyName = cms.untracked.string(\"cosmic_run\")\n\n#\tset the Emulator label for TP Task\ntpTask.tagEmul = cms.untracked.InputTag(\"valHcalTriggerPrimitiveDigis\")\n\nhcalOfflineSourceSequence = cms.Sequence(\n\tdigiTask\n\t+recHitTask\n\t+rawTask)\n\n\n\n","sub_path":"DQM/HcalTasks/python/OfflineSourceSequence_cosmic.py","file_name":"OfflineSourceSequence_cosmic.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"327436401","text":"import copy\nimport json\nimport time\nfrom collections import defaultdict\nfrom datetime import timedelta\n\nfrom django.conf import settings\nfrom django.db import models\nfrom django.dispatch.dispatcher import receiver\nfrom django.utils import timezone\nfrom hearthstone.enums import BnetGameType, FormatType\nfrom redis_lock import Lock as RedisLock\nfrom redis_semaphore import Semaphore\nfrom sqlalchemy.sql import and_\n\nfrom hearthsim.identity.accounts.models import BlizzardAccount\nfrom hsredshift.analytics.scheduling import QueryRefreshPriority\nfrom hsreplaynet.utils import log\nfrom hsreplaynet.utils.aws import redshift\nfrom hsreplaynet.utils.aws.sqs import write_messages_to_queue\nfrom hsreplaynet.utils.influx import influx_metric\n\n\ndef execute_query(parameterized_query, run_local=False, priority=None):\n\tif run_local:\n\t\t# IMMEDIATE Will cause the query to get run synchronously\n\t\tlog.info(\"run_local async refresh for: %s\" % parameterized_query.cache_key)\n\t\tparameterized_query.schedule_refresh(\n\t\t\tpriority=QueryRefreshPriority.IMMEDIATE\n\t\t)\n\t\t# _do_execute_query_work(parameterized_query)\n\t\t# Uncomment to cut-over to async redshift queries\n\telse:\n\t\t# This will queue the query for refresh as resources are available\n\t\tlog.info(\"Scheduling refresh for: %s (priority=%s)\" % (\n\t\t\tparameterized_query.unload_key,\n\t\t\tpriority,\n\t\t))\n\t\tparameterized_query.schedule_refresh(\n\t\t\tpriority=priority,\n\t\t)\n\n\t# # It's safe to launch multiple attempts to execute for the same query\n\t# # Because the dogpile lock will only allow one to execute\n\t# # But we can save resources by not even launching the attempt\n\t# # If we see that the lock already exists\n\t# if not _lock_exists(parameterized_query.cache_key):\n\t# \tlog.info(\"No lock already exists for query. Will attempt to execute async.\")\n\t#\n\t# \tif settings.ENV_AWS and settings.PROCESS_REDSHIFT_QUERIES_VIA_LAMBDA:\n\t# \t\t# In PROD use Lambdas so the web-servers don't get overloaded\n\t# \t\tfrom hsreplaynet.utils.aws.clients import LAMBDA\n\t# \t\tLAMBDA.invoke(\n\t# \t\t\tFunctionName=\"execute_redshift_query\",\n\t# \t\t\tInvocationType=\"Event\", # Triggers asynchronous invocation\n\t# \t\t\tPayload=_to_lambda_payload(parameterized_query),\n\t# \t\t)\n\t# \telse:\n\t# \t\t_do_execute_query_work(parameterized_query)\n\t# else:\n\t# \tmsg = \"An async attempt to run this query is in-flight. Will not launch another.\"\n\t# \tlog.info(msg)\n\n\ndef _to_lambda_payload(parameterized_query):\n\tpayload = {\n\t\t\"query_name\": parameterized_query.query_name,\n\t\t\"supplied_parameters\": parameterized_query.supplied_parameters\n\t}\n\n\treturn json.dumps(payload)\n\n\ndef _do_execute_query(parameterized_query, wlm_queue=None):\n\t# This method should always be getting executed within a Lambda context\n\n\t# Distributed dog pile lock pattern\n\t# From: https://pypi.python.org/pypi/python-redis-lock\n\tlog.info(\"About to attempt acquiring lock...\")\n\tredis_client = redshift.get_redshift_cache_redis_client()\n\n\twith RedisLock(redis_client, parameterized_query.cache_key, expire=300):\n\t\t# Get a lock with a 5-minute lifetime since that's the maximum duration of a Lambda\n\t\t# to ensure the lock is held for as long as the Python process / Lambda is running.\n\t\tlog.info(\"Lock acquired.\")\n\t\treturn _do_execute_query_work(parameterized_query, wlm_queue)\n\n\ndef _do_execute_query_work(parameterized_query, wlm_queue=None):\n\tif not parameterized_query.result_is_stale:\n\t\tlog.info(\"Up-to-date cached data exists. Exiting without running query.\")\n\telse:\n\t\tlog.info(\"Cached data missing or stale. Executing query now.\")\n\t\t# DO EXPENSIVE WORK\n\t\tstart_ts = time.time()\n\t\texception_raised = False\n\t\texception_msg = None\n\t\ttry:\n\t\t\tparameterized_query.refresh_result(wlm_queue)\n\t\texcept Exception as e:\n\t\t\texception_raised = True\n\t\t\texception_msg = str(e)\n\t\t\traise\n\t\tfinally:\n\t\t\tend_ts = time.time()\n\t\t\tduration_seconds = round(end_ts - start_ts, 2)\n\n\t\t\tquery_execute_metric_fields = {\n\t\t\t\t\"duration_seconds\": duration_seconds,\n\t\t\t\t\"exception_message\": exception_msg\n\t\t\t}\n\t\t\tquery_execute_metric_fields.update(\n\t\t\t\tparameterized_query.supplied_non_filters_dict\n\t\t\t)\n\n\t\t\tinflux_metric(\n\t\t\t\t\"redshift_query_execute\",\n\t\t\t\tquery_execute_metric_fields,\n\t\t\t\texception_thrown=exception_raised,\n\t\t\t\tquery_name=parameterized_query.query_name,\n\t\t\t\t**parameterized_query.supplied_filters_dict\n\t\t\t)\n\n\ndef evict_locks_cache(params):\n\tredis_client = redshift.get_redshift_cache_redis_client()\n\tlock_signal_key = _get_lock_signal_key(params.cache_key)\n\tredis_client.delete(lock_signal_key)\n\n\ndef _get_lock_signal_key(cache_key):\n\treturn \"lock:%s\" % cache_key\n\n\ndef _lock_exists(cache_key):\n\tlock_signal_key = _get_lock_signal_key(cache_key)\n\tredis_client = redshift.get_redshift_cache_redis_client()\n\tlock_signal = redis_client.get(lock_signal_key)\n\treturn lock_signal is not None\n\n\nclass PremiumUserCacheWarmingContext:\n\tdef __init__(self, user, blizzard_account_map):\n\t\tself.user = user\n\t\tself.blizzard_account_map = blizzard_account_map\n\n\t@classmethod\n\tdef from_user(cls, user):\n\t\ttime_horizon = timezone.now() - timedelta(days=30)\n\t\tblizzard_accounts = list(user.blizzard_accounts.all())\n\t\tblizzard_account_deck_map = defaultdict(lambda: defaultdict(set))\n\t\tfor blizzard_account in blizzard_accounts:\n\t\t\t# Make sure this gets initialized if it exists\n\t\t\t# even when there are no games attached\n\t\t\tdeck_map_for_account = blizzard_account_deck_map[blizzard_account]\n\t\t\tggps = blizzard_account.globalgameplayer_set.select_related(\n\t\t\t\t\"game\", \"deck_list\"\n\t\t\t).filter(game__match_start__gte=time_horizon)\n\t\t\tfor ggp in ggps.all():\n\t\t\t\tdeck = ggp.deck_list\n\t\t\t\tif deck.size == 30:\n\t\t\t\t\tgame_type = ggp.game.game_type\n\t\t\t\t\tdeck_map_for_account[deck].add(game_type)\n\n\t\treturn PremiumUserCacheWarmingContext(user, blizzard_account_deck_map)\n\n\t@property\n\tdef blizzard_accounts(self):\n\t\treturn self.blizzard_account_map.keys()\n\n\tdef get_deck_map_for_account(self, account):\n\t\treturn self.blizzard_account_map[account]\n\n\ndef warm_redshift_cache_for_user_context(context):\n\t# This should be called whenever a user becomes premium\n\tfill_personalized_query_queue([context])\n\n\ndef fill_global_query_queue(eligible_queries=None, filter_fresh_queries=True):\n\tqueue_name = settings.REDSHIFT_ANALYTICS_QUERY_QUEUE_NAME\n\tmessages = get_queries_for_cache_warming(eligible_queries)\n\tlog.info(\"Generated %i global query permutations for cache warming.\" % len(messages))\n\tif filter_fresh_queries:\n\t\tmessages = filter_freshly_cached_queries(messages)\n\t\tmsg = \"%i permutations remain after filtering fresh queries\" % len(messages)\n\t\tlog.info(msg)\n\twrite_messages_to_queue(queue_name, messages)\n\n\ndef run_local_warm_queries(eligible_queries=None):\n\tmessages = get_queries_for_cache_warming(eligible_queries)\n\tlog.info(\"Generated %i global query permutations for cache warming.\" % len(messages))\n\tstale_queries = filter_freshly_cached_queries(messages)\n\tmsg = \"%i permutations remain after filtering fresh queries\" % len(stale_queries)\n\tlog.info(msg)\n\tfor msg in stale_queries:\n\t\tquery = redshift.get_redshift_query(msg[\"query_name\"])\n\t\tparameterized_query = query.build_full_params(msg[\"supplied_parameters\"])\n\t\texecute_query(parameterized_query, run_local=True)\n\n\n_eligible_decks_cache = {}\n\n\ndef _get_global_stats_eligible_decks():\n\tquery = redshift.get_redshift_query(\"list_decks_by_win_rate\")\n\tstandard_query = query.build_full_params(dict(\n\t\tTimeRange=\"LAST_30_DAYS\",\n\t\tGameType=\"RANKED_STANDARD\",\n\t))\n\twild_query = query.build_full_params(dict(\n\t\tTimeRange=\"LAST_30_DAYS\",\n\t\tGameType=\"RANKED_WILD\",\n\t))\n\n\tdigest_cache_missing = _eligible_decks_cache.get(\"eligible_decks\", None) is None\n\tstandard_as_of = _eligible_decks_cache.get(\"standard_as_of\", None)\n\tstandard_is_stale = standard_as_of != standard_query.result_as_of\n\twild_as_of = _eligible_decks_cache.get(\"wild_as_of\", None)\n\twild_is_stale = wild_as_of != wild_query.result_as_of\n\n\tif digest_cache_missing or standard_is_stale or wild_is_stale:\n\t\tresult = set()\n\t\tfor player_class, decks in standard_query.response_payload[\"series\"][\"data\"].items():\n\t\t\tfor deck in decks:\n\t\t\t\tresult.add(deck[\"digest\"])\n\t\tfor player_class, decks in wild_query.response_payload[\"series\"][\"data\"].items():\n\t\t\tfor deck in decks:\n\t\t\t\tresult.add(deck[\"digest\"])\n\t\t_eligible_decks_cache[\"standard_as_of\"] = standard_query.result_as_of\n\t\t_eligible_decks_cache[\"wild_as_of\"] = standard_query.result_as_of\n\t\t_eligible_decks_cache[\"eligible_decks\"] = result\n\n\treturn _eligible_decks_cache[\"eligible_decks\"]\n\n\ndef enable_premium_accounts_in_redshift(accounts):\n\tfrom hsredshift.etl.models import premium_account\n\tsession = redshift.get_new_redshift_session()\n\n\tfor account in accounts:\n\t\tsession.execute(premium_account.delete().where(and_(\n\t\t\tpremium_account.c.region == int(account.region),\n\t\t\tpremium_account.c.account_lo == account.account_lo,\n\t\t)))\n\n\t\tsession.execute(premium_account.insert().values({\n\t\t\t\"region\": int(account.region),\n\t\t\t\"account_lo\": account.account_lo,\n\t\t\t\"user_id\": account.user_id,\n\t\t\t\"as_of\": timezone.now(),\n\t\t\t\"active\": True,\n\t\t}))\n\n\tsession.commit()\n\tsession.close()\n\n\ndef enable_premium_accounts_for_users_in_redshift(users):\n\taccounts = []\n\tfor user in users:\n\t\taccounts.extend(user.blizzard_accounts.all())\n\tenable_premium_accounts_in_redshift(accounts)\n\n\ndef enable_all_premium_users_in_redshift():\n\tfrom djpaypal.models import BillingAgreement\n\tfrom djstripe.models import Subscription\n\n\tusers = set()\n\n\tfor subscription in Subscription.objects.active():\n\t\tusers.add(subscription.customer.subscriber)\n\n\tfor agreement in BillingAgreement.objects.filter(state=\"Active\"):\n\t\tusers.add(agreement.user)\n\n\tenable_premium_accounts_for_users_in_redshift(users)\n\n\n@receiver(models.signals.post_save, sender=BlizzardAccount)\ndef sync_blizzard_account_to_redshift(sender, instance, **kwargs):\n\tif instance.user and instance.user.is_premium:\n\t\tenable_premium_accounts_in_redshift([instance])\n\n\ndef fill_personalized_query_queue(contexts, eligible_queries=None):\n\tqueue_name = settings.REDSHIFT_ANALYTICS_QUERY_QUEUE_NAME\n\tmessages = get_personalized_queries_for_cache_warming(\n\t\tcontexts,\n\t\teligible_queries\n\t)\n\tlog.info(\"Generated %i personalized permutations for cache warming.\" % len(messages))\n\tstale_queries = filter_freshly_cached_queries(messages)\n\tmsg = \"%i personalized perms remain after filtering fresh queries\" % len(stale_queries)\n\tlog.info(msg)\n\twrite_messages_to_queue(queue_name, stale_queries)\n\n\ndef _permutation_matches_game_types(perm, game_types):\n\tgt = perm.get(\"GameType\", None)\n\tis_w = gt == \"RANKED_WILD\" and BnetGameType.BGT_RANKED_WILD in game_types\n\tis_s = gt == \"RANKED_STANDARD\" and BnetGameType.BGT_RANKED_STANDARD in game_types\n\treturn is_w or is_s\n\n\ndef get_personalized_queries_for_cache_warming(\n\tcontexts,\n\teligible_queries=None,\n\tcatalogue=None\n):\n\tredshift_catalogue = catalogue if catalogue else redshift.get_redshift_catalogue()\n\tqueries = []\n\tfor query in redshift_catalogue.personalized_queries:\n\t\tis_eligible = eligible_queries is None or query.name in eligible_queries\n\n\t\tif query.cache_warming_enabled and is_eligible:\n\t\t\tfor permutation in query.generate_personalized_parameter_permutation_bases():\n\t\t\t\t# Each permutation will still be missing a Region and account_lo value\n\t\t\t\tfor ctx in contexts:\n\t\t\t\t\tfor blizzard_account in ctx.blizzard_accounts:\n\t\t\t\t\t\tnew_permutation = copy.copy(permutation)\n\t\t\t\t\t\tnew_permutation[\"Region\"] = blizzard_account.region.name\n\t\t\t\t\t\tnew_permutation[\"account_lo\"] = blizzard_account.account_lo\n\t\t\t\t\t\tif \"deck_id\" in query.get_available_non_filter_parameters():\n\t\t\t\t\t\t\tdeck_map_for_account = ctx.get_deck_map_for_account(blizzard_account)\n\n\t\t\t\t\t\t\tfor deck, gts in deck_map_for_account.items():\n\t\t\t\t\t\t\t\tif _permutation_matches_game_types(new_permutation, gts):\n\t\t\t\t\t\t\t\t\tnew_permutation_for_deck = copy.copy(new_permutation)\n\t\t\t\t\t\t\t\t\tnew_permutation_for_deck[\"deck_id\"] = deck.id\n\t\t\t\t\t\t\t\t\tlog.info(\"Warming: %s: %s\", new_permutation_for_deck, query.name)\n\t\t\t\t\t\t\t\t\tqueries.append({\n\t\t\t\t\t\t\t\t\t\t\"query_name\": query.name,\n\t\t\t\t\t\t\t\t\t\t\"supplied_parameters\": new_permutation_for_deck,\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tlog.info(\"Warming: %s: %s\", new_permutation, query.name)\n\t\t\t\t\t\t\tqueries.append({\n\t\t\t\t\t\t\t\t\"query_name\": query.name,\n\t\t\t\t\t\t\t\t\"supplied_parameters\": new_permutation\n\t\t\t\t\t\t\t})\n\n\treturn queries\n\n\ndef filter_freshly_cached_queries(messages):\n\tif not settings.ENV_AWS:\n\t\t# We can only reach the cache from inside AWS\n\t\t# So we cannot take advantage of this optimization outside AWS\n\t\t# Skipping filtering is okay as up-to-date queries will still\n\t\t# get skipped at query execution time\n\t\treturn messages\n\n\tresult = []\n\tfor msg in messages:\n\t\tquery = redshift.get_redshift_query(msg[\"query_name\"])\n\t\tparameterized_query = query.build_full_params(msg[\"supplied_parameters\"])\n\n\t\tif not parameterized_query.result_available or parameterized_query.result_is_stale:\n\t\t\t# Keep this message because the cache is stale\n\t\t\tresult.append(msg)\n\n\treturn result\n\n\ndef get_queries_for_cache_warming(eligible_queries=None):\n\tqueries = []\n\tfor query in redshift.get_redshift_catalogue().cache_warm_eligible_queries:\n\t\tis_eligible = eligible_queries is None or query.name in eligible_queries\n\t\tif is_eligible:\n\t\t\tfor permutation in query.generate_cachable_parameter_permutations():\n\t\t\t\tqueries.append({\n\t\t\t\t\t\"query_name\": query.name,\n\t\t\t\t\t\"supplied_parameters\": permutation\n\t\t\t\t})\n\treturn queries\n\n\ndef get_concurrent_redshift_query_queue_semaphore(queue_name):\n\tconcurrency = settings.REDSHIFT_QUERY_QUEUES[queue_name][\"concurrency\"]\n\tconcurrent_redshift_query_semaphore = Semaphore(\n\t\tredshift.get_redshift_cache_redis_client(),\n\t\tcount=concurrency,\n\t\tnamespace=queue_name,\n\t\tstale_client_timeout=300,\n\t\tblocking=False\n\t)\n\treturn concurrent_redshift_query_semaphore\n\n\ndef attempt_request_triggered_query_execution(\n\tparameterized_query,\n\trun_local=False,\n\tpriority=None\n):\n\tdo_personal = settings.REDSHIFT_TRIGGER_PERSONALIZED_DATA_REFRESHES_FROM_QUERY_REQUESTS\n\tif run_local or settings.REDSHIFT_TRIGGER_CACHE_REFRESHES_FROM_QUERY_REQUESTS:\n\t\texecute_query(parameterized_query, run_local, priority)\n\telif do_personal and parameterized_query.is_personalized:\n\t\texecute_query(parameterized_query, run_local, priority)\n\telse:\n\t\tlog.debug(\"Triggering query from web app is disabled\")\n\n\ndef get_cluster_set_data(\n\tgame_format=FormatType.FT_STANDARD,\n\tlookback=7,\n\tmin_observations=100,\n\tmin_pilots=10,\n\tblock=True\n):\n\tfrom hsreplaynet.utils.aws.redshift import get_redshift_query\n\n\tgt = \"RANKED_STANDARD\" if game_format == FormatType.FT_STANDARD else \"RANKED_WILD\"\n\tquery = get_redshift_query(\"list_cluster_set_data\")\n\ttime_range_val = \"LAST_%i_DAY\" % lookback\n\tif lookback > 1:\n\t\ttime_range_val += \"S\"\n\n\tparameterized_query = query.build_full_params(dict(\n\t\tTimeRange=time_range_val,\n\t\tmin_games=min_observations,\n\t\tmin_pilots=min_pilots,\n\t\tGameType=gt,\n\t))\n\n\tif not parameterized_query.result_available or parameterized_query.result_is_stale:\n\t\tif block:\n\t\t\tattempt_request_triggered_query_execution(parameterized_query, run_local=True)\n\t\t\tsleep_counter = 0\n\t\t\tMAX_SLEEP = 120\n\t\t\twhile not parameterized_query.result_available:\n\t\t\t\tif sleep_counter >= MAX_SLEEP:\n\t\t\t\t\traise RuntimeError(\n\t\t\t\t\t\t\"Waited %i seconds, clustering data not available\" % MAX_SLEEP\n\t\t\t\t\t)\n\t\t\t\ttime.sleep(1)\n\t\t\t\tsleep_counter += 1\n\n\t\telse:\n\t\t\tattempt_request_triggered_query_execution(parameterized_query)\n\t\t\treturn []\n\n\treturn parameterized_query.response_payload\n","sub_path":"hsreplaynet/analytics/processing.py","file_name":"processing.py","file_ext":"py","file_size_in_byte":15274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"212380176","text":"import os\nimport struct\nimport sys\nimport time\n\nfrom . import SCALE_2G\n\n# I/O Structures\nSTRUCT_OUT = struct.Struct(\">QBBBBBB\")\nSTRUCT_IN = struct.Struct(\">Qhhh\")\n\ndef writeAccelData(bus):\n write_file=True\n configAccel(ACCEL_FS_SEL_2G)\n start = time.time()\n file_time = int(start/600)*600\n f=open('%d.bin'%file_time,'ab')\n while write_file:\n f.write(\n STRUCT_OUT.pack(\n int(1000*time.time()),\n bus.read_byte_data(ADDR,reg.ACCEL_XOUT_H),\n bus.read_byte_data(ADDR,reg.ACCEL_XOUT_L),\n bus.read_byte_data(ADDR,reg.ACCEL_YOUT_H),\n bus.read_byte_data(ADDR,reg.ACCEL_YOUT_L),\n bus.read_byte_data(ADDR,reg.ACCEL_ZOUT_H),\n bus.read_byte_data(ADDR,reg.ACCEL_ZOUT_L)\n )\n )\n if time.time()-file_time>600:\n f.close();\n file_time = int(time.time()/600)*600\n f=open('%d.bin'%file_time,'ab')\n \n end = time.time()\n f.close()\n print((\"Wrote 1000 records in %f seconds\"%(end-start)))\n\ndef readAccelData(file_name = None, dir_name=\".\"):\n if file_name == None:\n file_time = int(time.time()/600)*600\n file_name = os.path.join(dir_name,'%d.bin'%file_time)\n\n f=open(file_name,'rb+')\n while True:\n record = f.read(STRUCT_IN.size)\n while len(record)0:\n record = record + rec\n if len(record)==0 and int(time.time()/600)*600 > file_time:\n f.close()\n file_time = int(time.time()/600)*600\n file_name = os.path.join(dir_name,'%d.bin'%file_time)\n f=None\n while f==None:\n try:\n f=open(file_name,'rb+')\n except IOError:\n time.sleep(0.1)\n pass\n\n t,x,y,z = STRUCT_IN.unpack(record)\n yield {'t':t,'x':x,'y':y,'z':z}\n","sub_path":"python/MPU9255/fileio.py","file_name":"fileio.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"161276676","text":"from os import path\nimport time\n\nimport yaml\n\nfrom kubernetes import client, config\n\n\ndef main():\n config.load_kube_config()\n\n with open(path.join(path.dirname(__file__), \"pocket-stat-daemonset.yaml\")) as f:\n # use safe load to disable warnings\n # https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation\n dep = yaml.safe_load(f)\n k8s_beta = client.AppsV1Api()\n resp = k8s_beta.create_namespaced_daemon_set(\n body=dep, namespace=\"default\")\n print(\"Daemonset created. status='%s'\" % str(resp.status))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"deploy/deploy_pocket_stat.py","file_name":"deploy_pocket_stat.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"592793016","text":"import requests \n\ntexto = input(\"Digite algo para ser buscado: \")\n\nURL = \"https://api.chucknorris.io/jokes/search?query={}\"\n\nresponse = requests.get(URL.format(texto))\n\nif response.status_code == 200:\n for e in response.json().get('result'):\n print(e.get('value'))\nelse:\n print(response.text)\n","sub_path":"aula01/api-env/exercicios/ex_2.py","file_name":"ex_2.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"640948094","text":"# app.py\nimport os\nimport boto3\nimport datetime\n\n\nfrom flask import Flask, jsonify, request\napp = Flask(__name__)\n\nUSERS_TABLE = os.environ.get('USERS_TABLE')\nBOOKS_TABLE = os.environ.get('BOOKS_TABLE')\nORDERS_TABLE = os.environ.get('ORDERS_TABLE')\n\nclient = boto3.client('dynamodb')\n\n\n@app.route(\"/\")\ndef hello():\n return \"Hello World!\"\n\n\n@app.route(\"/users/\")\ndef get_user(user_id):\n resp = client.get_item(\n TableName=USERS_TABLE,\n Key={\n 'userId': {'S': user_id}\n }\n )\n item = resp.get('Item')\n if not item:\n return jsonify({'error': 'User does not exist'}), 404\n\n return jsonify({\n 'userId': item.get('userId').get('S'),\n 'name': item.get('name').get('S')\n })\n\n\n@app.route(\"/users\", methods=[\"POST\"])\ndef create_user():\n user_id = request.json.get('userId')\n name = request.json.get('name')\n\n if not user_id or not name:\n return jsonify({'error': 'Please provide userId and name'}), 400\n\n print(\"user_id\", user_id)\n print(\"name\", name)\n print('Table name', USERS_TABLE)\n\n resp = client.put_item(\n TableName=USERS_TABLE,\n Item={\n 'userId': {'S': user_id},\n 'name': {'S': name}\n }\n )\n return jsonify({\n 'userId': user_id,\n 'name': name\n })\n\n\n@app.route(\"/books/\")\ndef get_book_info(book_name):\n resp = client.get_item(\n TableName=BOOKS_TABLE,\n Key={\n 'book_name': {'S': book_name}\n }\n )\n item = resp.get('Item')\n if not item:\n return jsonify({'error': 'Book does not exist'}), 404\n\n return jsonify({\n 'book_name': item.get('book_name').get('S'),\n 'pages': item.get('pages').get('N'),\n 'author': item.get('author').get('S'),\n 'price': item.get('price').get('N')\n })\n\n\n@app.route(\"/books\", methods=[\"POST\"])\ndef add_book():\n book_name = request.json.get('book_name')\n author = request.json.get('author')\n pages = request.json.get('pages')\n price = request.json.get('price')\n\n print(\"pages\", type(pages))\n print(\"price\", type(price))\n\n if not book_name or not author or not pages or not price:\n return jsonify({'error': 'Please provide book_name and author, '\n 'pages, price'}), 400\n resp = client.put_item(\n TableName=BOOKS_TABLE,\n Item={\n 'book_name': {'S': book_name},\n 'author': {'S': author},\n 'pages': {'N': str(pages)},\n 'price': {'N': str(price)}\n }\n )\n return jsonify({\n 'book_name': {'S': book_name},\n 'author': {'S': author},\n 'pages': {'N': str(pages)},\n 'price': {'N': str(price)}\n })\n\n\n@app.route(\"/orders/\")\ndef get_order_info(order_id):\n resp = client.get_item(\n TableName=ORDERS_TABLE,\n Key={\n 'orderId': {'S': order_id}\n }\n )\n item = resp.get('Item')\n if not item:\n return jsonify({'error': 'Book does not exist'}), 404\n\n return jsonify({\n 'book_name': item.get('book_name').get('S'),\n 'order_id': item.get('orderId').get('S'),\n 'UserId': item.get('userId').get('S'),\n 'order_date': item.get('order_date').get('S'),\n 'delivery_date': item.get('delivery_date').get('S')\n })\n\n\n@app.route(\"/orders\", methods=['POST'])\ndef order_books():\n book_name = request.json.get('book_name')\n userId = request.json.get('user_id')\n order_date = datetime.datetime.strftime(datetime.datetime.now(),\n '%m-%d-%Y:%H:%M:%S')\n order_id = userId + \"@\" + order_date\n delivery_date = request.json.get('delivery_date')\n\n if not book_name or not userId or not delivery_date:\n return jsonify({'error': 'Please provide book_name, user_id and '\n 'delivery_date'}), 400\n\n resp = client.put_item(\n TableName=ORDERS_TABLE,\n Item={\n 'book_name': {'S': book_name},\n 'userId': {'S': userId},\n 'order_date': {'S': order_date},\n 'orderId': {'S': order_id},\n 'delivery_date': {'S': delivery_date}\n }\n )\n\n return jsonify({\n 'book_name': {'S': book_name},\n 'userId': {'S': userId},\n 'order_date': {'S': order_date},\n 'orderId': {'S': order_id},\n 'delivery_date': {'S': delivery_date}\n })\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"502197860","text":"# -*- coding: utf-8 -*-\n# @project : just_to_eat\n# @file : 018_4Sum.py\n# @time : 2019-09-05\n\nfrom __future__ import annotations\n\n'''\n给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。\n\n注意:\n\n答案中不可以包含重复的四元组。\n\n示例:\n\n给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。\n\n满足要求的四元组集合为:\n[\n [-1, 0, 0, 1],\n [-2, -1, 1, 2],\n [-2, 0, 0, 2]\n]\n'''\n'''\nRuntime: 1496 ms, faster than 9.40% of Python3 online submissions for 4Sum.\nMemory Usage: 13.9 MB, less than 7.14% of Python3 online submissions for 4Sum.\n'''\n\nclass Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n if len(nums) < 4: return []\n nums.sort()\n result = []\n for index1, number1 in enumerate(nums[:-3]):\n for index2, number2 in enumerate(nums[index1+1:-2]):\n left = index2 + 1 + index1 + 1\n right = len(nums) - 1\n while left < right:\n if number1 + number2 + nums[left] + nums[right] == target:\n tmp = [number1, number2, nums[left], nums[right]]\n if tmp not in result:\n result.append(tmp)\n left+=1\n right-=1\n elif number1 + number2 + nums[left] + nums[right] > target:\n right-=1\n else:\n left+=1\n\n return result\n\nif __name__ == '__main__':\n Solution = Solution()\n result = Solution.fourSum([-3,-1,0,2,4,5], 1)\n print(result)","sub_path":"018_4Sum.py","file_name":"018_4Sum.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"54251881","text":"from django.contrib import admin\n\n# Register your models here.\nfrom .models import Notification\n\n\n# Register your models here.\nclass NotificationAdmin(admin.ModelAdmin):\n fields = ['department', 'seo', 'title', 'image', 'description', 'no_of_posts', 'start_date', 'end_date',\n 'last_payment_date', 'location', 'procedure', 'qualification', 'fee', 'age_limit', 'pay_scale',\n 'brochure', 'link'] # 'ad_link_desktop', 'ad_link_mobile'\n list_display = ['title', 'department', 'slug', 'end_date']\n\n\nadmin.site.register(Notification, NotificationAdmin)\n","sub_path":"notifications/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"245479717","text":"import numpy as np\nimport numpy.linalg as la\nimport sys\nimport utils\n\nimport scipy.stats as stat\n\ndef chisquare(data):\n n = sum(data.flatten())\n e = np.zeros(data.shape)\n for i in range(e.shape[0]):\n for j in range(e.shape[1]):\n e[i, j] = (sum(data[i,:].flatten()) * sum(data[:,j].flatten())) / n\n e = e.flatten()\n return stat.chisquare(data.flatten(), e.flatten())\n\nif __name__ == '__main__':\n data = np.array([[150, 40], [15, 3300]])\n sys.stdout.write('chisquare: ')\n print(chisquare(data))\n ","sub_path":"2017FA/CS412/HW/assignment_1/Question4.lbai5.py","file_name":"Question4.lbai5.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"471003029","text":"import collections\nimport json\nimport os\nimport sys\n\nfrom CNVRepeat import utilities\nfrom CNVRepeat.reference import Reference\nfrom CNVRepeat.utilities import get_key\n\n\nclass ClusterSettings(object):\n def __init__(self):\n self.cluster_type = \"local\"\n self.processes = utilities.cpu_count_physical()\n self.cluster_options = {}\n\n @staticmethod\n def deserialize(options_dict):\n settings = ClusterSettings()\n\n if \"processes\" in options_dict:\n settings.processes = options_dict[\"processes\"]\n if \"cluster_type\" in options_dict:\n settings.cluster_type = options_dict[\"cluster_type\"]\n if \"cluster_options\" in options_dict:\n settings.cluster_options = options_dict[\"cluster_options\"]\n\n return settings\n\n def serialize(self):\n return {\n \"processes\": self.processes,\n \"cluster_type\": self.cluster_type,\n \"cluster_options\": self.cluster_options\n }\n\n \nclass Options(object):\n def __init__(self, options_path, debug=False):\n self.options_path = options_path\n\n self.ref_fasta = None\n self.gtf = None\n self.bed = None\n self.bam = None\n self.fastq1 = None\n self.fastq2 = None\n self.repeat = None\n self.black = None\n self.binaries = {}\n self._reference = None\n self._constants = None\n self.output = None\n\n self.cluster_settings = ClusterSettings()\n\n self.debug = debug\n self.method = None \n self.random_dna_length = None\n self.random_dna_number = None\n\n def serialize(self, ):\n\n d = {\"ref_fasta\": self.ref_fasta,\n \"gtf\": self.gtf,\n \"bed\": self.bed,\n \"bam\": self.bam,\n \"fastq1\": self.fastq1,\n \"fastq2\": self.fastq2,\n \"repeat\": self.repeat,\n \"black\": self.black,\n \"output\": self.output,\n \"cluster_settings\": self.cluster_settings.serialize(),\n \"binaries\": self.binaries\n }\n\n return d\n\n @staticmethod\n def deserialize(options_dict, options_path):\n options = Options(options_path)\n options.ref_fasta = get_key(options_dict, \"ref_fasta\")\n options.gtf = get_key(options_dict, \"gtf\")\n options.bed = get_key(options_dict, \"bed\")\n options.bam = get_key(options_dict, \"bam\")\n options.fastq1 = get_key(options_dict, \"fastq1\")\n options.fastq2 = get_key(options_dict, \"fastq2\")\n options.repeat = get_key(options_dict, \"repeat\")\n options.black = get_key(options_dict, \"black\") \n options.binaries = get_key(options_dict, \"binaries\", dict, default={})\n options.output = get_key(options_dict, \"output\")\n\n if not os.path.exists(options.output):\n os.mkdir(options.output)\n\n options.cluster_settings = ClusterSettings.deserialize(\n options_dict.get(\"cluster_settings\", {}))\n\n return options\n\n @property\n def output_dir(self):\n return self.output \n \n @property\n def results_dir(self):\n return os.path.join(self.output_dir, \"results\")\n\n @property\n def working_dir(self):\n return os.path.join(self.output_dir, \"working\")\n\n @property\n def log_dir(self):\n return os.path.join(self.output_dir, \"logs\")\n\n @property\n def reference(self):\n if self._reference is None:\n self._reference = Reference(self.ref_fasta, self.debug)\n return self._reference\n\n def binary(self, name):\n \"\"\"\n Checks to see if a path has been specified for an external binary,\n otherwise just return the name of the binary to try running it\n if it's in $PATH\n \"\"\"\n \n bin_path = self.binaries.get(name, name)\n if utilities.which(bin_path) is None:\n raise utilities.BinaryNotFoundError(\n \"Failed to locate binary '{}'; please make sure it is in \".format(name) + \n \"your $PATH or add it to the configuration.json file\")\n return bin_path\n\n\n @property\n def debug(self):\n return self._debug\n \n @debug.setter\n def debug(self, mode=True):\n self._reference = None\n self._debug = mode\n\n def __str__(self):\n d = self.serialize()\n d[\"debug\"] = self.debug\n return json.dumps(d, sort_keys=True, indent=4)\n\n def __getstate__(self):\n \"\"\"\n allows pickling of Options instances, necessary for ipyparallel\n \"\"\"\n state = self.__dict__.copy()\n state[\"_reference\"] = None\n state[\"_constants\"] = None\n\n return state \n","sub_path":"src/CNVRepeat/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":4743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"370024761","text":"from util import Queue\n\ndef earliest_ancestor(ancestors, starting_node):\n # create a dictionary\n struct = {}\n\n # Loop through each pair in the ancestor list\n for pair in ancestors:\n # Parent is the first value of pair\n parent = pair[0]\n # Child is the second value of pair\n child = pair[1]\n\n # If Child is not in 'struct', add it\n if child not in struct:\n struct[child] = []\n\n # Then add the parents of each child to their list in the dict\n struct[child].append(parent)\n \n # Create a queue\n q = Queue()\n\n # Append the starting node \n q.enqueue([starting_node])\n\n # Set a default longest node to store the largest distance\n # index 0 and the last node - as it corresponds with the longest distance\n longest_node = [0,-1]\n\n # Check if the queue is empty\n while len(q) > 0:\n # pop the first path from the queue\n curr_path = q.popleft()\n\n # get the last node in the path \n last_node = curr_path[-1]\n\n # Check if the last node is in the dictionary\n if last_node not in struct:\n # if the curr_path is longer than the previous_path, that will be the new longest path\n if len(curr_path) > longest_node[0] and last_node > longest_node[1]:\n # store the new longest_node\n longest_node = [len(curr_path), last_node]\n \n # else, if the last_node does have parents\n else:\n # loop through each parent and queue up\n # a path from the current path to each parent\n for x in struct[last_node]:\n q.append(curr_path + [x])\n \n # if the longest_node is = starting_node, return -1 as the starting_node has no parents\n if longest_node[1] == starting_node:\n return -1\n\n # Else return the node furthest away, which is longest_node[1]\n else:\n return longest_node[1]\n\n\n","sub_path":"projects/ancestor/ancestor.py","file_name":"ancestor.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"164367083","text":"#-*-coding:utf-8-*-\nfrom bs4 import BeautifulSoup\nimport requests\nimport json\nimport time\n#下面这句库引入是在python2.x中\n#import MySQLdb\n#python3.x中的数据库库类引入\nimport pymysql\n#在python中可以注释掉下面三句\n'''import sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n'''\n#删掉了数据库连接的信息\nclass news_scrapy(object):\n def __init__(self):\n # 这里是真的懒得想英文.....而且一共没有几个栏目,不需要写爬虫\n self.__columnUrlDict = {\n '''\n \"zhongyaoxinwen\": \"https://www.xuexi.cn/98d5ae483720f701144e4dabf99a4a34/5957f69bffab66811b99940516ec8784.html\",\n \"zhongyaohuodong\": \"https://www.xuexi.cn/c06bf4acc7eef6ef0a560328938b5771/9a3668c13f6e303932b5e0e100fc248b.html\",\n \"zhongyaohuiyi\": \"https://www.xuexi.cn/89acb6d339cd09d5aaf0c2697b6a3278/9a3668c13f6e303932b5e0e100fc248b.html\",\n \"zhongyaojianghua\": \"https://www.xuexi.cn/588a4707f9db9606d832e51bfb3cea3b/9a3668c13f6e303932b5e0e100fc248b.html\",\n \"zhongyaowenzhang\": \"https://www.xuexi.cn/6db80fbc0859e5c06b81fd5d6d618749/9a3668c13f6e303932b5e0e100fc248b.html\",\n \"chuguofangwen\": \"https://www.xuexi.cn/2e5fc9557e56b14ececee0174deac67f/9a3668c13f6e303932b5e0e100fc248b.html\",\n \"zhishipishi\": \"https://www.xuexi.cn/682fd2c2ee5b0fa149e0ff11f8f13cea/9a3668c13f6e303932b5e0e100fc248b.html\",\n \"handianzhici\": \"https://www.xuexi.cn/13e9b085b05a257ed25359b0a7b869ff/9a3668c13f6e303932b5e0e100fc248b.html\",\n \"xinshidaijishi\": \"https://www.xuexi.cn/9ca612f28c9f86ad87d5daa34c588e00/9a3668c13f6e303932b5e0e100fc248b.html\",\n \"xuexishipin\": \"https://www.xuexi.cn/d05cad69216e688d304bb91ef3aac4c6/9a3668c13f6e303932b5e0e100fc248b.html\",\n \"zonghexinwen\": \"https://www.xuexi.cn/7097477a9643eacffe4cc101e4906fdb/9a3668c13f6e303932b5e0e100fc248b.html\",\n \"toutiaoxinwei\":\"https://www.xuexi.cn/72ac54163d26d6677a80b8e21a776cfa/9a3668c13f6e303932b5e0e100fc248b.html\"\n '''\n #学习重点\n \t\"xuexizhongdian\":\"https://www.xuexi.cn/72bead8d9b5821a270f4f2c043d1ef02/463634d0259f8d74722f42db51b659b5.html\",\n #学习新思想\n \"zhongyaoxinwen\":\"https://www.xuexi.cn/lgdata/1jscb6pu1n2.json?_st=26095725\",\n \"zhongyaohuodong\":\"https://www.xuexi.cn/lgdata/1jpuhp6fn73.json?_st=26095746\",\n \"zhongyaohuiyi\":\"https://www.xuexi.cn/lgdata/19vhj0omh73.json?_st=26095747\",\n \"zhongyaojianghua\":\"https://www.xuexi.cn/lgdata/132gdqo7l73.json?_st=26095749\",\n \"zhongyaowenzhang\":\"https://www.xuexi.cn/lgdata/1ahjpjgb4n3.json?_st=26095750\",\n \"chuguofangwen\":\"https://www.xuexi.cn/lgdata/1je1objnh73.json?_st=26095752\",\n \"zhishipishi\":\"https://www.xuexi.cn/lgdata/1kvrj9vvv73.json?_st=26095752\",\n \"handianzhici\":\"https://www.xuexi.cn/lgdata/17qonfb74n3.json?_st=26095753\",\n \"xinshidaijishi\":\"https://www.xuexi.cn/lgdata/1i30sdhg0n3.json?_st=26095754\",\n \"xuexishipin\":\"https://www.xuexi.cn/lgdata/1ap1igfgdn2.json?_st=26095755\",\n \"zonghexinwen\":\"https://www.xuexi.cn/lgdata/1ajhkle8l72.json?_st=26095756\",\n \"toutiaoxinwei\":\"https://www.xuexi.cn/lgdata/1crqb964p71.json?_st=26095757\",\n #十九大时间\n \"shijiudawenxian\":\"https://www.xuexi.cn/lgdata/11d24l914n4.json?_st=26095831\",\n \"shijiudabaogao\":\"https://www.xuexi.cn/lgdata/1a78j52k2n4.json?_st=26095832\",\n \"shijiujiezhongyangquanhui\":\"https://www.xuexi.cn/lgdata/1c7mgi6tg74.json?_st=26095835\",\n \"shijiujiezhongyangjiweiquanhui\":\"https://www.xuexi.cn/lgdata/1niulj5tbn4.json?_st=26095836\",\n \"yanshenyuedu\":\"https://www.xuexi.cn/lgdata/1nf12u57o74.json?_st=26096131\",\n \"niwenwoda\":\"https://www.xuexi.cn/lgdata/1jfhm81amn4.json?_st=26096132\",\n \"xueximianduimian\":\"https://www.xuexi.cn/lgdata/11gg7rev674.json?_st=26096133\",\n #学习理论\n \"xuexililun\":\"https://www.xuexi.cn/lgdata/u1ght1omn2.json?_st=26096137\",\n #红色中国\n \"yongyuandefengbei\":\"https://www.xuexi.cn/lgdata/1n544qrtv7c.json?_st=26096145\",\n #视频需要用视频爬虫去单独处理\n #\"shipinzhuanqu\":\"https://www.xuexi.cn/lgdata/3jsf4shrl928.json?_st=26096148\",\n ##红色中国-红色记忆\n \"changzhengjinianguan\":\"https://www.xuexi.cn/lgdata/u16ui97tnm.json?_st=26096163\",\n \"kangzhanjinianguan\":\"https://www.xuexi.cn/lgdata/1c0be8revnm.json?_st=26096164\",\n \"jiefangzhanzheng\":\"https://www.xuexi.cn/lgdata/1bh4bl63fnm.json?_st=26096164\",\n \"hongselvyou\":\"https://www.xuexi.cn/lgdata/181gpjpb4nm.json?_st=26096165\",\n \"hongselvyouluxian\":\"https://www.xuexi.cn/lgdata/1dil8gmtq7m.json?_st=26096166\",\n \"lijiedangdaihui\":\"https://www.xuexi.cn/lgdata/1of97bn6c7m.json?_st=26096168\",\n #红色中国-党史研究\n \"dangshigushi\":\"https://www.xuexi.cn/lgdata/1drkih7p27m.json?_st=26096167\",\n \"dangshizhishi\":\"https://www.xuexi.cn/lgdata/1k8ffl9m8nm.json?_st=26096170\",\n \"dangshiyanjiu\":\"https://www.xuexi.cn/lgdata/1ogogofuqnm.json?_st=26096170\",\n #红色中国-中国精神研究\n \"wusijingshen\":\"https://www.xuexi.cn/lgdata/1ibpde47i7l.json?_st=26096176\",\n \"hongchuanjingshen\":\"https://www.xuexi.cn/lgdata/ue2lvnpl7l.json?_st=26096176\",\n \"jinggangshanjingshen\":\"https://www.xuexi.cn/lgdata/uo3b9nde7l.json?_st=26096177\",\n \"changzhengjingshen\":\"https://www.xuexi.cn/lgdata/136cgvrgp7l.json?_st=26096178\",\n \"yananjingshen\":\"https://www.xuexi.cn/lgdata/1ebgr501e7l.json?_st=26096179\",\n \"taihangjingshen\":\"https://www.xuexi.cn/lgdata/10444suc57l.json?_st=26096179\",\n \"yimengjingshen\":\"https://www.xuexi.cn/lgdata/1nf7dv27p7l.json?_st=26096180\",\n \"xibaipojingshen\":\"https://www.xuexi.cn/lgdata/1gqebjagq7l.json?_st=26096181\",\n \"tierenjingshen\":\"https://www.xuexi.cn/lgdata/1ganajvkg7l.json?_st=26096181\",\n \"jiaoyulujingshen\":\"https://www.xuexi.cn/lgdata/16td1roi77l.json?_st=26096182\",\n \"liangdanyixingjingshen\":\"https://www.xuexi.cn/lgdata/17ictec57nl.json?_st=26096182\",\n \"hansaibajingshen\":\"https://www.xuexi.cn/lgdata/11fksd93o7l.json?_st=26096183\",\n \"gaigekaifangjingshen\":\"https://www.xuexi.cn/lgdata/2qvbqhmdrube.json?_st=26096184\",\n #学习科学\n \"kejisixiangyanjiu\":\"https://www.xuexi.cn/lgdata/1eppcq11fne.json?_st=26096190\",\n \"kexuejingshentan\":\"https://www.xuexi.cn/lgdata/1armpdlt5ne.json?_st=26096194\",\n \"guojiagongcheng\":\"https://www.xuexi.cn/lgdata/1moa0khf17e.json?_st=26096195\",\n \"5G\":\"https://www.xuexi.cn/lgdata/56j1nv2difvo.json?_st=26096196\",\n \"kejiqianyan\":\"https://www.xuexi.cn/lgdata/152ijthp37e.json?_st=26096196\",\n \"dangdaikexuejiagushi\":\"https://www.xuexi.cn/lgdata/11jihrmq37e.json?_st=26096198\",\n \"yixianfengcai\":\"https://www.xuexi.cn/lgdata/1cieuomejnn.json?_st=26096198\",\n \"zhengcejiedu\":\"https://www.xuexi.cn/lgdata/1lje05c9une.json?_st=26096200\",\n \"kepuzhishi\":\"https://www.xuexi.cn/lgdata/1drofao4h7e.json?_st=26096205\",\n \"zhongguokejishi\":\"https://www.xuexi.cn/lgdata/110jqimatnn.json?_st=26096206\",\n \"zhongguolidaikexuejia\":\"https://www.xuexi.cn/lgdata/153hr7eadnn.json?_st=26096206\",\n \"waiguokexuejia\":\"https://www.xuexi.cn/lgdata/14ddfon4e7n.json?_st=26096207\",\n \"shijiekejishi\":\"https://www.xuexi.cn/lgdata/14gko3bjk7n.json?_st=26096208\",\n #科学著作是pdf文本,爬到存数据库不好存,暂时去掉\n #\"kexuezhuzuo\":\"https://www.xuexi.cn/lgdata/u6i3lnss7e.json?_st=26096210\",\n \"xinlifudao\":\"https://www.xuexi.cn/lgdata/1h4s6pojfne.json?_st=26096211\",\n #环球视野\n \"xijinpingwaijiaosixiang\":\"https://www.xuexi.cn/lgdata/1ooaa665snf.json?_st=26096213\",\n \"shijieyanzhongdexijinping\":\"https://www.xuexi.cn/lgdata/vdppiu92n1.json?_st=26096214\",\n #环球视野-一带一路\n \"xinwenzixun\":\"https://www.xuexi.cn/lgdata/1kok79h5s7n.json?_st=26096216\",\n \"zhengcehuanjing\":\"https://www.xuexi.cn/lgdata/1mjdmg8mtnn.json?_st=26096216\",\n \"hulianhutong\":\"https://www.xuexi.cn/lgdata/1kb4calll7n.json?_st=26096217\",\n \"guojihezuo\":\"https://www.xuexi.cn/lgdata/t1u2cdg6nn.json?_st=26096218\",\n \"jicushuju\":\"https://www.xuexi.cn/lgdata/1dqdq0hj07n.json?_st=26096218\",\n \"gonghuasilu\":\"https://www.xuexi.cn/lgdata/1kmjuu09c7n.json?_st=26096219\",\n \"wenboyaniu\":\"https://www.xuexi.cn/lgdata/1063lvdd6nd.json?_st=26096222\",\n #视频,先去掉\n #\"wenbogongkiake\":\"https://www.xuexi.cn/lgdata/1o2r10b6f7d.json?_st=26096223\",\n #\"wenbojilupian\":\"https://www.xuexi.cn/lgdata/17j565ghcnd.json?_st=26096224\",\n #习近平文汇:栏目内容较杂,先去掉\n #学习电视台和学习慕课都是视频:先去掉\n #学习文化:栏目很多,先爬建筑、武术、楹联、医药,其余的基本功能满足后再加\n #学习文化-中国建筑:建筑与文化、建筑知识栏目数据不是通过json生成,而是在data+MD5里,先去掉\n \"gudaijianzhujicui\":\"https://www.xuexi.cn/lgdata/v4pq4uth7d.json?_st=26096242\",\n \"jindaijianzhujicui\":\"https://www.xuexi.cn/lgdata/1c59olfnvnd.json?_st=26096243\",\n \"jianshewenhuayujianzhuyanjiu\":\"https://www.xuexi.cn/lgdata/1oog782287d.json?_st=26096246\",\n \"jianzhumingjia\":\"https://www.xuexi.cn/lgdata/tnigd8qund.json?_st=26096248\",\n #学习文化-中华武术,中华武术教学是视频,先去掉\n \"wushuyanbian\":\"https://www.xuexi.cn/lgdata/1lnc6c84mnd.json?_st=26096250\",\n \"zhonghuashangwujingshen\":\"https://www.xuexi.cn/lgdata/11j85c92mnd.json?_st=26096252\",\n \"zhonghuawuhun\":\"https://www.xuexi.cn/lgdata/13d9au2i0nd.json?_st=26096253\",\n \"zhonghuawuxue\":\"https://www.xuexi.cn/lgdata/vb0qh7so7d.json?_st=26096254\",\n #学习文化-中华医药\n \"zhongyidianji\":\"https://www.xuexi.cn/lgdata/urm3g97vnn.json?_st=26096257\",\n \"lidaimingyi\":\"https://www.xuexi.cn/lgdata/168delc1d7e.json?_st=26096259\",\n \"dangdaimingyi\":\"https://www.xuexi.cn/lgdata/18r1mt5nh7e.json?_st=26096260\",\n \"zhonghuayiyaoyushijie\":\"https://www.xuexi.cn/lgdata/15q5l76icne.json?_st=26096262\",\n #学习文化-中华楹联,楹联视频先去掉\n \"minglianjianshang\":\"https://www.xuexi.cn/lgdata/1i276vso3ne.json?_st=26096267\",\n #学习文化-中华楹联-楹联与习俗-楹联习俗\n \"chunlianxisu\":\"https://www.xuexi.cn/lgdata/4j8eurk302bq.json?_st=26096268\",\n #学习文化-中华楹联-楹联与习俗-节令楹联\n \"jielingyinglian\":\"https://www.xuexi.cn/lgdata/4b0a3rjqb9uq.json?_st=26096270\",\n #学习文化-中华楹联-楹联与习俗-行业��联\n \"hangyeyinglian\":\"https://www.xuexi.cn/lgdata/48oc8va2veoh.json?_st=26096271\",\n #学习文化-中华楹联-楹联与习俗-喜庆楹联\n \"xiqingyinglian\":\"https://www.xuexi.cn/lgdata/4qkgon8lvjdj.json?_st=26096272\",\n #学习文化-中华楹联-楹联与习俗-宗教楹联\n \"zongjiaoyinglian\":\"https://www.xuexi.cn/lgdata/3m1efumdciph.json?_st=26096273\",\n #学习文化-中华楹联-楹联与习俗-其他楹联\n \"qitayinglian\":\"https://www.xuexi.cn/lgdata/4a3hb4kkg5v4.json?_st=26096275\",\n #学习文化-中华楹联-楹联知识\n \"yinglianzhishi\":\"https://www.xuexi.cn/lgdata/10jabihga7e.json?_st=26096277\",\n #强军兴军:1、习近平强军思想研究 2、强军时评 3、学习军史:军事家、军史故事、军史档案、军史文物4、古代军事家 5、古代兵器 6、兵器大观\n #其他的多数是图片和视频,先去掉\n \"xijinpingqiangjunsixiangyanjiu\":\"https://www.xuexi.cn/lgdata/12lm260c37e.json?_st=26096287\",\n \"qiangjushiping\":\"https://www.xuexi.cn/lgdata/1j2fuv9rs7e.json?_st=26096378\",\n \"junshijia\":\"https://www.xuexi.cn/lgdata/16ap1a07pnn.json?_st=26096382\",\n \"junshigushi\":\"https://www.xuexi.cn/lgdata/178c76irs7n.json?_st=26096383\",\n \"junshidangan\":\"https://www.xuexi.cn/lgdata/1nan78i05nn.json?_st=26096384\",\n \"junshirenwu\":\"https://www.xuexi.cn/lgdata/12l486vm97n.json?_st=26096385\",\n \"gudaijunshijia\":\"https://www.xuexi.cn/lgdata/1mo5h6vk07f.json?_st=26096387\",\n \"gudaibingqi\":\"https://www.xuexi.cn/lgdata/ug4o30g07f.json?_st=26096390\",\n \"bingqidaguan\":\"https://www.xuexi.cn/lgdata/1gd1n2n667f.json?_st=26096445\",\n #美丽中国:1、生态文明建设思想研究2、生态文明建设实践3、走遍中国4、记住乡愁5、历史文化名城6、历史文化名镇7、历史文化名街\n \"shengtaiwenmingjianshesixiangyanjiu\":\"https://www.xuexi.cn/lgdata/1ahi87vjg7e.json?_st=26096452\",\n \"shengtaiwenmingjiansheshijian\":\"https://www.xuexi.cn/lgdata/1eiarm6b5ne.json?_st=26096462\",\n \"zoubianzhongguo\":\"https://www.xuexi.cn/lgdata/3alk4pkja8hl.json?_st=26096463\",\n \"jizhuxiangchou\":\"https://www.xuexi.cn/lgdata/dfo6qrb8n1p.json?_st=26096457\",\n \"lishiwenhuamingcheng\":\"https://www.xuexi.cn/lgdata/12k7uv48b7e.json?_st=26096458\",\n \"lishiwenhuamingzhen\":\"https://www.xuexi.cn/lgdata/1ogcjrb5c7e.json?_st=26096466\",\n \"lishiwenhuamingjie\":\"https://www.xuexi.cn/lgdata/1b04bc5p5ne.json?_st=26096467\"\n\n }\n self.db = pymysql.connect(\"172.17.1.4\", \"emspapp\", \"emspapp\", \"QIANGGUO\", charset='utf8')\n self.headers={\n \"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36\"\n }\n self.urlList=[]#定义全局资讯详情url\n self.columnNum = 1#栏目数量\n self.countContent=1#某栏目的资讯数量\n\n def __decorateArticleUrlDict__(self):\n \"\"\"\n 用于对文章栏目url进行补充,以达到爬取网站所有文章的目的\n :return:\n \"\"\"\n #下面三单引号注释的是对txt里的地址的空链接处理,爬取内容的话已初始化,无需再处理\n from aboutCategory.get_category_url import get_category_url\n scrapy = get_category_url()#类的实例化\n #从其他脚本拿到所有可用的栏目url\n validUrlList = scrapy.getValidurlList()#去除空链接的列表\n\n #将原来的栏目url字典变成列表\n completedArticleColumnUrl = []\n for value in self.__columnUrlDict.values():\n completedArticleColumnUrl.append(value)#现在一个是原来txt里处理过空链接的列表validUrlList,一个是初始化里字典处理后的列表\n #将所有新拿到的且内容文章的栏目url,加入到completedArticleColumnUrl这个列表中\n for columnUrl in validUrlList:\n try:\n temp = self.__getPercolumn_allUrl__(columnUrl)#文章详情url列表\n #print(temp)\n articleColumnUrl = columnUrl\n #print(articleColumnUrl)\n #判断本次的栏目url是否已经存在于列表中\n flag = True\n for url in completedArticleColumnUrl:\n if url == articleColumnUrl:\n flag = False\n\n #本次栏目不存在于列表时才插入\n if flag == True:\n completedArticleColumnUrl.append(articleColumnUrl)\n except:\n print (\"这是一个无法获取文章的栏目,应该是视频\")\n print (\"文章栏目更新完毕,下面开始更新文章\")\n return completedArticleColumnUrl #返���的是所有栏目的链接,里面是具体的内容\n\n def __getArticleDetail__(self,newsUrl):#获取不带id参数的资讯url内容\n \"\"\"\n :param newsUrl:新闻页面的html地址,而不是js格式的请求地址\n :return: 一个包含了这篇新闻的各种信息的字典对象\n \"\"\"\n jsUrlTemp = newsUrl.rsplit('/')\n jsUrl = \"http:\" + '//' + jsUrlTemp[2] + '/' + jsUrlTemp[3] + '/data' + jsUrlTemp[4].replace('html', 'js')\n unitInfObj = requests.get(url=jsUrl,headers=self.headers)\n unitInfObj.encoding = 'utf-8'\n articleDict={}\n if unitInfObj.text!='empty':\n for key,value in json.loads(unitInfObj.text.lstrip('globalCache = ').rstrip(';'),encoding=\"utf-8\").items():\n if key == 'sysQuery':\n pass\n elif key!= 'sysQuery':\n try:\n if len(json.loads(unitInfObj.text.lstrip('globalCache = ').rstrip(';')))<=3:\n #if ('detail' in value)&&len(value['detail'])!=0:\n if ('detail' in value):\n articleDict['frst_name'] =value['detail']['frst_name']\n articleDict['source']=value['detail']['source']\n articleDict['editor']=value['detail']['editor']\n articleDict['original_time']=value['detail']['original_time']\n #print(type(value['detail']['cate_id'][0]))\n articleDict['cate_id']=value['detail']['cate_id']\n articleDict['article_url']=newsUrl\n articleDict['page_id']=value['detail']['_id']\n articleDict['content']=value['detail']['content']\n #print(value['detail']['_id'])\n return articleDict\n # return json.dumps(result, encoding=\"UTF-8\", ensure_ascii=False)\n elif 'list' in value:\n if value['list']['ossUrl']!='':\n print('该文章可能为视频')\n break\n else:\n print('该栏目不是视频也不是资讯,可能是资讯视频的列表,请检查')\n else:\n print('该栏目不是视频也不是资讯,请检查')#这里如果key有多个就打印多个,需要完善\n break\n except:\n pass\n else:\n print('该文章内容可能为空,请检查:'+jsUrl)\n def __getArticleDetail_id__(self,newsUrl,type):#获取带id参数的资讯url内容,一个参数是资讯url,一个参数是由文章列表传来的资讯类型\n jsUrlTemp=newsUrl.split('?id=')\n jsUrl='https://boot-source.xuexi.cn/data/app/'+jsUrlTemp[1]+'.js'#带id参数的详情url地址\n unitInfObj = requests.get(url=jsUrl,headers=self.headers)\n #print(jsUrl)\n #print(unitInfObj.text)\n unitInfObj.encoding = 'utf-8'\n articleDict={}\n res=json.loads(unitInfObj.text.lstrip(\"callback(\").rstrip(')'),encoding=\"utf-8\")\n #print(res)\n try:\n articleDict['frst_name'] =res['title']\n articleDict['source']=res['source']\n articleDict['editor']=res['audit_setting']['specified_audit']['send_person_name']\n articleDict['original_time']=res['publish_time']\n articleDict['cate_id']=type #从__getPercolumn_allUrl_Id____返回的内容类别\n articleDict['article_url']=newsUrl\n articleDict['page_id']=res['identity']['item_id']\n articleDict['content']=res['normalized_content']\n return articleDict\n except:\n pass\n def __getPercolumn_allUrl_Id____(self,columnUrl):\n response = requests.get(url=columnUrl,headers=self.headers)\n response.encoding='utf-8'\n if(len(json.loads(response.text))>=60):\n res=json.loads(response.text)[0:60]#由于内容太多,只取前60条内容\n else:\n res=json.loads(response.text)\n #urlList=[]#资讯详情url列表\n for value in res:#res是列表,value是字典\n if 'url' in value:\n self.urlList.append(value['url'])\n return self.urlList,res[0]['channelNames'][0] #返回两个,一个是资讯的url,一个是资讯的类别,在url带id的资讯字典里没有类别字段,所以从这返回到内容获取函数里,存到mysql\n def __getPercolumn_allUrl__(self,columnUrl):#获取所有栏目的资讯url\n \"\"\"\n :param:columnUrl,栏目的网址\n :return:urlList,单个栏目中所有新闻的网址\n \"\"\"\n jsUrlTemp = columnUrl.rsplit('/')\n jsUrl = \"http:\" + '//' + jsUrlTemp[2] + '/' + jsUrlTemp[3] + '/data' + jsUrlTemp[4].replace('html', 'js')\n print(jsUrl)\n res = requests.get(url=jsUrl,headers=self.headers)\n res.encoding = 'utf-8'\n #urlList = []\n for key,value in json.loads(res.text.lstrip('globalCache = ').rstrip(';'),encoding=\"utf-8\").items():\n if key != 'sysQuery':\n if len(value['list'])>=60:\n for item in value['list'][0:60]:#资讯详情有两种,一种是带id参数的,一种不带,两个if处理\n if 'art_id' in item:\n self.urlList.append(item['art_id'])#urlList为链接列表\n if 'static_page_url' in item:\n self.urlList.append(item['static_page_url'])#urlList为链接列表\n #time.sleep(1)\n #print(static_page_url)\n else:\n for item in value['list']:\n if 'art_id' in item:\n self.urlList.append(item['art_id'])\n if 'static_page_url' in item:\n self.urlList.append(item['static_page_url'])\n #print(urlList)\n return self.urlList #返回的是文章详情url列表\n\n def __firstTime__(self):\n # newstotal = []\n db = pymysql.connect(\"172.17.1.4\", \"emspapp\", \"emspapp\", \"QIANGGUO\", charset='utf8')\n cursor = db.cursor()\n for columnUrl in self.__columnUrlDict.values():\n for url in self.__getPercolumn_allUrl__(columnUrl):\n # newsItemList = []\n newsItemdict = self.__getArticleDetail__(url)\n # newstotal.append(result)\n # data = pandas.DataFrame(newsItemList)\n # pandas.io.sql.write_frame(data,\"qiangguoNews\",engine)\n # data.to_sql('qiangguoNews', con=engine,if_exists='replace')\n #直接使用DB-API把数据存进去↓\n insertsql = \"INSERT INTO QGNews(article_id,article_title,article_url,article_date,article_editor,article_source,column_id) VALUES('%s','%s','%s','%s','%s','%s','%s')\"%(newsItemdict['page_id'],newsItemdict['frst_name'],newsItemdict['article_url'],newsItemdict['original_time'],newsItemdict['editor'],newsItemdict['source'],newsItemdict['cate_id'])\n try:\n cursor.execute(insertsql)\n db.commit()\n print (insertsql)\n except:\n print (\"这一次错误\")\n cursor.close()\n def __CheckMysql__(self,columnUrl):\n #global count\n count =0\n cursor=self.db.cursor()\n if '.html' in columnUrl:#不带id参数的\n for url in self.__getPercolumn_allUrl__(columnUrl):#不带id参数的,主要是“学习重点”栏目\n print(' '+'检查第{}个栏目的第{}篇资讯'.format(self.columnNum,self.countContent))\n print(' '+url)\n try:\n if '.html' in url:\n content_dic = self.__getArticleDetail__(url)\n if '?id=' in url:\n content_dic = self.__getArticleDetail_id__(url,contentType)\n selectsql = \"select * from QGNews where article_id = '%s'\"%(content_dic['page_id'])\n cursor.execute(selectsql)\n if cursor.rowcount != 0:\n if count < 20:\n selectResult = cursor.fetchone()\n print (\"名称为《%s》的文章已存在,不需要更新\" % (selectResult[2]))\n count +=1\n else:\n print (\"第%s个栏目的文章已经不需要更新了\"%(self.columnNum))\n #self.columnNum = self.columnNum+1\n break\n else:\n insertsql = \"INSERT INTO QGNews(article_id,article_title,article_url,article_date,article_editor,article_source,column_id,article_content) VALUES('%s','%s','%s','%s','%s','%s','%s','%s')\" % (\n content_dic['page_id'], content_dic['frst_name'], content_dic['article_url'],\n content_dic['original_time'], content_dic['editor'], content_dic['source'],\n content_dic['cate_id'],content_dic['content'])\n #self.__insertData__(content_dic)\n try:\n cursor.execute(insertsql)\n self.db.commit()\n print (\"【新文章提醒】这是一则新的文章,名称为《%s》,已为您更新到数据库\" % (content_dic['frst_name']))\n except:\n print (\"这一次插入数据错误\")\n #self.countContent=self.countContent+1\n except:\n count += 1\n self.countContent=self.countContent+1#下一条资讯内容\n count=0\n self.countContent=1#该栏目的资讯已遍历完,进行下个栏目遍历时,该值清零\n self.columnNum=self.columnNum+1#下个栏目的序号\n self.urlList=[]#每次遍历完一个栏目都要清空,否则会存在已遍历过的栏目的资讯url\n if '.json?' in columnUrl:#带id参数的\n contentUrlList,contentType=self.__getPercolumn_allUrl_Id____(columnUrl)\n for url in contentUrlList:\n print(' '+'检查第{}个栏目的第{}篇资讯'.format(self.columnNum,self.countContent))\n print(url)\n try:\n if url[-5:]=='.html':\n content_dic = self.__getArticleDetail__(url)\n if '?id=' in url:\n content_dic = self.__getArticleDetail_id__(url,contentType)\n #print(content_dic['page_id'])\n selectsql = \"select * from QGNews where article_id = '%s'\"%(content_dic['page_id'])\n cursor.execute(selectsql)\n if cursor.rowcount != 0:\n if count < 20:\n selectResult = cursor.fetchone()\n print (\"名称为《%s》的文章已存在,不需要更新\" % (selectResult[2]))\n count +=1\n else:\n print (\"第%s个栏目的文章已经不需要更新了\"%(self.columnNum))\n #self.columnNum = self.columnNum+1\n break\n else:\n insertsql = \"INSERT INTO QGNews(article_id,article_title,article_url,article_date,article_editor,article_source,column_id,article_content) VALUES('%s','%s','%s','%s','%s','%s','%s','%s')\" % (\n content_dic['page_id'], content_dic['frst_name'], content_dic['article_url'],\n content_dic['original_time'], content_dic['editor'], content_dic['source'],\n content_dic['cate_id'],content_dic['content'])\n #self.__insertData__(content_dic)\n try:\n cursor.execute(insertsql)\n self.db.commit()\n print (\"【新文章提醒】这是一则新的文章,名称为《%s》,已为您更新到数据库\" % (content_dic['frst_name']))\n except:\n print (\"这一次插入数据错误\")\n except:\n count += 1\n self.countContent=self.countContent+1\n count=0\n self.countContent=1\n self.columnNum=self.columnNum+1\n self.urlList=[]#每次遍历完一个栏目都要清空,否则会存在已遍历过的栏目的资讯url\n def __insertData__(self,dic):\n insertsql = \"INSERT INTO QGNews(article_id,article_title,article_url,article_date,article_editor,article_source,column_id,article_content) VALUES('%s','%s','%s','%s','%s','%s','%s','%s')\" % (\n dic['page_id'], dic['frst_name'], dic['article_url'],\n dic['original_time'], dic['editor'], dic['source'],\n dic['cate_id'],dic['content'])\n return insertsql\n def __ConnectMysql__(self):\n db.pymysql.connect(\"172.17.1.4\",\"emspapp\",\"emspapp\",\"QIANGGUO\",charset='utf-8')\n cursor=db.cursor()\n return cursor\n def __Maintain__(self):\n # newstotal = []\n #db = pymysql.connect(\"172.17.1.4\", \"emspapp\", \"emspapp\", \"QIANGGUO\", charset='utf8')\n #cursor = db.cursor()\n for columnUrl in self.__columnUrlDict.values():#遍历所有的栏目链接,__init__初始化里的链接\n #count =0\n print (\"现在对第%s个栏目进行检测\" % (self.columnNum))\n print('\\n栏目地址:'+columnUrl)\n self.__CheckMysql__(columnUrl)\n '''if '.html' in columnUrl:#不带id参数的\n for url in self.__getPercolumn_allUrl__(columnUrl):#不带id参数的,主要是“学习重点”栏目\n print(url)\n try:\n newsItemdict = self.__getArticleDetail__(url)\n slef.__CheckMysql__(newsItemdict)\n except:\n count += 1\n if '.json?' in columnUrl:#带id参数的\n contentUrlList,contentType=self.__getPercolumn_allUrl_Id____(columnUrl)\n for url in contentUrlList:\n print(url)\n try:\n newsItemdict = self.__getArticleDetail_id__(columnUrl)\n slef.__CheckMysql__(newsItemdict)\n except:\n count += 1\n #print(url)\n try:\n newsItemdict = self.__getArticleDetail__(url)\n selectsql = \"select * from QGNews where article_id = '%s'\"%(newsItemdict['page_id'])\n cursor.execute(selectsql)\n if cursor.rowcount != 0:\n if count < 20:\n selectResult = cursor.fetchone()\n print (\"名称为《%s》的文章已存在,不需要更新\" % (selectResult[2]))\n count +=1\n else:\n print (\"第%s个栏目的文章已经不需要更新了\"%(columnNum))\n columnNum = columnNum+1\n break\n else:\n insertsql = \"INSERT INTO QGNews(article_id,article_title,article_url,article_date,article_editor,article_source,column_id) VALUES('%s','%s','%s','%s','%s','%s','%s')\" % (\n newsItemdict['page_id'], newsItemdict['frst_name'], newsItemdict['article_url'],\n newsItemdict['original_time'], newsItemdict['editor'], newsItemdict['source'],\n newsItemdict['cate_id'])\n try:\n cursor.execute(insertsql)\n db.commit()\n print (\"【新文章提醒】这是一则新的文章,名称为《%s》,已为您更新到数据库\" % (newsItemdict['frst_name']))\n except:\n print (\"这一次插入数据错误\")\n ''' \n else:\n print (\"本日的更新已完成\")\n\n self.db.cursor.close()\n\nif __name__ == '__main__':\n scrapy = news_scrapy()\n # scrapy.__firstTime__()\n scrapy.__Maintain__()\n # scrapy.decorateUrlDict()\n","sub_path":"news_content_scrapy-bak.py","file_name":"news_content_scrapy-bak.py","file_ext":"py","file_size_in_byte":32947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"530878824","text":"import sys\nimport os\n\n# Make sure we're using the right python. Assume we're running out of the venv.\nINTERP = os.path.join(os.getcwd(), 'bin', 'python')\nif sys.executable != INTERP:\n os.execl(INTERP, INTERP, *sys.argv)\n sys.path.append(os.getcwd())\n\nimport configparser\nimport importlib\n\nconfig = configparser.ConfigParser()\nconfig.read(\"config.ini\")\n\nbots = {}\nfor bot in config.sections():\n if \"disabled\" in config[bot] and config[bot][\"webhook\"] == \"1\":\n print(\"Bot {0} disabled\".format(bot))\n continue\n if \"webhook\" not in config[bot] or config[bot][\"webhook\"] != \"1\":\n print(\"Bot {0} not using webhook\".format(bot))\n continue\n if \"repo_name\" not in config[bot]:\n raise RuntimeError(\"Cannot find repo for bot {0}\".format(bot))\n bot_path = os.path.join(os.getcwd(), config[bot][\"repo_name\"])\n if not os.path.isdir(bot_path):\n raise RuntimeError(\"Cannot find path {0} for bot {1}\".format(bot_path,\n bot))\n sys.path.append(bot_path)\n # Assume the bot module is the same as the config file\n if \"module_name\" not in config[bot]:\n raise RuntimeError(\"Cannot find module for bot {0}\".format(bot))\n module = config[bot][\"module_name\"]\n importlib.import_module(module)\n bots[config[bot][\"token\"]] = getattr(sys.modules[module],\n \"create_webhook_bot\")(config[bot])\n\nif len(bots.keys()) == 0:\n raise RuntimeError(\"Not running any bots!\")\n\nfrom flask import Flask, request\nimport telegram\n\napplication = Flask(__name__)\n\n\n@application.route('/')\ndef hello():\n return \"\"\n\n\n@application.route('/telegram/', methods=['POST'])\ndef webhook(token):\n update = telegram.update.Update.de_json(request.get_json(force=True))\n if token not in bots.keys():\n return 'OK'\n bots[token].update_queue.put(update)\n return 'OK'\n\n\nif __name__ == \"__main__\":\n application.run()\n","sub_path":"passenger_wsgi.py","file_name":"passenger_wsgi.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"414540295","text":"from IoTPy.ioboard.uper import UPER1\nfrom IoTPy.things.rotary_encoder import RotaryEncoder\nfrom time import sleep\n\n\ndef on_rotation(direction, position):\n print(\"Rotated by %i, current position is %i\" % (direction, position))\n\n\nwith UPER1() as board, \\\n board.GPIO(1) as chan0, board.GPIO(2) as chan1, \\\n RotaryEncoder(chan0, chan1, on_rotation) as encoder:\n\n while True:\n sleep(0.5)\n","sub_path":"examples/sensors/02_RotaryEncoder.py","file_name":"02_RotaryEncoder.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"407319705","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom itertools import permutations \n\n\"\"\"\nCreated on Sun May 24 23:43:07 2020\n[Easy] Axis-aligned crate packing\n\nDescription\nYou have a 2-dimensional rectangular crate of size X by Y, and a bunch of boxes, each of size x by y. The dimensions are all positive integers.\n\nGiven X, Y, x, and y, determine how many boxes can fit into a single crate if they have to be placed so that the x-axis of the boxes is aligned with the x-axis of the crate, and the y-axis of the boxes is aligned with the y-axis of the crate. That is, you can't rotate the boxes. The best you can do is to build a rectangle of boxes as large as possible in each dimension.\n\nFor instance, if the crate is size X = 25 by Y = 18, and the boxes are size x = 6 by y = 5, then the answer is 12. You can fit 4 boxes along the x-axis (because 6*4 <= 25), and 3 boxes along the y-axis (because 5*3 <= 18), so in total you can fit 4*3 = 12 boxes in a rectangle.\n\nExamples\nfit1(25, 18, 6, 5) => 12\nfit1(10, 10, 1, 1) => 100\nfit1(12, 34, 5, 6) => 10\nfit1(12345, 678910, 1112, 1314) => 5676\nfit1(5, 100, 6, 1) => 0\n\n@author: ryanhennes\n\"\"\"\n#Original Problem\ndef fit1(X, Y, x, y):\n #use floor division to determine if the boxes can fit\n xRemainder = X // x\n yRemainder = Y // y\n return (xRemainder * yRemainder)\n\nprint(\"Original Solutions\")\nprint(fit1(25, 18, 6, 5))\nprint(fit1(10, 10, 1, 1))\nprint(fit1(12, 34, 5, 6))\nprint(fit1(12345, 678910, 1112, 1314))\nprint(fit1(5, 100, 6, 1))\n\n\n\"\"\"\nOptional bonus fit2\nYou upgrade your packing robot with the latest in packing technology: turning stuff. You now have the option of rotating all boxes by 90 degrees, so that you can treat a set of 6-by-5 boxes as a set of 5-by-6 boxes. You do not have the option of rotating some of the boxes but not others.\n\nfit2(25, 18, 6, 5) => 15\nfit2(12, 34, 5, 6) => 12\nfit2(12345, 678910, 1112, 1314) => 5676\nfit2(5, 5, 3, 2) => 2\nfit2(5, 100, 6, 1) => 80\nfit2(5, 5, 6, 1) => 0\nHint: is there an easy way to define fit2 in terms of fit1?\n\nNote that this is not the maximum possible number of boxes you could get if you rotated them independently. For instance, if you're fitting 3-by-2 boxes into a 5-by-5 crate, it's possible to fit 4 by varying the orientations, but fit2(5, 5, 3, 2) is 2, not 4. Handling the general case is much more complicated, and beyond the scope of today's challenge.\n\"\"\"\n#Bonus 1\ndef fit2(X, Y, x, y):\n bestArrangement = fit1(X, Y, x, y) #storing original box arrangment for comparison\n arr2 = fit1(X, Y, y, x) #rotating the boxes by 90 degrees\n if(bestArrangement < arr2):\n bestArrangement = arr2\n return bestArrangement\n\nprint(\"\\nBonus 1 Solutions\")\nprint(fit2(25, 18, 6, 5))\nprint(fit2(12, 34, 5, 6))\nprint(fit2(12345, 678910, 1112, 1314))\nprint(fit2(5, 5, 3, 2))\nprint(fit2(5, 100, 6, 1))\nprint(fit2(5, 5, 6, 1))\n \n\n\n\"\"\"\nOptional bonus fit3\nYou upgrade your warehouse to the third dimension. You're now given six parameters, X, Y, Z, x, y, and z. That is, you're given the X, Y, and Z dimensions of the crate, and the x, y, and z dimensions of the boxes. There are now six different possible orientations of the boxes. Again, boxes cannot be rotated independently: they all have to have the same orientation.\n\nfit3(10, 10, 10, 1, 1, 1) => 1000\nfit3(12, 34, 56, 7, 8, 9) => 32\nfit3(123, 456, 789, 10, 11, 12) => 32604\nfit3(1234567, 89101112, 13141516, 171819, 202122, 232425)) => 174648\n\"\"\"\n#Bonus 2\ndef fit1_3D(X, Y, Z, x, y, z):\n #use floor division to determine if the boxes can fit\n xRemainder = X // x\n yRemainder = Y // y\n zRemainder = Z // z\n return (xRemainder * yRemainder * zRemainder)\ndef fit3(X, Y, Z, x, y, z):\n bestArrangement = fit1_3D(X, Y, Z, x, y, z) #storing original box arrangment for comparison\n arr2 = fit1_3D(X, Y, Z, x, z, y) #rotating the boxes by 90 degrees\n arr3 = fit1_3D(X, Y, Z, y, x, z)\n arr4 = fit1_3D(X, Y, Z, z, y, x)\n arr5 = fit1_3D(X, Y, Z, y, z, x)\n arr6 = fit1_3D(X, Y, Z, z, x, y)\n if(bestArrangement < arr2):\n bestArrangement = arr2\n if(bestArrangement < arr3):\n bestArrangement = arr3\n if(bestArrangement < arr4):\n bestArrangement = arr4\n if(bestArrangement < arr5):\n bestArrangement = arr5\n if(bestArrangement < arr6):\n bestArrangement = arr6\n return bestArrangement\n\nprint(\"\\nBonus 2 Solutions\")\nprint(fit3(10, 10, 10, 1, 1, 1))\nprint(fit3(12, 34, 56, 7, 8, 9))\nprint(fit3(123, 456, 789, 10, 11, 12))\nprint(fit3(1234567, 89101112, 13141516, 171819, 202122, 232425))\n\n\n\n\n\"\"\"\nOptional bonus fitn\nYou upgrade your warehouse to the Nth dimension. Now you take a list of N crate dimensions, and N box dimensions. Assume that the boxes may be rotated in any of N! orientations so that each axis of the crate aligns with a different axis of the boxes. Again, boxes cannot be rotated independently.\n\nfitn([3, 4], [1, 2]) => 6\nfitn([123, 456, 789], [10, 11, 12]) => 32604\nfitn([123, 456, 789, 1011, 1213, 1415], [16, 17, 18, 19, 20, 21]) => 1883443968\n\"\"\"\n#Bonus 3\ndef fit1_N(crateDim, boxDim): #function taking in a list of creat and box dimensions that returns the arrangment score for the given dimensions\n #use floor division to determine if the boxes can fit\n remainders = []\n for i in range(len(crateDim)):\n remainders.append(crateDim[i] // boxDim[i])\n \n remainderScalar = 1\n for i in remainders:\n remainderScalar = remainderScalar * i\n return remainderScalar\n\ndef fitn(crateDim, boxDim):\n perm = permutations(boxDim) #generating all of the possible permutations for rotating\n bestArrangment = fit1_N(crateDim, boxDim) #creating a starting point to compare with the rest of the permutations\n for i in perm:\n tempArrangement = fit1_N(crateDim, i) #using the fit1_N function to return the score of the current arrangement\n if(tempArrangement > bestArrangment):\n bestArrangment = tempArrangement\n return bestArrangment\n \nprint(\"\\nBonus 3 Solutions\")\nprint(fitn([3, 4], [1, 2]))\nprint(fitn([123, 456, 789], [10, 11, 12]))\nprint(fitn([123, 456, 789, 1011, 1213, 1415], [16, 17, 18, 19, 20, 21]))\n\n\n\n","sub_path":"[Easy] Axis-aligned crate packing.py","file_name":"[Easy] Axis-aligned crate packing.py","file_ext":"py","file_size_in_byte":6145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"89992961","text":"import os\nimport sys\nimport numpy as np\nimport csv \n\ndef gradient_descent(X, y, lr, iteration):\n\t\n\tfeature_num = len(X[0])\n\terr = []\n\tb = 0\n\tw = np.zeros(feature_num).astype('float')\n\tlr_b = 0\n\tlr_w = np.zeros(feature_num).astype('float')\n\tLambda = 100.\n\n\tfor it in range(iteration):\n\t\tb_grad = 0.0\n\t\tw_grad = np.zeros(feature_num).astype('float')\n\t\tSum = 0.0\n\t\tfor n in range(len(X)):\n\t\t\terror = y[n] - b - np.dot(w,X[n])\n\t\t\tSum = Sum + error**2\n\t\t\tb_grad = b_grad - 2.0*error*1.0\n\t\t\tw_grad = w_grad - 2.0*error*X[n] + 2*Lambda*w\n\t\t\t\n\t\tlr_b += b_grad**2\n\t\tlr_w += np.square(w_grad)\n\t\t# update parameters\n\t\tb = b - lr * b_grad/np.sqrt(lr_b)\n\t\tw = w - lr * w_grad/(np.sqrt(lr_w) + 1e-21)\n\n\t\troot_mean = np.sqrt(Sum/len(X))\n\t\tif it % 10 == 0 :\n\t\t\terr = np.append( err, root_mean)\n\t\t\tSave = np.hstack((w, b))\n\t\tprint('Iteration: ' + str(it) + '. RMSE: ' + str(root_mean))\n\n\tnp.save('error.npy', err)\n\tnp.save('parameters.npy', Save)\t\n\treturn b, w\n\ndef get_test_result(data,para):\n\tw = para[:len(para)-1]\n\tb = para[len(para)-1]\n\ty = []\n\tfor i in data:\n\t\tresult = np.dot(i,w) + b\n\t\ty = np.append(y,result)\n\treturn y\n\n# path = os.getcwd() + '/ml-2018spring-hw1/train.csv'\n# data = [] \n# for i in range(18):\n# \tdata.append([])\n\n# # store data according to the feature\n# n_row = 0\n# text = open(path, 'r', encoding='big5') \n# row = csv.reader(text , delimiter=\",\")\n# for r in row:\n# \tif n_row != 0:\n# \t\tfor i in range(3,27):\n# \t\t\tif r[i] != \"NR\":\n# \t\t\t\tdata[(n_row-1)%18].append(float(r[i]))\n# \t\t\telse:\n# \t\t\t\tdata[(n_row-1)%18].append(float(0)) \n# \tn_row = n_row+1\n# text.close()\n\n\n# x = []\n# y = []\n# for i in range(12):\n# \tfor j in range(471):\n# \t\tx.append([])\n# \t\tfor t in range(18):\n# \t\t\tfor s in range(9):\n# \t\t\t\tx[471*i+j].append(data[t][480*i+j+s])\n# \t\ty.append(data[9][480*i+j+9])\n# x = np.array(x)\n# y = np.array(y)\n\n# # Data pre-processing for training data\n# del_num = np.array([])\n# for i in range(len(x)):\n# \ttmp1 = x[i][0:90]\n# \ttmp2 = x[i][99:]\n# \tPM25 = x[i][81:90]\n# \tif (len(tmp1[tmp1 <= 0]) > 0) or (y[i] >= 300 or y[i] <= 0) or (len(tmp2[tmp2 <= 0]) > 0) or (len(PM25[PM25 >= 300]) > 0):\n# \t\tdel_num = np.append( del_num, i)\n\n\n# train_X = np.delete(x, del_num, axis = 0)\n# train_Y = np.delete(y, del_num, axis = 0)\n# b, w = gradient_descent(train_X, train_Y, 10 ,50000)\n\n\n# path_test = os.getcwd() + '/ml-2018spring-hw1/test.csv' # argv[1]\npa_path = os.getcwd() + '/parameters.npy'\npara = np.load(pa_path)\ntest_x = []\nn_row = 0\ntext = open(sys.argv[1],\"r\")\nrow = csv.reader(text , delimiter= \",\")\n\n\n# Data pre-processing for testing data\nfor r in row:\n\tif n_row %18 == 0:\n\t\ttest_x.append([])\n\t\tfor i in range(2,11):\n\t\t\ttest_x[n_row//18].append(float(r[i]) )\n\telse :\n\t\tfor i in range(2,11):\n\t\t\tif r[i] == \"NR\":\n\t\t\t\ttest_x[n_row//18].append(0)\n\t\t\telif float(r[i]) == 0:\n\t\t\t\tif i==2: \n\t\t\t\t\tif r[i+1] == \"NR\": test_x[n_row//18].append(0)\n\t\t\t\t\telse: test_x[n_row//18].append(float(r[i+1]))\n\t\t\t\telse: test_x[n_row//18].append(test_x[n_row//18][-1])\n\t\t\telse:\n\t\t\t\ttest_x[n_row//18].append(float(r[i]))\n\tn_row = n_row+1\ntext.close()\ntest_x = np.array(test_x)\n\nresult = get_test_result(test_x,para)\n\nf = open(sys.argv[2],'w') # argv[2]\nf.write('id' + ',' + 'value\\n')\nfor i in range(len(result)):\n\tf.write('id_' + str(i) + ',' + str(result[i]) + '\\n')\nf.close()","sub_path":"hw1/hw1.py","file_name":"hw1.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"384721578","text":"\nfrom modules.IEnvironmentController import IEnvironmentController\nfrom python_terraform import *\nfrom modules import aws_service, splunk_sdk, github_service\nfrom tabulate import tabulate\nimport ansible_runner\nimport yaml\nimport time\nimport tarfile\nimport os\nimport glob\n\n\nclass TerraformController(IEnvironmentController):\n\n def __init__(self, config, log):\n super().__init__(config, log)\n custom_dict = self.config.copy()\n variables = dict()\n variables['config'] = custom_dict\n self.terraform = Terraform(working_dir='terraform',variables=variables)\n\n\n def build(self):\n self.log.info(\"[action] > build\\n\")\n return_code, stdout, stderr = self.terraform.apply(capture_output='yes', skip_plan=True, no_color=IsNotFlagged)\n if not return_code:\n self.log.info(\"attack_range has been built using terraform successfully\")\n self.list_machines()\n\n\n def destroy(self):\n self.log.info(\"[action] > destroy\\n\")\n return_code, stdout, stderr = self.terraform.destroy(capture_output='yes', no_color=IsNotFlagged)\n self.log.info(\"attack_range has been destroy using terraform successfully\")\n\n\n def stop(self):\n instances = aws_service.get_all_instances(self.config)\n aws_service.change_ec2_state(instances, 'stopped', self.log)\n\n\n def resume(self):\n instances = aws_service.get_all_instances(self.config)\n aws_service.change_ec2_state(instances, 'running', self.log)\n\n\n def test(self, test_file):\n # read test file\n test_file = self.load_file(test_file)\n\n # build attack range\n self.build()\n\n # wait\n self.log.info('Wait for 300 seconds before running simulations.')\n time.sleep(300)\n\n # simulate attack\n # create vars string for custom vars:\n if 'vars' in test_file:\n var_str = '$myArgs = @{ '\n i = 0\n for key, value in test_file['vars'].items():\n if i==0:\n var_str += '\"' + key + '\" = \"' + value + '\"'\n i += 1\n else:\n var_str += '; \"' + key + '\" = \"' + value + '\"'\n i += 1\n\n var_str += ' }'\n print(var_str)\n\n self.simulate(test_file['target'], test_file['simulation_technique'], 'no', var_str)\n\n else:\n self.simulate(test_file['target'], test_file['simulation_technique'], 'no')\n\n # wait\n self.log.info('Wait for 500 seconds before running the detections.')\n time.sleep(500)\n\n # run detection\n result = []\n\n for detection_obj in test_file['detections']:\n detection_file_name = detection_obj['name'].replace('-','_').replace(' ','_').lower() + '.yml'\n detection = self.load_file('../security-content/detections/' + detection_file_name)\n result_obj = dict()\n result_obj['detection'] = detection_obj['name']\n instance = aws_service.get_instance_by_name(\"attack-range-splunk-server\",self.config)\n if instance['State']['Name'] == 'running':\n result_obj['error'], result_obj['results'] = splunk_sdk.test_search(instance['NetworkInterfaces'][0]['Association']['PublicIp'], str(self.config['splunk_admin_password']), detection['search'], detection_obj['pass_condition'], detection['name'], self.log)\n else:\n self.log.error('ERROR: Splunk server is not running.')\n result.append(result_obj)\n\n #print(result)\n\n # store attack data\n if self.config['capture_attack_data'] == '1':\n self.dump_attack_data(test_file['simulation_technique'])\n\n # destroy attack range\n self.destroy()\n\n #result_cond = False\n for result_obj in result:\n if result_obj['error']:\n self.log.error('Detection Testing failed: ' + result_obj['results']['detection_name'])\n if self.config['automated_testing'] == '1':\n github_service.create_issue(result_obj['results']['detection_name'], self.config)\n #result_cond |= result_obj['error']\n sys.exit(0)\n\n\n def load_file(self, file_path):\n with open(file_path, 'r') as stream:\n try:\n file = list(yaml.safe_load_all(stream))[0]\n except yaml.YAMLError as exc:\n self.log.error(exc)\n sys.exit(\"ERROR: reading {0}\".format(file_path))\n return file\n\n\n\n def simulate(self, target, simulation_techniques, simulation_atomics, var_str = 'no'):\n target_public_ip = aws_service.get_single_instance_public_ip(target, self.config)\n\n # check if specific atomics are used then it's not allowed to multiple techniques\n techniques_arr = simulation_techniques.split(',')\n if (len(techniques_arr) > 1) and (simulation_atomics != 'no'):\n self.log.error('ERROR: if simulation_atomics are used, only a single simulation_technique is allowed.')\n sys.exit(1)\n\n run_specific_atomic_tests = 'True'\n if simulation_atomics == 'no':\n run_specific_atomic_tests = 'False'\n\n if target == 'attack-range-windows-client':\n runner = ansible_runner.run(private_data_dir='.attack_range/',\n cmdline=str('-i ' + target_public_ip + ', '),\n roles_path=\"../ansible/roles\",\n playbook='../ansible/playbooks/atomic_red_team.yml',\n extravars={'var_str': var_str, 'run_specific_atomic_tests': run_specific_atomic_tests, 'art_run_tests': simulation_atomics, 'art_run_techniques': simulation_techniques, 'ansible_user': 'Administrator', 'ansible_password': self.config['win_password'], 'ansible_port': 5985, 'ansible_winrm_scheme': 'http', 'art_repository': self.config['art_repository'], 'art_branch': self.config['art_branch']},\n verbosity=0)\n else:\n runner = ansible_runner.run(private_data_dir='.attack_range/',\n cmdline=str('-i ' + target_public_ip + ', '),\n roles_path=\"../ansible/roles\",\n playbook='../ansible/playbooks/atomic_red_team.yml',\n extravars={'var_str': var_str, 'run_specific_atomic_tests': run_specific_atomic_tests, 'art_run_tests': simulation_atomics, 'art_run_techniques': simulation_techniques, 'ansible_user': 'Administrator', 'ansible_password': self.config['win_password'], 'art_repository': self.config['art_repository'], 'art_branch': self.config['art_branch']},\n verbosity=0)\n\n if runner.status == \"successful\":\n self.log.info(\"successfully executed technique ID {0} against target: {1}\".format(simulation_techniques, target))\n else:\n self.log.error(\"failed to executed technique ID {0} against target: {1}\".format(simulation_techniques, target))\n sys.exit(1)\n\n\n def list_machines(self):\n instances = aws_service.get_all_instances(self.config)\n response = []\n instances_running = False\n for instance in instances:\n if instance['State']['Name'] == 'running':\n instances_running = True\n response.append([instance['Tags'][0]['Value'], instance['State']['Name'], instance['NetworkInterfaces'][0]['Association']['PublicIp']])\n else:\n response.append([instance['Tags'][0]['Value'], instance['State']['Name']])\n print()\n print('Status EC2 Machines\\n')\n if len(response) > 0:\n if instances_running:\n print(tabulate(response, headers=['Name','Status', 'IP Address']))\n else:\n print(tabulate(response, headers=['Name','Status']))\n else:\n print(\"ERROR: Can't find configured EC2 Attack Range Instances in AWS.\")\n print()\n\n\n def dump_attack_data(self, dump_name):\n\n # copy json from nxlog\n # copy raw data using powershell\n # copy indexes\n # packet capture with netsh\n # see https://medium.com/threat-hunters-forge/mordor-pcaps-part-1-capturing-network-packets-from-windows-endpoints-with-network-shell-e117b84ec971\n\n self.log.info(\"Dump log data\")\n\n folder = \"attack_data/\" + dump_name\n os.mkdir(folder)\n\n servers = []\n if self.config['windows_domain_controller'] == '1':\n servers.append('windows_domain_controller')\n if self.config['windows_server'] == '1':\n servers.append('windows_server')\n\n # dump json and windows event logs from Windows servers\n for server in servers:\n server_str = (\"attack-range-\" + server).replace(\"_\",\"-\")\n target_public_ip = aws_service.get_single_instance_public_ip(server_str, self.config)\n\n if server_str == 'attack-range-windows-client':\n runner = ansible_runner.run(private_data_dir='.attack_range/',\n cmdline=str('-i ' + target_public_ip + ', '),\n roles_path=\"../ansible/roles\",\n playbook='../ansible/playbooks/attack_data.yml',\n extravars={'ansible_user': 'Administrator', 'ansible_password': self.config['win_password'], 'ansible_port': 5985, 'ansible_winrm_scheme': 'http', 'hostname': server_str, 'folder': dump_name},\n verbosity=0)\n else:\n runner = ansible_runner.run(private_data_dir='.attack_range/',\n cmdline=str('-i ' + target_public_ip + ', '),\n roles_path=\"../ansible/roles\",\n playbook='../ansible/playbooks/attack_data.yml',\n extravars={'ansible_user': 'Administrator', 'ansible_password': self.config['win_password'], 'hostname': server_str, 'folder': dump_name},\n verbosity=0)\n\n if self.config['sync_to_s3_bucket'] == '1':\n for file in glob.glob(folder + \"/*\"):\n self.log.info(\"upload attack data to S3 bucket. This can take some time\")\n aws_service.upload_file_s3_bucket(self.config['s3_bucket_attack_data'], file, str(dump_name + '/' + os.path.basename(file)))\n","sub_path":"modules/TerraformController.py","file_name":"TerraformController.py","file_ext":"py","file_size_in_byte":10550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"579440266","text":"from typing import List, Any\n\nfrom LOTUS_regression.regression import mzm_regression\nfrom matplotlib.ticker import AutoMinorLocator\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport statsmodels as sm\nfrom datetime import datetime\nfrom scipy import stats\n\ndef plotmlr_perkm(pX, pY, pRegOutput, pltitle, plname):\n\n plt.close('all')\n\n fig, ax = plt.subplots()\n plt.title(pltitle)\n plt.xlabel('Years')\n plt.ylabel('PO3 (hPa)')\n\n plt.plot(pX, pY, label='Data', color='blue')\n plt.plot(pX, pRegOutput, label='Model', color='orange')\n\n ax.legend(loc='upper right', frameon=True, fontsize='small')\n\n # plt.savefig('/Volumes/HD3/KMI/MLR_Uccle/Plots/ilt_reltropop/' + plname + '.pdf')\n # plt.savefig('/Volumes/HD3/KMI/MLR_Uccle/Plots/ilt_reltropop/' + plname + '.eps')\n\n plt.savefig('/home/poyraden/Analysis/MLR_Uccle/Plots/Uccle_50years_2/Residuals/' + plname + '.pdf')\n plt.savefig('/home/poyraden/Analysis/MLR_Uccle/Plots/Uccle_50years_2/Residuals/' + plname + '.eps')\n plt.close()\n\n\n######################################################################################################################\n\n\n# part for using extended predictors\npre_name = 'OneLinear_prenor_RelTropop'\nplname = 'Trend_' + pre_name\ntag = ''\n\n# predictors = pd.read_csv('/home/poyraden/Analysis/MLR_Uccle/Files/Extended_ilt.csv')\npredictors = pd.read_csv('/home/poyraden/Analysis/MLR_Uccle/Files/Extended_ilt_alltrend_pre_nor.csv')\n# #\npredictors.rename(columns={'Unnamed: 0': 'date'}, inplace=True)\npredictors['date'] = pd.to_datetime(predictors['date'], format='%Y-%m')\npredictors.set_index('date', inplace=True)\n# predictors = predictors.loc['2000-01-01':'2018-12-01']\n\n# # try new predictors\n#\n# predictors= pd.read_csv('/home/poyraden/Analysis/MLR_Uccle/Files/NewPredictors_ilt.csv')\n# setp = set(predictors['Unnamed: 0'].tolist())\n#\n# predictors.rename(columns={'Unnamed: 0': 'date'}, inplace=True)\n# predictors['date'] = pd.to_datetime(predictors['date'], format='%Y-%m-%d')\n# predictors.set_index('date', inplace=True)\n\n\n# For DeBilt\n# predictors = predictors.loc['1992-11-01':'2018-12-01']\n\n\nuccle = pd.read_csv('/home/poyraden/Analysis/MLR_Uccle/Files/1km_monthlymean_reltropop_deseas.csv')\n\n# uccle = pd.read_csv('/home/poyraden/Analysis/MLR_Uccle/Files/DeBilt_1km_monthlymean_deseas.csv')\n\nprint('uccle', len(uccle), list(uccle), uccle.index)\nsetu = set(uccle.date.tolist())\n\n# uccle.rename(columns={'Unnamed: 0':'date'}, inplace=True)\n#uccle['date'] = dates\n# pd.to_datetime(uccle['date'], format='%Y-%m')\n# uccle.set_index('date', inplace=True)\n\nuccle.rename(columns={'Unnamed: 0':'date'}, inplace=True)\npd.to_datetime(uccle['date'], format='%Y-%m')\nuccle.set_index('date', inplace=True)\n# uccle = uccle.loc['2000-01-01':'2018-12-01']\n\nprint('predictors', len(predictors), list(predictors))\n\n# # new predictors\n# # remove uccle missing dates:\n# print('setp.difference(setu)', setp.difference(setu))\n# print('setu.difference(setp)', setu.difference(setp))\n# removep = list(setp.difference(setu))\n# removeu = list(setu.difference(setp))\n# uccle = uccle.drop(removeu)\n# print('after uccle', len(uccle))\n# for j in range(len(removep)):\n# removep[j] = datetime.strptime(removep[j], '%Y-%m-%d')\n# predictors = predictors.drop(removep)\n# print('after pre', len(predictors))\n\n\n\nalt = [''] * 36\nuc = {}\nuct = {}\nuct_pre = {}\nuct_post = {}\n\nregression_output = [0] * 36\nuX = [0] * 36\nuY = [0] * 36\nparam_list = [0] * 36\nerror_list = [0] * 36\nut = [0]*36\n\ntrend_pre = [0]*36\ntrend_pre_err = [0]*36\ntrend_post = [0]*36\ntrend_post_err = [0]*36\n\ntrend_pre_rel = [0]*36\ntrend_pre_err_rel = [0]*36\ntrend_post_rel = [0]*36\ntrend_post_err_rel = [0]*36\n\nmY = []\n\nmean_pre = [0]*36\nmean_post = [0]*36\n\nfor irt in range(24,-12,-1):\n alt[24-irt] = str(irt) + 'km_ds' #w.r.t. tropopause\n mY.append(irt)\n\nprint('MY', len(mY), mY)\n\n\n# for i in range(36):\nfor i in range(24, -12, -1):\n\n print(i, mY[i], alt[i])\n uc[i] = uccle\n\n## why these dates 1977?\n # uct_pre[i] = uc[i].loc['1977-02-01':'1996-12-01']\n # uct_post[i] = uc[i].loc['2000-02-01':'2017-06-01']\n #uct[i] = uc[i].loc['1977-02-01':'2017-06-01']\n uct[i] = uc[i]\n\n predictors, uct[i] = pd.DataFrame.align(predictors, uct[i], axis=0)\n\n uY[i] = uct[i][alt[i]].values\n uX[i] = predictors.values\n\n # print(i, len(uX[i]), len(uY[i]) )\n\n # mean_pre[i] = np.nanmean(uct_pre[i][alt[i]].values)\n # mean_post[i] = np.nanmean(uct_post[i][alt[i]].values)\n\n\n regression_output[i] = mzm_regression(uX[i], uY[i])\n param_list[i] = dict(zip(list(predictors), regression_output[i]['gls_results'].params))\n error_list[i] = dict(zip(list(predictors), regression_output[i]['gls_results'].bse))\n\n ut[i] = uct[i].index\n\n ptitle = str(alt[i])\n pname = pre_name + tag + str(alt[i])\n if(i == 24): print(i, len(ut[i]), len(uY[i]), len(regression_output[i]))\n\n #plotmlr_perkm(ut[i], uY[i], regression_output[i]['fit_values'], ptitle, pname)\n\n # trend_pre[i] = param_list[i]['linear_pre']\n # trend_pre_err[i] = error_list[i]['linear_pre']\n # trend_post[i] = param_list[i]['linear_post']\n # trend_post_err[i] = error_list[i]['linear_post']\n\n trend_pre_rel[i] = param_list[i]['linear_pre_all'] *100\n trend_pre_err_rel[i] = 2 * error_list[i]['linear_pre_all'] *100\n # trend_post_rel[i] = param_list[i]['linear_post'] *100\n # trend_post_err_rel[i] = 2 * error_list[i]['linear_post'] *100\n\n # trend_post_rel[i] = param_list[i]['pwlt_pre'] *100\n # trend_post_err_rel[i] = 2 * error_list[i]['pwlt_pre'] *100\n\nprint('uccle', trend_post_rel)\nprint('uccle', trend_pre_rel)\n\nprint('paramlist', param_list)\nprint('errorlist', error_list)\n\nplt.close('all')\n\nfig, axr = plt.subplots()\nplt.title('Uccle 1969-2018')\nplt.xlabel('Ozone Trend [%/dec]')\nplt.ylabel('Altitude relative to the tropopause [km]')\nplt.xlim(-8,12)\nplt.ylim(-12,25)\n\naxr.axvline(x=0, color='grey', linestyle='--')\naxr.axhline(y=0, color='grey', linestyle=':')\n\naxr.tick_params(axis='both', which='both', direction='in')\naxr.yaxis.set_ticks_position('both')\naxr.xaxis.set_ticks_position('both')\naxr.yaxis.set_minor_locator(AutoMinorLocator(5))\naxr.xaxis.set_minor_locator(AutoMinorLocator(5))\naxr.set_xticks([-5,0,5,10])\n\n\n\neb1 = axr.errorbar(trend_pre_rel, mY, xerr= trend_pre_err_rel, label='pre-1997', color='red', linewidth=1,\n elinewidth=0.5, capsize=1.5, capthick=1)\neb1[-1][0].set_linestyle('--')\n\neb2 = axr.errorbar(trend_post_rel, mY, xerr= trend_post_err_rel, label='post-1997', color='limegreen', linewidth=1,\n elinewidth=0.5, capsize=1.5, capthick=1)\neb2[-1][0].set_linestyle('--')\n\naxr.legend(loc='upper right', frameon=True, fontsize='small')\n\nplname = plname\nplt.savefig('/home/poyraden/Analysis/MLR_Uccle/Plots/Uccle_50years_2/Uccle_' + plname + '.pdf')\nplt.savefig('/home/poyraden/Analysis/MLR_Uccle/Plots/Uccle_50years_2/Uccle_' + plname + '.eps')\n\n# plt.savefig('/home/poyraden/Analysis/MLR_Uccle/Plots/Uccle_Deseas_RelTropop_Extended/' + plname + '.pdf')\n# plt.savefig('/home/poyraden/Analysis/MLR_Uccle/Plots/Uccle_Deseas_RelTropop_Extended/' + plname + '.eps')\n\nplt.show()\nplt.close()","sub_path":"MLR_Uccle_reltropop.py","file_name":"MLR_Uccle_reltropop.py","file_ext":"py","file_size_in_byte":7145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"312245606","text":"\n# Copyright 2017-present Open Networking Foundation\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 json\nimport time\nimport os\nimport sys\nfrom synchronizers.new_base.eventstep import EventStep\nfrom synchronizers.new_base.modelaccessor import VOLTService, RCORDSubscriber, model_accessor\n\nclass SubscriberDhcpEventStep(EventStep):\n topics = [\"dhcp.events\"]\n technology = \"kafka\"\n\n def __init__(self, *args, **kwargs):\n super(SubscriberDhcpEventStep, self).__init__(*args, **kwargs)\n\n def get_onu_sn(self, event):\n olt_service = VOLTService.objects.first()\n onu_sn = olt_service.get_onu_sn_from_openflow(event[\"deviceId\"], event[\"portNumber\"])\n if not onu_sn or onu_sn is None:\n self.log.exception(\"dhcp.events: Cannot find onu serial number for this event\", kafka_event=event)\n raise Exception(\"dhcp.events: Cannot find onu serial number for this event\")\n\n return onu_sn\n\n def process_event(self, event):\n value = json.loads(event.value)\n\n onu_sn = self.get_onu_sn(value)\n\n subscriber = RCORDSubscriber.objects.get(onu_device=onu_sn)\n\n self.log.debug(\"dhcp.events: Got event for subscriber\", subscriber=subscriber, event_value=value, onu_sn=onu_sn)\n\n subscriber.ip_address = value[\"ipAddress\"]\n subscriber.mac_address = value[\"macAddress\"]\n subscriber.save()\n","sub_path":"xos/synchronizer/event_steps/dhcp_event.py","file_name":"dhcp_event.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"369486494","text":"# exttension to the model class to handle individual pieces\nfrom configurations import *\nimport exceptions\nimport sys\n\n# corresponding to the piece function returns the name of the piece\n# for ex - K => \"King, white\"\ndef create_piece(piece, color='white'):\n\tif isinstance(piece, str):\n\t\tif piece.upper() in SHORT_NAME.keys():\n\t\t\tcolor = \"white\" if piece.isupper() else \"black\"\n\t\t\tpiece = SHORT_NAME[piece.upper()]\n\t\tpiece = piece.capitalize()\n\t\tif piece in SHORT_NAME.values():\n\t\t\treturn eval(\"{classname}(color)\".format(classname=piece))\n\traise exceptions.ChessError(\"invalid piece name: '{}'\".format(piece))\n\ndef get_numeric_notation(rowcol):\n\trow, col = rowcol\n\treturn int(col)-1, X_AXIS_LABELS.index(row)\n\nclass Piece():\n\n\tdef __init__(self, color):\n\t\tself.name = self.__class__.__name__.lower()\n\t\tif color == 'black':\n\t\t\tself.name = self.name.lower()\n\t\telif color == 'white':\n\t\t\tself.name = self.name.upper()\n\t\tself.color = color\n\n\t# reference to the model class\n\tdef keep_reference(self, model):\n\t\tself.model = model\n\n\t# given current_position, directions adn distance this returns the list of \n\t# all valid moves on a chess piece\n\tdef moves_available(self, current_position, directions, distance):\n\t\tmodel = self.model\n\t\tallowed_moves = []\n\t\tpiece = self\n\t\tstart_row, start_column = get_numeric_notation(current_position)\n\t\tfor x, y in directions:\n\t\t\tcollision = False\n\t\t\tfor step in range(1, distance + 1):\n\t\t\t\tif collision:\n\t\t\t\t\tbreak\n\t\t\t\tdestination = start_row + step * x, start_column + step * y\n\t\t\t\tif self.possible_position(destination) not in model.all_occupied_positions():\n\t\t\t\t\tallowed_moves.append(destination)\n\t\t\t\telif self.possible_position(destination) in model.all_occupied_positions_occupied_by_color(piece.color):\n\t\t\t\t\tcollision = True\n\t\t\t\telse: \n\t\t\t\t\tcollision = True # we made a collision with opposite color\n\t\t\t\t\tallowed_moves.append(destination)\n\t\tallowed_moves = filter(model.is_on_board, allowed_moves)\n\t\treturn map(model.get_alphanumeric_position, allowed_moves)\n\n\tdef possible_position(self, destination):\n\t\treturn self.model.get_alphanumeric_position(destination)\n\nclass King(Piece):\n\t# max moves = 1\n\t# orthogonal movement = Allowed\n\t# diagonal movement = Allowed\n\tdirections = ORTHOGONAL_POSITIONS + DIAGONAL_POSITIONS\n\tmax_distance = 1\n\n\tdef moves_available(self, current_position):\n\t\treturn super().moves_available(current_position, self.directions, self.max_distance)\n\t\n\nclass Queen(Piece):\n\t# max moves = 8\n\t# orthogonal movement = Allowed\n\t# diagonal movement = Allowed\n\tdirections = ORTHOGONAL_POSITIONS + DIAGONAL_POSITIONS\n\tmax_distance = 8\n\n\tdef moves_available(self, current_position):\n\t\treturn super().moves_available(current_position, self.directions, self.max_distance)\n\nclass Rook(Piece):\n\t# max moves = 8\n\t# orthogonal movement = Allowed\n\t# diagonal movement = not allowed\n\tdirections = ORTHOGONAL_POSITIONS\n\tmax_distance = 8\n\n\tdef moves_available(self, current_position):\n\t\treturn super().moves_available(current_position, self.directions, self.max_distance)\n\nclass Bishop(Piece):\n\t# max moves = 8\n\t# orthogonal movement = not allowed\n\t# diagonal movement = Allowed\n\tdirections = DIAGONAL_POSITIONS\n\tmax_distance = 8\n\n\tdef moves_available(self, current_position):\n\t\treturn super().moves_available(current_position, self.directions, self.max_distance)\n\n# only knight can jump over others\nclass Knight(Piece):\n\t# moves in form 'L'\n\tdef moves_available(self, current_position):\n\t\tmodel = self.model\n\t\tallowed_moves = []\n\t\tstart_position = get_numeric_notation(current_position.upper())\n\t\tpiece = model.get(current_position)\n\t\tfor x, y in KNIGHT_POSITIONS:\n\t\t\tdestination = start_position[0] + x, start_position[1] + y\n\t\t\tif(model.get_alphanumeric_position(destination) not in model.all_occupied_positions_occupied_by_color(piece.color)):\n\t\t\t\tallowed_moves.append(destination)\n\t\tallowed_moves = filter(model.is_on_board, allowed_moves)\n\t\treturn map(model.get_alphanumeric_position, allowed_moves)\n\nclass Pawn(Piece):\n\t# max moves = 2 at start, then only 1 \n\t# orthogonal movement = Allowed\n\t# diagonal movement = not allowed but, captures diagonally.\n\tdef moves_available(self, current_position):\n\t\tmodel = self.model\n\t\tpiece = self\n\t\tif self.color == 'white':\n\t\t\tinitial_position, direction, enemy = 1, 1, 'black'\n\t\telse:\n\t\t\tinitial_position, direction, enemy = 6, -1, 'white'\n\t\tallowed_moves = []\n\t\t#moving\n\t\tprobhited = model.all_occupied_positions()\n\t\tstart_position = get_numeric_notation(current_position.upper())\n\t\tforward = start_position[0] + direction, start_position[1]\n\t\tif model.get_alphanumeric_position(forward) not in probhited:\n\t\t\tallowed_moves.append(forward)\n\t\t\t# If starting now then allow double moves also\n\t\t\tif start_position[0] == initial_position:\n\t\t\t\tdouble_forward = (forward[0] + direction, forward[1])\n\t\t\t\tif model.get_alphanumeric_position(double_forward) not in probhited:\n\t\t\t\t\tallowed_moves.append(double_forward)\n\n\t\t#attacking\n\t\tfor a in range(-1, 2, 2):\n\t\t\tattack = start_position[0] + direction, start_position[1] + a\n\t\t\tif model.get_alphanumeric_position(attack) in model.all_occupied_positions_occupied_by_color(enemy):\n\t\t\t\tallowed_moves.append(attack)\n\n\t\tallowed_moves = filter(model.is_on_board, allowed_moves)\n\t\treturn map(model.get_alphanumeric_position, allowed_moves)\n","sub_path":"piece.py","file_name":"piece.py","file_ext":"py","file_size_in_byte":5258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"276618341","text":"from __future__ import division\nfrom nltk import word_tokenize\nfrom sklearn.metrics import accuracy_score\nimport pandas as pd\nimport numpy as np\nimport re\nimport json\n\"\"\"\ndf = pd.read_csv('disaster_data.csv')\ndf.dropna(axis = 0, how = 'any')\ndata = []\ndf = df.reindex(np.random.permutation(df.index))\nfor index, row in df.iterrows():\n\tif type(row['Tweet']) == float or type(row['Label']) == float:\n\t\tcontinue\n\tdata.append([re.sub(r'[^a-zA-Z]', ' ', re.sub(r'@[0-9a-zA-Z]+', ' ', re.sub(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', \" \", row['Tweet']))).lower(), row['Label']])\n#df = df.sample(frac=1).reset_index(drop=True)\ntrain, test = data[7000:], data[:7000]\n\"\"\"\ndef load_data(filename):\n\ttest = []\n\twith open(filename) as infile:\n\t\ttest = json.load(infile)\n\treturn test\n\nclass Naive_Bayes_Classifier:\n\t\n\tdef __init__(self):\n\t\tself.c_k = {}\n\t\tself.c_k_w = {}\n\t\n\tdef train(self, train):\n\t\tself.vocab = set(word for passage in train for word in word_tokenize(passage[0]))\n\t\tself.data = [[word_tokenize(i[0]), i[1]] for i in train]\n\t\tself.types = list(set([i[1] for i in train]))\n\t\tfor i in self.data:\n\t\t\tif i[1] not in self.c_k:\n\t\t\t\tself.c_k[i[1]] = 1\n\t\t\telse:\n\t\t\t\tself.c_k[i[1]] += 1\n\t\tfor i in self.data:\n\t\t\tif i[1] not in self.c_k_w:\n\t\t\t\tself.c_k_w[i[1]] = {}\n\t\t\tfor j in i[0]:\n\t\t\t\tif j not in self.c_k_w[i[1]]:\n\t\t\t\t\tself.c_k_w[i[1]][j] = 1\n\t\t\t\telse:\n\t\t\t\t\tself.c_k_w[i[1]][j] += 1\n\n\tdef test(self, test_data, label_map):\n\t\tself.vocab = self.vocab.union(set(word for passage in test_data for word in word_tokenize(passage[0])))\n\t\ttest_data = [[word_tokenize(i[0]), i[1]] for i in test_data]\n\t\tfor key in self.c_k_w:\n\t\t\tfor l in self.vocab:\n\t\t\t\tif l not in self.c_k_w[key]:\n\t\t\t\t\tself.c_k_w[key][l] = 0\n\t\tresult = []\n\t\tsum_k = {}\n\t\tfor k in self.types:\n\t\t\tsum_k[k] = sum([self.c_k_w[k][l] for l in self.vocab])\n\t\tfor i in test_data:\n\t\t\tprob = []\n\t\t\tfor k in self.types:\n\t\t\t\tp_k = self.c_k[k] / sum([self.c_k[t] for t in self.types])\n\t\t\t\tp_k_w = 1\n\t\t\t\tfor w in i[0]:\n\t\t\t\t\ttemp = (self.c_k_w[k][w] + 1) / (sum_k[k] + len(self.vocab))\n\t\t\t\t\tp_k_w = p_k_w * temp\n\t\t\t\tprob.append(p_k * p_k_w)\n\t\t\tresult.append(label_map[self.types[np.argmax(prob)]])\n\t\tprint(\"Accuracy: {:.2%}\".format(accuracy_score(result, [i[1] for i in test_data])))\n\t\n\tdef load(self):\n\t\twith open('classifier_model/model.json') as infile:\n\t\t\tmodel = json.load(infile)\n\t\t\tself.c_k = model[\"c_k\"]\n\t\t\tself.c_k_w = model[\"c_k_w\"]\n\t\t\tself.vocab = set(model[\"vocab\"])\n\t\t\tself.data = model[\"data\"]\n\t\t\tself.types = model[\"types\"]\n\t\n\tdef save(self):\n\t\tmodel = {}\n\t\tmodel[\"c_k\"] = self.c_k\n\t\tmodel[\"c_k_w\"] = self.c_k_w\n\t\tmodel[\"vocab\"] = list(self.vocab)\n\t\tmodel[\"data\"] = self.data\n\t\tmodel[\"types\"] = self.types\n\t\twith open('classifier_model/model.json', 'w') as outfile:\n\t\t\tjson.dump(model, outfile)\n\n\n\n","sub_path":"NB_model.py","file_name":"NB_model.py","file_ext":"py","file_size_in_byte":2799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"34"} +{"seq_id":"250196987","text":"\"\"\"Unit tests for nautobot_golden_config.\"\"\"\nfrom django.contrib.auth import get_user_model\n\nfrom django.urls import reverse\nfrom rest_framework import status\n\nfrom nautobot.utilities.testing import APITestCase\n\nfrom .conftest import create_device, create_feature_rule_json, create_config_compliance\n\n\nUser = get_user_model()\n\n\nclass GoldenConfigAPITest(APITestCase): # pylint: disable=too-many-ancestors\n \"\"\"Test the ConfigCompliance API.\"\"\"\n\n def setUp(self):\n \"\"\"Create a superuser and token for API calls.\"\"\"\n super().setUp()\n self.device = create_device()\n self.compliance_rule_json = create_feature_rule_json(self.device)\n self.base_view = reverse(\"plugins-api:nautobot_golden_config-api:configcompliance-list\")\n\n def test_root(self):\n \"\"\"Validate the root for Nautobot Chatops API.\"\"\"\n url = reverse(\"plugins-api:nautobot_golden_config-api:api-root\")\n response = self.client.get(\"{}?format=api\".format(url), **self.header)\n self.assertEqual(response.status_code, 200)\n\n def test_device_list(self):\n \"\"\"Verify that devices can be listed.\"\"\"\n url = reverse(\"dcim-api:device-list\")\n self.add_permissions(\"dcim.view_device\")\n response = self.client.get(url, **self.header)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data[\"count\"], 1)\n\n def test_config_compliance_list_view(self):\n \"\"\"Verify that config compliance objects can be listed.\"\"\"\n actual = '{\"foo\": {\"bar-1\": \"baz\"}}'\n intended = '{\"foo\": {\"bar-2\": \"baz\"}}'\n create_config_compliance(\n self.device, actual=actual, intended=intended, compliance_rule=self.compliance_rule_json\n )\n self.add_permissions(\"nautobot_golden_config.view_configcompliance\")\n response = self.client.get(self.base_view, **self.header)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data[\"count\"], 1)\n\n def test_config_compliance_post_new_json_compliant(self):\n \"\"\"Verify that config compliance detail view.\"\"\"\n self.add_permissions(\"nautobot_golden_config.add_configcompliance\")\n response = self.client.post(\n self.base_view,\n data={\n \"device\": self.device.id,\n \"intended\": '{\"foo\": {\"bar-1\": \"baz\"}}',\n \"actual\": '{\"foo\": {\"bar-1\": \"baz\"}}',\n \"rule\": self.compliance_rule_json.id,\n },\n format=\"json\",\n **self.header,\n )\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertTrue(response.data[\"compliance\"])\n\n def test_config_compliance_post_new_json_not_compliant(self):\n \"\"\"Verify that config compliance detail view.\"\"\"\n self.add_permissions(\"nautobot_golden_config.add_configcompliance\")\n response = self.client.post(\n self.base_view,\n data={\n \"device\": self.device.id,\n \"intended\": '{\"foo\": {\"bar-1\": \"baz\"}}',\n \"actual\": '{\"foo\": {\"bar-2\": \"baz\"}}',\n \"rule\": self.compliance_rule_json.id,\n },\n format=\"json\",\n **self.header,\n )\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertFalse(response.data[\"compliance\"])\n","sub_path":"nautobot_golden_config/tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":3403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"34"} +{"seq_id":"580484","text":"import os\nfrom pyramid.config import Configurator\nimport pyramid_beaker\nfrom pyramid_jinja2 import renderer_factory\nfrom sqlalchemy import engine_from_config\nfrom canyin import router\nfrom canyin.common import mongodb\n\nfrom .models import (\n DBSession,\n Base,\n )\n\nPROJECT_PATH = os.path.abspath(os.path.dirname(__file__))\n\ndef main(global_config, **settings):\n \"\"\" This function returns a Pyramid WSGI application.\n \"\"\"\n engine = engine_from_config(settings, 'sqlalchemy.')\n DBSession.configure(bind=engine)\n Base.metadata.bind = engine\n config = Configurator(settings=settings)\n session_factory = pyramid_beaker.session_factory_from_settings (settings)\n config.set_session_factory (session_factory)\n pyramid_beaker.set_cache_regions_from_settings (settings)\n config.include('pyramid_jinja2')\n config.add_renderer('.html', renderer_factory)\n config.add_static_view('static', 'static', cache_max_age=3600)\n router.includeme(config)\n config.scan()\n mongodb.initialize_mongo_db(config, settings)\n return config.make_wsgi_app()\n","sub_path":"canyin/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"34"} +{"seq_id":"121357435","text":"import cherrypy\n\nfrom functools import wraps\n\nfrom social.utils import setting_name, module_member\nfrom social.strategies.utils import get_strategy\nfrom social.backends.utils import user_backends_data\n\n\nDEFAULTS = {\n 'STRATEGY': 'social.strategies.cherrypy_strategy.CherryPyStrategy',\n 'STORAGE': 'social.apps.cherrypy_app.models.CherryPyStorage'\n}\n\n\ndef get_helper(name, do_import=False):\n config = cherrypy.config.get(setting_name(name), DEFAULTS.get(name, None))\n return do_import and module_member(config) or config\n\n\ndef strategy(redirect_uri=None):\n def decorator(func):\n @wraps(func)\n def wrapper(self, backend=None, *args, **kwargs):\n uri = redirect_uri\n\n if uri and backend and '%(backend)s' in uri:\n uri = uri % {'backend': backend}\n\n backends = get_helper('AUTHENTICATION_BACKENDS')\n strategy = get_helper('STRATEGY')\n storage = get_helper('STORAGE')\n self.strategy = get_strategy(backends, strategy, storage,\n cherrypy.request, backend,\n redirect_uri=uri, *args, **kwargs)\n if backend:\n return func(self, backend=backend, *args, **kwargs)\n else:\n return func(self, *args, **kwargs)\n return wrapper\n return decorator\n\n\ndef backends(user):\n \"\"\"Load Social Auth current user data to context under the key 'backends'.\n Will return the output of social.backends.utils.user_backends_data.\"\"\"\n return user_backends_data(user, get_helper('AUTHENTICATION_BACKENDS'),\n get_helper('STORAGE', do_import=True))\n","sub_path":"python-social-auth/social/apps/cherrypy_app/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"34"} +{"seq_id":"44525084","text":"import socket\nimport threading\n\nport = input('Port: ')\ns = socket.socket()\nhost = socket.gethostname()\ns.bind((host, int(port)))\ns.listen(5)\nprint('Server created on IP: ' + socket.gethostbyname(host) + ' Port: ' + port)\nclients = []\n\ndef client(c, clients):\n while True:\n data = c.recv(1024).decode()\n data = usernames[c].decode() + ': ' + data\n for x in clients:\n if x != c:\n if testConnection(x, clients):\n x.send(data.encode())\n\ndef testConnection(client, clients):\n try:\n client.send(''.encode())\n return True\n except:\n print('Client Disconnected')\n clients.remove(client)\n return False\n\nusernames = {}\n\nwhile True:\n c, addr = s.accept()\n print('Got connection from', addr)\n clients.append(c)\n username = c.recv(1024)\n usernames[c] = username\n for x in clients:\n if testConnection(x, clients):\n x.send((username.decode() + ' connected.').encode())\n\n t = threading.Thread(target=client, args=(c, clients,))\n t.start()\nc.close()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"34"} +{"seq_id":"64092973","text":"# python3\n# Copyright 2021 InstaDeep Ltd. 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\"\"\"MADQN system implementation.\"\"\"\n\nimport functools\nfrom typing import Any, Callable, Dict, Optional, Type, Union\n\nimport acme\nimport dm_env\nimport launchpad as lp\nimport reverb\nimport sonnet as snt\nfrom acme import specs as acme_specs\nfrom acme.tf import utils as tf2_utils\nfrom acme.utils import counting\n\nimport mava\nfrom mava import core\nfrom mava import specs as mava_specs\nfrom mava.components.tf.architectures import DecentralisedValueActor\nfrom mava.components.tf.modules.communication import BaseCommunicationModule\nfrom mava.components.tf.modules.exploration import LinearExplorationScheduler\nfrom mava.components.tf.modules.stabilising import FingerPrintStabalisation\nfrom mava.environment_loop import ParallelEnvironmentLoop\nfrom mava.systems.tf import executors\nfrom mava.systems.tf import savers as tf2_savers\nfrom mava.systems.tf.madqn import builder, execution, training\nfrom mava.utils import lp_utils\nfrom mava.utils.loggers import MavaLogger, logger_utils\nfrom mava.wrappers import DetailedPerAgentStatistics\n\n\nclass MADQN:\n \"\"\"MADQN system.\"\"\"\n\n def __init__(\n self,\n environment_factory: Callable[[bool], dm_env.Environment],\n network_factory: Callable[[acme_specs.BoundedArray], Dict[str, snt.Module]],\n logger_factory: Callable[[str], MavaLogger] = None,\n architecture: Type[DecentralisedValueActor] = DecentralisedValueActor,\n trainer_fn: Union[\n Type[training.MADQNTrainer], Type[training.MADQNRecurrentTrainer]\n ] = training.MADQNTrainer,\n communication_module: Type[BaseCommunicationModule] = None,\n executor_fn: Type[core.Executor] = execution.MADQNFeedForwardExecutor,\n exploration_scheduler_fn: Type[\n LinearExplorationScheduler\n ] = LinearExplorationScheduler,\n replay_stabilisation_fn: Optional[Type[FingerPrintStabalisation]] = None,\n epsilon_min: float = 0.05,\n epsilon_decay: float = 1e-4,\n num_executors: int = 1,\n num_caches: int = 0,\n environment_spec: mava_specs.MAEnvironmentSpec = None,\n shared_weights: bool = True,\n batch_size: int = 256,\n prefetch_size: int = 4,\n min_replay_size: int = 1000,\n max_replay_size: int = 1000000,\n samples_per_insert: Optional[float] = 32.0,\n n_step: int = 5,\n sequence_length: int = 20,\n period: int = 20,\n max_gradient_norm: float = None,\n discount: float = 0.99,\n optimizer: Union[snt.Optimizer, Dict[str, snt.Optimizer]] = snt.optimizers.Adam(\n learning_rate=1e-4\n ),\n target_update_period: int = 100,\n executor_variable_update_period: int = 1000,\n max_executor_steps: int = None,\n checkpoint: bool = True,\n checkpoint_subpath: str = \"~/mava/\",\n logger_config: Dict = {},\n train_loop_fn: Callable = ParallelEnvironmentLoop,\n eval_loop_fn: Callable = ParallelEnvironmentLoop,\n train_loop_fn_kwargs: Dict = {},\n eval_loop_fn_kwargs: Dict = {},\n ):\n \"\"\"Initialise the system\n\n Args:\n environment_factory (Callable[[bool], dm_env.Environment]): function to\n instantiate an environment.\n network_factory (Callable[[acme_specs.BoundedArray],\n Dict[str, snt.Module]]): function to instantiate system networks.\n logger_factory (Callable[[str], MavaLogger], optional): function to\n instantiate a system logger. Defaults to None.\n architecture (Type[DecentralisedValueActor], optional): system architecture,\n e.g. decentralised or centralised. Defaults to DecentralisedValueActor.\n trainer_fn (Union[ Type[training.MADQNTrainer],\n Type[training.MADQNRecurrentTrainer] ], optional): training type\n associated with executor and architecture, e.g. centralised training.\n Defaults to training.MADQNTrainer.\n communication_module (Type[BaseCommunicationModule], optional):\n module for enabling communication protocols between agents. Defaults to\n None.\n executor_fn (Type[core.Executor], optional): executor type, e.g.\n feedforward or recurrent. Defaults to\n execution.MADQNFeedForwardExecutor.\n exploration_scheduler_fn (Type[ LinearExplorationScheduler ], optional):\n function specifying a decaying scheduler for epsilon exploration.\n Defaults to LinearExplorationScheduler.\n replay_stabilisation_fn (Optional[Type[FingerPrintStabalisation]],\n optional): replay buffer stabilisaiton function, e.g. fingerprints.\n Defaults to None.\n epsilon_min (float, optional): final minimum epsilon value at the end of a\n decaying schedule. Defaults to 0.05.\n epsilon_decay (float, optional): epsilon decay rate. Defaults to 1e-4.\n num_executors (int, optional): number of executor processes to run in\n parallel. Defaults to 1.\n num_caches (int, optional): number of trainer node caches. Defaults to 0.\n environment_spec (mava_specs.MAEnvironmentSpec, optional): description of\n the action, observation spaces etc. for each agent in the system.\n Defaults to None.\n shared_weights (bool, optional): whether agents should share weights or not.\n Defaults to True.\n batch_size (int, optional): sample batch size for updates. Defaults to 256.\n prefetch_size (int, optional): size to prefetch from replay. Defaults to 4.\n min_replay_size (int, optional): minimum replay size before updating.\n Defaults to 1000.\n max_replay_size (int, optional): maximum replay size. Defaults to 1000000.\n samples_per_insert (Optional[float], optional): number of samples to take\n from replay for every insert that is made. Defaults to 32.0.\n n_step (int, optional): number of steps to include prior to boostrapping.\n Defaults to 5.\n sequence_length (int, optional): recurrent sequence rollout length. Defaults\n to 20.\n period (int, optional): consecutive starting points for overlapping\n rollouts across a sequence. Defaults to 20.\n max_gradient_norm (float, optional): maximum allowed norm for gradients\n before clipping is applied. Defaults to None.\n discount (float, optional): discount factor to use for TD updates. Defaults\n to 0.99.\n optimizer (Union[snt.Optimizer, Dict[str, snt.Optimizer]], optional):\n type of optimizer to use to update network parameters. Defaults to\n snt.optimizers.Adam( learning_rate=1e-4 ).\n target_update_period (int, optional): number of steps before target\n networks are updated. Defaults to 100.\n executor_variable_update_period (int, optional): number of steps before\n updating executor variables from the variable source. Defaults to 1000.\n max_executor_steps (int, optional): maximum number of steps and executor\n can in an episode. Defaults to None.\n checkpoint (bool, optional): whether to checkpoint models. Defaults to\n False.\n checkpoint_subpath (str, optional): subdirectory specifying where to store\n checkpoints. Defaults to \"~/mava/\".\n logger_config (Dict, optional): additional configuration settings for the\n logger factory. Defaults to {}.\n train_loop_fn (Callable, optional): function to instantiate a train loop.\n Defaults to ParallelEnvironmentLoop.\n eval_loop_fn (Callable, optional): function to instantiate an evaluation\n loop. Defaults to ParallelEnvironmentLoop.\n train_loop_fn_kwargs (Dict, optional): possible keyword arguments to send\n to the training loop. Defaults to {}.\n eval_loop_fn_kwargs (Dict, optional): possible keyword arguments to send to\n the evaluation loop. Defaults to {}.\n \"\"\"\n\n if not environment_spec:\n environment_spec = mava_specs.MAEnvironmentSpec(\n environment_factory(evaluation=False) # type:ignore\n )\n\n # set default logger if no logger provided\n if not logger_factory:\n logger_factory = functools.partial(\n logger_utils.make_logger,\n directory=\"~/mava\",\n to_terminal=True,\n time_delta=10,\n )\n\n self._architecture = architecture\n self._communication_module_fn = communication_module\n self._environment_factory = environment_factory\n self._network_factory = network_factory\n self._logger_factory = logger_factory\n self._environment_spec = environment_spec\n self._shared_weights = shared_weights\n self._num_exectors = num_executors\n self._num_caches = num_caches\n self._max_executor_steps = max_executor_steps\n self._checkpoint_subpath = checkpoint_subpath\n self._checkpoint = checkpoint\n self._logger_config = logger_config\n self._train_loop_fn = train_loop_fn\n self._train_loop_fn_kwargs = train_loop_fn_kwargs\n self._eval_loop_fn = eval_loop_fn\n self._eval_loop_fn_kwargs = eval_loop_fn_kwargs\n\n if issubclass(executor_fn, executors.RecurrentExecutor):\n extra_specs = self._get_extra_specs()\n else:\n extra_specs = {}\n\n self._builder = builder.MADQNBuilder(\n builder.MADQNConfig(\n environment_spec=environment_spec,\n epsilon_min=epsilon_min,\n epsilon_decay=epsilon_decay,\n shared_weights=shared_weights,\n discount=discount,\n batch_size=batch_size,\n prefetch_size=prefetch_size,\n target_update_period=target_update_period,\n executor_variable_update_period=executor_variable_update_period,\n min_replay_size=min_replay_size,\n max_replay_size=max_replay_size,\n samples_per_insert=samples_per_insert,\n n_step=n_step,\n sequence_length=sequence_length,\n period=period,\n max_gradient_norm=max_gradient_norm,\n checkpoint=checkpoint,\n optimizer=optimizer,\n checkpoint_subpath=checkpoint_subpath,\n ),\n trainer_fn=trainer_fn,\n executor_fn=executor_fn,\n extra_specs=extra_specs,\n exploration_scheduler_fn=exploration_scheduler_fn,\n replay_stabilisation_fn=replay_stabilisation_fn,\n )\n\n def _get_extra_specs(self) -> Any:\n \"\"\"helper to establish specs for extra information\n\n Returns:\n Dict[str, Any]: dictionary containing extra specs\n \"\"\"\n\n agents = self._environment_spec.get_agent_ids()\n core_state_specs = {}\n core_message_specs = {}\n\n networks = self._network_factory( # type: ignore\n environment_spec=self._environment_spec\n )\n for agent in agents:\n agent_type = agent.split(\"_\")[0]\n core_state_specs[agent] = (\n tf2_utils.squeeze_batch_dim(\n networks[\"q_networks\"][agent_type].initial_state(1)\n ),\n )\n if self._communication_module_fn is not None:\n core_message_specs[agent] = (\n tf2_utils.squeeze_batch_dim(\n networks[\"q_networks\"][agent_type].initial_message(1)\n ),\n )\n\n extras = {\n \"core_states\": core_state_specs,\n \"core_messages\": core_message_specs,\n }\n return extras\n\n def replay(self) -> Any:\n \"\"\"Replay data storage.\n\n Returns:\n Any: replay data table built according the environment specification.\n \"\"\"\n\n return self._builder.make_replay_tables(self._environment_spec)\n\n def counter(self, checkpoint: bool) -> Any:\n \"\"\"Step counter\n\n Args:\n checkpoint (bool): whether to checkpoint the counter.\n\n Returns:\n Any: checkpointing object logging steps in a counter subdirectory.\n \"\"\"\n\n if checkpoint:\n return tf2_savers.CheckpointingRunner(\n counting.Counter(),\n time_delta_minutes=15,\n directory=self._checkpoint_subpath,\n subdirectory=\"counter\",\n )\n else:\n return counting.Counter()\n\n def coordinator(self, counter: counting.Counter) -> Any:\n \"\"\"Coordination helper for a distributed program\n\n Args:\n counter (counting.Counter): step counter object.\n\n Returns:\n Any: step limiter object.\n \"\"\"\n\n return lp_utils.StepsLimiter(counter, self._max_executor_steps) # type: ignore\n\n def trainer(\n self,\n replay: reverb.Client,\n counter: counting.Counter,\n ) -> mava.core.Trainer:\n \"\"\"System trainer\n\n Args:\n replay (reverb.Client): replay data table to pull data from.\n counter (counting.Counter): step counter object.\n\n Returns:\n mava.core.Trainer: system trainer.\n \"\"\"\n\n # Create the networks to optimize (online)\n networks = self._network_factory( # type: ignore\n environment_spec=self._environment_spec, shared_weights=self._shared_weights\n )\n\n # Create system architecture with target networks.\n architecture = self._architecture(\n environment_spec=self._environment_spec,\n value_networks=networks[\"q_networks\"],\n shared_weights=self._shared_weights,\n )\n\n if self._builder._replay_stabiliser_fn is not None:\n architecture = self._builder._replay_stabiliser_fn( # type: ignore\n architecture\n )\n\n communication_module = None\n if self._communication_module_fn is not None:\n communication_module = self._communication_module_fn(\n architecture=architecture,\n shared=True,\n channel_size=1,\n channel_noise=0,\n )\n system_networks = communication_module.create_system()\n else:\n system_networks = architecture.create_system()\n\n # create logger\n trainer_logger_config = {}\n if self._logger_config and \"trainer\" in self._logger_config:\n trainer_logger_config = self._logger_config[\"trainer\"]\n trainer_logger = self._logger_factory( # type: ignore\n \"trainer\", **trainer_logger_config\n )\n\n dataset = self._builder.make_dataset_iterator(replay)\n counter = counting.Counter(counter, \"trainer\")\n\n return self._builder.make_trainer(\n networks=system_networks,\n dataset=dataset,\n counter=counter,\n communication_module=communication_module,\n logger=trainer_logger,\n )\n\n def executor(\n self,\n executor_id: str,\n replay: reverb.Client,\n variable_source: acme.VariableSource,\n counter: counting.Counter,\n trainer: Optional[training.MADQNTrainer] = None,\n ) -> mava.ParallelEnvironmentLoop:\n \"\"\"System executor\n\n Args:\n executor_id (str): id to identify the executor process for logging purposes.\n replay (reverb.Client): replay data table to push data to.\n variable_source (acme.VariableSource): variable server for updating\n network variables.\n counter (counting.Counter): step counter object.\n trainer (Optional[training.MADQNRecurrentCommTrainer], optional):\n system trainer. Defaults to None.\n\n Returns:\n mava.ParallelEnvironmentLoop: environment-executor loop instance.\n \"\"\"\n\n # Create the behavior policy.\n networks = self._network_factory( # type: ignore\n environment_spec=self._environment_spec, shared_weights=self._shared_weights\n )\n\n # Create system architecture with target networks.\n architecture = self._architecture(\n environment_spec=self._environment_spec,\n value_networks=networks[\"q_networks\"],\n shared_weights=self._shared_weights,\n )\n\n if self._builder._replay_stabiliser_fn is not None:\n architecture = self._builder._replay_stabiliser_fn( # type: ignore\n architecture\n )\n\n communication_module = None\n if self._communication_module_fn is not None:\n communication_module = self._communication_module_fn(\n architecture=architecture,\n shared=True,\n channel_size=1,\n channel_noise=0,\n )\n system_networks = communication_module.create_system()\n else:\n system_networks = architecture.create_system()\n\n # Create the executor.\n executor = self._builder.make_executor(\n q_networks=system_networks[\"values\"],\n action_selectors=networks[\"action_selectors\"],\n communication_module=communication_module,\n adder=self._builder.make_adder(replay),\n variable_source=variable_source,\n trainer=trainer,\n )\n\n # TODO (Arnu): figure out why factory function are giving type errors\n # Create the environment.\n environment = self._environment_factory(evaluation=False) # type: ignore\n\n # Create logger and counter; actors will not spam bigtable.\n counter = counting.Counter(counter, \"executor\")\n\n # Create executor logger\n executor_logger_config = {}\n if self._logger_config and \"executor\" in self._logger_config:\n executor_logger_config = self._logger_config[\"executor\"]\n exec_logger = self._logger_factory( # type: ignore\n f\"executor_{executor_id}\", **executor_logger_config\n )\n\n # Create the loop to connect environment and executor.\n train_loop = self._train_loop_fn(\n environment,\n executor,\n counter=counter,\n logger=exec_logger,\n **self._train_loop_fn_kwargs,\n )\n\n train_loop = DetailedPerAgentStatistics(train_loop)\n\n return train_loop\n\n def evaluator(\n self,\n variable_source: acme.VariableSource,\n counter: counting.Counter,\n trainer: training.MADQNTrainer,\n ) -> Any:\n \"\"\"System evaluator (an executor process not connected to a dataset)\n\n Args:\n variable_source (acme.VariableSource): variable server for updating\n network variables.\n counter (counting.Counter): step counter object.\n trainer (Optional[training.MADQNRecurrentCommTrainer], optional):\n system trainer. Defaults to None.\n\n Returns:\n Any: environment-executor evaluation loop instance for evaluating the\n performance of a system.\n \"\"\"\n\n # Create the behavior policy.\n networks = self._network_factory( # type: ignore\n environment_spec=self._environment_spec, shared_weights=self._shared_weights\n )\n\n # Create system architecture with target networks.\n architecture = self._architecture(\n environment_spec=self._environment_spec,\n value_networks=networks[\"q_networks\"],\n shared_weights=self._shared_weights,\n )\n\n if self._builder._replay_stabiliser_fn is not None:\n architecture = self._builder._replay_stabiliser_fn( # type: ignore\n architecture\n )\n\n communication_module = None\n if self._communication_module_fn is not None:\n communication_module = self._communication_module_fn(\n architecture=architecture,\n shared=True,\n channel_size=1,\n channel_noise=0,\n )\n system_networks = communication_module.create_system()\n else:\n system_networks = architecture.create_system()\n\n # Create the agent.\n executor = self._builder.make_executor(\n q_networks=system_networks[\"values\"],\n action_selectors=networks[\"action_selectors\"],\n variable_source=variable_source,\n communication_module=communication_module,\n trainer=trainer,\n evaluator=True,\n )\n\n # Make the environment.\n environment = self._environment_factory(evaluation=True) # type: ignore\n\n # Create logger and counter.\n counter = counting.Counter(counter, \"evaluator\")\n evaluator_logger_config = {}\n if self._logger_config and \"evaluator\" in self._logger_config:\n evaluator_logger_config = self._logger_config[\"evaluator\"]\n eval_logger = self._logger_factory( # type: ignore\n \"evaluator\", **evaluator_logger_config\n )\n\n # Create the run loop and return it.\n # Create the loop to connect environment and executor.\n eval_loop = self._eval_loop_fn(\n environment,\n executor,\n counter=counter,\n logger=eval_logger,\n **self._eval_loop_fn_kwargs,\n )\n\n eval_loop = DetailedPerAgentStatistics(eval_loop)\n return eval_loop\n\n def build(self, name: str = \"madqn\") -> Any:\n \"\"\"Build the distributed system as a graph program.\n\n Args:\n name (str, optional): system name. Defaults to \"madqn\".\n\n Returns:\n Any: graph program for distributed system training.\n \"\"\"\n\n program = lp.Program(name=name)\n\n with program.group(\"replay\"):\n replay = program.add_node(lp.ReverbNode(self.replay))\n\n with program.group(\"counter\"):\n counter = program.add_node(lp.CourierNode(self.counter, self._checkpoint))\n\n if self._max_executor_steps:\n with program.group(\"coordinator\"):\n _ = program.add_node(lp.CourierNode(self.coordinator, counter))\n\n with program.group(\"trainer\"):\n trainer = program.add_node(lp.CourierNode(self.trainer, replay, counter))\n\n with program.group(\"evaluator\"):\n program.add_node(lp.CourierNode(self.evaluator, trainer, counter, trainer))\n\n if not self._num_caches:\n # Use the trainer as a single variable source.\n sources = [trainer]\n else:\n with program.group(\"cacher\"):\n # Create a set of trainer caches.\n sources = []\n for _ in range(self._num_caches):\n cacher = program.add_node(\n lp.CacherNode(\n trainer, refresh_interval_ms=2000, stale_after_ms=4000\n )\n )\n sources.append(cacher)\n\n with program.group(\"executor\"):\n # Add executors which pull round-robin from our variable sources.\n for executor_id in range(self._num_exectors):\n source = sources[executor_id % len(sources)]\n program.add_node(\n lp.CourierNode(\n self.executor,\n executor_id,\n replay,\n source,\n counter,\n trainer,\n )\n )\n\n return program\n","sub_path":"multi-agent RL/Mava-develop/mava/systems/tf/madqn/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":24597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"77714778","text":"import os\nos.environ['CUDA_VISIBLE_DEVICES'] = '-1'\nos.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'\n# os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\nfrom Experiments import Experiments, Experiment\nimport argparse\n\nfrom classifiers import LRClassifier, NNClassifier, ElementPredictor, NodeClassifier\nimport tensorflow as tf; tf.get_logger().setLevel('ERROR')\nimport numpy as np\nfrom copy import deepcopy\n\nparser = argparse.ArgumentParser(description=\"\"\"\napicall creates an experiment where we try to predict the exstense of \"next call\" link between nodes. \n Currently, the process is trained using negative sampling procedure and additional classifier. Negative sampling \n is done uniformly form the collection of all the rest of the nodes. The number of negative samples is the batch is \n equal to the number of positive samples. The embeddigns themselves are not trained, only weights of classifier are \n updated. \n\"\"\")\n# parser.add_argument('experiment', default=None,\n# help='Select experiment [apicall|link|typeuse|varuse|fname|nodetype]')\nparser.add_argument(\"--base_path\", default=None, help=\"path to the trained GNN model\")\nparser.add_argument('--random', action='store_true')\nargs = parser.parse_args()\n\n# GAT\n# BASE_PATH = \"models/GAT-2020-05-05-17-23-39-269036-fname\" # trained on function names\n# BASE_PATH = \"models/GAT-2020-05-05-01-25-38-208819-varnames\" # trained on variable names\n# BASE_PATH = \"models/GAT-2020-05-04-01-25-52-792623-nextcall\" # trained on next call\n# BASE_PATH = \"models/GAT-2020-05-10-23-27-05-982293-multitask\"\n\n# RGCN\n# BASE_PATH = \"models/RGCN-2020-05-09-16-43-46-984454-fname-edgetype\" # trained on function names\n# BASE_PATH = \"models/RGCN-2020-05-08-21-35-13-542497-varname-edgetype\" # trained on variable names\n# BASE_PATH = \"models/RGCN-2020-05-06-19-53-15-933048-nextcall-edgetypes\" # trained on next call\n# BASE_PATH = \"models/RGCN-2020-05-11-10-14-50-783337-multitask\"\nBASE_PATH = \"models/RGCN-2020-05-11-20-34-49-002750-multitask-5layers\"\n\n# data files\nAPI_SEQ = \"data_files/python_flat_calls.csv.bz2\"\nVAR_USE = \"data_files/python_node_to_var.csv.bz2\"\n\ne = Experiments(base_path=BASE_PATH,\n api_seq_path=API_SEQ,\n type_use_path=None, #not needed\n node_type_path=None, #not needed\n variable_use_path=VAR_USE, #not needed\n function_name_path=None,\n gnn_layer=-1\n )\n\n# if args.random:\n# e.embed.e = np.random.randn(e.embed.e.shape[0], e.embed.e.shape[1])\n\n# EXPERIMENT_NAME = args.experiment\n\ndef run_experiment(EXPERIMENT_NAME, random=False):\n experiment = e[EXPERIMENT_NAME]\n\n ma_train = 0.\n ma_test = 0.\n ma_alpha = 2 / (10 + 1)\n\n if random:\n experiment.embed.e = deepcopy(experiment.embed.e)\n experiment.embed.e = np.random.randn(experiment.embed.e.shape[0], experiment.embed.e.shape[1])\n\n if EXPERIMENT_NAME in {'link', 'apicall', 'typeuse'}:\n clf = NNClassifier(experiment.embed_size)\n elif EXPERIMENT_NAME in {'varuse', 'fname'}:\n clf = ElementPredictor(experiment.embed_size, experiment.unique_elements, 100)\n elif EXPERIMENT_NAME in {'nodetype'}:\n clf = NodeClassifier(experiment.embed_size, experiment.unique_elements)\n else:\n raise ValueError(f\"Unknown experiment: {type}. The following experiments are available: [apicall|link|typeuse|varuse|fname|nodetype].\")\n\n # clf.compile(optimizer='adam',\n # loss='sparse_categorical_crossentropy')\n\n loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)\n\n train_loss = tf.keras.metrics.Mean(name='train_loss')\n train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')\n\n test_loss = tf.keras.metrics.Mean(name='test_loss')\n test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')\n\n @tf.function\n def train_step(batch):\n with tf.GradientTape() as tape:\n # training=True is only needed if there are layers with different\n # behavior during training versus inference (e.g. Dropout).\n predictions = clf(**batch, training=True)\n loss = loss_object(batch[\"y\"], predictions)\n gradients = tape.gradient(loss, clf.trainable_variables)\n optimizer.apply_gradients(zip(gradients, clf.trainable_variables))\n\n train_loss(loss)\n train_accuracy(batch[\"y\"], predictions)\n\n @tf.function\n def test_step(batch):\n # training=False is only needed if there are layers with different\n # behavior during training versus inference (e.g. Dropout).\n predictions = clf(**batch, training=False)\n t_loss = loss_object(batch[\"y\"], predictions)\n\n test_loss(t_loss)\n test_accuracy(batch[\"y\"], predictions)\n\n EPOCHS = 500\n\n # print(f\"\\n\\n\\nExperiment name: {EXPERIMENT_NAME}\")\n tests = []\n\n for epoch in range(EPOCHS):\n # Reset the metrics at the start of the next epoch\n train_loss.reset_states()\n train_accuracy.reset_states()\n test_loss.reset_states()\n test_accuracy.reset_states()\n\n\n for batch_ind, batch in enumerate(experiment.train_batches()):\n train_step(batch)\n\n if epoch % 1 == 0:\n\n for batch in experiment.test_batches():\n test_step(batch)\n\n ma_train = train_accuracy.result() * 100 * ma_alpha + ma_train * (1 - ma_alpha)\n ma_test = test_accuracy.result() * 100 * ma_alpha + ma_test * (1 - ma_alpha)\n tests.append(ma_test)\n\n # template = 'Epoch {}, Loss: {:.4f}, Accuracy: {:.4f}, Test Loss: {:.4f}, Test Accuracy: {:.4f}, Average Test {:.4f}'\n # print(template.format(epoch+1,\n # train_loss.result(),\n # train_accuracy.result()*100,\n # test_loss.result(),\n # test_accuracy.result()*100,\n # ma_test))\n\n # ma_train = train_accuracy.result() * 100 * ma_alpha + ma_train * (1 - ma_alpha)\n # ma_test = test_accuracy.result() * 100 * ma_alpha + ma_test * (1 - ma_alpha)\n\n return ma_train, max(tests)\n\nfor experiment_name in ['apicall','link','typeuse','varuse','fname','nodetype']:\n print(f\"\\n{experiment_name}:\")\n train_acc, test_acc = run_experiment(experiment_name, random=args.random)\n print(\"Train Accuracy: {:.4f}, Test Accuracy: {:.4f}\".format(train_acc, test_acc))\n # train_acc, test_acc = run_experiment(experiment_name, random=True)\n # print(\"Random Train Accuracy: {:.4f}, Test Accuracy: {:.4f}\".format(train_acc, test_acc))\n print(\"\\n\")","sub_path":"graph-network/run_experiment.py","file_name":"run_experiment.py","file_ext":"py","file_size_in_byte":6776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"558909785","text":"import os\nimport random\nfrom shutil import copyfile\n\nrootimg = './data/shapenetcore/masks'\nrootvol = './data/shapenetcore/masks'\n\nn_views=4\npath='data/subdatasets/shapenetcore_{}/masks'.format(n_views)\n\nfor cat in ['03001627', '04090263']:\n#for cat in os.listdir(rootimg):\n dir_img = os.path.join(rootimg, cat)\n for fn in os.listdir(dir_img):\n dst = os.path.join(path, cat, fn)\n os.makedirs(dst)\n N = random.sample(range(0, 9), n_views)\n for n in N:\n copyfile(os.path.join(dir_img, fn, 'v{}.png'.format(n)), os.path.join(dst, 'v{}.png'.format(n)))\n \n \n","sub_path":"create_subdataset.py","file_name":"create_subdataset.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"583507095","text":"import ftplib\nimport os\nimport zipfile\nimport sys\nimport time\nimport fnmatch\nfrom multiprocessing.pool import ThreadPool\nimport concurrent.futures\nfrom ETL.models import ExtractInfo, Source\n\n\nclass extract:\n\n def connection(self, url, user, password):\n self.ftp = ftplib.FTP(url)\n print(self.ftp.getwelcome())\n self.ftp.login(user, password)\n\n def paths(self, destination_path, local_path):\n self.ftp.cwd(destination_path)\n self.savedir = local_path\n os.chdir(self.savedir)\n\n def file_filters(self, fnbase_example):\n\n self.filematch = fnbase_example\n\n def downland_files(self, session_id):\n downloaded = []\n files = ExtractInfo.objects.filter(\n sessionID=session_id).values('fileName')\n source = Source.objects.get(source_id=session_id)\n\n for filename in self.ftp.nlst(self.filematch):\n\n if (checkFile(filename, files)):\n start = time.time()\n fhandle = open(filename, 'wb')\n print('Getting ' + filename)\n self.ftp.retrbinary('RETR ' + filename, fhandle.write)\n fhandle.close()\n downloaded.append(filename)\n\n end = time.time()\n\n durations = end - start\n size = int(os.stat(filename).st_size/1024)\n\n ExtractInfo.objects.create(\n fileName=filename,\n during=round(durations, 3),\n size=size,\n sessionID=source)\n\n\ndef checkFile(filename, files):\n for i in files:\n if i['fileName'] == filename:\n return False\n return True\n\n # extractClass = extract()\n # extractClass.connection(\"127.0.0.1\", \"murat\",\n # \"4747.Murat\") # URL, User and Password\n # # Destination path, local path\n # extractClass.paths(\"/\", \"c:\\\\Users\\\\murat\\\\Desktop\\\\CV\\\\\")\n # extractClass.file_filters(\"*.docx\") # Regex (Regular Expression)\n # extractClass.downland_files()\n","sub_path":"backend/ETL/actions/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"332744996","text":"## @package main_example_shooting_twobody\n# \\brief Main file for two-body orbit transfer problem setup\n# \\details Example shooting method using scipy.optimize and using the\n# method of particular solutions.\n# \\author Robyn Woollands\n# \\pre numpy, const.py\n# \\bug No bugs known\n\nimport pandas as pd\nfrom mpl_toolkits import mplot3d\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import minimize\nimport spiceypy as sp\nfrom scipy.integrate import solve_ivp as integrator\nfrom mpl_toolkits import mplot3d\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nimport const as cn\nimport sys\nfrom mps import mps_twobody\nfrom eom import eom_twobody\n# import plotly.express as px\n\ndef residuals(v0,tspan,states0,statesf):\n \"\"\"\n Computes error between current final state and desired final state for the\n Keplerian Lambert type problem. This is a numerical method not an analytic\n Lambert solver.\n Parameters:\n ===========\n v0 -- current initial velocity\n tspan -- vector containing initial and final time\n states0 -- initial states\n statesf -- final states\n Returns:\n ========\n res -- residual\n External:\n =========\n numpy, scipy.integrate\n \"\"\"\n states_in = np.zeros(6)\n states_in[0:3] = states0[0:3]\n states_in[3:6] = v0[0:3]\n sol = integrator(eom_twobody,(tspan[0],tspan[-1]),states_in,method='LSODA',rtol=1e-12)\n res = np.linalg.norm(statesf[0:3] - sol.y[0:3,-1])/cn.DU\n return res\n\n# Initial & Final Conditions\nsma = 8000\necc = 0\nrp = sma*(1-ecc)\nP = 2*np.pi*np.sqrt(sma**3 / cn.mu)\ntspan = np.array([0, 0.8*P])\nelm0 = np.array([rp, ecc, np.deg2rad(10), np.deg2rad(0), np.deg2rad(0), np.deg2rad(0), 0, cn.mu])\nstates0 = sp.conics(elm0,0)\nsma = sma + 100;\nrp = sma*(1-ecc)\nelm1 = np.array([rp, ecc, np.deg2rad(10), np.deg2rad(0), np.deg2rad(0), np.deg2rad(0), 0, cn.mu])\nstates1 = sp.conics(elm1,0)\nstatesf = sp.prop2b(cn.mu,states1,tspan[-1])\n\n# Method of Particular Solutions Shooting Method\n[v0,mps_err] = mps_twobody(tspan,states0,statesf)\nprint(\"mps err:\",mps_err)\nstates0_new = np.zeros(6)\nstates0_new[0:3] = states0[0:3]\nstates0_new[3:6] = v0[0:3]\n\n# Scipy's Optimize\nv0_guess = states0[3:6]\noptres = minimize(residuals,v0_guess[0:3],args=(tspan,states0,statesf),method='Nelder-Mead',tol=1e-13)\nstates0_new = np.zeros(6)\nstates0_new[0:3] = states0[0:3]\nstates0_new[3:6] = optres.x[0:3]\nprint(\"opt_err:\",optres.fun)\n\n# Check Solution\nsol = integrator(eom_twobody,(tspan[0],tspan[-1]),states0_new,method='LSODA',rtol=1e-12)\n\n# Plot\nfig = plt.figure()\nax = plt.axes(projection='3d')\nax.plot3D(sol.y[0,:],sol.y[1,:],sol.y[2,:])\nax.scatter3D(states0[0],states0[1],states0[2],'r')\nax.scatter3D(statesf[0],statesf[1],statesf[2],'g')\nplt.show()\n\n# import pandas as pd\n# statesdf=pd.DataFrame([states0,statesf] ,columns=['x','y','z','vx','vy','vz'])\n# statesdf['cat']=['s','f']\n# soldf=pd.DataFrame(sol.y.T ,columns=['x','y','z','vx','vy','vz'])\n# soldf['cat']='o'\n# soldf2=pd.concat([soldf,statesdf]).reset_index(drop=True)\n# print(soldf2)\n# fig = px.scatter_3d(soldf2,x='x', y='y', z='z',color='cat')\n# fig.show()\n","sub_path":"SpaceTelescopeRefueling/source/main_example_shooting_twobody.py","file_name":"main_example_shooting_twobody.py","file_ext":"py","file_size_in_byte":3175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"230536233","text":"#!/usr/bin/python\r\n# -*- coding:utf-8 -*-\r\n\r\nimport socket\r\nHOST = '10.10.160.77'\r\nPORT = 9010\r\n\r\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\ns.connect((HOST, PORT))\r\n\r\n# while True:\r\n\r\n\r\ncmd = input(\"Please input msg:\")\r\ntry:\r\n print ('send')\r\n s.send(cmd.encode())\r\n print ('send finish')\r\n data = s.recv(1024)\r\n print (data)\r\nexcept socket.error as e:\r\n print ('xxxxxxxxxx')\r\n print (e)\r\n print (e.message)\r\n\r\n #s.close()\r\n","sub_path":"node/spider-3.py","file_name":"spider-3.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"339311273","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Copyright (C) 2011 Yann GUIBET \n# See LICENSE for details.\n\nimport sqlite3\nfrom base64 import b64encode\nfrom config import dbpath\n\nclass Index:\n def __init__(self, db=dbpath):\n self.db = sqlite3.connect(db)\n try:\n self.create()\n except:\n pass\n \n def create(self):\n try:\n c = self.db.cursor()\n c.execute('CREATE TABLE datas (id INTEGER PRIMARY KEY, name TEXT UNIQUE, host TEXT, port INTEGER, login TEXT, pwd TEXT)')\n self.db.commit()\n finally:\n c.close()\n\n def get_all(self):\n c = self.db.cursor()\n res = []\n try:\n c.execute('SELECT * FROM datas')\n self.db.commit()\n for i in c:\n res.append(i)\n finally:\n c.close()\n return res\n\n def get_data_by_id(self, id):\n c = self.db.cursor()\n res = None\n try:\n c.execute('SELECT * FROM datas WHERE id=\"%d\"' % id)\n self.db.commit()\n res = c.fetchone()\n except:\n pass\n \n finally:\n c.close()\n return res\n\n def add_data(self, name, host, port, login, pwd):\n c = self.db.cursor()\n try:\n c.execute('INSERT INTO datas VALUES (NULL, \"%s\", \"%s\", %d, \"%s\", \"%s\")' % (name, host, port, login, b64encode(pwd).decode()))\n self.db.commit()\n except:\n raise\n\n finally:\n c.close() \n\n def rm_data(self, id):\n c = self.db.cursor()\n try:\n c.execute('DELETE FROM datas WHERE id=%d' % id)\n self.db.commit()\n if c.rowcount == 0:\n raise Exception(\"FAIL to rm_data\")\n except:\n raise\n\n finally:\n c.close()\n\n# def update_data(self, id, data, iv, hash):\n# c = self.db.cursor()\n# try:\n# c.execute('UPDATE datas SET data=\"%s\", iv=\"%s\", hash=\"%s\" WHERE id=%d' % (b64encode(data), b64encode(iv), b64encode(hash), id))\n# self.db.commit()\n# \n# except:\n# raise\n#\n# finally:\n# c.close() \n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"176737324","text":"import bpy\nimport mathutils\nimport numpy as np\n\n\n# Hips, Thighs, Calves\nclass Humanoid:\n def __init__(self, mesh_name, armature_name, pelvis, spine, thigh, calf):\n self.name = mesh_name\n self.armature_name = armature_name\n self.pelvis = pelvis\n self.spine = spine\n self.thighR = thigh+'R'\n self.thighL = thigh+'L'\n self.calfR = calf+'R'\n self.calfL = calf+'L'\n \n self.object = bpy.data.objects.get(mesh_name)\n self.armature = bpy.data.objects.get(armature_name)\n \n\n##########User Needs To Set This Part########################\n# Set Humanoid Wrapper for Default and Input Model\ndefault = Humanoid('default_mesh','default','pelvis', 'spine01','thigh_', 'calf_')\ninput = Humanoid('input_mesh','input','Hips','LowerSpine','UpperLeg.','LowerLeg.')\n# Original Garment Model\ngarment = bpy.data.objects.get('pants')\n\n\n#########functions and classes used throughout#########\ndef region_of_interest(obj):\n vertices = obj.data.vertices\n \n group_name = ['PANTS_PELVIS','PANTS_LEG_UPPER_R','PANTS_LEG_UPPER_L','PANTS_LEG_LOWER_R','PANTS_LEG_LOWER_L']\n vgs = []\n for name in group_name:\n vgs.append(obj.vertex_groups[name].index)\n\n bpy.ops.object.mode_set(mode = 'OBJECT')\n bpy.ops.object.select_all(action = 'DESELECT')\n obj.select_set(True)\n for v in vertices:\n check = False\n for group in v.groups:\n if group.group in vgs:\n check = True\n break\n if not check:\n v.select = True\n \n bpy.ops.object.mode_set(mode='EDIT')\n bpy.ops.mesh.delete(type='VERT')\n bpy.ops.object.mode_set(mode='OBJECT') \n bpy.ops.object.select_all(action = 'DESELECT')\n\n# make sure the models have matching global and local coordinates\ndef pants_segmentation(humanoid, garment):\n group_name = ['PANTS_PELVIS','PANTS_LEG_UPPER_R','PANTS_LEG_UPPER_L','PANTS_LEG_LOWER_R','PANTS_LEG_LOWER_L']\n obj = humanoid.object\n for name in group_name:\n if name in obj.vertex_groups.keys():\n print('segmentation exists for '+humanoid.name)\n return\n\n list = [obj, garment]\n if garment is None:\n list.remove(garment)\n \n bones = humanoid.armature.data.bones\n pelvis = bones[humanoid.pelvis]\n spine = bones[humanoid.spine]\n thighR = bones[humanoid.thighR]\n thighL = bones[humanoid.thighL]\n calfR = bones[humanoid.calfR]\n calfL = bones[humanoid.calfL] \n \n bounds = [spine.tail_local[2], thighR.head_local[2], thighR.tail_local[2], calfR.tail_local[2]]\n \n print(bounds)\n for object in list:\n indices = [[],[],[],[],[]]\n \n\n vertices = object.data.vertices\n for v in vertices:\n \tco = v.co\n \tif co[2] > bounds[0]:\n \t\tcontinue\n \telif co[2] > bounds[1]:\n \t\tindices[0].append(v.index)\n \telif co[2] > bounds[2]:\n \t\tif co[0]>pelvis.head[0]:\n \t\t\tindices[1].append(v.index)\n \t\telse:\n \t\t\tindices[2].append(v.index)\n \telif co[2]>bounds[3]:\n \t\tif co[0]>pelvis.head[0]:\n \t\t\tindices[3].append(v.index)\n \t\telse:\n \t\t\tindices[4].append(v.index)\n\n i = 0\n for nm in group_name:\n group = object.vertex_groups.new(name=nm)\n group.add(indices[i],0.5, 'REPLACE')\n i+=1\n\t\t\n\ndefault_aligned = default.object\ninput_aligned = input.object\n\n\n# T-shirt Segmentation of Humanoid objects\npants_segmentation(default,garment)\npants_segmentation(input,None)\n\nregion_of_interest(default_aligned)\nregion_of_interest(input_aligned)\n\n# Deformation\nbones = default.armature.data.bones\njoints = [bones[default.pelvis].head_local,#0\nbones[default.spine].tail_local,#1\nbones[default.thighR].head_local, #2\nbones[default.thighR].tail_local,#3\nbones[default.thighL].head_local,\nbones[default.thighL].tail_local,\nbones[default.calfR].tail_local,\nbones[default.calfL].tail_local]\n\nbones = input.armature.data.bones\nreference_joints = [bones[input.pelvis].head_local,#0\nbones[input.spine].tail_local, #1\nbones[input.thighR].head_local, #2\nbones[input.thighR].tail_local, #3\nbones[input.thighL].head_local, #4\nbones[input.thighL].tail_local, #5\nbones[input.calfR].tail_local, #6\nbones[input.calfL].tail_local] #7\n\nwidth_thigh = abs(joints[3][2]-joints[2][2])\nwidth_calf = abs(joints[6][2] - joints[3][2])\n\nratio_half_pelvis = abs(reference_joints[2][0]/joints[2][0])\nratio_waist = abs((reference_joints[0][2]-reference_joints[1][2])/(joints[0][2]-joints[1][2]))\nratio_thigh = abs((reference_joints[3][2]-reference_joints[2][2])/width_thigh)\nratio_calf = abs((reference_joints[6][2]-reference_joints[3][2])/width_calf)\n\nscl_pelvis = mathutils.Matrix.Scale(ratio_half_pelvis,4,[1,0,0])\nscl_waist = mathutils.Matrix.Scale(ratio_waist,4,[0,0,1])\nscl_thigh = mathutils.Matrix.Scale(ratio_thigh, 4, [0,0,1])\nscl_calf = mathutils.Matrix.Scale(ratio_calf, 4, [0,0,1])\n\ntrnsl_knee = mathutils.Matrix.Translation([0,0,-joints[3][2]])\ntrnsl_pelvis = mathutils.Matrix.Translation([0,0,-joints[2][2]])\ntrnsl_center = mathutils.Matrix.Translation(reference_joints[0]-joints[0])\n\nf_knee_x = (reference_joints[3][0]-joints[3][0])/width_thigh\nf_knee_y = (reference_joints[3][1]-joints[3][1])/width_thigh\nf_ankle_x = (reference_joints[6][0]-joints[6][0])/width_calf\nf_ankle_y = (reference_joints[6][1]-joints[6][1])/width_calf\n\nshr_knee_x = mathutils.Matrix.Shear('XY',4,[f_knee_x,0])\nshr_knee_y = mathutils.Matrix.Shear('XY',4,[0,-f_knee_y])\nshr_ankle_x = mathutils.Matrix.Shear('XY',4,[f_ankle_x,0])\nshr_ankle_y = mathutils.Matrix.Shear('XY',4,[0,-f_ankle_y])\n\n# transform \nfor obj in [garment, default_aligned]:\n vertices = obj.data.vertices\n vg_pelvis = obj.vertex_groups.get('PANTS_PELVIS').index\n vg_right_upper = obj.vertex_groups['PANTS_LEG_UPPER_R'].index\n vg_right_lower = obj.vertex_groups['PANTS_LEG_LOWER_R'].index\n vg_left_upper = obj.vertex_groups['PANTS_LEG_UPPER_L'].index\n vg_left_lower = obj.vertex_groups['PANTS_LEG_LOWER_L'].index\n \n for v in vertices:\n # scale pelvis - width\n v.co = scl_pelvis @ trnsl_center @ v.co\n \n for grp in v.groups:\n if grp.group == vg_pelvis:\n v.co = trnsl_pelvis.inverted() @ scl_waist @ trnsl_pelvis @ v.co\n break\n elif grp.group==vg_right_upper:\n v.co = trnsl_pelvis.inverted() @ shr_knee_y @ shr_knee_x @ scl_thigh @ trnsl_pelvis @ v.co\n break\n elif grp.group==vg_right_lower:\n v.co = trnsl_pelvis.inverted() @ shr_knee_y @ shr_knee_x @ scl_thigh @ trnsl_pelvis @ v.co\n v.co = trnsl_knee.inverted() @ shr_ankle_y @ shr_ankle_x @ scl_calf @ trnsl_knee @ v.co\n break\n elif grp.group == vg_left_upper:\n v.co = trnsl_pelvis.inverted() @ shr_knee_y @ shr_knee_x.inverted() @ scl_thigh @ trnsl_pelvis @ v.co\n \n break\n elif grp.group == vg_left_lower:\n v.co = trnsl_pelvis.inverted() @ shr_knee_y @ shr_knee_x.inverted() @ scl_thigh @ trnsl_pelvis @ v.co\n v.co = trnsl_knee.inverted() @ shr_ankle_y @ shr_ankle_x.inverted() @ scl_calf @ trnsl_knee @ v.co\n break\n v.co = trnsl_center.inverted() @ v.co\n ","sub_path":"trousers/scripts/aligner.py","file_name":"aligner.py","file_ext":"py","file_size_in_byte":7335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"73517860","text":"import pyfits as pf\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\n\ndef getPaths():\n\tpsf_path = '/Users/haynesstephens1/Desktop/research/microlens/files-pulled/mb98-6/mag16jul14_mb980006_kp_psf.fits'\n\timg_path = '/Users/haynesstephens1/Desktop/research/microlens/files-pulled/mb98-6/mag16jul14_MB980006_kp.fits'\n\tbkg_path = '/Users/haynesstephens1/Desktop/research/microlens/files-pulled/mb98-6/mag16jul14_mb980006_kp_back.fits'\n\t# starlist_path = '/Users/haynesstephens1/Desktop/research/microlens/files-pulled/mb98-6/mag16jul14_MB980006_kp_starlist.lis'\n\tstarlist_path = '/Users/haynesstephens1/Desktop/research/microlens/files-pulled/mb98-6/mag16jul14_MB980006_kp_rms.lis'\n\treturn psf_path, img_path, bkg_path, starlist_path\n\n\ndef loadFits(path):\n\t\"\"\"Load the fits file from the given path.\"\"\"\n\thdu_list = pf.open(path)\n\timage = hdu_list[0].data\n\theader = hdu_list[0].header\n\treturn image, header\n\n\ndef getData(psf_path, img_path, bkg_path):\n\tpsf, psf_hdr = loadFits(psf_path)\n\timg, img_hdr = loadFits(img_path)\n\tbkg, bkg_hdr = loadFits(bkg_path)\n\treturn psf, psf_hdr, img, img_hdr, bkg, bkg_hdr\n\n\ndef exInputs():\n\tpsf_path, img_path, bkg_path, starlist_path = getPaths()\n\tpsf, img, bkg = getData(psf_path, img_path, bkg_path)\n\tdy, dx = -30, 30\n\tx_coo, y_coo = 539.06702, 502.41699\n\tx_shape, y_shape = img.shape\n\t# y_coo = y_shape - y_coo\n\tmag = 9\n\ttarget = 'mb980006'\n\tplantStar(target, img, psf, starlist, y_coo, x_coo, mag, dy, dx)\n\treturn\n\n\ndef findPeak(psf):\n\ty_max, x_max = np.where(psf == np.max(psf))\n\ty_peak, x_peak = y_max[0], x_max[0]\n\treturn y_peak, x_peak\n\n\ndef findFWHM(psf, y_peak, x_peak):\n\t\"\"\"Find the FWHM in each direction of an image given coordinates\n\tof a peak pixel.\"\"\"\n\tpeak = psf[y_peak, x_peak]\n\ttop_vals = np.where(psf[:y_peak,x_peak] <= peak/2)[0]\n\ttop = top_vals[-1]\n\tbot_vals = np.where(psf[y_peak:, x_peak] <= peak/2)[0]\n\tbottom = bot_vals[0] + y_peak\n\tleft_vals = np.where(psf[y_peak, :x_peak] <= peak/2)[0]\n\tleft = left_vals[-1]\n\tright_vals = np.where(psf[y_peak, x_peak:] <= peak/2)[0]\n\tright = right_vals[0] + x_peak\n\tcoords = {'top': top, 'bot' : bottom, 'left' : left, 'right' : right}\n\treturn coords\n\n\ndef findFWHMx2(psf, y_peak, x_peak):\n\t\"\"\"Take the FWHM coordinates and double the size of the box\n\tthat they create.\"\"\"\n\tcoords = findFWHM(psf, y_peak, x_peak)\n\tnew_coords = {}\n\ttop_dist_x2 = (y_peak - coords['top']) * 2\n\tnew_top = y_peak - top_dist_x2\n\tnew_coords['top'] = new_top\n\tbot_dist_x2 = (coords['bot'] - y_peak) * 2\n\tnew_bot = y_peak + bot_dist_x2\n\tnew_coords['bot'] = new_bot\n\tleft_dist_x2 = (x_peak - coords['left']) * 2\n\tnew_left = x_peak - left_dist_x2\n\tnew_coords['left'] = new_left\n\tright_dist_x2 = (coords['right'] - x_peak) * 2\n\tnew_right = x_peak + right_dist_x2\n\tnew_coords['right'] = new_right\n\tprint(\"FWHM found and doubled for chosen PSF\")\n\tprint('[{0}: {1}, {2}: {3}]'.format(str(new_top), str(new_bot), str(new_left), str(new_right)))\n\treturn new_coords\n\n\ndef centroid1D(arr, start, end):\n\tx_vals = range(start, end)\n\tarr_len = len(arr)\n\tassert arr_len == len(x_vals), \"Unequal sizes: {0} and {1}\".format(arr_len, len(x_vals))\n\tsigma_xI = 0\n\tsigma_I = 0\n\tfor j in range(arr_len):\n\t\tintens = arr[j]\n\t\tsigma_xI += x_vals[j] * intens\n\t\tsigma_I += intens \n\tx_cm = sigma_xI / sigma_I\n\treturn x_cm\n\n\ndef centroidPSF(psf, coords):\n\t\"\"\"Find the centroid of a star within the box given by COORDS.\"\"\"\n\ttop = coords['top']\n\tbot = coords['bot']\n\tleft = coords['left']\n\tright = coords['right']\n\tsmall_psf = psf[top: bot + 1, left: right + 1]\n\tcols_sum = np.sum(small_psf, axis = 0)\n\tx_troid = centroid1D(cols_sum, left, right + 1)\n\trows_sum = np.sum(small_psf, axis = 1)\n\ty_troid = centroid1D(rows_sum, top, bot + 1)\n\tprint(\"Centroid: [{0}, {1}]\".format(y_troid, x_troid))\n\treturn y_troid, x_troid\n\n\ndef findAndCentroid(psf):\n\ty_peak, x_peak = findPeak(psf)\n\tcoords = findFWHMx2(psf, y_peak, x_peak)\n\ty_troid, x_troid = centroidPSF(psf, coords)\n\ty_troid, x_troid = int(round(y_troid)), int(round(x_troid)) #This line makes the centroid values integers instead of floats\n\treturn y_troid, x_troid\n\n\ndef getMagCalib(starlist):\n\tf=open(starlist,\"r\")\n\tlines=f.readlines()\n\tmags2counts = []\n\t# for x in lines:\n\t# \tmags2counts.append([float(x[13:19].replace(\" \",\"\")), float(x[96:].replace(\" \",\"\").strip(\"\\n\"))])\n\tfor x in lines:\n\t\tif x[0] == '#':\n\t\t\tcontinue\n\t\tmags2counts.append([float(x[15:21].replace(\" \",\"\")), float(x[131:].replace(\" \",\"\").strip(\"\\n\"))])\n\tf.close()\n\t\n\tdef findZ(mag, counts):\n\t\tz = mag + (2.5*(np.log10(counts)))\n\t\treturn z\n\n\tz_array = []\n\tfor mag, counts in mags2counts:\n\t\tz = findZ(mag, counts)\n\t\tz_array.append(z)\n\tz_mean = np.mean(np.array(z_array))\n\treturn z_mean\n\n\ndef magCalib(psf, starlist, mag):\n\tz_mean = getMagCalib(starlist)\n\n\tdef findCounts(mag, z_mean):\n\t\tcounts = 10 ** ((z_mean - mag)/(2.5))\n\t\treturn counts\n\n\tcounts = findCounts(mag, z_mean)\n\tpsf_calib = psf * counts\n\treturn psf_calib\n\n\ndef raiseFloor(psf):\n\traise_cst = 0\n\tnegatives = np.where(psf < 0)[0]\n\tif negatives.size != 0:\n\t\traise_cst = np.min(psf) * 2\n\t\traised_psf = psf + raise_cst\n\treturn psf, raise_cst\n\n\ndef addNoise(psf, gain): #Input is calibrated PSF\n\tpsf, raise_cst = raiseFloor(psf)\n\te_counts = psf * gain\n\tnoisy_e_counts = np.random.poisson(e_counts)\n\tnoisy_psf = noisy_e_counts / gain\n\treturn noisy_psf, raise_cst\n\n\ndef pixToArcsec(dy, dx, ps = 0.00993): # 'NIRC2-AO narrow' value from jluastro-nirc2/nirc2/reduce/calibrate.py\n\tdy_north = dy * ps\n\tdx_east = (-1) * dx * ps\n\tprint('Planted Star is {0}\" East and {1}\" North'.format(dx_east, dy_north))\n\treturn dy_north, dx_east\n\n\ndef coordCalib(y_coo, x_coo, dy, dx):\n\ty_plant = int(y_coo + dy)\n\tx_plant = int(x_coo + dx)\n\treturn y_plant, x_plant\n\n\ndef getFilename(target, dy, dx, mag, raise_cst):\n\tif dy < 0:\n\t\ty_shift = \"yn{0}\".format(abs(dy))\n\telse:\n\t\ty_shift = \"yp{0}\".format(dy)\n\tif dx < 0:\n\t\tx_shift = \"xn{0}\".format(abs(dx))\n\telse:\n\t\tx_shift = \"xp{0}\".format(dx)\n\n\tfilename = \"{0}_{1}_{2}_{3}_rc{4}\".format(target, y_shift, x_shift, mag, raise_cst)\n\treturn filename\n\n\ndef saveImg(img, hdr, filename):\n\thdu = pf.PrimaryHDU(img,header = hdr)\n\thdu.writeto('{0}.fits'.format(filename))\n\treturn\n\n\ndef chopDataAtCoord(img, y_coo, x_coo, side_length): #side_length should be a multiple of 2\n\thalf_length = side_length / 2\n\ttop = y_coo - half_length\n\tbot = y_coo + half_length\n\tleft = x_coo - half_length\n\tright = x_coo + half_length\n\treturn img[top:bottom + 1, left:right + 1]\n\n\ndef chopData(data, chop_length, name):\n\tside1, side2 = data.shape\n\tassert side1 == side2, \"{0} IS NOT A SQUARE.\".format(name)\n\thalf_side = side1 // 2\n\thalf_chop = chop_length // 2\n\ttop = half_side - half_chop\n\tbot = half_side + half_chop\n\tchopped_data = data[top:bot, top:bot]\n\treturn chopped_data\n\n\ndef chopImgs(psf, img, bkg, psf_chop_length, img_chop_length):\n\tpsf_chop = chopData(psf, psf_chop_length, 'PSF')\n\timg_chop = chopData(img, img_chop_length, 'IMG')\n\tbkg_chop = chopData(bkg, img_chop_length, 'BKG')\n\treturn psf_chop, img_chop, bkg_chop\n\n\ndef writeCooFile(y_coo, x_coo, filename):\n\twith open(filename + '.coo', 'w') as f:\n\t\tf.write(' {0} {1}'.format(x_coo, y_coo))\n\treturn\n\n\ndef printPixAndMag(y_shift, x_shift, psf_calib):\n\tprint('\\n')\n\tprint('Pixel Shift: {0}, {1}'.format(x_shift, y_shift))\n\tprint('Flux and Peak (DU): {0}, {1}'.format(np.sum(psf_calib), np.max(psf_calib)))\n\treturn\n\n\ndef plantStar(target, img, psf, bkg, starlist, y_coo, x_coo, mag, dy, dx):\n\ty_troid, x_troid = findAndCentroid(psf)\n\tpsf_calib = magCalib(psf, starlist, mag)\n\tpsf_calib, raise_cst = addNoise(psf_calib)\n\ty_plant, x_plant = coordCalib(y_coo, x_coo, dy, dx)\n\ty_c, x_c = y_plant - y_troid, x_plant - x_troid\n\tplt.figure()\n\tplt.imshow(img, origin = 'lower')\n\tpsf_height, psf_width = psf.shape\n\tprint(\"PSF: height = {0}, width = {1}\".format(psf_height, psf_width))\n\tprint(\"Subimage dimensions: height = {0}, width = {1}\".format(img[y_c:y_c+psf_height, x_c:x_c+psf_width].shape[0],img[y_c:y_c+psf_height, x_c:x_c+psf_width].shape[1]))\n\tprint(\"Calibrated PSF: height = {0}, width = {1}\".format(psf_calib.shape[0],psf_calib.shape[1]))\n\timg[y_c:y_c+psf_height, x_c:x_c+psf_width] = img[y_c:y_c+psf_height, x_c:x_c+psf_width] + psf_calib\n\ty_shift, x_shift = y_plant - y_coo, x_plant - x_coo\n\tpixToArcsec(y_shift, x_shift)\n\tfilename = getFilename(target, dy, dx, mag, raise_cst)\n\tplt.figure()\n\tplt.imshow(img, origin = 'lower')\n\tsaveImg(img, filename)\n\tplt.show()\n\treturn\n\n\ndef plantStarV2(target, psf, psf_hdr, img, img_hdr, bkg, bkg_hdr, starlist, y_coo_og, x_coo_og, mag, dy, dx, plot = True, gain = 4.0, psf_chop_length = 30, img_chop_length = 400):\n\ty_coo, x_coo = y_coo_og - ((img.shape[0] - img_chop_length) / 2), x_coo_og - ((img.shape[0] - img_chop_length) / 2)\n\ty_coo, x_coo = round(y_coo, 3), round(x_coo, 3)\n\tprint(\"New Coo (x,y): {0}, {1}\".format(x_coo, y_coo))\n\tpsf_chop, img_chop, bkg_chop = chopImgs(psf, img, bkg, psf_chop_length, img_chop_length)\n\ty_troid, x_troid = findAndCentroid(psf_chop)\n\t# plt.figure()\n\t# plt.imshow(psf_chop, origin = 'lower')\n\t# plt.plot(x_troid, y_troid, 'b+')\n\tpsf_calib = magCalib(psf_chop, starlist, mag)\n\tpsf_calib, raise_cst = addNoise(psf_calib, gain)\n\ty_plant, x_plant = coordCalib(y_coo, x_coo, dy, dx)\n\ty_c, x_c = y_plant - y_troid, x_plant - x_troid\n\tprint(\"Planted Star Coords (x, y): {0}, {1}\".format(x_c, y_c))\n\t# plt.figure()\n\t# plt.imshow(img_chop, origin = 'lower')\n\t# plt.plot(x_coo, y_coo, 'b+')\n\tpsf_height, psf_width = psf_chop.shape\n\tprint(\"PSF: height = {0}, width = {1}\".format(psf_height, psf_width))\n\tprint(\"Subimage dimensions: height = {0}, width = {1}\".format(img_chop[y_c:y_c+psf_height, x_c:x_c+psf_width].shape[0],img_chop[y_c:y_c+psf_height, x_c:x_c+psf_width].shape[1]))\n\tprint(\"Calibrated PSF: height = {0}, width = {1}\".format(psf_calib.shape[0],psf_calib.shape[1]))\n\timg_chop[y_c:y_c+psf_height, x_c:x_c+psf_width] = img_chop[y_c:y_c+psf_height, x_c:x_c+psf_width] + psf_calib\n\ty_shift, x_shift = y_plant - y_coo, x_plant - x_coo\n\tpixToArcsec(y_shift, x_shift)\n\tfilename = getFilename(target, dy, dx, mag, raise_cst)\n\t# plt.figure()\n\t# plt.imshow(img_chop, origin = 'lower')\n\t# plt.plot(x_coo, y_coo, 'b+')\n\t# plt.plot(x_plant, y_plant, 'r+')\n\tsaveImg(img_chop, img_hdr, filename)\n\tsaveImg(bkg_chop, bkg_hdr, filename + '_back')\n\tsaveImg(psf_chop, psf_hdr, filename + '_psf')\n\twriteCooFile(y_coo, x_coo, filename)\n\tprintPixAndMag(y_shift, x_shift, psf_calib)\n\tif plot:\n\t\tplt.figure()\n\t\tplt.imshow(psf_chop, origin = 'lower')\n\t\tplt.plot(x_troid, y_troid, 'b+')\n\n\t\tplt.figure()\n\t\tplt.imshow(img_chop, origin = 'lower')\n\t\tplt.plot(x_coo, y_coo, 'b+')\n\n\t\tplt.figure()\n\t\tplt.imshow(img_chop, origin = 'lower')\n\t\tplt.plot(x_coo, y_coo, 'b+')\n\t\tplt.plot(x_plant, y_plant, 'r+')\n\n\t\tplt.show()\n\treturn x_shift, y_shift, filename\n\n\ndef runEx():\n\tpsf_path, img_path, bkg_path, starlist_path = getPaths()\n\tpsf, psf_hdr, img, img_hdr, bkg, bkg_hdr = getData(psf_path, img_path, bkg_path)\n\tdy, dx = 10, 10\n\tx_coo_og, y_coo_og = 539.06702, 502.41699 #From starlist\n\t# TRY 540.170, 503.390\n\tx_shape, y_shape = img.shape\n\tmag = 9.0\n\ttarget = 'mb980006'\n\tplantStarV2(target, psf, psf_hdr, img, img_hdr, bkg, bkg_hdr, starlist_path, y_coo_og, x_coo_og, mag, dy, dx)\n\treturn\n\n","sub_path":"ml/star_planting/backup-scripts/starPlanter.py","file_name":"starPlanter.py","file_ext":"py","file_size_in_byte":11130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"376771089","text":"import math\n\n\ndef norm(vec):\n '''Return the norm of a vector stored as a dictionary,\n as described in the handout for Project 3.\n '''\n\n sum_of_squares = 0.0\n for x in vec:\n sum_of_squares += vec[x] * vec[x]\n\n return math.sqrt(sum_of_squares)\n\n\ndef cosine_similarity(vec1, vec2):\n numerator = 0\n for key, value in vec1.items():\n if key in vec2.keys():\n numerator += vec1[key] * vec2[key]\n denominator = 0\n den_v1 = 0\n den_v2 = 0\n for key, value in vec1.items():\n den_v1 += value**2\n for key, value in vec2.items():\n den_v2 += value**2\n denominator = (den_v1*den_v2)**(1/2)\n similarity = numerator/denominator\n return similarity\n\ndef adding_words_to_dict(words):\n for i in range(len(sentence)):\n if sentence[i] not in d:\n d[sentence[i]] = {}\n for otherword in sentence:\n if otherword == word:\n pass\n else:\n if otherword in d[word]:\n d[word][otherword] += 1\n else:\n d[word][otherword] = 1\n\ndef removedoubleword(sentence):\n for word in sentence:\n if sentence.count(word) > 1:\n sentence.remove(word)\n\ndef build_semantic_descriptors(sentences):\n d = {}\n #print(\"Sentences:\", sentences)\n for sentence in sentences:\n #print(\"Sentence:\", sentence)\n for word in sentence:\n if len(word) == 0:\n sentence.remove(word)\n for word in sentence:\n if word not in d.keys():\n d[word] = {}\n for otherword in sentence:\n if otherword == word or otherword == '':\n pass\n elif otherword in d[word].keys():\n d[word][otherword] += 1\n else:\n d[word][otherword] = 1\n return d\n\ndef update(d, sentences):\n new_d = build_semantic_descriptors(sentences)\n for key, values in new_d.items():\n if key in d.keys():\n for new_d_key, new_d_values in new_d[key].items():\n if new_d_key in d[key].keys():\n d[key][new_d_key] += new_d[key][new_d_key]\n else:\n d[key][new_d_key] = new_d[key][new_d_key]\n else:\n d[key] = new_d[key]\n return d\n\ndef build_semantic_descriptors_from_files(filenames):\n d = {}\n for i in range(len(filenames)):\n # print(filenames[i])\n f = open(filenames[i], encoding=\"latin-1\")\n text = f.read().lower().replace(\"!\", \".\").replace(\"?\", \".\").replace(\"-\", \" \").replace(\"--\", \" \").replace(\",\", \"\").replace(\":\", \"\").replace(\";\", \"\").replace(\". \", \".\").replace(\" .\", \".\").replace(\". \", \".\").replace(\"\\n\", \" \").replace(\" \", \" \").split(\".\")\n sentences = []\n for elem in text:\n new_sentence = elem.split(\" \")\n # print(\"new_sentece =\", new_sentence)\n # print(type(new_sentence))\n length = len(new_sentence)\n i = 0\n while i < length:\n # print(\"New type is: \", type(new_sentence))\n if new_sentence.count(new_sentence[i]) > 1:\n new_sentence.remove(new_sentence[i])\n length -= 1\n else:\n i += 1\n sentences.append(new_sentence)\n d = update(d, sentences)\n return d\n\ndef similarity_finder(word, choice, semantic_descriptors, similarity_fn):\n vec1 = semantic_descriptors[word]\n # print(vec1, \"vec1\")\n if choice in semantic_descriptors.keys():\n vec2 = semantic_descriptors[choice]\n else:\n vec2 = {-1: -1}\n # print(vec2, \"vec2\")\n similarity = similarity_fn(vec1, vec2)\n return similarity\n\n\n\ndef most_similar_word(word, choices, semantic_descriptors, similarity_fn):\n similarities = []\n for elem in choices:\n similarities.append(similarity_finder(word, elem, semantic_descriptors, similarity_fn))\n max_value = max(similarities)\n index = similarities.index(max_value)\n return choices[index]\n\n\n\ndef run_similarity_test(filename, semantic_descriptors, similarity_fn):\n f = open(filename, encoding=\"latin-1\")\n questions = f.read().split(\"\\n\")\n for i in range(len(questions)):\n questions[i] = questions[i].split(\" \")\n answers = []\n guesses = []\n #print(\"question:\", questions)\n for question in questions:\n if len(question) > 2:\n answers.append(question[1])\n guesses.append(most_similar_word(question[0], question[2:], semantic_descriptors, similarity_fn))\n else:\n questions.remove(question)\n total = len(questions)\n #print(answers)\n #print(guesses)\n correct = 0\n for i in range(len(answers)):\n if answers[i] == guesses[i]:\n correct += 1\n #print(correct/total * 100)\n return (correct/total) * 100\n\nif __name__ == \"__main__\":\n # print(norm({\"a\": 1, \"b\": 2, \"c\": 3}))\n\n #print(cosine_similarity({\"a\": 1, \"b\": 2, \"c\": 3}, {\"b\": 4, \"c\": 5, \"d\": 6}))\n\n # sentences = [[\"i\", \"am\", \"a\", \"sick\", \"man\"],\n # [\"i\", \"am\", \"a\", \"spiteful\", \"man\"],\n # [\"i\", \"am\", \"an\", \"unattractive\", \"man\"],\n # [\"i\", \"believe\", \"my\", \"liver\", \"is\", \"diseased\"],\n # [\"however\", \"i\", \"know\", \"nothing\", \"at\", \"all\", \"about\", \"my\",\n # \"disease\", \"and\", \"do\", \"not\", \"know\", \"for\", \"certain\", \"what\", \"ails\", \"me\"]]\n # print(build_semantic_descriptors(sentences))\n\n\n #3\n\n # sem_descriptors = build_semantic_descriptors_from_files([\"WarandPeace.txt\", \"Swann'sWay.txt\"])\n #\n # #4\n # # q = [\"i\", \"j\", \"k\"]\n # # l = [2, 3, 5]\n # # m = max(l)\n # # index = l.index(m)\n # #\n # # print(q[index])\n # #\n # # #5\n # # run_similarity_test(\"Project3Example.txt\", semantic_descriptors, cosine_similarity)\n # res = run_similarity_test(\"Project3Example.txt\", sem_descriptors, cosine_similarity)\n # print(res, \"of the guesses were correct\")\n # vec1 = {'cat': 1, 'food': 1}\n # vec2 = {'dog': 1}\n #\n # list = [-1, 0, 0, 0]\n # print(max(list))\n # index = list.index(0)\n # print(index)\n\n sem_desc = {\"dog\": {\"cat\": 1, \"food\": 1},\n \"cat\": {\"dog\": 1}}\n print(most_similar_word(\"dog\", [\"cat\", \"rat\"], sem_desc, cosine_similarity))\n\n build_semantic_descriptors_from_files([\"Project3Example.txt\"])\n\n","sub_path":"synonyms.py","file_name":"synonyms.py","file_ext":"py","file_size_in_byte":6367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"349237766","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponseRedirect\n\nfrom accounts.models import User\nfrom .forms import NewsletterUserSignUpForm\n\n\ndef newsletter_signup(request):\n if request.method == \"POST\":\n form = NewsletterUserSignUpForm(request.POST)\n\n if form.is_valid():\n instance = form.save(commit=False)\n if User.objects.filter(email=instance.email).exists():\n print(\"Sorry this email already exists\")\n else:\n instance.save()\n return redirect('newsletter:newsletter_success')\n\n else:\n form = NewsletterUserSignUpForm()\n\n template = \"newsletters/sign_up.html\"\n return render(request, template, {'form':form})\n\n\ndef post_new(request):\n if request.method == \"POST\":\n form = NewsletterUserSignUpForm(request.POST)\n if form.is_valid():\n instance = form.save(commit=False)\n post.author = request.user\n post.published_date = timezone.now()\n post.save()\n return redirect('post_detail', pk=post.pk)\n else:\n form = PostForm()\n return render(request, 'blog/post_edit.html', {'form': form})\n\ndef newsletter_unsubscribe(request):\n form = NewsletterUserSignUpForm(request.POST or None)\n\n if form.is_valid():\n instance = form.save(commit=False)\n if User.objects.filter(email=instance.email).exists():\n User.objects.filter(email=instance.email).delete()\n else:\n print(\"Sorry but we did not find your email address\")\n\n context = {\n 'form':form,\n }\n template = \"newsletters/unsubscribe.html\"\n return render(request, template, context)\n\n\ndef newsletter_success(request):\n template = \"newsletters/success.html\"\n return render(request,template)\n","sub_path":"newsletters/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"178339748","text":"from __future__ import division\nimport os\nimport math\nimport numpy\nimport random\nimport itertools\nimport scipy.stats\nimport scipy.spatial\nfrom enum import Enum\nfrom sklearn import svm\nimport coupling.utils.misc # for plt settings\nfrom collections import Counter\nimport matplotlib.pyplot as plt\nfrom collections import defaultdict\nfrom utils.serializer import JsonSerializer\nfrom sklearn.ensemble import RandomForestClassifier\n\ns_to_ms = 1e3\n__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n\nclass Index(Enum):\n BSSI = 0\n RSSI = 1\n\ndef load_data(path_scans):\n data = JsonSerializer(path_scans).deserialize()\n database_fingerprint = dict()\n for position, scan in data.items():\n fingerprint = scan[\"entries\"]\n bssi = numpy.array([entry[\"mac\"].upper() for entry in fingerprint])\n rssi = numpy.array([entry[\"rssi\"] for entry in fingerprint])\n nonzero = numpy.nonzero(rssi)\n bssi = bssi[nonzero]\n rssi = rssi[nonzero]\n assert len(bssi) == len(rssi)\n database_fingerprint[int(position)] = (bssi, rssi)\n return database_fingerprint\n\ndef get_rssi(x, y):\n bssi_x = x[Index.BSSI.value]\n bssi_y = y[Index.BSSI.value] \n rssi_x = x[Index.RSSI.value]\n rssi_y = y[Index.RSSI.value]\n ap_overlap = numpy.intersect1d(bssi_x, bssi_y)\n rssi_x_ret = numpy.zeros(shape=(len(ap_overlap)), dtype=numpy.int)\n rssi_y_ret = numpy.zeros(shape=(len(ap_overlap)), dtype=numpy.int)\n for i, ap in enumerate(ap_overlap):\n ap_idx = numpy.where(bssi_x == ap)\n rssi = rssi_x[ap_idx]\n rssi_x_ret[i] = numpy.median(rssi)\n ap_idx = numpy.where(bssi_y == ap)\n rssi = rssi_y[ap_idx]\n rssi_y_ret[i] = numpy.median(rssi)\n return rssi_x_ret, rssi_y_ret\n\nclass DatasetStatistics:\n \n def __init__(self, path_wifi_fingerprints, path_ble_fingerprints):\n self.wifi_fingerprints = load_data(path_wifi_fingerprints)\n self.ble_fingerprints = load_data(path_ble_fingerprints)\n self.total_num_ap, self.ap_num_per_scan = self.get_occurrences(self.wifi_fingerprints)\n self.total_num_beacon, self.beacon_num_per_scan = self.get_occurrences(self.ble_fingerprints)\n self.wifi_unique_total, self.wifi_unique_ratio = self.get_unique_ratio(self.wifi_fingerprints)\n self.ble_unique_total, self.ble_unique_ratio = self.get_unique_ratio(self.ble_fingerprints)\n \n def pprint(self, sampled_wifi_entries, sampled_ble_entries):\n print(\"### WiFi\")\n print(\"total num AP: \", self.total_num_ap)\n print(\"AP per scan: \", self.ap_num_per_scan)\n print(\"Total unique per scan:\", numpy.mean(self.wifi_unique_total))\n print(\"Ratio unique per scan: \", [round(entry*100, 2) for entry in self.wifi_unique_ratio])\n print(\"Ratio sampled APs:\", round(100*numpy.median([sampled_wifi_entries/total for total in self.wifi_unique_total]), 2))\n print(\"### BLE\")\n print(\"total num beacon: \", self.total_num_beacon)\n print(\"beacon per scan: \", self.beacon_num_per_scan)\n print(\"Total unique per scan:\", numpy.mean(self.ble_unique_total))\n print(\"Ratio unique per scan: \", [round(entry*100, 2) for entry in self.ble_unique_ratio])\n print(\"Ratio sampled beacons:\", round(100*numpy.mean([sampled_ble_entries/total for total in self.ble_unique_total]),2))\n \n def get_unique_ratio(self, fingerprints):\n unique_total = list()\n unique_ratio = list()\n for fingerprint in fingerprints.values():\n unique_bssi = set()\n assert len(fingerprint[Index.BSSI.value]) == len(fingerprint[Index.RSSI.value])\n for mac in fingerprint[Index.BSSI.value]:\n unique_bssi.add(mac) # without duplicates\n all_scan_values = len(fingerprint[Index.BSSI.value])\n unique_scan = len(unique_bssi)\n #duplicates = all_scan_values - scan_without_duplicates\n #duplicates_ratio.append(duplicates / all_scan_values)\n unique_ratio.append(unique_scan / all_scan_values)\n unique_total.append(unique_scan)\n return unique_total, unique_ratio\n \n def get_occurrences(self, fingerprints):\n bssi = set()\n bssi_per_scan = list()\n for fingerprint in fingerprints.values():\n per_scan = set()\n for mac in fingerprint[Index.BSSI.value]:\n per_scan.add(mac)\n bssi.add(mac)\n bssi_per_scan.append(len(per_scan))\n return len(bssi), (numpy.min(bssi_per_scan),\n numpy.max(bssi_per_scan), numpy.mean(bssi_per_scan))\n\nclass LocalizationFeatures:\n \n @classmethod\n def from_single_room(cls, path_scans, pos_in_area):\n scans = load_data(path_scans)\n pos_out_area = list(set(scans.keys()).difference(pos_in_area))\n cls.scans = scans\n cls.pos_in_area = pos_in_area\n cls.pos_out_area = pos_out_area\n return cls(scans, pos_in_area, pos_out_area)\n \n @classmethod\n def from_multiple_rooms(cls, path_scans, map_room_to_pos):\n features = dict()\n room_scans = dict()\n scans = load_data(path_scans)\n for room_id, positions in map_room_to_pos.items():\n pos_in_area = positions\n pos_out_area = list()\n for other_room_id in map_room_to_pos:\n if room_id != other_room_id:\n pos_out_area.extend(map_room_to_pos[other_room_id]) \n bssid = numpy.concatenate([scans[pos][0] for pos in positions])\n rssi = numpy.concatenate([scans[pos][1] for pos in positions])\n room_scans[room_id] = (bssid, rssi)\n features[room_id] = cls(scans, pos_in_area, pos_out_area)\n return room_scans, features\n \n def __init__(self, scans, pos_in_area, pos_out_area, len_combination=2, num_features=10):\n self.num_features = num_features\n self.imputing_values = self.ImputingValues(scans, self)\n self.groundtruth = dict()\n for pos_in in pos_in_area:\n self.groundtruth[pos_in] = 1\n for pos_out in pos_out_area:\n self.groundtruth[pos_out] = 0\n positions = pos_in_area + pos_out_area\n data_len = len(list(itertools.combinations(positions, len_combination)))\n self.X = numpy.empty(shape=(data_len, num_features))\n self.y = numpy.empty(shape=(data_len, 1))\n for i, (position1, position2) in enumerate(itertools.combinations(positions, len_combination)):\n pos1_data = scans[position1]\n pos2_data = scans[position2]\n feature = self.compute(pos1_data, pos2_data, self.imputing_values)\n within_area = self.groundtruth[position1] & self.groundtruth[position2]\n self.X[i] = feature\n self.y[i] = within_area\n self.y = self.y.ravel()\n \n class ImputingValues:\n def __init__(self, data, features, idx=0):\n # mean value over all non-nan values\n data_len = len(data) * len(data)\n spearman = numpy.empty(shape=(data_len))\n pearson = numpy.empty(shape=(data_len))\n manhattan = numpy.empty(shape=(data_len))\n euclidean = numpy.empty(shape=(data_len))\n for scan1 in data.values():\n for scan2 in data.values():\n overlap = features.overlap(scan1, scan2)\n rssi_scan1, rssi_scan2 = get_rssi(scan1, scan2)\n manhattan[idx] = features.manhattan_distance(rssi_scan1, rssi_scan2, overlap)\n euclidean[idx] = features.euclidean_distance(rssi_scan1, rssi_scan2, overlap)\n spearman[idx] = features.spearman_correlation(rssi_scan1, rssi_scan2)\n pearson[idx] = features.pearson_correlation(rssi_scan1, rssi_scan2)\n idx += 1\n self.mean_spearman = numpy.mean(spearman[~numpy.isnan(spearman)])\n self.mean_pearson = numpy.mean(pearson[~numpy.isnan(pearson)])\n self.mean_manhattan = numpy.mean(manhattan[~numpy.isnan(manhattan)])\n self.mean_euclidean = numpy.mean(euclidean[~numpy.isnan(euclidean)])\n \n def get_groundtruth(self, position):\n return self.groundtruth[position]\n \n def compute(self, scan1, scan2, imputing_values):\n return self.__compute(scan1, scan2, imputing_values, self.num_features)\n \n def __compute(self, scan1, scan2, imputing_values, num_features):\n feature = numpy.empty(shape=(num_features))\n overlap = self.overlap(scan1, scan2)\n feature[0] = overlap\n feature[1] = self.union(scan1, scan2)\n feature[2] = self.jaccard_distance(scan1, scan2)\n feature[3] = self.non_overlap(scan1, scan2)\n feature[4] = self.share_top_ap(scan1, scan2)\n feature[5] = self.share_range_ap(scan1, scan2)\n rssi_scan1, rssi_scan2 = get_rssi(scan1, scan2)\n feature[6] = self.get_value(self.spearman_correlation, imputing_values.mean_spearman,\n rssi_scan1, rssi_scan2)\n feature[7] = self.get_value(self.pearson_correlation, imputing_values.mean_pearson,\n rssi_scan1, rssi_scan2)\n feature[8] = self.get_value(self.manhattan_distance, imputing_values.mean_manhattan,\n rssi_scan1, rssi_scan2, overlap)\n feature[9] = self.get_value(self.euclidean_distance, imputing_values.mean_euclidean,\n rssi_scan1, rssi_scan2, overlap)\n return feature\n \n def get_value(self, method, imputing_value, *arg):\n value = None\n try:\n if len(arg[0]) > 0:\n if len(arg) == 2:\n value = method(arg[0], arg[1])\n elif len(arg) == 3:\n value = method(arg[0], arg[1], arg[2])\n else:\n value = imputing_value\n except:\n value = imputing_value\n if math.isnan(value) or value == None:\n value = imputing_value\n return value\n \n # AP presence\n def overlap(self, x, y): # raw count of overlapping routers\n return len(numpy.intersect1d(x[Index.BSSI.value], y[Index.BSSI.value]))\n \n def union(self, x, y): # size of the union of two lists\n return len(numpy.union1d(x[Index.BSSI.value], y[Index.BSSI.value]))\n \n # range: 0-1\n def jaccard_distance(self, x, y): # ratio between size of intersection and size of union of two lists\n bssi_x = x[Index.BSSI.value]\n bssi_y = y[Index.BSSI.value]\n union = len(numpy.union1d(bssi_x, bssi_y))\n intersection = len(numpy.intersect1d(bssi_x, bssi_y))\n jaccard = (union - intersection) / union\n return jaccard\n \n def non_overlap(self, x, y): # non-overlap: raw count of non-overlapping routers (size of union minus size of overlap)\n return self.union(x, y) - self.overlap(x, y)\n \n # RSSI of overlapping routers\n # RSSI range: -100 to 0 dBm, closer to 0 is higher strength\n def spearman_correlation(self, x, y):\n if len(x) > 2 and len(y) > 2:\n return scipy.stats.spearmanr(x, y).correlation\n else:\n return numpy.nan\n \n def pearson_correlation(self, x, y):\n if len(x) > 2 and len(y) > 2:\n return scipy.stats.pearsonr(x, y)[0]\n else:\n return numpy.nan\n \n def manhattan_distance(self, x, y, overlap):\n value = scipy.spatial.distance.cityblock(x, y)\n if math.isnan(value) or overlap == 0:\n return value\n else:\n return value / overlap\n \n def euclidean_distance(self, x, y, overlap):\n value = scipy.spatial.distance.euclidean(x, y)\n if math.isnan(value) or overlap == 0:\n return value\n else:\n return value / overlap\n \n # AP presence + RSSI\n def share_top_ap(self, x, y):\n max_idx_x = numpy.argmax(x[Index.RSSI.value])\n max_idx_y = numpy.argmax(y[Index.RSSI.value])\n max_ap_x = x[Index.BSSI.value][max_idx_x]\n max_ap_y = y[Index.BSSI.value][max_idx_y]\n return int(max_ap_x == max_ap_y)\n \n def share_range_ap(self, x, y, rssi_range=6): #top AP +/- 6db\n # positive if at least one overlapping access point in the lists\n # of routers of A and B within 6dB from the top router\n max_rssi_x = x[Index.RSSI.value].max()\n max_rssi_y = y[Index.RSSI.value].max()\n if max_rssi_x >= max_rssi_y:\n bottom_rssi = max_rssi_x - rssi_range\n else:\n bottom_rssi = max_rssi_y - rssi_range\n rssi_idx = numpy.where(x[Index.RSSI.value] >= bottom_rssi)[0]\n bssi_x = x[Index.BSSI.value][rssi_idx]\n rssi_idx = numpy.where(y[Index.RSSI.value] >= bottom_rssi)[0]\n bssi_y = y[Index.BSSI.value][rssi_idx]\n ap_overlap = numpy.intersect1d(bssi_x, bssi_y)\n return int(len(ap_overlap) > 0)\n \nclass ReasoningRandom:\n \n def predict(self, _):\n return int(random.getrandbits(1))\n \nclass ReasoningFiltering:\n \n def __init__(self, features):\n self.features = features\n \n def predict(self, feature):\n feature_distance = defaultdict(list)\n for X, y in zip(self.features.X, self.features.y):\n distance = scipy.spatial.distance.cosine(feature, X)\n feature_distance[y].append(distance)\n distance_in_area = numpy.mean(feature_distance[1])\n distance_out_area = numpy.mean(feature_distance[0])\n return int(distance_in_area < distance_out_area)\n \nclass ReasoningMachineLearning:\n \n def __init__(self, features):\n self.features = features\n self.rfc = RandomForestClassifier()\n self.rfc.fit(self.features.X, self.features.y)\n self.svm = svm.SVC()\n self.svm.fit(self.features.X, self.features.y)\n \n def predict_svm(self, feature):\n # calculate feature between scan1 and scan2\n # predict feature the class: in (1), out (0)\n feature = feature.reshape(1, -1)\n return int(self.svm.predict(feature))\n \n def predict_random_forest(self, feature):\n feature = feature.reshape(1, -1)\n return int(self.rfc.predict(feature))\n \nclass Localization:\n \n def __init__(self, features):\n self.features = features\n self.reasoning_random = ReasoningRandom()\n self.reasoning_filtering = ReasoningFiltering(self.features)\n self.reasoning_machine_learning = ReasoningMachineLearning(self.features)\n \n def evaluate(self, datalen):\n #from sklearn.model_selection import KFold\n #coupling_data_provider = CouplingDataProvider(None, None, parameter.wifi_scans[localization_pos_in], parameter.ble_scans[localization_pos_in])\n result_svm = dict()\n result_random = dict()\n result_filtering = dict()\n result_random_forest = dict()\n for test_position, test_scan in self.features.scans.items():\n svm = dict()\n random = dict()\n filtering = dict()\n random_forest = dict()\n ap_bssi = test_scan[0][:datalen]\n ap_rssi = test_scan[1][:datalen]\n test_scan = (ap_bssi, ap_rssi)\n for position, scan in self.features.scans.items():\n ap_bssi = scan[0][:datalen]\n ap_rssi = scan[1][:datalen]\n scan = (ap_bssi, ap_rssi)\n feature = self.features.compute(test_scan, scan, self.features.imputing_values)\n random[position] = self.reasoning_random.predict(None)\n filtering[position] = self.reasoning_filtering.predict(feature)\n svm[position] = self.reasoning_machine_learning.predict_svm(feature)\n random_forest[position] = self.reasoning_machine_learning.predict_random_forest(feature)\n result_svm[test_position] = self.in_area(svm, self.features.pos_in_area, self.features.pos_out_area)\n result_random[test_position] = self.in_area(random, self.features.pos_in_area, self.features.pos_out_area)\n result_filtering[test_position] = self.in_area(filtering, self.features.pos_in_area, self.features.pos_out_area)\n result_random_forest[test_position] = self.in_area(random_forest, self.features.pos_in_area, self.features.pos_out_area)\n print(\"random\")\n self.accuracy(result_random, self.features.pos_in_area, self.features.pos_out_area)\n print(\"filtering\")\n self.accuracy(result_filtering, self.features.pos_in_area, self.features.pos_out_area)\n print(\"svm\")\n self.accuracy(result_svm, self.features.pos_in_area, self.features.pos_out_area)\n print(\"random forest\")\n self.accuracy(result_random_forest, self.features.pos_in_area, self.features.pos_out_area)\n \n def in_area(self, prediction, pos_in_area, pos_out_area):\n predict_in_area = [prediction[pos] for pos in pos_in_area]\n predict_out_area = [prediction[pos] for pos in pos_out_area]\n positions = len(pos_in_area) + len(pos_out_area)\n return (sum(predict_in_area) / positions) > (sum(predict_out_area) / positions)\n \n # input predict: {pos_1: result={True|False}, pos_2: ... }\n def accuracy(self, predict, pos_in_area, pos_out_area):\n num_in_area = len(pos_in_area)\n num_out_area = len(pos_out_area)\n predict_in_area = [predict[pos] for pos in pos_in_area]\n predict_out_area = [predict[pos] for pos in pos_out_area]\n accuracy_in_area = Counter(predict_in_area)[True] / num_in_area\n accuracy_out_area = Counter(predict_out_area)[False] / num_out_area\n print ((accuracy_in_area + accuracy_out_area) / 2)\n \ndef offline_localization(path_ble_scans, path_wifi_scans):\n pos_in_area = [1, 2, 3, 4, 5]\n #from coupling.device_grouping.online.static.coupling_data_provider import CouplingDataProvider\n #from coupling.device_grouping.online.dynamic.coupling_data_provider import CouplingDataProvider\n #measurements_to_rooms = {1:[1,2,3,4,5], 2:[6,7,8,9], 3:[10,11], 4:[12,13], 5:[14,15,16,17,18,19],\n # 6:[20,21,22,23], 7:[24,25,26,27], 8:[28,29,30,31], 9:[32,33,34,35], 10:[36,37,38,39]}\n \n for sampling_period in [2, 5, 10, 15, 20, 25, 30]:\n wifi_datalen = int(round(get_wifi_entries(sampling_period)))\n ble_datalen = int(round(get_ble_entries(sampling_period)))\n print(\"sampling period:\", sampling_period)\n \n #print(\"WiFi\")\n #wifi_features = LocalizationFeatures.from_multiple_rooms(path_wifi_scans, measurements_to_rooms)\n wifi_features = LocalizationFeatures.from_single_room(path_wifi_scans, pos_in_area)\n wifi_localization = Localization(wifi_features)\n wifi_localization.evaluate(wifi_datalen)\n \n print(\"BLE\")\n #ble_features = LocalizationFeatures.from_multiple_rooms(path_ble_scans, measurements_to_rooms)\n ble_features = LocalizationFeatures.from_single_room(path_ble_scans, pos_in_area)\n ble_localization = Localization(ble_features)\n ble_localization.evaluate(ble_datalen)\n \ndef num_entries_per_ms(filename):\n entries_per_ms = list()\n data_path = os.path.join(__location__, \"data\", filename)\n fingerprints = JsonSerializer(data_path).deserialize()\n for scan in fingerprints.values():\n fingerprint = scan[\"entries\"]\n bssi = numpy.array([entry[\"mac\"] for entry in fingerprint])\n rssi = numpy.array([entry[\"rssi\"] for entry in fingerprint])\n assert len(bssi) == len(rssi)\n duration = int(scan[\"stopTimestamp\"]) - int(scan[\"startTimestamp\"]) # ms\n entries_per_ms.append(len(bssi) / duration)\n return numpy.mean(entries_per_ms)\n\ndef num_encounters(path_ble_scans):\n dummy = load_data(path_ble_scans)\n len_bssi = list()\n for bssi, _ in dummy.values():\n len_bssi.append(len(bssi))\n print(numpy.mean(len_bssi))\n\ndef print_num_entries(duration):\n ble_entries_ms = num_entries_per_ms(\"bluetooth-fingerprints\")\n wifi_entries_ms = num_entries_per_ms(\"wifi-fingerprints\")\n print(\"BLE entries/s:\", (duration * s_to_ms) * ble_entries_ms)\n print(\"Wi-Fi entries(s:\", (duration * s_to_ms) * wifi_entries_ms)\n\ndef get_ble_entries(duration):\n ble_entries_ms = num_entries_per_ms(\"bluetooth-fingerprints\")\n return (duration * s_to_ms) * ble_entries_ms\n\ndef get_wifi_entries(duration):\n wifi_entries_ms = num_entries_per_ms(\"wifi-fingerprints\")\n return (duration * s_to_ms) * wifi_entries_ms\n\ndef plot_sampled_entries():\n for data_type, get_entries in [(\"wifi\", get_wifi_entries), (\"ble\", get_ble_entries)]:\n periods = range(1, 31)\n entries = [get_entries(period) for period in periods]\n fig, ax = plt.subplots()\n ax.plot(periods, entries)\n #ax.axvline(entries[sampling_period-1], linestyle=\"--\")\n ax.grid()\n ax.set_xlabel(\"Sampling period (s)\")\n ax.set_ylabel(\"Sampling entries\")\n ax.set_xticks(periods)\n #ax.set_xticklabels(periods)\n plot_format = \"pdf\"\n plt.show()\n filename = \"localization-sampling-entries-\" + data_type + \".\" + plot_format\n fig.savefig(filename, plot_format=plot_format, bbox_inches=\"tight\")\n plt.close(fig)\n \ndef main():\n path_ble_scans = os.path.join(__location__, \"data\", \"bluetooth-fingerprints\")\n path_wifi_scans = os.path.join(__location__, \"data\", \"wifi-fingerprints\")\n \n sampling_period = 5\n #plot_sampled_entries()\n \n print(\"Data entries within time frame\")\n print_num_entries(sampling_period)\n \n sampled_wifi_entries = get_wifi_entries(sampling_period)\n sampled_ble_entries = get_ble_entries(sampling_period)\n \n print(\"Dataset statistics\")\n DatasetStatistics(path_wifi_scans, path_ble_scans).pprint(sampled_wifi_entries, sampled_ble_entries)\n \n print(\"Offline localization\")\n offline_localization(path_ble_scans, path_wifi_scans)\n \nif __name__ == '__main__':\n main()\n ","sub_path":"device-association/localization/localization_server.py","file_name":"localization_server.py","file_ext":"py","file_size_in_byte":22100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"550002697","text":"output = open(\"output.txt\", \"w\")\r\ninput = open(\"D-small-attempt2.in\", \"r\")\r\nnext(input)\r\nn = 1\r\nfor line in input:\r\n k,c, s = (int(x) for x in line.split())\r\n output.write(\"Case #\" + str(n) + \":\") \r\n for i in range (1, k+1):\r\n output.write(' ' + str(i))\r\n output.write(\"\\n\");\r\n n += 1\r\ninput.close()\r\noutput.close()\r\n","sub_path":"codes/BuildLinks1.10/test_input/CJ/16_0_4_aboisier_GCJ-Q16-Fractiles.py","file_name":"16_0_4_aboisier_GCJ-Q16-Fractiles.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"280606575","text":"\n# import sludge as sl # after pip install sludge\n\nimport os\nimport sys\nworkdir = os.getcwd()\nsys.path.append(workdir.rstrip('/examples/EnvironmentalBiotechnology_Rittmann/P296_CAS')+'ge/sludge/BioModelMatrix')\nsys.path.append(workdir.rstrip('/examples/EnvironmentalBiotechnology_Rittmann/P296_CAS')+'ge/sludge/')\nsys.path.append(workdir.rstrip('/examples/EnvironmentalBiotechnology_Rittmann/P296_CAS')+'ge/')\nfrom BioModel import *\nfrom TreatmentProcess import *\nfrom Tank import *\nfrom Flow import *\nfrom Grid import *\nfrom Calculation import *\nfrom Plot import *\n\nimport numpy as np\nimport pandas as pd\nimport time\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nplt.style.use('seaborn')\n# %matplotlib inline\n\ntp \t\t\t= TreatmentProcess()\ngd \t\t\t= Grid()\ncal\t\t\t= Calculation()\npl \t\t\t= Plot()\nBoundary\t= Tank_Boundary()\n\t\t\ntank1\t\t= Tank_CSTR(name='tank1', volume=390, Constant_DO=True, DO=7, BioCalculated=True)\ntank2\t\t= Tank_Settlling(name='tank2', volume_Outlet=1, volume_Blanket=1, Constant_DO=True, DO=0.0, BioCalculated=False,SettlingFactor=0.995270858)\n\nQin\t\t\t= Flow_InFlow(name='Qin', flow=1000)\nQr\t\t\t= Flow_RecirFlow(name='Qr', flow=310)\nQw\t\t\t= Flow_WastedFlow(name='Qw', flow=18)\n\nbm\t\t\t= BioModel()\nbm.model_file\t\t\t\t\t= os.getcwd()+\"/P296_matrix.xlsx\"\nbm.amount_BioParameter\t\t\t= 11\nbm.amount_BioProcess\t\t\t= 6\nbm.amount_BioComponent\t\t\t= 7\nbm.amount_BioSolubleComponent\t= 5\nbm.amount_BioComposition\t\t= 1\nbm.amount_BioTested\t\t\t\t= 5\t\nbm.build_BioModel()\nbm.BioParameter_Value \t= np.array(bm.BioParameter['DefaultValue'])\n\nBoundary.Snapshot \t\t= np.array(bm.BioComponent['SteadyStateInfluent'])\ntank1.Snapshot \t\t\t= np.array(bm.BioComponent['InitialValue/SteadyStateResult'])\ntank2.Snapshot_Blanket = np.array(bm.BioComponent['InitialValue/SteadyStateResult'])\ntank2.Snapshot_Outlet \t= np.array(bm.BioComponent['InitialValue/SteadyStateResult'])\nTankStack\t\t\t\t= np.stack((tank1.Snapshot, tank2.Snapshot_Blanket, tank2.Snapshot_Outlet), axis=1)\n\ngd.Grid_dt_second = 60 #s\ngd.Grid_CalcultionTime = 1000\ngd.Grid_TraceTimeReactor = 100\n\ncal.connection(Boundary, tank1, 'InBioComponent(:,1)', Qin)\ncal.connection(tank2, tank1, 'BioComponent(:,2)', Qr, SettlingZone='Blanket')\ncal.connection(tank1, tank2, 'BioComponent(:,1)', Qin+Qr, Qr+Qw)\ncal.connection(tank2, Boundary, 'BioComponent(:,3)', Qin-Qw, SettlingZone='Outlet')\ncal.connection(tank2, Boundary, 'BioComponent(:,2)', Qw, SettlingZone='Blanket')\n\ncal.OpenBLASdir = \"-L/usr/local/OpenBLAS/lib -lopenblas\"\n\ntp.build_TreatmentProcess(globals().items())\ngd.get_trace(tp, bm)\ntp.get_BalnceCheck()\n\ncal.get_Calculation(tp, bm, gd)\nexec('import '+cal.metafile_short.strip('.f90')+' as mcal') # import metaCalculation_short as mcal\n# print(mcal.__doc__)\n\nstart_time = time.time()\ngd.Trace_BioComponent = mcal.main(Boundary.Snapshot, TankStack)\nend_time = time.time()\nprint ('run time:'+str(end_time - start_time)+'s')\n\ngd.get_Trace_Snapshot(tp,bm)\n\n\npl.get_plot_component(tank2, ['S_S', 'S_UAP', 'S_BAP'], SettlingZone ='Outlet', title='tank1 COD')\n# pl.get_plot_biotested(tank1, ['TCOD', 'SCOD'], title='COD')\n# pl.get_plot_biotested(tank1, ['TTN', 'STN', 'NH4', 'NO3'], title='N')\n","sub_path":"sludge/tests/examples/EnvironmentalBiotechnology_Rittmann/P296_CAS/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"174852162","text":"\"\"\"\n@Author : sean cheng\n@Email : aya234@163.com\n@CreateTime : 2018/8/18\n@Program : 练习用PyGame制作一个2048的游戏,\n\"\"\"\n\nimport pygame\nimport sys\nfrom SettingVar import SettingVar\nfrom game_draw import draw_background, draw_game\nfrom GameFunction import init_game, add_elem, can_add_elem, can_move, is_win, win_or_lost\n\nsetting = SettingVar()\n\n\ndef main():\n global screen, tileFont, titleFont, normalFont\n\n pygame.init()\n screen = pygame.display.set_mode((800, 600))\n pygame.display.set_caption('游戏2048 ver 0.28 Program By Sean Cheng')\n\n font_path = 'c:\\\\windows\\\\Fonts\\\\SimHei.ttf'\n tileFont = pygame.font.Font(font_path, 36)\n titleFont = pygame.font.Font(font_path, 48)\n normalFont = pygame.font.Font(font_path, 24)\n resultFont = pygame.font.Font(font_path, 120)\n\n titleText = titleFont.render('游戏2048', True, setting.COLOR_DICT['gray'])\n titleRect = titleText.get_rect()\n titleRect.topleft = 570, 60\n\n btStartText = normalFont.render('开始游戏', True, setting.COLOR_DICT['tomato'])\n btStartRect = btStartText.get_rect()\n btStartRect.topleft = 620, 400\n btResetText = normalFont.render('重置游戏', True, setting.COLOR_DICT['tomato'])\n btResetRect = btResetText.get_rect()\n btResetRect.topleft = 620, 440\n btExitText = normalFont.render('退出游戏', True, setting.COLOR_DICT['tomato'])\n btExitRect = btExitText.get_rect()\n btExitRect.topleft = 620, 480\n\n gameArray = init_game()\n\n gamestatus = None\n\n while True:\n\n draw_background(screen, titleText, titleRect, btStartText, btStartRect, btResetText, btResetRect, btExitText,\n btExitRect)\n # 游戏状态条件的判断\n if gamestatus == 'play':\n gamestatus = win_or_lost(gameArray)\n draw_game(screen, tileFont, gameArray)\n elif gamestatus == 'win':\n winText = resultFont.render('YOU WIN!!', True, setting.COLOR_DICT['tomato'])\n winRect = winText.get_rect()\n winRect.topleft = 0, 0\n elif gamestatus == 'lost':\n lostText = resultFont.render('YOU LOST!!', True, setting.COLOR_DICT['tomato'])\n lostRect = lostText.get_rect()\n lostRect.topleft = 0, 0\n else:\n pass\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit(0)\n elif event.type == pygame.KEYUP and gamestatus == 'play':\n # 只有在游戏状态是play的时候,才按键有效。防止没有点击游戏开始就可以开始玩游戏\n if event.key == pygame.K_ESCAPE:\n pygame.quit()\n sys.exit(0)\n\n elif event.key in (pygame.K_a, pygame.K_LEFT):\n for i in reversed(range(setting.WINDOW_BLOCK_NUM)): # 要反序从右边开始往左边移动,不然只移动一格\n if i > 0:\n for j in range(setting.WINDOW_BLOCK_NUM):\n # 移动元素\n while gameArray[i][j] != 0 and gameArray[i - 1][j] == 0:\n gameArray[i - 1][j] = gameArray[i][j]\n gameArray[i][j] = 0\n # 合并元素\n if gameArray[i][j] == gameArray[i - 1][j]:\n gameArray[i - 1][j] *= 2\n gameArray[i][j] = 0\n add_elem(gameArray)\n\n elif event.key in (pygame.K_d, pygame.K_RIGHT):\n for i in range(setting.WINDOW_BLOCK_NUM):\n if i < setting.WINDOW_BLOCK_NUM - 1:\n for j in range(setting.WINDOW_BLOCK_NUM):\n # 移动元素\n while gameArray[i][j] != 0 and gameArray[i + 1][j] == 0:\n gameArray[i + 1][j] = gameArray[i][j]\n gameArray[i][j] = 0\n # 合并元素\n if gameArray[i][j] == gameArray[i + 1][j]:\n gameArray[i + 1][j] *= 2\n gameArray[i][j] = 0\n add_elem(gameArray)\n\n elif event.key in (pygame.K_w, pygame.K_UP):\n for i in range(setting.WINDOW_BLOCK_NUM):\n for j in reversed(range(setting.WINDOW_BLOCK_NUM)): # 要反序从上面往下面移动,不然只移动一格\n if j > 0:\n # 移动元素\n if gameArray[i][j] != 0 and gameArray[i][j - 1] == 0:\n gameArray[i][j - 1] = gameArray[i][j]\n gameArray[i][j] = 0\n # 合并元素\n if gameArray[i][j] == gameArray[i][j - 1]:\n gameArray[i][j - 1] *= 2\n gameArray[i][j] = 0\n add_elem(gameArray)\n\n elif event.key in (pygame.K_s, pygame.K_DOWN):\n for i in range(setting.WINDOW_BLOCK_NUM):\n for j in range(setting.WINDOW_BLOCK_NUM):\n if j < setting.WINDOW_BLOCK_NUM - 1:\n # 移动元素\n if gameArray[i][j] != 0 and gameArray[i][j + 1] == 0:\n gameArray[i][j + 1] = gameArray[i][j]\n gameArray[i][j] = 0\n # 合并元素\n if gameArray[i][j] == gameArray[i][j + 1]:\n gameArray[i][j + 1] *= 2\n gameArray[i][j] = 0\n add_elem(gameArray)\n\n # 右侧的按键的鼠标事件\n x, y = pygame.mouse.get_pos()\n pressed = pygame.mouse.get_pressed()\n\n # 按键的可用和禁用判断\n if gamestatus != 'play':\n btResetText = normalFont.render('重置游戏', True, setting.COLOR_DICT['gray'])\n else:\n btStartText = normalFont.render('开始游戏', True, setting.COLOR_DICT['gray'])\n\n # 开始游戏按键的鼠标事件,根据游戏状态来判断按键的颜色,只判断游戏状态是否‘start’即可,\n # 因为就算是游戏胜利或者失败,都可以点开始才更符合使用习惯。\n if btStartRect.collidepoint(x, y) and gamestatus != 'play':\n btStartText = normalFont.render('开始游戏', True, setting.COLOR_DICT['yellow'])\n for event in pressed:\n if event == 1:\n gameArray = init_game() # 初始化的游戏数组\n gamestatus = 'play'\n elif gamestatus != 'play':\n btStartText = normalFont.render('开始游戏', True, setting.COLOR_DICT['tomato'])\n\n # 重置游戏按键的鼠标事件,于开始按键类似的理由,只有在游戏的时候才需要重置,胜利和失败都不需要。\n if btResetRect.collidepoint(x, y) and gamestatus == 'play':\n btResetText = normalFont.render('重置游戏', True, setting.COLOR_DICT['yellow'])\n for event in pressed:\n if event == 1:\n gameArray = init_game() # 初始化的游戏数组\n elif gamestatus == 'play':\n btResetText = normalFont.render('重置游戏', True, setting.COLOR_DICT['tomato'])\n\n # 退出游戏按键的鼠标事件,不需要有一个游戏状态的判断,因为这个按键是需要任何时间都可用。\n if btExitRect.collidepoint(x, y):\n btExitText = normalFont.render('退出游戏', True, setting.COLOR_DICT['yellow'])\n for event in pressed:\n if event == 1:\n pygame.quit()\n sys.exit(0)\n else:\n btExitText = normalFont.render('退出游戏', True, setting.COLOR_DICT['tomato'])\n\n pygame.display.update()\n pygame.time.Clock().tick(30)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"game2048/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":8532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"296261333","text":"import requests\nimport datetime as dt\nimport smtplib\nimport time\n\nMY_LATITUDE = -33.4861900\nMY_LONGITUDE = -70.5248500\nGMT = -3\nnow = dt.datetime.now()\n\nISS_API = \"http://api.open-notify.org/iss-now.json\"\nSUN_API = \"https://api.sunrise-sunset.org/json\"\n\nSUN_API_PARAMS = {\n \"lat\" : MY_LATITUDE,\n \"lng\" : MY_LONGITUDE,\n \"formatted\": 0\n}\n\n#...........FUNCTIONS\ndef is_night():\n night_thisnight = [i for i in range(sunset_hour, 24)]\n night_next_morning = [i for i in range(sunrise_hour+1)]\n night_hours = night_thisnight + night_next_morning\n if my_hour in night_hours:\n return True\n\ndef is_near():\n lat_dif = iss_lat - MY_LATITUDE\n lng_dif = iss_lng - MY_LONGITUDE\n if -5 < lat_dif < 5 and -5 < lng_dif < 5:\n return True\n\ndef send_mail():\n my_email = \"test.for.smtplib90@gmail.com\"\n my_password = \"smtplibtest01\"\n to_adress = \"isma.conejeros@gmail.com\"\n msg_subject = \"ISS is near\"\n msg_body = \"Go outside and look up\"\n my_msg = f\"Subject: {msg_subject}\\n\\n{msg_body}\"\n with smtplib.SMTP(\"smtp.gmail.com\") as connection:\n connection.starttls()\n connection.login(user=my_email, password=my_password)\n connection.sendmail(\n from_addr=my_email, \n to_addrs=to_adress, \n msg=my_msg)\n\nwhile True:\n #.......API's\n #ISS\n my_request = requests.get(ISS_API)\n iss_req = my_request.json()\n iss_lat = float(iss_req['iss_position']['latitude'])\n iss_lng = float(iss_req['iss_position']['longitude'])\n\n #......MY PLACE\n my_request = requests.get(SUN_API, params = SUN_API_PARAMS)\n sun_req = my_request.json()\n sunrise = sun_req['results']['sunrise']\n sunset = sun_req['results']['sunset']\n\n #........CONVERT TIME\n my_hour = now.hour\n my_min = now.min\n\n sunrise_list = sunrise.split(\"T\")[1].split(\":\")\n sunrise_hour = int(sunrise.split(\"T\")[1].split(\":\")[0]) + GMT\n\n sunset_list = sunset.split(\"T\")[1].split(\":\")\n sunset_hour = int(sunset.split(\"T\")[1].split(\":\")[0]) + GMT\n\n if is_night() and is_near():\n send_mail()\n else:\n print(f'Not near -> distance = ({iss_lng - MY_LONGITUDE:.2f}, {iss_lat - MY_LATITUDE:.2f})')\n time.sleep(60)\n\n\n","sub_path":"Day 33/33_iss_notifier/iss_notifier.py","file_name":"iss_notifier.py","file_ext":"py","file_size_in_byte":2215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"328115288","text":"#!/usr/bin/env python\nfrom PyQt5.QtGui import QOpenGLWindow,QSurfaceFormat\nfrom PyQt5.QtWidgets import QApplication\nfrom PyQt5.QtCore import *\nimport sys\nfrom pyngl import *\nfrom OpenGL.GL import *\n\nclass MainWindow(QOpenGLWindow) :\n \n def __init__(self, parent=None):\n super(QOpenGLWindow, self).__init__(parent)\n self.cam=Camera()\n self.mouseGlobalTX=Mat4()\n self.width=1024\n self.height=720\n self.setTitle('pyNGL demo')\n self.spinXFace = 0\n self.spinYFace = 0\n self.rotate = False\n self.translate = False\n self.origX = 0\n self.origY = 0\n self.origXPos = 0\n self.origYPos = 0\n self.INCREMENT=0.01\n self.ZOOM=0.1\n self.modelPos=Vec3()\n\n def initializeGL(self) :\n self.makeCurrent()\n NGLInit.instance()\n glClearColor( 0.4, 0.4, 0.4, 1.0 ) \n glEnable( GL_DEPTH_TEST )\n glEnable( GL_MULTISAMPLE )\n shader=ShaderLib.instance()\n shader.loadShader('Phong','shaders/PhongVertex.glsl','shaders/PhongFragment.glsl')\n shader.use('Phong')\n m=Material(STDMAT.GOLD)\n m.loadToShader( \"material\" );\n self.cam.set(Vec3(1,1,1),Vec3.zero(),Vec3.up())\n self.cam.setShape( 45.0, 720.0 / 576.0, 0.05, 350.0 )\n shader.setUniform( \"viewerPos\", self.cam.getEye().toVec3() )\n iv = self.cam.getViewMatrix()\n iv.transpose()\n light=Light( Vec3( -2.0, 5.0, 2.0 ), Colour( 1.0, 1.0, 1.0, 1.0 ), Colour( 1.0, 1.0, 1.0, 1.0 ),LightModes.POINTLIGHT )\n light.setTransform( iv );\n light.loadToShader( 'light' )\n\n\n def loadMatricesToShader(self) :\n shader = ShaderLib.instance()\n\n normalMatrix=Mat3();\n M = self.mouseGlobalTX;\n MV = self.cam.getViewMatrix() * M;\n MVP = self.cam.getVPMatrix() * M;\n normalMatrix = Mat3(MV);\n normalMatrix.inverse().transpose();\n shader.setUniform( \"MV\", MV );\n shader.setUniform( \"MVP\", MVP );\n shader.setUniform( \"normalMatrix\", normalMatrix );\n shader.setUniform( \"M\", M );\n \n def paintGL(self):\n glViewport( 0, 0, self.width, self.height )\n glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT )\n shader=ShaderLib.instance()\n shader.use('Phong')\n #shader.use('nglColourShader')\n #shader.setUniform('Colour',1.0,0.0,0.0,1.0)\n rotX=Mat4();\n rotY=Mat4();\n rotX.rotateX( self.spinXFace );\n rotY.rotateY( self.spinYFace );\n self.mouseGlobalTX = rotY * rotX;\n self.mouseGlobalTX.m_30 = self.modelPos.m_x;\n self.mouseGlobalTX.m_31 = self.modelPos.m_y;\n self.mouseGlobalTX.m_32 = self.modelPos.m_z;\n prim = VAOPrimitives.instance()\n self.loadMatricesToShader()\n prim.draw( \"teapot\" )\n\n def resizeGL(self, w,h) :\n self.width=int(w* self.devicePixelRatio())\n self.height=int(h* self.devicePixelRatio())\n self.cam.setShape( 45.0, float( w ) / h, 0.05, 350.0 )\n\n\n\n def keyPressEvent(self, event) :\n key=event.key()\n if key==Qt.Key_Escape :\n exit()\n elif key==Qt.Key_W :\n glPolygonMode(GL_FRONT_AND_BACK,GL_LINE)\n elif key==Qt.Key_S :\n glPolygonMode(GL_FRONT_AND_BACK,GL_FILL)\n elif key==Qt.Key_Space :\n self.spinXFace=0\n self.spinYFace=0\n self.modelPos.set(Vec3.zero())\n \n self.update()\n\n def mouseMoveEvent(self, event) :\n if self.rotate and event.buttons() == Qt.LeftButton :\n diffx = event.x() - self.origX\n diffy = event.y() - self.origY\n self.spinXFace += int( 0.5 * diffy )\n self.spinYFace += int( 0.5 * diffx )\n self.origX = event.x()\n self.origY = event.y()\n self.update()\n\n elif self.translate and event.buttons() == Qt.RightButton :\n\n diffX = int( event.x() - self.origXPos )\n diffY = int( event.y() - self.origYPos )\n self.origXPos = event.x()\n self.origYPos = event.y()\n self.modelPos.m_x += self.INCREMENT * diffX;\n self.modelPos.m_y -= self.INCREMENT * diffY;\n self.update();\n\n def mousePressEvent(self,event) :\n if event.button() == Qt.LeftButton :\n self.origX = event.x()\n self.origY = event.y()\n self.rotate = True\n\n elif event.button() == Qt.RightButton :\n self.origXPos = event.x();\n self.origYPos = event.y();\n self.translate = True\n\n def mouseReleaseEvent(self,event) :\n if event.button() == Qt.LeftButton :\n self.rotate = False\n\n elif event.button() == Qt.RightButton :\n self.translate = False\n\n def wheelEvent(self,event) :\n numPixels = event.pixelDelta();\n\n if numPixels.x() > 0 :\n self.modelPos.m_z += self.ZOOM\n\n elif numPixels.x() < 0 :\n self.modelPos.m_z -= self.ZOOM\n self.update();\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n format=QSurfaceFormat()\n format.setSamples(4);\n format.setMajorVersion(4);\n format.setMinorVersion(1);\n format.setProfile(QSurfaceFormat.CoreProfile);\n # now set the depth buffer to 24 bits\n format.setDepthBufferSize(24);\n # set that as the default format for all windows\n QSurfaceFormat.setDefaultFormat(format);\n\n window = MainWindow()\n window.setFormat(format)\n window.resize(1024,720)\n window.show()\n sys.exit(app.exec_())\n","sub_path":"RealtimeRendering/SimpleNGL.py","file_name":"SimpleNGL.py","file_ext":"py","file_size_in_byte":5069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"517841630","text":"\"\"\"\nGiven a non negative integer number num. For every numbers i in the range 0 <= i <= num calculate\nthe number of 1's in their binary representation and return them as an array.\n\nExample 1:\n\nInput: 2\nOutput: [0,1,1]\nExample 2:\n\nInput: 5\nOutput: [0,1,1,2,1,2]\nFollow up:\n\nIt is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in\nlinear time O(n) /possibly in a single pass?\n\nSpace complexity should be O(n).\n\nCan you do it like a boss? Do it without using any builtin function like __builtin_popcount\nin c++ or in any other language.\n\"\"\"\n\n# number of 1s in [2-3] is one more than number of 1s in [0-1]\n# number of 1s in [4-7] is one more than number of 1s in [0-3]\n# number of 1s in [8-15] is one more than number of 1s in [0-7] and etc\n\n\n# DP, time O(n), space O(n)\nclass Solution(object):\n def countBits(self, num):\n \"\"\"\n :type num: int\n :rtype: List[int]\n \"\"\"\n dp = [0]\n for i in range(1, num + 1):\n dp.append(dp[i & (i-1)] + 1) # reduce the lower-end 1 to get the number in the previous set, and then +1\n return dp\n\n\nif __name__ == '__main__':\n mySol = Solution()\n x = 5\n print(\"inputs: %s\" % x)\n print('outputs: %s' % mySol.countBits(x))\n","sub_path":"python/counting_bits.py","file_name":"counting_bits.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"64819227","text":"# -*- coding: utf-8 -*-\n\nimport re\n\nfrom django.utils.html import escape\n\n\ndef as_ruby_tags(value):\n '''\n Expects a \"Manabi raw\" format string as input.\n '''\n return re.sub(\n r'|([^《》|]*)《([^《》|]*)》',\n r'\\1\\2',\n escape(value),\n re.UNICODE)\n","sub_path":"manabi/apps/furigana/jinja2.py","file_name":"jinja2.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"629939970","text":"#\n# working.py - Python Fast API Tutorial\n#\n# needs:\n# pip install fastapi\n# pip install uvicorn\n# pip install loguru\n#\n#\n# application server to be started in working.py directory with: \n# uvicorn working:app --reload\n#\n# -------------------------------------------------------------\nfrom fastapi import FastAPI, Path, Query, HTTPException, status\nfrom typing import Optional\nfrom pydantic import BaseModel\nimport psycopg2\nfrom psycopg2 import pool\nfrom loguru import logger\nimport configparser\n\nclass Item(BaseModel):\n item_id: int = 0\n item_text: str = \"\"\n\napp = FastAPI()\n\nlogger.add(\"/tmp/working.log\", format=\"{time} {level} {message}\", level=\"DEBUG\")\n\nconfig = configparser.ConfigParser()\nconfig.read(\"working.ini\")\npg_user = config['default']['user']\npg_password = config['default']['password']\npg_port = config['default']['port']\npg_host = config['default']['host']\npg_database = config['default']['database']\n\n\nconnection_pool = psycopg2.pool.SimpleConnectionPool(\n 1, # minimum number of connections\n 1, # maximum number of connections\n user=pg_user,\n password=pg_password,\n host=pg_host,\n port=pg_port,\n database=pg_database\n )\n\n# Get a connection from the pool\nconnection = connection_pool.getconn()\n\n\n# http://127.0.0.1:8000/\n@app.get(\"/\")\ndef home():\n logger.debug(\"Testing: OK\")\n return {\"Data\": \"Testing\"}\n\n\n# http://127.0.0.1:8000/about\n@app.get(\"/about\")\ndef about():\n logger.debug(\"About: OK\")\n return {\"Data\": \"About\"}\n\n# http://127.0.0.1:8000/get-items\n@app.get(\"/get-items/\")\ndef get_items() :\n item_list = []\n conn = connection\n cur = conn.cursor()\n try:\n cur.execute(\"\"\"\n SELECT item_id, item_text\n FROM public.items;\n \"\"\")\n item_list = cur.fetchall()\n cur.close()\n return item_list\n \n except (Exception, psycopg2.Error) as error:\n print(\"Error in SELECT\", error)\n\n\n# http://127.0.0.1:8000/get-item/1\n@app.get(\"/get-item/{item_id}\")\ndef get_item(p_item: int) -> Item:\n logger.debug(\"entry get_item\")\n conn = connection \n cur = conn.cursor()\n local_item = Item()\n logger.debug(\"try ... SELECT\")\n try:\n cur.execute(\"\"\"\n SELECT item_id, item_text \n FROM public.items \n WHERE item_id = %s;\n \"\"\", [p_item])\n row = (cur.fetchone())\n if row == None:\n local_item.item_id = -1\n local_item.item_text = \"\"\n else:\n local_item.item_id = row[0]\n local_item.item_text = row[1]\n logger.debug(\"end get_item\")\n return local_item\n conn.commit()\n\n except (Exception, psycopg2.Error) as error:\n print(\"Error in SELECT\", error)\n \n cur.close()\n\n\n#\n@app.post(\"/create-item/{item_id}\")\ndef create_item(item: Item):\n logger.debug(\"entry create_item\")\n conn = connection \n cur = conn.cursor() \n try:\n cur.execute(\"\"\"\n INSERT INTO public.items (item_id, item_text)\n VALUES (%s, %s);\n \"\"\", (item.item_id, item.item_text))\n conn.commit()\n cur.close()\n logger.debug(\"end create_item\")\n except (Exception, psycopg2.Error) as error:\n print(\"Error in INSERT\", error)\n conn.rollback() \n\n return item\n\n\n#\n@app.delete(\"/delete-item/{item_id}\")\ndef delete_item(p_item: int):\n local_item = Item()\n conn = connection\n cur = conn.cursor()\n try:\n cur.execute(\"\"\"\n SELECT item_id, item_text \n FROM public.items\n WHERE item_id = %s\n \"\"\", [p_item])\n row = cur.fetchone();\n if (row == None):\n local_item.item_id = -1\n local_item.item_text = \"\"\n return local_item\n else:\n local_item.item_id = row[0]\n local_item.item_text = row[1]\n\n cur.execute(\"\"\"\n DELETE FROM public.items \n WHERE item_id = %s \n \"\"\", [p_item])\n conn.commit()\n cur.close()\n\n except (Exception, psycopg2.Error) as error:\n print(\"Error in DELETE\", error)\n conn.rollback()\n\n return local_item\n\n\n#\n@app.put(\"/update-item/{item_id}\")\ndef update_item(p_item_id: int, p_item: Item):\n local_item = Item()\n conn = connection\n cur = conn.cursor()\n try:\n cur.execute(\"\"\"\n SELECT item_id, item_text \n FROM public.items\n WHERE item_id = %s\n \"\"\", [p_item_id])\n row = cur.fetchone();\n if (row == None):\n local_item.item_id = -1\n local_item.item_text = \"\"\n return local_item\n else:\n # no PK change\n local_item.item_id = p_item_id\n local_item.item_text = p_item.item_text\n\n cur.execute(\"\"\"\n UPDATE public.items \n SET item_text=%s\n WHERE item_id = %s \n \"\"\", (local_item.item_text, local_item.item_id))\n conn.commit()\n cur.close()\n\n except (Exception, psycopg2.Error) as error:\n print(\"Error in UPDATE\", error)\n conn.rollback()\n\n return local_item\n","sub_path":"working.py","file_name":"working.py","file_ext":"py","file_size_in_byte":5458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"201234799","text":"\n\"\"\"\nAuthor: Vipul Pawar\nProject: https://github.com/vipul9/Classification-of-High-Energy-Tracks-using-CNNs\n\"\"\"\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport os\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import dtypes\nimport random\n#import skflow\nfrom tensorflow.contrib import learn as skflow\nimport numpy as np\nfrom scipy import interp\nimport matplotlib.pyplot as plt\n#import plotly.plotly as py\nfrom sklearn.metrics import roc_curve, auc, confusion_matrix\n\n# Dataset Parameters - CHANGE HERE\nMODE = 'folder' # or 'file', if you choose a plain text file (see above).\nTRAIN_DATASET_PATH = './training_dataset' # the dataset file or root folder path.\nTEST_DATASET_PATH = './testing_dataset'\n\n# Image Parameters\nN_CLASSES = 2 # CHANGE HERE, total number of classes\nIMG_HEIGHT = 64 # CHANGE HERE, the image height to be resized to\nIMG_WIDTH = 64 # CHANGE HERE, the image width to be resized to\nCHANNELS = 1 # The 3 color channels, change to 1 if grayscale\n\n\n# Reading the dataset\n# 2 modes: 'file' or 'folder'\ndef read_images(dataset_path, mode, batch_size):\n imagepaths, labels = list(), list()\n if mode == 'file':\n # Read dataset file\n data = open(dataset_path, 'r').read().splitlines()\n for d in data:\n imagepaths.append(d.split(' ')[0])\n labels.append(int(d.split(' ')[1]))\n elif mode == 'folder':\n # An ID will be affected to each sub-folders by alphabetical order\n label = 0\n # List the directory\n try: # Python 2\n classes = sorted(os.walk(dataset_path).next()[1])\n except Exception: # Python 3\n classes = sorted(os.walk(dataset_path).__next__()[1])\n # List each sub-directory (the classes)\n for c in classes:\n c_dir = os.path.join(dataset_path, c)\n try: # Python 2\n walk = os.walk(c_dir).next()\n except Exception: # Python 3\n walk = os.walk(c_dir).__next__()\n # Add each image to the training set\n for sample in walk[2]:\n # Only keeps jpeg images\n if sample.endswith('.png') or sample.endswith('.jpg'):\n imagepaths.append(os.path.join(c_dir, sample))\n labels.append(label)\n label += 1\n else:\n raise Exception(\"Unknown mode.\")\n\n # Convert to Tensor\n imagepaths = tf.convert_to_tensor(imagepaths, dtype=tf.string)\n labels = tf.convert_to_tensor(labels, dtype=tf.int32)\n # Build a TF Queue, shuffle data\n image, label = tf.train.slice_input_producer([imagepaths, labels],\n shuffle=True)\n\n # Read images from disk\n image = tf.read_file(image)\n image = tf.image.decode_jpeg(image, channels=CHANNELS)\n\n # Resize images to a common size\n image = tf.image.resize_images(image, [IMG_HEIGHT, IMG_WIDTH])\n\n # Normalize\n image = image * 1.0/127.5 - 1.0\n\n # Create batches\n X, Y = tf.train.batch([image, label], batch_size=batch_size,\n capacity=batch_size * 8,\n num_threads=4)\n\n return X, Y\n\n# -----------------------------------------------\n# CNN\n# -----------------------------------------------\n\n\n# Parameters\nlearning_rate = 0.001\ntotal_img = 11000 # Total Number of images\nbatch_size = 50 # Batch size for training\nbatch_size_test = 50 # Batch size for testing\n\nepoch_steps = total_img/batch_size\nnum_epoch = 40 # Epoch is one complete presentation of data\nnum_steps = int(num_epoch * epoch_steps)\nnum_steps_test = int(total_img/batch_size_test)\ndisplay_step = 100\ndropout = 0.5 # Dropout, probability to keep units\n\n# Build the data input\nX_train, Y_train = read_images(TRAIN_DATASET_PATH, MODE, batch_size)\nX_train_test, Y_train_test = read_images(TRAIN_DATASET_PATH, MODE, batch_size_test)\nX_test, Y_test = read_images(TEST_DATASET_PATH, MODE, batch_size_test)\n\n# Create model\ndef conv_net(x, n_classes, dropout, reuse, is_training):\n # Define a scope for reusing the variables\n with tf.variable_scope('ConvNet', reuse=reuse):\n\n # Convolution Layer with 32 filters and a kernel size of 5\n conv1 = tf.layers.conv2d(x, 32, 5, activation=tf.nn.relu)\n # Max Pooling (down-sampling) with strides of 2 and kernel size of 2\n conv1 = tf.layers.max_pooling2d(conv1, 2, 2)\n\n # Convolution Layer with 32 filters and a kernel size of 5\n conv2 = tf.layers.conv2d(conv1, 64, 3, activation=tf.nn.relu)\n # Max Pooling (down-sampling) with strides of 2 and kernel size of 2\n conv2 = tf.layers.max_pooling2d(conv2, 2, 2)\n\n # Convolution Layer with 32 filters and a kernel size of 5\n conv3 = tf.layers.conv2d(conv2, 64, 1, activation=tf.nn.relu)\n # Max Pooling (down-sampling) with strides of 2 and kernel size of 2\n conv3 = tf.layers.max_pooling2d(conv3, 2, 2)\n\n # Flatten the data to a 1-D vector for the fully connected layer\n fc1 = tf.contrib.layers.flatten(conv3)\n\n # Fully connected layer (in contrib folder for now)\n fc1 = tf.layers.dense(fc1, 512)\n # Apply Dropout (if is_training is False, dropout is not applied)\n fc1 = tf.layers.dropout(fc1, rate=dropout, training=is_training)\n\n # Output layer, class prediction\n out = tf.layers.dense(fc1, n_classes)\n # Because 'softmax_cross_entropy_with_logits' already apply softmax,\n # we only apply softmax to testing network\n out = tf.nn.softmax(out) if not is_training else out\n\n return out\n\n\n# Because Dropout have different behavior at training and prediction time, we\n# need to create 2 distinct computation graphs that share the same weights.\n\n# Create a graph for training\nlogits_train = conv_net(X_train, N_CLASSES, dropout, reuse=False, is_training=True)\n# Create another graph for testing that reuse the same weights\nlogits_test = conv_net(X_train, N_CLASSES, dropout, reuse=True, is_training=False)\nlogits_train_test = conv_net(X_train_test,N_CLASSES, dropout, reuse=True, is_training=False)\n# Create another graph for testing that reuse the same weights\nlogits_test_test = conv_net(X_test, N_CLASSES, dropout, reuse=True, is_training=False)\n# Define loss and optimizer (with train logits, for dropout to take effect)\nloss_op = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits=logits_train, labels=Y_train))\noptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\ntrain_op = optimizer.minimize(loss_op)\n\n# Evaluate model (with test logits, for dropout to be disabled)\ncorrect_pred = tf.equal(tf.argmax(logits_test, 1), tf.cast(Y_train, tf.int64))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\ncorrect_pred_train = tf.equal(tf.argmax(logits_train_test, 1), tf.cast(Y_train_test, tf.int64),name=\"correct_pred_train\")\ntrue_train, score_train, abs_score_train = tf.cast(Y_train_test, tf.int64), tf.cast(logits_train_test[:,1],tf.float32), tf.argmax(logits_train_test,1)\naccuracy_train = tf.reduce_mean(tf.cast(correct_pred_train, tf.float32),name=\"train_accuracy\")\n\ncorrect_pred_test = tf.equal(tf.argmax(logits_test_test, 1), tf.cast(Y_test, tf.int64),name=\"correct_pred_test\")\ntrue_test, score_test, abs_score_test = tf.cast(Y_test, tf.int64), tf.cast(logits_test_test[:,1],tf.float32), tf.argmax(logits_test_test,1)\naccuracy_test = tf.reduce_mean(tf.cast(correct_pred_test, tf.float32),name=\"test_accuracy\")\n\n# Initialize the variables (i.e. assign their default value)\ninit = tf.global_variables_initializer()\n\n# Saver object\nsaver = tf.train.Saver()\nsum_test = 0\nsum_train = 0\n\ndef pred(y_true,y_score,isSignal):\n pred=list()\n if isSignal:\n for i in range(0,len(y_true)):\n if y_true[i]==1:\n pred.append(y_score[i])\n if not isSignal:\n for i in range(0,len(y_true)):\n if y_true[i]==0:\n pred.append(y_score[i])\n return pred\n# Start training\n\ndef roc(y_true,y_score):\n thresholds = np.linspace(0,1,101)\n ROC = np.zeros((101,2))\n l=len(y_true)\n Y1 = np.zeros(l,dtype=bool)\n Y2 = np.zeros(l,dtype=bool)\n for i in range(0,l):\n Y1[i] = y_true[i] == 1\n Y2[i] = y_true[i] == 0\n for i in range(101):\n t = thresholds[i]\n TP_t = np.logical_and( y_score > t, Y1 ).sum()\n TN_t = np.logical_and( y_score <=t, Y2 ).sum()\n FP_t = np.logical_and( y_score > t, Y2 ).sum()\n FN_t = np.logical_and( y_score <=t, Y1 ).sum()\n FPR_t = float(FP_t) / float(FP_t + TN_t)\n ROC[i,0] = FPR_t\n TPR_t = float(TP_t) / float(TP_t + FN_t)\n ROC[i,1] = TPR_t\n if t>0.49 and t<0.51:\n print(\"t = \"+\"{:.4f}\".format(t)+\", True positive rate = \"+\"{:.4f}\".format(TPR_t)+\", True Negetive Rate = \"+\"{:.4f}\".format(1-FPR_t))\n return ROC[:,0],ROC[:,1]\n\nwith tf.Session() as sess:\n\n # Run the initializer\n sess.run(init)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess,coord=coord)\n\n # Start the data queue\n tf.train.start_queue_runners()\n\n # Training cycle\n for step in range(1,num_steps+1):\n\n if step % display_step == 0:\n # Run optimization and calculate batch loss and accuracy\n _, loss, acc = sess.run([train_op, loss_op, accuracy])\n print(\"Step \" + str(step) + \", Minibatch Loss= \" + \\\n \"{:.4f}\".format(loss) + \", Training Accuracy= \" + \\\n \"{:.3f}\".format(acc))\n else:\n # Only run the optimization op (backprop)\n sess.run(train_op)\n\n print(\"Optimization Finished!\")\n y_true_train, y_score_train, y_abs_score_train, y_true_test, y_score_test, y_abs_score_test = list(),list(),list(),list(),list(),list()\n for step in range(1,num_steps_test+1):\n train_acc = sess.run(accuracy_train)\n test_acc = sess.run(accuracy_test)\n sum_train = float(sum_train) + float(train_acc)\n sum_test = float(sum_test) + float(test_acc)\n y_trueTrain,y_scoreTrain,y_abs_scoreTrain = sess.run([true_train,score_train,abs_score_train])\n y_trueTest, y_scoreTest,y_abs_scoreTest = sess.run([true_test,score_test,abs_score_test])\n y_true_train.extend(y_trueTrain)\n y_score_train.extend(y_scoreTrain)\n y_abs_score_train.extend(y_abs_scoreTrain)\n y_true_test.extend(y_trueTest)\n y_score_test.extend(y_scoreTest)\n y_abs_score_test.extend(y_abs_scoreTest)\n print(\"Step \" + str(step) + \", Training Accuracy= \" + \\\n \"{:.4f}\".format(train_acc) + \", Testing Accuracy= \"+\"{:.4f}\".format(test_acc))\n average_train=float(sum_train/num_steps_test)\n average_test=float(sum_test/num_steps_test)\n print(\"Training Accuracy = \"+ \"{:.4f}\".format(average_train) + \", Testing Accuracy = \" + \"{:.4f}\".format(average_test))\n \n sig_pred_test=pred(y_true_test,y_score_test,isSignal=True)\n bg_pred_test=pred(y_true_test,y_score_test,isSignal=False)\n sig_pred_train=pred(y_true_train,y_score_train,isSignal=True)\n bg_pred_train=pred(y_true_train,y_score_train,isSignal=False)\n #FPR, TPR, _ = roc_curve(y_true_test,y_abs_score_test,pos_label=1)\n FPR,TPR = roc(y_true_test,y_score_test)\n TNR = 1-FPR\n FNR = 1-TPR\n tn,fp,fn,tp = confusion_matrix(y_true_test,y_abs_score_test).ravel()\n AUC = auc(FPR, TPR)\n plt.figure(1)\n plt.plot(FPR, TPR, label='ROC curve (area = %0.2f)' % AUC)\n plt.plot([0, 1], [0, 1], 'r--')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.02])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('ROC Curve')\n plt.legend(loc=\"lower right\")\n\n plt.savefig('ROC.png')\n \n plt.figure(2)\n bins = np.linspace(0, 1, 50)\n counts_sig,bin_edges_sig=np.histogram(sig_pred_train,50)\n bin_centres_sig = (bin_edges_sig[:-1]+bin_edges_sig[1:])/2\n menStd_sig = np.sqrt(counts_sig)\n width = 0.01\n plt.errorbar(bin_centres_sig,counts_sig,yerr=menStd_sig,fmt='o',label='Signal(Training Set)')\n counts_bg,bin_edges_bg=np.histogram(bg_pred_train,50)\n bin_centres_bg = (bin_edges_bg[:-1]+bin_edges_bg[1:])/2\n menStd_bg = np.sqrt(counts_bg)\n plt.errorbar(bin_centres_bg,counts_bg,yerr=menStd_bg,fmt='o',label = 'Background(Training Set)')\n plt.hist(sig_pred_test,label='Signal(Testing set)',bins=bins,histtype='step',color='blue')\n plt.hist(bg_pred_test,label='Background(Testing set)',bins=bins,histtype='step',color='red')\n #plt.hist(sig_pred_train,label='Signal Train',bins=bins,histtype='step',density=True)\n #plt.hist(bg_pred_train,label='Background Train',bins=bins,histtype='step',density=True)\n plt.legend(loc=\"best\")\n plt.xlabel('Output',fontsize=18)\n plt.ylabel('Entries',fontsize=18)\n\n plt.savefig('histo.png')\n \n plt.figure(3)\n plt.plot(TPR,TNR, label = 'ROC curve')\n plt.xlabel('Signal Efficiency')\n plt.ylabel('Background Rejection')\n\n plt.savefig('signal_background.png')\n \n #plt.show()\n \n #saver.save(sess, '/home/dell/my_tf_model')\n coord.request_stop()\n coord.join(threads)\n \n","sub_path":"cnn_model.py","file_name":"cnn_model.py","file_ext":"py","file_size_in_byte":13118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"384498371","text":"import numpy as np \nimport matplotlib.pyplot as plt \nfrom mpl_toolkits.mplot3d import axes3d\nimport ROOT as R\nplt.style.use('ggplot')\nplt.rcParams['text.usetex'] = True\nplt.rcParams['text.latex.unicode'] = True\nplt.rcParams['font.family'] = 'lmodern'\n#a)\ndef rd_lk(a,b,m,seed=0):\n\tx_a = seed #whatever seed value default 0\n\tarr = [] #empty list for storage\n\n\tfor i in range(m): #loop for generation\n\t\tx_n =(a*x_a+b)%m #generates linear kongruent random numbers\n\t\tarr.append(x_n/m) #append normed values\n\t\tx_a = x_n #set new seed\n\n\treturn arr #returns array of normed random numbers \n\ndef pair(L):\n\treturn [(L[i],L[i+1]) for i in range(len(L)-1)] #[for j in range(steps-1)]\n\ndef triple(L):\n\treturn [(L[i],L[i+1],L[i+2]) for i in range(len(L)-2)]\n\ndef ntupel(L,n):\n\treturn [tuple([L[i+j] for j in range(n)]) for i in range(len(L)-n)] #maximale abstraktion\n\n\n\ndef aufg2():\n\t#b)\n\ta = rd_lk(a=1601,b=3456,m=10000)\n\t#b = rd_lk(a=1601,b=3456,m=10000,seed=50) #unterscheidet sich nur wenn seed nicht in voherigem array enthalten\n\t#print(a)\n\tfig = plt.figure(figsize=(16,9))\n\tplt.hist(a,bins=100,rasterized=True,color='red' ,alpha=0.5)\n\t#plt.hist(b,bins=100,rasterized=True,color='navy',alpha=0.5)\n\tplt.xlabel(r'random number value')\n\tplt.ylabel(r'n')\n\t#plt.savefig('rd_lk_2.png',dpi=300)\n\t#plt.show()\n\tplt.clf()\n\ttest = [0,4,2,6,4,8,6,10,8,9,10,11,12,13,14]\n\t#c)\n\tpairs = ntupel(a,2) #pair(a)\n\ttriplel = ntupel(a,3) # triple(a)\n\t\n\t#print(pairs)\n\t#print(triplel)\n\t\n\n\tfig = plt.figure()\n\tax1 = fig.add_subplot(111,projection='3d')\n\t#x , y , z = np.random.normal(size=(3,1000))\n\tx , y , z = zip(*triplel)\n\t\n\t\n\tax1.scatter(x,y,z, lw=0)\n\tax1.view_init(45, 45)\n\tplt.savefig('3dscatter.png',dpi=300)\n\t#plt.show()\n\tplt.clf()\n\n\tfig = plt.figure(figsize=(16,9))\n\tX,Y = zip(*pairs)\n\tplt.scatter(X,Y)\n\tplt.savefig('2dscatter.png',dpi=300)\n\t#plt.show()\n\tplt.clf()\n\n\t#d)\n\n\troot_random = np.zeros(10000)\n\tmyGen = R.TRandom()\n\tmyGen.RndmArray(10000,root_random)\n\tprint(root_random)\n\n\t#e)\n\troot_pairs = ntupel(root_random,2)\n\n\troot_triple = ntupel(root_random,3)\n\n\tfig = plt.figure(figsize=(16,9))\n\tplt.hist(root_random,bins=100,rasterized=True,color='red' ,alpha=0.5)\n\tplt.xlabel(r'random number value')\n\tplt.ylabel(r'n')\n\tplt.savefig('1dhist_root.png',dpi=300)\n\t#plt.show()\n\tplt.clf()\n\n\tfig = plt.figure()\n\tax1 = fig.add_subplot(111,projection='3d')\n\t#x , y , z = np.random.normal(size=(3,1000))\n\tx , y , z = zip(*root_triple)\n\t\n\t\n\tax1.scatter(x,y,z, lw=0)\n\tax1.view_init(45, 45)\n\tplt.savefig('3dscatter_root.png',dpi=300)\n\t#plt.show()\n\tplt.clf()\n\n\tfig = plt.figure(figsize=(16,9))\n\tX,Y = zip(*root_pairs)\n\tplt.scatter(X,Y)\n\tplt.savefig('2dscatter_root.png',dpi=300)\n\t#plt.show()\n\tplt.clf()\n\t#f) ja wenn x=1144 + 10000k \n\n\nif __name__ == '__main__':\n\taufg2()\n","sub_path":"Abgabe_Blatt02/aufgabe2.py","file_name":"aufgabe2.py","file_ext":"py","file_size_in_byte":2738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"53301210","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2021/7/5 17:11\n# @Author : Leanper\n\n# @File : 练习.py\n# @Software: PyCharm\n# @Desc:\n\nimport openpyxl\nwb = openpyxl.load_workbook('studyexcel.xlsx')\nsheet = wb.create_sheet(\"data3\")\nfor x in range(1, 26):\n for y in range(1, 26):\n if x == y:\n sheet.cell(x, y).value = str(x)+\",\"+str(y)\n else:\n sheet.cell(x, y).value = str(x)+\",\"+str(y)\nwb.save(\"studyexcel.xlsx\")\n\nprint(sheet[\"C3:F5\"][0])\n\n\nwb.close()\n","sub_path":"python/study/文件处理/excel/练习.py","file_name":"练习.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"430836268","text":"import logging\nimport datetime\nimport time\nfrom random import randint\nfrom uniflex.core import modules\nfrom uniflex.core import events\nfrom rem_events.sensing_events import *\n\n__author__ = \"Daniel Denkovski\"\n__copyright__ = \"Copyright (c) 2017, Faculty of Electrical Engineering and Information Technologies, UKIM, Skopje, Macedonia\"\n__version__ = \"0.1.0\"\n__email__ = \"{danield}@feit.ukim.edu.mk\"\n\n'''\nLocal controller of WiFi flex device.\nsudo uniflex-agent --config config_slave_1.yaml\n'''\n\nclass WifiFlexLocalController(modules.ControlApplication):\n\tdef __init__(self):\n\t\tsuper(WifiFlexLocalController, self).__init__()\n\t\tself.log = logging.getLogger('WifiFlexLocalController')\n\t\tself._mydev = None\n\t\tself.running = False\n\n\t@modules.on_start()\n\tdef my_start_function(self):\n\t\tself.log.info(\"start local wifi flex controller\")\n\t\tself.running = True\n\n\t\ttry:\n\t\t\tnode = self.localNode\n\t\t\tdevice = node.get_device(0)\n\t\t\tif device:\n\t\t\t\tself._mydev = device\n\n\t\t\twhile (not self._mydev.get_macaddr()): {}\n\n\t\t\tfor dev in node.get_devices():\n\t\t\t\tprint(\"Dev: \", dev.name)\n\n\t\t\tfor m in node.get_modules():\n\t\t\t\tprint(\"Module: \", m.name)\n\n\t\t\tfor apps in node.get_control_applications():\n\t\t\t\tprint(\"App: \", apps.name)\n\n\t\texcept Exception as e:\n\t\t\tself.log.error(\"{} Failed, err_msg: {}\".format(datetime.datetime.now(), e))\n\n\t\tself.log.info('... done')\n\n\t@modules.on_exit()\n\tdef my_stop_function(self):\n\t\tself.log.info(\"stop local wifi flex controller\")\n\t\tself.running = False\n\n","sub_path":"node_app/local_controller.py","file_name":"local_controller.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"598135429","text":"import math\n\nflag='1'\n\nwhile flag=='1':\n\n NumberTest = input('please input the number you wanna test:')\n Number = NumberTest.split(' ')\n sum = 0;n = len(Number); i = 0\n # 输入数据,初始化所需的参数\n\n while i20,.2f} \n its biaozhuncai is {2:<20,.2f}'''.format(u,pp,p))\n # 格式化输出\n\n flag=input('if you wanna test again input \\'1\\' , else input anything without \\'1\\'')\n # 判断是否继续","sub_path":"51_2.py","file_name":"51_2.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"444732836","text":"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import classification_report, confusion_matrix, precision_score, recall_score, f1_score, cohen_kappa_score\n\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import Sequential, Model #, Input\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.layers import LeakyReLU\n\n# Display options dataframes\npd.set_option('display.width',400)\npd.set_option('display.max_columns', 40)\n# Display options numpy arrays\nnp.set_printoptions(edgeitems=10)\nnp.core.arrayprint._line_width = 180\n\n# Wine Dataset retrieved from https://archive.ics.uci.edu/ml/datasets/wine+quality\n\n# Read CSV's for red and white wine\nred_wine = pd.read_csv('/home/becode/LearnAI/Data/Wine Quality/winequality-red.csv', sep=';')\nwhite_wine = pd.read_csv('/home/becode/LearnAI/Data/Wine Quality/winequality-white.csv', sep=';')\n\"\"\"\n# Check out both CSV's\nprint(\"-> RED WINE\")\nprint(red_wine.shape)\nprint(red_wine.head(10))\nprint(red_wine.describe())\nprint(red_wine.sample(10))\nprint(red_wine.isna().sum())\nprint(\"-> WHITE WINE\")\nprint(white_wine.shape)\nprint(white_wine.head(10))\nprint(white_wine.describe())\nprint(white_wine.sample(10))\nprint(white_wine.isna().sum())\n\n# Pairplots for red and white datasets\nsns.pairplot(red_wine)\nplt.show()\n\nsns.pairplot(white_wine)\nplt.show()\n\n# Pearson's coeff in correlation matrix for red and white\ncorr=red_wine.corr()\ntop_features=corr.index\nplt.figure(figsize=(20,20))\nsns.heatmap(red_wine[top_features].corr(),annot=True)\nplt.show()\n\ncorr=white_wine.corr()\ntop_features=corr.index\nplt.figure(figsize=(20,20))\nsns.heatmap(white_wine[top_features].corr(),annot=True)\nplt.show()\n\n\n# Plot alcohol column for both datasets in one image\nfig, ax = plt.subplots(1, 2)\n\nax[0].hist(red_wine.alcohol, 10, facecolor='red', alpha=0.5, label=\"Red wine\")\nax[1].hist(white_wine.alcohol, 10, facecolor='white', ec=\"black\", lw=0.5, alpha=0.5, label=\"White wine\")\n\n#fig.subplots_adjust(left=0, right=1, bottom=0, top=0.5, hspace=0.05, wspace=1)\nax[0].set_ylim([0, 1000])\nax[0].set_xlabel(\"Alcohol in % Vol\")\nax[0].set_ylabel(\"Frequency\")\nax[1].set_xlabel(\"Alcohol in % Vol\")\nax[1].set_ylabel(\"Frequency\")\nfig.suptitle(\"Distribution of Alcohol in % Vol\")\nplt.show()\n\n# You can get the values from numpy histogram function with bins for possible values for alcohol levels\nprint(np.histogram(red_wine.alcohol, bins=[7,8,9,10,11,12,13,14,15]))\nprint(np.histogram(white_wine.alcohol, bins=[7,8,9,10,11,12,13,14,15]))\n\n# Plotting Sulphates vs Quality for both red and white datasets\n\nfig, ax = plt.subplots(1, 2, figsize=(8, 4))\n\nax[0].scatter(red_wine['quality'], red_wine[\"sulphates\"], color=\"red\")\nax[1].scatter(white_wine['quality'], white_wine['sulphates'], color=\"white\", edgecolors=\"black\", lw=0.5)\n\nax[0].set_title(\"Red Wine\")\nax[1].set_title(\"White Wine\")\nax[0].set_xlabel(\"Quality\")\nax[1].set_xlabel(\"Quality\")\nax[0].set_ylabel(\"Sulphates\")\nax[1].set_ylabel(\"Sulphates\")\nax[0].set_xlim([0,10])\nax[1].set_xlim([0,10])\nax[0].set_ylim([0,2.5])\nax[1].set_ylim([0,2.5])\nfig.subplots_adjust(wspace=0.5)\nfig.suptitle(\"Wine Quality by Amount of Sulphates\")\n\nplt.show()\n\n\n# Plot Alcohol - Volatile Acidity for both red and white datasets\nnp.random.seed(570)\n\nredlabels = np.unique(red_wine['quality'])\nwhitelabels = np.unique(white_wine['quality'])\n\nfig, ax = plt.subplots(1, 2, figsize=(8, 4))\nredcolors = np.random.rand(6, 4)\nwhitecolors = np.append(redcolors, np.random.rand(1, 4), axis=0)\n\nfor i in range(len(redcolors)):\n redy = red_wine['alcohol'][red_wine.quality == redlabels[i]]\n redx = red_wine['volatile acidity'][red_wine.quality == redlabels[i]]\n ax[0].scatter(redx, redy, c=redcolors[i])\nfor i in range(len(whitecolors)):\n whitey = white_wine['alcohol'][white_wine.quality == whitelabels[i]]\n whitex = white_wine['volatile acidity'][white_wine.quality == whitelabels[i]]\n ax[1].scatter(whitex, whitey, c=whitecolors[i])\n\nax[0].set_title(\"Red Wine\")\nax[1].set_title(\"White Wine\")\nax[0].set_xlim([0, 1.7])\nax[1].set_xlim([0, 1.7])\nax[0].set_ylim([5, 15.5])\nax[1].set_ylim([5, 15.5])\nax[0].set_xlabel(\"Volatile Acidity\")\nax[0].set_ylabel(\"Alcohol\")\nax[1].set_xlabel(\"Volatile Acidity\")\nax[1].set_ylabel(\"Alcohol\")\n# ax[0].legend(redlabels, loc='best', bbox_to_anchor=(1.3, 1))\nax[1].legend(whitelabels, loc='best', bbox_to_anchor=(1.3, 1))\n# fig.suptitle(\"Alcohol - Volatile Acidity\")\nfig.subplots_adjust(top=0.85, wspace=0.7)\n\nplt.show()\n\n\"\"\"\n## COMBINE BOTH RED AND WHITE INTO 1 DATASET - DO NOTE THAT IT IS A VERY UNBALANCED COMBINATION, 1600 red vs 4900 White\n## BUT FOR THE SAKE OF THE EXPERiMENT WE'LL CONTINUE AS IS\n\n# First add a column 'type' to each dataset; 0 for white, 1 for red\nred_wine['type']= 0\nwhite_wine['type']= 1\nprint(red_wine.sample(10))\nprint(white_wine.sample(10))\n\n## Now we will combine the red and white datasets into 1 dataset which we will use for classification\nwine = pd.concat([red_wine, white_wine], ignore_index=True) # could use append but concat is newer, ignore index of original df's\nprint(wine.shape)\n# Now white isjust below red in one df, so for split random state is very important to split intest and train, also beacuse uneven ratios\n\n# Pearson's from the concatenated dataset\ncorr = wine.corr()\ntop_features=corr.index\nplt.figure(figsize=(20,20))\nsns.heatmap(wine[top_features].corr(),annot=True)\n#plt.show()\n\n## Set up train and test samples via scikit train_test_split\n\n# X,y\nX= wine.drop('type',axis=1) # features\n#y= wine.type # label\ny=np.ravel(wine.type) # label np.ravel 'flattens' y\n\n# Standardize X, y already binary encoded 0,1\nscaler = StandardScaler()\nX = scaler.fit_transform(X)\n\n# Split train/test\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=123)\n\n## MAKE MODEL (binary classification)\n\n# Initialize the constructor\nmodel = Sequential()\n\n# Add an input layer\nmodel.add(Dense(12, activation='relu', input_shape=(12,)))\n\n# Add one hidden layer\nmodel.add(Dense(8, activation='relu'))\n\n# Add an output layer , act= sigmoid so you get probability between 0 and 1\nmodel.add(Dense(1, activation='sigmoid'))\n\n# Model output shape\nprint(model.output_shape)\n\n# Model summary\nprint(model.summary())\n\n# Model config\nmodel.get_config()\n\n# List all weight tensors\nmodel.get_weights()\n\n# Compile and fit model\n#loss function = binary_crossentropy for the binary classification problem of determining whether a wine is red or white.\n# Lastly, with multi-class classification, you’ll make use of categorical_crossentropy\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\nmodel.fit(X_train, y_train, epochs=20, batch_size=1, verbose=1) # in batches of 1\n\n# Predict Values\ny_pred = model.predict(X_test)\n# !! IT IS PARAMOUNT TO ROUND HERE TO INT's TO CALCULATE SCORES, otherwise you\n# get list of floats and you want 0's or 1's !!!\ny_pred = np.round(y_pred)\nprint(y_pred[:5])\nprint(y_test[:5])\n\n# Evaluate model\nscore = model.evaluate(X_test, y_test,verbose=1)\n# score is a list that holds the combination of the loss and the accuracy\nprint(score)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])\n\nprint(f\"confusion_matrix : {confusion_matrix(y_test,y_pred)}\")\nprint(f\"precision_score : {precision_score(y_test,y_pred)}\")\nprint(f\"recall_score : {recall_score(y_test,y_pred)}\")\nprint(f\"f1_score : {f1_score(y_test,y_pred)}\")\n# The Kappa or Cohen’s kappa is the classification accuracy normalized by the imbalance of the classes in the data.\nprint(f\"cohen_kappa_score : {cohen_kappa_score(y_test,y_pred)}\")\n\n\"\"\"\nSUMMARY SCORES:\n[[0.]\n [1.]\n [1.]\n [1.]\n [0.]]\n[0 1 1 1 0]\n41/41 [==============================] - 0s 731us/step - loss: 0.0185 - accuracy: 0.9977\n[0.01851234771311283, 0.9976922869682312]\nTest loss: 0.01851234771311283\nTest accuracy: 0.9976922869682312\nconfusion_matrix : [[329 3]\n [ 0 968]]\nprecision_score : 0.9969104016477858\nrecall_score : 1.0\nf1_score : 0.9984528107271788\ncohen_kappa_score : 0.9939142755491196\n\n\"\"\"\n\n\n\n\n\n\n","sub_path":"Keras/Keras Wine Dataset Classification.py","file_name":"Keras Wine Dataset Classification.py","file_ext":"py","file_size_in_byte":8360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"481061577","text":"# from lib import Base\nfrom sqlite3 import connect\n\nclass temptable:\n def __init__(self, cur):\n self.cur = cur\n def __enter__(self):\n print('criando tabela')\n self.cur.execute('create table if not exists xxxxxx(x int, y int)')\n def __exit__(self, *args):\n print('saindo da tabela')\n self.cur.execute('drop table xxxxxx')\n\nwith connect('test.db') as conn:\n cur = conn.cursor()\n with temptable(cur):\n # cur.execute('create table xxxxxx(x int, y int)')\n cur.execute('insert into xxxxxx (x, y) values(1, 1)')\n cur.execute('insert into xxxxxx (x, y) values(1, 2)')\n cur.execute('insert into xxxxxx (x, y) values(1, 3)')\n cur.execute('insert into xxxxxx (x, y) values(1, 4)')\n # assert hasattr(temptable, 'xxxxxx'), \"fudeu\"\n for row in cur.execute('select x, y from xxxxxx'):\n print(row)\n for row in cur.execute('select sum(x * y) from xxxxxx'):\n print(row)\n # cur.execute('drop table xxxxxx')\n\nprint('yahoo')\n\nprint('demoro')\n# some behavior I want to implemente => write some __ function __\nclass Poly:\n def __init__(self, *coeffs):\n self.coeffs = coeffs\n\n def __repr__(self):\n return 'Poly(*{!r})'.format(self.coeffs)\n\n def __add__(self, other):\n return Poly(*( x + y for x, y in zip(self.coeffs, other.coeffs) ))\n \n def __len__(self):\n return len(self.coeffs)\n\np1 = Poly(1, 2, 3)\np2 = Poly(2, 4, 7)\n\nprint(p1)\nprint(p2)\n\nx = p1 + p2\n\nprint(x)\n\nprint('')\n\n# assert hasattr(Base, 'foo'), \"fudeu\"\n\n# class Derived(Base):\n# def bar(self):\n# return self.foo()\n\n\n# ss = Derived()\n\n# print(ss)","sub_path":"src/assets/py/play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"250239194","text":"# J. Gambino\n# Metis Pre-work\n# August 26, 2017\n\n# Import Libraries\nimport csv\n\n# Parse email address\nwith open('python/faculty.csv') as csvfile:\n faculty = csv.reader(csvfile)\n\n names = []\n degrees = []\n titles = []\n emails = []\n\n for row in faculty:\n names.append(row[0])\n degrees.append(row[1])\n titles.append(row[2])\n emails.append(row[3])\n\n#names = names[1::]\n#degrees = degrees[1::]\n#titles = titles[1::]\nemails = emails[1::]\n\n#for ii in range(0,len(emails)):\n# print(emails[ii])\n\n# Write to CSV File\nwith open('python/emails.csv', 'w+', newline = '') as csvfile:\n writer = csv.writer(csvfile)\n for value in emails:\n writer.writerow([value])\n","sub_path":"python/advanced_python_csv.py","file_name":"advanced_python_csv.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"86096634","text":"import numpy as np\nimport sys\nfrom collections import OrderedDict\n\nprint('Anzahl der Messgrößen eingeben')\np = int(input())\ndata = OrderedDict()\n\n\nhead = \"\"\nfor i in range(0, p):\n print(i+1, 'te Messgröße eingeben')\n v = input()\n data[v] = []\n head += v\n head += \" \"\n\nprint(head)\nprint('Zeilenweise die Messwerte eingeben: ')\nu = 'a'\nwhile u != 'x':\n for k in data:\n u = input()\n if u == 'x':\n break\n data[k].append(float(u))\n print(data[k])\n\nnp.savetxt('T_schwebe_60.txt', np.column_stack(data.values()), header = head)\n\n\n\n\n\nwith open('T_schwebe_60.tex', 'w') as f:\n\n\n f.write('\\\\begin{minipage}{0.49\\textwidth} \\n \\\\centering \\n \\\\begin{tabular}{')\n f.write(p*'S ')\n f.write('} \\n \\\\toprule \\\\\\ \\n')\n\n helpindex = 0\n for key in data.keys():\n if helpindex == p-1:\n f.write('$'+ key + '$ \\\\\\ \\n')\n else:\n f.write('$' + key + '$ & ')\n helpindex +=1\n\n\n\n\n f.write('\\\\midrule \\\\\\ \\n ')\n\n rowCount = len(data[v])\n for j in range(0, rowCount):\n helpindex = 0\n for i in data:\n\n if helpindex == p-1:\n f.write('{:.2f} \\\\\\ \\n '.format(data[i][j]))\n else:\n f.write('{:.2f} & '.format(data[i][j]))\n helpindex += 1\n\n\n f.write('\\\\bottomrule \\n \\\\end{tabular} \\n \\\\captionof{table}{...} \\n \\\\label{tab:...} \\n \\\\end{minipage}')\n","sub_path":"PHY341/V106_Pendel/Messdaten/input.py","file_name":"input.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"595607464","text":"def conflict(state, nextx):\n nexty = len(state)\n for i in range(nexty):\n #保证x坐标不相等,x.y的差值不想等即不在一条直线上\n if abs(state[i] - nextx) in (0, nexty - i):\n return True\n return False\n\n\ndef queens(num=8, state=()):\n for pos in range(num):\n if not conflict(state, pos):\n if len(state) == num-1:\n yield (pos, )\n else:\n for result in queens(num, state + (pos, )):\n yield (pos, ) + result\n\n\nlist1 = list(queens())\nprint(list1)","sub_path":"8皇后.py","file_name":"8皇后.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"217439534","text":"#!flask/bin/python\nfrom flask import Flask, jsonify\nfrom Main import main\napp = Flask(__name__)\n\ntasks = [\n {\n 'id': 1,\n 'title': u'Get Tweets',\n 'description': u'Get tweets of a user',\n 'done': False\n },\n {\n 'id': 2,\n 'title': u'Learn Python',\n 'description': u'Need to find a good Python tutorial on the web',\n 'done': False\n }\n]\n\n#@app.route('/TwitterApi/api/v1.0/tasks', methods=['GET'])\n#@app.route('/TwitterApi/api/v1.0/GetTweets', methods=['GET'])\n@app.route('/TwitterApi/api/v1.0/Tweets/', methods=['GET'])\ndef get_Tweets(scr_name):\n sucessful = False\n try:\n main(scr_name)\n sucessful = True\n except Exception as e:\n sucessful = False\n\n\n return jsonify({'successful': sucessful})\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"552802201","text":"import time\n\nclass Mytel:\n\n def __init__(self, brand, model, prodate, imei, contacts):\n self.brand = brand\n self.model = model\n self.prodate = prodate\n self.imei = imei\n self.contacts = contacts\n self.contacts = {}\n\n def showInfo(self):\n print(\"\"\"\n MyTel Information:\n Brand : {}\n Model : {}\n Pro Date: {}\n Imei No : {}\n Contacts: {}\n \"\"\".format(self.brand, self.model, self.prodate, self.imei, self.contacts))\n\n def contactsAdd(self, name, tel):\n print(\"Adding your contacttt\")\n self.contacts[name] = tel\n time.sleep(1)\n print(\"Your contact addedd\\n\")\n time.sleep(1)\n\n def showContacts(self):\n for name, tel in self.contacts.items():\n print(\"Your contacts list\")\n print(name, ':', tel)\n time.sleep(2)\n\n def contactsDelete(self, sel):\n sel = input(\"Name of the contact to delete:\")\n if sel in self.contacts:\n print(\"Deletinggg..\")\n self.contacts.pop(sel)\n\n time.sleep(1)\n print(\"Deleteddd\\n\")\n time.sleep(1)\n else:\n print(\"Name is not in contact list\\n\")\n time.sleep(1)\n\n def dial(self):\n for name, tel in self.contacts.items():\n print(name, ':', tel)\n name = input('Enter contact name to dial\\n')\n if name in self.contacts:\n print(f'{self.contacts[name]} dialinggg....\\n')\n time.sleep(3)\n print(f'{self.contacts[name]} is not available or outof coverage\\n')\n else:\n print(\"please check your contact's name\\n\")\n\ntelim = Mytel(\"LaCasa\", \"Black\", \"August 2019\", 123456789, [\"233\"])\nprint(\"Welcome To Telephone Book Trials\")\n\nwhile True:\n sel = input(\" ____Please choose your transaction___ \\n\"\n \"*View your phone info...1\\n\"\n \"*Add new contact ....2\\n\"\n \"*Browse contacts ....3\\n\"\n \"*Dial contact ....4\\n\"\n \"*Delete contact ....5\\n\"\n \"*Save&Exit *anykey*\\n\")\n###########################################################\n if sel == '1':\n telim.showInfo()\n time.sleep(2)\n###########################################################\n elif sel == '2':\n name = input('New contact name: ')\n tel = input('New contact number: ')\n telim.contactsAdd(name, tel)\n###########################################################\n elif sel == '3':\n telim.showContacts()\n###########################################################\n elif sel == '4':\n telim.dial()\n###########################################################\n elif sel == '5':\n\n telim.contactsDelete(sel)\n###########################################################\n else:\n print('Please wait shutting down!')\n time.sleep(1)\n print(\"Goodbye!!!\")\n quit()\n","sub_path":"telim.py","file_name":"telim.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"304865574","text":"import sys\nimport heapq\nfrom decimal import Decimal\n\ninput = sys.stdin.readline\na, b, c = map(str, input().split())\n\nroot_a = Decimal(a)**Decimal('0.5')\nroot_b = Decimal(b)**Decimal('0.5')\nroot_c = Decimal(c)**Decimal('0.5')\n\n\nif root_a + root_b < root_c:\n print(\"Yes\")\nelse:\n print(\"No\")","sub_path":"Python_codes/p02743/s150770834.py","file_name":"s150770834.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"529201288","text":"from typing import List\n\n\ndef main():\n steps = []\n with open('inputs/02.txt') as input_file:\n for line in input_file:\n steps.append(line.split())\n return part1(steps), part2(steps)\n\n\ndef part1(steps: List[List[str]]):\n depth = 0\n horz = 0\n for direction, num in steps:\n if direction == 'forward':\n horz = horz + int(num)\n elif direction == 'down':\n depth = depth + int(num)\n elif direction == 'up':\n depth = depth - int(num)\n return depth * horz\n\n\ndef part2(steps: List[List[str]]):\n aim = 0\n depth = 0\n horz = 0\n for direction, num in steps:\n if direction == 'forward':\n horz = horz + int(num)\n depth = depth + (aim * int(num))\n elif direction == 'down':\n aim = aim + int(num)\n elif direction == 'up':\n aim = aim - int(num)\n return depth * horz\n\n\nif __name__ == '__main__':\n result = main()\n print(result)\n","sub_path":"2021/02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"364237062","text":"from pc_lib import pc_api, pc_utility\n\n# --Configuration-- #\n\nparser = pc_utility.get_arg_parser()\n# INSERT ARGS HERE\nargs = parser.parse_args()\n\n# --Initialize-- #\n\npc_utility.prompt_for_verification_to_continue(args)\nsettings = pc_utility.get_settings(args)\npc_api.configure(settings)\n\n# --Main-- #\n\n# INSERT CODE HERE\nresult = pc_api.current_user()\nprint(result)","sub_path":"pc-script-example.py","file_name":"pc-script-example.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"175534146","text":"#!/usr/bin/env python\n# Oswald Berthold 2017\n# \n# - oneoverfnoise is a python port of gennoise.c by paul bourke\n# - levyflight is homegrown (?)\n\nfrom __future__ import print_function\n\nimport argparse\nimport numpy as np\nimport matplotlib.pylab as plt\nfrom sklearn.preprocessing import normalize\n\nimport logging\nfrom smp_base.common import get_module_logger\n\nlogger = get_module_logger(modulename = 'gennoise', loglevel = logging.INFO)\n\nN = 8192\nTWOPOWER = 13\nTWOPI = 6.283185307179586476925287\n\ndef next_point(prev):\n \"choose next destination\"\n mode = \"np\"\n alpha = 1.5\n # angle = random.uniform(0,(2*math.pi))\n if mode == \"random\":\n angle = random.normalvariate(0,1.8)\n distance = 2 * random.paretovariate(alpha)\n # distance = 2 * random.weibullvariate(1.0, 0.9)\n elif mode == \"np\":\n angle = np.random.normal(0, 1.8)\n distance = np.random.pareto(alpha)\n # cap distance at DMAX\n # if distance > DMAX:\n # distance = DMAX\n point = [(np.sin(angle) * distance)+prev[0], (np.cos(angle) * distance)+prev[1]]\n return np.asarray(point)\n\nclass Noise(object):\n def __init__(self):\n pass\n\n @classmethod\n def oneoverfnoise(self, N, beta, normalize = False):\n \"\"\"generate 1/f noise\n\n Arguments:\n - N(int): length\n - beta(float): 1/f**beta\n\n Returns:\n - tuple(freq, time) aka complex spectrum 'compl' and timeseries 'ts'\n \"\"\"\n # initialize complex component vectors\n real = np.zeros((N,))\n imag = np.zeros((N,))\n\n # iterate FFT bands up to nyquist\n # FIXME: vectorize this\n for i in range(1, N/2):\n # spectrum magnitude from eq. ?\n # mag = (i+1)**(-beta/2.) * np.random.normal(0., 1.)\n mag = np.power(i+1, -beta/2.) * np.random.normal(0., 1.)\n # mag = np.power(i+1, -beta/2.) * np.random.uniform(0., 1.)\n # spectrum phase random\n pha = TWOPI * np.random.uniform()\n\n # convert polar to cartesian\n real[i] = mag * np.cos(pha)\n imag[i] = mag * np.sin(pha)\n \n # fix corner case\n real[N-i] = real[i]\n imag[N-i] = -imag[i]\n imag[N/2] = 0\n\n # complex array\n compl = real + (imag*1j)\n \n # normalize spectral energy\n if normalize:\n compl /= np.linalg.norm(compl)\n \n # print(compl)\n ts = np.fft.ifft(compl) * N\n logger.debug('timeseries ts is type = %s, shape = %s, var = %s from ifft(compl)' % (type(ts), ts.shape, np.var(ts)))\n # if normalize:\n # ts /= np.abs(ts)\n logger.debug('timeseries ts is type = %s, shape = %s, var = %s from ifft(compl)' % (type(ts), ts.shape, np.var(ts)))\n return(compl, ts)\n\n @classmethod\n def levyflight(self, N):\n p = np.asarray([0,0])\n q = p\n qn = p\n numsamp = N\n p_ = np.zeros((numsamp, 2))\n # i = 0\n \n for i in range(numsamp):\n # q = next_point(p)\n # print(p, q)\n # p = q\n # add point\n if np.linalg.norm(qn - q) <= 1:\n q = next_point(p)\n dp = np.asarray(q)-np.asarray(p)\n # print(\"1\", dp)\n dp = normalize(dp[:,np.newaxis], axis=0).ravel()\n # print(\"2\", dp)\n # print(dp)\n qn = p + 1 * dp\n # draw line\n # pygame.draw.line(screen, white, p, qn, 1)\n p = qn\n p_[i,:] = p\n return p_\n \nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-b\", \"--beta\", type=float, default=0.)\n parser.add_argument(\"-l\", \"--len\", type=int, default=8192)\n parser.add_argument(\"-s\", \"--seed\", type=int, default=0)\n args = parser.parse_args()\n\n print(\"gennoise.main: args = %s\" % (args, ))\n \n beta = args.beta\n N = args.len\n seed = args.seed\n\n np.random.seed(seed)\n\n (compl, ts) = Noise.oneoverfnoise(N, beta, normalize = True)\n print(\"gennoise.main: compl = %s, ts = %s\" %(compl, ts))\n\n real = compl.real\n imag = compl.imag\n \n print(\"gennoise.main: real = %s, imag = %s\" %(real, imag))\n\n fig = plt.figure()\n \n ax1 = fig.add_subplot(2,1,1)\n ax1.set_title('Noise spectrum (real/imag)')\n ax1.plot(real, label = \"real\")\n ax1.plot(imag, label = \"imag\")\n ax1.legend()\n # np.fft.ifft()\n\n # print(ts.real)\n\n ax2 = fig.add_subplot(2,1,2)\n ax2.set_title('Noise timeseries (real)')\n ax2.plot(ts.real)\n\n fig.show()\n plt.show()\n","sub_path":"smp_base/gennoise.py","file_name":"gennoise.py","file_ext":"py","file_size_in_byte":4648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"215579416","text":"from typing import ValuesView\nimport torch\nfrom torch import nn\n\nfrom augmentation import SimCLR_augment\n\n\ndef get_encoder(net: nn.Module) -> nn.Module:\n \"\"\" input a network and output it's convolutional feature encoder\"\"\"\n return nn.Sequential(*(list(net.children())[:-1]))\n\n\ndef MLP(in_size, out_size, hidden_size=4096):\n return nn.Sequential(\n nn.Linear(in_size, hidden_size),\n nn.BatchNorm1d(hidden_size),\n nn.ReLU(inplace=True),\n nn.Linear(hidden_size, out_size)\n )\n\n\nclass SimSiam(nn.Module):\n def __init__(self, net: nn.Module) -> None:\n super().__init__()\n num_features = net.fc.in_features\n self.augment1 = SimCLR_augment\n self.augment2 = SimCLR_augment\n\n self.encoder = get_encoder(net)\n self.projector = MLP(in_size=num_features, out_size=256)\n self.predictor = MLP(in_size=256, out_size=256)\n\n self.criterion = nn.CosineSimilarity(dim=1)\n\n def forward(self, x):\n view1, view2 = self.augment1(x), self.augment2(x)\n proj1, proj2 = self.projector(self.encoder(view1)), self.projector(self.encoder(view2))\n pred1, pred2 = self.predictor(proj1), self.predictor(proj2)\n loss = -(self.criterion(proj1, pred2).mean() +\n self.criterion(proj2, pred1).mean()) * 0.5\n return loss.mean()\n","sub_path":"SimSiam.py","file_name":"SimSiam.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"176308940","text":"import asyncio\r\nimport os\r\nfrom datetime import datetime\r\nfrom selenium import webdriver\r\nimport threading\r\nfrom Servers import SendData\r\n\r\nWebsite = None\r\nThread1 = None\r\nThread2 = None\r\n\r\n\r\ndef DnD_monster(url_tag):\r\n global Website\r\n Website.switch_to_window(Website.window_handles[0]) # switches to first\r\n Website.get(url=url_tag)\r\n Image = Website.find_element_by_class_name('container').screenshot(\r\n r\"D:\\Innkeeper\\TempFiles/ScreenShot.png\")\r\n\r\n\r\ndef homebrew_monster(url_tag):\r\n global Website\r\n AmountOfTabs = len(Website.window_handles) # Gets tabs index\r\n Website.switch_to_window(Website.window_handles[AmountOfTabs - 1]) # switches to the last tab\r\n Website.get(url=url_tag)\r\n Image = Website.find_element_by_class_name('mw-parser-output').screenshot(\r\n r\"D:\\Innkeeper\\TempFiles/ScreenShot2.png\")\r\n\r\n\r\nasync def LoopCheck1():\r\n global Thread1\r\n while True:\r\n if not Thread1.is_alive():\r\n return True\r\n break\r\n\r\n\r\nasync def LoopCheck2():\r\n global Thread2\r\n while True:\r\n if not Thread2.is_alive():\r\n return True\r\n break\r\n\r\n\r\nasync def organiser(message, Data, ThreadNo, MonsterName, LastMessage):\r\n global Thread1, Thread2\r\n \"\"\"\r\n Items[0] - The index used to determine if its Homebrew or 5e, this determines what tab selenium loads on\r\n Items[1] - url tag\r\n \"\"\"\r\n\r\n Items = message.split(\"|\") # \"|\" is used to split items up from the request\r\n if Items[0] == \"0\": # 5e Monster (Donjon)\r\n Thread1 = threading.Thread(target=DnD_monster, args=(Items[1],))\r\n Thread1.start()\r\n try:\r\n Complete = await asyncio.wait_for(LoopCheck1(), timeout=2)\r\n if Complete:\r\n await SendData.Send(Data, 1, MonsterName, LastMessage)\r\n except asyncio.TimeoutError:\r\n await Data.channel.send(\"Oop! the request took too long to come back!\")\r\n\r\n elif Items[0] == \"1\": # Homebrew Monster (D&D Wiki)\r\n Thread2 = threading.Thread(target=homebrew_monster, args=(Items[1],))\r\n Thread2.start()\r\n try:\r\n Complete = await asyncio.wait_for(LoopCheck2(), timeout=2)\r\n if Complete:\r\n await SendData.Send(Data, 2, MonsterName, LastMessage)\r\n except asyncio.TimeoutError:\r\n await Data.channel.send(\"Oop! the request took too long to come back!\")\r\n\r\n\r\n else:\r\n print(f\"[{datetime.now().strftime('%y/%m/%d | %M:%M:%S')}] An Invalid Index has been sent to the monster server!\")\r\n\r\n\r\ndef loading(Paths):\r\n global Website\r\n os.environ['MOZ_FORCE_DISABLE_E10S'] = '1' # Force OS to allow Multiprocess firefox - IMPORTANT!\r\n\r\n Website = webdriver.Firefox(\r\n executable_path=Paths[\"GeckoDriver\"])\r\n Website.execute_script(\"window.open()\") # open tabs 1 , 2 to then toggle between\r\n AmountOfTabs = len(Website.window_handles) # Gets tabs index\r\n Website.switch_to_window(Website.window_handles[AmountOfTabs - 1]) # switches to the last tab\r\n Website.get(url=\"https://www.dandwiki.com/wiki/\")\r\n Website.switch_to_window(Website.window_handles[0]) # switches to last tab\r\n Website.get(url=\"http://www.jsigvard.com/dnd/\")\r\n","sub_path":"Servers/Monster_Server.py","file_name":"Monster_Server.py","file_ext":"py","file_size_in_byte":3228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"369933449","text":"import torch\nimport torch.nn as nn\nfrom mlearn import base\nimport torch.nn.functional as F\n\n\nclass LSTMClassifier(nn.Module):\n \"\"\"LSTM classifier.\"\"\"\n\n def __init__(self, input_dim: int, embedding_dim: int, hidden_dim: int, output_dim: int, num_layers: int,\n dropout: float = 0.0, batch_first: bool = True, **kwargs) -> None:\n \"\"\"\n Initialise the LSTM.\n\n :input_dim (int): The dimensionality of the input to the embedding generation.\n :hidden_dim (int): The dimensionality of the hidden dimension.\n :output_dim (int): Number of classes for to predict on.\n :num_layers (int): The number of recurrent layers in the LSTM (1-3).\n :dropout (float, default = 0.0): Value of dropout layer.\n :batch_first (bool, default = True): Batch the first dimension?\n \"\"\"\n super(LSTMClassifier, self).__init__()\n self.batch_first = batch_first\n self.name = 'onehot_lstm'\n self.info = {'Input dim': input_dim,\n 'Embedding dim': embedding_dim,\n 'Hidden dim': hidden_dim,\n 'Output dim': output_dim,\n '# Layers': num_layers,\n 'Dropout': dropout,\n 'Model': self.name,\n 'nonlinearity': 'tanh'\n }\n\n self.itoh = nn.Linear(input_dim, embedding_dim)\n self.lstm = nn.LSTM(embedding_dim, hidden_dim, num_layers, batch_first = batch_first)\n self.htoo = nn.Linear(hidden_dim, output_dim)\n\n # Set the method for producing \"probability\" distribution.\n self.dropout = nn.Dropout(dropout)\n self.softmax = nn.LogSoftmax(dim = 1)\n\n def forward(self, sequence: base.DataType) -> base.DataType:\n \"\"\"\n Forward step in the classifier.\n\n :sequence: The sequence to pass through the network.\n :return (base.DataType): The \"probability\" distribution for the classes.\n \"\"\"\n if not self.batch_first:\n sequence = sequence.transpose(0, 1)\n\n sequence = sequence.float()\n out = self.itoh(sequence) # Get embedding for the sequence\n out, (last_layer, _) = self.lstm(out) # Get layers of the LSTM\n out = self.htoo(self.dropout(last_layer))\n prob_dist = self.softmax(out) # The probability distribution\n\n return prob_dist.squeeze(0)\n\n\nclass MLPClassifier(nn.Module):\n \"\"\"MLP Classifier.\"\"\"\n\n def __init__(self, input_dim: int, hidden_dim: int, output_dim: int, dropout: float = 0.0,\n nonlinearity: str = 'tanh', batch_first: bool = True, **kwargs) -> None:\n \"\"\"\n Initialise the model.\n\n :input_dim (int): The dimension of the input to the model.\n :hidden_dim (int): The dimension of the hidden layer.\n :output_dim (int): The dimension of the output layer (i.e. the number of classes).\n :dropout (float, default = 0.0): Value of dropout layer.\n :nonlinearity (str, default = 'tanh'): String name of nonlinearity function to be used.\n :batch_first (bool): Batch the first dimension?\n \"\"\"\n super(MLPClassifier, self).__init__()\n self.batch_first = batch_first\n self.name = 'onehot_mlp'\n self.info = {'Model': self.name,\n 'Input dim': input_dim,\n 'Hidden dim': hidden_dim,\n 'Output dim': output_dim,\n 'nonlinearity': nonlinearity,\n 'Dropout': dropout\n }\n\n self.itoh = nn.Linear(input_dim, hidden_dim)\n self.htoh = nn.Linear(hidden_dim, hidden_dim)\n self.htoo = nn.Linear(hidden_dim, output_dim)\n\n # Set dropout and non-linearity\n self.dropout = nn.Dropout(dropout)\n self.nonlinearity = torch.relu if nonlinearity == 'relu' else torch.tanh\n self.softmax = nn.LogSoftmax(dim = 1)\n\n def forward(self, sequence: base.DataType):\n \"\"\"\n Forward step in the classifier.\n\n :sequence: The sequence to pass through the network.\n :return (base.DataType): The \"probability\" distribution for the classes.\n \"\"\"\n if self.batch_first:\n sequence = sequence.transpose(0, 1)\n\n sequence = sequence.float()\n out = self.dropout(self.nonlinearity(self.itoh(sequence)))\n out = self.dropout(self.nonlinearity(self.htoh(out)))\n out = out.mean(0)\n out = self.htoo(out)\n prob_dist = self.softmax(out) # Re-shape to fit batch size.\n\n return prob_dist\n\n\nclass CNNClassifier(nn.Module):\n \"\"\"CNN Classifier.\"\"\"\n\n def __init__(self, window_sizes: base.List[int], num_filters: int, input_dim: int, hidden_dim: int, output_dim: int,\n nonlinearity: str = 'relu', batch_first: bool = True, **kwargs) -> None:\n \"\"\"\n Initialise the model.\n\n :window_sizes (base.List[int]): The size of the filters (e.g. 1: unigram, 2: bigram, etc.)\n :num_filters (int): The number of filters to apply.\n :input_dim (int): The input dimension (can and should be limited beyond the raw input dimensions).\n :hidden_dim (int): Hidden dimension size.\n :output_dim (int): Output dimension.\n :nonlinearity (str): Name of nonlinearity function to use.\n :batch_first (bool, default: True): True if the batch is the first dimension.\n \"\"\"\n super(CNNClassifier, self).__init__()\n self.batch_first = batch_first\n self.name = 'onehot_cnn'\n self.info = {'Model': self.name,\n 'Window Sizes': \" \".join([str(it) for it in window_sizes]),\n '# Filters': num_filters,\n 'Input dim': input_dim,\n 'Hidden dim': hidden_dim,\n 'Output dim': output_dim,\n 'nonlinearity': nonlinearity\n }\n\n self.itoh = nn.Linear(input_dim, hidden_dim) # Works\n self.conv = nn.ModuleList([nn.Conv2d(1, num_filters, (w, hidden_dim)) for w in window_sizes])\n self.linear = nn.Linear(len(window_sizes) * num_filters, output_dim)\n self.nonlinearity = torch.relu if nonlinearity == 'relu' else torch.tanh\n self.softmax = nn.LogSoftmax(dim = 1)\n\n def forward(self, sequence) -> base.DataType:\n \"\"\"\n Forward step of the model.\n\n :sequence: The sequence to be predicted on.\n :return (base.DataType): The probability distribution computed by the model.\n \"\"\"\n # CNNs expect batch first so let's try that\n if not self.batch_first:\n sequence = sequence.transpose(0, 1)\n\n sequence = sequence.float()\n emb = self.itoh(sequence) # Get embeddings for sequence\n output = [self.nonlinearity(conv(emb.unsqueeze(1))).squeeze(3) for conv in self.conv]\n output = [F.max_pool1d(i, i.size(2)).squeeze(2) for i in output]\n output = torch.cat(output, 1)\n prob_dist = self.softmax(self.linear(output))\n\n return prob_dist\n\n\nclass RNNClassifier(nn.Module):\n \"\"\"RNN Classifier.\"\"\"\n\n def __init__(self, input_dim: int, hidden_dim: int, output_dim: int, dropout: float = 0.0, batch_first: bool = True,\n nonlinearity: str = 'tanh', **kwargs) -> None:\n \"\"\"\n Initialise the RNN classifier.\n\n :input_dim (int): The dimension of the input to the network.\n :hidden_dim (int): The dimension of the hidden representation.\n :output_dim (int): The dimension of the output representation.\n :dropout (float, default = 0.0): The value of the dropout layer.\n :batch_first (bool): Is batch the first dimension?\n :nonlinearity (str, default = 'tanh'): Set nonlinearity function.\n \"\"\"\n super(RNNClassifier, self).__init__()\n self.batch_first = batch_first\n self.name = 'onehot_rnn'\n self.info = {'Model': self.name,\n 'Input dim': input_dim,\n 'Hidden dim': hidden_dim,\n 'Output dim': output_dim,\n 'Dropout': dropout,\n 'nonlinearity': nonlinearity\n }\n\n # Initialise the hidden dim\n self.hidden_dim = hidden_dim\n\n # Define layers of the network\n self.itoh = nn.Linear(input_dim, hidden_dim)\n self.rnn = nn.RNN(hidden_dim, hidden_dim, batch_first = batch_first, nonlinearity = nonlinearity)\n self.htoo = nn.Linear(hidden_dim, output_dim)\n\n # Set the method for producing \"probability\" distribution.\n self.dropout = nn.Dropout(dropout)\n self.softmax = nn.LogSoftmax(dim=1)\n\n def forward(self, sequence) -> base.DataType:\n \"\"\"\n Forward step in the network.\n\n :inputs: The inputs to pass through network.\n :hidden: The hidden representation at the previous timestep.\n :return (base.DataType): Return the \"probability\" distribution and the new hidden representation.\n \"\"\"\n if not self.batch_first:\n sequence = sequence.transpose(0, 1)\n\n sequence = sequence.float()\n hidden = self.itoh(sequence) # Map from input to hidden representation\n hidden, last_h = self.rnn(hidden)\n output = self.htoo(self.dropout(last_h)) # Map from hidden representation to output)\n prob_dist = self.softmax(output) # Generate probability distribution of output\n\n return prob_dist.squeeze(0)\n","sub_path":"mlearn/modeling/onehot.py","file_name":"onehot.py","file_ext":"py","file_size_in_byte":9464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"268491230","text":"import nuke\nimport nukescripts.snap3d\n\n\n\ndef delTracker():\n node = nuke.thisNode()\n index = nuke.thisKnob().name()\n index = index.split('_')[1]\n\n track_name = 'Tracker_{}'.format(index)\n del_name = 'Delete_{}'.format(index)\n\n track_knob = node.knob(track_name)\n del_knob = node.knob(del_name)\n\n node.removeKnob(track_knob)\n node.removeKnob(del_knob)\n\t\n\t\t\n\t\n\ndef addTracker( vtx_pos ):\n #Grab this node and et index init\n node = nuke.selectedNode()\n index = node.knob('index').value()\n index = int(index) # value return a float\n \n pos_name =\"Tracker_{}\".format(index)\n del_name = 'Delete_{}'.format(index)\n pos_knob = nuke.XYZ_Knob(pos_name)\n del_knob = nuke.PyScript_Knob(del_name,\"Delete\", \"delTracker()\")\n\n pos_knob.setAnimated()\n pos_knob.setValue( vtx_pos ) \n pos_knob.setTooltip('value')\n \n node.addKnob(pos_knob)\n node.addKnob(del_knob)\n node.knob('index').setValue(index+1)\n\nvsel = nukescripts.snap3d.getSelection()\nfor v in vsel:\n tracker_list = ()\n pos = (v.position.x, v.position.y, v.position.z)\n addTracker(pos)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"294684858","text":"from collections import namedtuple\nimport io\n\nfrom reportlab.lib.pagesizes import portrait, A5\nfrom reportlab.lib.units import cm\nfrom reportlab.pdfbase import pdfmetrics\nfrom reportlab.pdfbase.cidfonts import UnicodeCIDFont\nfrom reportlab.pdfgen import canvas\nfrom playscript import PScLineType, PScLine\n\nSize = namedtuple('Size' , 'w h')\n\n\nclass PageMan:\n def __init__(self, size, margin=None, upper_space=None,\n font_name='HeiseiMin-W3', num_font_name='Times-Roman',\n font_size=10.0, line_space=None, before_init_page=None):\n \"\"\"コンストラクタ\n\n Parameters\n ----------\n size : tuple\n ページのサイズ (ポイント)\n margin : tuple\n 左右と上下のマージン (ポイント)\n upper_space : float\n 上の余白 (ポイント)\n font_name : str\n 本文のフォント\n num_font_name : str\n 数字のフォント\n font_size : float\n 本文のフォントサイズ (ポイント)\n line_space : float\n 本文の行間 (ポイント)\n before_init_page : function\n ページ初期化時のカスタム処理の関数\n \"\"\"\n\n # 属性の設定\n self.size = Size(*size)\n self.font_name = font_name\n self.num_font_name = num_font_name\n self.font_size = font_size\n self.before_init_page = before_init_page\n\n self.margin = Size(*margin) if margin else Size(2 * cm, 2 * cm)\n self.upper_space = self.size.h / 4 if upper_space is None \\\n else upper_space\n self.line_space = self.font_size * 0.95 if line_space is None \\\n else line_space\n\n # 書き出しの準備\n self.pdf = io.BytesIO()\n self.canvas = canvas.Canvas(self.pdf, pagesize=self.size)\n self.init_page()\n\n def get_line_x(self, l_idx):\n x = self.size.w - self.margin.w - self.font_size / 2\n x = x - l_idx * (self.font_size + self.line_space)\n return x\n\n def get_line_y(self, indent):\n y = self.size.h - self.margin.h - self.upper_space - indent\n return y\n\n def max_line_count(self):\n area_w = self.size.w - 2 * self.margin.w + self.line_space\n count = area_w // (self.font_size + self.line_space)\n return int(count)\n\n def init_page(self):\n \"\"\"ページごとの初期化処理\n \"\"\"\n # カスタム処理\n if self.before_init_page:\n self.before_init_page(self)\n\n # 横線を書き出す\n x1 = self.margin.w - self.line_space\n x2 = self.size.w - self.margin.w + self.line_space\n y = self.size.h - self.margin.h - self.upper_space\n self.canvas.setLineWidth(0.1)\n self.canvas.line(x1, y, x2, y)\n\n # フォントを設定する\n self.canvas.setFont(self.font_name, self.font_size)\n\n def commit_page(self):\n self.canvas.showPage()\n\n def close(self):\n self.commit_page()\n self.canvas.save()\n self.pdf.seek(0)\n\n def save(self, file_name):\n \"\"\"PDF をファイルに出力する\n\n Parameters\n ----------\n file_name : str\n 出力先のファイル名\n \"\"\"\n with open(file_name, 'wb') as f:\n f.write(self.pdf.read())\n\n def draw_line(self, l_idx, text, indent=None):\n \"\"\"テキストを行末まで書き出して残りを返す\n \"\"\"\n # インデントのデフォルトを1文字分とする\n if indent is None:\n indent = self.font_size\n\n x = self.get_line_x(l_idx)\n y = self.get_line_y(indent)\n\n height = self.size.h - 2 * self.margin.h - self.upper_space \\\n - indent\n max_len = int(height // self.font_size)\n\n # 簡易的ぶら下げ処理\n if len(text) > max_len and text[max_len] in '、。」':\n max_len += 1\n if len(text) > max_len and text[max_len] == '」':\n max_len -= 2\n\n # テキストを書き出す\n self.canvas.drawString(x, y, text[:max_len])\n return text[max_len:]\n\n def draw_lines(self, l_idx, lines, indent=None, first_indent=None):\n \"\"\"複数行に渡るテキストを書き出す\n \"\"\"\n if not first_indent:\n first_indent = indent\n\n # 改行で分ける\n texts = lines.splitlines()\n first_line = True\n\n for text in texts:\n line = text\n while len(line) > 0:\n # l_idx をチェックして改ページ\n if l_idx >= self.max_line_count():\n self.commit_page()\n self.init_page()\n l_idx = 0\n\n # 1行分だけ書き出す\n line_indent = first_indent if first_line else indent\n line = self.draw_line(l_idx, line, indent=line_indent)\n first_line = False\n l_idx += 1\n return l_idx\n\n def draw_single_line(self, l_idx, line, indent=None):\n \"\"\"1行に収まるテキストを書き出す\n \"\"\"\n # l_idx をチェックして改ページ\n if l_idx >= self.max_line_count():\n self.commit_page()\n self.init_page()\n l_idx = 0\n\n # テキストを書き出す\n _ = self.draw_line(l_idx, line, indent=indent)\n return l_idx + 1\n\n def draw_line_bottom(self, l_idx, line):\n \"\"\"テキストを下寄せで書き出す\n \"\"\"\n # インデント (1文字分)\n indent = self.font_size\n\n # 1行に収まる文字数にする\n height = self.size.h - 2 * self.margin.h - self.upper_space \\\n - indent\n max_len = int(height // self.font_size)\n line = line[:max_len]\n\n # 下端につくようにインデントを増やす\n indent += (max_len - len(line)) * self.font_size\n\n # テキストを1行として書き出す\n l_idx = self.draw_single_line(l_idx, line, indent=indent)\n return l_idx\n\n def draw_title(self, l_idx, ttl_line):\n \"\"\"題名を書き出す\n \"\"\"\n indent = self.font_size * 7\n l_idx = self.draw_lines(l_idx, ttl_line.text, indent=indent)\n return l_idx\n\n def draw_author(self, l_idx, athr_line):\n \"\"\"著者名を書き出す\n \"\"\"\n self.draw_line_bottom(l_idx, athr_line.text)\n return l_idx + 1\n\n def draw_charsheadline(self, l_idx, chead_line):\n \"\"\"登場人物見出し行を書き出す\n \"\"\"\n # インデント (8文字分)\n indent = self.font_size * 8\n\n # テキストを1行として書き出す\n l_idx = self.draw_single_line(l_idx, chead_line.text, indent=indent)\n return l_idx\n\n def draw_character(self, l_idx, char_line):\n \"\"\"登場人物行を書き出す\n \"\"\"\n name = char_line.name\n text = char_line.text if hasattr(char_line, 'text') else ''\n\n # 名前に説明をつけて一個の文字列にする\n if text:\n # 名前が2文字未満の場合は空白を足してから説明をつける\n if len(name) < 2:\n name += ' '\n text = name + ' ' + text\n else:\n text = name\n\n # インデント (7文字分 -> 10文字分)\n first_indent = self.font_size * 7\n indent = self.font_size * 10\n\n # テキストを書き出す\n l_idx = self.draw_lines(\n l_idx, text, indent=indent, first_indent=first_indent)\n return l_idx\n\n def draw_slugline(self, l_idx, hx_line, number=None, border=False):\n \"\"\"柱を書き出す\n \"\"\"\n # テキストを1行として書き出す\n l_idx = self.draw_single_line(l_idx, hx_line.text)\n\n # 囲み線\n if border:\n x = self.get_line_x(l_idx - 1)\n x1 = x + self.font_size / 2 + self.line_space * 0.8\n x2 = x - self.font_size / 2 - self.line_space * 0.8\n y1 = self.get_line_y(-(self.font_size * 3))\n y2 = self.margin.h - self.font_size\n\n self.canvas.setLineWidth(0.1)\n self.canvas.line(x1, y1, x1, y2)\n self.canvas.line(x1, y1, x2, y1)\n self.canvas.line(x2, y1, x2, y2)\n\n # 数字\n if number is not None:\n num_str = str(number)\n w = self.canvas.stringWidth(\n num_str, self.num_font_name, self.font_size)\n x = self.get_line_x(l_idx - 1) - w / 2\n y = self.get_line_y(-self.font_size)\n\n # 数字を書き出す\n self.canvas.setFont(self.num_font_name, self.font_size)\n self.canvas.drawString(x, y, num_str)\n\n # フォントを元に戻す\n self.canvas.setFont(self.font_name, self.font_size)\n\n return l_idx\n\n def draw_direction(self, l_idx, drct_line):\n \"\"\"ト書き行を書き出す\n \"\"\"\n indent = self.font_size * 7\n l_idx = self.draw_lines(l_idx, drct_line.text, indent=indent)\n return l_idx\n\n def draw_dialogue(self, l_idx, dlg_line):\n \"\"\"セリフ行を書き出す\n \"\"\"\n name = dlg_line.name\n text = dlg_line.text\n\n # 名前にセリフをつけて一個の文字列にする\n if len(name) == 1:\n name = ' ' + name + ' '\n elif len(name) == 2:\n name = name[0] + ' ' + name[1]\n text = name + '「' + text + '」'\n\n # インデント (1文字分 -> 5文字分)\n first_indent = self.font_size * 1\n indent = self.font_size * 5\n\n # テキストを書き出す\n l_idx = self.draw_lines(\n l_idx, text, indent=indent, first_indent=first_indent)\n return l_idx\n\n def draw_endmark(self, l_idx, endmk_line):\n \"\"\"エンドマークを書き出す\n \"\"\"\n self.draw_line_bottom(l_idx, endmk_line.text)\n return l_idx + 1\n\n def draw_comment(self, l_idx, cmmt_line):\n \"\"\"コメント行を書き出す\n \"\"\"\n indent = self.font_size * 7\n l_idx = self.draw_lines(l_idx, cmmt_line.text, indent=indent)\n return l_idx\n\n def draw_empty(self, l_idx, empty_line):\n \"\"\"空行を書き出す\n \"\"\"\n # 空文字列を1行として書き出す\n l_idx = self.draw_single_line(l_idx, '')\n return l_idx\n\n\ndef get_h2_letter(h2_count):\n if h2_count < 1:\n return ''\n h2_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n max_num = len(h2_letters)\n q = (h2_count - 1) // max_num\n s = (h2_count - 1) % max_num\n return get_h2_letter(q) + h2_letters[s]\n\n\ndef psc_to_pdf(psc, size=None, margin=None, upper_space=None,\n font_name='HeiseiMin-W3', num_font_name='Times-Roman',\n font_size=10.0, line_space=None, before_init_page=None,\n draw_page_num=True):\n \"\"\"PSc オブジェクトから PDF を生成する\n\n Parameters\n ----------\n psc : PSc\n ソースとなる PSc オブジェクト\n size : tuple\n ページのサイズ (ポイント)\n margin : tuple\n 左右と上下のマージン (ポイント)\n upper_space : float\n 上の余白 (ポイント)\n font_name : str\n 本文のフォント\n num_font_name : str\n 数字のフォント\n font_size : float\n 本文のフォントサイズ (ポイント)\n line_space : float\n 本文の行間 (ポイント)\n before_init_page : function\n ページ初期化時のカスタム処理の関数\n draw_page_num : bool\n ページ番号を書き出すかどうか\n\n Returns\n -------\n pdf : BytesIO\n 生成した PDF のバイナリストリーム\n \"\"\"\n # ページ初期化時のカスタム処理\n def custom_init(pm):\n if before_init_page:\n before_init_page(pm)\n\n if draw_page_num:\n # ページ番号を加算して文字列にする\n if hasattr(pm, 'page_num'):\n pm.page_num += 1\n else:\n pm.page_num = 1\n s = f'- {pm.page_num} -'\n\n # フォントと位置の準備\n f_name = pm.num_font_name\n f_size = pm.font_size * 0.8\n w = pm.canvas.stringWidth(s, f_name, f_size)\n pm.canvas.setFont(f_name, f_size)\n x = pm.size.w / 2 - w / 2\n y = pm.margin.h / 2\n\n # 書き出す\n pm.canvas.drawString(x, y, s)\n\n # フォントの設定\n pdfmetrics.registerFont(UnicodeCIDFont(font_name, isVertical=True))\n\n # ページの設定\n if not size:\n size = portrait(A5)\n if not margin:\n margin = (2.0 * cm, 2.0 * cm)\n pm = PageMan(size, margin=margin, upper_space=upper_space,\n font_name=font_name, num_font_name=num_font_name,\n font_size=font_size, line_space=line_space,\n before_init_page=custom_init)\n\n last_line_type = None\n h1_count = h2_count = 0\n l_idx = 0\n\n # 行ごとの処理\n for psc_line in psc.lines:\n line_type = psc_line.type\n\n # 行の種類が変わったら、1行空ける\n if last_line_type and (last_line_type != line_type):\n if not (last_line_type == PScLineType.TITLE \\\n and line_type == PScLineType.AUTHOR):\n l_idx += 1\n\n if line_type == PScLineType.TITLE:\n l_idx = pm.draw_title(l_idx, psc_line)\n\n elif line_type == PScLineType.AUTHOR:\n l_idx = pm.draw_author(l_idx, psc_line)\n\n elif line_type == PScLineType.CHARSHEADLINE:\n l_idx = pm.draw_charsheadline(l_idx, psc_line)\n\n elif line_type == PScLineType.CHARACTER:\n l_idx = pm.draw_character(l_idx, psc_line)\n\n elif line_type == PScLineType.H1:\n h1_count += 1\n h2_count = 0\n l_idx = pm.draw_slugline(\n l_idx, psc_line, number=h1_count, border=True)\n\n elif line_type == PScLineType.H2:\n h2_count += 1\n number = str(h1_count) + get_h2_letter(h2_count)\n l_idx = pm.draw_slugline(l_idx, psc_line, number=number)\n\n elif line_type == PScLineType.H3:\n l_idx = pm.draw_slugline(l_idx, psc_line)\n\n elif line_type == PScLineType.DIRECTION:\n l_idx = pm.draw_direction(l_idx, psc_line)\n\n elif line_type == PScLineType.DIALOGUE:\n l_idx = pm.draw_dialogue(l_idx, psc_line)\n\n elif line_type == PScLineType.ENDMARK:\n l_idx = pm.draw_endmark(l_idx, psc_line)\n\n elif line_type == PScLineType.COMMENT:\n l_idx = pm.draw_comment(l_idx, psc_line)\n\n elif line_type == PScLineType.EMPTY:\n l_idx = pm.draw_empty(l_idx, psc_line)\n\n else:\n raise TypeError(f'{line_type} はサポートされていません。' )\n\n last_line_type = line_type\n\n # PDF の入ったバイナリストリームを返す\n pm.close()\n return pm.pdf\n","sub_path":"conv/pdf.py","file_name":"pdf.py","file_ext":"py","file_size_in_byte":15117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"493652077","text":"\"\"\"\nMask R-CNN\nConfigurations and data loading code for the harz dataset.\nThis is a duplicate of the code in the noteobook train_harz.ipynb for easy\nimport into other notebooks, such as inspect_model.ipynb.\n\nCopyright (c) 2017 Matterport, Inc.\nLicensed under the MIT License (see LICENSE for details)\nWritten by Waleed Abdulla\n\"\"\"\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport os\nimport sys\nimport math\nimport random\nimport numpy as np\nimport cv2\nimport imgaug\n\n# Root directory of the project\nROOT_DIR = os.path.abspath(\"../../\")\n\nDEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, \"logs\")\nCOCO_MODEL_PATH = os.path.join(ROOT_DIR, \"mask_rcnn_coco.h5\")\nDEFAULT_DATA_DIR=\"/notebooks/tmp/data/DTM_DATA\"\n\n\n# Import Mask RCNN\nsys.path.append(ROOT_DIR) # To find local version of the library\nfrom mrcnn.config import Config\nfrom mrcnn import model as modellib, utils\nfrom mrcnn import utils\nimport skimage.io\nfrom scipy import ndimage\nfrom sklearn.model_selection import train_test_split\nfrom osgeo import gdal, ogr, osr\nimport gdalconst\n\n\nclass HarzConfig(Config):\n \"\"\"Configuration for training on harz dataset.\n Derives from the base Config class and overrides values specific\n harz dataset.\n \"\"\"\n # Give the configuration a recognizable name\n NAME = \"harz\"\n\n # Train on 1 GPU and 8 images per GPU. We can put multiple images on each\n # GPU because the images are small. Batch size is 8 (GPUs * images/GPU).\n GPU_COUNT = 2\n IMAGES_PER_GPU = 12\n\n # Number of classes (including background)\n NUM_CLASSES = 1 + 4 # background + 3 shapes\n\n # Use small images for faster training. Set the limits of the small side\n # the large side, and that determines the image shape.\n IMAGE_MIN_DIM = 256\n IMAGE_MAX_DIM = 256\n\n # Use smaller anchors because our image and objects are small\n RPN_ANCHOR_SCALES = (8, 16, 32, 64, 128) # anchor side in pixels\n\n # Reduce training ROIs per image because the images are small and have\n # few objects. Aim to allow ROI sampling to pick 33% positive ROIs.\n TRAIN_ROIS_PER_IMAGE = 64\n\n # Use a small epoch since the data is simple\n STEPS_PER_EPOCH = (4886 // (GPU_COUNT*IMAGES_PER_GPU)) + 1\n\n # use small validation steps since the epoch is small\n VALIDATION_STEPS = (611 // (GPU_COUNT*IMAGES_PER_GPU)) + 1\n\n\nclass HarzDataset(utils.Dataset):\n \"\"\"Generates the harz dataset. The dataset consists of bomb craters, \n meiler (charcoal kilns), barrows, and pinge (mining sinkholes)\n The images are generated on the fly. No file access required.\n \"\"\"\n\n def get_file_names(self, root, subset='train'):\n \"\"\"\n returns filenames for images in root and for the given subset (train,test,valid!)\n \"\"\"\n with open(os.path.join(root, 'labels.txt'), 'r') as f:\n lines = f.readlines()\n labels = np.empty((len(lines),))\n file_names = []\n for e, filename in enumerate(lines):\n file_name, classlabel = filename.split()\n labels[e] = int(classlabel)\n file_names.append(file_name)\n\n train_file_names, test_file_names, train_labels, test_labels = \\\n train_test_split(\n file_names,\n labels,\n test_size=0.1,\n stratify=labels,\n random_state=42\n )\n\n train_file_names, validation_file_names, train_labels, valid_labels = \\\n train_test_split(\n train_file_names,\n train_labels,\n test_size=len(test_file_names),\n stratify=train_labels,\n random_state=42\n )\n\n if subset == 'train':\n return train_file_names\n elif subset == 'test':\n return test_file_names\n else:\n return validation_file_names\n\n def load_data(self, dataset_dir, subset, height=256, width=256):\n \"\"\"Generate the requested number of synthetic images.\n data directory for images.\n height, width: the size of the generated images.\n \"\"\"\n # Add classes\n self.add_class(\"harz\", 1, \"bombs\")\n self.add_class(\"harz\", 2, \"meiler\")\n self.add_class(\"harz\", 3, \"barrows\")\n self.add_class(\"harz\", 4, \"pinge\")\n self.split = subset\n self.filenames = self.get_file_names(dataset_dir,subset)\n # self.imgs = [os.path.join(dataset_dir, 'RGB', f) for f in self.filenames]\n # self.masks = [os.path.join(dataset_dir, 'y', f) for f in self.filenames]\n\n # Add images\n\n for f in self.filenames:\n self.add_image(\"harz\", \n image_id=f, \n path=os.path.join(dataset_dir, 'RGB', f), \n width=width, \n height=height,\n mask_path=os.path.join(dataset_dir, 'y', f)\n )\n\n def load_image(self, image_id):\n \"\"\"Generate an image from the specs of the given image ID.\n Typically this function loads the image from a file, but\n in this case it generates the image on the fly from the\n specs in image_info.\n \"\"\"\n info = self.image_info[image_id]\n image = skimage.io.imread(info['path'], plugin='pil')\n return image\n\n def image_reference(self, image_id):\n \"\"\"Return the path of the image.\"\"\"\n info = self.image_info[image_id]\n if info[\"source\"] == \"harz\":\n return info[\"path\"]\n else:\n super(self.__class__, self).image_reference(image_id)\n\n def load_mask_helper(self, mask_path):\n \"returns instance mask for the label file at mask_path\"\n mask = skimage.io.imread(mask_path, plugin='pil')\n obj_ids = np.unique(mask)\n # exclude background\n obj_ids = obj_ids[1:]\n\n labeled_array, num_features = ndimage.label(mask)\n masks = np.zeros((mask.shape[0], mask.shape[1], num_features))\n labels = []\n for i in range(1, num_features+1):\n pos = np.where(labeled_array == i)\n masks[:,:,i-1][pos] = 1\n labels.append(mask[pos][0])\n\n return masks.astype(np.bool), np.array(labels, dtype=np.int32)\n\n def load_mask(self, image_id):\n \"\"\"Generate instance masks for shapes of the given image ID.\n \"\"\"\n info = self.image_info[image_id]\n mask_path = info['mask_path']\n return self.load_mask_helper(mask_path)\n\n\n############################################################\n# Evaluate and print mAP\n############################################################\n\ndef evaluate(model, dataset_val, inference_config):\n APs = []\n for image_id in dataset_val.image_ids:\n # Load image and ground truth data\n image, image_meta, gt_class_id, gt_bbox, gt_mask =\\\n modellib.load_image_gt(dataset_val, inference_config,\n image_id, use_mini_mask=False)\n molded_images = np.expand_dims(modellib.mold_image(image, inference_config), 0)\n # Run object detection\n results = model.detect([image], verbose=0)\n r = results[0]\n # Compute AP\n AP, precisions, recalls, overlaps =\\\n utils.compute_ap(gt_bbox, gt_class_id, gt_mask,\n r[\"rois\"], r[\"class_ids\"], r[\"scores\"], r['masks'])\n APs.append(AP)\n \n print(\"mAP: \", np.mean(APs))\n\n\n############################################################\n# Training\n############################################################\n\n\nif __name__ == '__main__':\n import argparse\n\n # Parse command line arguments\n parser = argparse.ArgumentParser(\n description='Train Mask R-CNN on Harz Dataset.')\n parser.add_argument(\"command\",\n metavar=\"\",\n help=\"'train' or 'evaluate' on Harz Dataset\")\n parser.add_argument('--dataset', required=False,\n default=DEFAULT_DATA_DIR,\n metavar=\"/path/to/data/dir/\",\n help='Directory of the Harz dataset')\n parser.add_argument('--model', required=True,\n metavar=\"/path/to/weights.h5\",\n help=\"Path to weights .h5 file or one of 'imagenet', 'last', or 'coco'\")\n parser.add_argument('--logs', required=False,\n default=DEFAULT_LOGS_DIR,\n metavar=\"/path/to/logs/\",\n help='Logs and checkpoints directory (default=logs/)')\n # parser.add_argument('--limit', required=False,\n # default=500,\n # metavar=\"\",\n # help='Images to use for evaluation (default=500)')\n parser.add_argument('--download', required=False,\n default=False,\n metavar=\"\",\n help='Automatically download and unzip MS-COCO files (default=False)',\n type=bool)\n args = parser.parse_args()\n print(\"Command: \", args.command)\n print(\"Model: \", args.model)\n print(\"Dataset: \", args.dataset)\n print(\"Logs: \", args.logs)\n print(\"Auto Download: \", args.download)\n\n # Configurations\n if args.command == \"train\":\n config = HarzConfig()\n else:\n class InferenceConfig(HarzConfig):\n # Set batch size to 1 since we'll be running inference on\n # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n DETECTION_MIN_CONFIDENCE = 0\n config = InferenceConfig()\n config.display()\n\n # Create model\n if args.command == \"train\":\n model = modellib.MaskRCNN(mode=\"training\", config=config,\n model_dir=args.logs)\n else:\n model = modellib.MaskRCNN(mode=\"inference\", config=config,\n model_dir=args.logs)\n\n # Select weights file to load\n if args.model.lower() == \"coco\":\n model_path = COCO_MODEL_PATH\n elif args.model.lower() == \"last\":\n # Find last trained weights\n model_path = model.find_last()\n elif args.model.lower() == \"imagenet\":\n # Start from ImageNet trained weights\n model_path = model.get_imagenet_weights()\n else:\n model_path = args.model\n\n # Load weights\n print(\"Loading weights \", model_path)\n if args.model.lower() == \"coco\":\n # Exclude the last layers because they require a matching\n # number of classes\n model.load_weights(model_path, by_name=True, exclude=[\n \"mrcnn_class_logits\", \"mrcnn_bbox_fc\",\n \"mrcnn_bbox\", \"mrcnn_mask\"])\n else:\n model.load_weights(model_path, by_name=True)\n\n # Train or evaluate\n if args.command == \"train\":\n # Training dataset. Use the training set and 35K from the\n # validation set, as as in the Mask RCNN paper.\n dataset_train = HarzDataset()\n dataset_train.load_data(args.dataset, 'train')\n dataset_train.prepare()\n\n # Validation dataset\n dataset_val = HarzDataset()\n dataset_val.load_data(args.dataset, 'validation')\n dataset_val.prepare()\n\n # Image Augmentation\n # Right/Left flip 50% of the time\n augmentation = imgaug.augmenters.Fliplr(0.5)\n\n # *** This training schedule is an example. Update to your needs ***\n\n # Training - Stage 1\n print(\"Training network heads\")\n model.train(dataset_train, dataset_val,\n learning_rate=config.LEARNING_RATE,\n epochs=20,\n layers='heads',\n augmentation=augmentation)\n\n # Training - Stage 2\n # Finetune layers from ResNet stage 4 and up\n print(\"Fine tune Resnet stage 4 and up\")\n model.train(dataset_train, dataset_val,\n learning_rate=config.LEARNING_RATE,\n epochs=40,\n layers='4+',\n augmentation=augmentation)\n\n # Training - Stage 3\n # Fine tune all layers\n print(\"Fine tune all layers\")\n model.train(dataset_train, dataset_val,\n learning_rate=config.LEARNING_RATE / 10,\n epochs=100,\n layers='all',\n augmentation=augmentation)\n\n elif args.command == \"evaluate\":\n # Validation dataset\n dataset_val = HarzDataset()\n dataset_val.load_data(args.dataset, 'test')\n dataset_val.prepare()\n print(\"Running harz evaluation on test data\")\n evaluate(model, dataset_val, config)\n else:\n print(\"'{}' is not recognized. \"\n \"Use 'train' or 'evaluate'\".format(args.command))\n\n","sub_path":"samples/harz/harz.py","file_name":"harz.py","file_ext":"py","file_size_in_byte":12781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"317243457","text":"text = (input(\"Podaj tekst do tluamczenia: \"))\ncounter = 0\n\nfor x in range(0,len(text)):\n\tif text[x] in [\"a\",\"e\",\"i\",\"o\",\"u\",\"y\"]:\n\t\ttext=text[0:x]+\"a\"+text[x+1:len(text)]\n\t\tcounter = counter+1\n\nprint(text)\nprint(\"ilosc samoglosek to: \",counter)\n","sub_path":"lab06/zad6.py","file_name":"zad6.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"605655969","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 14 09:58:01 2020\n\n@author: Axel\n\"\"\"\n\nimport copy\n#take a state point and return every base point in the state point\ndef flatten_list(nested_list):\n \"\"\"Flatten an arbitrarily nested list, without recursion (to avoid\n stack overflows). Returns a new list, the original list is unchanged.\n >> list(flatten_list([1, 2, 3, [4], [], [[[[[[[[[5]]]]]]]]]]))\n [1, 2, 3, 4, 5]\n >> list(flatten_list([[1, 2], 3]))\n [1, 2, 3]\n \"\"\"\n if not isinstance(nested_list,list):\n nested_list=[nested_list]\n nested_list = copy.deepcopy(nested_list)\n\n \n \n while nested_list:\n sublist = nested_list.pop(0)\n\n if isinstance(sublist, list):\n nested_list = sublist + nested_list\n else:\n yield sublist\n\ndef flattenStatePoint(statePoint):\n if not isinstance (statePoint,list):\n statePoint=[statePoint]\n return list(flatten_list(statePoint))\n\n#find all epis with a specific name in a list flattened with flattenEpiList()\ndef extractBasePointsFromFlattenedStatePoint(epiList, name):\n li=[]\n for epi in epiList:\n if epi.getName()==name:\n li.append(epi)\n return li\n\ndef properSubset(li1,li2):\n if li1 == li2:\n return False\n for v1 in li1:\n #if there is some v in the first list that is not in the second list, they can't be subsets\n match=False\n for v2 in li2:\n #print (v1.clause1)\n #print (v1.clause2)\n if v1.clause1 == v2.clause1:\n if v1.clause2 == v2.clause2:\n match=True\n if not match:\n return False\n return True\n\ndef VtoTupleList(v_1, ignoreNone=True):\n v_1AsSet = set([(v.getName(),v.getValue()) for v in v_1 if (v.getValue()!=None or ignoreNone==False)])\n return v_1AsSet\ndef properSubset_atomList(v_1,v_2):\n v_1AsSet =VtoTupleList(v_1)\n v_2AsSet =VtoTupleList(v_2)\n \n #print (v_1AsSet)\n #ensure SUBSET\n if v_1AsSet==v_2AsSet:\n return False\n subset=v_1AsSet.issubset(v_2AsSet)\n return subset\n\n\ndef CTMtoSCP(results, f): \n return [(result,f) for result in results]\n\n\ndef predictionsModelsGamma_lenient(predictions,gamma):\n for i in gamma:\n predHolds=False\n #some prediction is in gamma for that attribute\n for prediction in predictions[i]:\n if prediction in gamma[i]:\n predHolds=True\n #some prediction required by gamma was not met\n if not predHolds:\n return False\n return True\n\ndef predictionsModelsGamma_strict(predictions,gamma):\n for i in gamma:\n predHolds=True\n #some prediction is in gamma for that attribute\n for prediction in predictions[i]:\n if prediction in gamma[i]:\n predHolds=False\n #some prediction required by gamma was not met\n if not predHolds:\n return False\n return True\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":"Implementations/SCPimplementation2_backup20200622/Axel_ccobra/benchmarks/propositional/models/2020-Axel/StatePointOperations.py","file_name":"StatePointOperations.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"308475026","text":"from ast import walk, Call, Attribute, Constant\nimport os\nimport sys\n\n\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), \"..\", \"..\")))\n\n\nfrom testrunner import CodersLabTestSuite, CodersLabException, p, dedent\n\n\ntc = CodersLabTestSuite(\"Łączenie listy\")\n\n\n@tc.test('Zmienne \"a\", \"b\" oraz \"modulo\" istnieją', aborts=True)\ndef test_variables(invoke, **kwargs):\n variables = invoke()\n\n for name in (\"a\", \"b\", \"modulo\"):\n if name not in variables:\n raise CodersLabException(\"Nie znaleziono zmiennej {}\".format(p.b.get(name)))\n\n if not isinstance(variables[name], (int, float)):\n raise CodersLabException(\n dedent(\n \"\"\"\n Oczekiwano, że zmienna {} będzie miała wartość typu {} lub {}.\n Jej obecna typ to {}.\n \"\"\"\n ).format(\n p.b.get(name),\n p.b.get(\"int\"),\n p.b.get(\"float\"),\n p.b.get(type(variables[name]).__name__),\n )\n )\n\n\n@tc.test('Zmienna \"modulo\" ma odpowiednią wartość')\ndef test_variables(invoke, **kwargs):\n variables = invoke()\n\n if variables[\"a\"] % variables[\"b\"] != variables[\"modulo\"]:\n raise CodersLabException(\n dedent(\n \"\"\"\n Dla a={} oraz b={} oczekiwano że wartością zmiennej {} będzie {}.\n Jej obecna wartość to {}.\n \"\"\"\n ).format(\n p.b.get(variables[\"a\"]),\n p.b.get(variables[\"b\"]),\n p.b.get(\"modulo\"),\n p.b.get(variables[\"a\"] % variables[\"b\"]),\n p.b.get(variables[\"modulo\"]),\n )\n )\n\n\ntc.run()\n","sub_path":"03_Biblioteka_standardowa_w_jezyku_Python/03_Dzielenie_modulo/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"595432338","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom django.core.urlresolvers import reverse\nfrom django.contrib import messages\nfrom ..login_reg.models import User\nfrom .models import Item, ItemUserRelationship\n\n# Create your views here.\ndef index(request):\n\ttry:\n\t\trequest.session['user']\n\texcept KeyError:\n\t\treturn HttpResponse(\"

Please login first!

\")\n\tuser = User.objects.get(id=str(request.session['user']))\n\titems = Item.objects.filter(added_by=user.name)\n\ttemp = Item.objects.exclude(added_by=user.name)\n\twish = ItemUserRelationship.objects.filter(user=user)\n\tother = []\n\tif len(wish) == 0:\n\t\t\tother = temp\n\telse:\n\t\tfor t in temp:\n\t\t\tadd = True\n\t\t\tfor w in wish:\n\t\t\t\tif t.name == w.item.name:\n\t\t\t\t\tadd = False\n\t\t\tif add:\n\t\t\t\tother.append(t)\n\tcontext = {\n\t\t'name': user.name,\n\t\t'items': items,\n\t\t'other': other,\n\t\t'wish' : wish,\n\t}\n\treturn render(request, 'wish/index.html', context)\n\ndef add(request):\n\treturn render(request, 'wish/add.html')\n\ndef submit(request):\n\tuser = User.objects.get(id=str(request.session['user']))\n\tcontext = {\n\t\t'name': request.POST['name'],\n\t\t'added_by': user.name,\n\t}\n\tresult = Item.itemManager.validate(**context)\n\tif result[0]:\n\t\treturn redirect(reverse('wish_index'))\n\telse:\n\t\tfor msg in result[1]:\n\t\t\tmessages.add_message(request, messages.ERROR, msg)\n\t\treturn redirect(reverse('add'))\n\ndef delete(request, id):\n\titem = Item.objects.get(id=id)\n\titem.delete()\n\treturn redirect(reverse('wish_index'))\n\ndef wishlist(request, id):\n\titem = Item.objects.get(id=id)\n\tuser = User.objects.get(id=str(request.session['user']))\n\tItemUserRelationship.objects.create(item=item, user=user)\n\treturn redirect(reverse('wish_index'))\n\ndef remove(request, id):\n\titem = Item.objects.get(id=id)\n\tuser = User.objects.get(id=str(request.session['user']))\n\ttemp = ItemUserRelationship.objects.filter(item=item).filter(user=user)\n\ttemp[0].delete()\n\treturn redirect(reverse('wish_index'))\n\ndef info(request, id):\n\titem = Item.objects.get(id=id)\n\tother = ItemUserRelationship.objects.filter(item=item)\n\tcontext = {\n\t\t'name': item.name,\n\t\t'other': other\n\t}\n\treturn render(request, 'wish/info.html', context)","sub_path":"apps/wish/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"428689855","text":"import os\nimport time\nimport unittest\nfrom yj_application_apiTest.config import pathconfig\nfrom yj_application_apiTest.tools import htmlTestRunner\nfrom yj_application_apiTest.tools.filePath import fileposition\nfrom yj_application_apiTest.tools.sendEmailTools import sendEmai\n# 报告存放地址 ====在配置文件配置\nreportdir=pathconfig.reportdir\n# 用例存放地址====在配置文件配置\ncasedir=pathconfig.casedir\n\ndef runall_case():\n discover = unittest.defaultTestLoader.discover(casedir, pattern='test_*.py',top_level_dir=None)\n testcase=unittest.TestSuite()\n for test_suit in discover:\n for test_case in test_suit:\n testcase.addTests(test_case)\n # testcase.addTests(discover)\n return testcase\nif __name__==\"__main__\":\n # runner=unittest.TextTestRunner()\n now = time.strftime(\"%Y-%m-%d-%H_%M_%S\", time.localtime(time.time()))\n # 2、html报告文件路径\n report_abspath = os.path.join(reportdir, \"result_\" + now + \".html\")\n # 3、打开一个文件,将result写入此file中\n fp = open(report_abspath, \"wb\")\n runner = htmlTestRunner.HTMLTestRunner(stream=fp,title=u'接口自动化测试报告,测试结果如下:',description=u'用例执行情况:')\n runner.run(runall_case())\n fp.close()\n # 发送结果到邮箱\n newresult = fileposition.new_file(reportdir)\n emial = sendEmai\n emial.Sendemail(newresult)","sub_path":"yj_application_apiTest/main/main_runall_case.py","file_name":"main_runall_case.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"299760397","text":"\"\"\"Local Mouth
\n\n\"\"\"\n\nimport maya.cmds as cmds\n\nimport gurka.extensions.maya.lib.controlshape as controlshape\nimport gurka.extensions.maya.core.mgurkrigobj as mgurkrigobj\nimport gurka.extensions.maya.lib.mcurves as mcurves\nimport gurka.extensions.maya.lib.mmatrix as mmatrix\nreload(mmatrix)\nreload(mcurves)\n\nimport logging\n\nclass LocalMouth(mgurkrigobj.MGurkRigObj):\n\n def __init__(self):\n super(LocalMouth, self).__init__()\n\n # bools\n self.add(\"zip\", True, public=True, ui={\"layer\":\"Extras\"})\n self.add(\"facecontrols\", True, public=True, ui={\"layer\":\"Extras\"})\n self.add(\"upcrvpos\", 0.3, public=True, ui={\"layer\":\"Build\", \"nicename\":\"Up Curve Offset\"})\n\n\n # construction edge loop\n self.add(\"edgeloop\", [], public=True, ui={\"layer\":\"Build\",\n \"custom\":[\"gurka.extensions.maya.ui.customwidgets.mselect\", \"MSelect\"]})\n\n\n\n def pre(self):\n super(LocalMouth, self).pre()\n\n # add skeleton guide\n jnt_names = [\"jaw\", \"jawEnd\"]\n guides = self.addSkeletonChain(jnt_names, 5)\n\n for updwn in [\"upper\", \"lower\"]:\n # upper lip\n guide = cmds.spaceLocator(n=\"{}{}Lip_GUIDE\".format(self.get(\"name\"), updwn.title()))[0]\n locshp = cmds.listRelatives(guide, s=True)[0]\n controlshape.ControlShape.cube(guide)\n cmds.delete(locshp)\n\n cmds.setAttr(guide + \".overrideEnabled\", 1)\n cmds.setAttr(guide + \".overrideColor\", 9)\n\n cmds.parent(guide, guides[0])\n cmds.delete(cmds.parentConstraint(guides[1], guide, mo=False))\n\n self.add(\"%sLipGuide\"%updwn, guide)\n self.reg.add(\"transform\", guide)\n self.output.add(\"%sHead\"%updwn, guide)\n\n # arrow\n arrow = cmds.createNode(\"annotationShape\")\n arrow_parent = cmds.listRelatives(arrow, p=True)[0]\n crv = cmds.curve(p=[0,0,0], d=1)\n cmds.connectAttr(cmds.listRelatives(crv, s=True)[0] +\".worldMatrix[0]\",\n arrow+ \".dagObjectMatrix[0]\")\n crvshp = cmds.listRelatives(crv, s=True)[0]\n cmds.setAttr(crvshp + \".template\", 1)\n cmds.parent(crvshp, guide, r=True, s=True)\n cmds.delete(crv)\n cmds.parent(arrow, guides[0], r=True, s=True)\n cmds.setAttr(arrow + \".overrideEnabled\", 1)\n cmds.setAttr(arrow + \".overrideColor\", 9)\n cmds.delete(arrow_parent)\n\n def build(self):\n super(LocalMouth, self).build()\n\n edgeloop = self.get(\"edgeloop\")\n upcrvpos = self.get(\"upcrvpos\")\n\n upLipPos = self.get(\"upperLipGuide\")\n dwnLipPos = self.get(\"lowerLipGuide\")\n jaw = self.get(\"jawJnt\")\n\n modgrp = self.getModuleGroup()\n\n # if we cant find any edges return..\n if not len(edgeloop):\n logging.info(\"Missing Edge\")\n return\n\n upLipGrp = cmds.group(em=True, n=self.get(\"name\") + \"upperLip_GRP\")\n loLipGrp = cmds.group(em=True, n=self.get(\"name\") + \"lowerLip_GRP\")\n\n cmds.parent(loLipGrp, jaw)\n\n cmds.delete(cmds.parentConstraint(upLipPos, upLipGrp, mo=False))\n cmds.delete(cmds.parentConstraint(dwnLipPos, loLipGrp, mo=False))\n\n upper, lower = mcurves.create_edges(self.get(\"name\"), edgeloop)\n\n cmds.parent([upper, lower], modgrp)\n\n jntgrp = cmds.group(em=True, n=self.get(\"name\") + \"Deform_GRP\")\n cmds.parent(jntgrp, modgrp)\n\n cmds.addAttr(modgrp, ln=\"leftZip\", max=1.0, min=0.0, dv=0.0, k=True)\n cmds.addAttr(modgrp, ln=\"rightZip\", max=1.0, min=0.0, dv=0.0, k=True)\n cmds.addAttr(modgrp, ln=\"leftRadius\", max=10.0, min=0.001, dv=0.001, k=True)\n cmds.addAttr(modgrp, ln=\"rightRadius\", max=10.0, min=0.001, dv=0.001, k=True)\n\n\n # sort sides by slicing\n lowercvs = cmds.ls(lower + \".cv[*]\", fl=True)\n uppercvs = cmds.ls(upper + \".cv[*]\", fl=True)\n\n\n upperCrvPos = [cmds.xform(cv, t=True, ws=True, q=True) for cv in cmds.ls(upper + \".cv[*]\", fl=True)]\n lowerCrvPos = [cmds.xform(cv, t=True, ws=True, q=True) for cv in cmds.ls(lower + \".cv[*]\", fl=True)]\n\n upper = cmds.rebuildCurve(upper, ch=0, rpo=1,rt=0, end=1, kr=0, kcp=0, kep=1, kt=0, s=4, d= 3, tol=0.01)[0]\n lower = cmds.rebuildCurve(lower, ch=0, rpo=1,rt=0, end=1, kr=0, kcp=0, kep=1, kt=0, s=4, d= 3, tol=0.01)[0]\n\n # group points by parameter value\n param_data = {}\n for i, up_pos in enumerate(upperCrvPos, 1):\n\n up_param = mcurves.get_param_from_pos(upper, up_pos)\n\n if up_param not in param_data.keys(): param_data.update({up_param:[]})\n\n driv = cmds.group(em=True, n=\"%sUpperDriver%d_GRP\"%(self.get(\"name\"), i))\n offset = cmds.group(em=True, n=\"%sUpperOffset%d_GRP\"%(self.get(\"name\"), i))\n jnt = cmds.joint(n=\"%sUpper%d_JNT\"%(self.get(\"name\"), i))\n cmds.parent(offset, driv)\n\n param_data[up_param].append(offset)\n\n poci = cmds.createNode(\"pointOnCurveInfo\", n=\"_{}Upper{}_POCI\".format(self.get(\"name\"), i))\n\n cmds.connectAttr(upper + \".worldSpace\", poci + \".inputCurve\")\n cmds.setAttr(poci + \".turnOnPercentage\", True)\n cmds.setAttr(poci + \".parameter\", up_param)\n cmds.connectAttr(poci + \".position\", driv + \".translate\")\n\n\n for i, lo_pos in enumerate(lowerCrvPos, 1):\n\n lo_param = mcurves.get_param_from_pos(lower, lo_pos)\n\n if lo_param not in param_data.keys(): param_data.update({lo_param:[]})\n\n driv = cmds.group(em=True, n=\"%sLowerDriver%d_GRP\"%(self.get(\"name\"), i))\n offset = cmds.group(em=True, n=\"%sLowerOffset%d_GRP\"%(self.get(\"name\"), i))\n jnt = cmds.joint(n=\"%sLower%d_JNT\"%(self.get(\"name\"), i))\n cmds.parent(offset, driv)\n\n poci = cmds.createNode(\"pointOnCurveInfo\", n=\"_{}Lower{}_POCI\".format(self.get(\"name\"), i))\n\n cmds.connectAttr(lower + \".worldSpace\", poci + \".inputCurve\")\n cmds.setAttr(poci + \".turnOnPercentage\", True)\n cmds.setAttr(poci + \".parameter\", lo_param)\n cmds.connectAttr(poci + \".position\", driv + \".translate\")\n\n param_data[lo_param].append(offset)\n\n leftramps = []\n rightramps = []\n\n l_adl = cmds.createNode(\"addDoubleLinear\", name = self.get(\"name\") + \"LeftAddRadius_ADL\")\n cmds.connectAttr(modgrp + \".leftZip\", l_adl + \".input1\")\n cmds.connectAttr(modgrp + \".leftRadius\", l_adl + \".input2\")\n\n r_adl = cmds.createNode(\"addDoubleLinear\", name = self.get(\"name\") + \"RightAddRadius_ADL\")\n cmds.connectAttr(modgrp + \".rightZip\", r_adl + \".input1\")\n cmds.connectAttr(modgrp + \".rightRadius\", r_adl + \".input2\")\n\n sub = cmds.createNode(\"plusMinusAverage\", name = self.get(\"name\") + \"RightAddRadius_PMA\")\n cmds.setAttr(sub + \".operation\", 2)\n\n\n cmds.setAttr(sub + \".input2D[0].input2Dx\", 1.0)\n cmds.setAttr(sub + \".input2D[0].input2Dy\", 1.0)\n\n cmds.connectAttr(r_adl + \".output\", sub + \".input2D[1].input2Dx\")\n cmds.connectAttr(modgrp + \".rightZip\", sub + \".input2D[1].input2Dy\")\n\n\n\n\n\n for i, key in enumerate(param_data, 1):\n\n L_rmp = cmds.createNode(\"remapValue\", n=\"_{}{}Left_RMP\".format(self.get(\"name\"), i))\n R_rmp = cmds.createNode(\"remapValue\", n=\"_{}{}Right_RMP\".format(self.get(\"name\"), i))\n add = cmds.createNode(\"addDoubleLinear\", n=\"_{}{}RmpSum_ADL\".format(self.get(\"name\"), i))\n clamp = cmds.createNode(\"clamp\", n=\"_{}{}RmpSum_CLMP\".format(self.get(\"name\"), i))\n\n # connect ramps\n cmds.connectAttr(L_rmp + \".outValue\", add + \".input1\")\n cmds.connectAttr(R_rmp + \".outValue\", add + \".input2\")\n cmds.connectAttr(add + \".output\", clamp + \".input.inputR\")\n\n cmds.setAttr(clamp + \".maxR\", 1.0)\n\n # create a small offset\n value = key\n if key == 0: value = 0.01\n elif key == 1: value = 0.99\n\n cmds.setAttr(L_rmp + \".inputValue\", value)\n cmds.setAttr(R_rmp + \".inputValue\", value)\n\n leftramps.append(L_rmp)\n rightramps.append(R_rmp)\n\n loc = cmds.spaceLocator()[0]\n cmds.connectAttr(clamp + \".outputR\", loc + \".ty\")\n cmds.setAttr(loc + \".tx\", key)\n\n cmds.connectAttr(l_adl + \".output\", L_rmp + \".value[1].value_Position\")\n cmds.connectAttr(modgrp + \".leftZip\", L_rmp + \".value[0].value_Position\")\n\n cmds.setAttr(L_rmp + \".value[0].value_FloatValue\", 1)\n cmds.setAttr(L_rmp + \".value[1].value_FloatValue\", 0)\n\n cmds.setAttr(L_rmp + \".value[1].value_Interp\", 2)\n cmds.setAttr(L_rmp + \".value[0].value_Interp\", 2)\n\n cmds.connectAttr(sub + \".output2Dx\", R_rmp + \".value[1].value_Position\")\n cmds.connectAttr(sub + \".output2Dy\", R_rmp + \".value[0].value_Position\")\n\n cmds.setAttr(R_rmp + \".value[0].value_FloatValue\", 1)\n cmds.setAttr(R_rmp + \".value[1].value_FloatValue\", 0)\n\n cmds.setAttr(R_rmp + \".value[1].value_Interp\", 2)\n cmds.setAttr(R_rmp + \".value[0].value_Interp\", 2)\n\n\n\n\n\n\n\n\n\n\n\n\n # create up curve\n #self.upperUp = cmds.duplicate(self.upper, n=self.get(\"name\") + \"UpperUp_CRV\")[0]\n #self.lowerUp = cmds.duplicate(self.lower, n=self.get(\"name\") + \"LowerUp_CRV\")[0]\n\n\n\n\n\n '''\n for crv in [self.upperUp, self.lowerUp]:\n cmds.setAttr(crv + \".overrideEnabled\", 1)\n cmds.setAttr(crv + \".overrideDisplayType\", 1)\n\n cmds.setAttr(self.upperUp + \".ty\", upcrvpos)\n cmds.setAttr(self.lowerUp + \".ty\", upcrvpos)\n\n # create joints etc..\n alljoints = []\n\n for updwn in [\"upper\", \"lower\"]:\n crvpositions = getattr(self, updwn + \"CrvPos\")\n curve = getattr(self, updwn)[0]\n upcrv = getattr(self, updwn + \"Up\")\n updwngrp = cmds.group(em=True, n=\"{}{}\".format(self.get(\"name\"), updwn))\n cmds.parent(updwngrp, jntgrp)\n\n for e, cvpos in enumerate(crvpositions, 1):\n\n grp = cmds.group(em=True, n=\"{}{}{}_GRP\".format(self.get(\"name\"), updwn.title(), e))\n jnt = cmds.joint(n=\"{}{}{}_JNT\".format(self.get(\"name\"), updwn.title(), e))\n alljoints.append(jnt)\n\n self.reg.add(\"attribute\", jnt + \".radius\")\n\n cmds.xform(grp, t=cvpos, ws=True)\n cmds.parent(grp, updwngrp)\n\n\n npoc = cmds.createNode(\"nearestPointOnCurve\")\n\n cmds.connectAttr(curve + \".worldSpace\", npoc + \".inputCurve\")\n\n cmds.setAttr(npoc + \".inPosition.inPositionX\", cvpos[0])\n cmds.setAttr(npoc + \".inPosition.inPositionY\", cvpos[1])\n cmds.setAttr(npoc + \".inPosition.inPositionZ\", cvpos[2])\n\n param = cmds.getAttr(npoc + \".parameter\")\n cmds.delete(npoc)\n\n poci = cmds.createNode(\"pointOnCurveInfo\", n=\"_{}{}{}_POCI\".format(self.get(\"name\"),\n updwn.title(), e))\n\n cmds.connectAttr(curve + \".worldSpace\", poci + \".inputCurve\")\n cmds.setAttr(poci + \".turnOnPercentage\", True)\n cmds.setAttr(poci + \".parameter\", param)\n\n drivengrp = cmds.group(em=True, n=\"_{}{}{}_Driven\".format(self.get(\"name\"), updwn.title(), e))\n cmds.connectAttr(poci + \".position\", drivengrp + \".translate\")\n cmds.parent(drivengrp, updwngrp)\n\n cmds.parent(grp, drivengrp)\n\n poci_up = cmds.createNode(\"pointOnCurveInfo\", n=\"_{}{}Up{}_POCI\".format(self.get(\"name\"),\n updwn.title(), e))\n cmds.connectAttr(upcrv + \".worldSpace\", poci_up + \".inputCurve\")\n cmds.setAttr(poci_up + \".turnOnPercentage\", True)\n cmds.setAttr(poci_up + \".parameter\", param)\n\n upgrp = cmds.group(em=True, n=\"_{}{}{}_UP\".format(self.get(\"name\"), updwn.title(), e))\n cmds.connectAttr(poci_up + \".position\", upgrp + \".translate\")\n cmds.parent(upgrp, updwngrp)\n cmds.setAttr(upgrp + \".v\", 0)\n\n mmatrix.aimConstraint(upgrp, grp, mo=False, aimObject=drivengrp, upObject=modgrp)\n '''\n","sub_path":"gurka/extensions/maya/modules/face/localmouth.py","file_name":"localmouth.py","file_ext":"py","file_size_in_byte":12522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"19908915","text":"from lib import numbers\n\nimport config\n\ndef auth(data):\n if numbers.normalize(data[0]) in config.nomor_koor_pleton_cb:\n return True\n else:\n return False\n\ndef replymsg(driver, data):\n grp=data[1]\n kode_pleton=grp.split('-')[1]\n nama_pleton=pletonSwitcher(kode_pleton)\n if nama_pleton:\n msgreply=f'okeeeeee, absensi CB untuk *PLETON {nama_pleton}* dimulai, kepada peserta Character Building Politeknik Pos Indonesia 2020 untuk segera absen ke {config.bot_name} yaa, cukup dengan kirimkan pesannya ke GROUP PLETON kamu sudah bisa terabsen, minimal 2 - 3 pesan yaa...'\n else:\n msgreply=f'duhhh kakak koordinator, nama pletonnya ngga bisa {config.bot_name} temuin nih, coba cek yaa nama groupnyaa'\n return msgreply\n\ndef pletonSwitcher(kode_pleton):\n switcher = {\n '0': 'ITeung hore hore',\n '1': 'Bojong Menjeng',\n '2': 'Cangkuang',\n '3': 'Jiwa',\n '4': 'Batu Jaya',\n '5': 'Cibuaya',\n '6': 'Karangkamulyan',\n '7': 'Blandongan',\n '8': 'Tanggulun',\n '9': 'Serut',\n '10': 'Tridarma',\n '11': 'Batu Kalde',\n '12': 'Pasir Datar',\n '13': 'Huludayeuh',\n '14': 'Ulubelu',\n '15': 'Kawali',\n '16': 'Sanghyang',\n '17': 'Batu Tulis'\n }\n return switcher.get(kode_pleton, None)","sub_path":"module/absensi_cb_mulai.py","file_name":"absensi_cb_mulai.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"436638787","text":"from odoo.exceptions import RedirectWarning, UserError, ValidationError\nfrom odoo import api, models,fields\n\nclass EstateProperty(models.Model):\n\n _description = 'IAP Lead Enrichment API'\n _name = \"estate.property\"\n _order = \"id desc\"\n\n ## Fields base\n\n name = fields.Char(required=True, string=\"Name\")\n description = fields.Text()\n postcode = fields.Char()\n date_avaliability = fields.Date(copy=False)\n expected_price = fields.Float(required=True)\n selling_price = fields.Float( copy=False)\n bedrooms = fields.Integer(default=2)\n living_area = fields.Integer()\n facades = fields.Integer()\n garage = fields.Boolean()\n garden = fields.Boolean()\n garden_area = fields.Integer()\n garden_orientation = fields.Selection( string='Orientation', selection=[('south', 'South'), ('north', 'North'),('east', 'East'),('west', 'West')])\n state = fields.Selection(string=\"State\",selection=[('new',\"New\"),('offer_received',\"Offer Received\"),\n ('offer_accepted',\"Offer Accepted\"),('sold',\"Sold\"),('canceled',\"Canceled\")], required=True, copy=False, default='new')\n\n ## Constraints from SQL\n\n _sql_constraints = [\n ('check_selling_price', 'CHECK(selling_price >= 0)',\n 'The price of the offer must be strictly positive'),\n ('check_expected_price', 'CHECK(expected_price > 0)',\n 'The expected price must be strictly positive'),\n ]\n\n ## Fields entre models\n\n property_type_id=fields.Many2one(\"estate.type\",string=\"Type\")\n salesperson = fields.Many2one('res.users', string='Salesperson', default=lambda self: self.env.user)\n buyer = fields.Many2one('res.partner', string=\"Buyer\", copy=False)\n \n\n tag_ids=fields.Many2many(\"estate.tag\", string=\"Tags\")\n offer_ids = fields.One2many(\"estate.offer\", \"property_id\", string=\"Offers\")\n\n ## Fields computados \n\n total_area = fields.Float(compute=\"_compute_total_area\")\n best_price = fields.Float(compute=\"_compute_best_price\")\n \n\n ## Cálculo do field área total\n\n @api.depends(\"living_area\",\"garden_area\")\n def _compute_total_area(self):\n for rec in self:\n rec.total_area = rec.living_area + rec.garden_area\n\n\n ## Cálculo da maior oferta\n\n @api.depends(\"offer_ids\")\n def _compute_best_price(self):\n for rec in self:\n best = 0\n for x in rec.offer_ids:\n if x.price > best:\n best = x.price\n rec.best_price = best\n \n \n ## Automatização dos fields relacionados à garden\n \n @api.onchange(\"garden\")\n def _onchange_garden(self):\n if self.garden==True:\n self.garden_area = 10\n self.garden_orientation = 'north'\n if self.garden == False:\n self.garden_area = None\n self.garden_orientation = None\n\n ## Ação de cancelamento da property\n\n def action_cancel_property(self):\n for rec in self:\n if rec.state == 'sold':\n raise UserError(\"A sold property can not be cancelled\")\n else:\n rec.state = 'canceled'\n \n return True\n\n ## Ação de venda da property\n\n def action_sell_property(self):\n for rec in self:\n if rec.state == 'canceled':\n raise UserError(\"A canceled property can not be sold\")\n else:\n if not rec.buyer.id:\n raise UserError(\"A property without a buyer can not be sold\")\n else: rec.state = 'sold'\n \n return True\n\n ## Adicionando constrains\n\n @api.constrains('selling_price','expected_price')\n def _check_price_relation(self):\n for rec in self:\n if rec.selling_price != 0:\n if rec.selling_price<(0.9*rec.expected_price):\n raise ValidationError(\"The selling price cannot be lower than 90 percent of the expected price\")\n \n ## Overwriting da ação de unlink\n\n def unlink(self):\n for rec in self:\n if rec.state!='new' or rec.state!='canceled':\n raise UserError('You cannot delete a property if its state is not ‘New’ or ‘Canceled’')\n return super().unlink()\n\n \n\n\n\n","sub_path":"estate/models/estate_property.py","file_name":"estate_property.py","file_ext":"py","file_size_in_byte":4219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"234349165","text":"# Copyright (c) 2021, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are 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 Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from this\n# software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\"\"\"Tests for deepconsensus.models.model_utils.\"\"\"\n\nimport os\nimport uuid\n\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n\nimport tensorflow as tf\n\nfrom deepconsensus.models import model_configs\nfrom deepconsensus.models import model_utils\nfrom deepconsensus.utils import test_utils\n\n\nclass GetModelTest(absltest.TestCase):\n\n def test_valid_model_name(self):\n \"\"\"Tests that correct model name works.\"\"\"\n\n params = model_configs.get_config('fc+test')\n model_utils.modify_params(params)\n model = model_utils.get_model(params)\n self.assertIsInstance(model, tf.keras.Model)\n\n def test_invalid_model_name_throws_error(self):\n \"\"\"Tests that incorrect model name throws an error.\"\"\"\n\n with self.assertRaises(ValueError):\n params = model_configs.get_config('fc+test')\n model_utils.modify_params(params)\n params.model_name = 'incorrect_name'\n model_utils.get_model(params)\n\n\nclass ModifyParamsTest(parameterized.TestCase):\n\n @parameterized.parameters(['transformer+test', 'fc+test'])\n def test_params_modified(self, config_name):\n \"\"\"Tests that params are correctly modified based on the model.\"\"\"\n\n params = model_configs.get_config(config_name)\n\n # These params may have different values when running a sweep.\n # They should be modified so that they are equal.\n params.batch_size = 1\n params.default_batch_size = 2\n model_utils.modify_params(params)\n\n if config_name == 'fc+test':\n self.assertNotEqual(params.batch_size, params.default_batch_size)\n elif config_name == 'transformer+test':\n self.assertEqual(params.batch_size, params.default_batch_size)\n\n\nclass RunInferenceAndWriteResultsTest(absltest.TestCase):\n\n def test_output_dir_created(self):\n \"\"\"Tests that output dir created when it does not exist.\"\"\"\n\n out_dir = f'/tmp/output_dir/{uuid.uuid1()}'\n self.assertFalse(tf.io.gfile.isdir(out_dir))\n params = model_configs.get_config('transformer_learn_values+test')\n model_utils.modify_params(params)\n model = model_utils.get_model(params)\n checkpoint_path = test_utils.deepconsensus_testdata('model/checkpoint-1')\n checkpoint = tf.train.Checkpoint(model=model)\n checkpoint.restore(checkpoint_path)\n model.compile(\n optimizer=tf.keras.optimizers.Adam(learning_rate=params.learning_rate),\n loss=model_utils.get_deepconsensus_loss(params),\n metrics=model_utils.get_deepconsensus_metrics())\n model_utils.run_inference_and_write_results(model, out_dir, params)\n self.assertTrue(tf.io.gfile.isdir(out_dir))\n inference_output = os.path.join(out_dir, 'inference.csv')\n self.assertTrue(tf.io.gfile.exists(inference_output))\n with tf.io.gfile.GFile(inference_output) as inference_output_file:\n\n # Check that model.metric_names was called after real data was fed through\n # the model, and that metric names are correct.\n first_line = inference_output_file.readline()\n self.assertEqual(\n first_line, 'dataset,loss,' + ','.join([\n metric.name for metric in model_utils.get_deepconsensus_metrics()\n ]) + '\\n')\n\n\nif __name__ == '__main__':\n absltest.main()\n","sub_path":"deepconsensus/models/model_utils_test.py","file_name":"model_utils_test.py","file_ext":"py","file_size_in_byte":4708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"574367564","text":"#!/usr/bin/env python3.5\n\nimport unicodedata\n\nprint('| Binary | Decimal | Octal | Hexadecimal | Code |')\nprint('|----------|---------|-------|-------------|----------------------------------------------|')\n\nnames = []\n\n#mnames[7] = \"BS - Backspace\";\n\nmnames = {\n 0: \"NUL\",\n 1: \"SOH - START OF HEADING, CONSOLE INTERRUPT\",\n 2: \"STX - START OF TEXT\",\n 3: \"ETX - END OF TEXT\",\n 4: \"EOT - END OF TRANSMISSION\",\n 5: \"ENQ - ENQUIRY\",\n 6: \"ACK - ACKNOWLEDGEMENT\",\n 7: \"BEL - BELL\",\n 8: \"BS - BACKSPACE\",\n 9: \"HT - HORIZONTAL TAB\",\n 10: \"LF - LINE FEED\",\n 11: \"VT - VERTICAL TAB\",\n 12: \"FF - FORM FEED\",\n 13: \"CR - CARRIAGE RETURN\",\n 14: \"SO - SHIFT OUT\",\n 15: \"SI - SHIFT IN\",\n 16: \"DLE - DATA LINK ESCAPE\",\n 17: \"DC1 - DEVICE CONTROL 1 (OFT. XON)\",\n 18: \"DC2 - DEVICE CONTROL 2\" ,\n 19: \"DC3 - DEVICE CONTROL 3 (OFT. XOFF)\",\n 20: \"DC4 - DEVICE CONTROL 4\",\n 21: \"NAK - NEGATIVE ACKNOWLEDGMENT\",\n 22: \"SYN - SYNCHRONOUS IDLE\",\n 23: \"ETB - END OF TRANSMISSON BLOCK\",\n 24: \"CAN - CANCEL\",\n 25: \"EM - END OF MEDIUM\",\n 26: \"SUB - SUBSTITUTE\",\n 27: \"ESC - ESCAPE\",\n 28: \"FS - FILE SEPARATOR\",\n 29: \"GS - GROUP SEPARATOR\",\n 30: \"RS - RECORD SEPARATOR\",\n 31: \"US - UNIT SEPARATOR\",\n\n 127: \"DEL - DELETE\",\n }\n\nfor y in range(0,256):\n thisname = \"\"\n thisname = unicodedata.name(chr(y),\"d3fault\")\n\n if thisname != \"d3fault\":\n thisname = chr(y) + \" \" + thisname\n else:\n try:\n if mnames[y]:\n thisname = mnames[y]\n except:\n pass\n\n names.insert(y,thisname)\n\nfor x in range(0,256):\n print(\"| **{0:08b}** | {1:3d} | {2:03o} | {3:02X} | {4:44s} |\".format(x,x,x,x,names[x]))\n# print('+----------+-----+-----+-----+--------------------------------------------+')\n","sub_path":"ascii-table-003.py","file_name":"ascii-table-003.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"173126467","text":"\"\"\"\nsalesforce_utils/get_or_create_contact_note.py\n\n\n\"\"\"\nfrom salesforce_fields import contact_note as contact_note_fields\n\n# mimic ``simple_salesforce.Salesforce`` returned keys\nID_RESULT = \"id\"\nSUCCESS = \"success\"\nERRORS = \"errors\"\n\n\ndef get_or_create_contact_note(sf_connection, contact_note_dict):\n \"\"\"Look for an existing Contact Note with the same Contact, Subject, and\n Date of Contact fields. Return dict with its SafeID if exists,\n otherwise create and return Safe ID of newly created.\n\n Escapes apostrophes in the Subject field for querying via query string.\n\n :param sf_connection: ``simple_salesforce.Salesforce`` instance\n :param contact_note_dict: dictionary of Contact Note details, with keys\n already mapped to Salesforce API fieldnames and dates API-ready.\n :return: results dict (keys 'id', 'success', 'errors')\n :rtype: dict\n \"\"\"\n alum_sf_id = contact_note_dict[contact_note_fields.CONTACT]\n subject = _escape_apostrophes(contact_note_dict[contact_note_fields.SUBJECT])\n date_of_contact = contact_note_dict[contact_note_fields.DATE_OF_CONTACT]\n contact_note_query = (\n f\"SELECT {contact_note_fields.ID} \"\n f\"FROM {contact_note_fields.API_NAME} \"\n f\"WHERE {contact_note_fields.CONTACT} = '{alum_sf_id}' \"\n f\"AND {contact_note_fields.SUBJECT} = '{subject}' \"\n f\"AND {contact_note_fields.DATE_OF_CONTACT} = {date_of_contact} \"\n )\n\n results = sf_connection.query(contact_note_query)\n if results[\"totalSize\"]:\n # doesn't matter if more than one\n existing_sf_id = results[\"records\"][0][\"Id\"]\n return {\n ID_RESULT: existing_sf_id,\n SUCCESS: False,\n ERRORS: [f\"Found conflicting Contact Note {existing_sf_id}\",],\n }\n\n return sf_connection.Contact_Note__c.create(contact_note_dict)\n\n\ndef _escape_apostrophes(text):\n \"\"\"Escape apostrophes in the input text, ready for Salesforce API.\n\n :param text: str text in which to escape apostrophes\n :return: text with apostrophes escaped\n :rtype: str\n \"\"\"\n return text.replace(\"'\", \"\\\\'\")\n","sub_path":"salesforce_utils/get_or_create_contact_note.py","file_name":"get_or_create_contact_note.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"5730967","text":"#! /usr/bin/python3\nfrom megapi import *\nfrom time import sleep\n\nbot = MegaPi()\nbot.start()\n\n# these numbers will change when we get the new connectors\nLF_MOTOR_PORT = 1\nRR_MOTOR_PORT = 4\nARM_MOTOR_PORT = 3\nCLAW_MOTOR_PORT = 2\n\n#function reference:\n############################\n#move_forward(time,speed=90)\n#move_backward(time,speed=90)\n#turn_right(degrees=90)\n#turn_left(degrees=90)\n#pivot_right(degrees=90)\n#pivot_left(degrees=90)\n#pickup_item()\n#put_down_item()\n#drop_item()\n#stop()\n\n\n#updated this to be easier to use, just input the time you want it to move and then you can change the defaults if it is necessary\n\ndef move_forward(time, speed=90):\n bot.encoderMotorRun(LF_MOTOR_PORT, -speed)\n bot.encoderMotorRun(RR_MOTOR_PORT, speed)\n sleep(time)\n bot.encoderMotorRun(LF_MOTOR_PORT, 0)\n bot.encoderMotorRun(RR_MOTOR_PORT, 0)\n \ndef move_backward(time, speed=90):\n bot.encoderMotorRun(LF_MOTOR_PORT, speed)\n bot.encoderMotorRun(RR_MOTOR_PORT, -speed)\n sleep(time)\n bot.encoderMotorRun(LF_MOTOR_PORT, 0)\n bot.encoderMotorRun(RR_MOTOR_PORT, 0)\n\n#turn functions only turn the motor on the outside of the turn, this is the same speed as pivoting, but it doesn't get bogged down\n# as much when you are going for more than 45 degrees. This would be the default when driving around the area, not for precise alignment\n\n#just call the function and input your desired degrees to turn and it will be close to your target angle. It won't be perfect,\n# but doing multiple smaller adjustmests may be better than trying to get exact on the first pivot/turn\n\ndef turn_right(degrees=90):\n #print(\"turn right \", degrees, \" degrees\")\n speed=90\n time=7*(degrees/90)\n #bot.encoderMotorRun(LF_MOTOR_PORT, speed)\n bot.encoderMotorRun(RR_MOTOR_PORT, speed)\n sleep(time)\n bot.encoderMotorRun(LF_MOTOR_PORT, 0)\n bot.encoderMotorRun(RR_MOTOR_PORT, 0)\n \ndef turn_left(degrees=90):\n #print(\"turn left \", degrees, \" degrees\")\n speed=90\n time=7*(degrees/90)\n bot.encoderMotorRun(LF_MOTOR_PORT, -speed)\n #bot.encoderMotorRun(RR_MOTOR_PORT, -speed)\n sleep(time)\n bot.encoderMotorRun(LF_MOTOR_PORT, 0)\n bot.encoderMotorRun(RR_MOTOR_PORT, 0)\n\n#pivot functions run both motors so the robot rotates in place, it gets bogged down if you pivot for more than 45 degrees,\n# in one go, so ideally it could be used for precise lining up at the target and not for driving around autonomously.\n\ndef pivot_right(degrees=90):\n print(\"pivot right \", degrees, \" degrees\")\n speed=90\n time=7*(degrees/90)\n bot.encoderMotorRun(LF_MOTOR_PORT, speed)\n bot.encoderMotorRun(RR_MOTOR_PORT, speed)\n sleep(time)\n bot.encoderMotorRun(LF_MOTOR_PORT, 0)\n bot.encoderMotorRun(RR_MOTOR_PORT, 0)\n \ndef pivot_left(degrees=90):\n print(\"pivot left \", degrees, \" degrees\")\n speed=90\n time=7*(degrees/90)\n bot.encoderMotorRun(LF_MOTOR_PORT, -speed)\n bot.encoderMotorRun(RR_MOTOR_PORT, -speed)\n sleep(time)\n bot.encoderMotorRun(LF_MOTOR_PORT, 0)\n bot.encoderMotorRun(RR_MOTOR_PORT, 0)\n \ndef stop():\n bot.encoderMotorRun(LF_MOTOR_PORT, 0)\n bot.encoderMotorRun(RR_MOTOR_PORT, 0)\n bot.encoderMotorRun(ARM_MOTOR_PORT,0)\n bot.encoderMotorRun(CLAW_MOTOR_PORT,0)\n \ndef backupAndRotate():\n move_backward(0,0,0)\n turn_left(0,0)\n \n # delay for demonstration purposes only\n sleep(0.5)\n \ndef raise_claw(speed, time):\n bot.encoderMotorRun(ARM_MOTOR_PORT,-speed)\n sleep(time)\n bot.encoderMotorRun(ARM_MOTOR_PORT,0)\n \ndef lower_claw(speed, time):\n bot.encoderMotorRun(ARM_MOTOR_PORT,speed)\n sleep(time)\n bot.encoderMotorRun(ARM_MOTOR_PORT,0)\n \ndef tighten_claw(speed, time):\n bot.encoderMotorRun(CLAW_MOTOR_PORT,-speed)\n sleep(time)\n bot.encoderMotorRun(CLAW_MOTOR_PORT,0)\n \ndef loosen_claw(speed, time):\n #print(\"check\")\n bot.encoderMotorRun(CLAW_MOTOR_PORT,speed)\n sleep(time)\n bot.encoderMotorRun(CLAW_MOTOR_PORT,0)\n\n# these are the preset functions to pickup and drop the blocks\n# these are dependant on the above claw functions, so do not change those if you want these values to stay relevant.\n\ndef pickup_item():\n #print(\"pickup item\")\n lower_claw(50,4)\n tighten_claw(15,3.5)\n raise_claw(50,3.9)\n \ndef put_down_item():\n #print(\"put down item\")\n lower_claw(50,4)\n loosen_claw(30,2.6)\n raise_claw(50,3.9)\n \ndef drop_item():\n #print(\"drop item into bowl\")\n lower_claw(50,2)\n loosen_claw(30,2.6)\n raise_claw(50,1.9)\n \n \n# may be useful to call after putting a block down\ndef turn_around():\n print(\"turn 180 degrees\")\n \n","sub_path":"motion.py","file_name":"motion.py","file_ext":"py","file_size_in_byte":4612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"240200238","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nfrom flask import Flask, render_template, redirect, url_for, request\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nimport pandas as pd \nimport pickle\nimport numpy as np \nimport nltk\nfrom nltk.corpus import stopwords \nimport re\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.externals import joblib\nfrom newsplease import NewsPlease\nimport newspaper\nfrom newspaper import Article\nfrom sklearn import svm\nimport os\nimport boto3\n\n# Set the limit for number of articles to download\ndef dailyNews(paper):\n LIMIT = 30\n title_csv = []\n content_csv=[]\n url_csv = []\n # It uses the python newspaper library to extract articles\n# print(\"Building site for \", paper)\n paper = newspaper.build(paper, memoize_articles=False)\n noneTypeCount = 0\n count=1\n\n for content in paper.articles:\n if count > LIMIT:\n break\n try:\n content.download()\n content.parse()\n except Exception as e:\n print(e)\n print(\"continuing...\")\n continue\n # Again, for consistency, if there is no found publish date the article will be skipped.\n if content.publish_date is None:\n noneTypeCount = noneTypeCount + 1\n count = count + 1\n continue\n if content.title == 'Terms of Service' or content.title=='Privacy Policy' or content.url.startswith('https://cn.nytimes.com/') or content.url.startswith('http://cn.nytimes.com/'):\n err = 'error'\n else:\n title = content.title\n title_csv.append(title)\n\n text = content.text\n content_csv.append(text)\n \n url = content.url\n url_csv.append(url)\n\n count = count + 1\n noneTypeCount = 0 \n count = 1\n newsResult = dict(zip(title_csv, content_csv))\n urlResult = dict(zip(title_csv, url_csv))\n return newsResult,urlResult;\n\ndef url_Contents(url_article):\n article = NewsPlease.from_url(url_article)\n if (article.text) == None:\n print('None')\n else:\n content = article.text\n return content\n\nporter_stemmer = nltk.stem.porter.PorterStemmer()\n\n#spilts the sentences into words\ndef porter_tokenizer(text, stemmer=porter_stemmer):\n lower_txt = text.lower()\n tokens = nltk.wordpunct_tokenize(lower_txt)\n stems = [porter_stemmer.stem(t) for t in tokens]\n no_punct = [s for s in stems if re.match('^[a-zA-Z]+$', s) is not None]\n return no_punct\n\nstop_words = set(stopwords.words('english'))\n\ntfidf_vectorizer = TfidfVectorizer(stop_words='english',\n encoding='utf-8',\n decode_error='replace',\n strip_accents='unicode',\n analyzer='word',\n tokenizer=porter_tokenizer,\n ngram_range=(1,2),\n binary=False)\n\n\ndef vectorizeData():\n aws_id = ''\n aws_secret = ''\n client = boto3.client('s3',aws_access_key_id=aws_id, aws_secret_access_key=aws_secret)\n obj_job = client.get_object(Bucket='ads-final', Key='CleanData.csv')\n df = pd.read_csv(obj_job['Body'],encoding='utf-8')\n le = LabelEncoder()\n le.fit(df['Label'])\n\n df_labels = pd.DataFrame(np.array(le.transform(df['Label'])))\n \n skf = StratifiedKFold(n_splits = 5)\n \n for trn_indx, tst_indx in skf.split(df['Content'],df_labels):\n skf_X_train, skf_X_test = df['Content'].iloc[trn_indx], df['Content'].iloc[tst_indx]\n skf_Y_train, skf_Y_test = df_labels.iloc[trn_indx], df_labels.iloc[tst_indx]\n \n # Fit and transform the training data for tfidf\n tfidf_train = tfidf_vectorizer.fit_transform(skf_X_train)\n\n # Transform the test set \n tfidf_test = tfidf_vectorizer.transform(skf_X_test)\n \n return tfidf_train,tfidf_test,skf_Y_train,skf_Y_test\n\n#Generate the training and testing dataset\nX_train, X_test ,Y_train, Y_test = vectorizeData()\n\n#Using the SVM Model\nclf = svm.LinearSVC()\nclf.fit(X_train,Y_train)\nclf.score(X_test,Y_test)\n\n###########################################\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n@app.route('/about')\ndef about():\n return render_template('about.html')\n@app.route('/contact')\ndef contact():\n return render_template('contact.html')\n\n@app.route('/dailyNews',methods=['GET','POST'])\ndef daily_news():\n if request.method =='GET':\n methods='GET'\n return render_template('daily_news.html',methods=methods)\n elif request.method =='POST':\n url_final=[]\n title_lis =[]\n url_lis=[]\n content_lis=[]\n methods='POST'\n hidden1=request.form['input1']\n paper=request.form['paper']\n title_list,url_list = dailyNews(paper)\n my_prediction=[]\n for title,comment in title_list.items():\n data = [comment]\n vect = tfidf_vectorizer.transform(data).toarray()\n my_predict = clf.predict(vect)\n my_prediction.append(my_predict)\n for a,b in title_list.items():\n title_lis.append(a)\n content_lis.append(b)\n for c,d in url_list.items():\n url_lis.append(d)\n if paper =='https://www.nytimes.com/':\n paperName = 'New York Times'\n elif paper =='https://www.huffpost.com/':\n paperName = 'Huff Post'\n elif paper =='https://worldnewsdailyreport.com/':\n paperName = 'World News Daily Report'\n paperNames=[]\n c=len(title_lis)\n for i in range(1,c+1):\n paperNames.append(paperName)\n ################\n# count=1\n# if count==1:\n# title_csv = [e for e in title_lis]\n# url_csv = [f for f in url_lis]\n# content_csv = [g for g in content_lis]\n# name_csv = [h for h in paperNames]\n# count=count+1\n# elif count > 1:\n# for el in title_lis:\n# title_csv.append(el)\n# for ele in url_lis:\n# title_csv.append(ele)\n# for elem in content_lis:\n# title_csv.append(elem)\n# for elemt in paperNames:\n# title_csv.append(elemt)\n ################\n df = pd.DataFrame(data={'Title': title_lis,'Publication':paperNames,'URL': url_lis, 'Content': content_lis})\n df.to_csv(os.getcwd()+'/Daily_read.csv')\n return render_template('daily_news.html',methods=methods,prediction = my_prediction,title_lis=title_lis,url_lis=url_lis)\n\n@app.route('/urlNews',methods=['GET','POST'])\ndef url_news():\n if request.method =='GET':\n methods='GET'\n return render_template('url_news.html',methods=methods)\n elif request.method =='POST':\n hidden2=request.form['input2']\n methods='POST'\n url_article = request.form['url']\n comment = url_Contents(url_article)\n data = [comment]\n vect = tfidf_vectorizer.transform(data).toarray()\n my_prediction = clf.predict(vect)\n return render_template('url_news.html',hidden2=hidden2,methods=methods,url_article=url_article,prediction = my_prediction)\n\n\n@app.route('/content',methods=['GET','POST'])\ndef content():\n if request.method =='GET':\n methods='GET'\n return render_template('content.html',methods=methods)\n \n elif request.method =='POST':\n hidden3=request.form['input3']\n methods='POST'\n comment = request.form['comment']\n data = [comment]\n vect = tfidf_vectorizer.transform(data).toarray()\n my_prediction = clf.predict(vect)\n return render_template('content.html',hidden3=hidden3,methods=methods,prediction = my_prediction,comment=comment)\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Code/Docker Web App/Web_App_Final.py","file_name":"Web_App_Final.py","file_ext":"py","file_size_in_byte":8128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"376617377","text":"from PLC.Method import Method\nfrom PLC.Parameter import Parameter, Mixed\nfrom PLC.Filter import Filter\nfrom PLC.Auth import Auth\nfrom PLC.Persons import Person, Persons\nfrom PLC.sendmail import sendmail\n\nclass NotifyPersons(Method):\n \"\"\"\n Sends an e-mail message to the specified users. If person_filter\n is specified and is an array of user identifiers or usernames, or\n a struct of user attributes, only users matching the filter will\n receive the message.\n\n Returns 1 if successful.\n \"\"\"\n\n roles = ['admin', 'node']\n\n accepts = [\n Auth(),\n Mixed([Mixed(Person.fields['person_id'],\n Person.fields['email'])],\n Filter(Person.fields)),\n Parameter(str, \"E-mail subject\"),\n Parameter(str, \"E-mail body\")\n ]\n\n returns = Parameter(int, '1 if successful')\n\n def call(self, auth, person_filter, subject, body):\n persons = Persons(self.api, person_filter,\n ['person_id', 'first_name', 'last_name', 'email'])\n if not persons:\n raise PLCInvalidArgument(\"No such user(s)\")\n\n # Send email\n sendmail(self.api,\n To = [(\"%s %s\" % (person['first_name'], person['last_name']),\n person['email']) for person in persons],\n Subject = subject,\n Body = body)\n\n # Logging variables\n self.event_objects = {'Person': [person['person_id'] for person in persons]}\n self.message = subject\n\n return 1\n","sub_path":"PLC/Methods/NotifyPersons.py","file_name":"NotifyPersons.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"513332174","text":"import time\nfrom datetime import date as cdate\nfrom datetime import datetime as cdatetime\n\nfrom sqlalchemy import DateTime, Date, Time, text\n\nfrom blueprints import db\n\n\ndef getConnect(app=None, bind=None):\n \"\"\"\n 开放获得connection对象,用于多数据库\n :param app: current_app\n :param bind: 其他DB连接配置名\n :return:\n \"\"\"\n if bind is not None:\n conn = db.get_engine(app, bind)\n else:\n conn = db.get_engine(app)\n return conn\n\n\ndef queryBySQL(app=None, sess=None, sql=None, params=None):\n \"\"\"\n 用原生SQL进行查询,查询完成以后,把结果集转化为字典列表,字典的key就是字段名\n :param app:使用app的默认数据库连接进行查询\n :param sess:使用session来控制事务\n :param sql:原生SQL\n :param params: SQL使用的参数\n :return:\n \"\"\"\n if sess is None:\n conn = db.get_engine(app)\n statement = text(sql)\n db_result = conn.execute(statement, params)\n data = dbResultToDict(list(db_result))\n else:\n statement = text(sql)\n db_result = sess.execute(statement, params)\n data = dbResultToDict(list(db_result))\n return data\n\n\ndef executeBySQL(app=None, sess=None, sql=None, params=None):\n \"\"\"\n 用原生SQL进行查询,查询完成以后,把结果集转化为字典列表,字典的key就是字段名\n :param app:使用app的默认数据库连接进行查询\n :param sess:使用session来控制事务\n :param sql:原生SQL\n :param params: SQL使用的参数\n :return: 影响条数\n \"\"\"\n if sess is None:\n conn = db.get_engine(app)\n statement = text(sql)\n resultProxy = conn.execute(statement, params)\n else:\n statement = text(sql)\n resultProxy = sess.execute(statement, params)\n return resultProxy.rowcount\n\n\ndef countBySQL(app=None, sess=None, sql=None, params=None):\n \"\"\"\n 用原生SQL进行查询,查询完成以后,把结果集转化为字典列表,字典的key就是字段名\n :param app:使用app的默认数据库连接进行查询\n :param sess:数据库连接\n :param sql:原生SQL\n :param params: SQL使用的参数\n :return:\n \"\"\"\n if sess is None:\n conn = db.get_engine(app)\n statement = text(sql)\n db_result = conn.execute(statement, params)\n data = dbResultToDict(list(db_result))\n else:\n statement = text(sql)\n db_result = sess.execute(statement, params)\n data = dbResultToDict(list(db_result))\n\n return int(data[0].get('count'))\n\n\ndef dbResultToDict(result=None):\n \"\"\"\n 查询结果集转化为字典类型\n :param result:\n :return:\n \"\"\"\n # 当结果为result对象列表时,result有key()方法\n res = [dict(zip(r.keys(), r)) for r in result]\n # 这里r为一个字典,对象传递直接改变字典属性\n for r in res:\n find_datetime(r)\n return res\n\n\ndef find_datetime(value):\n \"\"\"\n 把结果里面的日期时间值进行格式化\n :param value:\n :return:\n \"\"\"\n for v in value:\n if isinstance(value[v], cdatetime):\n # 这里原理类似,修改的字典对象,不用返回即可修改\n value[v] = convert_datetime(value[v])\n\n\ndef convert_datetime(value):\n \"\"\"\n 根据值的类型,分别进行格式化操作\n :param value:\n :return:\n \"\"\"\n if value:\n if isinstance(value, (cdatetime, DateTime)):\n return value.strftime(\"%Y-%m-%d %H:%M:%S\")\n elif isinstance(value, (cdate, Date)):\n return value.strftime(\"%Y-%m-%d\")\n elif isinstance(value, (Time, time)):\n return value.strftime(\"%H:%M:%S\")\n else:\n return value\n\n# 留着备份\n# class db_utils(object):\n#\n# def queryToDict(self, models):\n# \"\"\"集合化查询结果\"\"\"\n# res = ''\n# if models is None:\n# return \"\"\n# if (isinstance(models, list)):\n# if (len(models) == 0):\n# return \"\"\n# elif (isinstance(models[0], Model)):\n# lst = []\n# for model in models:\n# gen = self.__model_to_dict(model)\n# dit = dict((g[0], g[1]) for g in gen)\n# lst.append(dit)\n# return lst\n# else:\n# res = self.__result_to_dict(models)\n# return str(res)\n# else:\n# if (isinstance(models, Model)):\n# gen = self.__model_to_dict(models)\n# dit = dict((g[0], g[1]) for g in gen)\n# return dit\n# else:\n# res = dict(zip(models.keys(), models))\n# self.__find_datetime(res)\n# return str(res)\n#\n# def __result_to_dict(self, results):\n# # 当结果为result对象列表时,result有key()方法\n# res = [dict(zip(r.keys(), r)) for r in results]\n# # 这里r为一个字典,对象传递直接改变字典属性\n# for r in res:\n# self.__find_datetime(r)\n# return res\n#\n# def __model_to_dict(self, model):\n# # 这段来自于参考资源\n# for col in model.__table__.columns:\n# if isinstance(col.type, DateTime):\n# value = self.__convert_datetime(getattr(model, col.name))\n# elif isinstance(col.type, Numeric):\n# value = float(getattr(model, col.name))\n# else:\n# value = getattr(model, col.name)\n# yield (col.name, value)\n#\n# def __find_datetime(self, value):\n# for v in value:\n# if (isinstance(value[v], cdatetime)):\n# value[v] = self.__convert_datetime(value[v]) # 这里原理类似,修改的字典对象,不用返回即可修改\n#\n# def __convert_datetime(self, value):\n# if value:\n# if (isinstance(value, (cdatetime, DateTime))):\n# return value.strftime(\"%Y-%m-%d %H:%M:%S\")\n# elif (isinstance(value, (cdate, Date))):\n# return value.strftime(\"%Y-%m-%d\")\n# elif (isinstance(value, (Time, time))):\n# return value.strftime(\"%H:%M:%S\")\n# else:\n# return \"\"\n","sub_path":"blueprints/bp_chatrobot/common/db_utils.py","file_name":"db_utils.py","file_ext":"py","file_size_in_byte":6293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"366290642","text":"from .joueur import Joueur\nfrom parser.read_question import Type\nfrom parser.infos import current_turn_infos, game_over\n\n\nclass Inspecteur(Joueur):\n \"\"\"\n IA de l'Inspecteur\n \"\"\"\n def __init__(self):\n super().__init__(0)\n\n def lancer(self):\n while not game_over(self.id):\n self.init_turn()\n self.question.read()\n if self.question.type == Type.DRAW:\n if len(self.question.args) == 1:\n self.act('0')\n continue\n infos, suspects = current_turn_infos(self.id)\n print(self.question.args)\n to_play = self.model.select_character(self.id, suspects,\n self.question.args)\n self.act(to_play)\n else:\n self.random_act()\n","sub_path":"player/inspecteur.py","file_name":"inspecteur.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"92593509","text":"class Laptop:\n discount_percent =10\n def __init__(self,brand,model_name,price):\n self.Laptop_brand=brand\n self.Lpatop_model_name=model_name\n self.Laptop_price=price\n self.Laptop_name=brand +' '+model_name\n\n def apply_discount(self):\n discount=self.Laptop_price-((self.Laptop_price*Laptop.discount_percent)/100)\n return f\"after appling discount price:{discount}\"\nl1=Laptop('HP','HP 15-da007ttx',48000)\nl2=Laptop('apple','macbook',230000)\nprint(l1.Laptop_name)\nprint(l1.Laptop_price)\nprint(l1.apply_discount())\nprint(l2.Laptop_name)\nprint(l2.Laptop_price)\nprint(l2.apply_discount())","sub_path":"chapter16/exercise16.2.py","file_name":"exercise16.2.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"61473332","text":"import cv2 as cv\r\nimport numpy as np\r\nimg = cv.imread('lean.jpg')\r\ncv.imshow('Lean',img)\r\n\r\nwidth,height =img.shape[1],img.shape[0]\r\n# we need to give the coordinates of the image we can get those by opening the image in paint and hover over the pixel values\r\ncoord = np.float32([[164,5],[281,1],[133,394],[241,397]])\r\n'''This is the order of the defining the co-ordinates, first co-ordinate is the pixel value of the top left, followed by top right\r\nbottom left, bottom right'''\r\nseq = np.float32([[0,0],[width,0],[0,height],[width,height]])\r\n# -- Matrix is to analogise with the coordinates present in image\r\nmatrix = cv.getPerspectiveTransform(coord,seq)\r\n# -- Attributes are the source, comparative matrix, dimensions\r\norient = cv.warpPerspective(img,matrix,(width,height))\r\ncv.imshow('Oriented',orient)\r\n\r\ncv.waitKey(0)\r\n","sub_path":"Orienting Images .py","file_name":"Orienting Images .py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"257294645","text":"# -*- coding: utf-8 -*-\n\nimport pytz\nfrom datetime import timedelta, time\nfrom pendulum import Time\n\nfrom .. import AbstractTestCase\n\n\nclass SubTest(AbstractTestCase):\n\n def test_sub_hours_positive(self):\n self.assertEqual(23, Time(0, 0, 0).subtract(hours=1).hour)\n\n def test_sub_hours_zero(self):\n self.assertEqual(0, Time(0, 0, 0).subtract(hours=0).hour)\n\n def test_sub_hours_negative(self):\n self.assertEqual(1, Time(0, 0, 0).subtract(hours=-1).hour)\n\n def test_sub_minutes_positive(self):\n self.assertEqual(59, Time(0, 0, 0).subtract(minutes=1).minute)\n\n def test_sub_minutes_zero(self):\n self.assertEqual(0, Time(0, 0, 0).subtract(minutes=0).minute)\n\n def test_sub_minutes_negative(self):\n self.assertEqual(1, Time(0, 0, 0).subtract(minutes=-1).minute)\n\n def test_sub_seconds_positive(self):\n self.assertEqual(59, Time(0, 0, 0).subtract(seconds=1).second)\n\n def test_sub_seconds_zero(self):\n self.assertEqual(0, Time(0, 0, 0).subtract(seconds=0).second)\n\n def test_sub_seconds_negative(self):\n self.assertEqual(1, Time(0, 0, 0).subtract(seconds=-1).second)\n\n def test_subtract_timedelta(self):\n delta = timedelta(seconds=16, microseconds=654321)\n d = Time(3, 12, 15, 777777)\n\n d = d.subtract_timedelta(delta)\n self.assertEqual(11, d.minute)\n self.assertEqual(59, d.second)\n self.assertEqual(123456, d.microsecond)\n\n d = Time(3, 12, 15, 777777)\n\n d = d - delta\n self.assertEqual(11, d.minute)\n self.assertEqual(59, d.second)\n self.assertEqual(123456, d.microsecond)\n\n def test_add_timedelta_with_days(self):\n delta = timedelta(days=3, seconds=45, microseconds=123456)\n d = Time(3, 12, 15, 654321)\n\n self.assertRaises(TypeError, d.subtract_timedelta, delta)\n\n def test_subtract_invalid_type(self):\n d = Time(0, 0, 0)\n\n try:\n d - 'ab'\n self.fail()\n except TypeError:\n pass\n\n try:\n 'ab' - d\n self.fail()\n except TypeError:\n pass\n\n def test_subtract_time(self):\n t = Time(12, 34, 56)\n t1 = Time(1, 1, 1)\n t2 = time(1, 1, 1)\n t3 = time(1, 1, 1, tzinfo=pytz.timezone('Europe/Paris'))\n\n diff = t - t1\n self.assertIsInstanceOfInterval(diff)\n self.assertInterval(diff, 0, hours=11, minutes=33, seconds=55)\n\n diff = t1 - t\n self.assertIsInstanceOfInterval(diff)\n self.assertInterval(diff, 0, hours=-11, minutes=-33, seconds=-55)\n\n diff = t - t2\n self.assertIsInstanceOfInterval(diff)\n self.assertInterval(diff, 0, hours=11, minutes=33, seconds=55)\n\n diff = t2 - t\n self.assertIsInstanceOfInterval(diff)\n self.assertInterval(diff, 0, hours=-11, minutes=-33, seconds=-55)\n\n self.assertRaises(TypeError, t.__sub__, t3)\n self.assertRaises(TypeError, t.__rsub__, t3)\n","sub_path":"tests/time_tests/test_sub.py","file_name":"test_sub.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"523968515","text":"# this automates the work note generation of the refund process after data has been entered into excel\r\n# this ran from linux ubuntu. \r\n# this also will enter the work notes and assign the DBA team\r\n# gregory.waters@gov.bc.ca 2019. \r\n\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\", message=\"Data Validation extension is not supported and will be removed\")\r\nimport openpyxl\r\nimport os\r\nimport inquirer\r\nimport requests\r\nimport pysnow\r\nimport json\r\n\r\n# os.chdir is for a linux subsystem, need to update that path for windows\r\nos.chdir('/mnt/share/n/DropBox/02 Refunds')\r\nworkbook = openpyxl.load_workbook('ServiceDeskRefunds.xlsx')\r\nsheet = workbook.get_sheet_by_name('2019-Refunds')\r\n\r\n###TO DO Make an option, just 1 refund, if yes --> use last row with data, if not, prompt row questions\r\n#default last row row_count=sheet.max_row print(row_count)\r\n\r\n#Get Receipt Type\r\nnew_receipt = input(\"Please paste in the receipt type; e.g., REGI SOFI COLIN or NAMES: \").upper()\r\nnew_receipt = new_receipt.replace(\" \", \"\")\r\n\r\nrow = sheet.max_row\r\n\r\nrow_int = int(row)\r\n\r\n\r\n#generate variable based off input for sql worknote \r\nif'REGI' or 'SOFI' or 'COLIN' in new_receipt:\r\n db = 'CPRD'\r\nif 'NAMES' in new_receipt:\r\n db = 'GLOBALP'\r\n\r\n#variables for print statement\r\nsql_statement= \"insert into payment_state (payment_state_id,payment_invoice_id,payment_state_type_cd,bcep_transaction_id,state_timestamp,refund_amount) values(payment_state_seq.nextval,'\"\r\nsql_work_note = ''\r\nitops_work_note = ''\r\nsql_db = 'Please run the following in '+ db +' and pass back once complete:\\n \\n'\r\n\r\n#make the ITOPS text statement\r\nfor i in range(row_int, row_int+1):\r\n work_note_itops = (\"\\nOriginal Transaction \\nAmount: \"+str(sheet.cell(row=i, column=5).value)+\"\\nTransaction ID: \"+str(sheet.cell(row=i, column=2).value)+\r\n \"\\nRef3: \"+new_receipt+\"00000\"+str(sheet.cell(row=i, column=3).value)+\r\n \"\\n\\nRefund Transaction \\nAmount: \"+\r\n str(sheet.cell(row=i, column=9).value)+\r\n \"\\nTransaction ID: \" + str(sheet.cell(row=i, column=7).value)+\r\n \"\\nRef3: \"+new_receipt+\"00000\"+str(sheet.cell(row=i, column=3).value)+\r\n \"\\n\\n--------------------------------------------\\n\")\r\n itops_work_note += work_note_itops\r\n\r\nitops_work_note += \"\\n Inserted into spreadsheet\"\r\n\r\nprint(itops_work_note)\r\n\r\n#make the sql statemenor i in range(row1_int,row2_int+1):\r\nwork_note_sql = (sql_statement+new_receipt+\"00000\"+str(sheet.cell(row=i, column=3).value)+\"','REFUNDED',\" + str(sheet.cell(row=i, column=7).value)+\",sysdate,\"+\r\nstr(sheet.cell(row=i, column=9).value)+\");\\n\\n\")\r\nsql_work_note += work_note_sql \r\n\r\nstore = {'token': None}\r\n\r\n# Takes care of refreshing the token storage if needed\r\ndef updater(new_token):\r\n print(\"OAuth token refreshed!\")\r\n store['token'] = new_token\r\n\r\n# Create the OAuthClient with the ServiceNow provided `client_id` and `client_secret`, and a `token_updater`\r\n# function which takes care of refreshing local token storage.\r\ns = pysnow.OAuthClient(client_id='eaf24769f03dc01cbf208c86789a4a5b',\r\n client_secret='NP5vu|VawR',\r\n token_updater=updater, instance='sbcsnprod')\r\n\r\nif not store['token']:\r\n #No previous token exists. Generate new.\r\n store['token'] = s.generate_token('bcrsapi', '97!K}D%H$2@A7a{#rRE]@5H!v;9LM9Ht4_pXr3(aGc/&>wyErFQJ??Vc<9%QM<')\r\n\r\n# Set the access / refresh tokens\r\ns.set_token(store['token'])\r\n\r\nwith open('data.json', 'w', encoding='utf-8') as f:\r\n json.dump(store, f, ensure_ascii=False, indent=4)\r\n\r\n# Let's define a `Resource` for the incident API.\r\nincident_resource = s.resource(api_path='/table/x_mscb4_sbc_inc_incident')\r\n\r\n#get the inc number\r\ninc = input(\"Please paste the INC number: \")\r\ninc = inc.replace(\" \",\"\")\r\n\r\n# Update 'short_description' for 'INC'\r\nupdate_itos = {'work_notes': itops_work_note}\r\nupdated_record_itos = incident_resource.update(query={'number': inc}, payload=update_itos)\r\n\r\n\r\n# Update to paste in sql statement and assign to dbas \r\nupdate_dba = {'work_notes': sql_db + sql_work_note, 'assignment_group' : 'Registries DBA', 'assigned_to' : ''}\r\nupdated_record_dba = incident_resource.update(query={'number': inc}, payload=update_dba)\r\n\r\nprint(\"Done\")\r\n\r\n","sub_path":"refund_new.py","file_name":"refund_new.py","file_ext":"py","file_size_in_byte":4194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"563167676","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author : Mike\n# @Contact : 597290963@qq.com\n# @Time : 2021/2/24 22:49\n# @File : RecoverTree.py\n\"\"\"\n给你二叉搜索树的根节点 root ,该树中的两个节点被错误地交换。请在不改变其结构的情况下,恢复这棵树。\n\n进阶:使用 O(n) 空间复杂度的解法很容易实现。你能想出一个只使用常数空间的解决方案吗?\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/recover-binary-search-tree\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\n\"\"\"\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def recoverTree(self, root: TreeNode) -> None:\n \"\"\"\n Do not return anything, modify root in-place instead.\n \"\"\"\n # 利用二叉搜索树,中序遍历为递增,找到错误的2个节点\n self.first_node = None\n self.second_node = None\n self.pre_Node = TreeNode(float('-inf'))\n\n def dfs(node):\n if not node:\n return\n\n dfs(node.left)\n if not self.first_node and self.pre_Node.val >= node.val:\n self.first_node = self.pre_Node\n if self.first_node and self.pre_Node.val >= node.val:\n self.second_node = node\n\n self.pre_Node = node\n dfs(node.right)\n\n dfs(root)\n self.first_node.val, self.second_node.val = self.second_node.val, self.first_node.val\n","sub_path":"datastructure/Stack/RecoverTree.py","file_name":"RecoverTree.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"401606481","text":"\"\"\"Setup.py for restpy.\"\"\"\n\nfrom setuptools import find_packages\nfrom setuptools import setup\n\n\nwith open('README.rst') as f:\n\n README = f.read()\n\nwith open('requirements.txt') as f:\n\n REQUIREMENTS = f.readlines()\n\nsetup(\n name='RESTpy',\n version='0.7.1',\n url='https://github.com/kevinconway/rest.py',\n license='BSD',\n description='Werkzeug extensions for building RESTful services.',\n author='Kevin Conway',\n author_email='kevinjacobconway@gmail.com',\n long_description=README,\n classifiers=[],\n packages=find_packages(exclude=['tests', 'build', 'dist', 'docs']),\n install_requires=REQUIREMENTS,\n)\n","sub_path":"pypi_install_script/RESTpy-0.7.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"225949436","text":"#!/usr/bin/env python\n\nimport datetime\nimport os\nimport sys\nimport threading\nimport time\nimport traceback\nimport signal\nfrom iotools import IOTools\n\n\nclass Logger(object):\n def __init__(self, onRobot):\n self.useTerminal = not onRobot\n self.terminal = sys.stdout\n self.log = 0\n if os.path.isdir('/tmp/sandbox'):\n self.log = open('/tmp/sandbox/log.txt', 'a+')\n\n def write(self, message):\n if self.useTerminal:\n self.terminal.write(message)\n if self.log:\n self.log.write(message)\n self.log.flush()\n\n def flush(self):\n pass\n\n\nclass Sandbox:\n __version = '2018a'\n\n def __init__(self, onRobot):\n print(datetime.datetime.now())\n print('[Sandbox] R:SS Sandbox ' + Sandbox.__version)\n\n def signal_handler(signal, frame):\n print('[INFO] [Sandbox] Received signal no. {}'.format(signal))\n self.destroy()\n sys.exit(0)\n\n signal.signal(signal.SIGINT, signal_handler)\n signal.signal(signal.SIGTERM, signal_handler)\n\n self.__done = False\n self.__IO = IOTools(onRobot)\n\n try:\n def led_control_d():\n \"\"\"\n This is the LED control *daemon* thread target.\n \"\"\"\n ifkit = self.__IO.interface_kit\n led = ifkit.led\n\n # Blink all LEDs 3 times\n for _ in range(3):\n for i in range(3):\n ifkit.setOutputState(i, 1)\n time.sleep(0.15)\n for i in range(3):\n ifkit.setOutputState(i, 0)\n time.sleep(0.15)\n\n t = 0\n\n # Start heartbeat\n while not self.__done:\n t = (t + 1) % 100\n for i in range(3):\n led._status[i] = ((t + led._ofs[i]) % led._mod[i] == 0) and led._val[i] and bool(led._rep[i])\n led._rep[i] = led._rep[i] - int(led._rep[i] > 0 and led._status[i])\n ifkit.setOutputState(i, led._status[i])\n time.sleep(0.15)\n\n def toddler_control():\n \"\"\"\n This is the toddler *control* thread target.\n \"\"\"\n while not self.__done:\n self.__toddler.control()\n\n def toddler_vision():\n \"\"\"\n This is the toddler *vision* thread target.\n \"\"\"\n while not self.__done:\n self.__toddler.vision()\n\n sys.path.insert(0, '/home/student/')\n sys.path.insert(1, '/home/pi/')\n import toddler\n\n self.__toddler = toddler.Toddler(self.__IO)\n\n try:\n self.__led_control_d = threading.Thread(target=led_control_d)\n self.__toddler_control = threading.Thread(target=toddler_control)\n self.__toddler_vision = threading.Thread(target=toddler_vision)\n\n self.__led_control_d.setDaemon(True)\n\n self.__led_control_d.start()\n self.__toddler_control.start()\n self.__toddler_vision.start()\n\n while threading.active_count() > 0:\n time.sleep(1)\n except KeyboardInterrupt:\n print('[INFO] [Sandbox] You pressed Ctrl+C!')\n self.destroy()\n sys.exit(0)\n except Exception:\n print('[ERROR] [Sandbox] The toddler is hurt:')\n traceback.print_exc()\n\n def destroy(self):\n self.__done = True\n self.__toddler_control.join()\n self.__toddler_vision.join()\n self.__IO.destroy()\n\n\nif __name__ == '__main__':\n onRobot = bool(sys.argv.count('-rss'))\n sys.stdout = Logger(onRobot)\n sys.stderr = sys.stdout\n sandbox = Sandbox(onRobot)\n","sub_path":"rpi/sandbox.py","file_name":"sandbox.py","file_ext":"py","file_size_in_byte":3941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"67223949","text":"# -*- coding: utf-8 -*-\n\"\"\" =================================================\n -- file: projects/yearcompass_booklet_2015_2016/models.py\n -- site: Translations\n================================================= \"\"\"\n### -------------- Python packages -------------- ###\n### -------------- Django packages -------------- ###\nfrom django.db import models\n### ----------- Third party packages ------------ ###\n### ----------- External app packages ----------- ###\n### ---------------- App packages --------------- ###\nfrom transformer import BookletTransformer\n\nclass BookletLine(models.Model):\n \"\"\"------------------------------------------------\n - Model name: BookletLine -\n ------------------------------------------------\"\"\"\n line = models.TextField(\n verbose_name=u'Translatable line',\n )\n\n context = models.TextField(\n verbose_name=u'Optional context for translators',\n blank=True,\n )\n\n number = models.PositiveSmallIntegerField(\n verbose_name=u'The token number of the line',\n unique=True,\n )\n\n class Meta:\n verbose_name = u'Booklet line'\n verbose_name_plural = u'Booklet lines'\n ordering = ('number',)\n\n def __unicode__(self):\n return str(self.number) + ' | ' + unicode(self.line)\n\n def save(self, update_text=False, *args, **kwargs):\n # Remove unecessary spaces from the line\n self.line = self.line.strip()\n\n # Auto add numbers if not present\n if not self.number:\n # Search for the max number, and auto increase current number by one\n max_number = BookletLine.objects.aggregate(models.Max('number'))['number__max']\n if max_number: self.number = int(max_number) + 1\n else: self.number = 1\n\n # Call parent save\n super(BookletLine, self).save(*args, **kwargs)\n\n # Update booklet Text only if signal arrives\n if update_text:\n BookletTransformer().line2text()\n\nclass BookletText(models.Model):\n \"\"\"------------------------------------------------\n - Model name: BookletText -\n ------------------------------------------------\"\"\"\n full_text = models.TextField(\n verbose_name=u'Translatable text',\n )\n\n class Meta:\n verbose_name = u'Booklet text'\n ordering = ('id',)\n\n def __unicode__(self):\n return 'YearCompass booklet text'\n\n def save(self, update_lines=False, check_duplicates=False, *args, **kwargs):\n # Call parent save\n super(BookletText, self).save(*args, **kwargs) \n\n # Update booklet Lines only if signal arrives\n if update_lines:\n BookletTransformer().text2line(check_duplicates)\n","sub_path":"projects/yearcompass_booklet_2015_2016/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"231311912","text":"import json\nfrom splinter import Browser as Firefox\nfrom metasozlukapi import *\nfrom metasozlukapi.client.exception import *\nimport re\n\ndef json_repr(obj):\n \"http://stackoverflow.com/a/4682553\"\n nuller = (0, [], (), None)\n \n def serialize(obj):\n \"\"\"Recursively walk object's hierarchy.\"\"\"\n if isinstance(obj, (bool, int, float, str)):\n return obj\n elif obj == None:\n return\n elif isinstance(obj, dict):\n obj = obj.copy()\n for key in obj:\n obj[key] = serialize(obj[key])\n return obj\n elif isinstance(obj, list):\n return [serialize(item) for item in obj if not obj in nuller]\n elif isinstance(obj, tuple):\n return tuple(serialize([item for item in obj if not obj in nuller]))\n elif hasattr(obj, '__dict__'):\n return serialize(obj.__dict__)\n else:\n return repr(obj)\n \n return json.dumps(serialize(obj), ensure_ascii=False)\n\nclass Browser(object):\n url = {\n \"main\" : \"http://metasozluk.com\",\n \"login\": \"http://metasozluk.com/?r=site/giris\",\n \"entry\" : \"http://metasozluk.com/?r=girdi/goster&g={}\",\n \"topic\" : \"http://metasozluk.com/?r=girdi/index&m=home&t={}&p={}\",\n \"topic_all\" : \"http://metasozluk.com/?r=girdi/index&m=home&t={}&hepsi=True&p={}\",\n \"profile\" : \"http://metasozluk.com/?r=kullanici/profil&u={}\",\n \"search\" : \"http://metasozluk.com/?r=arama%2Fara&q={}&p={}\"\n }\n \n def __init__(self, username = None, password = None):\n self.browser = Firefox()\n self.__initialize()\n self.username = None\n self.password = None\n if username != None:\n self.login(username, password)\n \n def __initialize(self):\n self.browser.visit(self.url[\"main\"])\n \n def login(self, username, password):\n self.browser.visit(self.url[\"login\"])\n self.browser.fill(\"LoginForm[username]\", username)\n self.browser.fill(\"LoginForm[password]\", password)\n self.browser.find_by_css(\".settingprofile-save\").click()\n if self.browser.find_by_css(\".error-message ul li\") != []:\n raise InvalidUsernameOrPasswordException(username)\n self.username = username\n self.password = password\n return True\n \n def get_entry(self, idn):\n idn = str(idn)\n entry = Entry()\n self.browser.visit(self.url[\"entry\"].format(idn))\n entry.idn = idn\n entry.topic = Topic()\n entry.topic.title = self.browser.find_by_css(\"#thread-header h1 a\").value\n entry.topic.idn = int(re.findall(\"t=([0-9]+)\", self.browser.find_by_css(\"#thread-header h1 a\").outer_html)[0])\n entry.content = self.browser.find_by_css(\".comment-text\").value\n entry.author = User()\n entry.author.nick = self.browser.find_by_css(\".comment-info .pull-right a\").value\n entry.author.idn = int(re.findall(\"u=([0-9]+)\", self.browser.find_by_css(\".comment-info .pull-right a\").outer_html)[0])\n entry.date = self.browser.find_by_css(\".comment-date\").value\n entry.likes = int(self.browser.find_by_css(\".likenumber\").value)\n return entry\n \n def get_topic(self, idn, all=False, page=1):\n idn = str(idn)\n topic = Topic()\n \n if page < 1:\n raise InvalidPageException(str(page), \"Page number cannot be under 1.\")\n \n if all == True:\n self.browser.visit(self.url[\"topic_all\"].format(idn, page))\n topic.all = True\n else:\n self.browser.visit(self.url[\"topic\"].format(idn, page))\n topic.all = False\n \n if self.browser.find_by_css(\"#error-message\") != []:\n raise UndefinedOffsetException()\n \n cats = self.browser.find_by_css(\".entry-list-cats-link\")\n \n topic.idn = int(idn)\n topic.title = self.browser.find_by_css(\"#thread-header h1 a\").value\n topic.all = all\n \n for cat in cats:\n cat.click()\n \n del cats\n \n entries = self.browser.find_by_css(\".entry-section\")\n \n for section in entries:\n entry = Entry()\n entry.idn = int(section.find_by_css(\".entry-list-cats-content span a\").value[1:])\n entry.content = section.find_by_css(\".comment-text\").value\n entry.author = User()\n entry.author.nick = self.browser.find_by_css(\".comment-info .pull-right a\").value\n entry.author.idn = int(re.findall(\"u=([0-9]+)\", self.browser.find_by_css(\".comment-info .pull-right a\").outer_html)[0])\n entry.date = section.find_by_css(\".comment-date\").value\n entry.likes = int(section.find_by_css(\".likenumber\").value)\n topic.entries.append(entry)\n \n del entries, entry\n \n return topic\n \n def get_user(self, idn):\n idn = str(idn)\n user = User()\n user.idn = int(idn)\n \n self.browser.visit(self.url[\"profile\"].format(idn))\n \n if self.browser.find_by_css(\"#error-message\") != []:\n raise InvalidProfileException()\n \n info = self.browser.find_by_css(\".profile-info\")\n panels = self.browser.find_by_css(\".profile-panel-list\")\n \n user.nick = self.browser.find_by_css(\".user-name\")[0].value\n user.level = info.find_by_css(\".profile-info li span\")[1].value[8:]\n user.university = info.find_by_css(\".profile-info li span\")[2].value[12:]\n user.department = info.find_by_css(\".profile-info li span\")[3].value[7:]\n user.sex = info.find_by_css(\".profile-info li span\")[4].value[10:]\n user.city = info.find_by_css(\".profile-info li span\")[5].value[7:]\n \n user.total_title = int(self.browser.find_by_css(\".user-box-list span\")[0].value)\n user.total_entry = int(self.browser.find_by_css(\".user-box-list span\")[1].value)\n user.last_one_month = int(self.browser.find_by_css(\".user-box-list span\")[2].value)\n user.last_one_week = int(self.browser.find_by_css(\".user-box-list span\")[3].value)\n \n latest_entries = panels[0].find_by_tag(\"li\")\n latest_topics = panels[1].find_by_tag(\"li\")\n most_liked_entries = panels[2].find_by_tag(\"li\")\n most_informative_entries = panels[3].find_by_tag(\"li\")\n \n for entry in latest_entries:\n e = Entry()\n e.idn = int(re.findall(\"g=([0-9]+)\", entry.find_by_tag(\"a\")[0][\"href\"])[0])\n e.topic = Topic()\n e.topic.title = entry.find_by_tag(\"a\")[0].value\n e.topic.title = re.sub(\" - #[0-9]+\", \"\", e.topic.title)\n e.author = user.nick\n user.latest_entries.append(e)\n \n for entry in latest_topics:\n t = Topic()\n t.idn = int(re.findall(\"t=([0-9]+)\", entry.find_by_tag(\"a\")[0][\"href\"])[0])\n e.topic.title = entry.find_by_tag(\"a\")[0].value\n user.latest_topics.append(e)\n \n for entry in most_liked_entries:\n e = Entry()\n e.idn = int(re.findall(\"g=([0-9]+)\", entry.find_by_tag(\"a\")[0][\"href\"])[0])\n e.topic = Topic()\n e.topic.title = entry.find_by_tag(\"a\")[0].value\n e.topic.title = re.sub(\" - #[0-9]+\", \"\", e.topic.title)\n e.author = user.nick\n user.most_liked_entries.append(e)\n \n for entry in most_informative_entries:\n e = Entry()\n e.idn = int(re.findall(\"g=([0-9]+)\", entry.find_by_tag(\"a\")[0][\"href\"])[0])\n e.topic = Topic()\n e.topic.title = entry.find_by_tag(\"a\")[0].value\n e.topic.title = re.sub(\" - #[0-9]+\", \"\", e.topic.title)\n e.author = user.nick\n user.most_informative_entries.append(e)\n \n for key in user.__dict__:\n if user.__dict__[key] == \"\": user.__dict__[key] = None\n \n return user\n \n def search(self, query, page=1):\n query = str(query)\n query_type = None\n search = Search()\n search.query = query\n \n if page < 1:\n raise InvalidPageException(str(page), \"Page number cannot be under 1.\")\n \n if query[0] == \"@\":\n query_type = \"profile\"\n elif query[0] == \"#\":\n query_type = \"entry\"\n elif query[0] == \"$\":\n query_type = \"category\"\n else:\n query_type = \"topic\"\n \n if query_type == \"category\":\n raise NotSupportedYetException(\"Category search is not supported yet.\")\n \n self.browser.visit(self.url[\"search\"].format(query, page))\n \n if query_type == \"profile\":\n if self.browser.find_by_css(\".no-entry-message\") != []:\n raise InvalidProfileException(query)\n else:\n uid = re.findall(\"u=([0-9]+)\", self.browser.url)[0]\n search.results = self.get_user(uid)\n return search\n elif query_type == \"entry\":\n if self.browser.find_by_css(\".no-entry-message\") != []:\n raise InvalidEntryException(query)\n else:\n search.results = self.get_entry(query[1:])\n return search\n elif query_type == \"topic\":\n if self.browser.find_by_css(\".no-entry-message\") != []:\n raise InvalidTopicException(query)\n else:\n if self.browser.find_by_css(\"#search-result-container\") != []:\n entries = []\n results = self.browser.find_by_css(\".search-result\")\n for section in results:\n entry = Entry()\n entry.idn = section.find_by_css(\".entry-list-cats-content span a\").value[1:]\n entry.topic = Topic()\n entry.topic.title = self.browser.find_by_css(\".thread-title a\").value\n entry.topic.idn = re.findall(\"t=([0-9]+)\", self.browser.find_by_css(\".thread-title a\").outer_html)[0]\n entry.content = section.find_by_css(\".comment-text\").value\n entry.author = User()\n entry.author.nick = self.browser.find_by_css(\".comment-info .pull-right a\").value\n entry.author.idn = re.findall(\"u=([0-9]+)\", self.browser.find_by_css(\".comment-info .pull-right a\").outer_html)[0]\n entry.date = section.find_by_css(\".comment-date\").value\n entry.likes = section.find_by_css(\".likenumber\").value\n entries.append(entry)\n search.results = entries\n else:\n search.results = self.get_entry(re.findall(\"t=([0-9]+)\", self.browser.url))[0]\n return search","sub_path":"src/metasozlukapi/client/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":10916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"310355610","text":"import math\nfrom numpy import array, linalg, dot, add\n\ndef beta4(jets,ebeam):\n\n rows = []\n for i in range(4):\n rows.append([])\n for jet in jets:\n rows[0].append(jet.px()/jet.energy())\n rows[1].append(jet.py()/jet.energy())\n rows[2].append(jet.pz()/jet.energy())\n rows[3].append(jet.energy()/jet.energy()) \n\n constraint = [0.,0.,0.,2.*ebeam]\n\n d2 = array(rows)\n d = array(constraint)\n #print d2\n #print d\n energies = linalg.solve(d2,d)\n #print energies\n chi2 = 0.\n for i,jet in enumerate(jets):\n\n if energies[i] > 0. :\n uncert = 0.5*math.sqrt(jet.energy()) + 0.05*jet.energy()\n delta = (jet.energy()-energies[i])/uncert\n if delta > 0. : \n chi2 += delta*delta\n else:\n chi2 += delta*delta/4.\n else:\n chi2 += 1000.\n\n p4 = jet.p4()\n p4.SetPxPyPzE(jet.px()*energies[i]/jet.energy(),\n jet.py()*energies[i]/jet.energy(),\n jet.pz()*energies[i]/jet.energy(),\n energies[i])\n jet.setP4(p4)\n\n return chi2\n","sub_path":"CMGTools/LEP3/python/analyzers/beta4.py","file_name":"beta4.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"646143165","text":"# Copyright (c) The Libra Core Contributors\n# SPDX-License-Identifier: Apache-2.0\n\nfrom .protocol_command import ProtocolCommand\nfrom .payment import PaymentObject\nfrom .utils import JSONSerializable\nfrom .command_processor import CommandValidationError\nfrom .errors import OffChainErrorCode\n\n\n# Functions to check incoming diffs\nclass PaymentLogicError(CommandValidationError):\n \"\"\" Indicates a payment processing error. \"\"\"\n pass\n\n\n# Note: ProtocolCommand is JSONSerializable, so no need to extend again.\n@JSONSerializable.register\nclass PaymentCommand(ProtocolCommand):\n ''' Creates a new ``PaymentCommand`` based on a given payment.\n\n The command creates the object version of the payment given\n and depends on any previous versions of the given payment.\n\n Args:\n payment (PaymentObject): The payment from which to build the command.\n '''\n\n def __init__(self, payment_object):\n ProtocolCommand.__init__(self)\n ref_id = payment_object.reference_id\n self.reads_version_map = [(ref_id, payment_object.previous_version)] \\\n if payment_object.previous_version else []\n self.writes_version_map = [(ref_id, payment_object.get_version())]\n self.command = payment_object.get_full_diff_record()\n\n def __eq__(self, other):\n return ProtocolCommand.__eq__(self, other) \\\n and self.command == other.command\n\n def get_request_cid(self):\n \"\"\" Suggests the cid that the request with this command should contain.\n\n Each cid should ideally be unique, and the same command should create a\n request with the same cid. \"\"\"\n\n _, new_version = self.writes_version_map[0]\n return new_version\n\n\n def get_object(self, version_number, dependencies):\n \"\"\" Returns the new payment object defined by this command. Since this\n may depend on a previous payment (when it is an update) we need to\n provide a dictionary of its dependencies.\n\n Args:\n version_number (int): The version number\n dependencies (list): The list of dependencies.\n\n Raises:\n PaymentLogicError: If the payment depends on more than one other\n payment.\n\n Returns:\n PaymentObject: The updated payment.\n \"\"\"\n # First find dependencies & created objects.\n new_version = self.get_new_version_number()\n if new_version != version_number:\n raise PaymentLogicError(\n OffChainErrorCode.payment_dependency_error,\n f\"Unknown object {version_number} (only know {new_version})\"\n )\n\n # This indicates the command creates a fresh payment.\n if len(self.reads_version_map) == 0:\n payment = PaymentObject.create_from_record(self.command)\n payment.set_version(new_version)\n return payment\n\n # This command updates a previous payment.\n elif len(self.reads_version_map) == 1:\n _, dep = self.reads_version_map[0]\n if dep not in dependencies:\n raise PaymentLogicError(\n OffChainErrorCode.payment_dependency_error,\n f'Could not find payment dependency: {dep}'\n )\n dep_object = dependencies[dep]\n\n # Need to get a deepcopy new version.\n updated_payment = dep_object.new_version(new_version, store=dependencies)\n\n PaymentObject.from_full_record(\n self.command, base_instance=updated_payment)\n return updated_payment\n\n raise PaymentLogicError(\n OffChainErrorCode.payment_wrong_structure,\n f\"Should depend on exactly one object, got: {len(self.reads_version_map)}\")\n\n def get_payment(self, dependencies):\n version = self.get_new_version_number()\n\n # Optimization to prevent repeated checks and deep copying\n if version in dependencies:\n return dependencies[version]\n\n return self.get_object(version, dependencies)\n\n def get_json_data_dict(self, flag):\n ''' Get a data dictionary compatible with JSON serilization\n (json.dumps).\n\n Args:\n flag (utils.JSONFlag): whether the JSON is intended\n for network transmission (NET) to another party or local\n storage (STORE).\n\n Returns:\n dict: A data dictionary compatible with JSON serilization.\n '''\n data_dict = ProtocolCommand.get_json_data_dict(self, flag)\n data_dict['payment'] = self.command\n return data_dict\n\n @classmethod\n def from_json_data_dict(cls, data, flag):\n \"\"\" Construct the object from a serlialized JSON\n data dictionary (from json.loads).\n\n Args:\n data (dict): A JSON data dictionary.\n flag (utils.JSONFlag): whether the JSON is intended\n for network transmission (NET) to another party or local\n storage (STORE).\n\n Raises:\n PaymentLogicError: If there is an error while creating the payment.\n\n Returns:\n PaymentCommand: A PaymentCommand from the input data.\n \"\"\"\n self = super().from_json_data_dict(data, flag)\n # Thus super() is magic, but do not worry we get the right type:\n assert isinstance(self, PaymentCommand)\n self.command = data['payment']\n\n if len(self.reads_version_map) > 1:\n # TODO: Test for such errors within protocol.py tests.\n raise PaymentLogicError(\n OffChainErrorCode.payment_wrong_structure,\n \"A payment can only depend on a single previous payment\"\n )\n\n if len(self.writes_version_map) != 1:\n # TODO: Test for such errors within protocol.py tests.\n raise PaymentLogicError(\n OffChainErrorCode.payment_wrong_structure,\n \"A payment always creates a new payment\")\n\n return self\n\n # Helper functions for payment commands specifically\n def get_previous_version_number(self):\n \"\"\" Returns the version of the previous payment, or None if this\n command creates a new payment\n\n Returns:\n The version of the previous payment, or None if this\n command creates a new payment.\n \"\"\"\n # This is ensured from the constructors.\n assert len(self.reads_version_map) <= 1\n if len(self.reads_version_map) == 0:\n return None\n _, prev_version = self.reads_version_map[0]\n return prev_version\n\n def get_new_version_number(self):\n ''' Returns the version number of the payment.\n\n Returns:\n int: The version number of the payment.\n '''\n # Ensured from the constructors.\n assert len(self.writes_version_map) == 1\n _, new_version = self.writes_version_map[0]\n return new_version\n","sub_path":"src/offchainapi/payment_command.py","file_name":"payment_command.py","file_ext":"py","file_size_in_byte":7012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"416081705","text":"#Given N axis-aligned rectangles where N > 0, determine if they all together form an exact cover of a rectangular region.\n\n#Each rectangle is represented as a bottom-left point and a top-right point. For example, a unit square is represented as [1,1,2,2]. (coordinate of bottom-left point is (1, 1) and top-right point is (2, 2)).\n\n\n#Example 1:\n\n#rectangles = [\n# [1,1,3,3],\n# [3,1,4,2],\n# [3,2,4,4],\n# [1,3,2,4],\n# [2,3,3,4]\n#]\n\n#Return true. All 5 rectangles together form an exact cover of a rectangular region.\n\n\n\n\n#Example 2:\n\n#rectangles = [\n# [1,1,2,3],\n# [1,3,2,4],\n# [3,1,4,2],\n# [3,2,4,4]\n#]\n\n#Return false. Because there is a gap between the two rectangular regions.\n\n\n\n\n#Example 3:\n\n#rectangles = [\n# [1,1,3,3],\n# [3,1,4,2],\n# [1,3,2,4],\n# [3,2,4,4]\n#]\n\n#Return false. Because there is a gap in the top center.\n\n\n\n\n#Example 4:\n\n#rectangles = [\n# [1,1,3,3],\n# [3,1,4,2],\n# [1,3,2,4],\n# [2,2,4,4]\n#]\n\n#Return false. Because two of the rectangles overlap with each other.\n\nfrom typing import List\nclass Solution:\n def isRectangleCover(self, rectangles: List[List[int]]) -> bool:\n X1, Y1 = float('inf'), float('inf')\n X2, Y2 = -float('inf'), -float('inf')\n\n points = set()\n actual_area = 0\n for x1, y1, x2, y2 in rectangles:\n X1, Y1 = min(X1, x1), min(Y1, y1)\n X2, Y2 = max(X2, x2), max(Y2, y2)\n\n actual_area += (x2-x1) * (y2-y1)\n\n p1, p2 = (x1, y1), (x1, y2)\n p3, p4 = (x2, y1), (x2, y2)\n\n for p in [p1, p2, p3, p4]:\n if p in points:\n points.remove(p)\n else:\n points.add(p)\n\n expected_area = (X2-X1) * (Y2-Y1)\n if actual_area != expected_area:\n return False\n\n if len(points) != 4:\n return False\n\n if (X1, Y1) not in points: return False\n if (X1, Y2) not in points: return False\n if (X2, Y1) not in points: return False\n if (X2, Y2) not in points: return False\n\n return True","sub_path":"python_code/391_Perfect_Rectangle.py","file_name":"391_Perfect_Rectangle.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"653548669","text":"#encoding:utf-8\nfrom flask import flash,url_for,render_template,redirect\nfrom sayhello import app,db\nfrom sayhello.forms import HelloForm\nfrom sayhello.models import Information\nfrom sayhello.recommend import recommned_model\n@app.route(\"/\",methods=[\"GET\",\"POST\"])\ndef index():\n insurance=\"\"\n Card_ID=\"\"\n form=HelloForm()\n if form.validate_on_submit():\n Age=form.Age.data\n Income=form.Income.data\n Weight=form.Weight.data\n Height=form.Height.data\n Marriage=form.Marriage.data\n Sex=form.Sex.data\n Card_ID=form.Card_Id.data\n if (form.Critical_illness.data == \"Yes\"):\n Specific = 1\n else:\n Specific = 0\n Deposit=form.Deposit.data\n if (form.Family_insured.data == \"Yes\"):\n Insured = 1\n else:\n Insured = 0\n print(\"No.\"+Card_ID +\" customer\" + \" is waiting for your advice\")\n flash('Your message has been updated')\n insurance=recommned_model.get_recommendation(Age,Income,Weight,Height,Deposit,Specific,Insured,Sex,Marriage)\n print(insurance)\n return render_template(\"index.html\", form=form, recommendation=insurance, card_ID=Card_ID)\n if not form.validate_on_submit():\n print(form.errors)\n return render_template(\"index.html\",form=form,recommendation=insurance,card_ID=Card_ID)\n\n\n","sub_path":"sayhello/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"264479839","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.contrib.auth.models import User\nfrom django.db import models\n\nfrom django.contrib.contenttypes.models import ContentType\n\nfrom PIL import Image\n\nclass Profile(models.Model):\n\tcharter = models.CharField(max_length=10, blank=True, null=True, verbose_name='cédula')\n\tbirthday = models.DateField(blank=True, null=True, verbose_name='fecha de nacimiento')\n\tcellphone = models.CharField(max_length=32, blank=True, null=True, verbose_name='número de celular')\n\tavatar = models.ImageField(upload_to='social/avatares/', blank=True, null=True,)\t\n\tis_complete = models.BooleanField(default=False)\n\tuser = models.OneToOneField(User, on_delete=models.CASCADE)\n\n\tdef __unicode__(self):\n\t\treturn self.user\n\n\tdef get_full_name(self):\n\t\treturn self.user.get_full_name()\n\t\t\n\tdef get_profiles(self, status):\n\t\tprofiles = []\n\n\t\tfriendships = Friendship.objects.filter(\n\t\t\tmodels.Q(from_profile=self) |\n\t\t\tmodels.Q(to_profile=self)\n\t\t).filter(status=status)\n\n\t\tfor friendship in friendships:\n\t\t\tprofile = friendship.from_profile if friendship.to_profile == self else friendship.to_profile\n\t\t\tprofiles.append(profile)\n\n\t\treturn profiles\t\t\n\n\tdef friends(self):\t\t\t\t\n\t\tfriends = self.get_profiles(Friendship.FRIENDSHIP_FRIEND)\n\t\treturn friends\n\n\tdef blocked_friends(self):\t\t\t\t\t\n\t\tblocked = self.get_profiles(Friendship.FRIENDSHIP_BLOCKED)\n\t\treturn blocked\n\n\tdef requests(self):\n\t\tprofiles = []\n\n\t\tfriendships = Friendship.objects.filter(\n\t\t\tto_profile=self,\n\t\t\tstatus=Friendship.FRIENDSHIP_REQUEST\n\t\t)\n\n\t\tfor friendship in friendships:\t\t\t\n\t\t\tprofiles.append(friendship.from_profile)\n\n\t\treturn profiles\n\n\tdef sent_requests(self):\n\t\tprofiles = []\n\n\t\tfriendships = Friendship.objects.filter(\n\t\t\tfrom_profile=self,\n\t\t\tstatus=Friendship.FRIENDSHIP_REQUEST\n\t\t)\n\n\t\tfor friendship in friendships:\t\t\t\n\t\t\tprofiles.append(friendship.to_profile)\n\n\t\treturn profiles\n\n\tdef commercial(self):\n\t\tfrom showcase.models import Locality\n\t\ttry:\n\t\t\tlocality = Locality.objects.get(owner=self, is_commercial=True)\n\t\t\treturn locality.commercial\n\t\texcept Locality.DoesNotExist:\n\t\t\treturn None\n\n\tdef save(self, *args, **kwargs):\n\t\tsuper(Profile, self).save(*args, **kwargs)\n\n\t\tif self.avatar:\n\t\t\tprocess_image(self.avatar, 500)\n\nclass FriendshipManager(models.Manager):\n\tdef send_request(self, from_profile, to_profile):\n\t\tif from_profile == to_profile:\n\t\t\traise ValidationError(\"No se puede enviar una solicitud el mismo\")\n\n\t\tfriendships = Friendship.objects.filter(\n\t\t\tmodels.Q(from_profile=from_profile) | models.Q(to_profile=from_profile),\n\t\t\tmodels.Q(from_profile=to_profile) | models.Q(to_profile=to_profile)\n\t\t)\n\n\t\tif len(friendships) > 0:\n\t\t\treturn False\n\n\t\tfriendship = Friendship.objects.create(\n\t\t\tfrom_profile = from_profile,\n\t\t\tto_profile = to_profile,\n\t\t\tstatus = Friendship.FRIENDSHIP_REQUEST\n\t\t)\n\n\t\treturn friendship\n\n\tdef accept(self, from_profile, to_profile):\n\t\tfriendships = Friendship.objects.filter(from_profile=from_profile, to_profile=to_profile)\n\t\tif len(friendships) != 1:\n\t\t\traise ValidationError('Error de integridad')\n\n\t\tfriendship = friendships[0]\n\n\t\tfriendship.status = Friendship.FRIENDSHIP_FRIEND\n\t\tfriendship.save()\n\t\treturn True\n\n\tdef reject(self, from_profile, to_profile):\n\t\tfriendships = Friendship.objects.filter(\n\t\t\tfrom_profile=from_profile, to_profile=to_profile, status=Friendship.FRIENDSHIP_REQUEST\n\t\t)\n\t\tif len(friendships) != 1:\n\t\t\traise ValidationError('Error de integridad')\n\n\t\tfriendships.delete()\n\t\treturn True\n\n\tdef delete_friend(self, profile1, profile2):\n\t\tfriendships = Friendship.objects.filter(\n\t\t\tmodels.Q(from_profile=profile1) | models.Q(to_profile=profile1),\n\t\t\tmodels.Q(from_profile=profile2) | models.Q(to_profile=profile2)\n\t\t).filter(status=Friendship.FRIENDSHIP_FRIEND)\n\n\t\tfriendships.delete()\n\t\treturn True\n\n\t\n\tdef check_status(self, profile1, profile2, check=True):\n\t\tfriendships = Friendship.objects.filter(\n\t\t\tfrom_profile=profile1, to_profile=profile2\t\t\t\n\t\t)\n\n\t\tif len(friendships) == 0:\n\t\t\treturn self.check_status(profile2, profile1, check=False) if check else 'Envia una solicitud'\n\t\t\n\t\tfriendship = friendships[0]\n\n\t\tif friendship.status == Friendship.FRIENDSHIP_REQUEST:\n\t\t\treturn 'Solicitud enviada.' if check else 'Solicitud recibida.'\n\t\telif friendship.status == Friendship.FRIENDSHIP_FRIEND:\n\t\t\treturn 'Amigos'\n\t\telse:\n\t\t\treturn 'Bloqueado'\n\nclass Friendship(models.Model):\n\tFRIENDSHIP_REQUEST = 1\n\tFRIENDSHIP_FRIEND = 2\n\tFRIENDSHIP_BLOCKED = 3\n\n\tSTATE_CHOICES = (\n\t\t(FRIENDSHIP_REQUEST, 'Solicitud'),\n\t\t(FRIENDSHIP_FRIEND, 'Amistad'),\t\t\n\t\t(FRIENDSHIP_BLOCKED, 'Bloqueado'),\t\t\n\t)\n\n\tclass Meta:\n\t\tunique_together = ('from_profile', 'to_profile')\n\n\tfrom_profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='relationship')\n\tto_profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='to_profile')\n\tstatus = models.PositiveSmallIntegerField(default=1, choices=STATE_CHOICES)\n\tdate_joined = models.DateTimeField(auto_now=True)\n\n\tobjects = FriendshipManager()\n\nclass Comment(models.Model):\n\ttext = models.TextField(blank=True, null=True)\n\timage = models.ImageField(upload_to='showcase/events/',blank=True, null=True)\n\tprofile = models.ForeignKey(Profile)\n\tobject_id = models.IntegerField()\n\tdate_joined = models.DateTimeField(auto_now_add=True)\n\tcontenttype = models.ForeignKey(ContentType, on_delete=models.CASCADE)\n\n\tdef save(self, *args, **kwargs):\n\t\tsuper(Comment, self).save(*args, **kwargs)\n\n\t\tif self.image:\n\t\t\tprocess_image(self.image, 1500)\n\nclass Subscriber(models.Model):\n\tobject_id = models.IntegerField()\n\tprofile = models.ForeignKey(Profile, on_delete=models.CASCADE)\n\tcontenttype = models.ForeignKey(ContentType, on_delete=models.CASCADE)\t\n\n\n\n\n\ndef process_image(image_field, size):\n\timage = Image.open(image_field)\n\twidth, height = image.size\n\tbox = (0,0,width, height)\n\n\tif width > height:\n\t\tvalue = (width - height) / 2\n\t\tbox = (value, 0, width - value, height)\n\telse:\n\t\tvalue = (height - width) / 2\n\t\tbox = (0, value, width, height - value)\n\n\tcut_image = image.crop(box)\n\n\tnew_size = cut_image.width\n\n\tif new_size > size:\n\t\tcut_image = cut_image.resize((size, size), Image.ANTIALIAS)\n\n\tcut_image.save(image_field.path)\n","sub_path":"social/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"598820947","text":"\"\"\"This module contains an array structure and its corresponding methods.\"\"\"\n\n\nclass Array:\n \"\"\"Class to create the object array and being able to manipulate as it.\"\"\"\n\n def __init__(self, size=1):\n \"\"\"\n Implements the array as a list in Python. Initialize the array with zeros.\n :param size: Integer with the fixed size of the array.\n \"\"\"\n self.array = [None for n in range(0, int(size))]\n\n def traverse(self):\n \"\"\"\n Print all the array elements one by one.\n \"\"\"\n print(\"\\n\")\n index = 0\n for element in self.array:\n print(\"Index {} = {}\".format(index, element))\n index += 1\n\n def insertion(self, index, value):\n \"\"\"\n Adds an element at the given index.\n :param index: Integer with the array position to insert the value\n :param value: Any type value to be inserted\n \"\"\"\n if self.array[int(index)] is None:\n self.array[int(index)] = value\n\n def deletion(self, index):\n \"\"\"\n Adds an element at the given index.\n :param index: Integer with the array position to delete the value\n \"\"\"\n if self.array[int(index)]:\n self.array[int(index)] = None\n\n def search(self, index=None, value=None):\n \"\"\"\n Adds an element at the given index.\n :param index: Integer with the array position to search\n :param value: Any type value to be searched\n\n :return Any type value that match the parameters\n \"\"\"\n if index:\n return self.array[int(index)]\n elif value:\n # return list(filter(lambda x: x == value, self.array))[0]\n searched_value = [n for n in self.array if n == value]\n return searched_value[0] if searched_value else None\n\n def update(self, index, value):\n \"\"\"\n Updates an element at the given index.\n :param index: Integer with the array position to update the value\n :param value: Any type value to be updated\n \"\"\"\n if self.array[int(index)]:\n self.array[int(index)] = value\n\n\nif __name__ == \"__main__\":\n arr = Array(8)\n arr.traverse()\n arr.insertion(index=4, value=23)\n arr.insertion(index=1, value=13)\n arr.insertion(index=6, value=2)\n arr.traverse()\n arr.deletion(6)\n arr.traverse()\n print(arr.search(index=4))\n print(arr.search(value=23))\n arr.update(index=4, value=68)\n print(arr.search(index=4))\n","sub_path":"Data_Structures/array.py","file_name":"array.py","file_ext":"py","file_size_in_byte":2500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"583717054","text":"from bs4 import BeautifulSoup\nimport requests\nimport datetime\n\nurl='http://www.dukwon.hs.kr/user/carte/list.do?menuCd=#meals_date'\nr=requests.get(url)\n\nsoup=BeautifulSoup(r.text,\"html.parser\")\n\nmr=soup.find_all(class_=\"meals_table_day01\")\n\nnow = datetime.datetime.now()\nyear=now.strftime(\"%Y\")\nmonth=now.strftime(\"%m\")\nday=int(now.strftime(\"%d\"))\n\nfor i in range(0,7):\n tmp=mr[i].find(\"dd\").get_text()\n \n if(tmp==\"\"):\n tmp=\"No Breakfast\"\n\n tmp=tmp.replace(\"ㆍ\",\"\")\n if day+i<10:\n f = open(\"/home/dukwonlunch/www/data/josik\" + year + month + '0' + str(day + i) + \".txt\", 'w', encoding=\"utf-8\")\n else:\n f=open(\"/home/dukwonlunch/www/data/josik\"+year+month+str(day+i)+\".txt\",'w',encoding=\"utf-8\")\n f.write(tmp)\n f.close()\n\nfor i in range(7,14):\n tmp=mr[i].find(\"dd\").get_text()\n \n if(tmp==\"\"):\n tmp=\"No Lunch\"\n\n tmp=tmp.replace(\"ㆍ\",\"\")\n if day+i<10:\n f = open(\"/home/dukwonlunch/www/data/jungsik\" + year + month + '0' + str(day + i - 7) + \".txt\", 'w', encoding=\"utf-8\")\n else:\n f=open(\"/home/dukwonlunch/www/data/jungsik\"+year+month+str(day+i-7)+\".txt\",'w',encoding=\"utf-8\")\n f.write(tmp)\n f.close()\n\nfor i in range(14,21):\n tmp=mr[i].find(\"dd\").get_text()\n \n if(tmp==\"\"):\n tmp=\"No Dinner\"\n\n tmp=tmp.replace(\"ㆍ\",\"\")\n if day+i<10:\n f = open(\"/home/dukwonlunch/www/data/dinner\" + year + month + '0' + str(day + i - 14) + \".txt\", 'w', encoding=\"utf-8\")\n else:\n f=open(\"/home/dukwonlunch/www/data/dinner\"+year+month+str(day+i-14)+\".txt\",'w',encoding=\"utf-8\")\n f.write(tmp)\n f.close()\n","sub_path":"Weekly Support/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"246618457","text":"from PIL import Image\nimport mechanize\nfrom mechanize import Browser\nfrom bs4 import BeautifulSoup\nimport json, timeit,os\nfrom cap import resolve\nimport http.cookiejar as cookielib\nimport urllib\nimport time\nimport os\nimport pytesseract\nimport sys\nimport argparse\ntry:\n import Image\nexcept ImportError:\n from PIL import Image\nfrom subprocess import check_output\n\nglobal url\nurl = \"http://www.mca.gov.in/mcafoportal/viewCompanyMasterData.do\"\n\ndef resolve(path):\n #Uses tessaract ocr to solve captcha\n\tcheck_output(['convert', path, '-resample', '600', path])\n\treturn pytesseract.image_to_string(Image.open(path))\n\ndef removeextras(_val):\n #Removes extra spaces,newlines and tabs\n if _val:\n try:\n _val = _val.text.replace(\" \",\"\").replace(\"\\n\",\"\").replace(\"\\t\",\"\").strip()\n except:\n _val = _val.replace(\" \",\"\").replace(\"\\n\",\"\").replace(\"\\t\",\"\").strip()\n \n return _val\n\ndef extractHeaderTable(_trs):\n \"\"\"Extracts tables which have headers\n Arguments : BeautifulSoup obj of all the trs under a table\n Returns : json \n Format : [\n {\"header1\":value1,\"header2\":value2,\"header3\":value3},\n {\"header1\":value1,\"header2\":value2,\"header3\":value3}\n ]\n \"\"\"\n _json = [] \n _headers =[x.text for x in _trs[0].find_all(\"th\")]\n for tr in _trs[1:]:\n txt = [removeextras(x) for x in tr.find_all(\"td\")]\n _tmp = {_headers[num]:removeextras(y) for num,y in enumerate(txt)}\n _json.append(_tmp)\n \n return _json\n \ndef extractTable(_trs):\n \"\"\"Extracts\n \n Arguments:\n _trs -- BeautifulSoup obj of all the trs under a table\n \n Returns:\n [json] -- return normal key:value dictionary\n \"\"\"\n _json = {}\n _tds = [_tr.find_all(\"td\") for _tr in _trs]\n _json = {removeextras(_td[0]):removeextras(_td[1]) for _td in _tds}\n\n return _json\n\ndef tableToJson(_table):\n \"\"\"tries to identify the type of table and returns json\n \n Arguments:\n _table -- BeautifulSoup obj of the table\n \n Returns:\n [json] -- returns normal key:value dictionary\n \"\"\"\n _json = {}\n trs = _table.find_all(\"tr\")\n\n if (\"\" in str(trs[0])) and (\"\" in str(trs[0])):\n _json = extractHeaderTable(trs)\n else:\n _json = extractTable(trs)\n\n print(_json)\n return _json\n\n\ndef getBrowser():\n \"\"\"Create mechanize browser object\n \n Returns:\n [browser obj] -- returns browser obj\n \"\"\"\n cj = cookielib.CookieJar()\n br= mechanize.Browser()\n br.set_handle_equiv(True)\n br.set_handle_redirect(True)\n br.set_handle_referer(True)\n br.set_handle_robots(False)\n br.set_cookiejar(cj)\n br.set_header(\"User-Agent\",\" Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0\")\n return br\n\ndef solve_captcha(br,url):\n \"\"\"Fetchs the webpage,captcha image and tries to solve the captcha\n \n Arguments:\n br -- browser object\n url -- url\n \n Returns:\n [str] -- solved captcha, \"\" if couldnt solve it\n \"\"\"\n print(\"Fetching the page\")\n r=br.open(url)\n html=r.read()\n soup=BeautifulSoup(html,features=\"html5lib\")\n im = soup.find('img', id='captcha')\n image_response = br.open_novisit(im['src'])\n k = image_response.read()\n c_file = \"captcha.jpeg\"\n with open(c_file,\"wb\") as f:\n f.write(k)\n f.close()\n print(\"Solving captcha\")\n starttime = timeit.default_timer()\n captcha = resolve(c_file)\n stoptime = timeit.default_timer()\n captcha = captcha.lower().replace(\" \",\"\")\n\n return captcha\n\ndef fetchresponse(url,cin,save):\n \"\"\"tries to solve the captcha multiple times until we get a string \n and uses that to submit the cin number to the page\n \n Arguments:\n url -- url of the page\n cin -- cin number of the company\n save -- Save the response html page if True\n \n Returns:\n [str] -- Response HTML page\n \"\"\"\n br = getBrowser()\n captcha = None\n while not captcha:\n captcha = solve_captcha(br,url)\n if not captcha:\n print(\"couldnt parse captcha correctly trying again after 1 sec\")\n time.sleep(1)\n\n print(\"fetching\")\n br.select_form(nr=2)\n br.form['companyID'] = cin\n br.form['userEnteredCaptcha']=captcha\n resp = br.submit().read().decode(\"utf-8\")\n \n if save:\n savefile(resp,cin,\"html\")\n \n\n return resp\n\ndef checkdata(resp):\n \"\"\"checks if the response page from fetchresponse function contains the data\n \n Arguments:\n resp {[type]} -- HTML string\n \n Returns:\n [Bool] -- True if the data is present else false\n \"\"\"\n if \"Enter Characters shown below :\" in resp:\n #If this string is present in the page it means the captcha was wrong\n return False\n\n soup = BeautifulSoup(resp,\"html.parser\")\n _res = soup.find(\"table\",id=\"resultTab1\")\n #another check to see if the table actually containing the data is present\n return bool(_res)\n\ndef savefile(_data,_filename,_format=\"json\"):\n \"\"\"Saves the file to the disk in results folder\n \n Arguments:\n _data -- data that needs to be saved to file\n _filename -- filename without extension\n \n Keyword Arguments:\n _format -- Format/extension of the file (default: {\"json\"})\n \"\"\"\n try:\n if _format==\"json\":\n _data = json.dumps(_data,indent=4)\n\n path = os.path.join(\"results\",_filename+\".\"+_format)\n with open(path,\"w\") as f:\n f.write(_data)\n except Exception as e:\n print(e)\n print(\"***************FILE STARTS******************\")\n print(_data)\n print(\"***************FILE END******************\")\n\ndef getDetails(resp):\n \"\"\"function which fetchs the company data and director data tables \n and passes to the tableToJson function to get json\n \n Arguments:\n resp -- HTML string\n \n Returns:\n [json] -- {\n \"company\":{}\n \"directors:[{},{},{}]\n }\n \"\"\"\n soup = BeautifulSoup(resp,\"html.parser\")\n _json = {}\n\n companydata = \"resultTab1\"\n directors = \"resultTab6\"\n\n companytable = soup.find(\"table\",id=companydata)\n directorstable = soup.find(\"table\",id=directors)\n\n companyjson = tableToJson(companytable)\n if companyjson:\n _json[\"company\"] = companyjson\n\n directorsjson = tableToJson(directorstable)\n if directorsjson:\n _json[\"directors\"] = directorsjson\n \n return _json\n\ndef extractdata(url,cin,save=True):\n \"\"\"Kinda like the main function\n \n Arguments:\n url -- URL of the page\n cin -- cin number\n \n Keyword Arguments:\n save {bool} -- if True saves the response and json to results folder (default: {True})\n \n Returns:\n [json] -- json\n \"\"\"\n check = False\n while check==False:\n _resp = fetchresponse(url,cin,save=True)\n check = checkdata(_resp) \n if not check:\n print(\"No data found or wrong captcha trying again after 1 sec\")\n time.sleep(1)\n\n _json = getDetails(_resp)\n \n if save:\n savefile(_json,cin)\n \n return _json\n\ndef extractfile(url,path):\n \"\"\"Same as extractdata function but takes cin numbers from file path\n \n Arguments:\n path -- path to the text file\n \"\"\"\n with open(path) as f:\n _text = f.read()\n \n _text = _text.split()\n for num,cin in enumerate(_text):\n print(\"Extracting and saving data for index: {} ,cin: {}\\n\\n\".format(num,cin))\n _json = extractdata(url,cin)\n time.sleep(2)\n\n print(\"Done\")\n\n \nif __name__==\"__main__\":\n if not os.path.isdir(\"results\"):\n os.mkdir(\"results\")\n \n argparser = argparse.ArgumentParser()\n argparser.add_argument('cin',help = 'CIN Number')\n argparser.add_argument('-f','--file',help = 'path to txt file containing cins',action=\"store_true\")\n args = argparser.parse_args()\n cin = args.cin\n _file = args.file\n\n if _file:\n print(\"extracting data from file: {}\\n\\n\".format(cin))\n extractfile(url,cin)\n else:\n print(\"extracting data for cin: {}\\n\\n\".format(cin))\n extractdata(url,cin)\n\n","sub_path":"solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":8258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"401674397","text":"import numpy as np\nimport csv\nimport math as m\nimport matplotlib.pyplot as plt\nimport sys\n\ndef acc_point(log, pred, acc):\n\n predict = 0\n for i in range(len(pred)):\n if acc[i] == 1:\n if (1.0 / (1.0 + np.exp(-np.dot(np.transpose(log), pred[i])))) >= 0.5:\n predict += 1\n elif acc[i] == 0:\n if (1 - (1.0 / (1.0 + np.exp(-np.dot(np.transpose(log), pred[i]))))) >= 0.5:\n predict += 1\n return predict / len(pred)\n\nif __name__ == '__main__':\n\n # Read in file paths for training and testing files\n traincsv = str(sys.argv[1])\n testcsv = str(sys.argv[2])\n trainpath = \"./{}\".format(traincsv)\n testpath = \"./{}\".format(testcsv)\n\n # Read from training data and store usable data\n f = open(trainpath, \"r\")\n train = list(csv.reader(f, delimiter=\",\"))\n train = np.array(train[0:], dtype=np.float)\n # Remove extra info from data\n p_train = np.delete(train, 256, 1)\n p_train = p_train/255\n p_train = np.insert(p_train, 0, 1, axis=1)\n a_train = np.delete(train, np.s_[0:256], 1)\n\n # Read from testing data and store usable data\n f = open(testpath, \"r\")\n test = list(csv.reader(f, delimiter=\",\"))\n test = np.array(test[0:], dtype=np.float)\n # Remove extra info from data\n p_test = np.delete(test, 256, 1)\n p_test = p_test/255\n p_test = np.insert(p_test, 0, 1, axis=1)\n a_test = np.delete(test, np.s_[0:256], 1)\n\n # Set up to use logistic regression\n log = np.zeros(p_train.shape[1])\n eps = m.exp(-3)\n nu = 0.0001\n k = 0\n l = [0.001, 0.01, 1, 10, 100, 1000]\n batches = 100\n\n # Initiallize matrix to store plot points\n mx = [[], [], []]\n\n # While loop for gradient descent\n while True:\n # Begin gradient descent\n descent = np.zeros(p_train.shape[1])\n # Loop through every training item\n for i in range(p_train.shape[0]):\n a_predic = 1.0 / (1.0 + m.exp(-np.dot(np.transpose(log), p_train[i])))\n descent += ((a_predic - a_train[i]) * p_train[i])\n log -= (nu*(descent + (l[5]*log)))\n # Add each point to the matrix\n k += 1\n mx[0].append(k)\n mx[1].append(acc_point(log, p_train, a_train))\n mx[2].append(acc_point(log, p_test, a_test))\n\n if k == batches:\n break\n\n # Plot the graphs\n fig, ax = plt.subplots()\n\n ax.plot(mx[0], mx[1], label=\"Training\")\n ax.plot(mx[0], mx[2], label=\"Testing\")\n ax.legend(loc=\"lower right\")\n plt.show()","sub_path":"asm1/q2_1.py","file_name":"q2_1.py","file_ext":"py","file_size_in_byte":2878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"289204561","text":"##############################################################################\n# Parte do livro Introdução à Programação com Python\n# Autor: Nilo Ney Coutinho Menezes\n# Editora Novatec (c) 2010-2019\n# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8\n# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3\n# Terceira edição - Janeiro/2019 - ISBN 978-85-7522-718-3\n# Site: http://python.nilo.pro.br/\n#\n# Arquivo: listagem3\\capítulo 06\\06.06 - Programa 6.2 - Cálculo da média com notas digitadas.py\n# Descrição: Programa 6.2 - C��lculo da média com notas digitadas\n##############################################################################\n\n# Programa 6.2 - Cálculo da média com notas digitadas\nnotas = [0, 0, 0, 0, 0]\nsoma = 0\nx = 0\nwhile x < 5:\n notas[x] = float(input(f\"Nota {x}:\"))\n soma += notas[x]\n x += 1\nx = 0\nwhile x < 5:\n print(f\"Nota {x}: {notas[x]:6.2f}\")\n x += 1\nprint(f\"Média: {soma / x:5.2f}\")\n","sub_path":"capitulo 06/06.06 - Programa 6.2 - Calculo da media com notas digitadas.py","file_name":"06.06 - Programa 6.2 - Calculo da media com notas digitadas.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"361144463","text":"from reportlab.lib.enums import TA_JUSTIFY, TA_CENTER\nfrom reportlab.lib.pagesizes import A4\nfrom reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image\nfrom reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle\nfrom reportlab.lib.units import cm\nfrom reportlab.platypus.tables import Table, TableStyle\n\nfrom email import encoders\nfrom email.mime.base import MIMEBase\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nimport ssl\nimport smtplib\n\nfrom Crypto.Cipher import AES\n\nfrom module import kelas, bkd\nimport subprocess\nfrom os import path\n\nimport datetime, os\nimport qrcode\nfrom lib import wa, reply, numbers\n\nimport config\n\ndef auth(data):\n if kelas.getNpmandNameMahasiswa(data[0]) != None:\n ret = True\n else:\n ret = False\n return ret\n\ndef replymsg(driver, data):\n msgreply = \"\"\n if kelas.cekSiap():\n num = numbers.normalize(data[0]) \n try:\n if kelas.getNpmandNameMahasiswa(num):\n npm, nama = kelas.getNpmandNameMahasiswa(num)\n # print(npm, nama)\n tahunID = kelas.getTahunID()\n namaMhs, prodiMhs, singkatan, prodiID, email = getMahasiswaByNpm(npm)\n # print(namaMhs, prodiMhs, singkatan, prodiID, email)\n noSurat = insertMhs(npm, prodiID, tahunID)\n # print(noSurat)\n if checkApproveMhs(npm, prodiID, tahunID):\n data = f\"{npm};{singkatan};{noSurat}\"\n subprocess.Popen([\"python\", \"run.py\", os.path.basename(__file__).split('.')[0],data], cwd=config.cwd)\n wmsg = reply.getWaitingMessage(os.path.basename(__file__).split('.')[0])\n wmsg = wmsg.replace('#EMAIL#', email)\n wmsg = wmsg.replace('#BOTNAME#', config.bot_name)\n wa.typeAndSendMessage(driver, wmsg)\n else:\n msgreply = \"SKMK anda telah diajukan, silahkan hubungi Ka. Baak untuk minta approve SKMK yang telah diajukan\"\n else:\n msgreply = f\"Ikan teri pake saos.. anda siapa bos..\\nSebenarnya ada beberapa kemungkinan, pertama kamu bukan mahasiswa yg udh wisuda.. Mungkin no hp di SIAP salah kali... apalagi ya.. kyknya itu aja..\"\n \n except Exception as e:\n msgreply = f'Ikan hiu makan tomat.. ada error mat... {str(e)}'\n \n else:\n # pass\n wa.typeAndSendMessage(driver, 'Mohon maaf server Akademik SIAP sedang dalam kondisi DOWN, mohon untuk menginformasikan ke ADMIN dan tunggu')\n return msgreply\n\ndef run(data):\n data = data.split(';')\n npm = data[0]\n singkatan = data[1].lower()\n noSurat = data[2]\n \n makePage(npm, singkatan, noSurat)\n\ndef makePage(npm, prodi, noSurat):\n checkDir(f\"./skmk/skmk-{prodi}/\")\n \n fileName = f\"./skmk/skmk-{prodi}/{npm}.pdf\"\n \n year = datetime.datetime.now().year\n month = datetime.datetime.now().month\n day = datetime.datetime.now().day\n tahunID = kelas.getTahunID()\n semester, tahun = getTahunAjaran(tahunID)\n mhs = getMahasiswa(npm)\n \n doc = SimpleDocTemplate(fileName,\n pagesize=A4,\n rightMargin=2.5*cm,\n leftMargin=2.5*cm,\n topMargin=4*cm,\n bottomMargin=3*cm)\n contain=[]\n styles=getSampleStyleSheet()\n styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY, fontName='Times', fontSize=12, leading=14))\n styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER, fontName='Times'))\n \n ptext = 'SURAT KETERANGAN MASIH KULIAH'\n contain.append(Paragraph(ptext, styles[\"Center\"]))\n contain.append(Spacer(1, .4*cm))\n \n ptext = f'No : {noSurat}/SKMK/BAAK/{convertRomawi(month)}/{year}'\n contain.append(Paragraph(ptext, styles[\"Center\"]))\n contain.append(Spacer(1, 1.8*cm))\n \n ptext = 'Direktur Politeknik Pos Indonesia menerangkan dengan sesungguhnya bahwa,'\n contain.append(Paragraph(ptext, styles[\"Justify\"]))\n contain.append(Spacer(1, 1*cm))\n \n styleWrap = styles[\"BodyText\"]\n styleWrap.alignment = TA_JUSTIFY\n styleWrap.fontName = 'Times'\n styleWrap.fontSize = 12\n styleWrap.leading = 14\n \n data = [['Nama Mahasiswa', ':', mhs[0]],\n ['Tempat / Tanggal Lahir', ':', f\"{mhs[1]}, {convertYmd(mhs[2])}\"],\n ['Agama', ':', mhs[3]],\n ['Alamat Mahasiswa', ':', Paragraph(f'{mhs[4]}, Rt. {mhs[5] if mhs[5] != \"NULL\" else \"-\"}, Rw. {mhs[6] if mhs[6] != \"NULL\" else \"-\"}, {mhs[7]}, {mhs[8]} - {mhs[9]}', styleWrap)],\n ['Program Studi', ':', mhs[10]],\n ['NPM', ':', npm],\n ['Nama Orang Tua', ':', mhs[11]],\n ['Pekerjaan Orang Tua', ':', mhs[12].strip()],\n ['Alamat Orang Tua', ':', Paragraph(f'{mhs[13]}, Rt. {mhs[14] if mhs[14] != \"NULL\" else \"-\"}, Rw. {mhs[15] if mhs[15] != \"NULL\" else \"-\"}', styleWrap)],\n ['Kota, Kode Pos', ':', f'{mhs[16]}, {mhs[18]}'],\n ]\n table = Table(data, [5*cm, .5*cm, 10.5*cm], [.6*cm, .6*cm, .6*cm, 1.1*cm, .6*cm, .6*cm, .6*cm, .6*cm, 1.1*cm, .6*cm])\n table.setStyle(TableStyle([\n ('FONT',(0,0),(-1,-1),'Times-Roman', 12),\n ('VALIGN',(0,0),(-1,-1),'TOP'), \n ]))\n contain.append(table)\n contain.append(Spacer(1, .7*cm))\n \n ptext = f'Adalah benar terdaftar dan aktif sebagai Mahasiswa Politeknik Pos Indonesia Semester {semester} Tahun Akademik {tahun}'\n contain.append(Paragraph(ptext, styles[\"Justify\"]))\n contain.append(Spacer(1, .8*cm))\n \n ptext = 'Demikian surat keterangan ini dibuat untuk dipergunakan seperlunya.'\n contain.append(Paragraph(ptext, styles[\"Justify\"]))\n contain.append(Spacer(1, 1*cm))\n \n nik, nama = getKaBaak()\n \n link = makeLinkVerifiy(getKodeDosen(nik), npm)\n pathTTDKaBaak = makeQrcodeLinkVerifySign(link, npm, prodi)\n \n data = [\n ['', f'Bandung, {day} {convertMonth(month)} {year}'],\n ['', 'Direktur.'],\n ['', 'Ka. BAAK'],\n ['', Image(pathTTDKaBaak, 3.8 * cm, 3.8 * cm)],\n ['', nama],\n ]\n\n table = Table(data, [8*cm, 8*cm], [.6*cm, .6*cm, .6*cm, 4*cm, .6*cm])\n table.setStyle(TableStyle([\n ('FONT',(0,0),(-1,-1),'Times-Roman', 12),\n # ('INNERGRID', (0,0), (-1,-1), 1, colors.black),\n # ('BOX', (0,0), (-1,-1), 1, colors.black),\n ('VALIGN',(0,0),(-1,-1),'MIDDLE'), \n ('ALIGN', (0,0), (-1,-1), 'CENTER'),\n ]))\n contain.append(table)\n\n doc.build(contain, onFirstPage=headerFooter, onLaterPages=headerFooter)\n \n sendEmail(mhs[19], f\"{npm}.pdf\", f\"./skmk/skmk-{prodi}/\", mhs[0])\n\ndef headerFooter(canvas, doc):\n canvas.saveState()\n \n header = Image(f'./skmk/header.png', 19*cm, 2.5*cm)\n w, h = header.wrap(doc.width, 2.5*cm)\n header.drawOn(canvas, 1*cm, doc.height + 4*cm)\n\n footer = Image(f'./skmk/footer.png', 19*cm, 1.8*cm)\n w, h = footer.wrap(doc.width, 2.5*cm)\n footer.drawOn(canvas, 1*cm, h - 1.5*cm)\n\n canvas.restoreState()\n\ndef getKaBaak():\n db = kelas.dbConnectSiap()\n sql = f\"SELECT NIPY, Nama FROM simpati.simak_mst_pejabat WHERE JenisJabatanID='11'\"\n with db:\n cur = db.cursor()\n cur.execute(sql)\n row = cur.fetchone()\n if row is not None:\n return [row[0], row[1]]\n \n return None\n\ndef getMahasiswa(npm):\n db = kelas.dbConnectSiap()\n sql = f\"SELECT smm.Nama, smm.TempatLahir, smm.TanggalLahir, sra.Nama, smm.Alamat, smm.RT, smm.RW, smm.Kota, smm.Propinsi, smm.KodePos, smp.Nama, smm.NamaAyah, srpo.Nama, smm.AlamatOrtu, smm.RTOrtu, smm.RWOrtu, smm.KotaOrtu, smm.PropinsiOrtu, smm.KodePosOrtu, smm.Email FROM simak_mst_mahasiswa as smm, simak_ref_agama as sra, simak_mst_prodi as smp, simak_ref_pekerjaan_ortu as srpo WHERE sra.Agama=smm.Agama AND smp.ProdiID=smm.ProdiID AND srpo.Pekerjaan=smm.PekerjaanAyah AND smm.MhswID = '{npm}'\"\n with db:\n cur = db.cursor()\n cur.execute(sql)\n row = cur.fetchone()\n if row is not None:\n return row\n \n return None\n\ndef getMahasiswaByNpm(npm):\n db = kelas.dbConnectSiap()\n sql = f\"select smm.Nama, smp.Nama, smp.Singkatan, smm.ProdiID, smm.Email from simak_mst_mahasiswa as smm, simak_mst_prodi as smp where smm.ProdiID=smp.ProdiID and smm.MhswID = '{npm}'\"\n with db:\n cur = db.cursor()\n cur.execute(sql)\n row = cur.fetchone()\n if row is not None:\n return [row[0], row[1], row[2], row[3], row[4]]\n return False\n\ndef getKodeDosen(nik):\n db = kelas.dbConnectSiap()\n sql = f'select Login from simak_mst_dosen where NIPY=\"{nik}\"'\n with db:\n cur = db.cursor()\n cur.execute(sql)\n row = cur.fetchone()\n if row is not None:\n return row[0]\n return None\n\ndef getNamaDosen(kodeDosen):\n db = kelas.dbConnectSiap()\n sql = f\"select Nama, Gelar from simak_mst_dosen where Login = '{kodeDosen}'\"\n with db:\n cur = db.cursor()\n cur.execute(sql)\n row = cur.fetchone()\n if row is not None:\n return f\"{row[0].title()}, {row[1]}\"\n return False\n\ndef checkMhs(npm, prodi, tahunID):\n db=kelas.dbConnect()\n sql=f\"select id from skmk_data where npm = {npm} and prodiID = {prodi} and tahunID like '{tahunID[:4]}%'\"\n with db:\n cur=db.cursor()\n cur.execute(sql)\n row=cur.fetchone()\n if row:\n return row[0]\n return False\n\n\ndef insertMhs(npm, prodi, tahunID):\n db=kelas.dbConnect()\n if not checkMhs(npm, prodi, tahunID):\n sql = f\"INSERT INTO skmk_data (npm, prodiID, tahunID) VALUE ('{npm}', '{prodi}', '{tahunID}')\"\n with db:\n cur=db.cursor()\n cur.execute(sql)\n\n return checkMhs(npm, prodi, tahunID)\n \ndef checkApproveMhs(npm, prodi, tahunID):\n db=kelas.dbConnect()\n sql=f\"select * from skmk_data where npm = {npm} and prodiID = {prodi} and tahunID like '{tahunID[:4]}%' and approve is not null\"\n with db:\n cur=db.cursor()\n cur.execute(sql)\n row=cur.fetchone()\n if row:\n return True\n return False\n\ndef getTahunAjaran(tahunID):\n jenjang = tahunID[-1]\n tahun = f\"{tahunID[:4]}/{int(tahunID[:4])+1}\"\n \n semesters = {\n \"1\": \"Ganjil\",\n \"2\": \"Genap\",\n \"3\": \"Genap\"\n }\n \n semester = semesters.get(jenjang, \"-\")\n return [semester, tahun]\n\ndef convertYmd(ymd):\n data = ymd.strftime('%d-%m-%Y').split(\"-\")\n return f\"{data[0]} {convertMonth(data[1])} {data[2]}\"\n\ndef convertMonth(month):\n # print(month)\n months = {\n '01': 'Januari',\n '02': 'Februari',\n '03': 'Maret',\n '04': 'April',\n '05': 'Mei',\n '06': 'Juni',\n '07': 'Juli',\n '08': 'Agustus',\n '09': 'September',\n '10': 'Oktober',\n '11': 'November',\n '12': 'Desember',\n }\n return months.get(str(month), \"-\")\n\ndef convertRomawi(month):\n # print(month)\n months = {\n '1': 'I',\n '2': 'II',\n '3': 'III',\n '4': 'IV',\n '5': 'V',\n '6': 'VI',\n '7': 'VII',\n '8': 'VIII',\n '9': 'IX',\n '10': 'X',\n '11': 'XI',\n '12': 'XII',\n }\n return months.get(str(month), \"-\")\n\ndef makeLinkVerifiy(kodeDosen, npm):\n datenow = datetime.datetime.date(datetime.datetime.now()).strftime('%d-%m-%Y')\n timenow = datetime.datetime.now().time().strftime('%H:%M:%S')\n module_name=\"skmk\"\n data = f'{module_name};{datenow};{timenow};{kodeDosen};{npm};'\n makeit64 = f'{data}{bkd.randomString(64 - len(data))}'\n obj = AES.new(config.key.encode(\"utf8\"), AES.MODE_CBC, config.iv.encode('utf8'))\n cp = obj.encrypt(makeit64.encode(\"utf8\"))\n passcode = cp.hex()\n space = '%20'\n link = f'https://api.whatsapp.com/send?phone={config.nomor_iteung}&text=iteung{space}tanda{space}tangan{space}{passcode}'\n return link\n\ndef makeQrcodeLinkVerifySign(link, npm, prodi):\n checkDir(f\"./skmk/qrcode-{prodi}/\")\n img = qrcode.make(link)\n filepath = f'./skmk/qrcode-{prodi}/qrcode-{npm}.png'\n img.save(filepath)\n return filepath\n\ndef verifyDigitalSign(resultpasscode):\n data = resultpasscode.split(';')\n tanggal = data[1]\n waktu = data[2]\n namaMhs, prodiMhs, singkatan, prodiID, email = getMahasiswaByNpm(data[4])\n namaDosen = getNamaDosen(data[3])\n \n msgreply = f'Surat Keterangan Masih Kuliah {namaMhs} dari prodi {prodiMhs} telah ditandatangani oleh {namaDosen} sebagai Ka. BAAK Politeknik Pos Indonesia, penerbitan tanda tangan pada {tanggal} jam {waktu}.'\n return msgreply\n\ndef checkDir(dir_path):\n if path.exists(dir_path):\n pass\n else:\n os.mkdir(dir_path)\n\ndef checkFile(file_path):\n return path.exists(file_path)\n\ndef sendEmail(email, fileName, path, mhs):\n try:\n subject = f\"SKMK {mhs}\"\n body = f\"Jadi ini skmk kamu {mhs}\"\n\n sender_email = config.email_iteung\n receiver_email = email\n # print(email)\n # receiver_email = 'divakrishnam@yahoo.com'\n password = config.pass_iteung\n\n message = MIMEMultipart()\n message[\"From\"] = f'ITeung <{config.email_iteung}>'\n message[\"To\"] = receiver_email\n message[\"Subject\"] = subject\n message[\"Bcc\"] = receiver_email\n\n message.attach(MIMEText(body, \"plain\"))\n\n with open(path+fileName, \"rb\") as attachment:\n part = MIMEBase(\"application\", \"octet-stream\")\n part.set_payload(attachment.read())\n\n encoders.encode_base64(part)\n\n part.add_header(\n \"Content-Disposition\",\n \"attachment; filename= %s \" % fileName,\n )\n\n message.attach(part)\n \n text = message.as_string()\n\n context = ssl.create_default_context()\n with smtplib.SMTP_SSL(\"smtp.gmail.com\", 465, context=context) as server:\n server.login(sender_email, password)\n server.sendmail(sender_email, receiver_email, text)\n\n print(f'File {fileName} berhasil dikirim ke {email}')\n except FileNotFoundError:\n print(\"File tidak ditemukan\")\n except Exception as e: \n print(str(e))","sub_path":"module/skmk.py","file_name":"skmk.py","file_ext":"py","file_size_in_byte":14327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"81592154","text":"#!/usr/bin/env python3\n\n\nimport numpy as np\nimport pandas as pd\nimport pymc3 as pm\n\nimport psycopg2\n\n\n# mix of large stations and PATH data\nexclude = ['R010', 'R011', 'R012', 'R020', 'R021', 'R022', 'R031', 'R032',\n 'R033', 'R045', 'R046', 'R047', 'R048', 'R072', 'R195', 'R293',\n 'R328', 'R469', 'R535', 'R536', 'R541', 'R545', 'R547', 'R548',\n 'R549', 'R550', 'R552']\n\n\ndef main(date_start='2016-11-15', date_stop='2017-02-15', shock='2017-01-01',\n name_of_event='second_avenue_opens',\n units_changed=['R570', 'R571', 'R572']):\n conn = create_connection()\n units = get_unit_list(conn)\n query = build_large_query(units, date_start, date_stop)\n data = resample(pull_data(query, conn))\n saved_traces = prediction(data)\n filtered = filter_traces(saved_traces, data.index.get_loc(shock))\n create_and_save_dataframe(filtered, units_changed, name_of_event)\n\n\ndef create_connection():\n user = 'mikemoran'\n dbname = 'fullstations'\n return psycopg2.connect(database=dbname, user=user)\n\n\ndef get_unit_list(conn):\n query = '''\n select distinct unit from details\n order by unit asc;\n '''\n df = pd.read_sql(query, conn)\n units = df.unit.unique().tolist()\n return [u for u in units if u not in exclude] # removes major stations\n\n\ndef build_large_query(units, start, stop, include_exit=True):\n ''' build out a large SQL query that pulls all units (stations)\n entrance and potentially exit data\n '''\n select = '{}.enter {}_enter, {}.exit {}_exit'\n if not include_exit:\n select = '{}.enter {}'\n join = 'full outer join {} on r001.date_time = {}.date_time'\n select_parts = ',\\n'.join(select.format(u, u, u, u) for u in units)\n start_station = units[0]\n join_parts = '\\n'.join(join.format(u, u) for u in units[1:])\n query = f'''select {start_station}.date_time, {select_parts}\n from {start_station} {join_parts}\n where {start_station}.date_time between '{start}' and '{stop}'\n order by date_time asc;\n '''\n return query\n\n\ndef pull_data(query, conn):\n df = (pd.read_sql(query, conn, parse_dates=['date_time'])\n .set_index('date_time'))\n try:\n df.index = df.index.tz_convert('EST')\n except TypeError:\n df.index = df.index.tz_localize('EST')\n df.index = pd.DatetimeIndex(df.index)\n df.columns = df.columns.str.upper()\n return df\n\n\ndef resample(dataframe):\n df = dataframe.resample('1D', closed='right').sum()\n df['date'] = df.index.date\n df.set_index('date', inplace=True)\n df.index = pd.DatetimeIndex(df.index)\n return df.iloc[1:] # to remove the partial starting day\n\n\ndef prediction(data):\n saved_traces = {}\n for station in data.columns:\n df = data[station].fillna(0)\n trace = get_model_results(df, sample=10000, tune=5000)\n saved_traces[station] = trace[5000:]\n return saved_traces\n\n\ndef get_model_results(data, sample=8000, tune=4000):\n with pm.Model() as model:\n mu = data.mean()\n lambda_1 = pm.Exponential('riders_before', 1 / mu)\n lambda_2 = pm.Exponential('riders_after', 1 / mu)\n tau = pm.DiscreteUniform('day_of_shock', lower=0, upper=data.shape[0] - 1)\n idx = np.arange(data.shape[0])\n lambda_ = pm.math.switch(tau >= idx, lambda_1, lambda_2)\n observation = pm.Poisson('observed', lambda_, observed=data.values)\n step = pm.Metropolis()\n trace = pm.sample(sample, tune=tune, step=step)\n return trace\n\n\ndef filter_traces(traces, shock):\n filtered = {}\n for unit, trace in traces.items():\n before = trace.get_values('riders_before').mean()\n after = trace.get_values('riders_after').mean()\n date = trace.get_values('day_of_shock').mean()\n if ((shock - 7 < date < shock + 7) and # day needs to be near actual\n (np.abs(after - before) > 1000)): # larger changes only\n filtered[unit] = after - before\n return filtered\n\n\ndef create_and_save_dataframe(data, changed, name):\n df = pd.DataFrame(data, index=changed).transpose()\n # handle \"forward\" change\n # below fails... check notebook\n changed_riders = df.loc[changed].iloc[:, 0].sum() / len(changed)\n df = df / changed_riders\n for unit in df.index:\n if unit not in df.columns:\n df[unit] = np.NaN\n df = df[sorted(df.columns)]\n df.loc[changed] = (1 - df[changed].transpose()) / len(changed)\n df.loc[changed, changed] = 0\n df.to_csv(f'{name}.csv')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"run_single.py","file_name":"run_single.py","file_ext":"py","file_size_in_byte":4569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"313919164","text":"# time O(k*n), k=len(words[0]), n = len(s), sliding window\n# start from i (0 word_dict[blocks[right]]:\n window[blocks[left]] -= 1\n if window[blocks[left]] < word_dict[blocks[left]]:\n cnt -= 1\n left += 1\n if cnt == n:\n res.append(i+left*k) # mistake: res.append(left*k)\n window[blocks[left]] -= 1\n cnt -= 1\n left += 1\n right += 1\n\n\n\n\nfrom collections import defaultdict\nfrom copy import copy\n# time O(n*m*k), space O(m*k), n=len(S), m=len(L), k=len(L[0])\nclass Solution1:\n # @param S, a string\n # @param L, a list of string\n # @return a list of integer\n def findSubstring(self, S, L): \n if not S or not L:\n return []\n \n n = len(S)\n m = len(L) # number of words\n k = len(L[0]) # word length\n ans = []\n \n _dict = defaultdict(int)\n for word in L:\n _dict[word] += 1\n \n for i in range(n - k*m + 1):\n temp_dict = copy(_dict)\n for j in range(m):\n temp_word = S[i+j*k: i+j*k+k]\n temp_dict[temp_word] -= 1\n if temp_dict[temp_word] < 0:\n break\n else:\n ans.append(i)\n \n return ans\n\n\n\"\"\"\n\nYou are given a string, s, and a list of words, words, \nthat are all of the same length. \nFind all starting indices of substring(s) in s \nthat is a concatenation of each word in words exactly once \nand without any intervening characters.\n\nExample 1:\n\nInput:\n s = \"barfoothefoobarman\",\n words = [\"foo\",\"bar\"]\nOutput: [0,9]\nExplanation: Substrings starting at index 0 and 9 are \"barfoor\" and \"foobar\" respectively.\nThe output order does not matter, returning [9,0] is fine too.\n\n\"\"\"\n\n","sub_path":"0030. Substring with Concatenation of All Words.py","file_name":"0030. Substring with Concatenation of All Words.py","file_ext":"py","file_size_in_byte":3584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"8267822","text":"import Regras_import_Entidades as Regra\r\nimport Obj_Entidades as Oe\r\nimport Objetos_Virtuais as Ov\r\n\r\n\r\nclass BuildingRulesDigitalPoint(object):\r\n def __init__(self, ponto: Ov.PontoDigital, obj_include: Ov.Include, lista_pds: list):\r\n self._ponto = ponto\r\n self._include = obj_include\r\n self._pasta = obj_include.path\r\n self.__lista_pds = lista_pds\r\n\r\n self.regra_define_vinculo_com_ied()\r\n self.regra_import_entrada_fisica()\r\n\r\n def regra_define_vinculo_com_ied(self):\r\n item_encontrado = None\r\n ied_encontrado = None\r\n\r\n for ponto_pds in self.__lista_pds:\r\n if self._ponto.id == ponto_pds.ID:\r\n item_encontrado = ponto_pds\r\n\r\n if item_encontrado:\r\n for _ied in self._include.ieds:\r\n if item_encontrado == _ied.tac:\r\n ied_encontrado = _ied\r\n\r\n self._ponto.vinculo = ied_encontrado\r\n\r\n def regra_import_entrada_fisica(self):\r\n __pdf = Regra.ImportarEntidade(self._pasta, 'pdf', Oe.PDF).lista\r\n\r\n for item in __pdf:\r\n if (__pdf.PNT == self._ponto.id) and (__pdf.TPPNT == 'PDS'):\r\n self._ponto.endereco_fisico = item.ID\r\n\r\n def regra_define_severidade(self):\r\n pass\r\n\r\n\r\n","sub_path":"Regra_cria_ponto_digital.py","file_name":"Regra_cria_ponto_digital.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"640788599","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n@date: 2020/11/21 下午2:37\n@file: resnet_recognizer.py\n@author: zj\n@description: \n\"\"\"\nfrom abc import ABC\n\nimport torch.nn as nn\nfrom torch.nn.modules.module import T\nfrom torchvision.models.resnet import resnet18, resnet50, resnext50_32x4d\nfrom torchvision.models.utils import load_state_dict_from_url\n\nfrom zcls.config.key_word import KEY_OUTPUT\nfrom .. import registry\nfrom ..backbones.basicblock import BasicBlock\nfrom ..backbones.bottleneck import Bottleneck\nfrom ..backbones.sknet_block import SKNetBlock\nfrom ..backbones.resnest_block import ResNeStBlock\nfrom ..backbones.resnet_backbone import ResNetBackbone\nfrom ..backbones.resnet_d_backbone import ResNetDBackbone\nfrom ..heads.resnet_head import ResNetHead\nfrom ..heads.resnet_d_head import ResNetDHead\nfrom ..norm_helper import get_norm, freezing_bn\nfrom ..act_helper import get_act\nfrom ..conv_helper import get_conv\n\narch_settings = {\n # name: (Backbone, Head, Block, Layer_planes, groups, width_per_group)\n 'resnet18': (ResNetBackbone, ResNetHead, BasicBlock, (2, 2, 2, 2), 1, 64),\n 'resnet34': (ResNetBackbone, ResNetHead, BasicBlock, (3, 4, 6, 3), 1, 64),\n 'resnet50': (ResNetBackbone, ResNetHead, Bottleneck, (3, 4, 6, 3), 1, 64),\n 'resnet101': (ResNetBackbone, ResNetHead, Bottleneck, (3, 4, 23, 3), 1, 64),\n 'resnet152': (ResNetBackbone, ResNetHead, Bottleneck, (3, 8, 36, 3), 1, 64),\n 'resnext50_32x4d': (ResNetBackbone, ResNetHead, Bottleneck, (3, 4, 6, 3), 32, 4),\n 'resnext101_32x8d': (ResNetBackbone, ResNetHead, Bottleneck, (3, 4, 23, 3), 32, 8),\n # name: (Backbone, Head, Block, Layer_planes, groups, width_per_group)\n 'resnetd18': (ResNetDBackbone, ResNetDHead, BasicBlock, (2, 2, 2, 2), 1, 64),\n 'resnetd34': (ResNetDBackbone, ResNetDHead, BasicBlock, (3, 4, 6, 3), 1, 64),\n 'resnetd50': (ResNetDBackbone, ResNetDHead, Bottleneck, (3, 4, 6, 3), 1, 64),\n 'resnetd101': (ResNetDBackbone, ResNetDHead, Bottleneck, (3, 4, 23, 3), 1, 64),\n 'resnetd152': (ResNetDBackbone, ResNetDHead, Bottleneck, (3, 8, 36, 3), 1, 64),\n 'resnextd50_32x4d': (ResNetDBackbone, ResNetDHead, Bottleneck, (3, 4, 6, 3), 32, 4),\n 'resnedxdt101_32x8d': (ResNetDBackbone, ResNetDHead, Bottleneck, (3, 4, 23, 3), 32, 8),\n # name: (Backbone, Head, Block, Layer_planes, groups, width_per_group)\n 'sknet50': (ResNetDBackbone, ResNetDHead, SKNetBlock, (3, 4, 6, 3), 1, 64),\n # name: (Backbone, Head, Block, Layer_planes, radix, groups, width_per_group)\n 'resnest50_1s1x64d': (ResNetDBackbone, ResNetDHead, ResNeStBlock, (3, 4, 6, 3), 1, 1, 64),\n 'resnest50_2s1x64d': (ResNetDBackbone, ResNetDHead, ResNeStBlock, (3, 4, 6, 3), 2, 1, 64),\n 'resnest50_4s1x64d': (ResNetDBackbone, ResNetDHead, ResNeStBlock, (3, 4, 6, 3), 4, 1, 64),\n 'resnest50_2s2x40d': (ResNetDBackbone, ResNetDHead, ResNeStBlock, (3, 4, 6, 3), 2, 2, 40),\n 'resnest50_2s2x40d_fast': (ResNetDBackbone, ResNetDHead, ResNeStBlock, (3, 4, 6, 3), 2, 2, 40)\n}\n\n\nclass ResNetRecognizer(nn.Module, ABC):\n\n def __init__(self,\n ##################### for RECOGNIZER\n # zcls预训练模型\n pretrained=\"\",\n # 预训练模型类别数\n pretrained_num_classes=1000,\n # 固定BN\n fix_bn=False,\n # 仅训练第一层BN\n partial_bn=False,\n ##################### for HEAD\n # 随机失活概率\n dropout_rate=0.,\n # 输出类别数\n num_classes=1000,\n ##################### for BACKBONE\n # 架构\n arch='resnet18',\n # 输入通道数\n in_planes=3,\n # 基础通道数,\n base_planes=64,\n # 每一层通道数\n layer_planes=(64, 128, 256, 512),\n # 是否执行空间下采样\n down_samples=(0, 1, 1, 1),\n # 是否使用注意力模块\n with_attentions=(0, 0, 0, 0),\n # 衰减率\n reduction=16,\n # 注意力模块类型\n attention_type='GlobalContextBlock2D',\n # 卷积层类型\n conv_layer=None,\n # 归一化层类型\n norm_layer=None,\n # 激活层类型\n act_layer=None,\n # 零初始化残差连接\n zero_init_residual=False,\n # 是否使用AvgPool进行下采样\n use_avg=False,\n # 在3x3之前执行下采样操作\n fast_avg=False\n ):\n super(ResNetRecognizer, self).__init__()\n assert arch in arch_settings.keys()\n self.fix_bn = fix_bn\n self.partial_bn = partial_bn\n\n radix = 1\n if 'resnest' in arch:\n backbone_layer, head_layer, block_layer, layer_blocks, radix, groups, width_per_group = arch_settings[arch]\n if 'fast' in arch:\n fast_avg = True\n else:\n backbone_layer, head_layer, block_layer, layer_blocks, groups, width_per_group = arch_settings[arch]\n\n self.backbone = backbone_layer(\n in_planes=in_planes,\n base_planes=base_planes,\n layer_planes=layer_planes,\n layer_blocks=layer_blocks,\n down_samples=down_samples,\n groups=groups,\n width_per_group=width_per_group,\n with_attentions=with_attentions,\n reduction=reduction,\n attention_type=attention_type,\n block_layer=block_layer,\n conv_layer=conv_layer,\n norm_layer=norm_layer,\n act_layer=act_layer,\n zero_init_residual=zero_init_residual,\n radix=radix,\n use_avg=use_avg,\n fast_avg=fast_avg\n )\n feature_dims = block_layer.expansion * layer_planes[-1]\n self.head = head_layer(\n feature_dims=feature_dims,\n num_classes=pretrained_num_classes,\n dropout_rate=dropout_rate,\n )\n\n self.init_weights(pretrained,\n pretrained_num_classes,\n num_classes)\n\n def init_weights(self,\n pretrained,\n pretrained_num_classes,\n num_classes\n ):\n if pretrained != \"\":\n state_dict = load_state_dict_from_url(pretrained, progress=True)\n self.backbone.load_state_dict(state_dict, strict=False)\n self.head.load_state_dict(state_dict, strict=False)\n if num_classes != pretrained_num_classes:\n fc = self.head.fc\n fc_features = fc.in_features\n self.head.fc = nn.Linear(fc_features, num_classes)\n self.head.init_weights()\n\n def train(self, mode: bool = True) -> T:\n super(ResNetRecognizer, self).train(mode=mode)\n\n if mode and (self.partial_bn or self.fix_bn):\n freezing_bn(self, partial_bn=self.partial_bn)\n\n return self\n\n def forward(self, x):\n x = self.backbone(x)\n x = self.head(x)\n\n return {KEY_OUTPUT: x}\n\n\nclass TorchvisionResNet(nn.Module, ABC):\n\n def __init__(self,\n arch=\"resnet18\",\n num_classes=1000,\n torchvision_pretrained=False,\n pretrained_num_classes=1000,\n fix_bn=False,\n partial_bn=False,\n zero_init_residual=False):\n super(TorchvisionResNet, self).__init__()\n\n self.num_classes = num_classes\n self.fix_bn = fix_bn\n self.partial_bn = partial_bn\n\n if arch == 'resnet18':\n self.model = resnet18(pretrained=torchvision_pretrained, num_classes=pretrained_num_classes,\n zero_init_residual=zero_init_residual)\n elif arch == 'resnet50':\n self.model = resnet50(pretrained=torchvision_pretrained, num_classes=pretrained_num_classes,\n zero_init_residual=zero_init_residual)\n elif arch == 'resnext50_32x4d':\n self.model = resnext50_32x4d(pretrained=torchvision_pretrained, num_classes=pretrained_num_classes,\n zero_init_residual=zero_init_residual)\n else:\n raise ValueError('no such value')\n\n self.init_weights(num_classes, pretrained_num_classes)\n\n def init_weights(self, num_classes, pretrained_num_classes):\n if num_classes != pretrained_num_classes:\n fc = self.model.fc\n fc_features = fc.in_features\n self.model.fc = nn.Linear(fc_features, num_classes)\n\n nn.init.normal_(self.model.fc.weight, 0, 0.01)\n nn.init.zeros_(self.model.fc.bias)\n\n def train(self, mode: bool = True) -> T:\n super(TorchvisionResNet, self).train(mode=mode)\n\n if mode and (self.partial_bn or self.fix_bn):\n freezing_bn(self, partial_bn=self.partial_bn)\n\n return self\n\n def forward(self, x):\n x = self.model(x)\n\n return {KEY_OUTPUT: x}\n\n\n@registry.RECOGNIZER.register('ResNet')\ndef build_resnet(cfg):\n # for recognizer\n recognizer_name = cfg.MODEL.RECOGNIZER.NAME\n torchvision_pretrained = cfg.MODEL.RECOGNIZER.TORCHVISION_PRETRAINED\n pretrained = cfg.MODEL.RECOGNIZER.PRETRAINED\n pretrained_num_classes = cfg.MODEL.RECOGNIZER.PRETRAINED_NUM_CLASSES\n fix_bn = cfg.MODEL.NORM.FIX_BN\n partial_bn = cfg.MODEL.NORM.PARTIAL_BN\n # for backbone\n arch = cfg.MODEL.BACKBONE.ARCH\n in_planes = cfg.MODEL.BACKBONE.IN_PLANES\n base_planes = cfg.MODEL.BACKBONE.BASE_PLANES\n layer_planes = cfg.MODEL.BACKBONE.LAYER_PLANES\n down_samples = cfg.MODEL.BACKBONE.DOWN_SAMPLES\n conv_layer = get_conv(cfg)\n norm_layer = get_norm(cfg)\n act_layer = get_act(cfg)\n zero_init_residual = cfg.MODEL.RECOGNIZER.ZERO_INIT_RESIDUAL\n use_avg = cfg.MODEL.BACKBONE.USE_AVG\n fast_avg = cfg.MODEL.BACKBONE.FAST_AVG\n # for head\n dropout_rate = cfg.MODEL.HEAD.DROPOUT\n num_classes = cfg.MODEL.HEAD.NUM_CLASSES\n # for attention\n with_attentions = cfg.MODEL.ATTENTION.WITH_ATTENTIONS\n reduction = cfg.MODEL.ATTENTION.REDUCTION\n attention_type = cfg.MODEL.ATTENTION.ATTENTION_TYPE\n\n if recognizer_name == 'TorchvisionResNet':\n return TorchvisionResNet(\n arch=arch,\n num_classes=num_classes,\n torchvision_pretrained=torchvision_pretrained,\n pretrained_num_classes=pretrained_num_classes,\n fix_bn=fix_bn,\n partial_bn=partial_bn,\n zero_init_residual=zero_init_residual\n )\n elif recognizer_name == 'ZClsResNet':\n return ResNetRecognizer(\n # for RECOGNIZER\n pretrained=pretrained,\n pretrained_num_classes=pretrained_num_classes,\n fix_bn=fix_bn,\n partial_bn=partial_bn,\n # for HEAD\n dropout_rate=dropout_rate,\n num_classes=num_classes,\n # for BACKBONE\n arch=arch,\n in_planes=in_planes,\n base_planes=base_planes,\n layer_planes=layer_planes,\n down_samples=down_samples,\n with_attentions=with_attentions,\n reduction=reduction,\n attention_type=attention_type,\n conv_layer=conv_layer,\n norm_layer=norm_layer,\n act_layer=act_layer,\n zero_init_residual=zero_init_residual,\n use_avg=use_avg,\n fast_avg=fast_avg\n )\n else:\n raise ValueError(f'{recognizer_name} does not exist')\n","sub_path":"zcls/model/recognizers/resnet_recognizer.py","file_name":"resnet_recognizer.py","file_ext":"py","file_size_in_byte":11775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"383517877","text":"from testInput import input\ndef toggle(val):\n if val == True:\n return False\n else:\n return True\nfor _ in range(int(input())):\n n = int(input())\n arr = []\n for i in range(n):\n arr.append(list(map(int, input().split())))\n mark = [False] * n\n check = True\n for i in range(n):\n if arr[0][i] == (i + 1):\n mark[i] = True\n else:\n check = False\n if check == True:\n print(0)\n else:\n flag = False\n count = 0\n for i in range(n - 1, 0, -1):\n if flag:\n mark[i] = toggle(mark[i])\n\n if mark[i] == True:\n continue\n else:\n mark[i] = True\n flag = toggle(flag)\n count += 1\n print(count )\n","sub_path":"Codechef/September_long_challenge/adamat.py","file_name":"adamat.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"354123011","text":"import requests, time\nfrom lxml import html\n\nstart_time = time.time() # 初始时间戳\nnow = time.strftime(\"%Y%m%d\", time.localtime()) # 当前日期戳\n\n# ========================输入区开始========================\nID = \"1788862154\" # 微博用户ID\n\nurl_prefix = 'http://sinacn.weibodangan.com//user/'\nfull_url = url_prefix + ID\n\n# ========================执行区开始========================\npage = requests.get(full_url)\ntree = html.fromstring(page.text)\nnickname = tree.xpath('//h3[@class=\"username\"]/text()')[0]\ndata = tree.xpath('//td/text()')\nfriends = data[0]\nfans = data[1].replace(\" \", \"\")\nposts = data[2]\nlocation = tree.xpath(\"//div[@class='info'][1]/text()\")[0]\ndescription = tree.xpath(\"//div[@class='info'][2]/text()\")[0]\nalldays = tree.xpath(\"//div[@class='hidden-xs hidden-sm']/p[1]/text()\")[0]\ndays = alldays[7:]\nstarted = tree.xpath(\"//span[@id='register_time']/text()\")[0]\ninfo = (nickname, friends, fans, posts, location, description, time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()), days)\n\ntext = '\\t'.join(info)\nprint(text)\n# ================写入剪贴板================\nimport pyperclip\npyperclip.copy(text)\nspam = pyperclip.paste()\n\n# ================运行时间计时================\nrun_time = time.time() - start_time\nif run_time < 60: # 两位小数的秒\n print(\"耗时:{:.2f}秒\".format(run_time))\nelif run_time < 3600: # 分秒取整\n print(\"耗时:{:.0f}分{:.0f}秒\".format(run_time // 60, run_time % 60))\nelse: # 时分秒取整\n print(\"耗时:{:.0f}时{:.0f}分{:.0f}秒\".format(run_time // 3600, run_time % 3600 // 60, run_time % 60))\n","sub_path":"微博-信息获取.py","file_name":"微博-信息获取.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"178329907","text":"from nltk import stem\nfrom nltk.tokenize import RegexpTokenizer\nfrom knock71 import stopwords_exsits\nfrom collections import defaultdict\nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.externals import joblib\n\ndef regex_str(sentence):\n\ttokenizer = RegexpTokenizer(r'\\w+')\n\tstemmer = stem.PorterStemmer()\n\twords = tokenizer.tokenize(sentence)\n\treturn [stemmer.stem(word) for word in words if not stopwords_exsits(word)]\n\t\ndef count_word(words):\n\tword_counts = defaultdict(int)\n\tfor word in words:\n\t\tword_counts[word] += 1\n\treturn word_counts\n\ndef create_features_with_labels(txt_path=\"sentiment.txt\"):\n\tfeature_lists = []\n\tlabel_list = []\n\traw_result = {}\n\twith open(txt_path, 'r') as f:\n\t\tfor line in f:\n\t\t\tlabel, sentence = line.split(\"\\t\")\n\t\t\tlabel_list.append(int(label))\n\t\t\tword_counts = count_word(regex_str(sentence))\n\t\t\tfeature_lists.append(word_counts)\n\traw_result[\"input\"] = feature_lists\n\traw_result[\"label\"] = label_list\n\treturn raw_result\n\ndef vect_features(feature_lists):\n\tv = DictVectorizer()\n\treturn v.fit_transform(feature_lists)\n\nif __name__ == '__main__':\n\tresult = create_features_with_labels()\n\tprint(result[\"input\"][:5])\n\tprint(result[\"label\"][:5])","sub_path":"lifan/chapter08/knock72.py","file_name":"knock72.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"305981941","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_bootstrap_components as dbc\n\nimport yield_page, piotroski, dice_rolls\n\n# Since we're adding callbacks to elements that don't exist in the app.layout,\n# Dash will raise an exception to warn us that we might be\n# doing something wrong.\n# In this case, we're adding the elements through a callback, so we can ignore\n# the exception.\n\napp = dash.Dash(__name__, suppress_callback_exceptions=True)\nserver = app.server\n\napp.layout = html.Div([\n dcc.Location(id='url', refresh=False),\n dbc.NavbarSimple(\n children=[\n dbc.NavItem(dbc.NavLink(\"Yield Calculator\", href=\"/yield\")),\n dbc.NavItem(dbc.NavLink(\"Piotroski Score\", href=\"/fm1\")),\n dbc.NavItem(dbc.NavLink(\"Simulating Dice Rolls\", href=\"/dice\"))\n ],\n brand=\"Finance Dashboard\",\n brand_href=\"/\",\n color=\"primary\",\n dark=True\n ),\n html.Div(id='page-content')\n])\n\nhome_layout = html.Div([\n html.H2(\"This is the home page.\"),\n html.P(\"Click on the different links to explore different items\"),\n html.P(\"Created by - Kanak\")\n])\n\nHOME_LINK = dcc.Link('Home', href='/')\n\nALL_LINKS = html.Div([\n HOME_LINK, html.Br(),\n dcc.Link('Yield Calculator', href='/yield'), html.Br(),\n dcc.Link('Piotroski Score', href='/fm1'), html.Br(),\n dcc.Link('Simulating Dice Rolls', href='/dice')\n])\n\nyield_page.register_callbacks(app)\n\npiotroski.register_callbacks(app)\n\ndice_rolls.register_callbacks(app)\n\n# Financial Metrics 2 and so on...\n\n'''\nNote, we can do the above thing dynamically. Can make a folder called content-pages. Then, for each python file in that folder, we import the file, create the corresponding layout, and register the corresponding callback\n'''\n\n# Update the index\n@app.callback(dash.dependencies.Output('page-content', 'children'),\n [dash.dependencies.Input('url', 'pathname')])\ndef display_page(pathname):\n if pathname == '/yield':\n return yield_page.layout\n elif pathname == '/fm1':\n return piotroski.layout\n elif pathname == '/dice':\n return dice_rolls.layout\n else:\n return home_layout\n # You could also return a 404 \"URL not found\" page here\n\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","sub_path":"index_page.py","file_name":"index_page.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"468032488","text":"import linecache\nimport numpy as np\n\n\nclass WordEmbedding:\n\n def __init__(self, embfile):\n\n self.embfile = embfile\n\n self.dimensions = 0\n self.embeddings_index = dict()\n self.index_words()\n self.vocabulary_size = len(self.embeddings_index)\n self.embedding_matrix = None\n\n def index_words(self):\n print('Indexing words...', end='', flush=True)\n with open(self.embfile, encoding=\"utf8\") as file:\n for line_no, line in enumerate(file):\n values = line.split()\n word = values[0]\n self.dimensions = len(values[1:])\n self.embeddings_index[word] = line_no + 1\n print('done')\n\n def create_embedding_matrix(self, tokenizer):\n print('Create embedding matrix...', end='', flush=True)\n self.vocabulary_size = len(tokenizer.word_index) + 1\n self.embedding_matrix = np.zeros(shape=(self.vocabulary_size, self.dimensions))\n for word, index in tokenizer.word_index.items():\n line_no = self.embeddings_index.get(word)\n if line_no is not None:\n line = linecache.getline(self.embfile, line_no)\n try:\n values = line.split()\n if word != values[0]:\n print('Word-Line mismatch!')\n continue\n\n self.embedding_matrix[index] = np.asarray(values[1:], dtype='float32')\n except Exception:\n continue\n print('done')\n\n def sequences_to_embeddings(self, sequences):\n seq_embeddings = np.zeros(shape=(sequences.shape[0], sequences.shape[1], self.dimensions))\n for i, sequence in enumerate(sequences):\n for j, word_index in enumerate(sequence):\n seq_embeddings[i, j, :] = self.embedding_matrix[word_index]\n return seq_embeddings\n","sub_path":"model/embedding.py","file_name":"embedding.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"418354771","text":"import unittest\nfrom pypix import *\n\n# Dictionaries of frame data, seperated into a list corresponding to cluster\nCLUSTERS = [{\n (175,10): 51,\n (176,10): 82,\n (176,12): 9,\n (174,10): 6,\n (174,11): 59,\n (175,11): 117,\n (176,11): 62,\n (174,12): 46,\n (175,12): 128}, {\n (146,41): 32,\n (147,41): 45,\n (146,42): 211,\n (147,42): 89}, {\n (95,176): 81,\n (96,176): 73,\n (92,177): 38,\n (93,177): 27,\n (94,177): 48,\n (91,178): 156,\n (92,178): 16,\n (93,178): 57,\n (91,179): 183}, {\n (147,240): 25,\n (148,240): 219}, {\n (156,253): 22,\n (156,254): 44,\n (157,254): 37,\n (157,255): 21,\n (158,255): 42,\n (159,255): 54}, {\n (75,75): 36 }\n]\n\n# Calculate the data for the whole frame by combining the data for each cluster\nTEST_FRAME_DATA = dict()\nfor cluster in CLUSTERS:\n TEST_FRAME_DATA.update(cluster)\n\nclass TestFrame(unittest.TestCase):\n\n # Read test frame\n def setUp(self):\n self.f = Frame.from_file(\"test_frame.lsc\")\n\n def test_width(self):\n # TEST 1.1\n self.assertEqual(self.f.width, 256)\n\n def test_height(self):\n # TEST 1.2\n self.assertEqual(self.f.height, 256)\n\n def test_in_grid(self):\n # Boundary testing\n # Check origin boundary\n # TEST 2.1\n self.assertEqual(self.f.in_grid((0,0)), True, \"(0,0) should be in_grid\")\n # TEST 2.2\n self.assertEqual(self.f.in_grid((0,-1)), False, \"(0,-1) should not be in_grid\")\n # Test 2.3\n self.assertEqual(self.f.in_grid((-1,0)), False, \"(-1,0) should not be in_grid\")\n\n # Check furthest corner boundary\n width = self.f.width\n height = self.f.height\n # Indices start from 0, so (width, height) should be outside grid\n # Test 2.4\n self.assertEqual(self.f.in_grid((width-1,height-1)), True, \"(width-1,height-1) should be in_grid\")\n # Test 2.5\n self.assertEqual(self.f.in_grid((width,height-1)), False, \"(width,height-1) should not be in_grid\")\n # Test 2.6\n self.assertEqual(self.f.in_grid((width-1,height)), False, \"(width-1,height) should not be in_grid\")\n\n def test_grid_access(self):\n # Test 3.1\n self.assertEqual(type(self.f[(175,10)]), Hit, \"Dictionary access of frame object should return hit object\")\n # Test 3.2\n self.assertEqual(self.f[(175,10)].value, 51, \"Dictionary access of frame object should return Hit with correct value\")\n # assertRaises requires a function, so wrap the invalid co-ordinate in lambda\n # Test 3.3\n self.assertRaises(KeyError, lambda: self.f[(500,500)])\n\n def test_pixel_values(self):\n # Test 4\n for x in range(self.f.width):\n for y in range(self.f.height):\n self.assertEqual(self.f[(x,y)].value, TEST_FRAME_DATA.get((x,y), 0),\n \"Incorrect pixel value for (%d, %d). Should be %d, got %d\"\n % (x, y, TEST_FRAME_DATA.get((x,y), 0), self.f[(x,y)].value))\n\n def test_pixels(self):\n # Use assertEqual so order doesn't matter\n # Test 5\n self.assertItemsEqual(self.f.hit_pixels, TEST_FRAME_DATA.keys())\n\n def test_counts(self):\n # Use assertEqual so order doesn't matter\n # Test 6\n self.assertItemsEqual(self.f.counts, TEST_FRAME_DATA.values())\n\n def test_min_x(self):\n # Test 7.1\n self.assertEqual(self.f.min_x, 75)\n def test_max_x(self):\n # Test 7.2\n self.assertEqual(self.f.max_x, 176)\n def test_min_y(self):\n # Test 7.3\n self.assertEqual(self.f.min_y, 10)\n def test_max_y(self):\n # Test 7.4\n self.assertEqual(self.f.max_y, 255)\n\n def test_number_of_neighbours(self):\n # Test 8.1\n self.assertEqual(self.f.number_of_neighbours((175,11)), 8)\n # Test 8.2\n self.assertEqual(self.f.number_of_neighbours((75,75)), 0)\n # Test 8.3\n self.assertEqual(self.f.number_of_neighbours((93,177)), 4)\n\n def test_get_max_neighbours(self):\n # Test 9\n self.assertEqual(self.f.get_max_neighbours(), (8, [(175, 11)]))\n\n def test_calculate_clusters(self):\n # Test 10\n # Cluster is done on pixel positions only, so we check each pixel\n # is in the correct cluster\n frame_clusters = self.f.calculate_clusters()\n # Grab copies of the correct and calculated clusters, as lists of sorted pixel coords.\n # Sorting the lists makes sure that Python sees the sublists of frame_cluster_pixels and\n # correct_cluster_pixels as the same.\n frame_cluster_pixels = [cluster.hit_pixels.sort() for cluster in frame_clusters]\n correct_cluster_pixels = [cluster.keys().sort() for cluster in CLUSTERS]\n self.assertItemsEqual(frame_cluster_pixels, correct_cluster_pixels)\n\n# Run the tests\nunittest.main(verbosity=2)\n","sub_path":"crayfish/pypix/test_pypix.py","file_name":"test_pypix.py","file_ext":"py","file_size_in_byte":4892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"66661768","text":"import gc\r\ngc.collect()\r\nimport music\r\n_m=['c6:1','r','c6,1','r','r','r']\r\ndef setAlarm(on):\r\n if on:\r\n music.play(_m,wait=False,loop=True) \r\n else:\r\n music.stop()\r\ndef beep():\r\n music.pitch(2000,200,wait=False)\r\n# Created by pyminifier (https://github.com/liftoff/pyminifier)\r\n","sub_path":"maqueen-plus/microbit_V2/dist/mbalarm.py","file_name":"mbalarm.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"216842804","text":"import urllib.parse as up\nimport requests\n\n# ./shellscript.sh -f hu -t en -w \"eper\"\n\n# word = \"eper\"\n# target = \"en\"\n# source = \"hu\"\n\n\ndef csinald(source, target, word):\n if len(source) == 0:\n source = up.quote(\"hu\")\n if len(target) == 0:\n target = up.quote(\"en\")\n\n url = \"https://google-translate1.p.rapidapi.com/language/translate/v2\"\n\n payload = (\n \"q=\"\n + up.quote(word.lower())\n + \"&target=\"\n + up.quote(target.lower())\n + \"&source=\"\n + up.quote(source.lower())\n + \"\"\n )\n\n headers = {\n \"content-type\": \"application/x-www-form-urlencoded\",\n \"accept-encoding\": \"application/gzip\",\n \"x-rapidapi-key\": \"5cca084016msh3c02e2e347d45bcp1c478ajsne900a02d99c3\",\n \"x-rapidapi-host\": \"google-translate1.p.rapidapi.com\",\n }\n\n response = requests.request(\"POST\", url, data=payload, headers=headers)\n translation_data = response.json()\n translation = translation_data[\"data\"][\"translations\"][0][\"translatedText\"]\n\n print(translation.lower())\n","sub_path":"src/translator.py","file_name":"translator.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"263124715","text":"import configparser\nimport psycopg2\nimport sys\nfrom sql_queries import create_table_queries, drop_table_queries\n\n\ndef drop_tables(cur, conn):\n '''\n Executes table drops for a given db connection and an associated cursor.\n Drop statements are defined in sql_queries drop_table_queries.\n :param cur:\n :param conn:\n :return:\n '''\n error = \"none\"\n for query in drop_table_queries:\n try:\n cur.execute(query)\n conn.commit()\n except psycopg2.Error as e:\n print(f\"Error on dropping table. Current query: {query}\")\n print(e)\n error = 'error'\n conn.close()\n sys.exit(1)\n\n print(f\"Finished: tables dropped. Error status: {error}\")\n\n\ndef create_tables(cur, conn):\n '''\n Executes table create for a given db connection and an associated cursor.\n Create statements are defined in sql_queries create_table_queries.\n :param cur:\n :param conn:\n :return:\n '''\n error = \"none\"\n for query in create_table_queries:\n try:\n cur.execute(query)\n conn.commit()\n except psycopg2.Error as e:\n print(f\"Error on creating tables. Current query: {query}\")\n print(e)\n error = 'error'\n conn.close()\n sys.exit(1)\n\n print(f\"Finished: tables created. Error status: {error}\")\n\n\ndef main():\n '''\n Execute drop and create tables as prepartion for ETL.\n :return:\n '''\n config = configparser.ConfigParser()\n config.read('dwh.cfg')\n\n\n conn_string = \"postgresql://{}:{}@{}:{}/{}\".format(config['ETL']['DWH_DB_USER'], config['ETL']['DWH_DB_PASSWORD'],\n config['ETL']['DWH_ENDPOINT'], config['ETL']['DWH_PORT'],\n config['ETL']['DWH_DB'])\n conn = psycopg2.connect(conn_string)\n cur = conn.cursor()\n\n drop_tables(cur, conn)\n create_tables(cur, conn)\n\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"create_tables.py","file_name":"create_tables.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"84666984","text":"# 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\"\"\"Set of utilities for dealing with archives.\"\"\"\n\nimport os\nimport re\nimport zipfile\n\ntry:\n # pylint: disable=unused-import\n # pylint: disable=g-import-not-at-top\n import zlib\n _ZIP_COMPRESSION = zipfile.ZIP_DEFLATED\nexcept ImportError:\n _ZIP_COMPRESSION = zipfile.ZIP_STORED\n\n\ndef MakeZipFromDir(dest_zip_file, src_dir, skip_file_regex=None):\n \"\"\"Similar to shutil.make_archive (which is available in python >=2.7).\n\n Examples:\n Filesystem:\n /tmp/a/\n /tmp/b/B\n\n >>> MakeZipFromDir('my.zip', '/tmp')\n Creates zip with content:\n a/\n b/B\n\n >>> MakeZipFromDir('my.zip', '/tmp', 'b.*')\n Creates zip with content:\n a/\n\n >>> MakeZipFromDir('my.zip', '/tmp', 'b/.*')\n Creates zip with content:\n a/\n b/\n\n Note this is caller responsibility to use appropriate platform-dependent\n path separator.\n\n Note filenames containing path separator are supported, but specifying\n skip_file_regex might be slightly more tricky.\n\n Args:\n dest_zip_file: str, filesystem path to the zip file to be created. Note that\n directory should already exist for destination zip file.\n src_dir: str, filesystem path to the directory to zip up\n skip_file_regex: regex, files and directories with names relative to src_dir\n matching this pattern will be excluded from the archive.\n \"\"\"\n def IsSkipped(relative_name):\n \"\"\"Decides if given file or directory should be skipped.\"\"\"\n if skip_file_regex is None:\n return False\n return re.match(skip_file_regex, relative_name) is not None\n\n zip_file = zipfile.ZipFile(dest_zip_file, 'w', _ZIP_COMPRESSION)\n try:\n for root, _, filelist in os.walk(src_dir):\n # In case this is empty directory.\n path = os.path.normpath(os.path.relpath(root, src_dir))\n if IsSkipped(path):\n continue\n if path and path != os.curdir:\n zip_file.write(root, path)\n for f in filelist:\n filename = os.path.normpath(os.path.join(root, f))\n relpath = os.path.relpath(filename, src_dir)\n if IsSkipped(relpath):\n continue\n if os.path.isfile(filename):\n zip_file.write(filename, relpath)\n finally:\n zip_file.close()\n","sub_path":"google-cloud-sdk/lib/googlecloudsdk/core/util/archive.py","file_name":"archive.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"607367590","text":"# 검색 알고리즘\n\n# 선형 검색\n# 직선모양 (선형) 으로 늘어선 배열에서 검색하는 경우에 원하는 키값을 가진 원소를 찾을 때까지 맨 앞부터 스캔하여 순서대로 검색하는 알고리즘\n\ndef seq_search(a, key):\n for i in range(len(a)):\n if a[i] == key:\n return i\n return -1\n\nif __name__ == '__main__':\n num = int(input('원소의 개수를 입력하시오. : '))\n x = [None] * num\n\n for i in range(num):\n x[i] = int(input(f'x[{i}]: '))\n \n ky = int(input('찾는 값을 입력하세요. (정수형) : '))\n\n\n idx = seq_search(x,ky)\n\n if idx == -1 :\n print('그런 값은 존재하지 않습니다.')\n else :\n print(f'검색결과 : x[{idx}]')","sub_path":"seq_search.py","file_name":"seq_search.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"405617728","text":"import init\n\nprint(\"Welcome! Welcome!\")\njk=open(activeAccounts)\npickle.load(activeAccounts)\n\nkl= init.getPubIP()\njk=activeAccounts.get(kl, 0)\nif(jk==0):\n print(\"Please sign in with your PythonG Live account please:\")\n signIn()\nelse:\n print(\"Which lottery would you like to play today?\")\n","sub_path":"PYTHONG/GLotto/GLotto.py","file_name":"GLotto.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"416870222","text":"# 문제 38 : 호준이의 아르바이트\n# 호준이는 아르바이트로 영어 학원에서 단어 시험지를 채점하는 일을 하고 있다. 호준이가 일하는 학원은 매번 1위부터 3위까지\n# 학생에서 상으로 사탕을 준다. 그런데 오늘은 사탕이다 떨어져서 호준이가 채점을 하고 점수를 보내면, 당신이 아이들의 숫자만큼 사탕을 사러 가기로 했다.\n# 학생들의 점수를 공백으로 구분하여 입력받는다. 1위~3위 학생은 여러명일 수 있고, 1~3위 학생 중 중복되는 학생까지 포함하여 사탕을 사기로 한다.\n\n\"\"\"\n점수입력 : 97 86 75 66 55 97 85 97 97 95\n출력 : 6\n\"\"\"\n\nparsing = input('점수입력 : ').strip().split()\nstudents = [int(x) for x in parsing]\nscores = set(students)\nbest3 = set()\n\nfor i in range(3):\n max_score = max(scores)\n best3.add(max(scores))\n scores.remove(max_score)\n\ntotal = 0\nfor score in best3:\n total += students.count(score)\n\nprint('출력: ', total)\n","sub_path":"code/38.py","file_name":"38.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"308112487","text":"from __future__ import annotations\n\nimport json\nimport os\n\nfrom PySide2 import QtCore\nfrom PySide2.QtCore import QObject, Qt, Signal\nfrom PySide2.QtGui import QIcon, QMovie, QPixmap\nfrom PySide2.QtWidgets import (\n QDialog,\n QFileDialog,\n QGridLayout,\n QGroupBox,\n QHBoxLayout,\n QLabel,\n QMessageBox,\n QPushButton,\n QTextBrowser,\n)\nfrom jinja2 import Environment, FileSystemLoader, select_autoescape\n\nfrom game.debriefing import Debriefing, wait_for_debriefing\nfrom game.game import Event, Game, logging\nfrom game.persistency import base_path\nfrom game.unitmap import UnitMap\nfrom qt_ui.windows.GameUpdateSignal import GameUpdateSignal\n\n\nclass DebriefingFileWrittenSignal(QObject):\n\n instance = None\n debriefingReceived = Signal(Debriefing)\n\n def __init__(self):\n super(DebriefingFileWrittenSignal, self).__init__()\n DebriefingFileWrittenSignal.instance = self\n\n def sendDebriefing(self, debriefing: Debriefing):\n self.debriefingReceived.emit(debriefing)\n\n @staticmethod\n def get_instance() -> DebriefingFileWrittenSignal:\n return DebriefingFileWrittenSignal.instance\n\n\nDebriefingFileWrittenSignal()\n\n\nclass QWaitingForMissionResultWindow(QDialog):\n\n def __init__(self, gameEvent: Event, game: Game, unit_map: UnitMap) -> None:\n super(QWaitingForMissionResultWindow, self).__init__()\n self.setModal(True)\n self.gameEvent = gameEvent\n self.game = game\n self.unit_map = unit_map\n self.setWindowTitle(\"Waiting for mission completion.\")\n self.setWindowIcon(QIcon(\"./resources/icon.png\"))\n self.setMinimumHeight(570)\n\n self.initUi()\n DebriefingFileWrittenSignal.get_instance().debriefingReceived.connect(self.updateLayout)\n self.wait_thread = wait_for_debriefing(\n lambda debriefing: self.on_debriefing_update(debriefing), self.game,\n self.unit_map)\n\n def initUi(self):\n self.layout = QGridLayout()\n\n header = QLabel(self)\n header.setGeometry(0, 0, 655, 106)\n pixmap = QPixmap(\"./resources/ui/conflict.png\")\n header.setPixmap(pixmap)\n self.layout.addWidget(header, 0, 0)\n\n self.gridLayout = QGridLayout()\n\n jinja = Environment(\n loader=FileSystemLoader(\"resources/ui/templates\"),\n autoescape=select_autoescape(\n disabled_extensions=(\"\",),\n default_for_string=True,\n default=True,\n ),\n trim_blocks=True,\n lstrip_blocks=True,\n )\n self.instructions_text = QTextBrowser()\n self.instructions_text.setHtml(\n jinja.get_template(\"mission_start_EN.j2\").render())\n self.instructions_text.setOpenExternalLinks(True)\n self.gridLayout.addWidget(self.instructions_text, 1, 0)\n\n progress = QLabel(\"\")\n progress.setAlignment(QtCore.Qt.AlignCenter)\n progress_bar = QMovie(\"./resources/ui/loader.gif\")\n progress.setMovie(progress_bar)\n\n self.actions = QGroupBox(\"Actions :\")\n self.actions_layout = QHBoxLayout()\n self.actions.setLayout(self.actions_layout)\n\n self.manually_submit = QPushButton(\"Manually Submit [Advanced users]\")\n self.manually_submit.clicked.connect(self.submit_manually)\n self.actions_layout.addWidget(self.manually_submit)\n self.cancel = QPushButton(\"Abort mission\")\n self.cancel.clicked.connect(self.close)\n self.actions_layout.addWidget(self.cancel)\n self.gridLayout.addWidget(self.actions, 2, 0)\n\n\n self.actions2 = QGroupBox(\"Actions :\")\n self.actions2_layout = QHBoxLayout()\n self.actions2.setLayout(self.actions2_layout)\n self.manually_submit2 = QPushButton(\"Manually Submit [Advanced users]\")\n self.manually_submit2.clicked.connect(self.submit_manually)\n self.actions2_layout.addWidget(self.manually_submit2)\n self.cancel2 = QPushButton(\"Abort mission\")\n self.cancel2.clicked.connect(self.close)\n self.actions2_layout.addWidget(self.cancel2)\n self.proceed = QPushButton(\"Accept results\")\n self.proceed.setProperty(\"style\", \"btn-success\")\n self.proceed.clicked.connect(self.process_debriefing)\n self.actions2_layout.addWidget(self.proceed)\n\n progress_bar.start()\n self.layout.addLayout(self.gridLayout, 1, 0)\n self.setLayout(self.layout)\n\n def updateLayout(self, debriefing: Debriefing) -> None:\n updateBox = QGroupBox(\"Mission status\")\n updateLayout = QGridLayout()\n updateBox.setLayout(updateLayout)\n self.debriefing = debriefing\n\n updateLayout.addWidget(QLabel(\"Aircraft destroyed\"), 0, 0)\n updateLayout.addWidget(\n QLabel(str(len(list(debriefing.air_losses.losses)))), 0, 1)\n\n updateLayout.addWidget(\n QLabel(\"Front line units destroyed\"), 1, 0)\n updateLayout.addWidget(\n QLabel(str(len(list(debriefing.front_line_losses)))), 1, 1)\n\n updateLayout.addWidget(\n QLabel(\"Other ground units destroyed\"), 2, 0)\n updateLayout.addWidget(\n QLabel(str(len(list(debriefing.ground_object_losses)))), 2, 1)\n\n updateLayout.addWidget(\n QLabel(\"Buildings destroyed\"), 3, 0)\n updateLayout.addWidget(\n QLabel(str(len(list(debriefing.building_losses)))), 3, 1)\n\n updateLayout.addWidget(QLabel(\"Base Capture Events\"), 4, 0)\n updateLayout.addWidget(\n QLabel(str(len(debriefing.base_capture_events))), 4, 1)\n\n # Clear previous content of the window\n for i in reversed(range(self.gridLayout.count())):\n try:\n self.gridLayout.itemAt(i).widget().setParent(None)\n except:\n logging.exception(\"Failed to clear window\")\n\n # Set new window content\n self.gridLayout.addWidget(updateBox, 0, 0)\n\n if not debriefing.state_data.mission_ended:\n self.gridLayout.addWidget(QLabel(\"Mission is being played\"), 1, 0)\n self.gridLayout.addWidget(self.actions, 2, 0)\n else:\n self.gridLayout.addWidget(QLabel(\"Mission is over\"), 1, 0)\n self.gridLayout.addWidget(self.actions2, 2, 0)\n\n def on_debriefing_update(self, debriefing: Debriefing) -> None:\n try:\n logging.info(\"On Debriefing update\")\n logging.debug(debriefing)\n DebriefingFileWrittenSignal.get_instance().sendDebriefing(debriefing)\n except Exception:\n logging.exception(\"Got an error while sending debriefing\")\n self.wait_thread = wait_for_debriefing(\n lambda d: self.on_debriefing_update(d), self.game, self.unit_map)\n\n def process_debriefing(self):\n self.game.finish_event(event=self.gameEvent, debriefing=self.debriefing)\n self.game.pass_turn()\n\n GameUpdateSignal.get_instance().sendDebriefing(self.debriefing)\n GameUpdateSignal.get_instance().updateGame(self.game)\n self.close()\n\n def debriefing_directory_location(self) -> str:\n return os.path.join(base_path(), \"liberation_debriefings\")\n\n def closeEvent(self, evt):\n super(QWaitingForMissionResultWindow, self).closeEvent(evt)\n if self.wait_thread is not None:\n self.wait_thread.stop()\n\n def submit_manually(self):\n file = QFileDialog.getOpenFileName(self, \"Select game file to open\", filter=\"json(*.json)\", dir=\".\")\n print(file)\n try:\n with open(file[0], \"r\") as json_file:\n json_data = json.load(json_file)\n json_data[\"mission_ended\"] = True\n debriefing = Debriefing(json_data, self.game, self.unit_map)\n self.on_debriefing_update(debriefing)\n except Exception as e:\n logging.error(e)\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Information)\n msg.setText(\"Invalid file : \" + file[0])\n msg.setWindowTitle(\"Invalid file.\")\n msg.setStandardButtons(QMessageBox.Ok)\n msg.setWindowFlags(Qt.WindowStaysOnTopHint)\n msg.exec_()\n return\n\n","sub_path":"qt_ui/windows/QWaitingForMissionResultWindow.py","file_name":"QWaitingForMissionResultWindow.py","file_ext":"py","file_size_in_byte":8230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"374332542","text":"'''\r\nThe Fibonacci sequence is defined by the recurrence relation:\r\n\r\nFn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.\r\nHence the first 12 terms will be:\r\n\tF1 = 1\r\n\tF2 = 1\r\n\tF3 = 2\r\n\tF4 = 3\r\n\tF5 = 5\r\n\tF6 = 8\r\n\tF7 = 13\r\n\tF8 = 21\r\n\tF9 = 34\r\n\tF10 = 55\r\n\tF11 = 89\r\n\tF12 = 144\r\nThe 12th term, F12, is the first term to contain three digits.\r\n\r\nWhat is the index of the first term in the Fibonacci sequence to contain 1000 digits?\r\n\r\nAnswer:\r\n4782\r\n'''\r\n\r\n# 6mins, classic fibonacci algorithm\r\n\r\nimport time\r\nstart = time.time()\r\n\r\na = 1\r\nb = 1\r\ncount = 2\r\nwhile True:\r\n\ttmp = b\r\n\tb = a+b\r\n\ta = tmp\r\n\tcount+=1\r\n\tif len(str(b))==1000:\r\n\t\tprint(count)\r\n\t\tbreak\r\n\r\nprint(time.time()-start)\r\n","sub_path":"Project Euler/025._1000-digit_Fibonacci_number.py","file_name":"025._1000-digit_Fibonacci_number.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"395961342","text":"from intcode import Intcode\nimport sys\n\n\ndef get_new_position(position, next_move):\n x, y = position\n if next_move == 1:\n position = (x, y - 1)\n elif next_move == 2:\n position = (x, y + 1)\n elif next_move == 3:\n position = (x - 1, y)\n elif next_move == 4:\n position = (x + 1, y)\n else:\n assert(\"Invalid move: \" + next_move)\n\n return position\n\n\ndef build_map(cpu, position, m):\n reverse_moves = [0, 2, 1, 4, 3]\n elements = [\"#\", \".\", \"O\"]\n for next_move in range(1, 5):\n new_position = get_new_position(position, next_move)\n if new_position in m.keys():\n continue\n cpu.input.append(next_move)\n cpu.run()\n result = cpu.output.pop(0)\n m[new_position] = elements[result]\n if result != 0:\n build_map(cpu, new_position, m)\n cpu.input.append(reverse_moves[next_move])\n cpu.run()\n cpu.output.pop()\n\n\ndef print_map(m):\n print(len(m))\n min_x, min_y, max_x, max_y = 0, 0, 0, 0\n for position in m.keys():\n min_x = min(min_x, position[0])\n min_y = min(min_y, position[1])\n max_x = max(max_x, position[0])\n max_y = max(max_y, position[1])\n\n screen = [['_'] * (max_x - min_x + 1) for _ in range(min_y, max_y + 1)]\n for item in m.items():\n ((x, y), element) = item\n screen[y - min_y][x - min_x] = element\n\n for l in screen:\n print(\"\".join(l))\n\n\ndef find_oxygen(m):\n queue = [((0, 0), 0)]\n visited = set()\n while queue:\n (position, path_length) = queue.pop(0)\n if position in visited or position not in m.keys():\n continue\n visited.add(position)\n if m[position] == 'O':\n return (path_length, position)\n if m[position] == '#':\n continue\n for next_move in range(1, 5):\n queue.append(\n (get_new_position(position, next_move), path_length + 1))\n\n\ndef oxygenize(m, start_position):\n time = 0\n queue = [start_position]\n while True:\n new_queue = []\n while queue:\n position = queue.pop(0)\n m[position] = 'O'\n for next_move in range(1, 5):\n new_position = get_new_position(position, next_move)\n if m[new_position] == \".\":\n new_queue.append(new_position)\n if not new_queue:\n return time\n queue = new_queue\n time += 1\n\n\ndef problem1(program):\n m = {}\n build_map(Intcode(list(program)), (0, 0), m)\n m[(0, 0)] = \"*\"\n print(find_oxygen(m))\n\n\ndef problem2(program):\n m = {}\n build_map(Intcode(list(program)), (0, 0), m)\n _, oxygen_position = find_oxygen(m)\n print(oxygenize(m, oxygen_position))\n\n\nwith open(sys.argv[1], \"r\") as f:\n program = list(map(lambda n: int(n), f.readline().split(\",\")))\n problem1(program)\n problem2(program)","sub_path":"2019/Day15/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"164219983","text":"#########################################################\n# -*- coding: utf-8 -*-\n\nimport socket\nimport errno\nimport sys\nimport winreg\n#########################################################\nfrom ..data_access.decoding import Decoding\n##########################################################\n\n\nclass Windows_app(Decoding):\n\n\n def _basic_information(self):\n\n _machine = {}\n # Open the key and return the handle object.\n with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r\"HARDWARE\\DESCRIPTION\\System\\BIOS\") as hKey:\n # Open the key and return the handle object.\n with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r\"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\") as hKeyOs:\n\n try:\n\n _model = self.avoid_exception(hKey, 'SystemVersion', 0)\n _vendor = self.avoid_exception(hKey, 'SystemManufacturer', 0)\n _operation_system = self.avoid_exception(hKeyOs, 'ProductName', 0)\n _bios_vendor = self.avoid_exception(hKey, 'BIOSVendor', 0)\n _bios_version = self.avoid_exception(hKey, 'BIOSVersion', 0)\n\n _machine['System_Version'] = _model\n _machine['System_Manufacturer'] = _vendor\n _machine['Product_Name'] = _operation_system\n _machine['Bios_Vendor'] = _bios_vendor\n _machine['Bios_Version'] = _bios_version\n\n except WindowsError as e:\n pass\n\n return _machine\n\n def _run_key_by_default(self):\n # we gonna be the dictionary that gonna save the apps with his own version\n app = {}\n\n key = super().get_architectures(winreg.HKEY_LOCAL_MACHINE, r\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\")\n\n for hKey, Architecture in key.items():\n for n in range(0, winreg.QueryInfoKey(hKey)[1]):\n try:\n Temp = {}\n Name = (winreg.EnumValue(hKey, n)[0])\n Temp['Path'] = (winreg.EnumValue(hKey, n)[1])\n Temp['Architecture'] = Architecture\n\n app[Name] = Temp\n\n except WindowsError as e:\n pass\n hKey.Close()\n\n return app\n\n def _run_key_by_user(self):\n\n app = {}\n Temp_app = {}\n\n key = super().get_architectures(winreg.HKEY_CURRENT_USER, r\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\")\n\n for hKey, Architecture in key.items():\n for n in range(0, winreg.QueryInfoKey(hKey)[1]):\n try:\n Temp = {}\n Name = (winreg.EnumValue(hKey, n)[0])\n Temp['Path'] = (winreg.EnumValue(hKey, n)[1])\n Temp['Architecture'] = Architecture\n\n Temp_app[Name] = Temp\n except WindowsError as e:\n pass\n hKey.Close()\n\n app[super().get_sid_current_account()] = Temp_app\n return app\n\n def _users(self):\n\n # we gonna be the dictionary that gonna save the apps with his own version\n users = {}\n # Open the key and return the handle object.\n with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,\n r\"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\") as hKey:\n\n for i in range(0, winreg.QueryInfoKey(hKey)[0]):\n subKeyName = winreg.EnumKey(hKey, i)\n\n with winreg.OpenKey(hKey, subKeyName) as OpenSubKey:\n try:\n name = (winreg.QueryValueEx(OpenSubKey, 'ProfileImagePath')[0])\n\n # Setting the values on the list\n users[subKeyName] = name\n\n except OSError as e:\n if e.errno == errno.ENOENT:\n # Display doesn't exist in this key\n pass\n\n # finally return the dictionary with the app and the his path\n\n return users\n\n def Get_Rules(Self, hKey):\n\n Rules = {}\n\n for n in range(0, winreg.QueryInfoKey(hKey)[1]):\n try:\n TEMP = (winreg.EnumValue(hKey, n)[1])\n Rules[(winreg.EnumValue(hKey, n)[0])] = TEMP\n except WindowsError as e:\n pass\n hKey.Close()\n return Rules\n\n def Firewall_rules(self):\n\n AllRules = {}\n\n hKey0 = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r\"SYSTEM\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\FirewallRules\")\n hKey1 = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r\"SYSTEM\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\RestrictedServices\\Configurable\\System\")\n hKey2 = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r\"SYSTEM\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\RestrictedServices\\Static\\System\")\n\n Rules0 = self.Get_Rules(hKey0)\n Rules1 = self.Get_Rules(hKey1)\n Rules2 = self.Get_Rules(hKey2)\n\n AllRules['FirewallRules'] = Rules0\n AllRules[r'RestrictedServices\\Configurable\\System'] = Rules1\n AllRules[r'RestrictedServices\\Static\\System'] = Rules2\n\n return AllRules\n\n def Detect_Applications_by_default(self):\n Apps = []\n\n key = super().get_architectures(winreg.HKEY_LOCAL_MACHINE, r\"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\")\n\n for hKey, Architecture in key.items():\n for i in range(0, winreg.QueryInfoKey(hKey)[0]):\n app = {}\n argument = {}\n sub_key_name = winreg.EnumKey(hKey, i)\n open_sub_key = winreg.OpenKey(hKey, sub_key_name)\n\n try:\n app_name = self.avoid_exception(open_sub_key, 'DisplayName', 0)\n display_icon = self.avoid_exception(open_sub_key, 'DisplayIcon', 0)\n app_version = self.avoid_exception(open_sub_key, 'DisplayVersion', 0)\n publisher = self.avoid_exception(open_sub_key, 'Publisher', 0)\n help_link = self.avoid_exception(open_sub_key, 'HelpLink', 0)\n install_location = self.avoid_exception(open_sub_key, 'InstallLocation', 0)\n install_date = self.avoid_exception_Date(open_sub_key, 'InstallDate', 0)\n\n # Setting the values on the dict\n argument['Name'] = app_name\n argument['DisplayIcon'] = display_icon\n argument['Version'] = app_version\n argument['Publisher'] = publisher\n argument['Help_link'] = help_link\n argument['Install_location'] = install_location\n argument['Install_date'] = install_date\n argument['Architecture'] = Architecture\n\n # We save the name of the app and his version on the dictionary\n app[sub_key_name] = argument\n Apps.append(app)\n\n except Exception as e:\n print(e)\n open_sub_key.Close()\n hKey.Close()\n\n # finally return the dictionary with the app and the host name of the host\n return Apps\n\n def Detect_Applications_by_user(self):\n\n apps = []\n current_user = {}\n\n with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r\"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\", 0,\n (winreg.KEY_ALL_ACCESS)) as Subhkey:\n for p in range(0, winreg.QueryInfoKey(Subhkey)[0]):\n temp_app = {}\n argument = {}\n sub_key = winreg.EnumKey(Subhkey, p)\n app__sub_key = winreg.OpenKey(Subhkey, sub_key)\n try:\n app_name = self.avoid_exception(app__sub_key, 'DisplayName', 0)\n display_icon = self.avoid_exception(app__sub_key, 'DisplayIcon', 0)\n app_version = self.avoid_exception(app__sub_key, 'DisplayVersion', 0)\n publisher = self.avoid_exception(app__sub_key, 'Publisher', 0)\n help_link = self.avoid_exception(app__sub_key, 'HelpLink', 0)\n install_location = self.avoid_exception(app__sub_key, 'InstallLocation', 0)\n install_date = self.avoid_exception_Date(app__sub_key, 'InstallDate', 0)\n\n # Setting the values on the dict\n argument['Name'] = app_name\n argument['DisplayIcon'] = display_icon\n argument['Version'] = app_version\n argument['Publisher'] = publisher\n argument['Help_link'] = help_link\n argument['Install_location'] = install_location\n argument['Install_date'] = install_date\n argument['Architecture'] = None\n\n temp_app[sub_key] = argument\n\n apps.append(temp_app)\n except OSError as e:\n if e.errno == errno.ENOENT:\n # Display doesn't exist in this key\n pass\n Subhkey.Close()\n\n current_user[super().get_sid_current_account()] = apps\n\n return current_user\n\n def get_initial_state(self):\n information = []\n\n machine_information = {'machine_information': self._basic_information()}\n start_machine_default = {'Start_by_Default': self._run_key_by_default()}\n start_machine_by_user = {'_run_key_by_user': self._run_key_by_user()}\n users = {'_users': self._users()}\n rules = {'All_Firewall_Rules': self.Firewall_rules()}\n apps = {'Applications_by_default': self.Detect_Applications_by_default()}\n apps_user = {'Applications_by_user': self.Detect_Applications_by_user()}\n hostname = {'hostname':socket.gethostname()}\n\n information.append(hostname)\n information.append(machine_information)\n information.append(start_machine_default)\n information.append(start_machine_by_user)\n information.append(users)\n information.append(rules)\n information.append(apps)\n information.append(apps_user)\n\n platform_host= {sys.platform : information}\n json_info = {self.get_key(): platform_host}\n\n return json_info\n\n\n","sub_path":"visor/server/windows/registry/windows/windows.py","file_name":"windows.py","file_ext":"py","file_size_in_byte":10406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"409842885","text":"import pyttsx,pyowm\nengine = pyttsx.init()\nrate = engine.getProperty('rate')\nengine.setProperty('rate', rate-50)\nengine.say('Searching for weather data in varanasi.')\nengine.say('Please wait for processing of request')\n\nowm = pyowm.OWM('YOUR API KEY')\nobservation = owm.weather_at_place('Varanasi')\nw = observation.get_weather()\ncondition = w.get_status()\nmin_temp = w.get_temperature('celsius')['temp_min']\nmax_temp = w.get_temperature('celsius')['temp_max']\nhumidity = w.get_humidity()\nwind_speed=w.get_wind()['speed']\n\nweather_notes = \"Weather now is \"+str(condition)+\" with \"+str(humidity)+\" percent humidity\"\nweather_notes += \"\\n. The temperature is expected to lie between \"+str(min_temp)+\" and \"+str(max_temp)+\" degree celsius\"\nweather_notes += \", with a wind speed of \"+str(wind_speed)+\" meters per second\"\nweather_notes += \"\\n. Have a nice day sir\"\nengine.say(weather_notes)\nengine.runAndWait()\n\n","sub_path":"buffer/responses/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"294539631","text":"# Copyright (c) 2014, Adaptiv Design\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are 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 notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n\n# 3. Neither the name of the copyright holder nor the names of its contributors\n# may be used to endorse or promote products derived from this software without\n# specific prior written permission.\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport inspect\n\nfrom django.apps import apps\nfrom django.apps.registry import Apps\nfrom django.db import models\nfrom django.utils import six, lru_cache\n\nfrom sellmo.core.indexing.fields import (\n BooleanField, CharField, FloatField, IntegerField, DecimalField, ModelField\n)\nfrom sellmo.utils.convention import class_name_from_parts\n\nfrom .introspection import db_table_for_index\n\n\nINDEX_TO_DB_FIELDS = {\n BooleanField: lambda field_name, index_field: (models.NullBooleanField, [], {}),\n CharField: lambda field_name, index_field: (models.CharField, [], {\n 'max_length': index_field.max_length\n }),\n FloatField: lambda field_name, index_field: (models.FloatField, [], {}),\n IntegerField: lambda field_name, index_field: (models.IntegerField, [], {}),\n DecimalField: lambda field_name, index_field: (models.DecimalField, [], {\n # Introspection can't always resolve max_digits and decimal_places\n # (sqllite for instance)\n 'max_digits': index_field.max_digits if index_field.max_digits is not None else 10,\n 'decimal_places': index_field.decimal_places if index_field.decimal_places is not None else 2,\n }),\n ModelField: lambda field_name, index_field: (models.ForeignKey, [index_field.model], {\n # We can take advantage of database cascades\n # though other types of indexes won't have this.\n # However this adapter has been implemented to detect stale\n # records, and thus this behaviour is not required.\n # For concistency purposes, and since the impact is minimal,\n # disable cascading.'\n 'db_constraint': False,\n # Since we disable constraints, introspection can't lookup relations\n # thats why we keep track of the app_label, model_name in the column\n # name.\n 'db_column': '%s_id__%s__%s' % (field_name, index_field.model._meta.app_label, index_field.model._meta.model_name),\n })\n}\n\n\ndef db_field_for_index_field(field_name, index_field):\n db_field = None\n for typ in inspect.getmro(type(index_field)):\n if typ in INDEX_TO_DB_FIELDS:\n field_cls, args, kwargs = INDEX_TO_DB_FIELDS[type(index_field)](\n field_name, index_field\n )\n db_field = field_cls(\n *args, **dict(\n {\n 'null': True,\n 'db_index': True\n }, **kwargs\n )\n )\n break\n\n if db_field is None:\n raise TypeError(index_field)\n\n return db_field\n\n\nclass IndexModelApps(Apps):\n def __init__(self, *args, **kwargs):\n super(IndexModelApps, self).__init__(*args, **kwargs)\n self._models = []\n\n def register_model(self, app_label, model):\n self._models.append(model)\n\n @lru_cache.lru_cache(maxsize=None)\n def get_models(\n self,\n include_auto_created=False,\n include_deferred=False,\n include_swapped=False\n ):\n return self._models\n\n\nclass IndexModelFactory(object):\n def __init__(self):\n self.apps = IndexModelApps()\n\n def index_model(self, index, fields=None):\n model_name = class_name_from_parts(index.name, 'index')\n\n class Meta:\n apps = self.apps\n app_label = 'indexing'\n db_table = db_table_for_index(index)\n\n attrs = {'Meta': Meta, '__module__': '__fake__'}\n\n fields = index.fields if fields is None else fields\n for field_name, index_field in six.iteritems(fields):\n if not index_field.multi_value:\n db_field = db_field_for_index_field(field_name, index_field)\n attrs[field_name] = db_field\n\n model = type(model_name, (models.Model, ), attrs)\n related_models = {}\n\n for field_name, index_field in six.iteritems(fields):\n if index_field.multi_value:\n related_model = self.index_multi_value_field(\n index, model, field_name, index_field\n )\n\n related_models[field_name] = related_model\n\n return model, related_models\n\n def index_multi_value_field(\n self, index, index_model, field_name, index_field\n ):\n model_name = class_name_from_parts(index.name, 'index', field_name)\n\n class Meta:\n apps = self.apps\n app_label = 'indexing'\n db_table = db_table_for_index(index, field_name)\n\n attrs = {\n 'Meta': Meta,\n '__module__': '__fake__',\n 'index': models.ForeignKey(\n index_model,\n related_name=field_name\n ),\n 'value': db_field_for_index_field('value', index_field)\n }\n\n model = type(model_name, (models.Model, ), attrs)\n return model\n","sub_path":"sellmo/core/indexing/adapters/database/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"104282421","text":"from pyramid.authentication import CallbackAuthenticationPolicy, AuthTktCookieHelper, \\\n BasicAuthAuthenticationPolicy, AuthTktAuthenticationPolicy\n\nfrom pyramid_multiauth import MultiAuthenticationPolicy\nfrom pyramid.interfaces import IAuthenticationPolicy\n\nfrom c2cgeoportal_geoportal.resources import defaultgroupsfinder\nfrom zope.interface import implementer\nimport time\nimport math\n\nimport logging\n\nLOG = logging.getLogger(__name__)\n\ndef create_authentication(settings):\n timeout = settings.get(\"authtkt_timeout\")\n timeout = None if timeout is None else int(timeout)\n reissue_time = settings.get(\"reissue_time\")\n reissue_time = None if reissue_time is None else int(reissue_time)\n http_only = settings.get(\"authtkt_http_only\", \"True\")\n http_only = http_only.lower() in (\"true\", \"yes\", \"1\")\n secure = settings.get(\"authtkt_secure\", \"True\")\n secure = secure.lower() in (\"true\", \"yes\", \"1\")\n cookie_authentication_policy = AppAwareAuthTktAuthenticationPolicy(\n settings[\"authtkt_secret\"],\n callback=defaultgroupsfinder,\n cookie_name=settings[\"authtkt_cookie_name\"],\n timeout=timeout, max_age=timeout, reissue_time=reissue_time,\n hashalg=\"sha512\", http_only=http_only, secure=secure,\n parent_domain=True\n )\n basic_authentication_policy = BasicAuthAuthenticationPolicy(c2cgeoportal_check)\n policies = [cookie_authentication_policy, basic_authentication_policy]\n return MultiAuthenticationPolicy(policies)\n\n\ndef c2cgeoportal_check(username, password, request): # pragma: no cover\n if request.registry.validate_user(request, username, password):\n return defaultgroupsfinder(username, request)\n return None\n\n\n@implementer(IAuthenticationPolicy)\nclass AppAwareAuthTktAuthenticationPolicy(AuthTktAuthenticationPolicy):\n def remember(self, request, userid, **kw):\n \"\"\" Accepts the following kw args: ``max_age=,\n ``tokens=``.\n\n Return a list of headers which will set appropriate cookies on\n the response.\n\n \"\"\"\n is_app = request.params.get('app', 'false').lower() == 'true'\n if is_app:\n # Force any cookie to be set with a big expiration time\n # when login is done from the Android or iOS apps\n kw['max_age'] = math.ceil(time.time() + (10 * 365 * 24 * 60 * 60))\n\n return super().remember(request, userid, **kw)\n","sub_path":"geoportal/geoportailv3_geoportal/lib/lux_authentication.py","file_name":"lux_authentication.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"225116733","text":"from config import *\nimport random\nimport copy\n\nTYPE_AD = {\n NORMAL: { { NORMAL: 1 }, { FIGHT: 1 }, { FLYING: 1 }, { POISON: 1 }, { GROUND: 1 }, { ROCK: 0.5 }, { BUG: 1 }, { GHOST: 0 }, { FIRE: 1 }, { WATER: 1 }, { GRASS: 1 }, { ELECTRIC: 1 }, { PSYCHIC: 1 }, { ICE: 1 }, { DRAGON: 1 } },\n FIGHT: { { NORMAL: 2 }, { FIGHT: 1 }, { FLYING: 0.5 }, { POISON: 0.5 }, { GROUND: 1 }, { ROCK: 2 }, { BUG: 0.5 }, { GHOST: 0 }, { FIRE: 1 }, { WATER: 1 }, { GRASS: 1 }, { ELECTRIC: 1 }, { PSYCHIC: 0.5 }, { ICE: 2 }, { DRAGON: 1 } },\n FLYING: { { NORMAL: 1 }, { FIGHT: 2 }, { FLYING: 1 }, { POISON: 1 }, { GROUND: 1 }, { ROCK: 0.5 }, { BUG: 2 }, { GHOST: 1 }, { FIRE: 1 }, { WATER: 1 }, { GRASS: 2 }, { ELECTRIC: 0.5 }, { PSYCHIC: 1 }, { ICE: 1 }, { DRAGON: 1 } },\n POISON: { { NORMAL: 1 }, { FIGHT: 1 }, { FLYING: 1 }, { POISON: 0.5 }, { GROUND: 0.5 }, { ROCK: 0.5 }, { BUG: 2 }, { GHOST: 0.5 }, { FIRE: 1 }, { WATER: 1 }, { GRASS: 2 }, { ELECTRIC: 0.5 }, { PSYCHIC: 1 }, { ICE: 1 }, { DRAGON: 1 } },\n GROUND: { { NORMAL: 1 }, { FIGHT: 1 }, { FLYING: 0 }, { POISON: 2 }, { GROUND: 1 }, { ROCK: 2 }, { BUG: 0.5 }, { GHOST: 1 }, { FIRE: 2 }, { WATER: 1 }, { GRASS: 0.5 }, { ELECTRIC: 2 }, { PSYCHIC: 1 }, { ICE: 1 }, { DRAGON: 1 } },\n ROCK: { { NORMAL: 1 }, { FIGHT: 0.5 }, { FLYING: 2 }, { POISON: 1 }, { GROUND: 0.5 }, { ROCK: 1 }, { BUG: 2 }, { GHOST: 1 }, { FIRE: 2 }, { WATER: 1 }, { GRASS: 1 }, { ELECTRIC: 1 }, { PSYCHIC: 1 }, { ICE: 2 }, { DRAGON: 1 } },\n BUG: { { NORMAL: 1 }, { FIGHT: 0.5 }, { FLYING: 0.5 }, { POISON: 2 }, { GROUND: 1 }, { ROCK: 1 }, { BUG: 1 }, { GHOST: 0.5 }, { FIRE: 0.5 }, { WATER: 1 }, { GRASS: 2 }, { ELECTRIC: 1 }, { PSYCHIC: 1 }, { ICE: 1 }, { DRAGON: 1 } },\n GHOST: { { NORMAL: 0 }, { FIGHT: 1 }, { FLYING: 1 }, { POISON: 1 }, { GROUND: 1 }, { ROCK: 1 }, { BUG: 1 }, { GHOST: 2 }, { FIRE: 1 }, { WATER: 1 }, { GRASS: 1 }, { ELECTRIC: 1 }, { PSYCHIC: 0 }, { ICE: 1 }, { DRAGON: 1 } },\n FIRE: { { NORMAL: 1 }, { FIGHT: 1 }, { FLYING: 1 }, { POISON: 1 }, { GROUND: 1 }, { ROCK: 0.5 }, { BUG: 2 }, { GHOST: 1 }, { FIRE: 0.5 }, { WATER: 0.5 }, { GRASS: 2 }, { ELECTRIC: 1 }, { PSYCHIC: 1 }, { ICE: 2 }, { DRAGON: 0.5 } },\n WATER: { { NORMAL: 1 }, { FIGHT: 1 }, { FLYING: 1 }, { POISON: 1 }, { GROUND: 2 }, { ROCK: 2 }, { BUG: 1 }, { GHOST: 1 }, { FIRE: 2 }, { WATER: 0.5 }, { GRASS: 0.5 }, { ELECTRIC: 1 }, { PSYCHIC: 1 }, { ICE: 1 }, { DRAGON: 0.5 } },\n GRASS: { { NORMAL: 1 }, { FIGHT: 1 }, { FLYING: 0.5 }, { POISON: 0.5 }, { GROUND: 2 }, { ROCK: 2 }, { BUG: 0.5 }, { GHOST: 1 }, { FIRE: 0.5 }, { WATER: 2 }, { GRASS: 0.5 }, { ELECTRIC: 1 }, { PSYCHIC: 1 }, { ICE: 1 }, { DRAGON: 0.5 } },\n ELECTRIC: { { NORMAL: 1 }, { FIGHT: 1 }, { FLYING: 2 }, { POISON: 1 }, { GROUND: 0 }, { ROCK: 1 }, { BUG: 1 }, { GHOST: 1 }, { FIRE: 1 }, { WATER: 2 }, { GRASS: 0.5 }, { ELECTRIC: 1 }, { PSYCHIC: 1 }, { ICE: 1 }, { DRAGON: 0.5 } },\n PSYCHIC: { { NORMAL: 1 }, { FIGHT: 2 }, { FLYING: 1 }, { POISON: 2 }, { GROUND: 1 }, { ROCK: 1 }, { BUG: 1 }, { GHOST: 1 }, { FIRE: 1 }, { WATER: 1 }, { GRASS: 1 }, { ELECTRIC: 1 }, { PSYCHIC: 0.5 }, { ICE: 1 }, { DRAGON: 1 } },\n ICE: { { NORMAL: 1 }, { FIGHT: 1 }, { FLYING: 2 }, { POISON: 1 }, { GROUND: 2 }, { ROCK: 1 }, { BUG: 1 }, { GHOST: 1 }, { FIRE: 1 }, { WATER: 0.5 }, { GRASS: 2 }, { ELECTRIC: 1 }, { PSYCHIC: 1 }, { ICE: 0.5 }, { DRAGON: 2 } },\n DRAGON: { { NORMAL: 1 }, { FIGHT: 1 }, { FLYING: 1 }, { POISON: 1 }, { GROUND: 1 }, { ROCK: 1 }, { BUG: 1 }, { GHOST: 1 }, { FIRE: 1 }, { WATER: 1 }, { GRASS: 1 }, { ELECTRIC: 1 }, { PSYCHIC: 1 }, { ICE: 1 }, { DRAGON: 2 } },\n}\n\nclass BattleManager:\n\n def __init__(self, player, res):\n self.player = player\n self.res = res\n\n self.curr_pokemon = player.party[0]\n self.enemy_pokemon = None\n\n self.escape_attempts = 0\n\n def start_battle(self, battle_type):\n self.curr_pokemon = self.player.party[0]\n self.enemy_pokemon = None\n\n self.escape_attempts = 0\n\n if battle_type == WILD_POKEMON_BATTLE:\n self.generate_wild_pokemon()\n\n def generate_wild_pokemon(self):\n rarity = random.random()\n if rarity <= VERY_COMMON_THRESHOLD:\n self.enemy_pokemon = copy.copy(random.choice(self.res.pokedex_rarity[VERY_COMMON]))\n elif rarity <= COMMON_THRESHOLD:\n self.enemy_pokemon = copy.copy(random.choice(self.res.pokedex_rarity[COMMON]))\n elif rarity <= RARE_THRESHOLD:\n self.enemy_pokemon = copy.copy(random.choice(self.res.pokedex_rarity[RARE]))\n elif rarity <= VERY_RARE_THRESHOLD:\n self.enemy_pokemon = copy.copy(random.choice(self.res.pokedex_rarity[VERY_RARE]))\n elif rarity <= LEGENDARY_THRESHOLD:\n self.enemy_pokemon = copy.copy(random.choice(self.res.pokedex_rarity[LEGENDARY]))\n\n if self.enemy_pokemon.wild == LEGENDARY:\n self.enemy_pokemon.set_level(self.enemy_pokemon.default_level)\n else:\n level_range = self.player.get_level() \\\n if self.player.get_level() - WILD_POKEMON_RANGE < 0 \\\n else WILD_POKEMON_RANGE\n\n self.enemy_pokemon.set_level(self.player.get_level() - random.randint(0, level_range - 1))\n\n def move_available(self, move):\n return move.pp != 0\n\n def should_struggle(self, pokemon):\n for move in pokemon.moveset:\n if move.pp != 0: return False\n return True\n\n # true - player, false - enemy\n def moves_first(self):\n return self.curr_pokemon.speed > self.enemy_pokemon.speed\n\n def move_hit(self, move):\n if move.accuracy == 100: return True\n return random.randint(0, 100) < move.accuracy\n\n def can_run(self):\n self.escape_attempts += 1\n a = self.curr_pokemon.speed\n b = (self.enemy_pokemon.speed / 4) % 256\n if b == 0: return True\n f = (a * 32 / b) + 30 * self.escape_attempts\n\n if f > 255:\n return True\n else:\n return random.uniform(0, 255) < f","sub_path":"battle/battle_manager.py","file_name":"battle_manager.py","file_ext":"py","file_size_in_byte":5997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"287046572","text":"import random\r\nfrom scipy.spatial import distance\r\ndef euc(a, b):\r\n\treturn distance.euclidean(a,b)\r\nclass MyKNN():\r\n\tdef fit(self, x_train, y_train):\r\n\t\tself.x_train= x_train\r\n\t\tself.y_train= y_train\r\n\tdef predict(self, x_test):\r\n\t\tpredictions = []\r\n\t\tfor row in x_test:\r\n\t\t\tlabel = self.closest(row)\r\n\t\t\tpredictions.append(label)\r\n\t\treturn predictions\r\n\tdef closest(self, row):\r\n\t\tbest_dist = euc(row, self.x_train[0])\r\n\t\tbest_index=0\r\n\t\tfor i in range(1, len(self.x_train)):\r\n\t\t\tdist = euc(row, self.x_train[i])\r\n\t\t\tif dist < best_dist:\r\n\t\t\t\tbest_dist= dist\r\n\t\t\t\tbest_index= i\r\n\t\treturn self.y_train[best_index]\r\nfrom sklearn import datasets\r\nbreast_cancer = datasets.load_breast_cancer()\r\nx=breast_cancer.data\r\ny=breast_cancer.target\r\nfrom sklearn.cross_validation import train_test_split\r\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.5)\r\nmy_clf=MyKNN()\r\nmy_clf.fit(x_train,y_train)\r\npredictions=my_clf.predict(x_test)\r\nfrom sklearn.metrics import accuracy_score\r\nprint(accuracy_score(y_test,predictions))\r\n","sub_path":"breast_cancer_dataset_ownKNN.py","file_name":"breast_cancer_dataset_ownKNN.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"640064686","text":"(x,y) = build_lists(population,vim_index,ecad_index)\n\n# plot\necad_base_index,vim_base_index = 12,13\n\n(xbase,ybase) = build_lists(population,vim_base_index,ecad_base_index)\n\nplt.plot(xbase,ybase,\"o\",color=\"lightgray\")\n\nplt.hold(True)\nplt.plot(x,y,\"o\",color='black')\nplt.hold(False)\n\n#plt.plot(x,y,\"o\",color='darkgray')\n#plt.plot(x,y,\"o\")\n\n#plt.title(title)\n\nxmin,xmax = 0,400\nymin,ymax = 0,400\n\n#loglog\n#xmin,xmax = 0.001,500\n#ymin,ymax = 00.001,500\n\nax = plt.gca()\nax.set_ylim(ymin=ymin)\nax.set_xlim(xmin=xmin)\nax.set_ylim(ymax=ymax)\nax.set_xlim(xmax=xmax)\n\nif current_panel in [1,2,3]:\n ax.set_ylabel(ylab)\n\nif current_panel in [3,6]:\n ax.set_xlabel(xlab)\n\n\n\nplt.text(figlab_x, figlab_y, figlab,fontweight='bold',\n horizontalalignment='left', verticalalignment='top',\n fontsize=32,\n transform = ax.transAxes)\n\n\n\n \n#plt.axhline(y=1,color='black')\n#plt.axvline(x=1,color='black')\n\n# Title\ntexty = 0.9\na = 0.00\n#if title==u'TGF${\\\\beta}$12 + VEGFA \\n+ VIVIT':\n# a = 0.08\n\nplt.text(0.7, texty-a, title,\n horizontalalignment='left', verticalalignment='top',\n fontsize=32,\n transform = ax.transAxes)\n\n\n# Label epithelial quadrant \n#plt.text(0.02, texty,\"Epithelial\",\n# horizontalalignment='left',\n# fontsize=28,\n# transform = ax.transAxes)\n\n# Label mesenchymal quadrant \n#plt.text(0.7, 0.1, \"Mesenchymal\",\n# horizontalalignment='left',\n# fontsize=28,\n# transform = ax.transAxes)\n\n#r1=plt.Rectangle( (xmin,1), 1-xmin,ymax ,color='gray',alpha=0.2,zorder=1)\n#r2=plt.Rectangle( (1,ymin), xmax,1-ymin ,color='orange',alpha=0.2,zorder=1)\n\n\n#ax.add_patch(r1)\n#ax.add_patch(r2)\n\n# \n\n\nplt.xticks(np.arange(xmin, xmax+1, 100))\nplt.yticks(np.arange(ymin, ymax+1, 100))\n \n\nplt.rcParams.update({'font.size': 32})\nplt.tight_layout(pad=0.2, w_pad=0.5, h_pad=1.0)\n\ncurrent_panel = current_panel + 1 \n","sub_path":"Results/scatter_abundance.py","file_name":"scatter_abundance.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"11982088","text":"import os\nimport sys\n\nREPO_DIRECTORY = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(REPO_DIRECTORY)\n\nimport inspect\nimport secrets\nfrom flask import request, redirect\nimport functools\nfrom datetime import datetime\nfrom config import TOKEN_TIMEOUT_HOURS\n\n\nclass TokenHandler:\n \"\"\"\n Class for handling tokens of logged in users\n\n Attributes\n ----------\n tokens : (dict of dicts)\n Dict of recognized tokens\n keys: last_contact (datetime), user_id (str)\n\n Methods\n -------\n gen_token(user_id)\n Generate token and save to tokens dict\n auth_token(token)\n Auth token and update time if valid\n auth_request(func) - Decorator\n Auth request from user cookie\n \"\"\"\n\n def __init__(self,\n tokens=None):\n \"\"\"\n Init token handler\n\n :param tokens: (dict of dicts) Dict of recognized tokens\n keys: last_contact (datetime), user_id (str)\n \"\"\"\n\n self.tokens = tokens or {}\n\n\n def gen_token(self,\n user_info):\n \"\"\"\n Generate token and save to tokens dict\n\n :return: (str) token\n \"\"\"\n\n user_info['last_contact'] = datetime.now()\n\n token = secrets.token_hex()\n self.tokens[token] = user_info\n\n return token\n\n\n def auth_token(self,\n token):\n \"\"\"\n Auth token and update time if valid\n\n :return: (dict or None) user_info dict if authorized, None if not\n \"\"\"\n\n user_info = self.tokens.get(token, {})\n token_time = user_info.get('last_contact', None)\n\n if not token_time:\n return None\n\n time_diff = (datetime.now() - token_time).total_seconds()/3600\n if time_diff > TOKEN_TIMEOUT_HOURS:\n self.tokens.pop(token, None)\n return None\n\n self.tokens[token]['last_contact'] = datetime.now()\n\n return user_info\n\n\n def auth_request(self,\n func):\n \"\"\"\n Decorator: Auth request from user cookie\n\n Redirects to login or continues to desired server func (page)\n \"\"\"\n\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n user_token = request.cookies.get('soulwings', '')\n user_info = self.auth_token(user_token)\n\n if user_info:\n prms = list(inspect.signature(func).parameters)\n if 'user_info' in prms:\n kwargs['user_info'] = user_info\n return func(*args, **kwargs)\n\n else:\n return redirect('/login')\n\n return wrapper\n","sub_path":"sw_app/TokenHandler.py","file_name":"TokenHandler.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"643568055","text":"from time import sleep\nfrom RPi import GPIO\nfrom ultra import *\nfrom servo import *\nfrom ESC import *\n\ntrg_pin = 15\nech_pin = 13\nsrv_pin = 11\nesc_pin = 7\n\ntry:\n GPIO.setwarnings(False)\n GPIO.setmode(GPIO.BOARD)\n srv = Servo(srv_pin)\n esc = ESC(esc_pin)\n ult = Ultra(trg_pin, ech_pin)\n sleep(3)\n '''\n esc.start()\n sleep(2)\n esc.stop()\n '''\n while True:\n srv.left()\n sleep(2)\n srv.right()\n sleep(2)\n srv.straight()\n sleep(2)\nexcept KeyboardInterrupt:\n pass\nfinally:\n print()\n GPIO.cleanup()","sub_path":"car/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"313851194","text":"from Common import Request, Assert, read_excel, Login\nimport allure\nimport pytest\n\nrequest = Request.Request()\nassertion = Assert.Assertions()\n\nidsList=[]\n\nexcel_list = read_excel.read_excel_list('./document/youhuiquan.xlsx')\nlength = len(excel_list)\nfor i in range(length):\n idsList.append(excel_list[i].pop())\n\nurl = 'http://192.168.1.137:8080/'\nhead = {}\nitem_id=0\n\n@allure.feature('优惠券模块')\nclass Test_yhq:\n\n @allure.story('查询优惠券列表')\n def test_get_yhq_list(self):\n global head\n head = Login.Login().get_token()\n get_yhq_list_resp = request.get_request(url=url + 'coupon/list', params={'pageNum': 1, 'pageSize': 10}, headers=head)\n resp_json = get_yhq_list_resp.json()\n json_data = resp_json['data']\n data_list = json_data['list']\n item = data_list[0]\n global item_id\n item_id = item['id']\n assertion.assert_code(get_yhq_list_resp.status_code, 200)\n assertion.assert_in_text(resp_json['message'], '成功')\n\n\n @allure.story('删除优惠券')\n def test_del_yhq(self):\n del_resp = request.post_request(url=url + 'coupon/delete/' + str(item_id), headers=head)\n resp_json = del_resp.json()\n assertion.assert_code(del_resp.status_code, 200)\n assertion.assert_in_text(resp_json['message'], '成功')\n\n @allure.story('批量添加优惠券')\n @pytest.mark.parametrize(\"name,amount,minPoint,publishCount,msg\",excel_list,ids=idsList)\n def test_add_yhq_list(self,name,amount,minPoint,publishCount,msg):\n json={\"type\":0,\"name\":name,\"platform\":0,\"amount\":amount,\"perLimit\":1,\"minPoint\":minPoint,\"startTime\":\"2019-03-31T16:00:00.000Z\",\n \"endTime\":\"2019-04-16T16:00:00.000Z\",\"useType\":0,\"note\":\"\",\"publishCount\":publishCount,\"productRelationList\":[],\n \"productCategoryRelationList\":[]}\n add_resp = request.post_request(url=url + 'coupon/create', json=json, headers=head)\n resp_json = add_resp.json()\n assertion.assert_code(add_resp.status_code, 200)\n assertion.assert_in_text(resp_json['message'], msg)\n","sub_path":"TestCase/test_youhuiquan.py","file_name":"test_youhuiquan.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"221590222","text":"import os\nimport unittest\n\nfrom carball import decompile_replays\n\nOUTPUT_DIR = os.path.join('..', 'replays', 'pickled')\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\n\nclass DBTest(unittest.TestCase):\n def setUp(self):\n if not os.path.isdir(OUTPUT_DIR):\n os.makedirs(OUTPUT_DIR)\n\n replays_folder = os.path.join(BASE_DIR, 'replays')\n for filename in [f for f in os.listdir(replays_folder) if os.path.isfile(os.path.join(replays_folder, f))]:\n filepath = 'replays/' + filename\n print(filepath)\n output = 'replays/decompiled/{}'.format(filepath.replace(\".replay\", \".json\"))\n self.g = decompile_replays.decompile_replay(filepath, output)\n break\n\n def test_replay_attrs(self):\n self.assertIsNotNone(self.g.api_game.name)\n self.assertIsNotNone(self.g.api_game.map)\n self.assertIsNotNone(self.g.api_game.id)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"carball/tests/db_test.py","file_name":"db_test.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"227433575","text":"# -*- coding: utf-8 -*-\n# Notice: Change time before usage!\n# Note with Tstart, cannot get the latest data!\nTEST='True'\n \nif TEST=='True':\n code_test='603993'\n# Tstart=''\n# Tend=''\n Tstart='2015-11-16'\n Tend='2018-01-17'\n\n\"\"\"\nCreated on Sun Aug 27 00:39:55 2017\n@author: Guanglin Kuang\n\"\"\"\n#Reference1: http://tushare.org/classifying.html\n#Reference2: http://www.waditu.cn/trading.html#id3\n\nimport tushare as ts\nimport pandas as pd\nimport numpy as np\nimport datetime\nimport time\nimport matplotlib.pyplot as plt\nplt.rcParams['font.sans-serif']=['SimHei']\n\n##### First Part:\n##### Definition of the functions.\n\n#################Definition for simple moving average (SMA)#################################\ndef CalSMA(Close,k):\n SMA=pd.Series(0.0, index=Close.index)\n for i in range(k-1,len(Close)):\n SMA[i]=sum(Close[(i-k+1):(i+1)]/k)\n return SMA\n\ndef EWMACal(Close, period, expo):\n EWMA=pd.Series(0.0, index=Close.index)\n EWMA[period-1]=np.mean(Close[:period])\n for i in range(period, len(Close)):\n EWMA[i]=expo*Close[i]+(1-expo)*EWMA[i-1]\n return EWMA\n\n###############################Definition for Wu Lian Yang##################################\ndef WuLianYang(Open, Close, High, Low, Signal):\n for i in range(len(Close)-10, len(Close)-5):\n Yang=[]\n incr=[]\n Kincrease1=(Close[i+1]-Close[i])/Close[i]\n Kvibrate1=(High[i+1]-Low[i+1])/Low[i+1]\n Kextend1=(Close[i+1]-Open[i+1])/Open[i+1]\n if all([Kincrease1 >= 0, Kincrease1 < 0.03, Kvibrate1 < 0.05, Kextend1 > -0.005]):\n Yang.append(1)\n \n Kincrease2=(Close[i+2]-Close[i+1])/Close[i+1]\n Kvibrate2=(High[i+2]-Low[i+2])/Low[i+2]\n Kextend2=(Close[i+2]-Open[i+2])/Open[i+2]\n if all([Kincrease2 >= 0, Kincrease2 < 0.03, Kvibrate2 < 0.05, Kextend2 > -0.005]):\n Yang.append(1)\n if Low[i+2] >= Low[i+1]:\n incr.append(1)\n \n Kincrease3=(Close[i+3]-Close[i+2])/Close[i+2]\n Kvibrate3=(High[i+3]-Low[i+3])/Low[i+3]\n Kextend3=(Close[i+3]-Open[i+3])/Open[i+3]\n if all([Kincrease3 >= 0, Kincrease3 < 0.03, Kvibrate3 < 0.05, Kextend3 > -0.005]):\n Yang.append(1)\n if Low[i+3] >= Low[i+2]:\n incr.append(1)\n \n Kincrease4=(Close[i+4]-Close[i+3])/Close[i+3]\n Kvibrate4=(High[i+4]-Low[i+4])/Low[i+4]\n Kextend4=(Close[i+4]-Open[i+4])/Open[i+4]\n if all([Kincrease4 >= 0, Kincrease4 < 0.03, Kvibrate4 < 0.05, Kextend4 > -0.005]):\n Yang.append(1)\n if Low[i+4] >= Low[i+3]:\n incr.append(1)\n \n Kincrease5=(Close[i+5]-Close[i+4])/Close[i+4]\n Kvibrate5=(High[i+5]-Low[i+5])/Low[i+5]\n Kextend5=(Close[i+5]-Open[i+5])/Open[i+5]\n if all([Kincrease5 >= 0, Kincrease5 < 0.03, Kvibrate5 < 0.05, Kextend5 > -0.005]):\n Yang.append(1)\n if Low[i+5] >= Low[i+4]:\n incr.append(1)\n \n if all([len(Yang) >= 3, len(incr) >=2, (Close[i+5]-Close[i+1])/Close[i+1] > 0.01, \\\n Kincrease1 > -0.02, Kincrease1 < 0.03, Kvibrate1 < 0.06, Kextend1 > -0.02, Kextend1 < 0.03, \\\n Kincrease2 > -0.02, Kincrease2 < 0.03, Kvibrate2 < 0.06, Kextend2 > -0.02, Kextend2 < 0.03, \\\n Kincrease3 > -0.02, Kincrease3 < 0.03, Kvibrate3 < 0.06, Kextend3 > -0.02, Kextend3 < 0.03, \\\n Kincrease4 > -0.02, Kincrease4 < 0.03, Kvibrate4 < 0.06, Kextend4 > -0.02, Kextend4 < 0.03, \\\n Kincrease5 > -0.02, Kincrease5 < 0.03, Kvibrate5 < 0.06, Kextend5 > -0.02, Kextend5 < 0.03]):\n Signal[i+5]=1 \n\n#####################################Definition for Jin Cha###########################################\ndef JinCha(Close, SMA20, SMA120, Signal):\n for i in range(len(Close)-10,len(Close)):\n if all([abs(SMA20[i]-SMA120[i])/SMA120[i] < 0.005, \\\n SMA20[i] >= SMA20[i-1], \n SMA120[i] >= SMA120[i-1], \\\n Close[i] >= SMA20[i], Close[i] >= SMA120[i]]):\n Signal[i]=1\n\n#######################################Definition for MA Duo Tou#####################################\ndef DuoTou(Close, SMA5, SMA10, SMA20,SMA60, SMA120, SMA250, Signal):\n for i in range(len(Close)-10,len(Close)-3):\n if all([Close[i] >= SMA5[i], (Close[i]-SMA5[i])/SMA5[i] < 0.1, \\\n Close[i] >= SMA10[i], (Close[i]-SMA10[i])/SMA10[i] < 0.12, \\\n Close[i] >= SMA20[i], (Close[i]-SMA20[i])/SMA20[i] < 0.15, \\\n Close[i] >= SMA60[i], (Close[i]-SMA60[i])/SMA60[i] < 0.2, \\\n Close[i] >= SMA120[i], (Close[i]-SMA120[i])/SMA120[i] < 0.25, \\\n Close[i] >= SMA250[i], (Close[i]-SMA250[i])/SMA250[i] < 0.3, \\\n (Close[i+1]-Close[i])/Close[i] > -0.05, \\\n (Close[i+2]-Close[i])/Close[i] > -0.05, \\\n (Close[i+3]-Close[i])/Close[i] > -0.05]):\n Signal[i+3]=1\n\n#Important!\n#####################################Definition for K Tu Pou#########################################\ndef TuPou(Close, Volume, Signal):\n for i in range(len(Close)-10,len(Close)-2):\n Kchange1=(Close[i+1]-Close[i])/Close[i]\n Vchange1=(Volume[i+1]-Volume[i])/Volume[i]\n Kchange2=(Close[i+2]-Close[i+1])/Close[i+1]\n \n if all([Kchange1 >= 0.035, Vchange1 >= 0.2 , Kchange2 >= -0.02]):\n Signal[i+2] = 1\n \n####################################Definition for Zhang Ting#######################################\ndef ZhangTing(Close, Signal):\n for i in range(len(Close)-30,len(Close)-1): \n if all([(Close[i]-Close[i-1])/Close[i-1] > 0.095, \\\n (Close[i+1]-Close[i])/Close[i] < 0.095]):\n Signal[i+1] = 1\n\n#######################################Duo Fang Xin Hao#####################################\ndef DuoFangXinHao(Open, Close, High, Low, Signal):\n for i in range(len(Close)-10, len(Close)-3):\n Kchange1=(Close[i+1]-Close[i])/Close[i]\n Kextend1=(Close[i+1]-Open[i+1])/Open[i+1]\n Kvibrate1=(High[i+1]-Low[i+1])/Low[i+1]\n \n Kchange2=(Close[i+2]-Close[i+1])/Close[i+1]\n Kextend2=(Close[i+2]-Open[i+2])/Open[i+2]\n\n Kchange3=(Close[i+3]-Close[i+2])/Close[i+2]\n Kextend3=(Close[i+3]-Open[i+3])/Open[i+3]\n \n # Duo Fang Pao \n if all([Kchange1 < -0.03, Kextend1 < -0.03, Kextend2 > 0.03]):\n Signal[i+2] = 1\n \n # Shang Zhang Bao Xian\n if all([Kchange1 < -0.02, Kextend1 > -0.03, Kextend1 < 0.01, Kvibrate1 < 0.05, \\\n (Open[i+2]-Low[i+1])/Low[i+1] < -0.01, (Close[i+2]-High[i+1])/High[i+1] > 0.01, \\\n Kchange2 > 0.01, Kextend2 > 0.03]):\n Signal[i+2] = 1\n \n # Chui Zi Xian\n com=min(Open[i+2], Close[i+2])\n if all([(Low[i+2]-com)/com < -0.03, \\\n Low[i+2] < Low[i+1], \\\n Low[i+3] > Low[i+2]]):\n Signal[i+3] = 1\n\n # Zao Chen Zhi Xin\n if all([Kchange1 < -0.03, Kextend1 < -0.03, \\\n Kchange2 > -0.02, Kchange2 < 0.01, abs(Kextend2) < 0.02,\\\n Kchange3 > 0.03, Kextend3 > 0.03]):\n Signal[i+3]=1\n\n # TiaoKong\n if all([(Low[i+3]-High[i+2])/High[i+2] > 0.01, \\\n (Low[i+3]-High[i+2])/High[i+2] < 0.99]):\n Signal[i+3] = 1\n\n####################################Definition for Wen Jian#######################################\ndef WenJian(Close, SMA5, Signal):\n for i in range(len(Close)-10, len(Close)-4):\n Yang=[]\n incr=[]\n\n if Close[i+1] >= SMA5[i+1]:\n Yang.append(1)\n if Low[i+1] >= SMA5[i+1]:\n incr.append(1)\n\n if Close[i+2] >= SMA5[i+2]:\n Yang.append(1)\n if Low[i+2] >= SMA5[i+2]:\n incr.append(1)\n \n if Close[i+3] >= SMA5[i+3]:\n Yang.append(1)\n if Low[i+3] >= SMA5[i+3]:\n incr.append(1)\n\n if Close[i+4] >= SMA5[i+4]:\n Yang.append(1)\n if Low[i+4] >= SMA5[i+4]:\n incr.append(1) \n\n if all([len(Yang) >= 3, len(incr) >=2]):\n Signal[i+4]=1 \n\n#MACD is most important!\ndef MACD(Close, DIFF, DEA, Signal): \n #Di Wei Jin Cha\n for i in range(len(Close)-10, len(Close)-1): \n if all([DIFF[i]<= DEA[i], DIFF[i]<1.0, DIFF[i+1]>=DEA[i+1]]):\n Signal[i+1]=1\n \n #Chuan Guo 0 Zhou\n for i in range(len(Close)-10, len(Close)-2):\n if all([DEA[i+1]<=0, DEA[i+2]>=0]):\n Signal[i+2]=1\n\n #Jiang Cha Wei Cha\n for i in range(len(Close)-10, len(Close)-2):\n if all([DIFF[i]>=DEA[i], DIFF[i+1]<=DIFF[i], DIFF[i+1]<=DIFF[i+2], \\\n abs(DIFF[i+1]-DEA[i+1])<=0.1, DIFF[i+2] >= DEA[i+2], \\\n DEA[i]<=DEA[i+1], DEA[i+1]<=DEA[i+2]]):\n Signal[i+2]=1 \n\n # Nianhe\n for i in range(len(Close)-10, len(Close)-5):\n Yang=[]\n incr=[]\n\n if abs(DIFF[i+1]-DEA[i+1])<=0.1:\n Yang.append(1)\n if (DIFF[i+1]-DEA[i+1])>=0 and (DIFF[i+1]-DEA[i+1])<=0.1:\n incr.append(1) \n\n if abs(DIFF[i+2]-DEA[i+2])<=0.1:\n Yang.append(1)\n if (DIFF[i+2]-DEA[i+2])>=0 and (DIFF[i+2]-DEA[i+2])<=0.1:\n incr.append(1) \n\n if abs(DIFF[i+3]-DEA[i+3])<=0.1:\n Yang.append(1) \n if (DIFF[i+3]-DEA[i+3])>=0 and (DIFF[i+3]-DEA[i+3])<=0.1:\n incr.append(1) \n\n if abs(DIFF[i+4]-DEA[i+4])<=0.1:\n Yang.append(1)\n if (DIFF[i+4]-DEA[i+4])>=0 and (DIFF[i+4]-DEA[i+4])<=0.1:\n incr.append(1) \n\n if abs(DIFF[i+5]-DEA[i+5])<=0.1:\n Yang.append(1) \n if (DIFF[i+5]-DEA[i+5])>=0 and (DIFF[i+5]-DEA[i+5])<=0.1:\n incr.append(1) \n \n if all([len(Yang) >=4, len(incr) >=3]):\n Signal[i+5]=1 \n\ndef DKDJ(Close):\n #Dayly KDJ.\n dates=Close.index.to_series()\n \n periodHigh=pd.Series(np.zeros(len(Close)), index=Close.index)\n periodLow=pd.Series(np.zeros(len(Close)), index=Close.index)\n RSV=pd.Series(np.zeros(len(Close)), index=Close.index)\n\n for i in range(len(Close)-50, len(Close)):\n period=dates[i-8:i+1]\n periodHigh[i]=High[period].max()\n periodLow[i]=Low[period].min()\n RSV[i]=100*(Close[i]-periodLow[i])/(periodHigh[i]-periodLow[i])\n \n KValue=pd.Series(50.0,index=Close.index)\n for i in range(len(Close)-50,len(Close)):\n KValue[i]=2.0/3*KValue[i-1]+1.0/3*RSV[i]\n \n DValue=pd.Series(50.0,index=RSV.index)\n for i in range(len(Close)-50,len(RSV)):\n DValue[i]=2.0/3*DValue[i-1]+1.0/3*KValue[i]\n \n if all([DValue[-2] <= DValue[-1], KValue[-1] >= DValue[-1]]):\n return True\n else:\n return False\n\ndef WKDJ(code):\n #Weekly KDJ.\n try:\n if TEST=='True':\n stock2=ts.get_k_data(code, ktype = 'W', start=Tstart, end=Tend)\n else:\n stock2=ts.get_k_data(code, ktype = 'W')\n except:\n time.sleep(1)\n if TEST=='True':\n stock2=ts.get_k_data(code, ktype = 'W', start=Tstart, end=Tend)\n else:\n stock2=ts.get_k_data(code, ktype = 'W')\n\n stock2.index=stock2.iloc[:,0]\n stock2.index=pd.to_datetime(stock2.index,format='%Y-%m-%d')\n stock2=stock2.iloc[:,1:-1]\n Close2=stock2.close\n \n dates2=Close2.index.to_series() \n periodHigh=pd.Series(np.zeros(len(Close2)), index=Close2.index)\n periodLow=pd.Series(np.zeros(len(Close2)), index=Close2.index)\n RSV=pd.Series(np.zeros(len(Close2)), index=Close2.index)\n\n for i in range(len(Close2)-50, len(Close2)):\n period=dates2[i-8:i+1]\n periodHigh[i]=High[period].max()\n periodLow[i]=Low[period].min()\n RSV[i]=100*(Close2[i]-periodLow[i])/(periodHigh[i]-periodLow[i])\n \n KValue=pd.Series(50.0,index=Close2.index)\n for i in range(len(Close2)-50,len(Close2)):\n KValue[i]=2.0/3*KValue[i-1]+1.0/3*RSV[i]\n \n DValue=pd.Series(50.0,index=RSV.index)\n for i in range(len(Close2)-50,len(RSV)):\n DValue[i]=2.0/3*DValue[i-1]+1.0/3*KValue[i]\n\n if all([DValue[-2] <= DValue[-1], KValue[-1] >= DValue[-1]]):\n return True\n else:\n return False\n \n##### Second Part:\n##### Process all the stocks one by one\nstock_info=ts.get_stock_basics()\ncodes=sorted(list(stock_info.index))\n\ntoday=datetime.date.today().strftime('%Y-%m-%d')\nfo=open('Stocks-%s.txt' % today,'w')\n \nM=0\n\nif TEST=='True':\n codes=[]\n codes.append(code_test)\n \nfor code in codes: \n M+=1\n print(M)\n \n if float(stock_info.loc[stock_info.index==code].pe) > 200:\n continue\n elif float(stock_info.loc[stock_info.index==code].pb) > 15:\n continue\n elif float(stock_info.loc[stock_info.index==code].esp) < 0:\n continue\n elif float(stock_info.loc[stock_info.index==code].perundp) < 0:\n continue\n elif float(stock_info.loc[stock_info.index==code].rev) < -20:\n continue\n elif float(stock_info.loc[stock_info.index==code].profit) < -20:\n continue\n\n# elif float(stock_info.loc[stock_info.index==code].gpr) < 15:\n# continue\n# elif float(stock_info.loc[stock_info.index==code].npr) < 0:\n# continue \n\n try:\n if TEST=='True':\n stock=ts.get_k_data(code, start=Tstart, end=Tend)\n else:\n stock=ts.get_k_data(code)\n except:\n time.sleep(1)\n if TEST=='True':\n stock=ts.get_k_data(code, start=Tstart, end=Tend)\n else:\n stock=ts.get_k_data(code)\n\n if len(stock) < 250:\n continue\n\n stock.index=stock.iloc[:,0]\n stock.index=pd.to_datetime(stock.index,format='%Y-%m-%d')\n stock=stock.iloc[:,1:-1]\n Open=stock.open\n Close=stock.close\n High=stock.high\n Low=stock.low\n Volume=stock.volume \n\n###Main filter 1:\n DIFF=EWMACal(Close,12,2.0/(1+12)) - EWMACal(Close,26,2.0/(1+26))\n DEA=EWMACal(DIFF,9,2.0/(1+9))\n\n if not all([(round(DIFF[-2],2) <= round(DIFF[-1],2) \\\n or round(DEA[-2],2) <= round(DEA[-1],2)), \\\n DEA[-1]>=-0.5, DEA[-1]<=5.0]):\n continue\n \n###Main filter 2:\n SMA20=CalSMA(Close,20)\n SMA250=CalSMA(Close,250)\n if not all([round(Close[-1],2) >= round(SMA20[-1],2), round(SMA20[-2],2) <= round(SMA20[-1],2), \\\n round(Close[-1],2) >= round(SMA250[-1],2), round(SMA250[-4],2) <= round(SMA250[-1],2)]):\n continue\n\n###Delicate filters:\n Max=max(Close)\n Min=min(Close) \n \n SMA5=CalSMA(Close,5)\n SMA10=CalSMA(Close,10)\n SMA60=CalSMA(Close,60)\n SMA120=CalSMA(Close,120)\n\n if not all([(Close[-1]-SMA10[-1])/SMA10[-1] >= -0.05, (Close[-1]-SMA10[-1])/SMA10[-1] <= 0.1, \\\n round(SMA10[-2],2) <= round(SMA10[-1],2), \\\n round(SMA60[-2],2) <= round(SMA60[-1],2), \\\n round(SMA120[-3],2) <= round(SMA120[-1],2), \\\n (Close[-1]-SMA20[-1])/SMA20[-1] >= 0, (Close[-1]-SMA20[-1])/SMA20[-1] <= 0.2, \\\n (Close[-1]-SMA60[-1])/SMA60[-1] >= 0, (Close[-1]-SMA60[-1])/SMA60[-1] <= 0.3, \\\n (max(Close[-10:])-min(Close[-10:]))/min(Close[-10:]) <= 0.3, \\\n (max(Close[-60:])-min(Close[-60:]))/min(Close[-60:]) <= 0.6]):\n continue\n\n Signal=pd.Series(0,index=Close.index)\n WuLianYang(Open, Close, High, Low, Signal)\n JinCha(Close, SMA20, SMA120, Signal)\n DuoTou(Close, SMA5, SMA10, SMA20,SMA60, SMA120, SMA250, Signal)\n TuPou(Close, Volume, Signal)\n ZhangTing(Close, Signal)\n DuoFangXinHao(Open, Close, High, Low, Signal)\n WenJian(Close, SMA5, Signal)\n MACD(Close, DIFF, DEA, Signal) \n\n#####Proces and write out the results.\n for i in range(len(Close)-10, len(Close)):\n if Signal[i]==1 and DKDJ(Close) and WKDJ(code):\n fo.write(\"%s\\n\" %(code))\n break\n\n# Write out the signal date, for testing.\n if TEST=='True':\n print(code)\n for i in range(len(Close)-10, len(Close)):\n if Signal[i]==1 and DKDJ(Close) and WKDJ(code):\n BuyIn=Signal[i:i+1]\n BuyIn=str(BuyIn).split('\\n')[1:-1]\n \n for line in BuyIn:\n print(line)\n \nfo.close() \n","sub_path":"Life/Stock_Fund/Qunatitative/Stock/Quantitative-KGL-Short-V3.1.py","file_name":"Quantitative-KGL-Short-V3.1.py","file_ext":"py","file_size_in_byte":16326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"480771146","text":"import typing as t\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n\ndef rel_err(err, prev_err):\n return (prev_err - err) / abs(1e-6 + prev_err)\n\n\ndef _add_bias(X):\n if X.ndim == 1:\n X = X.reshape(-1, 1)\n\n return np.hstack((np.ones((X.shape[0], 1)), X))\n\n\ndef predict(X, theta, add_bias: bool = True):\n if add_bias:\n X = _add_bias(X)\n\n return np.dot(theta, X.T)\n\n\ndef fit(\n X,\n y,\n step_size: float = 1e-2,\n max_it: int = 1e8,\n max_rel_err: float = 1e-6,\n random_state: t.Optional[int] = None,\n initial_theta: t.Optional[np.ndarray] = None,\n):\n max_it = int(max_it)\n\n X = _add_bias(X)\n\n if initial_theta is not None:\n theta = np.asarray(initial_theta, dtype=float)\n\n else:\n if random_state is not None:\n np.random.seed(random_state)\n\n theta = np.random.randn(X.shape[1])\n\n it = 0\n it_to_print = 1\n\n prev_mse = 1 / (1 + max_rel_err)\n gd_path = []\n\n while it < max_it and not np.isnan(prev_mse):\n it += 1\n y_pred = predict(X, theta, add_bias=False)\n err = y_pred - y\n theta -= step_size * np.mean(err * X.T, axis=1)\n\n mse = np.mean(np.square(err))\n\n if it % it_to_print == 0:\n print(f\"{it:<{9}} - MSE: {mse:.6f}\")\n gd_path.append(np.hstack((theta, mse)))\n it_to_print = min(it_to_print + 5, 100)\n\n if abs(rel_err(mse, prev_mse)) <= max_rel_err:\n it = max_it\n\n prev_mse = mse\n\n print(f\"Converged - MSE: {mse:.6f}\")\n gd_path.append(np.hstack((theta, mse)))\n\n return theta, np.asarray(gd_path)\n\n\ndef _test():\n m = 50\n\n dims = 1\n\n X1 = np.arange(m) + 2 * np.random.randn(m)\n\n if dims == 2:\n X2 = (np.random.random(m) < 0.2).astype(float)\n\n X = np.hstack((X1.reshape(-1, 1), X2.reshape(-1, 1)))\n y = 0.8 * X1 - 10 * X2 + 4 * np.random.randn(m)\n\n else:\n X = X1\n y = 0.8 * X1 + 8 * np.random.randn(m)\n\n X = 2 * (X - X.min(axis=0)) / np.ptp(X, axis=0) - 1\n\n theta, path = fit(X, y, initial_theta=[99, 99])\n\n print(\"Parameters:\", theta)\n\n if X.ndim == 1:\n plt.scatter(X, y)\n\n w = np.linspace(X.min(), X.max(), 100)\n w_pred = predict(w, theta)\n plt.plot(w, w_pred, color=\"red\")\n plt.title(f\"MSE: {np.mean(np.square(w - w_pred)):.6f}\")\n\n plt.show()\n\n fig = plt.figure()\n ax = fig.gca(projection=\"3d\")\n S1 = np.linspace(0, 101, 100)\n S1, S2 = np.meshgrid(S1, S1)\n\n ERR = np.zeros_like(S1)\n\n for i in np.arange(ERR.shape[0]):\n for j in np.arange(ERR.shape[1]):\n T1, T2 = S1[i, j], S2[i, j]\n ERR[i, j] = np.mean(np.square(predict(X, [T1, T2]) - y))\n\n ax.plot_surface(S1, S2, ERR, cmap=matplotlib.cm.coolwarm, alpha=0.7)\n ax.plot(path[:, 0], path[:, 1], path[:, 2], color=\"black\")\n ax.scatter(theta[0], theta[1], path[-1, 2], color=\"red\", s=16)\n\n plt.title(\"Error function surface\")\n\n plt.show()\n\n\n\n\nif __name__ == \"__main__\":\n _test()\n","sub_path":"classical-ml-algorithm-implementation/supervised/py-logistic-regression/deprecated/lr.py","file_name":"lr.py","file_ext":"py","file_size_in_byte":3084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"364823039","text":"class Solution(object):\r\n def addDigits(self, num):\r\n \"\"\"\r\n :type num: int\r\n :rtype: int\r\n \"\"\"\r\n if not num:\r\n return 0\r\n l = len(str(num))\r\n digits = [(num//10**i)%10 for i in range(l)]\r\n i = 0\r\n output = 0\r\n while i1:\r\n output = output%10 + output//10\r\n i+=1\r\n return output","sub_path":"algorithm/p258.py","file_name":"p258.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"53496529","text":"from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QLabel, QMessageBox, QFormLayout, \\\n QVBoxLayout, QHBoxLayout, QLineEdit, QComboBox\nfrom PyQt5.QtCore import Qt\n\nfrom convenience.server_apis import make_http_request\n\nfrom .add_dialogs import AddHourlyRateDialog, AddVehicleTypeDialog\nfrom .base_dialog import BaseDialog\n\n\nclass EditHourlyRateDialog(AddHourlyRateDialog):\n def __init__(self, https_session, entity_type, selected_item_id, parent=None):\n super().__init__(https_session, entity_type, parent=parent)\n self.selected_item_id = selected_item_id\n self.initUI()\n\n def initUI(self):\n entity_name = self.entity_type.replace(\"_\", \" \")\n self.setWindowTitle(\"Edit \" + entity_name)\n\n self.text_lbl.setText(\"Please, edit \" + entity_name + \" info:\")\n self.buttonBox.disconnect() # disconnect all object signals from their slots. We need it to remove BaseDialog slot for accepted signal.\n self.buttonBox.accepted.connect(self.edit_hourly_rate)\n self.buttonBox.rejected.connect(self.reject)\n\n\n def edit_hourly_rate(self):\n if self.form_validator(self.amount_le.text()):\n hourly_rate = {\"amount\": self.amount_le.text()}\n response = make_http_request(self.https_session, \"put\", \"hourly_rates/\" + str(self.selected_item_id), json = hourly_rate)\n if response:\n QMessageBox.information(self, \"Server response\", response.text)\n self.done(0)\n else:\n self.done(1)\n\n\nclass EditVehicleTypeDialog(AddVehicleTypeDialog):\n def __init__(self, https_session, entity_type, selected_item_id, parent=None):\n super().__init__(https_session, entity_type, parent=parent)\n self.selected_item_id = selected_item_id\n self.initUI()\n\n def initUI(self):\n entity_name = self.entity_type.replace(\"_\", \" \")\n self.setWindowTitle(\"Edit \" + entity_name)\n\n self.text_lbl.setText(\"Please, edit \" + entity_name + \" info:\")\n self.buttonBox.disconnect() # disconnect all object signals from their slots. We need it to remove BaseDialog slot for accepted signal.\n self.buttonBox.accepted.connect(self.edit_vehicle_type)\n self.buttonBox.rejected.connect(self.reject)\n\n\n def edit_vehicle_type(self):\n if self.form_validator(self.name_le.text(), self.rate_percentage_le.text()):\n vehicle_type = {\n \"name\": self.name_le.text(),\n \"rate_percentage\": self.rate_percentage_le.text()\n }\n response = make_http_request(self.https_session, \"put\", \"vehicle_types/\" + str(self.selected_item_id), json = vehicle_type)\n if response:\n QMessageBox.information(self, \"Server response\", response.text)\n self.done(0)\n else:\n self.done(1)\n\n\nclass EditUserCategoryDialog(BaseDialog):\n def __init__(self, https_session, entity_type, selected_item_id, hourly_rates, parent=None):\n super().__init__(https_session, entity_type, parent=parent)\n self.selected_item_id = selected_item_id\n self.hourly_rates = hourly_rates\n self.initUI()\n\n\n def initUI(self):\n entity_name = self.entity_type.replace(\"_\", \" \")\n self.setWindowTitle(\"Edit \" + entity_name)\n\n self.text_lbl.setText(\"Please, edit \" + entity_name + \" info:\")\n self.buttonBox.accepted.connect(self.edit_user_category)\n\n self.hourly_rate_cmb = QComboBox()\n self.hourly_rate_cmb.addItems([str(hourly_rate.get_amount()) for hourly_rate in self.hourly_rates])\n self.form_layout.addRow(\"Hourly rate: \", self.hourly_rate_cmb)\n\n\n def edit_user_category(self):\n cmb_index = self.hourly_rate_cmb.currentIndex()\n if cmb_index != -1:\n hourly_rate = self.hourly_rates[cmb_index]\n user_category = {\n \"id_hourly_rate\": hourly_rate.get_id(),\n \"service_validity_start\": None,\n \"service_validity_end\": None\n }\n response = make_http_request(self.https_session, \"put\", \"user_categories/\" + str(self.selected_item_id), json = user_category)\n if response:\n QMessageBox.information(self, \"Server response\", response.text)\n self.done(0)\n else:\n self.done(1)\n else:\n QMessageBox.information(self, \"uPark tip\", \"Select an hourly rate first!\")\n","sub_path":"uPark_client/ui_widgets/admin/other_settings/edit_dialogs.py","file_name":"edit_dialogs.py","file_ext":"py","file_size_in_byte":4661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"505101083","text":"from collections import deque\n\n\nclass BinarySearchTree:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n def depth_first_for_each(self, cb):\n # give value to callback (pre-order)\n cb(self.value)\n # check the left\n if self.left:\n self.left.depth_first_for_each(cb)\n # check the right\n if self.right:\n self.right.depth_first_for_each(cb)\n\n def breadth_first_for_each(self, cb):\n # create queue (FIFO)\n queue = deque()\n # add first el to queue\n queue.append(self)\n # while queue is not empty\n while queue:\n # remove from front of queue\n popped = queue.popleft()\n # pass into callback\n cb(popped.value)\n # if children (left and right) exist, add to queue\n if popped.left:\n queue.append(popped.left)\n if popped.right:\n queue.append(popped.right)\n\n def insert(self, value):\n new_tree = BinarySearchTree(value)\n if (value < self.value):\n if not self.left:\n self.left = new_tree\n else:\n self.left.insert(value)\n elif value >= self.value:\n if not self.right:\n self.right = new_tree\n else:\n self.right.insert(value)\n\n def contains(self, target):\n if self.value == target:\n return True\n if self.left:\n if self.left.contains(target):\n return True\n if self.right:\n if self.right.contains(target):\n return True\n return False\n\n def get_max(self):\n if not self:\n return None\n max_value = self.value\n current = self\n while current:\n if current.value > max_value:\n max_value = current.value\n current = current.right\n return max_value\n","sub_path":"search/binary_search_tree.py","file_name":"binary_search_tree.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"416472030","text":"import os\n\nrootdir = os.path.abspath(os.path.join(__file__, \"..\", \"..\"))\n\nmldir = os.path.join(rootdir, \"ml\")\n\nimport sys\nsys.path.append(mldir)\n\nimport pfm\n\nargv = sys.argv[1:]\n\nargv0 = argv[0]\nargv1 = argv[1]\n\nimg = pfm.load(argv0)\n\nimg.jacobian_transform()\nimg.save_png(argv1, 0.0, 1.8)","sub_path":"tools/jacobian_transform.py","file_name":"jacobian_transform.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"493395215","text":"import platform\n\nversion = platform.python_version()\nif '3.' not in version:\n print('Error: You must use python3!')\nelse:\n print('Running...')\n\n\ndef main():\n \"\"\" main function \"\"\"\n\n print(\"\"\"Python Version: {0}\nPython Implementation: {1}\nOperating System: {2}\nRelease: {3}\n\"\"\".format(platform.python_version(),\n platform.python_implementation(),\n platform.system(),\n platform.release()))\n\nmain()\n","sub_path":"sys_info.py","file_name":"sys_info.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"153161129","text":"import matplotlib.pyplot as plt\nfrom random import randint\nimport pygal\nimport json\nfrom pygal_maps_world.i18n import COUNTRIES\nfrom pygal.maps.world import COUNTRIES\n\n# 安装及使用方式\n# pip install pygal_maps_world\n# import pygal.maps.world\n# wm = pygal.maps.world.World()\n\n# 折线图\ndef linechart():\n\tinput_squares = [1,2,3,4,5]\n\tsquares = [1,4,9,16,25]\n\tplt.plot(input_squares,squares,linewidth=5)\n\t# 设置图表标题,并给坐标轴加上标签\n\tplt.title('Squares Numbers',fontsize=24)\n\tplt.xlabel('Value',fontsize=14)\n\tplt.ylabel('Squares of Value',fontsize=14)\n\t# 设置刻度标记的大小\n\tplt.tick_params(axis='both',labelsize=14)\n\n\tplt.show()\n\n# 单个散点图\ndef scatterChart_single():\n\tplt.scatter(2,4)\n\n\tplt.title('Squares Numbers',fontsize=24)\n\tplt.xlabel('Value',fontsize=14)\n\tplt.ylabel('Squares of Value',fontsize=14)\n\n\tplt.tick_params(axis='both',which='major',labelsize=14)\t\n\n\tplt.show()\n\n# 散点图\ndef scatterChart():\n\tx_values = [1,2,3,4,5]\n\ty_values = [1,4,9,16,25]\n\tplt.scatter(x_values,y_values,s=100)\n\n\tplt.title('Squares Numbers',fontsize=24)\n\tplt.xlabel('Value',fontsize=14)\n\tplt.ylabel('Squares of Value',fontsize=14)\n\tplt.tick_params(axis='both',which='major',labelsize=14)\n\n\tplt.show()\n\n# 自动计算数据\ndef auto_scatter():\n\tx_values = list(range(1,1001))\n\ty_values = [x**2 for x in x_values]\n\tplt.scatter(x_values,y_values,s=10)\n\n\tplt.title('Squares Numbers',fontsize=24)\n\tplt.xlabel('Value',fontsize=14)\n\tplt.ylabel('Squares of Value',fontsize=14)\n\n\t# 设置每个坐标轴的取值范围\n\tplt.axis([0,1100,0,1100000])\n\n\tplt.show()\n\n# 直方图\ndef histogram(s,num,title,xtitle,ytitle):\n\tmax_num = num\n\tfrequencies = []\n\tff = []\n\tfor i in range(0,max_num):\n\t\tfrequency = s[i]\n\t\tfrequencies.append(frequency[1])\n\tprint(frequencies)\n\t# 对结果进行可视化\n\thist = pygal.Bar()\n\thist.x_labels = [s[j][0] for j in range(0,max_num)]\n\thist.x_title = xtitle\n\thist.y_title = ytitle\n\thist.y_labels = [str(abs(i)) for i in range(-10000,12000,2000)]\n\n\n\thist.add(title,frequencies)\n\thist.render_to_file('test.svg')\n\n# 直方图\n# 掷骰子,从1~6中选出一个随机数,多次循环,查看各值的频率\ndef histogram_single():\n\tmax_num = 6\n\tresult = []\n\tfor i in range(1,101):\n\t\tresult.append(randint(1,max_num))\n\tprint(result)\n\tfrequencies = []\n\tfor i in range(1,max_num+1):\n\t\tfrequency = result.count(i)\n\t\tfrequencies.append(frequency)\n\tprint(frequencies)\n\t# 对结果进行可视化\n\thist = pygal.Bar()\n\thist.x_labels = ['1','2','3','4','5','6']\n\thist.x_title = 'Result'\n\thist.y_title = 'Frequency of Result'\n\n\thist.add('D6',frequencies)\n\thist.render_to_file('die_visual.svg')\n\n# 直方图\n# 掷两个骰子,从1~6中选出一个随机数,多次循环,查看各值的频率\ndef histogram_double():\n\tmax_num = 6\n\tresult = []\n\tfor i in range(1,1001):\n\t\tresult.append(randint(1,max_num)+randint(1,max_num))\n\tfrequencies = []\n\tfor i in range(2,max_num*2+1):\n\t\tfrequency = result.count(i)\n\t\tfrequencies.append(frequency)\n\t# 结果可视化\n\thist = pygal.Bar()\n\thist.x_labels = range(2,max_num*2+1)\n\thist.x_title = 'Result'\n\thist.y_title = 'Frequency of Value'\n\n\thist.add('D6 + D6',frequencies)\n\thist.render_to_file('die_visual.svg')\n\n# 获取两个字母的国别码\ndef get_country(country):\n\ttry:\n\t\ta = list(COUNTRIES.keys())[list(COUNTRIES.values()).index (country)]\n\texcept Exception:\n\t\treturn None\n\telse:\n\t\treturn a\t\n\n\n# 世界人口图\ndef population():\n\t# 获取人口信息\n\twith open('../other/population_json.json','r+') as file:\n\t\tpop_data = json.load(file)\n\t# print(pop_data)\n\tcc_populations = {}\n\tfor pop_dict in pop_data:\n\t\tif pop_dict['Year'] == 2016:\n\t\t\tcountry_code = get_country(pop_dict['Country Name'])\n\t\t\tpop_value = int(pop_dict['Value'])\n\t\t\tif country_code:\n\t\t\t\tcc_populations[country_code] = pop_value\n\n\t# 根据人口数量将所有的国家分成三组\n\tcc_pops_1, cc_pops_2, cc_pops_3 = {}, {}, {}\n\tfor cc, pop in cc_populations.items():\n\t\tif pop < 10000000:\n\t\t\tcc_pops_1[cc] = pop\n\t\telif pop < 1000000000:\n\t\t\tcc_pops_2[cc] = pop\n\t\telse:\n\t\t\tcc_pops_3[cc] = pop\n\n\t# 制作地图\n\twm = pygal.maps.world.World()\n\twm.title = 'World Population in 2016, by Country'\n\twm.add('0-10m', cc_pops_1)\n\twm.add('10m-1bn', cc_pops_2)\n\twm.add('>1bn', cc_pops_3)\n\t# wm.add('2016',cc_populations)\n\t# wm.add('Asia',['cn','pk','np','th','kp','kr'])\n\t# wm.add('North America', ['ca', 'mx', 'us'])\n\twm.render_to_file('World_Population.svg')\n\n\n\n\n\n\n\n\n\n\n\n\n\n# ---------------- 测试 ---------------------#\nif __name__ == '__main__':\n\t# linechart()\n\t# scatterChart_single()\n\t# scatterChart()\n\t# auto_scatter()\n\t# histogram()\n\t# histogram_single()\n\t# histogram_double()\n\tpopulation()\n\t# print(COUNTRIES)","sub_path":"图表/Chart.py","file_name":"Chart.py","file_ext":"py","file_size_in_byte":4663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"293786218","text":"from collections import Counter\r\nimport csv\r\n\r\nwith open ('height-weight.csv', newline = '') as f:\r\n reader = csv.reader(f)\r\n file_data = list(reader)\r\n \r\nfile_data.pop(0)\r\nnewData = []\r\n\r\nfor i in range(len(file_data)):\r\n n_num = file_data[i][2]\r\n newData.append(float(n_num))\r\n\r\ndata = Counter(newData)\r\nmodeData_for_range = {\r\n \"50-60\" : 0,\r\n \"60-70\" : 0,\r\n \"70-80\" :0\r\n }\r\n\r\nfor height,occurence in data.items():\r\n if 50mode_occurence:\r\n modeRange,mode_occurence = [int(range.split(\"-\")[0]),int(range.split(\"-\")[1])],occurence\r\n\r\nmode = float((modeRange[0] + modeRange[1])/2)\r\n\r\nprint(mode)","sub_path":"Python/centralTendencyProject/mode1.py","file_name":"mode1.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"532762356","text":"# Made by QuestDevs Team: DraX, DrLecter, Rolarga\r\n# With invaluable support from: [TI]Blue, warrax\r\n# v0.1.r0 2005.12.05\r\n\r\nimport sys\r\nfrom java.util import Iterator\r\nfrom net.sf.l2j.gameserver.datatables import SkillTable\r\nfrom net.sf.l2j.gameserver.model.quest import State\r\nfrom net.sf.l2j.gameserver.model.quest import QuestState\r\nfrom net.sf.l2j.gameserver.model.quest.jython import QuestJython as JQuest\r\nfrom net.sf.l2j.gameserver.serverpackets import CreatureSay\r\n\r\nqn=\"501_ProofOfClanAlliance\"\r\nqd=\"Proof of Clan Alliance\"\r\n\r\n# Quest Npcs\r\nSIR_KRISTOF_RODEMAI = 7756\r\nSTATUE_OF_OFFERING = 7757\r\nWITCH_ATHREA = 7758\r\nWITCH_KALIS = 7759\r\n\r\n# Quest Items\r\nHERB_OF_HARIT = 3832\r\nHERB_OF_VANOR = 3833\r\nHERB_OF_OEL_MAHUM = 3834\r\nBLOOD_OF_EVA = 3835\r\nSYMBOL_OF_LOYALTY = 3837\r\nPROOF_OF_ALLIANCE = 3874\r\nVOUCHER_OF_FAITH = 3873\r\nANTIDOTE_RECIPE = 3872\r\nPOTION_OF_RECOVERY= 3889\r\n\r\n#Quest mobs, drop, rates and prices\r\nCHESTS=range(5173,5178)\r\nCHEST_LOCS = [\r\n [102273,103433,-3512],\r\n [102190,103379,-3524],\r\n [102107,103325,-3533],\r\n [102024,103271,-3500],\r\n [102327,103350,-3511],\r\n [102244,103296,-3518],\r\n [102161,103242,-3529],\r\n [102078,103188,-3500],\r\n [102381,103267,-3538],\r\n [102298,103213,-3532],\r\n [102215,103159,-3520],\r\n [102132,103105,-3513],\r\n [102435,103184,-3515],\r\n [102352,103130,-3522],\r\n [102269,103076,-3533],\r\n [102186,103022,-3541]\r\n ]\r\n\r\nMOBS=[[685,HERB_OF_VANOR],[644,HERB_OF_HARIT],[576,HERB_OF_OEL_MAHUM]]\r\nRATE=35\r\n#stackable items paid to retry chest game: (default 10k adena)\r\nRETRY_ITEMS=57\r\nRETRY_PRICE=10000\r\n\r\ndef leader(player) :\r\n leaderst = None\r\n clan = player.getClan()\r\n if clan :\r\n leader = clan.getLeader().getPlayerInstance()\r\n if leader : \r\n leaderst = leader.getQuestState(qn) \r\n return leaderst\r\n\r\ndef randomize_chests(leaderst) :\r\n chests = [ 1,0,0,1,1,0]\r\n for i in range(len(chests)-1, 0, -1) :\r\n j = leaderst.getRandom(5)\r\n chests[i], chests[j] = chests[j], chests[i]\r\n for i in range(len(chests)): chests[i]=str(chests[i])\r\n leaderst.set(\"chests\",\" \".join(chests))\r\n return\r\n\r\nclass Quest (JQuest) :\r\n\r\n def __init__(self,id,name,descr):\r\n JQuest.__init__(self,id,name,descr)\r\n self.questItemIds = [ANTIDOTE_RECIPE, VOUCHER_OF_FAITH, POTION_OF_RECOVERY]\r\n # a hashtable tracking this quest's (chest) spawns, indexed by leaderST\r\n self.spawn_tracker = {}\r\n\r\n def chest_game(self,leaderst,command) :\r\n if command == \"start\" :\r\n leaderst.set(\"chest_game\",\"1\")\r\n leaderst.set(\"chest_count\",\"0\")\r\n attempts = leaderst.getInt(\"chest_try\")\r\n leaderst.set(\"chest_try\",str(attempts+1))\r\n randomize_chests(leaderst)\r\n tempList = []\r\n for x,y,z in CHEST_LOCS :\r\n rand = leaderst.getRandom(5)\r\n tempList.append(leaderst.addSpawn(5173+rand,x,y,z,0,0,60000))\r\n self.spawn_tracker[leaderst]=tempList\r\n leaderst.startQuestTimer(\"chest_timer\",60000)\r\n elif command == \"stop\" :\r\n try:\r\n leaderst.set(\"chest_game\",\"0\")\r\n if self.spawn_tracker.has_key(leaderst) :\r\n trackedSpawns = self.spawn_tracker.pop(leaderst)\r\n for chest in trackedSpawns :\r\n chest.decayMe()\r\n except: pass\r\n\r\n def onAdvEvent (self,event,npc,player):\r\n leaderst = 0\r\n if player.isClanLeader() == 1 :\r\n leaderst = player.getQuestState(qn)\r\n else :\r\n leaderst = leader(player)\r\n if not leaderst:\r\n return\r\n htmltext = event\r\n##### Leaders area ######\r\n if event == \"7756-03.htm\" :\r\n leaderst.setState(PART2)\r\n leaderst.set(\"cond\",\"1\")\r\n leaderst.playSound(\"ItemSound.quest_accept\")\r\n elif event == \"7759-03.htm\" :\r\n leaderst.setState(PART3)\r\n leaderst.set(\"cond\",\"2\")\r\n leaderst.set(\"dead_list\",\" \")\r\n elif event == \"7759-07.htm\" :\r\n leaderst.takeItems(SYMBOL_OF_LOYALTY,1)\r\n leaderst.takeItems(SYMBOL_OF_LOYALTY,1)\r\n leaderst.takeItems(SYMBOL_OF_LOYALTY,1)\r\n leaderst.giveItems(ANTIDOTE_RECIPE,1)\r\n leaderst.setState(PART4)\r\n leaderst.set(\"cond\",\"3\")\r\n leaderst.set(\"ingredients\",\"0 0 0\")\r\n leaderst.set(\"chest_count\",\"0\")\r\n leaderst.set(\"chest_game\",\"0\")\r\n leaderst.set(\"chest_try\",\"0\")\r\n skill = SkillTable.getInstance().getInfo(4082,1)\r\n skill.getEffects(player, player, False)\r\n leaderst.addNotifyOfDeath(player)\r\n elif event == \"chest_timer\" :\r\n htmltext = \"\"\r\n self.chest_game(leaderst,\"stop\")\r\n##### Members area ######\r\n elif event == \"7757-04.htm\" :\r\n deadlist = leaderst.get(\"dead_list\").split()\r\n deadlist.append(str(player.getObjectId()))\r\n leaderst.set(\"dead_list\",\" \".join(deadlist))\r\n player.doDie(player)\r\n leaderst.giveItems(player,SYMBOL_OF_LOYALTY,1,0)\r\n leaderst.playSound(player,\"ItemSound.quest_accept\")\r\n if player.getQuestState(qn) :\r\n player.getQuestState(qn).exitQuest(1)\r\n elif event == \"7758-03.htm\" :\r\n self.chest_game(leaderst,\"start\")\r\n elif event == \"7758-07.htm\" :\r\n if leaderst.getQuestItemsCount(player,RETRY_ITEMS) < RETRY_PRICE :\r\n htmltext = \"7758-06.htm\"\r\n else :\r\n leaderst.takeItems(player,RETRY_ITEMS,RETRY_PRICE)\r\n return htmltext\r\n\r\n def onTalk (self,npc,st):\r\n htmltext = \"no_quest.htm\"\r\n leaderst = leader(st.getPlayer())\r\n if not leaderst : return htmltext\r\n npcId = npc.getNpcId()\r\n if npcId == SIR_KRISTOF_RODEMAI:\r\n if st.getPlayer().getClan() == None or st.getPlayer().isClanLeader() == 0:\r\n st.exitQuest(1)\r\n htmltext = \"7756-10.htm\"\r\n else :\r\n if st.getPlayer().getClan().getLevel() <= 2 :\r\n st.exitQuest(1)\r\n htmltext = \"7756-08.htm\"\r\n elif st.getPlayer().getClan().getLevel() >= 4 :\r\n st.exitQuest(1)\r\n htmltext = \"7756-09.htm\"\r\n elif st.getState() == PART5 and st.getQuestItemsCount(VOUCHER_OF_FAITH):\r\n st.playSound(\"ItemSound.quest_fanfare_2\")\r\n st.takeItems(VOUCHER_OF_FAITH,1)\r\n st.giveItems(PROOF_OF_ALLIANCE,1)\r\n st.addExpAndSp(0,120000)\r\n htmltext=\"7756-07.htm\"\r\n st.exitQuest(1)\r\n elif st.getState() in [PART2,PART3] :\r\n htmltext = \"7756-06.htm\"\r\n elif st.getQuestItemsCount(PROOF_OF_ALLIANCE) == 0 :\r\n st.set(\"cond\",\"0\")\r\n htmltext = \"7756-01.htm\"\r\n else :\r\n st.exitQuest(1)\r\n elif npcId == WITCH_KALIS:\r\n if st.getPlayer().getClan() == None :\r\n st.exitQuest(1)\r\n else:\r\n if st.getPlayer().isClanLeader() == 1 :\r\n if st.getState() == PART2 :\r\n htmltext = \"7759-01.htm\"\r\n elif st.getState() == PART3 :\r\n htmltext = \"7759-05.htm\"\r\n if st.getQuestItemsCount(SYMBOL_OF_LOYALTY) == 3 :\r\n try : deads=len(st.get(\"dead_list\").split())\r\n finally :\r\n if deads == 3 :\r\n htmltext = \"7759-06.htm\"\r\n elif st.getState() == PART4:\r\n if st.getQuestItemsCount(HERB_OF_HARIT) and \\\r\n st.getQuestItemsCount(HERB_OF_VANOR) and \\\r\n st.getQuestItemsCount(HERB_OF_OEL_MAHUM) and \\\r\n st.getQuestItemsCount(BLOOD_OF_EVA) and \\\r\n st.getQuestItemsCount(ANTIDOTE_RECIPE) and \\\r\n st.getInt(\"chest_game\") == 3 :\r\n st.takeItems(ANTIDOTE_RECIPE,1)\r\n st.takeItems(HERB_OF_HARIT,1)\r\n st.takeItems(HERB_OF_VANOR,1)\r\n st.takeItems(HERB_OF_OEL_MAHUM,1)\r\n st.takeItems(BLOOD_OF_EVA,1)\r\n st.set(\"cond\",\"4\")\r\n st.setState(PART5)\r\n st.giveItems(POTION_OF_RECOVERY,1)\r\n st.giveItems(VOUCHER_OF_FAITH,1)\r\n htmltext = \"7759-08.htm\"\r\n st.playSound(\"ItemSound.quest_finish\")\r\n elif st.getQuestItemsCount(VOUCHER_OF_FAITH)==0:\r\n htmltext = \"7759-10.htm\"\r\n else :\r\n st.exitQuest(1)\r\n else :\r\n try :\r\n if leaderst.getState() == PART4 :\r\n htmltext = \"7759-11.htm\"\r\n st.exitQuest(1)\r\n except :\r\n st.exitQuest(1)\r\n elif npcId == STATUE_OF_OFFERING:\r\n if st.getPlayer().getClan() == None :\r\n st.exitQuest(1)\r\n else :\r\n if st.getPlayer().isClanLeader() == 1 :\r\n if leaderst.getState() in [PART2,PART3,PART4,PART5] :\r\n htmltext = \"7757-03.htm\"\r\n else :\r\n if st.getPlayer().getLevel() <= 39 :\r\n htmltext = \"7757-02.htm\"\r\n st.exitQuest(1)\r\n elif leaderst.getState() == PART3 :\r\n dlist=[]\r\n deads=3\r\n dlist=leaderst.get(\"dead_list\").split()\r\n deads = len(dlist)\r\n if deads < 3 :\r\n if str(st.getPlayer().getObjectId()) not in dlist :\r\n if not leaderst.getQuestItemsCount(st.getPlayer(),SYMBOL_OF_LOYALTY) :\r\n htmltext = \"7757-01.htm\"\r\n else :\r\n htmltext = \"7757-06.htm\"\r\n else :\r\n htmltext = \"You cannot die again!\"\r\n st.exitQuest(1)\r\n elif npcId == WITCH_ATHREA :\r\n if st.getPlayer().getClan() == None :\r\n st.exitQuest(1)\r\n else :\r\n if st.getPlayer().isClanLeader() == 0 :\r\n if leaderst :\r\n if leaderst.getState() == PART4 :\r\n game_state=leaderst.getInt(\"chest_game\")\r\n if game_state == 0 :\r\n if leaderst.getInt(\"chest_try\") == 0 :\r\n htmltext=\"7758-01.htm\"\r\n else :\r\n htmltext=\"7758-05.htm\"\r\n elif game_state == 1 :\r\n htmltext=\"7758-09.htm\"\r\n elif game_state == 2 :\r\n timer=leaderst.getQuestTimer(\"chest_timer\")\r\n if timer != None : timer.cancel()\r\n self.chest_game(leaderst,\"stop\")\r\n leaderst.set(\"chest_game\",\"3\")\r\n leaderst.giveItems(st.getPlayer(),BLOOD_OF_EVA,1,0)\r\n leaderst.playSound(st.getPlayer(),\"ItemSound.quest_middle\")\r\n htmltext=\"7758-08.htm\"\r\n st.exitQuest(1)\r\n return htmltext\r\n\r\n def onKill(self,npc,player,isPet) :\r\n if player.isClanLeader() == 1 :\r\n return\r\n leaderst = leader(player)\r\n ### first part, general checking\r\n npcId=npc.getNpcId()\r\n if not leaderst :\r\n return \"Quest clan leader not available.\"\r\n elif leaderst.getInt(\"cond\") > 2 :\r\n ingredients = []\r\n try :\r\n if leaderst.get(\"ingredients\") != None :\r\n ingredients = leaderst.get(\"ingredients\").split()\r\n finally :\r\n ### second part, herbs gathering\r\n if len(ingredients) :\r\n for m in range(len(MOBS)) :\r\n if not int(ingredients[m]) :\r\n if npcId == MOBS[m][0] :\r\n if leaderst.getQuestItemsCount(player,MOBS[m][1]) == 0 :\r\n if leaderst.getRandom(100) < RATE :\r\n leaderst.giveItems(player,MOBS[m][1],1,0)\r\n ingredients[m]='1'\r\n leaderst.set(\"ingredients\",\" \".join(ingredients))\r\n leaderst.playSound(player,\"ItemSound.quest_middle\")\r\n return\r\n ### third part, chest game\r\n if npcId in CHESTS :\r\n timer=leaderst.getQuestTimer(\"chest_timer\")\r\n #if timer == None : self.chest_game(leaderst,\"stop\");return \"Time is up!\"\r\n chests = leaderst.get(\"chests\").split()\r\n for i in range(len(chests)) :\r\n if npcId == 5173+i and chests[i] == '1' :\r\n npc.broadcastPacket(CreatureSay(npc.getObjectId(),0,npc.getName(),\"###### BINGO! ######\"))\r\n count=leaderst.getInt(\"chest_count\")\r\n if count < 4 :\r\n count+=1\r\n leaderst.set(\"chest_count\",str(count))\r\n if count == 4 :\r\n leaderst.getQuestTimer(\"chest_timer\").cancel()\r\n self.chest_game(leaderst,\"stop\")\r\n leaderst.set(\"chest_game\",\"2\")\r\r\n leaderst.playSound(player,\"ItemSound.quest_middle\")\r\n else :\r\n leaderst.playSound(player,\"ItemSound.quest_itemget\")\r\n return\r\n\r\n def onDeath(self, npc, pc, st) :\r\n if st.getPlayer() == pc :\r\n timer=st.getQuestTimer(\"chest_timer\")\r\n if timer != None : timer.cancel()\r\n st.exitQuest(1)\r\n\r\nQUEST = Quest(501,qn,qd)\r\nCREATED = State('Start', QUEST)\r\nPART2 = State('Part2', QUEST)\r\nPART3 = State('Part3', QUEST)\r\nPART4 = State('Part4', QUEST)\r\nPART5 = State('Part5', QUEST)\r\nCOMPLETED = State('Completed', QUEST)\r\n\r\nQUEST.setInitialState(CREATED)\r\n\r\nQUEST.addStartNpc(SIR_KRISTOF_RODEMAI)\r\nQUEST.addStartNpc(STATUE_OF_OFFERING)\r\nQUEST.addStartNpc(WITCH_ATHREA)\r\n\r\nQUEST.addTalkId(SIR_KRISTOF_RODEMAI)\r\nQUEST.addTalkId(STATUE_OF_OFFERING)\r\nQUEST.addTalkId(WITCH_ATHREA)\r\nQUEST.addTalkId(WITCH_KALIS)\r\n\r\nfor i in range(len(MOBS)) :\r\n QUEST.addKillId(MOBS[i][0])\r\n\r\nfor i in CHESTS :\r\n QUEST.addKillId(i)","sub_path":"DataPack/data/scripts/quests/501_ProofOfClanAlliance/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":13256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"460292223","text":"import datetime\nimport json\nimport logging\n\nfrom django.conf import settings\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404\n# Create your views here.\nfrom django.views.generic import ListView, DetailView\nfrom django.views.generic.base import View\nfrom django.views.generic.edit import ModelFormMixin\nfrom ..categories.models import Category\nfrom ..sales.forms import UpdateSalesForm\nfrom ..sales.models import Sale, SaleProduct\nfrom ..products.models import Product\n\nfrom rest_framework import status\nfrom rest_framework.authentication import BasicAuthentication\nfrom rest_framework.authentication import SessionAuthentication\nfrom rest_framework.generics import get_object_or_404\nfrom rest_framework.permissions import AllowAny\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\n\nclass ListSalesView(LoginRequiredMixin, ListView):\n template_name = 'list_car.html'\n context_object_name = 'sales'\n\n def get_queryset(self):\n return self.request.user.sales.all().order_by('-date_requested')\n\n def get_context_data(self, **kwargs):\n context = super(ListSalesView, self).get_context_data(**kwargs)\n context['categories'] = Category.objects.filter(is_subcategory=False, is_enabled=True)\n return context\n\n\nclass SaleDetailListView(LoginRequiredMixin, DetailView):\n form_class = UpdateSalesForm\n template_name = 'carrito.html'\n context_object_name = 'sale'\n\n def get_object(self, queryset=None):\n uid = self.kwargs.get(\"uid\")\n decoded = settings.HASHIDS.decode(uid)\n id = decoded[0] if decoded else None\n sale = get_object_or_404(self.request.user.sales.filter(state=Sale.REQUESTED), id=id)\n return sale\n\n def get_context_data(self, **kwargs):\n context = super(SaleDetailListView, self).get_context_data(**kwargs)\n context['categories'] = Category.objects.filter(is_subcategory=False, is_enabled=True)\n return context\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n context = self.get_context_data(object=self.object)\n return self.render_to_response(context)\n\n\nclass ListUpdateSaleView(LoginRequiredMixin, ModelFormMixin, DetailView):\n form_class = UpdateSalesForm\n template_name = 'car_buy.html'\n context_object_name = 'sale'\n\n def get_object(self, queryset=None):\n uid = self.kwargs.get(\"uid\")\n decoded = settings.HASHIDS.decode(uid)\n id = decoded[0] if decoded else None\n sale = get_object_or_404(self.request.user.sales.filter(state=Sale.REQUESTED), id=id)\n return sale\n\n def get_context_data(self, **kwargs):\n context = super(ListUpdateSaleView, self).get_context_data(**kwargs)\n context['categories'] = Category.objects.filter(is_subcategory=False)\n return context\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n context = self.get_context_data(object=self.object)\n return self.render_to_response(context)\n\n def post(self, request, *args, **kwargs):\n \"\"\"\n Handles POST requests, instantiating a form instance with the passed\n POST variables and then checked for validity.\n \"\"\"\n form = UpdateSalesForm(request.POST, request.FILES)\n if form.is_valid():\n return self.form_valid(form)\n else:\n return self.form_invalid(form)\n\n # PUT is a valid HTTP verb for creating (with a known URL) or editing an\n # object, note that browsers only support POST for now.\n def put(self, *args, **kwargs):\n return self.post(*args, **kwargs)\n\n def form_valid(self, form):\n sale = self.get_object()\n paid = datetime.datetime.now()\n total_amount = 0\n for sp in sale.sale_products.all():\n total_amount += sp.amount\n sale.total_amount = total_amount\n sale.state = Sale.PAID\n sale.date_paid = paid\n sale.voucher = form.cleaned_data.get('voucher')\n sale.code_voucher = form.cleaned_data.get('code')\n sale.save()\n return HttpResponseRedirect(reverse_lazy('sales:list-car'))\n\n def get_form(self, form_class=None):\n \"\"\"\n Returns an instance of the form to be used in this view.\n \"\"\"\n if form_class is None:\n form_class = self.get_form_class()\n ins = self.get_form_kwargs()\n ins['instance'] = None\n return form_class(ins)\n\n\nclass CreateSaleView(LoginRequiredMixin, View):\n def post(self, *args, **kwargs):\n logging.debug(self.request.POST)\n _id = self.request.POST.get('id')\n _quantity = int(self.request.POST.get('quantity'))\n _size = self.request.POST.get('size')\n response_data = {}\n if _id and _quantity and _size:\n product = get_object_or_404(Product, id=_id)\n\n if self.request.user.sales.filter(state=Sale.REQUESTED).last():\n sale = self.request.user.sales.filter(state=Sale.REQUESTED).last()\n sale_product = SaleProduct(\n sale=sale, product=product,\n quantity=_quantity,\n size=_size,\n amount=product.net_price * _quantity\n )\n sale_product.save()\n sale.total_amount += sale_product.amount\n sale.save()\n else:\n sale = Sale(user=self.request.user)\n sale.save()\n sale_product = SaleProduct(\n sale=sale,\n product=product,\n quantity=_quantity,\n size=_size,\n amount=product.net_price * _quantity\n )\n sale_product.save()\n sale.total_amount = sale_product.amount\n sale.save()\n response_data['status'] = 200\n response_data['uid'] = sale.uid\n return HttpResponse(\n json.dumps(response_data),\n content_type=\"application/json\"\n )\n else:\n logging.error(\"Error\")\n\n response_data['status'] = 500\n return HttpResponse(\n json.dumps(response_data),\n content_type=\"application/json\"\n )\n\n\nclass SaleDetailView(LoginRequiredMixin, DetailView):\n model = Sale\n template_name = 'sale_detail.html'\n context_object_name = 'sale'\n\n def get_object(self, queryset=None):\n uid = self.kwargs.get(\"uid\")\n decoded = settings.HASHIDS.decode(uid)\n id = decoded[0] if decoded else None\n sale = get_object_or_404(self.request.user.sales, id=id)\n return sale\n\n def get_context_data(self, **kwargs):\n context = super(SaleDetailView, self).get_context_data(**kwargs)\n context['categories'] = Category.objects.filter(is_subcategory=False, is_enabled=True)\n return context\n\n\nclass RemoveProductCartAPI(APIView):\n authentication_classes = (SessionAuthentication, BasicAuthentication)\n #permission_classes = (IsAuthenticated,)\n # authentication_classes = ()\n permission_classes = (AllowAny,)\n\n def post(self, request, *args, **kwargs):\n logging.info(\"remove item from cart\")\n _pk = self.kwargs.get(\"pk\")\n logging.info(_pk)\n sp = SaleProduct.objects.get(pk=_pk)\n sp.delete()\n return Response({'detail': 'Producto eliminado del carrito'}, status=status.HTTP_200_OK)\n","sub_path":"Release/SWGI/inventario/catalogo_productos/eshop/apps/sales/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"309860718","text":"'''\nCreated on Sep 28, 2011\n\n@author: arefaey\n'''\nfrom constants import *\nimport re\nfrom httplib2 import Http\n\nclass VPC(object): \n# Initialize new client to the target_uri with optional auth_token\n def __init__(self, target_url=DEFAULT_TARGET, auth_token=None):\n self.version = VERSION\n self.target = None\n self.host = None\n self.user = None\n self.proxy = None\n self.auth_token = None\n self.http = Http()\n if not (re.match('^https?', target_url)):\n target_url = \"http://%s\" %target_url\n re.sub('/\\/+$/', '', target_url)\n self.target = target_url\n self.auth_token = auth_token\n \n def info(self):\n _, content = self.http.request(self.target+INFO_PATH)\n return content","sub_path":"vpc/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"439331428","text":"import pygame\nimport os\nimport random\n\nWIDTH, HEIGHT = 900, 500\nCHARACTER_WIDTH, CHARACTER_HEIGHT = 120, 120\nWIN = pygame.display.set_mode((WIDTH, HEIGHT))\npygame.display.set_caption(\"Lamp Warrior\")\n\n\nWHITE = (255, 255, 255)\n\nFPS = 60\nVEL = 10\n\nBACKGROUND_IMAGE = pygame.image.load(os.path.join('Assets','background.jpg'))\nBACKGROUND_BOX = WIN.get_rect()\n\nPLAYER_TOKEN_IMAGE = pygame.image.load(os.path.join('Assets', 'jake_drawing.png'))\nPLAYER_TOKEN = pygame.transform.scale(PLAYER_TOKEN_IMAGE, (CHARACTER_WIDTH, CHARACTER_HEIGHT))\n\ndef draw_window(lamp, previous_location):\n WIN.blit(BACKGROUND_IMAGE, previous_location, (previous_location[0], previous_location[1], CHARACTER_HEIGHT, CHARACTER_WIDTH))\n WIN.blit(PLAYER_TOKEN, (lamp.x, lamp.y))\n pygame.display.update()\n\n# Function to handle the character's movement.\ndef lamp_handle_movement(keys_pressed, lamp):\n if keys_pressed[pygame.K_LEFT] and lamp.x > 0: # LEFT\n lamp.x -= VEL\n if keys_pressed[pygame.K_RIGHT] and lamp.x + lamp.width < WIDTH: # RIGHT\n lamp.x += VEL\n if keys_pressed[pygame.K_UP] and lamp.y - VEL > 0: # UP\n lamp.y -= VEL\n if keys_pressed[pygame.K_DOWN] and lamp.y + VEL + lamp.height < HEIGHT: # DOWN\n lamp.y += VEL\n\ndef main():\n lamp = pygame.Rect(100, 300, CHARACTER_WIDTH, CHARACTER_HEIGHT)\n\n WIN.blit(BACKGROUND_IMAGE, BACKGROUND_BOX)\n\n clock = pygame.time.Clock()\n run = True\n\n while run:\n clock.tick(FPS)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n \n keys_pressed = pygame.key.get_pressed()\n previous_location = (lamp.x, lamp.y)\n lamp_handle_movement(keys_pressed, lamp)\n draw_window(lamp, previous_location)\n \n pygame.quit()\n\nif __name__ == \"__main__\":\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"338698613","text":"\"\"\"This file contains all the classes you must complete for this project.\n\nYou can use the test cases in agent_test.py to help during development, and\naugment the test suite with your own test cases to further test your code.\n\nYou must test your agent's strength against a set of agents with known\nrelative strength using tournament.py and include the results in your report.\n\"\"\"\nimport random\nimport isolation\n\n\nclass Timeout(Exception):\n \"\"\"Subclass base exception for code clarity.\"\"\"\n pass\n\n\ndef custom_score(game, player):\n return combined_score(game, player)\n\n\n\ndef custom_score_1(game, player):\n return current_candidate(game,player)\n\ndef custom_score_2(game, player):\n return center_focused_score(game,player)\n\n\n\n\n \ndef combined_score(game, player):\n #This heuristics combines the move score and center focused score.\n #It gives different weights to the above two at different stages of the game\n if game.is_loser(player):\n return float(\"-inf\")\n\n if game.is_winner(player):\n return float(\"inf\")\n \n blank_spaces = game.get_blank_spaces()\n board_size = game.height*game.width\n \n #First half of the game\n if 0<=len(blank_spaces)<= board_size/2.0:\n game_status = \"First Half\"\n #Second half of the game\n elif board_size/2.0 < len(blank_spaces) <= board_size:\n game_status = \"Last Half\"\n\n\n\n\n score1 = center_focused_score(game, player)\n score2 = moves_score(game, player)\n game_weight = 5.0\n \n #Set the scores with different emphasis.\n f_score = float( game_weight*score1 + score2 )\n l_score = float(score1 + game_weight*score2)\n \n if game_status == \"First Half\":\n return f_score\n elif game_status == \"Last Half\":\n return l_score\n \n\ndef combo_score(game, player): \n score3 = away_from_blocked_score(game,player)\n score1 = center_focused_score(game, player)\n score2 = moves_score(game, player)\n score = float(score1+2*score2)\n \n return score \n \n\ndef moves_score(game, player ): \n if game.is_loser(player):\n return float(\"-inf\")\n\n if game.is_winner(player):\n return float(\"inf\")\n \n\n own_moves = len(game.get_legal_moves(player)) #Player's moves left\n opp_moves = len(game.get_legal_moves(game.get_opponent(player))) #Opponent's moves left\n own_weight = 1.0 #The weight of the player's moves left\n opp_weight = 4.0 #The weight of the opponent's moves left\n\n score = float(own_weight*own_moves - opp_weight*opp_moves)\n\n return score\n\n\n\ndef away_from_blocked_score(game, player):\n if game.is_loser(player):\n return float(\"-inf\")\n\n if game.is_winner(player):\n return float(\"inf\")\n \n opp_r, opp_c = game.get_player_location(game.get_opponent(player))\n r, c = game.get_player_location(player)\n blank_spaces = game.get_blank_spaces()\n neighbours = []\n for (square_r, square_c) in blank_spaces:\n if max(abs(square_r - r), abs(square_c - c)) == 1:\n neighbours.append( (square_r, square_c))\n score = float(len(neighbours))\n return score\n\n\n \ndef center_focused_score(game, player):\n if game.is_loser(player):\n return float(\"-inf\")\n\n if game.is_winner(player):\n return float(\"inf\")\n \n r, c = game.get_player_location(player)\n \n #Find center cell\n rows = game.height\n cols = game.width\n center_r = int(rows/2)\n center_c = int(cols/2)\n assert center_r == center_c\n \n max_score = center_r +0.5 # Set up center score\n\n\n delta_r = abs(r - center_r)\n delta_c = abs(c - center_c)\n \n #The score will decrease as it gets closer and closer to the edges\n layer = max(delta_r,delta_c)\n score = max_score - layer\n return score\n \n \n\nclass CustomPlayer:\n \"\"\"Game-playing agent that chooses a move using your evaluation function\n and a depth-limited minimax algorithm with alpha-beta pruning. You must\n finish and test this player to make sure it properly uses minimax and\n alpha-beta to return a good move before the search time limit expires.\n\n Parameters\n ----------\n search_depth : int (optional)\n A strictly positive integer (i.e., 1, 2, 3,...) for the number of\n layers in the game tree to explore for fixed-depth search. (i.e., a\n depth of one (1) would only explore the immediate sucessors of the\n current state.)\n\n score_fn : callable (optional)\n A function to use for heuristic evaluation of game states.\n\n iterative : boolean (optional)\n Flag indicating whether to perform fixed-depth search (False) or\n iterative deepening search (True).\n\n method : {'minimax', 'alphabeta'} (optional)\n The name of the search method to use in get_move().\n\n timeout : float (optional)\n Time remaining (in milliseconds) when search is aborted. Should be a\n positive value large enough to allow the function to return before the\n timer expires.\n \"\"\"\n\n def __init__(self, search_depth=3, score_fn=custom_score,\n iterative=True, method='minimax', timeout=10.):\n self.search_depth = search_depth\n self.iterative = iterative\n self.score = score_fn\n self.method = method\n self.time_left = None\n self.TIMER_THRESHOLD = timeout\n\n \n def get_move(self, game, legal_moves, time_left):\n \"\"\"Search for the best move from the available legal moves and return a\n result before the time limit expires.\n\n This function must perform iterative deepening if self.iterative=True,\n and it must use the search method (minimax or alphabeta) corresponding\n to the self.method value.\n\n **********************************************************************\n NOTE: If time_left < 0 when this function returns, the agent will\n forfeit the game due to timeout. You must return _before_ the\n timer reaches 0.\n **********************************************************************\n\n Parameters\n ----------\n game : `isolation.Board`\n An instance of `isolation.Board` encoding the current state of the\n game (e.g., player locations and blocked cells).\n\n legal_moves : list<(int, int)>\n A list containing legal moves. Moves are encoded as tuples of pairs\n of ints defining the next (row, col) for the agent to occupy.\n\n time_left : callable\n A function that returns the number of milliseconds left in the\n current turn. Returning with any less than 0 ms remaining forfeits\n the game.\n\n Returns\n -------\n (int, int)\n Board coordinates corresponding to a legal move; may return\n (-1, -1) if there are no available legal moves.\n \"\"\"\n\n self.time_left = time_left\n\n\n # TODO: finish this function!\n\n # Perform any required initializations, including selecting an initial\n # move from the game board (i.e., an opening book), or returning\n # immediately if there are no legal moves\n \n \n if not legal_moves:\n return (-1, -1)\n \n\n try:\n # The search method call (alpha beta or minimax) should happen in\n # here in order to avoid timeout. The try/except block will\n # automatically catch the exception raised by the search method\n # when the timer gets close to expiring\n \n # Initialisation : s and m1 are for score and best moves for the current depth of search\n #best_score and m2 are for best score of the over all search\n s = float(\"-inf\")\n move =()\n max_depth = game.height*game.width\n center_square = int(game.height/2), int(game.width/2)\n if center_square in legal_moves:\n m1 = center_square\n else:\n m1 = legal_moves[0]\n best_score = float(\"-inf\")\n m2 = m1\n score = float(\"-inf\")\n\n\n if self.iterative == True:\n if self.method == 'minimax':\n \n depth = 1\n while depth <= max_depth:# Iterate depths until there is no more moves left\n #for m in legal_moves:\n # Implement minimax search for every potential moves\n score, move = self.minimax(game, depth)\n # Return with the best moves of the current depth of search\n if score > s:\n s = score\n m1 = move\n # Store the score and best moves so far before funthering to the next search depth\n best_score = s \n m2 = m1\n depth = depth + 1\n #If time is running out, return the best move so far\n if self.time_left() < self.TIMER_THRESHOLD:\n raise Timeout()\n \n elif self.method == 'alphabeta':\n \n depth = 0\n while depth <= max_depth:# Iterate depths until there is no more moves left\n #for m in legal_moves:\n # Implement alpha-beta pruning for every potential moves\n score, move = self.alphabeta(game, depth)\n # Return with the best moves of the current depth of search\n if score > s:\n s = score\n m1 = move\n # Store the score and best moves so far before funthering to the next search depth \n best_score = s\n m2 = m1\n depth = depth + 1\n #print (depth)\n #If time is running out, return the best move so far\n if self.time_left() < self.TIMER_THRESHOLD:\n raise Timeout()\n \n \n \n else:\n #Complete search without iterative deepning\n \n if self.method == 'minimax':\n for m in legal_moves:\n #Implement minimax search, return with the best moves found\n score, _ = self.minimax(game.forecast_move(m), self.search_depth)\n if score > s:\n s = score\n m2 = m\n\n elif self.method == 'alphabeta':\n for m in legal_moves:\n #Implement alpha-beta pruning, return with the best moves found \n score, _ = self.alphabeta(game.forecast_move(m), self.search_depth)\n if score > s:\n s = score\n m2 = m\n #print (s, score, m2, m1)\n\n \n \n \n \n\n except Timeout:\n # Handle any actions required at timeout, if necessary\n return m2\n\n return m2\n # Return the best move from the last completed search iteration\n\n\n def minimax(self, game, depth, maximizing_player=True):\n \"\"\"Implement the minimax search algorithm as described in the lectures.\n\n Parameters\n ----------\n game : isolation.Board\n An instance of the Isolation game `Board` class representing the\n current game state\n\n depth : int\n Depth is an integer representing the maximum number of plies to\n search in the game tree before aborting\n\n maximizing_player : bool\n Flag indicating whether the current search depth corresponds to a\n maximizing layer (True) or a minimizing layer (False)\n\n Returns\n -------\n float\n The score for the current search branch\n\n tuple(int, int)\n The best move for the current branch; (-1, -1) for no legal moves\n\n Notes\n -----\n (1) You MUST use the `self.score()` method for board evaluation\n to pass the project unit tests; you cannot call any other\n evaluation function directly.\n \"\"\"\n\n\n # TODO: finish this function!\n\n #Initialisation: find all the possible moves, and store them in \"moves\" list\n if self.time_left() < self.TIMER_THRESHOLD:\n raise Timeout()\n \n moves = game.get_legal_moves()\n\n #If there is no possible moves any more, return the end-of-game values\n if not moves:\n return game.utility(self), (-1, -1)\n \n #If the current depth is root, return the current best score //\n # and first move from the left end of the search tree\n if depth == 0:\n return self.score(game, self), moves[0]\n \n \n \n if maximizing_player == True: #Max level search\n best_score = float(\"-inf\")\n move = ()\n \n for m in moves:\n #Take values from all the child nodes and store the node with maximum score\n v, _ = self.minimax(game.forecast_move(m), depth-1, maximizing_player = False)\n if v > best_score:\n best_score = v\n move = m\n\n\n \n else: # Min level Search\n best_score = float(\"inf\")\n move = ()\n for m in moves: \n #Take values from all the child nodes and store the node with minimum score \n v, _ = self.minimax(game.forecast_move(m), depth-1, maximizing_player = True)\n if v < best_score:\n best_score = v\n move = m\n \n\n \n return best_score, move\n\n\n\n def alphabeta(self, game, depth, alpha=float(\"-inf\"), beta=float(\"inf\"), maximizing_player=True):\n \"\"\"Implement minimax search with alpha-beta pruning as described in the\n lectures.\n\n Parameters\n ----------\n game : isolation.Board\n An instance of the Isolation game `Board` class representing the\n current game state\n\n depth : int\n Depth is an integer representing the maximum number of plies to\n search in the game tree before aborting\n\n alpha : float\n Alpha limits the lower bound of search on minimizing layers\n\n beta : float\n Beta limits the upper bound of search on maximizing layers\n\n maximizing_player : bool\n Flag indicating whether the current search depth corresponds to a\n maximizing layer (True) or a minimizing layer (False)\n\n Returns\n -------\n float\n The score for the current search branch\n\n tuple(int, int)\n The best move for the current branch; (-1, -1) for no legal moves\n\n Notes\n -----\n (1) You MUST use the `self.score()` method for board evaluation\n to pass the project unit tests; you cannot call any other\n evaluation function directly.\n \"\"\"\n\n #Initialisation: find all the possible moves, and store them in \"moves\" list\n if self.time_left() < self.TIMER_THRESHOLD:\n raise Timeout()\n moves = game.get_legal_moves()\n \n #If there is no possible moves any more, return the end-of-game values\n if not moves:\n return game.utility(self), (-1, -1)\n \n #If the current depth is root, return the current best score //\n # and first move from the left end of the search tree\n if depth == 0:\n return self.score(game, self), moves[0]\n \n if maximizing_player == True: # Max level search\n move = ()\n for m in moves:\n #Take values from all the child nodes and store the node that has score higher than\n #lower boundary value alpha\n v, _ = self.alphabeta(game.forecast_move(m), depth-1, alpha, beta, maximizing_player = False)\n if v > alpha:\n alpha = v #reset alpha with the new value\n move = m\n \n #if any child branch has its highest score smaller than alpha, prune that branch \n if beta <= alpha:\n break\n\n return alpha, move\n\n \n else:\n move = ()\n for m in moves:\n #Take values from all the child nodes and store the node that has score lower than\n #upper boundary value beta\n v, _ = self.alphabeta(game.forecast_move(m), depth-1, alpha, beta, maximizing_player = True)\n if v < beta:\n beta = v #reset beta with the new value\n move = m\n \n #if any child branch has its lowest score larger than beta, prune that branch \n if beta <= alpha:\n break\n \n return beta, move\n\n","sub_path":"game_agent.py","file_name":"game_agent.py","file_ext":"py","file_size_in_byte":17423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"508507780","text":"import boto3\r\n\r\n\r\nclient = boto3.client(\r\n 's3',\r\n # Hard coded strings as credentials, not recommended.\r\n aws_access_key_id='AKIAJ2CZYAIYMGTQA7AA',\r\n aws_secret_access_key='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'\r\n)\r\n# response = client.list_buckets()\r\nlist=client.list_objects(Bucket='letter-for-australia')['Contents']\r\nprint(list)\r\nfor s3_key in list:\r\n s3_object = s3_key['Key']\r\n print(s3_object)\r\n if not s3_object.endswith(\"/\"):\r\n client.download_file('letter-for-australia', s3_object, s3_object+'.pdf')\r\n else:\r\n import os\r\n if not os.path.exists(s3_object):\r\n os.makedirs(s3_object)\r\n# response = client.create_bucket(\r\n# ACL='public-read',\r\n# Bucket='letter-for-australia',\r\n# CreateBucketConfiguration={\r\n# 'LocationConstraint': 'ap-southeast-1'\r\n# }\r\n# )\r\n# print(response)\r\n\r\n# with open('ak.pdf', 'rb') as data:\r\n # print(client.upload_fileobj(data, 'letter-for-australia', 'E12345678'))","sub_path":"AWS/exp/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"371585622","text":"import torch.nn as nn\nimport torch.nn.functional as F\nimport torch\n\n\nclass Basic3DBlock(nn.Module):\n def __init__(self, in_planes, out_planes, kernel_size):\n super(Basic3DBlock, self).__init__()\n self.block = nn.Sequential(\n nn.Conv3d(in_planes, out_planes, kernel_size=kernel_size, stride=1, padding=((kernel_size-1)//2)),\n nn.BatchNorm3d(out_planes),\n nn.ReLU(True)\n )\n \n def forward(self, x):\n return self.block(x)\n\n\nclass Res3DBlock(nn.Module):\n def __init__(self, in_planes, out_planes):\n super(Res3DBlock, self).__init__()\n self.res_branch = nn.Sequential(\n nn.Conv3d(in_planes, out_planes, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm3d(out_planes),\n nn.ReLU(True),\n nn.Conv3d(out_planes, out_planes, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm3d(out_planes)\n )\n\n if in_planes == out_planes:\n self.skip_con = nn.Sequential()\n else:\n self.skip_con = nn.Sequential(\n nn.Conv3d(in_planes, out_planes, kernel_size=1, stride=1, padding=0),\n nn.BatchNorm3d(out_planes)\n )\n \n def forward(self, x):\n res = self.res_branch(x)\n skip = self.skip_con(x)\n return F.relu(res + skip, True)\n\n\nclass Inception3DBlock(nn.Module):\n def __init__(self, in_planes, f1,f3,f5):\n super(Inception3DBlock, self).__init__()\n self.conv1= nn.Sequential(\n nn.Conv3d(in_planes, f1, kernel_size=1, stride=1, padding=0),\n nn.BatchNorm3d(f1),\n nn.ReLU(True)\n )\n self.conv3 = nn.Sequential(\n nn.Conv3d(in_planes, f3, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm3d(f3),\n nn.ReLU(True)\n )\n self.conv5 = nn.Sequential(\n nn.Conv3d(in_planes, f5, kernel_size=5, stride=1, padding=2),\n nn.BatchNorm3d(f5),\n nn.ReLU(True)\n )\n\n def forward(self, X):\n out = torch.cat((self.conv1(X),self.conv3(X),self.conv5(X)),dim=1)\n return F.relu(out, True)\n\n \nclass Pool3DBlock(nn.Module):\n def __init__(self, pool_size):\n super(Pool3DBlock, self).__init__()\n self.pool_size = pool_size\n \n def forward(self, x):\n return F.avg_pool3d(x, kernel_size=self.pool_size, stride=self.pool_size)\n\n\nclass HO_ShapeNet(nn.Module):\n def __init__(self, input_channels, hand_channels, obj_channels):\n super(HO_ShapeNet, self).__init__()\n self.hand_channels = hand_channels\n self.obj_channels = obj_channels\n\n self.front_layers = nn.Sequential(\n Inception3DBlock(input_channels,16,32,64), # (b,112,44,44,44)\n Pool3DBlock(2), # (b,112,22,22,22)\n Inception3DBlock(16 + 32 + 64, 8, 16, 32), # (b,56,22,22,22)\n Pool3DBlock(2), # (b,56,11,11,11)\n Inception3DBlock(8+16+32, 4, 8, 16), # (b,28,11,11,11)\n Inception3DBlock(4+8+16 , 2,4,8), # (b,14,11,11,11)\n )\n self.handlayer_mid = Basic3DBlock(14, 7, 1)\n self.handlayer_end = nn.Linear(7 * 11 * 11 * 11 ,hand_channels*3)\n\n self.objlayer_mid = Basic3DBlock(14, 12, 1)\n self.objlayer_end = nn.Linear(12 * 11 * 11 * 11, obj_channels*3)\n\n self._initialize_weights()\n\n def forward(self, x):\n batch_sz = x.size()[0]\n x_front = self.front_layers(x) # # #(b,14,11,11,11)\n\n in_hand = self.handlayer_mid(x_front)\n hand_verts = self.handlayer_end(in_hand.view(batch_sz,-1))\n\n in_obj = self.objlayer_mid(x_front)\n obj_verts = self.objlayer_end(in_obj.view(batch_sz,-1))\n\n hand_verts = hand_verts.reshape((batch_sz,self.hand_channels,3))\n obj_verts = obj_verts.reshape((batch_sz, self.obj_channels, 3))\n result = {\n 'handverts': hand_verts,\n 'objverts': obj_verts\n }\n return result\n\n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv3d):\n nn.init.normal_(m.weight, 0, 0.001)\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.ConvTranspose3d):\n nn.init.normal_(m.weight, 0, 0.001)\n nn.init.constant_(m.bias, 0)\n","sub_path":"networks/HO_Nets/HO_ShapeNet.py","file_name":"HO_ShapeNet.py","file_ext":"py","file_size_in_byte":4382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"180815966","text":"from django.http import HttpResponse\nfrom django.shortcuts import render, get_object_or_404, get_list_or_404\nimport datetime\nimport sqlite3\n\nconn = sqlite3.connect(SQLITEDB)\ncurr = conn.cursor()\n\ndef unsubscribe(request, email=None):\n if email == None:\n return HttpResponse(\"Huh?\")\n\n date = datetime.date.today()\n ip = request.META['HTTP_X_REAL_IP']\n decodedEmail = email.decode('base64','strict')\n\n sql= '''INSERT INTO mailer (optOut, dateOut, ipOut, mailerEmail) VALUES (\"1\", ?, ?, ?)'''\n curr.execute(sql, (date, ip, decodedEmail))\n conn.commit()\n \n context = { 'title' : 'Unsubscribe', 'email' : decodedEmail, 'ip' : ip, 'todayDate' : date, }\n return render(request, 'mailer/unsubscribe.html', context, content_type=\"text/html\")\n\n","sub_path":"www/mailer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"578480344","text":"from django.contrib.auth import authenticate, login\n\nimport vk\n\nfrom .models import User\n\n\ndef vk_auth(request):\n vk_token = request.GET.get('access_token')\n session = vk.Session()\n api = vk.API(session, v=5.0)\n user_info = api.users.get(access_token=vk_token, fields=['photo_200', ])[0]\n user_id = user_info['id']\n same_user = User.objects.filter(vk_id=user_id)\n if same_user.exists():\n user = authenticate(vk_id=user_id)\n login(request, user)\n return {'success': True}\n else:\n new_user = User(\n vk_id=user_id,\n first_name=user_info['first_name'],\n last_name=user_info['last_name'],\n role='User',\n picture=user_info['photo_200'],\n )\n new_user.save()\n return {'success': True}\n return {'error': True}\n","sub_path":"registration/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"481181053","text":"import subprocess\n\n#Get WiFi Passwords With Python\n#http://nitratine.net/get-wifi-passwords-with-python/\n\n#>netsh wlan show profile twcwifi key=clear\n\n''' Amped_SR | gone2088\nWIFIDADEA5-5G | lulu33880166\nHiWiFi_2E69FC | 1234567890\nAndyCindy | 1122334455\nTIMIOS | northpole\n '''\n\n''' a = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles'])\nprint(a)\n\na = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']).decode('utf-8', errors=\"ignore\")\nprint(a)\nprint(type(a)) '''\n\na = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']).decode('utf-8', errors=\"ignore\").split('\\n')\nprint('11111-----')\nprint(type(a))\nprint(a)\n\n''' a = [i for i in a if \"All User Profile\" in i]\nprint('22222------')\nprint(type(a))\nprint(a) '''\n\na = [i.split(\":\")[1][1:-1] for i in a if \"All User Profile\" in i]\nfor i in a:\n print('3----- ', i)\n try:\n results = subprocess.check_output(['netsh', 'wlan', 'show', 'profile', i, 'key=clear']).decode('utf-8', errors=\"ignore\").split('\\n')\n results = [b.split(\":\")[1][1:-1] for b in results if \"Key Content\" in b]\n try:\n print (\"{:<30}| {:<}\".format(i, results[0]))\n except IndexError:\n print (\"{:<30}| {:<}\".format(i, \"\"))\n except subprocess.CalledProcessError:\n print (\"{:<30}| {:<}\".format(i, \"ENCODING ERROR\"))\n\na = input(\"\")\n\n","sub_path":"Python_Fun/python_wifi_pw.py","file_name":"python_wifi_pw.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"303122061","text":"from random import randint as random\n\n# Имена.\nmale_names = ['John', 'Steve', 'Kevin', 'Bill', 'Adam', 'Ivan', 'Oleg', 'Mikhail', 'Alexandr', 'Vladimir', 'Mikle']\nfemale_names = ['Lucy', 'Mary', 'Kate', 'Eve', 'Liza', 'Olga', 'Nastya', 'Marlin', 'Britnie']\nsurnames = ['Brown', 'Smith', 'Johnson', 'Williams', '\tJones', 'Miller', 'Jackson']\n\nclass Person:\n people = []\n\n PRICE_OF_SCHOOL = 10\n HARD_TO_LIFE = 0.03\n TAXES = 0.5\n MAX_CHILDREN = 4\n DAMAGE_OF_WORK = 1\n chance_born = 20\n chance_work = 50\n GIFT_MIN = 20\n GIFT_MAX = 50\n MARY_DESIRE = 10 # if random(0, (len(self.people) // MARY_DESIRE + 1)) == 0: mary(self, i) Чем больше тем больше невест перебирает жених прежде чем женится.\n WORK_YEARS_MAX = 60 # Пенсия.\n WORK_YEARS_MIN = 18 # Детский труд.\n SMALL_OF_PENSION = 0.1\n SMALL_OF_CHILD = 0.1\n GIFT_TO_CHILD = 0.1\n\n life = True\n skillsens = 0\n skill = 0\n health = 100.0\n years = 0\n married = False\n def __init__(self, name = '', surname = '', female = False, money = 0, step = 0, Active = True):\n if Active:\n self.spouse = Person('-', '-', not(female), 0, step, False)\n self.step = step\n self.name = name\n self.surname = surname\n self.money = money\n self.female = female\n self.skillsens = random(1,10) / 5\n self.children = list()\n\n def decide(self):\n if self.life:\n if self.money < 10:\n work(self)\n else:\n\n g = self.money * self.GIFT_TO_CHILD / (len(self.children) + 1)\n for i in self.children:\n i.money += g\n self.money -= g\n\n r = random(0,100)\n if r < Person.chance_born:\n if self.married == True:\n if self.female:# Если это женщина то она рожает.\n if len(self.children) < Person.MAX_CHILDREN + 1:\n born(self, self.people)\n else:\n study(self,self)\n else:# Если это мужчина, то он вместо рождения ребёнка материально помогает жене и детям материально.\n gift = random(self.GIFT_MIN, self.GIFT_MAX) / 100 * self.money\n print('gift:', self.name, ' ', gift,' -> ', self.spouse.name)\n self.money -= gift\n self.spouse.money += gift\n for i in self.children:\n gift = random(self.GIFT_MIN, self.GIFT_MAX) / 100 * self.money\n print('gift:', self.name, ' ', gift, ' -> ', i.name)\n self.money -= gift\n i.money += gift\n else:\n for i in self.people:\n if i.female != self.female:\n if random(0, (len(self.people) // self.MARY_DESIRE + 1)) == 0:\n mary(self, i) # Do func mary!!!\n\n\n elif r < (Person.chance_born + Person.chance_work):\n work(self)\n else:\n study(self, self)\n\ndef mary(sp1, sp2):\n print(sp1.name, '0O with ', sp2.name)\n sp1.spouse = sp2\n sp2.spouse = sp1\n sp1.married = True\n sp2.married = True\n\n if sp1.female:\n sp1.surname = sp2.surname\n else:\n sp2.surname = sp1.surname\n\ndef study(parent, student):\n parent.money -= Person.PRICE_OF_SCHOOL\n student.skill += student.skillsens\n\ndef work(worker):\n zp = worker.skill ** 2 // 2 + 2\n if worker.years > Person.WORK_YEARS_MAX:\n zp = zp * Person.SMALL_OF_PENSION\n if worker.years < Person.WORK_YEARS_MIN:\n zp = zp * Person.SMALL_OF_CHILD\n worker.money += zp\n worker.health -= Person.DAMAGE_OF_WORK / (worker.skill + 1) + 0.5\n\ndef born(parent, people):\n if parent.female:\n female = random(0,1)\n money = parent.money // 2\n parent.money -= money\n if female == 0:\n ran = random( 0,(len(male_names) - 1) )\n name = male_names[ran]\n\n ran = random(0,10)\n if ran == 0:\n\n ran = random( 0,(len(surnames) - 1) )\n surname = surnames[ran]\n else:\n surname = parent.spouse.surname\n\n\n pers = Person(name, surname, False, money, parent.step + 1)\n people.append(pers)\n parent.children.append(pers)\n\n print(parent.name, ' borned boy and called him ', name)\n\n else:\n ran = random( 0,(len(female_names) - 1) )\n name = female_names[ran]\n surname = parent.spouse.surname\n pers = Person(name, surname, True, money, parent.step + 1)\n people.append(pers)\n parent.children.append(pers)\n\n print(parent.name, ' borned girl and called her ', name)\n\n\n\n\n","sub_path":"person.py","file_name":"person.py","file_ext":"py","file_size_in_byte":5222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"436769058","text":"from flask import Flask\nfrom flask_restful import Api\nfrom flask_jwt import JWT\nfrom flask_cors import CORS\nfrom flasgger import Swagger\n\nfrom security import authenticate, identity\nfrom resources.user import UserRegister\nfrom resources.customer import Customer, CustomerList\nfrom resources.score import Score, ScoreList\n\napp = Flask(__name__)\n#cors = CORS(app)\ncors = CORS(app, resorces={r'/*': {\"origins\": '*'}})\napp.config['CORS_HEADERS'] = 'application/json'\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.secret_key = 'EiEiO'\napi = Api(app)\n\n\n@app.before_first_request\ndef create_tables():\n db.create_all()\n\n\napp.config['SWAGGER'] = {\n \"uiversion\": 3,\n \"swagger_version\": \"3.0\",\n \"title\": \"challenge API\",\n \"specs_route\": \"/challenge-api-docs/\",\n \"description\": \"This is the version 1 challenge API\",\n}\n\nSwagger(app)\n\njwt = JWT(app, authenticate, identity)\n\napi.add_resource(Score, '/score/')\napi.add_resource(ScoreList, '/scores')\napi.add_resource(Customer, '/customer/')\napi.add_resource(CustomerList, '/customers')\napi.add_resource(UserRegister, '/register')\n\nif __name__ == '__main__':\n from db import db\n db.init_app(app)\n app.run(host='0.0.0.0', port=80, debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"469787687","text":"from random import uniform\n\nimport pytest\nfrom steps.cdb import select_cdb_document, save_document_couchdb\nfrom steps.object import get_item_from, correspond_selected_object, check_count\nfrom steps.waitings import waiting_tasks_processing, waiting_couchdb_seq\nfrom utils.getter import gen_couchdb_id, get_time_in_format\n\n\n@pytest.allure.CRITICAL\n@pytest.allure.feature('REST.Functional - Склад - Заявки(demand)')\n@pytest.mark.demand\n@pytest.mark.functional_tests\n@pytest.mark.store\n@pytest.mark.usefixtures('reset_layer')\nclass TestSeleniumSmokeNomenclatureDemand:\n # Background #######################################################################################################\n @pytest.fixture()\n @pytest.allure.step('Background')\n def background(self, rest_api, psql, couchdb):\n background_result = dict()\n\n # Настройки себестоимости\n background_result['org_settings'] = rest_api.select_objects('core.company')['ds']\n background_result['org_set'] = get_item_from(\n background_result['org_settings'],\n amount='single',\n condition='random',\n table=None\n )\n background_result['org_set'].update(\n {\n 'actualBalancePrimeCost': 'FUTURE',\n 'balancePrimeCost': 'POSITIVE_AND_NEGATIVE',\n 'negativeBalanceContribution': 'ONE',\n 'primeCostCalculationMethod': 'AVG_POSITIVE',\n 'routeWithdrawMode': 'BYROUTEWITHDRAWTYPE',\n 'snapshotBalancePrimeCost': 'BEFORE',\n 'zeroBalanceContribution': 'NIL'\n }\n )\n background_result['org_set'] = rest_api.send_update(\n 'core.company',\n background_result['org_set'],\n )\n\n background_result['measure_list'] = rest_api.select_objects('core.dictionaries.measureunits')['ds']\n background_result['measure_pc'] = get_item_from(\n background_result['measure_list'],\n amount='single',\n condition='table',\n table={\n 'title': 'пц'\n }\n )\n background_result['measure_sht'] = get_item_from(\n background_result['measure_list'],\n amount='single',\n condition='table',\n table={\n 'title': 'шт'\n }\n )\n background_result[\"background_result['org_settings']\"] = rest_api.select_objects('core.company')['ds']\n background_result[\"background_result['org_set']\"] = get_item_from(\n background_result['org_settings'],\n amount='single',\n condition='random',\n table=None\n )\n background_result['org_set'].update(\n {\n 'dishBaseMeasureUnit': background_result['measure_pc'],\n 'modBaseMeasureUnit': background_result['measure_pc'],\n 'productBaseMeasureUnit': background_result['measure_sht'],\n 'semiproductBaseMeasureUnit': background_result['measure_sht']\n }\n )\n background_result['org_set'] = rest_api.send_update(\n 'core.company',\n background_result['org_set'],\n )\n\n background_result['cooking_franch'] = select_cdb_document(couchdb, 'cooking_place-')\n background_result['cooking_franch_1'] = get_item_from(\n background_result['cooking_franch'],\n amount='single',\n condition='random',\n table=None\n )\n background_result['sale_franch'] = select_cdb_document(couchdb, 'sale_place-')\n background_result['sale_franch_1'] = get_item_from(\n background_result['sale_franch'],\n amount='single',\n condition='random',\n table=None\n )\n background_result['store_list'] = rest_api.select_objects('warehouse.store')['ds']\n background_result['store_1'] = get_item_from(\n background_result['store_list'],\n amount='single',\n condition='table',\n table={\n 'title': 'Склад 1'\n }\n )\n background_result['terminal_rq'] = {\n 'battery': 100,\n 'localIp': '127.0.0.1',\n 'ssid': 'QuickResto 2.4GHz',\n 'title': 'Терминал 1'\n }\n\n background_result['terminal_document'] = {\n '_id': 'terminal-1',\n 'deviceManufacturer': '',\n 'deviceModel': 'Тестовый',\n 'name': 'Терминал 1',\n 'rq': background_result['terminal_rq'],\n 'state': 'new',\n 'tokenOwner': 'terminal-1',\n 'updateSource': 'terminal-1'\n }\n\n save_document_couchdb(couchdb, background_result['terminal_document'])\n waiting_couchdb_seq(couchdb, psql)\n\n # Было ожидание 2\n waiting_tasks_processing(psql)\n return background_result\n\n # Scenario 0 #######################################################################################################\n @pytest.allure.story(\"\"\"Создание заявки, проверка\"\"\")\n @pytest.mark.demand_0\n @pytest.mark.case_0\n def test_case_functional_demand_0(self, rest_api, psql, couchdb, background):\n with pytest.allure.step('Step 1 #####################################'):\n # Создаем блюдо\n dish = rest_api.send_create(\n 'warehouse.nomenclature.dish',\n 'item',\n {\n 'basePriceInList': round(uniform(100, 999), 3),\n 'designator': 'dish',\n 'name': 'Блюдо 1',\n 'routeWithdrawType': 'BYROUTING'\n }\n )\n\n # Создаем товар для Блюда\n single = rest_api.send_create(\n 'warehouse.nomenclature.singleproduct',\n 'item',\n {\n 'designator': 'single',\n 'name': 'Товар 1'\n }\n )\n\n # Добавляем товар в техкарту блюда\n rest_api.send_create(\n 'warehouse.nomenclature.routecard',\n 'item',\n payload_table={\n 'cardProduct': single,\n 'cardProductQty': 2,\n 'finalWeight': 2,\n 'grossWeightBaseMeasureUnit': 2,\n 'grossWeightKg': 2,\n 'netWeight': 2\n },\n params={\n 'owner_object': dish,\n 'object_version': 1\n }\n )\n dish = rest_api.send_update(\n 'warehouse.nomenclature.dish',\n dish,\n )\n\n # Создаем склад 2\n litebusiness = rest_api.select_objects('core.company.businesses.litebusiness')['ds']\n store_2 = rest_api.send_create(\n 'warehouse.store',\n 'item',\n {\n 'liteBusiness': litebusiness[0]['object'],\n 'title': 'Склад 2'\n }\n )\n\n with pytest.allure.step('Step 2 #####################################'):\n # Запрашиваем документ блюда\n product_docs = select_cdb_document(couchdb, 'product-')\n prod_1 = get_item_from(\n product_docs,\n amount='single',\n condition='table',\n table={\n 'name': dish['name']\n }\n )\n\n # Запрашиваем данные для документа demand-\n current_time = get_time_in_format(\n format_time='couchdb',\n offset_min=0\n )\n current_time_tz = get_time_in_format(\n format_time='couchdbtz',\n offset_min=0\n )\n\n user_list = select_cdb_document(couchdb, 'user-')\n user_waiter = get_item_from(\n user_list,\n amount='single',\n condition='table',\n table={\n 'firstName': 'test'\n }\n )\n\n tablescheme_list = rest_api.select_objects('front.tablemanagement')['ds']\n tablescheme_1 = get_item_from(\n tablescheme_list,\n amount='single',\n condition='table',\n table={\n 'name': 'Заведение 1'\n }\n )\n\n # Создаем документ demand-\n demand = {\n '_id': gen_couchdb_id('demand'),\n 'blocked': False,\n 'createFrontDocId': 'terminal-1',\n 'createTime': current_time,\n 'createTimeTZ': current_time_tz,\n 'createUserDocId': user_waiter['_id'],\n 'items': [\n {\n 'cookingPlaceDocId': background['cooking_franch_1']['_id'],\n 'name': prod_1['name'],\n 'productDocId': prod_1['_id'],\n 'quantity': 3,\n 'salePlaceDocId': background['sale_franch_1']['_id']\n }\n ],\n 'lastFrontRevision': False,\n 'nodeIndex': 0,\n 'purged': True,\n 'tablesSchemeDocId': tablescheme_1['refId'],\n 'terminalDocId': 'terminal-1',\n 'tokenOwner': 'back',\n 'updateFrontDocId': 'terminal-1',\n 'updateSource': 'terminal-1',\n 'updateTime': current_time,\n 'updateTimeTZ': current_time_tz,\n 'updateUserDocId': user_waiter['_id'],\n 'userDocId': user_waiter['_id']\n }\n\n save_document_couchdb(couchdb, demand)\n waiting_couchdb_seq(couchdb, psql)\n\n # Было ожидание 3\n waiting_tasks_processing(psql)\n with pytest.allure.step('Step 3 #####################################'):\n # Проверяем заявку в БО\n demand_list = rest_api.select_objects('warehouse.documents.demand')['ds']\n check_count(demand_list, 1, 'demand_list')\n correspond_selected_object(\n demand_list[0]['object'],\n {\n 'operatorName': 'test test',\n 'status': 'new',\n 'terminalName': 'Тестовый #1'\n }\n )\n\n demand_items = rest_api.select_objects(\n 'warehouse.documents.demand.demanditem',\n {\n 'owner_object': demand_list[0]['object']\n }\n )['ds']\n check_count(demand_items, 1, 'demand_items')\n correspond_selected_object(\n demand_items[0]['object'],\n {\n 'amount': 3,\n 'measureUnitName': dish['measureUnit']['title'],\n 'productClassName': dish['className'],\n 'storeItemName': dish['name']\n }\n )\n\n demand_components = rest_api.select_objects(\n 'warehouse.documents.demand.demandcomponent',\n {\n 'owner_object': demand_list[0]['object']\n }\n )['ds']\n check_count(demand_components, 1, 'demand_components')\n correspond_selected_object(\n demand_components[0]['object'],\n {\n 'amount': 6,\n 'product': {\n 'title': single['name'],\n },\n 'productClassName': single['className'],\n 'store': {\n 'title': background['store_1']['title'],\n }\n }\n )\n\n with pytest.allure.step('Step 4 #####################################'):\n # Создаем ВП через заявку\n rest_api.send_create(\n 'warehouse.documents.demand.demandexchange',\n 'item',\n {\n 'comment': 'Заявка',\n 'fromStore': background['store_1'],\n 'store': store_2\n },\n params={\n 'owner_object': demand_list[0]['object'],\n 'object_version': None\n }\n )\n exchange = rest_api.send_update(\n 'warehouse.documents.demand',\n demand_list[0]['object'],\n )\n\n # Проводим созданную ВП\n rest_api.send_action(\n 'warehouse.documents.demand.demandexchange',\n {\n 'actionName': 'process',\n 'data': {\n 'timeZone': -300,\n },\n 'ids': [1],\n 'owner': {\n 'ownerContextClassName': exchange['className'],\n },\n 'ownerContextId': exchange['id']\n },\n )\n waiting_tasks_processing(psql)\n\n with pytest.allure.step('Step 5 #####################################'):\n # Проверяем ВП в селекторе, модуле Склад\n exchange_list = rest_api.select_objects('warehouse.documents.exchange')['ds']\n check_count(exchange_list, 1, 'exchange_list')\n correspond_selected_object(\n exchange_list[0]['object'],\n {\n 'comment': 'Заявка',\n 'documentNumber': 'ВП1'\n }\n )\n\n # Проверяем селектор, остатки, отчет по движению\n single_list = rest_api.select_objects('warehouse.nomenclature.singleproduct')['ds']\n check_count(single_list, 1, 'single_list')\n correspond_selected_object(\n single_list[0]['object'],\n {\n 'currentPrimeCost': 0,\n 'measureUnitName': single['measureUnitName'],\n 'storeQuantity': 0\n }\n )\n\n single_balance = rest_api.select_objects(\n 'warehouse.nomenclature.balances',\n {\n 'owner_object': single_list[0]['object']\n }\n )['ds']\n check_count(single_balance, 2, 'single_balance')\n correspond_selected_object(\n single_balance,\n {\n 'balance': -6,\n 'balanceBaseMU': -6,\n 'measureUnitName': single['measureUnitName']\n },\n select_option={\n 'store': {\n 'title': background['store_1']['title'],\n }\n }\n )\n correspond_selected_object(\n single_balance,\n {\n 'balance': 6,\n 'balanceBaseMU': 6,\n 'measureUnitName': single['measureUnitName']\n },\n select_option={\n 'store': {\n 'title': store_2['title'],\n }\n }\n )\n\n waiting_tasks_processing(psql)\n single_movement = rest_api.select_objects(\n 'warehouse.nomenclature.singleproduct_movement',\n {\n 'owner_object': single_list[0]['object'],\n 'custom_params': {\n 'mode': 'previous60Days'\n }\n }\n )['ds']\n check_count(single_movement, 2, 'single_movement')\n correspond_selected_object(\n single_movement,\n {\n 'amount': -6,\n 'amountAtStore': -6,\n 'documentId': 'ВП1',\n 'primeCost': 0,\n 'product': {\n 'title': single['title'],\n },\n 'type': 'ExchangeInvoice'\n },\n select_option={\n 'store': {\n 'title': background['store_1']['title'],\n }\n }\n )\n correspond_selected_object(\n single_movement,\n {\n 'amount': 6,\n 'amountAtStore': 6,\n 'documentId': 'ВП1',\n 'primeCost': 0,\n 'product': {\n 'title': single['title'],\n },\n 'type': 'ExchangeInvoice'\n },\n select_option={\n 'store': {\n 'title': store_2['title'],\n }\n }\n )\n\n # Проверяем селектор, остатки, отчет по движению\n dish_list = rest_api.select_objects('warehouse.nomenclature.dish')['ds']\n check_count(dish_list, 1, 'dish_list')\n correspond_selected_object(\n dish_list[0]['object'],\n {\n 'currentPrimeCost': 0,\n 'measureUnitName': dish['measureUnitName'],\n 'storeQuantity': 0\n }\n )\n\n dish_balance = rest_api.select_objects(\n 'warehouse.nomenclature.balances',\n {\n 'owner_object': dish_list[0]['object']\n }\n )['ds']\n check_count(dish_balance, 2, 'dish_balance')\n correspond_selected_object(\n dish_balance,\n {\n 'balance': 0,\n 'balanceBaseMU': 0,\n 'measureUnitName': dish['measureUnitName']\n },\n select_option={\n 'store': {\n 'title': background['store_1']['title'],\n }\n }\n )\n correspond_selected_object(\n dish_balance,\n {\n 'balance': 0,\n 'balanceBaseMU': 0,\n 'measureUnitName': dish['measureUnitName']\n },\n select_option={\n 'store': {\n 'title': store_2['title'],\n }\n }\n )\n\n dish_movement = rest_api.select_objects(\n 'warehouse.nomenclature.singleproduct_movement',\n {\n 'owner_object': dish_list[0]['object']\n }\n )['ds']\n check_count(dish_movement, 0, 'dish_movement')\n","sub_path":"scenarios/rest/functional_tests/documents/test_functional_demand.py","file_name":"test_functional_demand.py","file_ext":"py","file_size_in_byte":19232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"556534526","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\nfrom typing import Optional\nfrom copy import deepcopy\nfrom src.subgraph import SubGraph\nimport numpy as np\nfrom sklearn.cluster import DBSCAN\nimport logging\n\n\ndef create_fabric(fabric_uid: str,\n anomaly_threshold: float = 4.0,\n slow_learn_rate: float = 0.1,\n fast_learn_rate: float = 0.7,\n ltm_attention_heads: int = 3,\n prune_threshold: float = 0.01,\n generalisation_sensitivity: float = 1.0,\n normalise_groups: dict = None) -> dict:\n \"\"\"\n function to create the basic fabric structure\n \n :param fabric_uid: a unique identifier of this part of the fabric\n :param anomaly_threshold: the number of standard deviations in error above which is considered an anomaly\n :param slow_learn_rate: the learning rate to adjust the mapping errors and standard deviations\n :param fast_learn_rate: the learning rate used to adjust each neuron's distance threshold and the fastest learning rate for long-term-memory\n :param ltm_attention_heads: the number of attention heads used to learn sequences\n :param prune_threshold: the probability threshold below which an edge is considered not to exist and thus deleted\n :param generalisation_sensitivity: 1.0 = standard, below 1.0 decreases generalisation and potentially over-fitting, above 1.0 increases generalisation and thus potentially under-fitting \n :param normalise_groups: a dictionary mapping edge types to a normalisation group - allows different edge types to be normalised together \n :return: fabric dictionary\n \"\"\"\n\n fabric = {\n # the unique identify for this fabric\n #\n 'uid': fabric_uid,\n\n # the domains of neural gas\n #\n 'domains': {},\n\n # a factor for adjusting the generalisation\n #\n 'generalise_factor': generalisation_sensitivity,\n\n # threshold for edge probabilities below which assumed to be zero and deleted - speed optimisation as reduces number of edges to\n # search through and learn\n #\n 'prune_threshold': prune_threshold,\n\n # the alpha used for fast learning\n #\n 'fast_learn_rate': fast_learn_rate,\n\n # the alpha used for slow learning\n #\n 'slow_learn_rate': slow_learn_rate,\n\n # the number of exponential moving averages that maintain the long term memory of a sequence\n #\n 'attention_heads': ltm_attention_heads,\n\n # a SubGraph of the long term memory of all training sub graphs seen so far\n #\n 'long_term_memory': None,\n\n # dictionary of edge_types and corresponding normalisation group\n #\n 'normalise_groups': {},\n\n # unique ID for each update to the fabric\n #\n 'update_id': 0,\n\n # number of standard deviations for anomaly detection\n #\n 'anomaly_stdev_threshold': anomaly_threshold,\n\n # flag indicates attributes at this level of the fabric have changed\n #\n 'updated': True\n }\n\n if normalise_groups is not None:\n fabric['normalise_groups'] = normalise_groups\n\n logging.debug(f'created fabric: {fabric}')\n \n return fabric\n\n\ndef add_domain(fabric: dict, \n domain: str) -> None:\n \"\"\"\n function to add a new domain to a fabric\n \n :param fabric: the fabric to add the domain to\n :param domain: the name of the new domain\n :return: None\n \"\"\"\n \n fabric['domains'][domain] = {\n # the number of times this domain have been trained\n #\n 'mapped': 0,\n\n # the next neuron ID to be used in this domain\n #\n 'next_neuron_id': 0,\n\n # the neuron id that was the last BMU\n #\n 'last_bmu_id': None,\n\n # the exponential moving average of the mapping error for this domain\n #\n 'ema_error': None,\n\n # the exponential moving average of the variance of the error for this domain\n #\n 'ema_variance': 0.0,\n\n # the current error threshold above which would be considered an anomaly\n #\n 'anomaly_threshold': 0.0,\n\n # dictionary of anomalies keyed by ref id of the update\n #\n 'anomalies': {},\n\n # the error threshold below wich would be considered a motif\n #\n 'motif_threshold': float('inf'),\n\n # dictionary of motifs keyed by ref id of the update\n #\n 'motifs': {},\n\n # dictionary of neurons in domain keyed by neuron id\n #\n 'neurons': {},\n\n # dictionary of mins and maxes keyed by group of edge types\n #\n 'sg_edge_min_max': {},\n\n # edge types used for finding the bmu\n #\n 'search_edge_types': set(),\n\n # flag to indicate the attributes at this level have changed\n #\n 'updated': True\n }\n\n logging.debug(f'added domain:{domain} to fabric {fabric[\"uid\"]}')\n\n\ndef add_neuron(fabric: dict, \n domain: str, \n sub_graph: SubGraph, \n distance_threshold: float) -> str:\n \"\"\"\n function adds a new neruon to the fabric domain\n \n :param fabric: the fabric to update\n :param domain: the domain to update\n :param sub_graph: the SubGraph the neuron represents\n :param distance_threshold: the initial distance threshold for this neuron\n :return: the id of the new neuron\n \"\"\"\n\n # get the next neuron id\n #\n new_id = str(fabric['domains'][domain]['next_neuron_id'])\n fabric['domains'][domain]['next_neuron_id'] += 1\n\n neuron = {\n\n # sub_graph that represents the learned generalisation of edges\n #\n 'generalisation': SubGraph(sub_graph),\n\n # the number of times this neuron has been a BMU\n #\n 'n_bmu': 1,\n\n # the update stamp when this neuron was the last BMU\n #\n 'last_bmu': fabric['update_id'],\n\n # the number of times this neuron has been a runner up\n #\n 'n_runner_up': 0,\n\n # the update stamp when this neuron was last a runner up\n #\n 'last_runner_up': None,\n\n # the exponential moving average mapping error for this neuron\n #\n 'ema_error': 0.0,\n\n # the learnt edges to other neurons\n #\n 'synapses': SubGraph(),\n\n # the community label fro this neuron\n #\n 'community': 0,\n\n # the error threshold for this neuron - below which this neuron is considered a BMU\n #\n 'threshold': fabric['generalise_factor'] * distance_threshold,\n\n # flag to indicate the attributes at this level ahev changed\n #\n 'updated': True\n }\n\n fabric['domains'][domain]['neurons'][new_id] = neuron\n\n logging.debug(f'added neuron: {new_id} to domain{domain} in fabric {fabric[\"uid\"]}')\n\n return new_id\n\n\ndef get_generalised_distance(fabric: dict, \n domain: str, \n sub_graph: SubGraph, \n search_edge_types: set, \n edge_type_weights: Optional[dict] = None) -> list:\n \"\"\"\n function to calculate the distances of an sub_graph to all neurons within the domain of a fabric\n :param fabric: the fabric that contains the domain\n :param domain: the domain that constains the neurons\n :param sub_graph: the SubGraph to compare to the neurons\n :param search_edge_types: a set of edge types that will be compared\n :param edge_type_weights: a dictionary mapping edge types to a weight - if None then weight assumed to be equal\n :return: a list of tuples containing the neuron_id, the distance, the path of reasoning explaining the contribution of each edge\n \"\"\"\n distances = []\n\n for neuron_id in fabric['domains'][domain]['neurons']:\n distance, por = fabric['domains'][domain]['neurons'][neuron_id]['generalisation'].calc_euclidean_distance(sub_graph=sub_graph,\n compare_edge_types=search_edge_types,\n edge_type_weights=edge_type_weights)\n distances.append((neuron_id, distance, por, fabric['domains'][domain]['neurons'][neuron_id]['n_bmu']))\n\n # sort in neurons ascending order of distance and descending order of n_bmu (in case two or more have same distance prefer the most updated)\n #\n distances.sort(key=lambda x: (x[1], -x[3]))\n\n logging.debug(f'calculated distance against {len(fabric[\"domains\"][domain][\"neurons\"])} neurons in domain: {domain} fabric {fabric[\"uid\"]}')\n\n return distances\n\n\ndef update_domain_error(fabric: dict, \n domain: str,\n bmu_id: str,\n error: float,\n ref_id: str,\n new_id: Optional[str] = None,\n ) -> tuple:\n \"\"\"\n function to update the domain's mapping error and to detect anomalies or motifs \n :param fabric: the fabric to update\n :param domain: the domain to update\n :param bmu_id: the id of the BMU neuron\n :param new_id: the id of the new neuron\n :param error: the distance error of the incoming SubGraph to the BMU\n :param ref_id: the external reference id to log with an anomaly or motif\n :return: tuple containing booleans: (IsAnomaly, IsMotif)\n \"\"\"\n\n # update the exponential moving average error - note first value equals first error recording\n #\n if fabric['domains'][domain]['ema_error'] is None:\n fabric['domains'][domain]['ema_error'] = error\n else:\n fabric['domains'][domain]['ema_error'] += (error - fabric['domains'][domain]['ema_error']) * fabric['slow_learn_rate']\n\n fabric['domains'][domain]['ema_variance'] += (pow(error - fabric['domains'][domain]['ema_error'], 2) - fabric['domains'][domain]['ema_variance']) * fabric['slow_learn_rate']\n\n # record breaches of anomaly threshold\n #\n report: dict = {'bmu_id': bmu_id, 'new_id': new_id, 'mapped': fabric['domains'][domain]['mapped'], 'error': error}\n anomaly = False\n motif = False\n\n if error > fabric['domains'][domain]['anomaly_threshold']:\n fabric['domains'][domain]['anomalies'][ref_id] = report\n anomaly = True\n elif error <= fabric['domains'][domain]['motif_threshold']:\n fabric['domains'][domain]['motifs'][ref_id] = report\n motif = True\n\n # update thresholds for next training data\n #\n stdev = np.sqrt(fabric['domains'][domain]['ema_variance'])\n fabric['domains'][domain]['anomaly_threshold'] = fabric['domains'][domain]['ema_error'] + (fabric['anomaly_stdev_threshold'] * stdev)\n fabric['domains'][domain]['motif_threshold'] = max(fabric['domains'][domain]['ema_error'] - (2 * stdev), 0.0)\n\n fabric['domains'][domain]['updated'] = True\n\n logging.debug(f'updated mapping errors for domain: {domain} fabric: {fabric[\"uid\"]} anomaly: {anomaly} motif: {motif}')\n\n return anomaly, motif\n\n\ndef update_synapse(fabric: dict, \n learn_rate: float,\n source_domain: str, \n source_id: str, \n target_domain: str, \n target_id: str, \n edge_type: str,\n edge_uid: Optional[str] = None\n ) -> None:\n \"\"\"\n function to update the synapse sub_graph of a neuron with an edge\n :param fabric: the fabric that contains the domain\n :param learn_rate: the learn rate to learn the edge\n :param source_domain: the domain that contains the source neuron\n :param source_id: the id of the source neuron\n :param target_domain: the domain that contains the target neuron \n :param target_id: the id of the target neuron\n :param edge_type: the type of edge to create\n :param edge_uid: the uid of the edge to create\n :return: None\n \"\"\"\n\n # create a sub graph to learn\n #\n sub_graph = SubGraph()\n sub_graph.set_item(source_node=(source_domain, source_id),\n edge=(edge_type, edge_uid),\n target_node=(target_domain, target_id))\n\n fabric['domains'][source_domain]['neurons'][source_id]['synapses'].learn(sub_graph=sub_graph,\n learn_rate=learn_rate,\n learn_edge_types={edge_type},\n prune_threshold=fabric['prune_threshold'])\n\n fabric['domains'][target_domain]['neurons'][target_id]['updated'] = True\n\n logging.debug(f'updated edge: ({edge_type},{edge_uid}) source neuron: ({source_domain},{source_id}) target neuron: ({target_domain},{target_id})')\n\n\ndef update_generalisation(fabric: dict, \n domain: str, \n neuron_id: str, \n sub_graph: SubGraph,\n learn_rate: float, \n learn_edge_types: set) -> None:\n \"\"\"\n function updates the generalisation for a neuron\n :param fabric: the fabric that contains the domain\n :param domain: the domain that contains the neuron\n :param neuron_id: the neuron id\n :param sub_graph: the sub_graph to learn\n :param learn_rate: \n :param learn_edge_types: \n :return: \n \"\"\"\n\n fabric['domains'][domain]['neurons'][neuron_id]['generalisation'].learn(sub_graph=sub_graph,\n learn_rate=learn_rate,\n learn_edge_types=learn_edge_types,\n prune_threshold=fabric['prune_threshold'])\n\n fabric['domains'][domain]['neurons'][neuron_id]['updated'] = True\n\n logging.debug(f'updated generalised graph for neuron:{neuron_id} in domain: {domain} in fabric {fabric[\"uid\"]}')\n\n\ndef normalise_sub_graph(fabric: dict,\n domain: str,\n sub_graph: SubGraph) -> SubGraph:\n \"\"\"\n function normalises any edge in the sub graph that has a numeric value - the fabric keeps track of the max and min values seen so far and will re-normalise\n any neuron generalisation if the max or mins are exceeded \n :param fabric: the fabric that contains the domain\n :param domain: the domain that contains the neurons that this sub graph will be normailsed for\n :param sub_graph: the sub graph to normalise\n :return: a normalised sub graph\n \"\"\"\n\n norm_sg = SubGraph(sub_graph=sub_graph)\n\n renormalise_edges = set()\n\n for edge in norm_sg:\n if norm_sg[edge]['numeric'] is not None:\n\n # if this edge type isnt in the normalise groups dict then add\n #\n if norm_sg[edge]['edge_type'] not in fabric['normalise_groups']:\n fabric['normalise_groups'][norm_sg[edge]['edge_type']] = norm_sg[edge]['edge_type']\n\n group = fabric['normalise_groups'][norm_sg[edge]['edge_type']]\n\n # update the global min and max for this edge\n #\n if group not in fabric['domains'][domain]['sg_edge_min_max']:\n fabric['domains'][domain]['sg_edge_min_max'][group] = {'min': norm_sg[edge]['numeric'] - 0.001, 'max': norm_sg[edge]['numeric'],\n 'prev_min': norm_sg[edge]['numeric'] - 0.001, 'prev_max': norm_sg[edge]['numeric']}\n\n elif norm_sg[edge]['numeric'] < fabric['domains'][domain]['sg_edge_min_max'][group]['min']:\n fabric['domains'][domain]['sg_edge_min_max'][group]['prev_min'] = fabric['domains'][domain]['sg_edge_min_max'][group]['min']\n fabric['domains'][domain]['sg_edge_min_max'][group]['prev_max'] = fabric['domains'][domain]['sg_edge_min_max'][group]['max']\n\n fabric['domains'][domain]['sg_edge_min_max'][group]['min'] = norm_sg[edge]['numeric']\n renormalise_edges.add(edge)\n\n elif norm_sg[edge]['numeric'] > fabric['domains'][domain]['sg_edge_min_max'][group]['max']:\n fabric['domains'][domain]['sg_edge_min_max'][group]['prev_min'] = fabric['domains'][domain]['sg_edge_min_max'][group]['min']\n fabric['domains'][domain]['sg_edge_min_max'][group]['prev_max'] = fabric['domains'][domain]['sg_edge_min_max'][group]['max']\n fabric['domains'][domain]['sg_edge_min_max'][group]['max'] = norm_sg[edge]['numeric']\n renormalise_edges.add(edge)\n\n # normalise the numeric\n #\n norm_sg[edge]['numeric'] = ((norm_sg[edge]['numeric'] - fabric['domains'][domain]['sg_edge_min_max'][group]['min']) /\n (fabric['domains'][domain]['sg_edge_min_max'][group]['max'] - fabric['domains'][domain]['sg_edge_min_max'][group]['min']))\n\n # if the global mins and maxes have changed then need to renormalise existing neurons\n #\n if len(renormalise_edges) > 0:\n # the domain min and max must have changed\n #\n fabric['domains'][domain]['updated'] = True\n\n for neuron in fabric['domains'][domain]['neurons']:\n\n # get out the neuron's generalised sub_graph\n #\n n_sg = fabric['domains'][domain]['neurons'][neuron]['generalisation']\n\n # for each edge that has changed\n #\n for edge in renormalise_edges:\n if edge in n_sg and n_sg[edge]['numeric'] is not None:\n\n # this neuron is changing\n #\n fabric['domains'][domain]['neurons'][neuron]['updated'] = True\n\n group = fabric['normalise_groups'][n_sg[edge]['edge_type']]\n\n # first denormalise using previous min and max\n #\n denorm_numeric = ((n_sg[edge]['numeric'] *\n (fabric['domains'][domain]['sg_edge_min_max'][group]['prev_max'] - fabric['domains'][domain]['sg_edge_min_max'][group]['prev_min'])) +\n fabric['domains'][domain]['sg_edge_min_max'][group]['prev_min'])\n\n # then normalise using new min and max\n #\n n_sg[edge]['numeric'] = ((denorm_numeric - fabric['domains'][domain]['sg_edge_min_max'][group]['min']) /\n (fabric['domains'][domain]['sg_edge_min_max'][group]['max'] - fabric['domains'][domain]['sg_edge_min_max'][group]['min']))\n\n return norm_sg\n\n\ndef denormalise_sub_graph(fabric: dict,\n domain: str,\n sub_graph: SubGraph) -> SubGraph:\n \"\"\"\n function to denormalise a sub graph based on the max and mins of numeric edges seen in the domain\n :param fabric: the fabric that contains the domain\n :param domain: the domain that contains the max and mins\n :param sub_graph: the sub graph to denormalise\n :return: the denormalised sub graph\n \"\"\"\n\n # create a new copy\n #\n denorm_sg = SubGraph(sub_graph=sub_graph)\n\n for edge in denorm_sg:\n\n # if the edge has been normalised then it will be present in fabric['domains'][domain]['sg_edge_min_max']\n #\n if denorm_sg[edge]['numeric'] is not None and denorm_sg[edge]['edge_type'] in fabric['normalise_groups']:\n group = fabric['normalise_groups'][denorm_sg[edge]['edge_type']]\n denorm_sg[edge]['numeric'] = ((denorm_sg[edge]['numeric'] *\n (fabric['domains'][domain]['sg_edge_min_max'][group]['max'] - fabric['domains'][domain]['sg_edge_min_max'][group]['min'])) +\n fabric['domains'][domain]['sg_edge_min_max'][group]['min'])\n return denorm_sg\n\n\ndef decode_fabric(fabric: dict) -> dict:\n \"\"\"\n function to copy the fabric, calculate the communities for each domain of neurons and denormalise all neurons\n :param fabric: the fabric to copy\n :return: the decoded fabric\n \"\"\"\n\n decoded_fabric = deepcopy(fabric)\n for domain in decoded_fabric['domains']:\n\n # update the community for the domain before denormalising sdrs\n #\n update_community(fabric=decoded_fabric,\n domain=domain,\n search_edge_types=decoded_fabric['domains'][domain]['search_edge_types'])\n\n # denormalise the generalised sdrs\n #\n for neuron_id in decoded_fabric['domains'][domain]['neurons']:\n decoded_fabric['domains'][domain]['neurons'][neuron_id]['generalisation'] = denormalise_sub_graph(fabric=fabric,\n domain=domain,\n sub_graph=decoded_fabric['domains'][domain]['neurons'][neuron_id]['generalisation'])\n\n return decoded_fabric\n\n\ndef update_community(fabric: dict,\n domain: str,\n search_edge_types: set) -> None:\n \"\"\"\n function to calculate the community of neurons within a domain\n :param fabric: the fabric that contains the domain\n :param domain: the domain that contains the neurons\n :param search_edge_types: set of edge types to use in the distance calculation between neurons\n :return: None\n \"\"\"\n\n if len(fabric['domains'][domain]['neurons']) > 3:\n neuron_idx = 0\n neuron_id_map = {}\n for neuron_id in fabric['domains'][domain]['neurons']:\n neuron_id_map[neuron_id] = neuron_idx\n neuron_idx += 1\n\n # matrix of distances between all neurons within the domain\n #\n distances = [[-1.0] * len(fabric['domains'][domain]['neurons'])\n for _ in range(len(fabric['domains'][domain]['neurons']))]\n sum_distance = 0.0\n n_distances = 0.0\n for neuron_id_1 in fabric['domains'][domain]['neurons']:\n for neuron_id_2 in fabric['domains'][domain]['neurons']:\n if neuron_id_1 != neuron_id_2:\n if distances[neuron_id_map[neuron_id_2]][neuron_id_map[neuron_id_1]] == -1.0:\n neuron_1_sdr = fabric['domains'][domain]['neurons'][neuron_id_1]['generalisation']\n neuron_2_sdr = fabric['domains'][domain]['neurons'][neuron_id_2]['generalisation']\n\n nn_distance, _ = neuron_1_sdr.calc_euclidean_distance(sub_graph=neuron_2_sdr, compare_edge_types=search_edge_types)\n\n distances[neuron_id_map[neuron_id_1]][neuron_id_map[neuron_id_2]] = nn_distance\n distances[neuron_id_map[neuron_id_2]][neuron_id_map[neuron_id_1]] = nn_distance\n sum_distance += nn_distance\n n_distances += 1\n else:\n distances[neuron_id_map[neuron_id_1]][neuron_id_map[neuron_id_2]] = 0.0\n distances[neuron_id_map[neuron_id_2]][neuron_id_map[neuron_id_1]] = 0.0\n\n dist_matrix = np.array(distances)\n communities = DBSCAN(eps=sum_distance / n_distances, min_samples=3).fit(dist_matrix)\n for neuron_id in fabric['domains'][domain]['neurons']:\n fabric['domains'][domain]['neurons'][neuron_id]['community'] = communities.labels_[neuron_id_map[neuron_id]]\n\n\ndef train_domain(fabric: dict,\n domain: str,\n sub_graph: SubGraph,\n ref_id: str,\n search_edge_types: set,\n learn_edge_types: set,\n edge_type_weights: Optional[dict] = None,\n learn_nearest_neighbours: bool = True) -> dict:\n \"\"\"\n method trains a fabric domain with a sub graph\n\n :param fabric: the fabric that contains the domain\n :param domain: the domain to train\n :param sub_graph: the sub graph to train the domain\n :param ref_id: the reference id for this action\n :param search_edge_types: the set of edge types to used to find the BMU neuron\n :param learn_edge_types: the set of edge types that will be learnt by the BMU neuron\n :param edge_type_weights: an optional dictionary mapping edge types to weights used in the search for the BMU neuron\n :param learn_nearest_neighbours: boolean flag if True will force the learning of the nearest neighbour to the BMU neuron\n :return: path of reasoning dictionary\n \"\"\"\n\n # add the domain of not existing\n #\n if domain not in fabric['domains']:\n add_domain(fabric=fabric, domain=domain)\n\n # create a new unique update_id\n #\n fabric['update_id'] += 1\n fabric['updated'] = True\n\n logging.debug(f'training domain: {domain} in fabric {fabric[\"uid\"]} for ref id: {ref_id} and update id: {fabric[\"update_id\"]}')\n\n # keep track of the number of times this domain has been mapped to\n #\n fabric['domains'][domain]['mapped'] += 1\n fabric['domains'][domain]['updated'] = True\n\n # keep track of the edge types used to find the bmu\n #\n fabric['domains'][domain]['search_edge_types'].update(search_edge_types)\n\n # prepare a path of reasoning\n #\n por = {\n # the external reference for this update\n #\n 'ref_id': ref_id,\n domain: {\n # the number of times this domain has been mapped\n #\n 'mapped': fabric['domains'][domain]['mapped'],\n\n # the neuron id of the BMU\n #\n 'bmu_id': None,\n\n # the learning rate used to modify the BMU\n #\n 'bmu_learn_rate': None,\n\n # the error threshold of the BMU\n #\n 'bmu_threshold': None,\n\n # the ID of a neuron that has just been created\n #\n 'created_id': None,\n\n # the neuron id of the runner up neuron\n #\n 'runner_up_id': None,\n\n # the learning rate used to modify the runner up\n #\n 'runner_up_learn_rate': None,\n\n # the path of reasoning resulting from searching for the BMU\n #\n 'search_por': None,\n\n # the distance to the BMU\n #\n 'bmu_distance': None,\n\n # the exponential moving average of the domain error\n #\n 'ema_error': None,\n\n # set the anomaly and motif thresholds to values prior to update\n #\n 'anomaly_threshold': fabric['domains'][domain]['anomaly_threshold'],\n 'motif_threshold': fabric['domains'][domain]['motif_threshold']\n\n }\n }\n\n # if the fabric in the required domain is empty then just add a new neuron\n #\n if len(fabric['domains'][domain]['neurons']) == 0:\n\n # add new neuron and set threshold to 0.0 to make it easy for next neuron to be added\n #\n new_id = add_neuron(fabric=fabric, domain=domain, sub_graph=sub_graph, distance_threshold=0.0)\n\n # remember this neuron id was last bmu\n #\n fabric['domains'][domain]['last_bmu_id'] = new_id\n\n # por needs to know this was a new neuron\n #\n por[domain]['created_id'] = new_id\n\n else:\n\n # calc the distances of incoming data to all existing neurons in the required domain\n #\n distances = get_generalised_distance(fabric=fabric,\n domain=domain,\n sub_graph=sub_graph,\n search_edge_types=search_edge_types,\n edge_type_weights=edge_type_weights)\n\n # the bmu is the closest neuron\n #\n bmu_id = distances[0][0]\n por[domain]['bmu_id'] = bmu_id\n\n logging.debug(f'found BMU neuron:{bmu_id} in domain: {domain} of fabric: {fabric[\"uid\"]}')\n\n bmu_distance = distances[0][1]\n\n por[domain]['bmu_distance'] = bmu_distance\n por[domain]['search_por'] = distances[0][2]\n por[domain]['bmu_threshold'] = fabric['domains'][domain]['neurons'][bmu_id]['threshold']\n\n # if the distance exceeds the bmu threshold then add a new neuron\n #\n if bmu_distance > fabric['domains'][domain]['neurons'][bmu_id]['threshold']:\n\n new_id = add_neuron(fabric=fabric, domain=domain, sub_graph=sub_graph, distance_threshold=bmu_distance)\n por[domain]['created_id'] = new_id\n\n # adjust the existing bmu threshold to make it harder to insert a new neuron next to it\n #\n fabric['domains'][domain]['neurons'][bmu_id]['threshold'] += (((bmu_distance * fabric['generalise_factor']) - fabric['domains'][domain]['neurons'][bmu_id]['threshold']) *\n fabric['fast_learn_rate'])\n\n # remember the last bmu for this domain\n #\n fabric['domains'][domain]['last_bmu_id'] = new_id\n\n else:\n\n # no new neuron is created so set to None\n #\n new_id = None\n\n # update the number of times the bmu neuron has been mapped\n #\n fabric['domains'][domain]['neurons'][bmu_id]['n_bmu'] += 1\n\n # keep track of the last time it was mapped to\n #\n fabric['domains'][domain]['neurons'][bmu_id]['last_bmu'] = fabric['update_id']\n\n # keep track of the average error of mapped data\n #\n fabric['domains'][domain]['neurons'][bmu_id]['ema_error'] += (bmu_distance - fabric['domains'][domain]['neurons'][bmu_id]['ema_error']) * fabric['slow_learn_rate']\n\n # calculate the learning rate for this neuron\n #\n bmu_learn_rate = (1 / fabric['domains'][domain]['neurons'][bmu_id]['n_bmu'])\n por[domain]['bmu_learn_rate'] = bmu_learn_rate\n\n # adjust the threshold of the existing bmu\n #\n fabric['domains'][domain]['neurons'][bmu_id]['threshold'] += (((bmu_distance * fabric['generalise_factor']) - fabric['domains'][domain]['neurons'][bmu_id]['threshold']) *\n fabric['fast_learn_rate'])\n\n # learn the generalisations\n #\n update_generalisation(fabric=fabric,\n domain=domain,\n neuron_id=bmu_id,\n sub_graph=sub_graph,\n learn_rate=bmu_learn_rate,\n learn_edge_types=learn_edge_types)\n\n # process the runner up if required\n #\n if learn_nearest_neighbours and len(distances) > 1:\n\n runner_up_id = distances[1][0]\n runner_up_distance = distances[1][1]\n if runner_up_distance <= fabric['domains'][domain]['neurons'][runner_up_id]['threshold']:\n\n por[domain]['runner_up_id'] = runner_up_id\n\n logging.debug(f'found Runner up neuron: {runner_up_id} in domain {domain} in fabric {fabric[\"uid\"]}')\n\n runner_up_learn_rate = min(bmu_learn_rate, (1 / fabric['domains'][domain]['neurons'][runner_up_id]['n_bmu']))\n por[domain]['runner_up_learn_rate'] = runner_up_learn_rate\n\n fabric['domains'][domain]['neurons'][runner_up_id]['threshold'] += (((runner_up_distance * fabric['generalise_factor']) -\n fabric['domains'][domain]['neurons'][runner_up_id]['threshold']) *\n fabric['fast_learn_rate'])\n\n # map sub_graph to the runner up\n #\n update_generalisation(fabric=fabric,\n domain=domain,\n neuron_id=runner_up_id,\n sub_graph=sub_graph,\n learn_rate=runner_up_learn_rate,\n learn_edge_types=learn_edge_types)\n\n # remember last time it was a runner up\n #\n fabric['domains'][domain]['neurons'][runner_up_id]['last_runner_up'] = fabric['update_id']\n\n # update the number of times the runner_up neuron has been runner up\n #\n fabric['domains'][domain]['neurons'][runner_up_id]['n_runner_up'] += 1\n\n # update nearest neighbour edges\n #\n update_synapse(fabric=fabric,\n source_domain=domain, source_id=bmu_id,\n target_domain=domain, target_id=runner_up_id,\n edge_type='nn',\n learn_rate=bmu_learn_rate)\n\n # remember the last bmu for this domain\n #\n fabric['domains'][domain]['last_bmu_id'] = bmu_id\n\n por[domain]['anomaly'], por[domain]['motif'] = update_domain_error(fabric=fabric,\n domain=domain,\n bmu_id=bmu_id,\n new_id=new_id,\n error=bmu_distance,\n ref_id=ref_id)\n por[domain]['error'] = bmu_distance\n por[domain]['ema_error'] = fabric['domains'][domain]['ema_error']\n\n return por\n\n\ndef learn_spatial(fabric: dict,\n ref_id: str,\n sub_graph: SubGraph,\n search_edge_types: set,\n learn_edge_types: set) -> dict:\n \"\"\"\n function to train the SPATIAL domain of a fabric\n :param fabric: the fabric to train\n :param ref_id: the reference id for this action\n :param sub_graph: the sub graph to train the SPATIAL domain\n :param search_edge_types: the set of edge types to use to find the BMU neuron\n :param learn_edge_types: the set of edge types to learn by the BMU neuron\n :return: path of reasoning dictionary\n \"\"\"\n\n # add the SPATIAL domain if it doesn't exist\n #\n if 'SPATIAL' not in fabric['domains']:\n add_domain(fabric=fabric, domain='SPATIAL')\n\n # first train the main spatial domain\n #\n spatial_norm_sdr = normalise_sub_graph(fabric=fabric, domain='SPATIAL', sub_graph=sub_graph)\n por = train_domain(fabric=fabric,\n domain='SPATIAL',\n sub_graph=spatial_norm_sdr,\n ref_id=ref_id,\n search_edge_types=search_edge_types,\n learn_edge_types=learn_edge_types,\n learn_nearest_neighbours=True)\n\n return por\n\n\ndef learn_temporal(fabric: dict,\n ref_id: str,\n sub_graph: SubGraph,\n search_edge_types: set,\n learn_edge_types: set) -> dict:\n \"\"\"\n function to train the TEMPORAL domain of a fabric with a sequence of sub graphs. It does this by maintaining an infinite filter memory of sub_graphs seen\n stored in a single sub graph with n attention heads of edges that are learned at increasingly slower rates\n\n :param fabric: the fabric to train\n :param ref_id: the reference id for this action\n :param sub_graph: the sub raph to train the TEMPORAL domain\n :param search_edge_types: the set of edge types to use to find the BMU neuron\n :param learn_edge_types: the set of edge types to learn by the BMU neuron\n :return: path of reasoning dictionary\n \"\"\"\n\n # the path of reasoning\n #\n por = {}\n\n if fabric['long_term_memory'] is not None:\n # the temporal domain will search and learn edges for each attention head\n #\n ltm_search_edge_types = {f'{edge_type}_HEAD_{head}' for edge_type in search_edge_types for head in range(fabric['attention_heads'])}\n ltm_learn_edge_types = {f'{edge_type}_HEAD_{head}' for edge_type in learn_edge_types for head in range(fabric['attention_heads'])}\n\n # add the TEMPORAL domain if it doesn't exist\n #\n if 'TEMPORAL' not in fabric['domains']:\n add_domain(fabric=fabric,\n domain='TEMPORAL')\n\n # normalise the current long_term_memory\n #\n ltm_norm_sg = normalise_sub_graph(fabric=fabric, domain='TEMPORAL', sub_graph=fabric['long_term_memory'])\n\n # train the temporal domain with the current normalised long_term_memory\n #\n por = train_domain(fabric=fabric,\n domain='TEMPORAL',\n sub_graph=ltm_norm_sg,\n ref_id=ref_id,\n search_edge_types=ltm_search_edge_types,\n learn_edge_types=ltm_learn_edge_types,\n learn_nearest_neighbours=True)\n\n # learn the edge between the temporal_neuron and the spatial neuron\n #\n spatial_neuron_id = fabric['domains']['SPATIAL']['last_bmu_id']\n temporal_neuron_id = fabric['domains']['TEMPORAL']['last_bmu_id']\n temporal_learn_rate = (1 / fabric['domains']['TEMPORAL']['neurons'][temporal_neuron_id]['n_bmu'])\n update_synapse(fabric=fabric,\n source_domain='TEMPORAL', source_id=temporal_neuron_id,\n target_domain='SPATIAL', target_id=spatial_neuron_id,\n edge_type='temporal_nn',\n learn_rate=temporal_learn_rate)\n\n else:\n fabric['long_term_memory'] = SubGraph()\n\n # update the long_term_memory sub_graph\n # for the number of required attention heads, create a head specific set of edges and train the current temporal sub_graph with a head specific learn_rate\n #\n for head in range(fabric['attention_heads']):\n ltm_sg = SubGraph()\n\n edge_types_to_learn = set()\n\n # long_term_memory memorises the denormalised incoming SubGraph\n #\n for edge in sub_graph:\n\n # temporal sub_graph is only interested in the edge types used to find the spatial domain bmu\n #\n if sub_graph[edge]['edge_type'] in search_edge_types:\n\n # each head has a specific edge_type\n #\n edge_type = f\"{sub_graph[edge]['edge_type']}_HEAD_{head}\"\n edge_types_to_learn.add(edge_type)\n\n # make sure all HEAD edge types are in the same normalisation group\n #\n if sub_graph[edge]['edge_type'] in fabric['normalise_groups']:\n fabric['normalise_groups'][edge_type] = f\"{fabric['normalise_groups'][sub_graph[edge]['edge_type']]}_HEAD\"\n else:\n fabric['normalise_groups'][edge_type] = f\"{sub_graph[edge]['edge_type']}_HEAD\"\n\n # copy incoming data, making each edge specific to head\n #\n ltm_sg.set_item(source_node=(sub_graph[edge]['source_type'], sub_graph[edge]['source_uid']),\n edge=(edge_type, sub_graph[edge]['edge_uid']),\n target_node=(sub_graph[edge]['target_type'], sub_graph[edge]['target_uid']),\n probability=sub_graph[edge]['prob'],\n numeric=sub_graph[edge]['numeric'])\n\n fabric['long_term_memory'].learn(sub_graph=ltm_sg,\n\n # the learn rate depends on the attention head being trained - it decreases by the power\n #\n learn_rate=pow(fabric['fast_learn_rate'], head + 1),\n learn_edge_types=edge_types_to_learn,\n prune_threshold=fabric['prune_threshold'])\n return por\n\n\ndef learn_association(fabric: dict,\n ref_id: str,\n domain: str,\n sub_graph: SubGraph,\n search_edge_types: set,\n learn_edge_types: set,\n spatial_neuron_id: Optional[str] = None,\n learn_nearest_neighbours: bool = True) -> dict:\n \"\"\"\n a function to train an association domain that is linked to the SPATIAL domain BMU neuron\n :param fabric: the fabric that contains the association domain\n :param ref_id: the reference id for this action\n :param domain: the association domain to train\n :param sub_graph: the sub graph to train the association domain\n :param search_edge_types: the set of edge types to use to find the BMU neuron\n :param learn_edge_types: the set of edge types to learn by the BMU neuron\n :param spatial_neuron_id: optional SPATIAL domain bmu neuron to associate with the Association domain - if None then previous SPATIAL BMU used\n :param learn_nearest_neighbours: boolean flag to indicate if the nearest neighbour of the association BMU neuron is also learnt\n :return: path of reasoning dictionary\n \"\"\"\n\n # add the domain if it doesn't exist\n #\n if domain not in fabric['domains']:\n add_domain(fabric=fabric, domain=domain)\n\n # will need the spatial neuron id an learning rate\n #\n if spatial_neuron_id is None:\n spatial_neuron_id = fabric['domains']['SPATIAL']['last_bmu_id']\n spatial_learn_rate = (1 / fabric['domains']['SPATIAL']['neurons'][spatial_neuron_id]['n_bmu'])\n\n # normalise the sub_graph\n #\n norm_sg = normalise_sub_graph(fabric=fabric, domain=domain, sub_graph=sub_graph)\n por = train_domain(fabric=fabric,\n domain=domain,\n sub_graph=norm_sg,\n ref_id=ref_id,\n search_edge_types=search_edge_types,\n learn_edge_types=learn_edge_types,\n learn_nearest_neighbours=learn_nearest_neighbours)\n\n # learn the connection between the spatial neuron and the association neuron\n #\n neuron_id = fabric['domains'][domain]['last_bmu_id']\n update_synapse(fabric=fabric,\n source_domain='SPATIAL', source_id=spatial_neuron_id,\n target_domain=domain, target_id=neuron_id,\n edge_type='association',\n learn_rate=spatial_learn_rate)\n return por\n\n\ndef get_association(fabric: dict,\n domain: str,\n neuron_id: str,\n depth: int) -> dict:\n \"\"\"\n recursive function that will retrieve the association neurons for the given neuron_id within a given domain\n :param fabric: the fabric that contains the domain\n :param domain: the domain that contains the neuron\n :param neuron_id: the neuron id to retrieve the associations for\n :param depth: the depth of associations to find\n :return: dictionary of all associations\n \"\"\"\n\n query_result = {'associations': {}}\n total_probabilities = {}\n\n synapse_sdr = fabric['domains'][domain]['neurons'][neuron_id]['synapses']\n for edge in synapse_sdr:\n if synapse_sdr[edge]['edge_type'] != 'nn':\n association_domain = synapse_sdr[edge]['target_type']\n\n if association_domain not in query_result['associations']:\n query_result['associations'][association_domain] = []\n total_probabilities[association_domain] = 0.0\n\n total_probabilities[association_domain] += synapse_sdr[edge]['prob']\n association_neuron = fabric['domains'][association_domain]['neurons'][synapse_sdr[edge]['target_uid']]\n association = {'domain': association_domain,\n 'neuron_id': synapse_sdr[edge]['target_uid'],\n 'probability': synapse_sdr[edge]['prob'],\n 'n_bmu': association_neuron['n_bmu'],\n 'ema_error': association_neuron['ema_error'],\n 'community': association_neuron['community'],\n 'generalisation': denormalise_sub_graph(fabric=fabric,\n domain=association_domain,\n sub_graph=association_neuron['generalisation'])\n }\n if depth - 1 > 0:\n next_associations = get_association(fabric=fabric, domain=association_domain, neuron_id=synapse_sdr[edge]['target_uid'], depth=(depth - 1))\n association.update(next_associations)\n query_result['associations'][association_domain].append(association)\n\n for association_domain in total_probabilities:\n for association in query_result['associations'][association_domain]:\n association['probability'] /= total_probabilities[association_domain]\n query_result['associations'][association_domain].sort(key=lambda x: x['probability'], reverse=True)\n\n return query_result\n\n\ndef query_domain(fabric: dict,\n domain: str,\n sub_graph: SubGraph,\n association_depth: int = 1) -> dict:\n \"\"\"\n function that queries the the specified domain and returns the neuron most similar to the exemplar sub graph\n :param fabric: the fabric that contains the domain\n :param domain: the domain to query\n :param sub_graph: the exemplar sub graph\n :param association_depth: the depth of association to return\n :return: dictionary of the most similar neuron and its' associations\n \"\"\"\n\n query_result = {}\n if domain in fabric['domains']:\n\n # normalise\n #\n norm_sg = normalise_sub_graph(fabric=fabric, domain=domain, sub_graph=sub_graph)\n search_edge_types = {norm_sg[edge]['edge_type'] for edge in norm_sg}\n distances = get_generalised_distance(fabric=fabric, domain=domain, sub_graph=norm_sg, search_edge_types=search_edge_types)\n\n # the bmu is the closest neuron\n #\n query_result['bmu_id'] = distances[0][0]\n query_result['domain'] = domain\n query_result['distance'] = distances[0][1]\n query_result['por'] = distances[0][2]\n\n # fill out important attributes about neuron\n #\n query_result['n_bmu'] = fabric['domains'][domain]['neurons'][query_result['bmu_id']]['n_bmu']\n query_result['ema_error'] = fabric['domains'][domain]['neurons'][query_result['bmu_id']]['ema_error']\n query_result['community'] = fabric['domains'][domain]['neurons'][query_result['bmu_id']]['community']\n\n # create the copy of the generalised graph and denormalise\n #\n query_result['generalisation'] = denormalise_sub_graph(fabric=fabric,\n domain=domain,\n sub_graph=fabric['domains'][domain]['neurons'][query_result['bmu_id']]['generalisation'])\n\n # provide associations\n #\n if association_depth > 0:\n next_associations = get_association(fabric=fabric, domain=domain, neuron_id=query_result['bmu_id'], depth=association_depth)\n query_result.update(next_associations)\n else:\n query_result['associations'] = {}\n\n return query_result\n\n\ndef next_in_sequence(fabric: dict) -> dict:\n \"\"\"\n function to return the predicted sub graph that is next in the sequence given the current long term memory of the fabric\n :param fabric: the fabric to query\n :return: the predicted neuron and its' associations\n \"\"\"\n\n # using the current long term memory get the next in sequence\n #\n query_result = query_domain(fabric=fabric, domain='TEMPORAL', sub_graph=fabric['long_term_memory'], association_depth=2)\n\n return query_result\n","sub_path":"src/neuro_gas_fabric.py","file_name":"neuro_gas_fabric.py","file_ext":"py","file_size_in_byte":48527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"154854449","text":"# curio/meta.py\n# ___ \n# \\./ DANGER: This module implements some experimental\n# .--.O.--. metaprogramming techniques involving async/await.\n# \\/ \\/ If you use it, you might die. \n#\n\nimport sys\nimport inspect\nfrom functools import wraps\n\nfrom .kernel import Kernel\n\ndef awaitable(syncfunc):\n '''\n Decorator that allows an asynchronous function to be paired with a \n synchronous function in a single function call. The selection of\n which function executes depends on the calling context. For example:\n\n def spam(sock, maxbytes): (A)\n return sock.recv(maxbytes)\n\n @awaitable(read) (B)\n async def spam(sock, maxbytes):\n return await sock.recv(maxbytes)\n\n In later code, you could use the spam() function in either a synchronous\n or asynchronous context. For example:\n\n def foo():\n ...\n r = spam(s, 1024) # Calls synchronous function (A) above\n ... \n \n async def bar():\n ...\n r = await spam(s, 1024) # Calls async function (B) above\n ...\n\n '''\n def decorate(asyncfunc):\n if inspect.signature(syncfunc) != inspect.signature(asyncfunc):\n raise TypeError('%s and async %s have different signatures' %\n (syncfunc.__name__, asyncfunc.__name__))\n @wraps(asyncfunc)\n def wrapper(*args, **kwargs):\n if sys._getframe(1).f_code.co_flags & 0x80:\n return asyncfunc(*args, **kwargs)\n else:\n return syncfunc(*args, **kwargs)\n return wrapper\n return decorate\n\nclass _AwaitDict(dict):\n '''\n Metaclass helper that allows sync/async methods to be paired together.\n Uses the @awaitable decorator above to do the pairing.\n '''\n def __setitem__(self, name, value):\n sync_func = None\n async_func = None\n previous_func = self.get(name)\n if previous_func:\n if inspect.iscoroutinefunction(previous_func):\n async_func = previous_func\n else:\n sync_func = previous_func\n if inspect.iscoroutinefunction(value):\n async_func = value\n else:\n sync_func = value\n if sync_func and async_func:\n value = awaitable(sync_func)(async_func)\n super().__setitem__(name, value)\n\nclass DualIOMeta(type):\n '''\n Metaclass that allows the definition of both synchronous and asynchronous\n methods in the same class. For example:\n\n class Spam(metaclass=DualIOMeta):\n def foo(self):\n ...\n async def foo(self):\n ...\n\n The method foo() becomes a single method that triggers the appropriate version\n depending on the calling context. See the @awaitable decorator above.\n '''\n def __prepare__(self, *args, **kwargs):\n return _AwaitDict()\n\nclass DualIO(metaclass=DualIOMeta):\n pass\n\ndef allow_sync(func):\n if not inspect.iscoroutinefunction(func):\n raise TypeError('%s must be a coroutine' % func.__name__)\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n if sys._getframe(1).f_code.co_flags & 0x80:\n return func(*args, **kwargs)\n else:\n # Not being called from a coroutine. Have a kernel run it\n with Kernel() as k:\n return k.run(func(*args, **kwargs))\n\n return wrapper\n\n\n\n\n\n\n","sub_path":"curio/meta.py","file_name":"meta.py","file_ext":"py","file_size_in_byte":3547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"182401174","text":"# 최대공약수와 최소공배수\ndef solution(n, m):\n answer = []\n\n def gcd(n, m):\n r = n % m\n if r == 0:\n return m\n else:\n return gcd(m, r)\n\n answer.append(gcd(n, m))\n answer.append(n * m / gcd(n, m))\n\n return answer","sub_path":"programmers/python/level01/12940.py","file_name":"12940.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"354774397","text":"#!/usr/bin/python\n__Author__ = \"Vincent Lamy\"\n__version__ = \"2021.1015\"\n\nimport sys\n\nfrom q_functions import *\n# Default values\nusername = ''\nquota_size = ''\ndefault_quota_size = 50000000000\nsrc_path = '/Lab-Q/HomeDir/'\nhomedir_owner = 'q-admins'\n\n\n# Logging Details\nlogging.basicConfig(filename='Q-HomedirCreate.log', level=logging.INFO,\n format='%(asctime)s,%(levelname)s,%(message)s')\n# Get command arguments\nargv = sys.argv[1:]\n\n\n\ntry:\n opts, args = getopt.getopt(argv,\"hu:q:\",[\"help\",\"user=\",\"quota=\"])\nexcept getopt.GetoptError:\n print ('{} -u -q '.format(sys.argv[0]))\n print('-u / --username= Username to setup homedir for')\n print('-q / --quota= Quota Limit to define on the homedir (50M, 50G, 50T, 50P/ optional ')\n sys.exit(2)\nprint(opts)\nfor opt, arg in opts:\n if opt in (\"-h\", \"--help\"):\n print ('{} -u -q '.format(sys.argv[0]))\n print('-u / --username= Username to setup homedir for')\n print('-q / --quota= Quota Limit to define on the homedir (50M, 50G, 50T, 50P) / optional ')\n sys.exit(0)\n elif opt in (\"-u\", \"--username\"):\n username = arg\n elif opt in (\"-q\", \"--quota\"):\n quota_size = arg\n\n\nif username == '':\n print('Username must be provided')\n print('{} -u -q '.format(sys.argv[0]))\n print('-u / --username= Username to setup homedir for')\n print('-q / --quota= Quota Limit to define on the homedir (50M, 50G, 50T, 50P) / optional ')\n sys.exit(1)\n\n\nif quota_size == '':\n quota_size = default_quota_size\nelse:\n # Check if quota unit is supported\n unit = quota_size[-1]\n if unit in (\"M\", \"G\", \"T\", \"P\"):\n quota_size = convert_quota_size(quota_size,logging)\n else:\n print('Quota unit provided is no support : {}'.format(quota_size))\n print('{} -u -q '.format(sys.argv[0]))\n print('-u / --username= Username to setup homedir for')\n print('-q / --quota= Quota Limit to define on the homedir (50M, 50G, 50T, 50P) / optional ')\n sys.exit(1)\n\n# Build the homedir path\nhomedir_path = src_path+username+'/'\n\n# Read credentials\njson_file = open('./credentials.json', 'r')\njson_data = json_file.read()\njson_object = json.loads(json_data)\njson_file.close()\n\n# Parse cluster credentials\nprimary_cluster_address = json_object['primary_cluster_address']\nprimary_port_number = json_object['primary_port_number']\nprimary_username = json_object['primary_username']\nprimary_password = json_object['primary_password']\n\n# Connect to cluster\ntry:\n prc = RestClient(primary_cluster_address, primary_port_number)\n prc.login(primary_username, primary_password)\n logging.info('main,Connection established with {}'.format(primary_cluster_address))\n print('Connection established with {}'.format(primary_cluster_address))\nexcept Exception as err:\n logging.error('main,Connection cannot be established with {}'.format(primary_cluster_address))\n logging.error(\n 'Error message is {}'.format(err.__dict__))\n logging.info('main,Ending program now')\n quit()\n\n# Check if user exists on Active Directory through Qumulo cluster - exit if user do no exist\n# User attributes such as auth_id are stored in ad_user for futur use in this script\ntry:\n ad_user = prc.auth.find_identity(domain='ACTIVE_DIRECTORY',name=username)\n logging.info('main,User {} exists on Active Directory and its auth_id is {}'.format(ad_user['name'],\n ad_user['auth_id']))\n print('User {} exists on Active Directory and its auth_id is {}'.format(ad_user['name'],ad_user['auth_id']))\nexcept Exception as err:\n error = err.__dict__\n logging.error('main,User {} does not exists on the Active Directory'.format(username))\n logging.error('main,Error description is : {}'.format(error['description']))\n logging.info('main,Exiting program now')\n print('User {} does not exists on the Active Directory'.format(username))\n print('Error description is : {}'.format(error['description']))\n print('Exiting program now')\n prc.close()\n logging.info('main,Connection ended with {}'.format(primary_cluster_address))\n print('Connection ended with {}'.format(primary_cluster_address))\n quit(1)\n\n# Create directory on the cluster\ntry:\n created_dir = prc.fs.create_directory(username,src_path)\n logging.info('main,Directory {} has been created on the cluster'.format(created_dir['path']))\n print('Directory {} has been created on the cluster'.format(created_dir['path']))\nexcept Exception as err:\n error = err.__dict__\n if error['error_class'] == 'fs_entry_exists_error':\n logging.warning('main,Directory {}{} already exists on this cluster'.format(src_path,username))\n print('Directory {}{} already exists on this cluster'.format(src_path,username))\n\n# Modify the owner of this directory - must be user / group in homedir_owner\ntry:\n homdir_ad_owner = prc.auth.find_identity(domain='ACTIVE_DIRECTORY', name=homedir_owner)\n chg_own = prc.fs.set_file_attr(path=homedir_path,owner=homdir_ad_owner['auth_id'])\n logging.info('main,Owner of directory {} is now {}'.format(chg_own['path'],homdir_ad_owner['name']))\n print('Owner of directory {} is now {}'.format(chg_own['path'],homdir_ad_owner['name']))\nexcept Exception as err:\n error = err.__dict__\n logging.error('main,Error when trying to change owner of directory {} with {}'.format(chg_own['path'],\n ad_user['name']))\n logging.error('main,Error message is {}'.format(err.__dict__))\n print('Error when trying to change owner of directory {} with {}'.format(chg_own['path'],\n ad_user['name']))\n print('Error message is {}'.format(err.__dict__))\n\n# Set ACL for user on its homedir - Full control with heritance\n\n# Generate JSON object for ACLs\njson_acl = gen_json_acl(username,homedir_owner)\n\n# Update ACLs on user homedir\ntry:\n upd_acl = prc.fs.set_acl_v2(acl=json_acl,path=homedir_path)\n logging.info('main,ACLs updated for directory {}'.format(homedir_path))\n print('ACLs updated for directory {}'.format(homedir_path))\nexcept Exception as err:\n error = err.__dict__\n print('Error when trying to update ACLs on directory {}'.format(homedir_path))\n print('Error message is {}'.format(err.__dict__))\n logging.error('main,Error when trying to update ACLs on directory {}'.format(homedir_path))\n logging.error('main,Error message is {}'.format(err.__dict__))\n\n# Create a quota for the homedir\ntry:\n # Get Directory ID on the filesystem (mandatory for setting quota on it)\n homedir_attr = prc.fs.get_file_attr(path=homedir_path)\n homedir_quota = prc.quota.create_quota(homedir_attr['id'],quota_size)\n logging.info('main,Quota has been set for directory {} - limit is {} bytes'.format(homedir_path,quota_size))\n print('Quota has been set for directory {} - limit is {} bytes'.format(homedir_path,quota_size))\nexcept Exception as err:\n error = err.__dict__\n logging.error('main, Quota can not be set for directory {}'.format(homedir_path))\n logging.error('main, Error description is : {}'.format(error['description']))\n print('Quota can not be set for directory {}'.format(homedir_path))\n print('Error description is : {}'.format(error['description']))\n\nprc.close()\nlogging.info('main,Connection ended with {}'.format(primary_cluster_address))\nprint('Connection ended with {}'.format(primary_cluster_address))\n\n\n\n\n\n","sub_path":"HomedirCreate.py","file_name":"HomedirCreate.py","file_ext":"py","file_size_in_byte":7700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"502536559","text":"import os\nimport copy\nimport xml.etree.ElementTree as ET\n\nimport numpy as np\nfrom keras.utils import Sequence\nfrom yad2k.models.keras_yolo import preprocess_true_boxes\nfrom PIL import Image\n\n\ndef parse_annotation(ann_dir, img_dir, labels=[]):\n all_imgs = []\n seen_labels = {}\n \n for ann in sorted(os.listdir(ann_dir)):\n img = {'object':[]}\n\n tree = ET.parse(ann_dir + ann)\n \n for elem in tree.iter():\n if 'filename' in elem.tag:\n img['filename'] = img_dir + elem.text\n if 'width' in elem.tag:\n img['width'] = int(elem.text)\n if 'height' in elem.tag:\n img['height'] = int(elem.text)\n if 'object' in elem.tag or 'part' in elem.tag:\n obj = {}\n \n for attr in list(elem):\n if 'name' in attr.tag:\n obj['name'] = attr.text\n\n if obj['name'] in seen_labels:\n seen_labels[obj['name']] += 1\n else:\n seen_labels[obj['name']] = 1\n \n if len(labels) > 0 and obj['name'] not in labels:\n break\n else:\n img['object'] += [obj]\n \n if 'bndbox' in attr.tag:\n for dim in list(attr):\n if 'xmin' in dim.tag:\n obj['xmin'] = int(round(float(dim.text)))\n if 'ymin' in dim.tag:\n obj['ymin'] = int(round(float(dim.text)))\n if 'xmax' in dim.tag:\n obj['xmax'] = int(round(float(dim.text)))\n if 'ymax' in dim.tag:\n obj['ymax'] = int(round(float(dim.text)))\n\n if len(img['object']) > 0:\n all_imgs += [img]\n \n return all_imgs, seen_labels\n\nclass BatchGenerator(Sequence):\n def __init__(self, images, \n config,\n shuffle=True, \n jitter=True, \n norm=None):\n self.generator = None\n\n self.images = images\n self.config = config\n\n self.shuffle = shuffle\n self.jitter = jitter\n self.norm = norm\n\n # self.anchors = [BoundBox(0, 0, config['ANCHORS'][2*i], config['ANCHORS'][2*i+1]) for i in range(int(len(config['ANCHORS'])//2))]\n self.anchors = config['ANCHORS']\n\n if shuffle: np.random.shuffle(self.images)\n\n def __len__(self):\n return int(np.ceil(float(len(self.images))/self.config['BATCH_SIZE'])) \n\n def num_classes(self):\n return len(self.config['LABELS'])\n\n def size(self):\n return len(self.images) \n\n def load_annotation(self, image):\n annots = []\n\n for obj in image['object']:\n annot = [self.config['LABELS'].index(obj['name']),\n obj['xmin'], \n obj['ymin'],\n obj['xmax'], \n obj['ymax']]\n annots += [annot]\n\n if len(annots) == 0: annots = [[]]\n\n return np.array(annots)\n \n def load_boxes(self, images):\n boxes = []\n for image in images:\n boxes.append(self.load_annotation(image))\n return boxes\n \n def get_detector_mask(self, boxes, anchors):\n '''\n Precompute detectors_mask and matching_true_boxes for training.\n Detectors mask is 1 for each spatial position in the final conv layer and\n anchor that should be active for the given boxes and 0 otherwise.\n Matching true boxes gives the regression targets for the ground truth box\n that caused a detector to be active or 0 otherwise.\n '''\n detectors_mask = [0 for i in range(len(boxes))]\n matching_true_boxes = [0 for i in range(len(boxes))]\n for i, box in enumerate(boxes):\n detectors_mask[i], matching_true_boxes[i] = preprocess_true_boxes(box, anchors, [608, 608])\n\n return np.array(detectors_mask), np.array(matching_true_boxes)\n \n def process_boxes(self, boxes):\n '''processes the boxes'''\n\n orig_size = np.array([[608, 608]])\n\n if boxes is not None:\n # Box preprocessing.\n # Original boxes stored as 1D list of class, x_min, y_min, x_max, y_max.\n boxes = [box.reshape((-1, 5)) for box in boxes]\n # Get extents as y_min, x_min, y_max, x_max, class for comparision with\n # model output.\n boxes_extents = [box[:, [2, 1, 4, 3, 0]] for box in boxes]\n\n # Get box parameters as x_center, y_center, box_width, box_height, class.\n boxes_xy = [0.5 * (box[:, 3:5] + box[:, 1:3]) for box in boxes]\n boxes_wh = [box[:, 3:5] - box[:, 1:3] for box in boxes]\n boxes_xy = [boxxy / orig_size for boxxy in boxes_xy]\n boxes_wh = [boxwh / orig_size for boxwh in boxes_wh]\n boxes = [np.concatenate((boxes_xy[i], boxes_wh[i], box[:, 0:1]), axis=1) for i, box in enumerate(boxes)]\n\n # find the max number of boxes\n max_boxes = 0\n for boxz in boxes:\n if boxz.shape[0] > max_boxes:\n max_boxes = boxz.shape[0]\n\n # add zero pad for training\n for i, boxz in enumerate(boxes):\n if boxz.shape[0] < max_boxes:\n zero_padding = np.zeros( (max_boxes-boxz.shape[0], 5), dtype=np.float32)\n boxes[i] = np.vstack((boxz, zero_padding))\n\n return np.array(boxes)\n\n def load_image(self, filename):\n img = Image.open(filename)\n return np.array(img)\n \n def __getitem__(self, idx):\n l_bound = idx*self.config['BATCH_SIZE']\n r_bound = (idx+1)*self.config['BATCH_SIZE']\n\n if r_bound > len(self.images):\n r_bound = len(self.images)\n l_bound = r_bound - self.config['BATCH_SIZE']\n\n x_batch = np.zeros((r_bound - l_bound, self.config['IMAGE_H'], self.config['IMAGE_W'], 3))\n\n # boxes = self.load_boxes(self.images[l_bound: r_bound])\n boxes = []\n for image in self.images[l_bound: r_bound]:\n boxes.append(self.load_annotation(image))\n \n boxes = self.process_boxes(boxes)\n\n it = iter(self.config['ANCHORS'])\n anchors = np.array(list(zip(it, it)))\n detectors_mask, matching_true_boxes = self.get_detector_mask(boxes, anchors)\n\n instance_count = 0\n for train_instance in self.images[l_bound:r_bound]:\n # assign input image to x_batch\n img = Image.open(train_instance['filename'])\n img = np.array(img, dtype='float32')\n img = img / 255.\n x_batch[instance_count] = np.array(img)\n\n # increase instance counter in current batch\n instance_count += 1\n\n #print(' new batch created', idx)\n return [x_batch, boxes, detectors_mask, matching_true_boxes], np.zeros(len(x_batch))\n\n def on_epoch_end(self):\n if self.shuffle: np.random.shuffle(self.images)","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":7310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"371635963","text":"\"\"\"\n__author__ == 'zhaoyang'\n__time__ = '2021-05-27 20:31'\n\"\"\"\n# 如果有个多个业务线,就可以分多个包;\n# wework,下面只放置通用的包\n\nimport json\n\nimport requests\n\nfrom service.api实战02.api.base_api import Base\n\n\nclass WeWork(Base):\n # 作用:主要是为了声明类型,python中现在也支持类型了\n token: str = None\n\n def get_token(self):\n # r = requests.get(\"https://qyapi.weixin.qq.com/cgi-bin/gettoken\",\n # params={\"corpid\": \"wwb2e5afaafb9d6136\",\n # \"corpsecret\": \"p3tMp8-8U0jMCH4exb-i72ltKMoyN4HwXVb0LsHacoI\"\n # }\n #\n # )\n\n # 具体的api对象通过这样的设计,可以实现数据化,为以后的自动化生成奠定了一个好的基础\n data = {\n 'url': 'https://qyapi.weixin.qq.com/cgi-bin/gettoken',\n 'method': 'get',\n 'params': {\n \"corpid\": \"wwb2e5afaafb9d6136\",\n \"corpsecret\": \"p3tMp8-8U0jMCH4exb-i72ltKMoyN4HwXVb0LsHacoI\"\n }\n }\n self.logging.info(\"获取externalcontact的token--------------\")\n r = self.request(data)\n self.token = r.json()['access_token']\n assert r.status_code == 200\n\n\n # print(r.json()) # json,没有处理,返回没有处理的类似json格式的数据;\n # print(r.json()['access_token'])\n\n\n def get_token_user(self):\n data = {\n 'url': 'https://qyapi.weixin.qq.com/cgi-bin/gettoken',\n 'method': 'get',\n 'params': {\n \"corpid\": \"wwb2e5afaafb9d6136\",\n \"corpsecret\": \"ibVVP3rYxbsOMb1bGCM08pBGOmhlyPxt5xWeeY1TULU\"\n }\n }\n self.logging.info(\"获取user的token--------------\")\n r = self.request(data)\n self.user_token = r.json()['access_token']\n assert r.status_code == 200\n\n","sub_path":"service/api实战02/api/wework_api.py","file_name":"wework_api.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"11239451","text":"\"\"\"\nHelper functions for the models.\n\nCopyright 2019\nVincent Fortuin\nMicrosoft Research Cambridge\n\"\"\"\n\nimport numpy as np\nfrom core import *\nfrom torch_backend import *\nfrom collections import OrderedDict\n\n\ndef conv_bn(c_in, c_out, bn_weight_init=1.0, **kw):\n return {\n 'conv': nn.Conv2d(c_in, c_out, kernel_size=3, stride=1, padding=1, bias=False),\n 'bn': batch_norm(c_out, bn_weight_init=bn_weight_init, **kw),\n 'relu': nn.ReLU(True)\n }\n\n\ndef residual(c, **kw):\n return {\n 'in': Identity(),\n 'res1': conv_bn(c, c, **kw),\n 'res2': conv_bn(c, c, **kw),\n 'add': (Add(), [rel_path('in'), rel_path('res2', 'relu')]),\n }\n\n\ndef basic_net(channels, weight, pool, num_outputs=10, **kw):\n return {\n 'prep': conv_bn(3, channels['prep'], **kw),\n 'layer1': dict(conv_bn(channels['prep'], channels['layer1'], **kw), pool=pool),\n 'layer2': dict(conv_bn(channels['layer1'], channels['layer2'], **kw), pool=pool),\n 'layer3': dict(conv_bn(channels['layer2'], channels['layer3'], **kw), pool=pool),\n\n 'pool': nn.MaxPool2d(4),\n 'flatten': Flatten(),\n 'linear': nn.Linear(channels['layer3'], num_outputs),\n 'out': Mul(weight),\n }\n\n\ndef large_net(channels, weight, pool, num_outputs=10, **kw):\n return {\n 'prep': conv_bn(3, channels['prep'], **kw),\n 'layer1': dict(conv_bn(channels['prep'], channels['layer1'], **kw), pool=pool),\n 'layer2': dict(conv_bn(channels['layer1'], channels['layer2'], **kw), pool=pool),\n 'layer3': dict(conv_bn(channels['layer2'], channels['layer3'], **kw), pool=pool),\n 'layer4': dict(conv_bn(channels['layer3'], channels['layer4'], **kw)),\n 'layer5': dict(conv_bn(channels['layer4'], channels['layer5'], **kw)),\n\n 'pool': nn.MaxPool2d(4),\n 'flatten': Flatten(),\n 'linear': nn.Linear(channels['layer5'], num_outputs),\n 'out': Mul(weight),\n }\n\n\ndef scale_prior(model, scaling_factor):\n old_params = model.prior.state_dict()\n new_params = OrderedDict()\n\n for k, v in old_params.items():\n if k.split(\".\")[-1] in [\"weight\", \"bias\"]:\n new_params[k] = v * scaling_factor\n else:\n new_params[k] = v\n\n model.prior.load_state_dict(new_params)\n\n\ndef net(channels=None, weight=1.0, pool=nn.MaxPool2d(2), extra_layers=(), output_size=10,\n res_layers=('layer1', 'layer3'), net_type=\"basic\", **kw):\n channels = channels or {'prep': 64, 'layer1': 128, 'layer2': 256, 'layer3': 512, 'layer4': 512, 'layer5': 512}\n if net_type == \"basic\":\n n = basic_net(channels, weight, pool, num_outputs=output_size, **kw)\n elif net_type == \"large\":\n n = large_net(channels, weight, pool, num_outputs=output_size, **kw)\n else:\n raise ValueError(\"Unknown net_type.\")\n for layer in res_layers:\n n[layer]['residual'] = residual(channels[layer], **kw)\n for layer in extra_layers:\n n[layer]['extra'] = conv_bn(channels[layer], channels[layer], **kw)\n return n\n\n\nclass SpatialConcreteDropout(nn.Module):\n \"\"\"\n Adapted from https://github.com/yaringal/ConcreteDropout\n \"\"\"\n def __init__(self, weight_regularizer=1e-6,\n dropout_regularizer=1e-5, init_min=0.1, init_max=0.1):\n super(SpatialConcreteDropout, self).__init__()\n\n self.weight_regularizer = weight_regularizer\n self.dropout_regularizer = dropout_regularizer\n\n init_min = np.log(init_min) - np.log(1. - init_min)\n init_max = np.log(init_max) - np.log(1. - init_max)\n\n self.p_logit = nn.Parameter(torch.empty(1).uniform_(init_min, init_max))\n\n def forward(self, x, layer=None):\n p = torch.sigmoid(self.p_logit)\n\n out = layer(self._spatial_concrete_dropout(x, p))\n\n sum_of_square = 0\n for param in layer.parameters():\n sum_of_square += torch.sum(torch.pow(param, 2))\n\n weights_regularizer = self.weight_regularizer * sum_of_square / (1 - p)\n\n dropout_regularizer = p * torch.log(p)\n dropout_regularizer += (1. - p) * torch.log(1. - p)\n\n input_dimensionality = x[0].numel() # Number of elements of first item in batch\n dropout_regularizer *= self.dropout_regularizer * input_dimensionality\n\n regularization = weights_regularizer + dropout_regularizer\n return out, regularization\n\n def _spatial_concrete_dropout(self, x, p):\n eps = 1e-4\n temp = 2./3.\n\n unif_noise = torch.rand((x.shape[0], x.shape[1], 1, 1), dtype=x.dtype, device=x.device) # batch, channel, H, W\n\n drop_prob = (torch.log(p + eps)\n - torch.log(1 - p + eps)\n + torch.log(unif_noise + eps)\n - torch.log(1 - unif_noise + eps))\n\n drop_prob = torch.sigmoid(drop_prob / temp)\n random_tensor = 1 - drop_prob\n retain_prob = 1 - p\n\n x = torch.mul(x, random_tensor)\n x /= retain_prob\n\n return x\n\n\ndef get_hparams(seed=0):\n np.random.seed(seed)\n\n m_space = [1,2,4,8,16,32,64,128,512,1024]\n init_space = [0.25, 0.5, 1., 2., 4.]\n lr_space = [0.001, 0.005, 0.01, 0.05, 0.1, 0.5]\n out_space = [0.1, 1., 10.]\n\n hparams = {}\n hparams[\"M\"] = int(np.random.choice(m_space))\n hparams[\"init_scale\"] = np.random.choice(init_space)\n hparams[\"lr\"] = np.random.choice(lr_space)\n hparams[\"out_weight\"] = np.random.choice(out_space)\n\n return hparams\n","sub_path":"src/scripts/model_helpers.py","file_name":"model_helpers.py","file_ext":"py","file_size_in_byte":5447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"271806736","text":"#!/usr/bin/python\n\n\"\"\"\n Read a bunch of CSV files and create a raw abundance matrix.\n Good for DESeq2 analysis.\n Try to clustering the results: If two miRNAs has overlapping contig positions\n only the more abundant can survive.\n\"\"\"\n\nfrom __future__ import print_function\nimport sys\nimport re\n\nclass MiRNA:\n\n\tpattern = re.compile('([ATGC]+)\\(([0-9]+)\\)')\n\n\tdef __init__(self, raw):\n\t\tfields = raw.rstrip().split(\",\")\n\t\tself.contig = fields[0]\n\t\tself.start = int(fields[1])\n\t\tself.end = int(fields[2])\n\t\tself.abundance = float(fields[4])\n\t\tself.seq = fields[5]\n\t\t# Put all potential star sequences \n\t\tself.star = list()\n\t\tstars = fields[12].split()\n\t\tfor s in stars:\n\t\t\tfound = self.pattern.findall(s)\n\t\t\tfor f in found:\n\t\t\t\tself.star.append([f[0], int(f[1])])\n\n\tdef overlap(self, mirna):\n\t\tif self.contig == mirna.contig and self.start < mirna.end and self.end > mirna.start:\n\t\t\treturn True\n\t\treturn False\n\n# result matrix columns: input CSVs rows: mirna sequences\nmatrix = dict()\n\nfor i in sys.argv[1:]:\n\tcsv = open(i, \"r\")\n\tcsv.readline()\n\tfor line in csv:\n\t\tmirna = MiRNA(line)\n\t\tif mirna.seq not in matrix:\n\t\t\tmatrix[mirna.seq] = dict()\n\t\tmatrix[mirna.seq][i] = mirna\n\tcsv.close()\n\n# remove elements if it can be found only one experiment and there is no star sequence\nfor i in matrix.keys():\n\tif len(matrix[i]) == 1 and len(matrix[i].values()[0].star) == 0:\n\t\tdel matrix[i]\n\n\nmirids = matrix.keys()\ntodelete = set()\nfor m1 in range(0, len(mirids) - 1):\n\tk1 = mirids[m1]\n\tfor m2 in range(m1 + 1, len(mirids)):\n\t\tk2 = mirids[m2]\n\t\tif matrix[k1].values()[0].overlap(matrix[k2].values()[0]):\n\t\t\t# I need to learn some functional approaches\n\t\t\ts1 = 0\n\t\t\tfor i in matrix[k1].values():\n\t\t\t\ts1 += i.abundance\n\t\t\ts2 = 0\n\t\t\tfor i in matrix[k2].values():\n\t\t\t\ts2 += i.abundance\n\t\t\tif s1 > s2:\n\t\t\t\ttodelete.add(k1)\n\t\t\telse:\n\t\t\t\ttodelete.add(k2)\n\nfor t in todelete:\n\tdel matrix[t]\n\nprint(\"\\t\".join(sys.argv[1:]))\nfor i in matrix:\n\tprint(i, end=\"\")\n\tfor j in sys.argv[1:]:\n\t\tif j in matrix[i]:\n\t\t\tprint(\"\\t\",matrix[i][j].abundance, end=\"\",sep=\"\")\n\t\telse:\n\t\t\tprint(\"\\t0\", end=\"\")\n\tprint()\n\n","sub_path":"mircatmatrix3.py","file_name":"mircatmatrix3.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"406639202","text":"import io\n\n\ndef df_metadata(df) -> tuple:\n \"\"\"\n return a tuple of (size, shape, info)\n \"\"\"\n buffer = io.StringIO()\n df.info(buf=buffer)\n return (df.size, df.shape, buffer.getvalue())\n\n\ndef df_print_metadata(df) -> None:\n \"\"\"\n print metadata of dataframe\n \"\"\"\n size, shape, info = df_metadata(df)\n print(\"DATAFRAME METADATA\")\n print(f\"Size: {size}\")\n print()\n print(f\"Shape: {shape[0]} x {shape[1]}\")\n print()\n print(\"Info:\")\n print(info, end=\"\")\n\n\ndef df_peek(df) -> tuple:\n \"\"\"\n return head and tail of df\n \"\"\"\n return df.head().append(df.tail())\n\n\ndef df_print_summary(df):\n \"\"\"\n columns is a sequence of columns whose IQR and range will be calculated\n \"\"\"\n print(\"SUMMARY\")\n description = df.describe()\n print(\"Description:\")\n print(description)\n print()\n print(\"IQR:\")\n for col in df.columns:\n print(\n f\"\\t{col}: {description.loc['75%', col] - description.loc['25%', col]}\"\n )\n print()\n print(\"Range:\")\n for col in df.columns:\n print(f\"\\t{col}: {df[col].max() - df[col].min()}\")\n\n\ndef series_is_whole_nums(series):\n try:\n return (series % 1 == 0).all()\n except TypeError:\n return False\n\n\ndef df_float_to_int(df):\n to_coerce = {}\n for col in df.columns:\n if series_is_whole_nums(df[col]):\n to_coerce[col] = int\n return df.astype(to_coerce)\n\n\ndef df_print_missing_vals(df):\n # any missing values?\n print(\"\\nMissing Values:\\n\")\n null_counts = df.isnull().sum()\n if len(null_counts[null_counts > 0]) == 0:\n print(\"No missing values\")\n else:\n print(null_counts[null_counts > 0])\n\n\ndef df_percent_missing_vals(df):\n return (df.isnull().sum() / df.shape[0]) * 100\n\n\ndef df_drop_cols(df, to_drop):\n return df.drop(columns=to_drop)\n\n\ndef df_remove_outliers(df, cols, zscore_limit):\n df_clean = None\n for col in cols:\n df_clean = df[\n (np.abs(stats.zscore(df[cols])) < zscore_limit).all(axis=1)\n ]\n return df_clean\n\n\n# define function that will combine variables; one argument can be an operator function. like operator.add\n\n\ndef df_print_r_and_p_values(X, y):\n r_and_p_values = {col: stats.pearsonr(X[col], y) for col in X.columns}\n print(\"PEARSON'S R\")\n for k, v in r_and_p_values.items():\n col = k\n r, p = v\n print(f\"{col}:\")\n print(\n f\"\\tPearson's R is {r:.2f} with a significance p-value of {p: .3}\\n\"\n )\n\n\ndef linreg_fit_and_predict(x_train, y_train, x_test, y_test):\n lm = LinearRegression()\n lm.fit(x_train, y_train)\n\n y_label = y_train.columns[0]\n y_intercept = lm.intercept_[0]\n m = lm.coef_[0][0]\n x_label = x_train.columns[0]\n print(f\"Univariate: {y_label} = {y_intercept:.2f} + {m:.3}*{x_label}\")\n print()\n\n preds_train = lm.predict(x_train)\n\n # run test data through model\n preds_test = lm.predict(x_test)\n\n return lm, preds_train, preds_test\n\n\ndef evaluate_model_train(x, y, preds):\n y_label = y.columns[0]\n x_label = x.columns[0]\n\n print(\"Model Evaluation on TRAIN Data\")\n meanse = mean_squared_error(y, preds)\n print(f\"\\tMSE: {meanse:.3f}\")\n\n medianae = median_absolute_error(y, preds)\n print(f\"\\tMAE: {medianae:.3f}\")\n\n r2 = r2_score(y, preds)\n print(\n f\"\\t{r2:.2%} of the variance in {y_label} can be explained by {x_label}.\"\n )\n print()\n\n print(\"P-VALUE\")\n f_vals, p_vals = f_regression(x, y)\n print(f\"\\tTrain: {p_vals[0]:.3}\")\n print()\n\n\ndef evaluate_model_test(x, y, preds):\n y_label = y.columns[0]\n x_label = x.columns[0]\n\n print(\"Model Evaluation on TEST Data\")\n meanse = mean_squared_error(y, preds)\n print(f\"\\tMSE: {meanse:.3f}\")\n\n medianae = median_absolute_error(y, preds)\n print(f\"\\tMAE: {medianae:.3f}\")\n\n r2 = r2_score(y, preds)\n print(\n f\"\\t{r2:.2%} of the variance in {y_label} can be explained by {x_label}.\"\n )\n print()\n\n print(\"P-VALUE\")\n f_vals, p_vals = f_regression(x, y)\n print(f\"\\tTest: {p_vals[0]:.3}\")\n print()\n\n\ndef plot_residuals(y_test, preds_test):\n y_label = y_test.columns[0]\n plt.scatter(preds_test, preds_test - y_test, c=\"g\", s=20)\n plt.hlines(y=0, xmin=preds_test.min(), xmax=preds_test.max())\n plt.title(\"Residual plot\")\n plt.ylabel(\"Residuals\")\n plt.xlabel(y_label)\n plt.show()\n\n\ndef linreg_model(x_train, y_train, x_test, y_test):\n lm, preds_train, preds_test = linreg_fit_and_predict(\n x_train, y_train, x_test, y_test\n )\n\n evaluate_model_train(x_train, y_train, preds_train)\n evaluate_model_test(x_test, y_test, preds_test)\n\n plot_residuals(y_test, preds_test)\n \n\ndef evaluate_multi_model_train(X, y, preds):\n y_label = y.columns[0]\n X_labels = X.columns\n\n print(\"Model Evaluation on TRAIN Data\")\n meanse = mean_squared_error(y, preds)\n print(f\"\\tMSE: {meanse:.3f}\")\n\n medianae = median_absolute_error(y, preds)\n print(f\"\\tMAE: {medianae:.3f}\")\n\n r2 = r2_score(y, preds)\n print(\n f\"\\t{r2:.2%} of the variance in {y_label} can be explained by {X_labels}.\"\n )\n print()\n\n print(\"P-VALUE\")\n f_vals, p_vals = f_regression(X, y)\n print(f\"\\tTrain: {p_vals[0]:.3}\")\n print()\n \ndef evaluate_multi_model_test(X, y, preds):\n y_label = y.columns[0]\n X_labels = X.columns\n\n print(\"Model Evaluation on TEST Data\")\n meanse = mean_squared_error(y, preds)\n print(f\"\\tMSE: {meanse:.3f}\")\n\n medianae = median_absolute_error(y, preds)\n print(f\"\\tMAE: {medianae:.3f}\")\n\n r2 = r2_score(y, preds)\n print(\n f\"\\t{r2:.2%} of the variance in {y_label} can be explained by {X_labels}.\"\n )\n print()\n\n print(\"P-VALUE\")\n f_vals, p_vals = f_regression(X, y)\n print(f\"\\tTest: {p_vals[0]:.3}\")\n print()\n \ndef multi_linreg_fit_and_evaluate(X_train, y_train, X_test, y_test):\n lm = LinearRegression()\n lm.fit(X_train, y_train)\n\n y_label = y_train.columns[0]\n y_intercept = lm.intercept_[0]\n print(\"Multivariate:\")\n print(f\"{y_label} = \")\n print(f\"{y_intercept:.3f}\")\n for i, col in enumerate(X_train.columns):\n coefficient = lm.coef_[0][i]\n print(f\"+ {coefficient:.3}*{col}\")\n\n preds_train = lm.predict(X_train)\n evaluate_multi_model_train(X_train, y_train, preds_train)\n \n preds_test = lm.predict(X_test)\n evaluate_model_test(X_test, y_test, preds_test)\n \n plot_residuals(y_test, preds_test)\n\n\ndef normalize_cols(df_train, df_test, cols):\n df_train_norm = pd.DataFrame()\n for col in cols:\n minimum = df_train[col].min()\n maximum = df_train[col].max()\n df_train_norm[f\"{col}_norm\"] = (df_train[col] - minimum) / (maximum - minimum)\n \n df_test_norm = pd.DataFrame()\n for col in cols:\n minimum = df_train[col].min() # use the min and max from the train set\n maximum = df_train[col].max()\n df_test_norm[f\"{col}_norm\"] = (df_test[col] - minimum) / (maximum - minimum)\n return df_train_norm, df_test_norm","sub_path":"helper_functions.py","file_name":"helper_functions.py","file_ext":"py","file_size_in_byte":7036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"226827338","text":"class RegisterCommands:\r\n comparators = {\r\n '==': lambda a, b: a == b,\r\n '!=': lambda a, b: a != b,\r\n '<=': lambda a, b: a <= b,\r\n '>=': lambda a, b: a >= b,\r\n '<': lambda a, b: a < b,\r\n '>': lambda a, b: a > b\r\n }\r\n\r\n def __init__(self, raw_input) -> None:\r\n super().__init__()\r\n list_input = raw_input.split()\r\n self.target = list_input[0]\r\n self.sign = 1 if list_input[1] == 'inc' else -1\r\n self.amount = self.sign * int(list_input[2])\r\n self.condition_target = list_input[4]\r\n self.condition_comparator = list_input[5]\r\n self.condition_value = int(list_input[6])\r\n\r\n def execute(self, registers):\r\n if self.target not in registers:\r\n registers[self.target] = 0\r\n if self.condition_target not in registers:\r\n registers[self.condition_target] = 0\r\n\r\n condition_values = (registers.get(self.condition_target), self.condition_value)\r\n condition_lambda = self.comparators.get(self.condition_comparator)\r\n if (condition_lambda(*condition_values)):\r\n registers[self.target] = registers.get(self.target) + self.amount\r\n return registers[self.target]\r\n\r\n\r\nclass Register:\r\n day = 8\r\n test = 2\r\n\r\n def process(self, raw_input):\r\n registerCommands = self.parseInput(raw_input)\r\n register = {}\r\n max_value = 0\r\n for registerCommand in registerCommands:\r\n new_value = registerCommand.execute(register)\r\n if new_value:\r\n max_value = max(max_value, new_value)\r\n\r\n if self.test == 1:\r\n return max(register.values())\r\n else:\r\n return max_value\r\n\r\n def parseInput(self, raw_input):\r\n return [RegisterCommands(row) for row in raw_input]\r\n\r\n def executeTestOnFile(self, input_filename):\r\n with open(input_filename) as input_file:\r\n raw_input = input_file.readlines()\r\n\r\n result = self.process(raw_input)\r\n print(result)\r\n\r\n with open(self.get_output_filename(), 'w') as output_file:\r\n output_file.write(str(result))\r\n\r\n def get_output_filename(self):\r\n return \"day\" + str(self.day).zfill(2) + \".\" + str(self.test).zfill(2) + \".output\"\r\n\r\n def get_input_filename(self):\r\n return \"day\" + str(self.day).zfill(2) + \".input\"\r\n\r\n\r\nif __name__ == \"__main__\":\r\n exercise = Register()\r\n exercise.executeTestOnFile(exercise.get_input_filename())\r\n","sub_path":"day08.py","file_name":"day08.py","file_ext":"py","file_size_in_byte":2509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"60454250","text":"\"\"\" Copyright 2012, 2013 UW Information Technology, University of Washington\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\nfrom django.test import TestCase\nfrom django.conf import settings\nfrom django.test.client import Client\nfrom spotseeker_server.models import Spot\nimport simplejson as json\nimport random\nfrom django.test.utils import override_settings\nfrom mock import patch\nfrom django.core import cache\nfrom spotseeker_server import models\n\n\n@override_settings(SPOTSEEKER_AUTH_MODULE='spotseeker_server.auth.all_ok')\n@override_settings(SPOTSEEKER_SPOT_FORM='spotseeker_server.default_forms.spot.DefaultSpotForm')\n@override_settings(SPOTSEEKER_SPOTEXTENDEDINFO_FORM='spotseeker_server.default_forms.spot.DefaultSpotExtendedInfoForm')\nclass SpotPOSTTest(TestCase):\n \"\"\" Tests creating a new Spot via POST.\n \"\"\"\n\n def test_valid_json(self):\n dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache')\n with patch.object(models, 'cache', dummy_cache):\n c = Client()\n new_name = \"testing POST name: {0}\".format(random.random())\n new_capacity = 10\n response = c.post('/api/v1/spot/', '{\"name\":\"%s\",\"capacity\":\"%d\", \"location\": {\"latitude\": 50, \"longitude\": -30} }' % (new_name, new_capacity), content_type=\"application/json\", follow=False)\n\n self.assertEquals(response.status_code, 201, \"Gives a Created response to creating a Spot\")\n self.assertIn(\"Location\", response, \"The response has a location header\")\n\n self.spot = Spot.objects.get(name=new_name)\n\n self.assertEquals(response[\"Location\"], 'http://testserver' + self.spot.rest_url(), \"The uri for the new spot is correct\")\n\n get_response = c.get(response[\"Location\"])\n self.assertEquals(get_response.status_code, 200, \"OK in response to GETing the new spot\")\n\n spot_json = json.loads(get_response.content)\n\n self.assertEquals(spot_json[\"name\"], new_name, \"The right name was stored\")\n self.assertEquals(spot_json[\"capacity\"], new_capacity, \"The right capacity was stored\")\n\n def test_non_json(self):\n c = Client()\n response = c.post('/api/v1/spot/', 'just a string', content_type=\"application/json\", follow=False)\n self.assertEquals(response.status_code, 400)\n\n def test_invalid_json(self):\n c = Client()\n response = c.post('/api/v1/spot/', '{}', content_type=\"application/json\", follow=False)\n self.assertEquals(response.status_code, 400)\n\n def test_extended_info(self):\n dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache')\n with patch.object(models, 'cache', dummy_cache):\n c = Client()\n new_name = \"testing POST name: {0}\".format(random.random())\n new_capacity = 10\n json_string = '{\"name\":\"%s\",\"capacity\":\"%s\", \"location\": {\"latitude\": 50, \"longitude\": -30},\"extended_info\":{\"has_outlets\":\"true\"}}' % (new_name, new_capacity)\n response = c.post('/api/v1/spot/', json_string, content_type=\"application/json\", follow=False)\n get_response = c.get(response[\"Location\"])\n spot_json = json.loads(get_response.content)\n extended_info = {\"has_outlets\": \"true\"}\n self.assertEquals(spot_json[\"extended_info\"], extended_info, \"extended_info was succesffuly POSTed\")\n\n def test_multiple_correct_extended_info(self):\n dummy_cache = cache.get_cache('django.core.cache.backends.dummy.DummyCache')\n with patch.object(models, 'cache', dummy_cache):\n c = Client()\n json_string1 = '{\"name\":\"%s\",\"capacity\":\"10\", \"location\": {\"latitude\": 50, \"longitude\": -30},\"extended_info\":{\"has_whiteboards\":\"true\", \"has_printing\":\"true\", \"has_displays\":\"true\", \"num_computers\":\"38\", \"has_natural_light\":\"true\"}}' % (\"testing POST name: {0}\".format(random.random()))\n response1 = c.post('/api/v1/spot/', json_string1, content_type=\"application/json\", follow=False)\n json_string2 = '{\"name\":\"%s\",\"capacity\":\"10\", \"location\": {\"latitude\": 50, \"longitude\": -30},\"extended_info\":{\"has_outlets\":\"true\", \"has_outlets\":\"true\", \"has_scanner\":\"true\", \"has_projector\":\"true\", \"has_computers\":\"true\"}}' % (\"testing POST name: {0}\".format(random.random()))\n response2 = c.post('/api/v1/spot/', json_string2, content_type=\"application/json\", follow=False)\n json_string3 = '{\"name\":\"%s\",\"capacity\":\"10\", \"location\": {\"latitude\": 50, \"longitude\": -30},\"extended_info\":{\"has_outlets\":\"true\", \"has_printing\":\"true\", \"has_projector\":\"true\", \"num_computers\":\"15\", \"has_computers\":\"true\", \"has_natural_light\":\"true\"}}' % (\"testing POST name: {0}\".format(random.random()))\n response3 = c.post('/api/v1/spot/', json_string3, content_type=\"application/json\", follow=False)\n\n url1 = response1[\"Location\"]\n url2 = response2[\"Location\"]\n url3 = response3[\"Location\"]\n\n response = c.get(url1)\n spot_json1 = json.loads(response.content)\n response = c.get(url2)\n spot_json2 = json.loads(response.content)\n response = c.get(url3)\n spot_json3 = json.loads(response.content)\n\n self.assertEquals(spot_json1[\"extended_info\"], json.loads(json_string1)['extended_info'], \"extended_info was succesffuly POSTed\")\n self.assertEquals(spot_json2[\"extended_info\"], json.loads(json_string2)['extended_info'], \"extended_info was succesffuly POSTed\")\n self.assertEquals(spot_json3[\"extended_info\"], json.loads(json_string3)['extended_info'], \"extended_info was succesffuly POSTed\")\n","sub_path":"test/spot_post.py","file_name":"spot_post.py","file_ext":"py","file_size_in_byte":6181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"232855557","text":"from pecan import expose\nfrom pecan import request\nfrom galaxia.gapi.handler.v1 import status_handler\nimport logging\n\n\nlog = logging.getLogger(__name__)\n\n\nclass StatusController(object):\n @expose(generic=True)\n def index(self):\n time_interval = request.GET.get('time_interval')\n unit_type = request.GET.get('unit_type')\n search_string = request.GET.get('search_string')\n search_type = request.GET.get('search_type')\n status = request.GET.get('status')\n handler = status_handler.StatusHandler()\n unit_list = handler.get_units(unit_type, search_string, search_type, time_interval, status)\n return unit_list\n","sub_path":"galaxia/gapi/controller/v1/status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"314010324","text":"__author__ = 'Guoguo'\n\n# \n\n#print (counts)\n\n# \n\nstuff = dict()\nprint (stuff.get('candy',-1))\n\ncounts = dict()\nprint('Enter a line of text:')\nline = input('')\n\nwords = line.split()\nprint('Words: ', words)\n\nprint ('Counting...')\nfor word in words:\n counts[word] = counts.get(word,0) + 1\n\nprint ('Counts', counts)\n\nbigcount = None\nbigword = None\n\nfor word, count in counts.items():\n if bigcount is None or count > bigcount:\n bigword = word\n bigcount = count\n\nprint('most common word: ', bigword, 'appearance: ',bigcount)\n","sub_path":"Courera/dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"547384219","text":"#variable creation\na=5\nprint(a)\n\n#multiple assignments\na=b=9\nprint(a,b)\n\n#even both int and a string\na=b=1,\"hi\"\nprint(a)\nprint(b)\n\n#global variable \nglobal x\nx=10\n\ndef foo():\n\tx=5\n\tprint(\"hi\")\nprint(x) #prints a as 10 since global alone\n\n#local variable usage\ndef fib():\n\ty=9\n\treturn y\ny=fib()\nprint(y)\n\n'''OUTPUT:\nstud@HP-246-Notebook-PC:~$ python abi_variables.py\n5\n9 9\n(1, 'hi')\n(1, 'hi')\n10\n9\n'''\n\n\n\n","sub_path":"abi_variables.py","file_name":"abi_variables.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"334801113","text":"from backend.agent import Agent\nfrom backend.models.graph import Network\nfrom backend.models.ontology import Ontology\nfrom backend.utils.FRUtils import format_pretty_htn\n\nimport json, os, unittest\n\nclass AnotherBackLegTestCase(unittest.TestCase):\n\n def setUp(self):\n self.n = Network()\n self.ontology = self.n.register(Ontology.init_default())\n\n def resource(self, fp):\n r = None\n with open(fp) as f:\n r = json.load(f)\n return r\n\n def test_input(self):\n file = os.path.abspath(__package__) + \"/resources/DemoMay2018_Analyses_ext.json\"\n demo = self.resource(file)\n\n input = []\n\n for i in range(35):\n input.append(demo[i])\n # print(demo[i][\"sentence\"])\n\n\n # print(demo[11][\"sentence\"])\n\n\n agent = Agent(ontology=self.ontology)\n agent.logger().enable()\n\n # # agent.logger().disable()\n\n print(\"\\n========================================\\n\")\n for i in input:\n agent.input(i)\n print(\"\\n\\n\")\n print(\"HTN (simplified):\")\n print(format_pretty_htn(agent.wo_memory, agent.wo_memory[\"WM.BUILD.1\"], indent=1))\n print(\"\")\n print(\"============================================\")\n print(\"\")\n print(agent.wo_memory)\n print(\"=\"*80)\n\n def test_ltm(self):\n file = os.path.abspath(__package__) + \"/resources/DemoMay2018_Analyses_ext.json\"\n demo = self.resource(file)\n\n agent = Agent(ontology=self.ontology)\n # agent.logger().disable()\n agent.logger().enable()\n\n input = []\n\n for i in range(36):\n input.append(demo[i])\n # input = [\n # demo[0], # We will build a chair.\n\n # demo[1], # I need a screwdriver to assemble a chair.\n # demo[2], # Get a screwdriver.\n\n # demo[3], # First, we will build a front leg of the chair.\n # demo[4], # Get a foot bracket.\n # demo[5], # Get a front bracket.\n # demo[6], # Get a dowel.\n # demo[7], # Hold the dowel.\n # demo[8], # I am using the screwdriver to affix the brackets on the dowel with screws.\n # demo[9], # Release the dowel.\n # demo[10], # We have assembled a front leg.\n # demo[11], # Now, another front leg.\n # demo[12], # Get another foot bracket.\n # demo[13], # Get another front bracket.\n # demo[14], # Get another dowel.\n # demo[15], # Hold the dowel.\n # demo[16], # I am putting another set of brackets of the dowel.\n # demo[17], # Release the dowel.\n # demo[18], # I have assembled another front chair leg\n # demo[19]\n # ]\n for i in input:\n agent.input(i)\n print(\"\\n\\n\")\n\n print(\"\\nLong Term Memory BUILD-LT1\\n\")\n print(format_pretty_htn(agent.lt_memory, agent.lt_memory[\"BUILD.1\"], indent=1))\n print(\"========\")\n\n # print(\"\")\n # print(\"Action Queue\")\n # print(agent.action_queue)\n\n # from backend.contexts.ACTContext import ACTContext\n # agent.context = ACTContext(agent)\n\n # print(\"\")\n # agent.logger().enable()\n\n\n # agent.input(demo[0])\n # print(\"\")\n # print(\"Action Queue\")\n # print(agent.action_queue)\n\n\n # print(\"Action Queue\")\n # for i in input:\n # agent.input(i)\n # print(agent.action_queue)\n\n\n\n\n\n\n\n\n","sub_path":"tests/AnotherBackLegTestCase.py","file_name":"AnotherBackLegTestCase.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"631958398","text":"import os\nimport torch\nfrom torchvision.utils import save_image\n\n\n\n\ndef train(data_loader,D,G,d_optimizer,g_optimizer,criterion,config,device = torch.device('cuda')):\n total_step = len(data_loader)\n num_epochs = config.getint('h_param','num_epochs')\n batch_size = config.getint('h_param','batch_size')\n latent_size = config.getint('h_param','latent_size')\n\n def denorm(x):\n out = (x+1) / 2\n return out.clamp(0,1)\n\n for epoch in range(num_epochs):\n for i, (images, _) in enumerate(data_loader):\n images = images.reshape(batch_size, -1).to(device)\n \n real_labels = torch.ones(batch_size, 1).to(device)\n fake_labels = torch.zeros(batch_size, 1).to(device)\n\n outputs = D(images)\n d_loss_real = criterion(outputs, real_labels)\n real_score = outputs\n\n z = torch.randn(batch_size, latent_size).to(device)\n fake_images = G(z)\n outputs = D(fake_images)\n d_loss_fake = criterion(outputs, fake_labels)\n fake_score = outputs\n\n d_loss = d_loss_real + d_loss_fake\n d_optimizer.zero_grad()\n g_optimizer.zero_grad()\n d_loss.backward()\n d_optimizer.step()\n\n z = torch.randn(batch_size, latent_size).to(device)\n fake_images = G(z)\n outputs = D(fake_images)\n\n g_loss = criterion(outputs, real_labels)\n\n d_optimizer.zero_grad()\n g_optimizer.zero_grad()\n\n if (i+1) % 200 == 0:\n print('Epoch [{}/{}], Step [{}/{}], d_loss: {:.4f}, g_loss: {:.4f}, D(x): {:.2f}, D(G(z)): {:.2f}' \n .format(epoch, num_epochs, i+1, total_step, d_loss.item(), g_loss.item(), \n real_score.mean().item(), fake_score.mean().item()))\n if (epoch) == 0:\n images = images.reshape(images.size(0), 1, 28, 28)\n save_image(denorm(images), os.path.join(config.get('path','sample_dir'),'real_images.png'))\n\n fake_images = fake_images.reshape(fake_images.size(0),1,28,28)\n save_image(denorm(fake_images),os.path.join(config.get('path','sample_dir'),'fake_images-{}.png'.format(epoch+1)))","sub_path":"trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"24773820","text":"from pyqtgraph.Qt import QtCore, QtGui\nimport pyqtgraph as pg\nimport numpy as np\nfrom datos import data\n\nd=data('mtcars')\nt1 = d.pivot_table( values = 'carb',index=['cyl'], columns = ['gear'], aggfunc = len)\nbar_width = 0.25\nwin = pg.plot(title='Simple Bar Chart')\nbg1 = pg.BarGraphItem(x=t1.columns, height=t1.values[0], width=bar_width, brush='g')\nbg2 = pg.BarGraphItem(x=t1.columns+bar_width, height=t1.values[1], width=bar_width, brush='r')\nbg3 = pg.BarGraphItem(x=t1.columns+2*bar_width, height=t1.values[2], width=bar_width, brush='y')\nwin.addItem(bg1)\nwin.addItem(bg2)\nwin.addItem(bg3)\nwin.setTitle('Car Distribution by Gear and Cylindres ')\nwin.setLabel('left', \"Frequency\", )\nwin.setLabel('bottom', \"Number of Gears\")\n\nif __name__ == '__main__':\n import sys\n if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):\n QtGui.QApplication.instance().exec_()","sub_path":"display-patterns/Discrete Quantities/Pruebas/A32Multiset_Bar_Chart_Pyqtgraph.py","file_name":"A32Multiset_Bar_Chart_Pyqtgraph.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"128898859","text":"import json\n\nfrom django.db.models import Prefetch\nfrom django.http.response import Http404, HttpResponse\nfrom django.shortcuts import get_object_or_404, redirect, render, reverse\nfrom django.utils.decorators import method_decorator\nfrom django.views import generic\nfrom django.views.decorators.cache import never_cache\n\nfrom .forms import ProductForm\nfrom .models import File, Order, Product\nfrom .utils import email_helper, zipFiles\n\n# Create your views here.\n\n\n# =========================================================== Seller View ===================================================\n\n\nclass ProductCreateView(generic.View):\n form_class = ProductForm\n template_name = \"index.html\"\n\n def post(self, request, *args, **kwargs):\n \"\"\"Depreciated, in favor of REST Endpoint\"\"\"\n product_form = self.form_class(request.POST or None)\n if product_form.is_valid():\n product = product_form.save()\n for _file in request.FILES.getlist(\"files\"):\n file_obj = File.objects.create(\n product=product, file_data=_file.file.read(), file_name=_file.name\n )\n request.session[\"product_id\"] = product.pk\n return redirect(reverse(\"core:product_seller_email_updates\"))\n else:\n return render(\n request, self.template_name, context={\"errors\": product_form.errors}\n )\n\n def get(self, request, *args, **kwargs):\n return render(request, \"index.html\")\n\n\nclass ProductEmailUpdatesView(generic.TemplateView):\n\n template_name = \"sell-email.html\"\n\nclass ProductSellerView(generic.DetailView):\n template_name = \"pymnt-dash.html\"\n model = Product\n\n def get_object(self, **kwargs):\n products = Product.objects.filter(token=self.kwargs.get(\"token\"))\n if not products.exists():\n raise Http404(\"Product with given token does not exist\")\n\n product = products.prefetch_related(\"orders\").first()\n return product\n\n def get_context_data(self, **kwargs):\n context = super(ProductSellerView, self).get_context_data(**kwargs)\n context[\"btc_balance\"] = context[\"object\"].btc_balance\n # context[\"bch_balance\"]=context[\"object\"].bch_balance\n context[\"public_uri\"] = self.request.build_absolute_uri(\n reverse(\"core:product_info_buyer\", kwargs={\"uid\": context[\"object\"].uid})\n )\n context[\"orders\"] = context[\"object\"].orders.filter(\n status_of_transaction=Order.StatusChoices.CONFIMED\n )\n return context\n\n\n# ===================================================== BUYER VIEW ============================================\n\n\nclass ProductPublicView(generic.TemplateView):\n\n template_name = \"buyerLanding.html\"\n\nclass IntializeOrder(generic.TemplateView):\n\n template_name = \"buyerPay.html\"\n\nclass OrderConfirmCallbackView(generic.View):\n def post(self, request, *args, **kwargs):\n data = json.loads(request.body)\n status_of_transaction = data.get(\"status\", None)\n order_id = data.get(\"order_id\", None)\n if status_of_transaction is None or order_id is None:\n return HttpResponse(\"Invalid data\", status=400)\n\n order = get_object_or_404(Order, pk=int(order_id))\n\n if status_of_transaction >= order.status_of_transaction:\n order.status_of_transaction = max(\n order.status_of_transaction, status_of_transaction\n )\n order.save()\n return redirect(\n reverse(\n \"core:order_info_buyer\", kwargs={\"order_id\": order.order_id}\n )\n )\n\n return HttpResponse(\"Order status isn't changed\")\n\n\nclass OrderStatusView(generic.View):\n order_status_view = {\n 0: \"confirmation.html\",\n 1: \"confirmation.html\",\n 2: \"payStatus.html\",\n }\n\n def get_order(self, **kwargs):\n order = get_object_or_404(Order, uid=self.kwargs.get(\"order_uid\"))\n return order\n\n @method_decorator(never_cache)\n def get(self, request, *args, **kwargs):\n order = self.get_order(**kwargs)\n try:\n request.session[\"order\"][\n \"status_of_transaction\"\n ] = order.status_of_transaction\n request.session.modified = True\n except KeyError:\n request.session[\"order\"] = {\n \"status_of_transaction\": order.status_of_transaction\n }\n\n context = {\n \"order\": order,\n \"download_uri\": request.build_absolute_uri(\n reverse(\n \"core:order_info_buyer\", kwargs={\"order_id\": order.order_id}\n )\n ),\n }\n\n return render(\n request,\n self.order_status_view[order.status_of_transaction],\n context=context,\n )\n\n\nclass DownloadFiles(generic.View):\n def get_order(self, **kwargs):\n orders = Order.objects.filter(order_id=kwargs[\"order_id\"])\n if not orders.exists():\n raise Http404(\"Order with given order id does not exist\")\n\n order = (\n orders.select_related(\"product\")\n .prefetch_related(\n Prefetch(\n \"product__files\",\n queryset=File.objects.filter(\n product__orders__order_id=kwargs[\"order_id\"]\n ),\n to_attr=\"files_list\",\n )\n )\n .first()\n )\n return order\n\n def get(self, request, *args, **kwargs):\n\n order = self.get_order(**kwargs)\n\n try:\n status_of_transaction = request.session[\"order\"][\"status_of_transaction\"]\n if status_of_transaction == 2:\n files = order.product.files_list\n zipped_file = zipFiles(files)\n response = HttpResponse(\n zipped_file, content_type=\"application/octet-stream\"\n )\n response[\n \"Content-Disposition\"\n ] = f\"attachment; filename={order.product.product_name}.zip\"\n return response\n else:\n return HttpResponse(\"Order is being processed\")\n except KeyError:\n return HttpResponse(\"Session may have expired try refreshing\", status=400)\n except Exception as e:\n repr(e)\n return HttpResponse(repr(e), status=400)\n\n\nclass UpdateOrderStatusCallback(generic.View):\n email_template = \"emails/payment.html\"\n email_subject = \"emails/product_page.txt\"\n extra_email_context = {}\n\n def get(self, request, *args, **kwargs):\n order = get_object_or_404(Order, address=request.GET[\"addr\"])\n order.status_of_transaction = max(\n order.status_of_transaction, int(request.GET[\"status\"])\n )\n order.txid = request.GET[\"txid\"]\n if int(request.GET[\"status\"]) == 2:\n order.received_value = float(request.GET[\"value\"]) / 1e8\n self.extra_email_context[\"track_uri\"] = self.request.build_absolute_uri(\n reverse(\n \"core:product_info_seller\", kwargs={\"token\": order.product.token}\n )\n )\n email_helper(\n request,\n order.product.email,\n self.email_subject,\n self.email_template,\n html_email_template_name=self.email_template,\n extra_email_context=self.extra_email_context,\n )\n order.save()\n return HttpResponse(200)\n","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"50417185","text":"from django.db.models import Sum\nfrom django.utils import timezone\nfrom core.authentication import AuthenticationManager\nfrom health.models.activity import Activity\nfrom health.models.consumption import Consumption\nfrom health.models.weight import WeightHistory\n\n\ndef get_cards(request):\n cards = []\n\n user = AuthenticationManager.get_session_user(request=request)\n today = timezone.now().date()\n\n consumption = Consumption.objects.filter(user=user, date=today).aggregate(Sum(\"calorie\"))\n daily_calorie_intake = consumption[\"calorie__sum\"] if consumption[\"calorie__sum\"] else 0\n\n activity = Activity.objects.filter(user=user, date=today).aggregate(Sum(\"calorie\"))\n daily_calorie_outtake = activity[\"calorie__sum\"] if activity[\"calorie__sum\"] else 0\n\n latest_weight = None\n weights = WeightHistory.objects.filter(user=user)\n if weights is not None and weights.count() > 0:\n latest_weight = weights.order_by('-date')[0]\n\n weight = \"-\"\n if latest_weight is not None and latest_weight.weight is not None:\n weight= latest_weight.weight\n\n bmi = \"-\"\n if latest_weight is not None and latest_weight.bmi is not None:\n bmi= latest_weight.bmi\n\n card1 = {\n 'title': 'Weight',\n 'value': weight,\n 'unit': 'kg',\n 'comment': 'today',\n 'icon1': 'ti-server',\n 'icon2': 'ti-reload'\n }\n cards.append(card1)\n card2 = {\n 'title': 'BMI',\n 'value': bmi,\n 'unit': '',\n 'comment': 'today',\n 'icon1': 'ti-pulse',\n 'icon2': 'ti-reload'\n }\n cards.append(card2)\n card3 = {\n 'title': 'Intake',\n 'value': daily_calorie_intake,\n 'unit': 'cal',\n 'comment': 'today',\n 'icon1': 'ti-upload',\n 'icon2': 'ti-reload'\n }\n cards.append(card3)\n card4 = {\n 'title': 'Outtake',\n 'value': daily_calorie_outtake,\n 'unit': 'cal',\n 'comment': 'today',\n 'icon1': 'ti-download',\n 'icon2': 'ti-reload'\n }\n cards.append(card4)\n return cards\n","sub_path":"fitplus/core/cards.py","file_name":"cards.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"603897533","text":"from itertools import dropwhile\n\ndef least_divisor(k,n):\n while k < n:\n if n%k == 0: return k\n else: k +=1\n return n\n \ndef prime_factors(n):\n k = 2\n N = n\n factors = []\n while N > 1:\n k = least_divisor(k,N)\n factors.append(k)\n N = N/k\n return factors\n \ndef solution():\n n = 600851475143\n return max(prime_factors(n))\n\nif __name__ == \"__main__\":\n print(solution())\n \n","sub_path":"src/p03.py","file_name":"p03.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"316758740","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/3/5 11:56\n# @Author : Yajun Yin\n# @Note :\n\n\nimport tensorflow as tf\n\n# 使用tf.train.match_filenames_once函数获取符合一个正则表达式的所有文件\n# 得到的文件列表可以通过tf.train.string_input_producer函数有效管理\nfiles = tf.train.match_filenames_once(\"/path/to/data.tfrecords-*\")\n\n# tf.train.string_input_producer函数创建输入队列\n# num_epochs:计算一轮后自动停止\nfilename_queue = tf.train.string_input_producer(files, shuffle=False, num_epochs=1)\n\nreader = tf.TFRecordReader()\n_, serialized_example = reader.read(filename_queue)\nfeatures = tf.parse_single_example(serialized_example, features={\n 'i': tf.FixedLenFeature([], tf.int64),\n 'j': tf.FixedLenFeature([], tf.int64)})\n\nwith tf.Session() as sess:\n init_op = tf.local_variables_initializer()\n init_op.run()\n\n print(files.eval())\n\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess, coord)\n\n for i in range(4):\n print(sess.run([features['i'], features['j']]))\n coord.request_stop()\n coord.join(threads)\n","sub_path":"Practice-In-Tensorflow/file_queue.py","file_name":"file_queue.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"237070459","text":"\"\"\"\nResults analysis\n\"\"\"\n\nimport pandas\nfrom mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes, mark_inset\nfrom scipy import stats\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch\nfrom torch import nn\nimport os\n\n\n\nsystems = ['flexy air ctrl']\n\n\nlinear_map = ['linear', 'softSVD']\nN = ['8', '16', '32']\n# policy = ['mlp', 'rnn']\n# activations = ['gelu', 'softexp']\n# models = ['/people/drgo694/neuromancer/neuromancer/neuromancer/datasets/Flexy_air/best_model_flexy1.pth',\n# '/qfs/projects/deepmpc/best_flexy_models/best_blocknlin_nlinsearch/best_model.pth',\n# '/people/drgo694/neuromancer/neuromancer/neuromancer/datasets/Flexy_air/best_model_flexy2.pth']\nmodels = ['/people/drgo694/neuromancer/neuromancer/neuromancer/datasets/Flexy_air/best_model_flexy1.pth']\n\ndef process_res(res, key, system_metrics={}):\n # system_metrics[key] = {}\n if not res.empty:\n if res['metrics.best_nstep_test_ref_loss'].idxmin() is not np.nan:\n best = res.loc[res['metrics.best_nstep_test_ref_loss'].idxmin()]\n else:\n best = None\n system_metrics[key]['best'] = best\n res = res.loc[res['metrics.best_nstep_dev_ref_loss'].notnull()]\n # extract metrics\n nstep_dev = res['metrics.best_nstep_dev_loss']\n nstep_test = res['metrics.best_nstep_test_loss']\n nstep_test_ref = res['metrics.best_nstep_test_ref_loss']\n nstep_dev_ref = res['metrics.best_nstep_dev_ref_loss']\n\n # log metrics\n system_metrics[key]['mean_nstep_dev'] = nstep_dev.mean()\n system_metrics[key]['mean_nstep_test'] = nstep_test.mean()\n system_metrics[key]['mean_nstep_test_ref'] = nstep_test_ref.mean()\n system_metrics[key]['mean_nstep_dev_ref'] = nstep_dev_ref.mean()\n\n system_metrics[key]['std_nstep_dev'] = nstep_dev.std()\n system_metrics[key]['std_nstep_test'] = nstep_test.std()\n system_metrics[key]['std_nstep_test_ref'] = nstep_test_ref.std()\n system_metrics[key]['std_nstep_dev_ref'] = nstep_dev_ref.std()\n\n system_metrics[key]['min_nstep_dev'] = nstep_dev.min()\n system_metrics[key]['min_nstep_test'] = nstep_test.min()\n system_metrics[key]['min_nstep_test_ref'] = nstep_test_ref.min()\n system_metrics[key]['min_nstep_dev_ref'] = nstep_dev_ref.min()\n return system_metrics\n\nif __name__ == '__main__':\n\n # res = pandas.read_pickle(\"../results/control/flexy_deepmpc_2020_9_8.pkl\")\n # res = pandas.read_csv(\"../results/control/flexy_deepmpc_2020_9_8.csv\")\n res = pandas.read_csv(\"../results/control/flexy_deepmpc_2020_9_13.csv\")\n\n res.rename(columns={'params.model_file': 'models', 'params.linear_map': 'linear_map',\n 'params.activation': 'activation', 'params.policy': 'policy',\n 'params.nsteps': 'nsteps'}, inplace=True)\n # hierarchical index\n res.reset_index(inplace=True)\n # res.set_index(['index', 'models', 'linear_map', 'activation', 'policy', 'nsteps'], drop=False, inplace=True)\n res.set_index(['index', 'linear_map', 'nsteps'], drop=False, inplace=True)\n res.index\n\n system_metrics = {}\n if not res.empty:\n if res['metrics.best_nstep_dev_ref_loss'].idxmin() is not np.nan:\n best = res.loc[res['metrics.best_nstep_dev_ref_loss'].idxmin()]\n else:\n best = None\n system_metrics['best'] = best\n for nstep in N:\n system_metrics[nstep] = {}\n res_system_N = res.loc[res.nsteps == int(nstep)]\n system_metrics = process_res(res=res_system_N, key=nstep, system_metrics=system_metrics)\n # if not res_system_N.empty:\n # if res_system_N['metrics.best_nstep_dev_ref_loss'].idxmin() is not np.nan:\n # best = res_system_N.loc[res_system_N['metrics.best_nstep_dev_ref_loss'].idxmin()]\n # else:\n # best = None\n # system_metrics[nstep+'best'] = best\n for linear in linear_map:\n system_metrics[nstep][linear] = {}\n res_system_N_lin = res_system_N.loc[res_system_N.linear_map == linear]\n system_metrics[nstep] = process_res(res=res_system_N_lin, key=linear, system_metrics=system_metrics[nstep])\n # if not res_system_N_lin.empty:\n # if res_system_N_lin['metrics.best_nstep_dev_ref_loss'].idxmin() is not np.nan:\n # best = res_system_N_lin.loc[res_system_N_lin['metrics.best_nstep_dev_ref_loss'].idxmin()]\n # else:\n # best = None\n # system_metrics[linear + nstep + 'best'] = best\n\n # for type in models:\n # system_metrics[nstep][type] = {}\n # res_system_N_type = res_system_N.loc[res_system_N.models == type]\n # system_metrics[nstep] = process_res(res=res_system_N_type, key=type, system_metrics=system_metrics[nstep])\n # for linear in linear_map:\n # system_metrics[nstep][type][linear] = {}\n # res_system_N_type_lin = res_system_N_type.loc[res_system_N_type.linear_map == linear]\n # system_metrics[nstep][type] = process_res(res=res_system_N_type_lin, key=linear, system_metrics=system_metrics[nstep][type])\n # for nonlinear in policy:\n # system_metrics[nstep][type][linear][nonlinear] = {}\n # res_system_N_type_nonlin = res_system_N_type_lin.loc[res_system_N_type_lin.policy == nonlinear]\n # system_metrics[nstep][type][linear] = process_res(res=res_system_N_type_nonlin, key=nonlinear,\n # system_metrics=system_metrics[nstep][type][linear])\n\n metrics_df = pandas.DataFrame.from_dict(system_metrics)\n\n # # # # # # # # # #\n # METRICS\n # # # # # # # # # #\n idx = []\n for model in models:\n idx.append(model.split('/')[-1])\n stdopen, stdnstep, meanopen, meannstep, min_nstep_dev, min_nstep_test = \\\n [pandas.DataFrame(index=idx,\n columns=N) for i in range(6)]\n\n for i in N:\n stdopen[i] = \\\n metrics_df[i]['std_nstep_dev_ref']\n stdnstep[i] = \\\n metrics_df[i]['std_nstep_test_ref']\n meanopen[i] = \\\n metrics_df[i]['mean_nstep_dev_ref']\n meannstep[i] = \\\n metrics_df[i]['mean_nstep_test_ref']\n min_nstep_dev[i] = \\\n metrics_df[i]['min_nstep_dev_ref']\n min_nstep_test[i] = \\\n metrics_df[i]['min_nstep_test_ref']\n\n # idx = []\n # for model in models:\n # idx.append(model)\n # stdopen, stdnstep, meanopen, meannstep, min_nstep_dev, min_nstep_test = \\\n # [pandas.DataFrame(index=idx,\n # columns=N) for i in range(6)]\n #\n # for i in N:\n # for model in models:\n # # if not not metrics_df[i]:\n # # if not not metrics_df[i][model][linear][nonlinear]:\n # stdopen.loc[model,i] = \\\n # metrics_df[i][model]['std_nstep_dev_ref']\n # stdnstep.loc[model,i] = \\\n # metrics_df[i][model]['std_nstep_test_ref']\n # meanopen.loc[model, i] = \\\n # metrics_df[i][model]['mean_nstep_dev_ref']\n # meannstep.loc[model, i] = \\\n # metrics_df[i][model]['mean_nstep_test_ref']\n # min_nstep_dev.loc[model, i] = \\\n # metrics_df[i][model]['min_nstep_dev_ref']\n # min_nstep_test.loc[model, i] = \\\n # metrics_df[i][model]['min_nstep_test_ref']\n\n # # # # # # # # # #\n # PLOTS and Tables\n # # # # # # # # # #\n\n # Latex Table\n for k in [stdopen, stdnstep, meanopen, meannstep, min_nstep_dev, min_nstep_test]:\n print(k.to_latex(float_format=lambda x: '%.3f' % x))\n\n # Bar plot\n fig = plt.figure(figsize=(14, 10))\n width = 0.05\n ind = np.arange(len(N))\n for i, n in enumerate(idx):\n # plt.bar(ind + i * width, minopen.iloc[i], width, label=n, edgecolor='white')\n plt.bar(ind+i*width, min_nstep_dev.loc[n], width, label=n, edgecolor='white')\n plt.xlabel('Training Prediction Horizon')\n plt.ylabel('min nstep dev MSE')\n plt.xticks(ind + width, N)\n plt.legend(loc='best')\n plt.tight_layout()\n plt.grid()\n plt.yscale(\"log\")\n # plt.savefig('../figs/open_loop.eps')\n # plt.savefig('../figs/open_loop_.png')\n\n\n fig = plt.figure(figsize=(14, 10))\n ind = np.arange(len(N))\n for i, n in enumerate(idx):\n plt.bar(ind+i*width, min_nstep_test.loc[n], width, label=n, edgecolor='white')\n plt.xlabel('Training Prediction Horizon')\n plt.ylabel('min nstep test MSE')\n plt.xticks(ind + 1.5*width, N)\n plt.legend(loc='best')\n plt.tight_layout()\n plt.grid()\n plt.yscale(\"log\")\n # plt.savefig('../figs/nstep_mse.eps')\n # plt.savefig('../figs/nstep_mse.png')\n\n # copy artifacts\n if False:\n os.system('mkdir ..\\\\results\\\\'+system_metrics['best']['params.savedir'].split('.')[0].split('/')[1])\n os.system('scp drgo694@ohmahgerd:'+system_metrics['best']['artifact_uri']+'/* '+'..\\\\results\\\\'+system_metrics['best']['params.savedir'].split('.')[0].split('/')[1])\n","sub_path":"neuromancer/analysis/results_analysis_flexy_ctrl.py","file_name":"results_analysis_flexy_ctrl.py","file_ext":"py","file_size_in_byte":9150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"433263232","text":"import sys\nread = lambda :sys.stdin.readline().rstrip()\n\nM = int(read())\ncups = [0, 1, 2, 3]\nfor _ in range(M):\n a, b = map(int, read().split())\n temp = cups[a]\n cups[a] = cups[b]\n cups[b] = temp\nfor i in range(4):\n if cups[i] == 1:\n print(i)","sub_path":"Baekjoon,SWEA, etc/백준/1547.py","file_name":"1547.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"28204210","text":"\n# region Comments STRUKTURA OPISA\n\n# PODATKE V OBLIKI CSV VPISE V EXCEL\n# 1. podajanje artiklov po vrsticah !!!\n#\n# OBLIKA podatkov zapisanih v Excel\n# Kategorija, Naziv, Opis\n#\n#\n# PODATKI, KI SESTAVLJAJO OPIS\n# Opis karakteristike enote\n# Proizvajalec: Kaysun by Frigicoll, Španija\n# Uvoznik: REAM d.o.o.\n#\n# Tehnicni podatki:\n# Nazivna moč hlajenja: nazivna / min /maks kW\n# Nazivna moč ogrevanja: nazivna / min / maks kW\n# SEER: xxx\n# SCOP: xxx\n# COP: xxx\n# Energetski razred(hlajenje): xxx\n# Električna moč(ogrevanje): nazivna / min / maks W\n# Električni priključek: 230V / 1F / 50Hz\n# Hladivo: xxx\n# Zvočni tlak SPL: xxx dB(A)\n# Cevne povezave: (tekoča/plinska) mm\n# Dimenzije DxŠxV: (a x b x c) mm\n# Teža: xxx kg\n\n# endregion Comments STRUKTURA OPISA\n\nimport csv\nimport openpyxl, re, itertools, collections\nimport unittest\n# import datoteke\n\n# region CSV V SEZNAM\n# 1. Zapiši vrednosti iz .csv datoteke v obliki seznama seznamov\n# datoteka_sez = [[vrstica],\n# [vrstica]]\ndatoteka_sez = []\n\n\ndef func_csv_v_sez(m):\n \"\"\"Odpre csv datoteko shranjeno na lokaciji m in jo pretvori v seznam\n\n :param str m: mesto datoteke\n :return str datoteka_sez: csv dokument v obliki seznama seznamov\n \"\"\"\n\n global datoteka_sez\n with open(m, encoding='utf-8') as datoteka:\n csv_bralnik = csv.reader(datoteka)\n datoteka_sez = [i for i in csv_bralnik]\n\ndatoteka_sez = [['podatek', 'enota', 'vrednost', 'vrednost2'],\n ['A aaaa', 'mm', '10', '20'],\n ['B bbbb', 'mm', '100', '200'],\n ['C cccc', 'mm', '1000', '2000']]\n\ndef func_dimenzije():\n global datoteka_sez\n temp_sez = []\n while len(temp_sez) < 3:\n for vrstica in datoteka_sez:\n if re.search('^[ABCabc]\\s*', vrstica[0]):\n temp_sez.append(vrstica)\n dimenzije = ['Dimenzije DxŠxV', '']\n for stolpec in range(2,len(temp_sez)+1):\n x = lambda s: '('+' x '.join([temp_sez[0][s], temp_sez[1][s], temp_sez[2][s]]) + ') mm'\n dimenzije.append(x(stolpec))\n return dimenzije\n\nprint(func_dimenzije())\n\n# endregion CSV V SEZNAM\n\n\n# region VREDNOSTI V SLOVAR\n# 2. Iteriraj skozi podatke in jih shrani v slovar, KATEREGA\n# ključi so terke(x, y),\n# param x: stolpec [2:]\n# param y: vrstica\n\n# TODO 11.4. : Popravi: Po nazivu, ki ga nočemo dodati naj funkcija vpraša samo enkrat\ndatoteka_slo = {}\n\n\ndef func_vrednosti_v_slo():\n \"\"\"Shrani vednosti v obliki slovarja. Vrednosti so podane v treh seznamov, pri čemer dva seznama predstavljata ključ, tretji seznam pa predstavlja vrednost\n\n dict(\n ('karakteristika', 'model'): vrednost\n )\n\n dict(\n (key1, key2): values[i],\n )\n \"\"\"\n\n global datoteka_slo\n key1 = [i[0] for i in datoteka_sez[1:]]\n key2 = datoteka_sez[0][2:]\n values = []\n [values.extend(i[2:]) for i in datoteka_sez[1:]]\n\n for n, produkt in enumerate(itertools.product(key1, key2)):\n if produkt in datoteka_slo.keys():\n vprasaj = input(\n '>>{}<< se ponovi, zamenjam? (da/enter): '.format(produkt[0]))\n if vprasaj.lower() == 'da':\n datoteka_slo[produkt] = values[n]\n else:\n continue\n datoteka_slo[produkt] = values[n]\n\n# endregion VREDNOSTI V SLOVAR\n\n\n# region KATERE VREDNOSTI\nprevod_slo = datoteke.prevodi_slo\n\n\ndef func_katere_vrednosti():\n \"\"\"Iteriraj po prevem členu vrstice in vprašaj za prevod. Če prevoda ni, potem nadaljuje na naslednjo vrstico.\n \"\"\"\n\n global prevod_slo\n prevod_slo = {}\n i = 1\n vrstica = datoteka_sez[0]\n # if datoteke.prevodi_slo:\n # prevod_slo = datoteke.prevodi_slo\n # print('Prevodi uvoženi')\n # return None\n print('Dodaj prevod in ENTER / Preskoči vrstico z ENTER')\n while i < len(datoteka_sez):\n vrstica = datoteka_sez[i]\n prevod = input(\n '{} {} (\"prevod\"/nazaj): '.format(vrstica[0], vrstica[1]))\n if prevod.lower() == 'nazaj':\n i -= 1\n continue\n elif prevod:\n prevod_slo[(vrstica[0])] = prevod\n i += 1\n print(prevod_slo)\n\n# endregion KATERE VREDNOSTI\n\n\n# region USTVARI EXCEL\nzvezek, strani, stran, celica = None, None, None, None\n\n\ndef temp_naslovna_vrstica(ime_lista):\n naslovna = ['Šifra', 'Naziv', 'Naziv dodatno',\n 'Dodatni text', 'Prodajna cena']\n for stolpec, vrednost in enumerate(naslovna, 1):\n _ = ime_lista.cell(column=stolpec, row=1, value=vrednost)\n\n\ndef temp_dimenzioniraj_celico(ime_lista):\n ime_lista.column_dimensions['A'].width = 10\n ime_lista.column_dimensions['B'].width = 30\n ime_lista.column_dimensions['C'].width = 15\n ime_lista.column_dimensions['D'].width = 60\n ime_lista.column_dimensions['e'].width = 10\n for c in stran[1]:\n c.fill = openpyxl.styles.PatternFill(\"solid\", fgColor='ffff99')\n for c in stran[1]:\n c.alignment = openpyxl.styles.Alignment(wrap_text=True)\n double = openpyxl.styles.Side(border_style=\"double\", color=\"111111\")\n for c in stran[1]:\n c.border = openpyxl.styles.Border(bottom=double)\n\n\ndef func_ustvari_zvezek():\n global zvezek, strani, stran, celica\n zvezek = openpyxl.Workbook()\n try:\n stran = zvezek['Sheet']\n stran.title = input('Vnesi ime lista: ')\n temp_naslovna_vrstica(stran)\n temp_dimenzioniraj_celico(stran)\n except:\n strani = zvezek.sheetnames\n stran = zvezek[strani[0]]\n stran.title = input('{} / podaj novo ime: '.format(strani[0]))\n temp_naslovna_vrstica(stran)\n temp_naslovna_vrstica(stran)\n temp_dimenzioniraj_celico(stran)\n\n\ndef func_uvozi_zvezek(mesto):\n global zvezek, strani, stran\n zvezek = openpyxl.load_workbook(mesto)\n strani = zvezek.sheetnames\n ime = input('Vnesi ime lista: ')\n if ime in strani:\n stran = zvezek.get_sheet_by_name(ime)\n else:\n zvezek.create_sheet(ime)\n stran = zvezek.get_sheet_by_name(ime)\n temp_naslovna_vrstica(stran)\n temp_dimenzioniraj_celico(stran)\n\n\ndef func_zamenjaj_list():\n global zvezek, strani, stran\n i = zvezek.get_index(zvezek.active)\n if i+1 < len(zvezek.sheetnames):\n strani = zvezek.sheetnames\n stran = zvezek[strani[i+1]]\n stran.title = input('{} / podaj novo ime: '.format(strani[i]))\n temp_naslovna_vrstica(stran)\n temp_dimenzioniraj_celico(stran)\n else:\n ime = input('vnesi ime novega lista: ')\n zvezek.create_sheet(ime)\n zvezek.active = -1\n stran = zvezek.active\n temp_naslovna_vrstica(stran)\n temp_dimenzioniraj_celico(stran)\n\n\ndef func_shrani_zvezek(mesto):\n global zvezek\n zvezek.save(mesto.split('/')[-1][:-3]+'_OPAL'+'.xlsx')\n# endregion USTVARI EXCEL\n\n\n# 3b. Iteriraj skozi različice\n# Za različico:\n# Pripravi podatke za vpis v excel\n# opis = podatki shranjeni kot niz\n# iteriraj skozi vrstice s prevodom:\n# dodaj k opisu ključ in pripadajočo vrednost\n# vpiši v excel\nopis_enote = ''\ndeklaracija = '\\nPROIZVAJALEC: Mitsubishi Electric Hydronics & IT Cooling Systems S.p.A., Japonska\\nUVOZNIK: REAM d.o.o., Trzin\\n'\ntehnicni_opis = 'TEHNIČNI PODATKI:\\n'\n\n\ndef func_opis_al(datoteka):\n global opis_enote\n opis_enote = 'VNESI OPIS {}\\n'.format(datoteka)\n\ndef func_opis(mesto, datoteka):\n global opis_enote\n with open(mesto) as dat_txt:\n dat = dat_txt.readlines()\n copy = False\n for vrstica in dat:\n if vrstica.split('_')[0].isdigit():\n copy = False\n opis_enote = opis_enote.strip('\\n')\n if vrstica[:-1] == datoteka:\n copy = True\n continue\n if copy:\n opis_enote += vrstica\n\n\ndef func_izjeme(eno, vel):\n if eno == 'V/ph/Hz':\n eno = ''\n if vel in {'230/1/50', '230/1+N/50'} :\n vel = '230V/ 1F/ 50Hz'\n elif vel in {'400/3/50', '400/3+N/50'}:\n vel = '400V/ 3F/ 50Hz'\n else:\n vel = 'preveri podatek'\n return eno, vel\n\n\n# Sestavi tehnični opis za enoto\n# TODO 11.4. : Popravi: Vnesi izjemo za električni priključek, presek inštalacijskih cevi\ndef func_sestavi_opis(enota):\n global tehnicni_opis, deklaracija, opis_enote\n tehnicni_opis = 'TEHNIČNI PODATKI:\\n'\n uporabljene = []\n for vrstica in datoteka_sez:\n naziv = vrstica[0]\n if naziv in prevod_slo.keys() and not naziv in uporabljene:\n uporabljene.append(naziv)\n velicina = datoteka_slo[(naziv, enota)]\n en = vrstica[1]\n en, velicina = func_izjeme(en, velicina)\n _ = [prevod_slo[naziv], velicina, en]\n tehnicni_opis += '{0}: {1} {2}\\n'.format(*_)\n return opis_enote + deklaracija + '\\n' + tehnicni_opis\n\n\ndef func_zapisi_v_zvezek(slika='', substativ=''):\n global stran\n for i, enota in enumerate(datoteka_sez[0][2:], 2):\n stran['A'+str(i)] = enota.replace(slika, substativ).replace(' ', '-')\n stran['B'+str(i)] = enota.replace(slika, substativ)\n stran['C'+str(i)] = 'CLIMAVENETA'\n stran['D'+str(i)] = func_sestavi_opis(enota)\n for c in stran['D']:\n c.alignment = openpyxl.styles.Alignment(wrap_text=True)\n\n","sub_path":"CLIMAVENETA/V1/funkcije.py","file_name":"funkcije.py","file_ext":"py","file_size_in_byte":9440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"296415535","text":"\"\"\"Notification Abstract.\"\"\"\n\n# Django\nfrom django.db import models\n\n# Models\nfrom omnilatam.apps.user.models import User \nfrom django.db.models.query import QuerySet\n\n# ContentType\nfrom django.contrib.contenttypes.fields import GenericForeignKey\nfrom django.contrib.contenttypes.models import ContentType \n\n# Utilities\nfrom django.utils import timezone\nfrom swapper import load_model\n\n# Signals\nfrom omnilatam.apps.notification.signals import notify\n\n\nLEVELS = (\n ('sent', 'Sent'),\n ('received', 'Received'),\n)\n\nclass NotificacionAbstract(models.Model):\n\t\"\"\"Notificacion Abstract\n\t\t\n\tNotificacionAbstract acts as an abstract base class from which every\n\tother model in the project will inherit.\n\n\tFormat:\n\t\t \n\n\t\tExample:\n\t\t <2 minutes ago>\n\n\t\"\"\"\n\n\tlevel = models.CharField(max_length=20, choices=LEVELS)\n\treceiver = models.ForeignKey(\n\t\tUser,\n\t\trelated_name='notification',\n\t\ton_delete=models.CASCADE,\n\t\tblank=True,\n\t\tnull=True\n\t)\n\tread = models.BooleanField(default=False, blank=False, db_index=True)\n\n\tactor_content_type = models.ForeignKey(ContentType, related_name='actor_notify', on_delete=models.CASCADE)\n\tactor_object_id = models.PositiveIntegerField()\n\tactor = GenericForeignKey(\"actor_content_type\", \"actor_object_id\")\n\n\tverb = models.CharField(max_length=225)\n\n\ttimestamp = models.DateTimeField(default=timezone.now, db_index=True)\n\n\n\tclass Meta:\n\t\tabstract = True\n\t\tordering = ('-timestamp',)\n\t\tindex_together = ('receiver', 'read')\n\n\tdef __str__(self):\n\t\tnotify = {\n\t\t\t'actor':self.actor,\n\t\t\t'verb': self.verb,\n\t\t\t'date': self.timesince()\n\t\t}\n\n\t\treturn u\"%(actor)s %(verb)s %(date)s\" % notify\n\n\tdef timesince(self, now=None):\n\t\t\"\"\"\n\t\tShortcut for the django.utils.timesince.timesince function \n\t\tof the current timestamp.\n\t\t\"\"\"\n\t\tfrom django.utils.timesince import timesince\n\t\treturn timesince(self.timestamp, now)\n\n\tdef mark_as_read(self):\n\t\t\"\"\"Mark read a notify.\"\"\"\n\t\tif self.read:\n\t\t\tself.read = True\n\t\t\tself.save()\n\n\tdef mark_as_unread(self):\n\t\t\"\"\"Mark unread a notify.\"\"\"\n\t\tif self.read:\n\t\t\tself.read = False\n\t\t\tself.save()\n\n\ndef notification(verb, **kwargs):\n\t\"\"\"Handler function to create Notification instance upon action signal call.\"\"\"\n\n\treceiver = kwargs.pop('receiver')\n\tprint(receiver)\n\tactor = kwargs.pop('actor')\n\tprint('Actor', actor)\n\tlevel = kwargs.pop('level', LEVELS)\n\ttimestamp = kwargs.pop('timestamp', timezone.now())\n\n\tNotify = load_model('notification', 'notificacion')\n\n\t# Check if User\n\tif isinstance(receiver, (QuerySet, list)):\n\t\treceivers = receiver\n\telse:\n\t\treceivers = [receiver]\n\n\tnotifyes = []\n\tfor receiver in receivers:\n\t\tnewnotify = Notify(\n\t\t\treceiver=receiver,\n\t\t\tactor_content_type=ContentType.objects.get_for_model(actor),\n\t\t\tactor_object_id=actor.pk,\n\t\t\tverb=str(verb),\n\t\t\ttimestamp=timestamp,\n\t\t\tlevel=level\n\t\t)\n\n\t\tnewnotify.save()\n\t\tnotifyes.append(newnotify)\n\n\treturn notifyes\n\nnotify.connect(notification, dispatch_uid='notification.models.notificacion')","sub_path":"apps/notification/utils/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"416502934","text":"# This document is part of Pydar\n# https://github.com/geowurster/Pydar\n\n\n# =================================================================================== #\n#\n# New BSD License\n#\n# Copyright (c) 2014, Kevin D. Wurster\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * The names of its contributors may not be used to endorse or promote products\n# derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n# =================================================================================== #\n\n\n\"\"\"\nCSV\n\"\"\"\n\n\nfrom __future__ import print_function\n\nimport struct\nfrom .. import core\n\n\n#/* ======================================================================= */#\n#/* Driver Attributes\n#/* ======================================================================= */#\n\nr = True\nw = True\nheader = True\nvlrs = True\npoints = True\nwaveform = False\nshortname = 'CSV'\nlongname = 'Delimited Text'\n\n\n#/* ======================================================================= */#\n#/* Define sniffer() function\n#/* ======================================================================= */#\n\ndef sniffer(infile, **kwargs):\n\n \"\"\"\n Determine whether or not input file is able to be read by\n this driver\n\n :param infile:\n :type infile: str\n\n :return: True if all tests pass, False otherwise\n :rtype: bool\n \"\"\"\n\n # Open the file to sniff out file type\n with open(infile, 'r') as f:\n pass\n\n\n return False\n\n\n#/* ======================================================================= */#\n#/* Define Read() class\n#/* ======================================================================= */#\n\nclass Read(object):\n\n def __init__(self, infile):\n\n \"\"\"\n Extract data from a\n\n :param infile: input ASPRS LAS file\n :type infile: str\n \"\"\"\n\n # File containers\n self.infile = infile\n self.header = core.Header()\n self.vlrs = core.VLRS()\n self.points = core.Records()\n self.waveform_packets = core.Waveform()\n\n # Additional information\n self.read_position = 0\n\n # Parse the header\n\n with open(self.infile, 'rb') as open_file:\n\n stream = open_file.read(235)\n\n self.header.file_signature = struct.unpack('4s', stream[:4])[0] # char[4] 4 bytes\n self.header.file_source_id = struct.unpack('H', stream[4:6])[0] # unsigned short 2 bytes\n self.header.global_encoding = struct.unpack('H', stream[6:8])[0] # unsigned short 2 bytes\n self.header.project_guid1 = struct.unpack('I', stream[8:12])[0] # unsigned long 4 bytes\n self.header.project_guid2 = struct.unpack('H', stream[12:14])[0] # unsigned short 2 byte\n self.header.project_guid3 = struct.unpack('H', stream[14:16])[0] # unsigned short 2 byte\n self.header.project_guid4 = struct.unpack('8B', stream[16:24])[0] # unsigned char[8] 8 bytes\n\n self.header.version_major = struct.unpack('B', stream[24:25])[0] # unsigned char 1 byte\n self.header.version_minor = struct.unpack('B', stream[25:26])[0] # unsigned char 1 byte\n\n self.header.system_identifier = struct.unpack('32s', stream[26:58])[0] # char[32] 32 bytes\n self.header.generating_software = struct.unpack('32s', stream[58:90])[0] # char[32] 32 bytes\n self.header.creation_day = struct.unpack('H', stream[90:92])[0] # unsigned short 2 bytes\n self.header.creation_year = struct.unpack('H', stream[92:94])[0] # unsigned short 2 bytes\n\n self.header.header_size = struct.unpack('H', stream[94:96])[0] # unsigned short 2 bytes\n self.header.offset_to_point_data = struct.unpack('I', stream[96:100])[0] # unsigned long 4 bytes\n self.header.num_vlrs = struct.unpack('I', stream[100:104])[0] # unsigned long 4 bytes\n\n self.header.point_data_format_id = struct.unpack('B', stream[104:105])[0] # unsigned char 1 byte\n self.header.point_data_record_length = struct.unpack('H', stream[105:107])[0] # unsigned short 2 bytes\n self.header.num_point_records = struct.unpack('I', stream[107:111])[0] # unsigned long 4 bytes\n self.header.num_points_by_return = list(struct.unpack('IIIII', stream[111:131])) # unsigned long[5] 20 bytes\n\n self.header.x_scale_factor = struct.unpack('d', stream[131:139])[0] # Double 8 bytes\n self.header.y_scale_factor = struct.unpack('d', stream[139:147])[0] # Double 8 bytes\n self.header.z_scale_factor = struct.unpack('d', stream[147:155])[0] # Double 8 bytes\n self.header.x_offset = struct.unpack('d', stream[155:163])[0] # Double 8 bytes\n self.header.y_offset = struct.unpack('d', stream[163:171])[0] # Double 8 bytes\n self.header.z_offset = struct.unpack('d', stream[171:179])[0] # Double 8 bytes\n\n self.header.max_x = struct.unpack('d', stream[179:187])[0] # Double 8 bytes\n self.header.min_x = struct.unpack('d', stream[187:195])[0] # Double 8 bytes\n self.header.max_y = struct.unpack('d', stream[195:203])[0] # Double 8 bytes\n self.header.min_y = struct.unpack('d', stream[203:211])[0] # Double 8 bytes\n self.header.max_z = struct.unpack('d', stream[211:219])[0] # Double 8 bytes\n self.header.min_z = struct.unpack('d', stream[219:227])[0] # Double 8 bytes\n self.header.start_waveform_packet_record = struct.unpack('d', stream[227:235])[0] # Double 8 bytes\n\n def reset_reading(self):\n\n \"\"\"\n Reset the reading position to 0\n\n :return: None\n :rtype: None\n \"\"\"\n\n self.read_position = 0\n\n return None\n\n def seek(self, position):\n\n \"\"\"\n Set the reading position to a certain point number\n\n :raises TypeError: if the input position is not an integer > 0\n :return: None\n :rtype: None\n \"\"\"\n\n if not isinstance(position, int):\n raise TypeError(\"ERROR: Invalid position - must be an int > 0: %s\" % position)\n\n self.read_position = position\n\n return None\n\n def get_header(self):\n\n \"\"\"\n Creates a header instance and populates with the appropriate values\n\n :return: an instance of the core.Header() class\n :rtype: \n \"\"\"\n\n\n\n self.header = h\n\n return self.header\n\n def get_vlrs(self):\n\n \"\"\"\n Extracts all VLR's from the loaded file\n\n :return: an instance of the core.VLRS() class with populated data\n :rtype: \n \"\"\"\n\n # VLRs\n vlr_len = 54\n if self.header is None:\n slice_min = 235\n else:\n slice_min = self.header.header_size\n slice_max = slice_min + vlr_len\n vlr_output = []\n with open(self.infile, 'rb') as open_file:\n\n stream = open_file.read()\n\n for i in range(self.header.num_vlrs):\n vlr_entry = {}\n vlr_entry['reserved'] = struct.unpack('H', stream[slice_min:slice_max])[0] # unsigned short 2 bytes\n slice_min += 2\n slice_max += 2\n vlr_entry['user_id'] = struct.unpack('16s', stream[slice_min:slice_max])[0] # char[16]\n slice_min += 16\n slice_max += 16\n vlr_entry['record_id'] = struct.unpack('H', stream[slice_min:slice_max])[0] # unsigned short 2 bytes\n slice_min += 2\n slice_max += 2\n vlr_entry['record_len_after_header'] = struct.unpack('H', stream[slice_min:slice_max])[0] # unsigned short 2 bytes\n slice_min += 2\n slice_max += 2\n vlr_entry['description'] = struct.unpack('32s', stream[slice_min:slice_max])[0] # char[32] 32 bytes\n slice_min += 32\n slice_max += 32\n vlr_output.append(vlr_entry)\n\n self.vlrs = vlr_output\n\n return self.vlrs\n\n def get_points(self):\n\n \"\"\"\n\n :return: core class instance\n :rtype: \n \"\"\"\n pass\n\n\n#/* ======================================================================= */#\n#/* Define Write() class\n#/* ======================================================================= */#\n\n\nclass Write(object):\n\n def __init__(self):\n pass\n","sub_path":"acronym/lidar/drivers/csv.py","file_name":"csv.py","file_ext":"py","file_size_in_byte":9727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"171220099","text":"import re\nimport json\nimport datetime\nfrom collections import Counter\n\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import render, render_to_response, get_object_or_404\nfrom django.http import HttpResponse, JsonResponse\n\nfrom django.views.generic import TemplateView, DetailView\nfrom django.template.response import TemplateResponse\n\nfrom django.db.models import Q\n\nfrom django.utils.html import mark_safe\n\n\nfrom leagion.models import User, Team, League, Match, Roster\n\n# views\nclass Index(TemplateView):\n template_name = \"index.html\"\n\n def get_context_data(self):\n context = {\"leagues\": []}\n for league in League.objects.all():\n league_ctx = {\n \"name\": league.name,\n \"teams\": [],\n \"detail_url\": reverse(\"league-detail\", args=(league.id,)),\n }\n matches = list(league.matches.all().values(\"id\", \"home_team_id\", \"away_team_id\"))\n\n for team in league.teams.all():\n team_ctx = {\n \"name\": team.name,\n \"players\": [],\n \"detail_url\": reverse(\"team-detail\", args=(team.id,)),\n \"matches_played\": len([m for m in matches if m['home_team_id'] == team.id or m['away_team_id'] == team.id]),\n }\n for player in team.players.all():\n player_ctx = {\n \"full_name\": \"{} {}\".format(player.first_name, player.last_name)\n }\n team_ctx[\"players\"].append(player_ctx)\n\n league_ctx[\"teams\"].append(team_ctx)\n\n context[\"leagues\"].append(league_ctx)\n\n\n return context\n\n\nclass LeagueDetail(DetailView):\n template_name = \"league_detail.html\"\n\n context_object_name = \"league\"\n pk_url_kwarg = \"league_id\"\n queryset = League.objects.all()\n\n def get_context_data(self, object):\n context = super(LeagueDetail, self).get_context_data()\n league = context['league']\n context['matches'] = [{\n 'location': match.location.name,\n 'home_team': match.home_team.name,\n 'home_points': match.home_points,\n 'away_team': match.away_team.name,\n 'away_points': match.away_points,\n 'match_datetime': match.match_datetime,\n 'match_detail_url': reverse(\"match-detail\", args=(match.id,)),\n } for match in league.matches.all().order_by(\"match_datetime\")]\n\n return context\n\n\nclass TeamDetail(DetailView):\n template_name = \"team_detail.html\"\n\n context_object_name = \"team\"\n pk_url_kwarg = \"team_id\"\n queryset = Team.objects.all()\n\n def get_context_data(self, object):\n context = super(TeamDetail, self).get_context_data()\n team = context['team']\n\n matches = team.league.matches.filter(\n Q(away_team=team)|Q(home_team=team)\n ).order_by(\"match_datetime\").select_related(\"location\")[:15]\n\n roster_player_ids = Roster.objects.filter(\n team=team\n ).values_list(\"players__id\", flat=True)\n matches_played = Counter(roster_player_ids) #fuck yeah python\n\n context['matches'] = [{\n 'location': match.location.name,\n 'match_datetime': match.match_datetime,\n 'match_detail_url': reverse(\"match-detail\", args=(match.id,)),\n\n 'home_team': match.home_team.name,\n 'home_points': match.home_points,\n 'away_team': match.away_team.name,\n 'away_points': match.away_points,\n\n 'is_home_win': match.is_home_win,\n 'is_away_win': match.is_away_win,\n\n 'is_draw': match.is_draw,\n 'team_won': match.get_winning_team() == team,\n 'status': match.get_status_for_team(team),\n } for match in matches]\n\n context['players'] = [{\n \"full_name\": \"{} {}\".format(player.first_name, player.last_name),\n \"detail_url\": reverse(\"player-detail\", args=(player.id,)),\n \"matches_played\": matches_played[player.id],\n } for player in team.players.all()]\n\n return context\n\n\nclass MatchDetail(DetailView):\n template_name = \"match_detail.html\"\n\n context_object_name = \"match\"\n pk_url_kwarg = \"match_id\"\n queryset = Match.objects.all()\n\n def build_match_context(self, match):\n \"\"\"\n can be the postponed match\n \"\"\"\n\n if match is None:\n return {}\n\n return {\n 'location': match.location.name,\n 'match_datetime': match.match_datetime,\n\n 'home_team': match.home_team.name,\n 'home_points': match.home_points,\n 'away_team': match.away_team.name,\n 'away_points': match.away_points,\n\n 'is_home_win': match.is_home_win,\n 'is_away_win': match.is_away_win,\n\n 'is_draw': match.is_draw,\n\n 'status': match.get_status_display(),\n 'postponed_match': self.build_match_context(match.postponed_to),\n }\n\n def get_context_data(self, object):\n context = super(MatchDetail, self).get_context_data()\n match = context['match']\n home_team = match.home_team\n away_team = match.away_team\n\n home_roster_player_ids = Roster.objects.filter(\n team=home_team\n ).values_list(\"players__id\", flat=True)\n home_matches_played = Counter(home_roster_player_ids)\n\n away_roster_player_ids = Roster.objects.filter(\n team=away_team\n ).values_list(\"players__id\", flat=True)\n away_matches_played = Counter(away_roster_player_ids)\n\n context['match'] = self.build_match_context(match)\n\n context['home_team'] = {\n 'roster': [{\n \"full_name\": \"{} {}\".format(player.first_name, player.last_name),\n \"matches_played\": home_matches_played[player.id],\n } for player in home_team.players.filter(id__in=match.rosters.get(team_id=home_team.id).players.values_list(\"id\", flat=True))\n ]\n }\n\n context['away_team'] = {\n 'roster': [{\n \"full_name\": \"{} {}\".format(player.first_name, player.last_name),\n \"matches_played\": away_matches_played[player.id],\n } for player in away_team.players.filter(id__in=match.rosters.get(team_id=away_team.id).players.values_list(\"id\", flat=True))\n ]\n }\n\n return context\n\n\nclass PlayerDetail(DetailView):\n template_name = \"player_detail.html\"\n\n context_object_name = \"player\"\n pk_url_kwarg = \"player_id\"\n queryset = User.objects.all()\n\n def get_context_data(self, object):\n player = object\n context = super(PlayerDetail, self).get_context_data()\n context[\"full_name\"] = \"{} {}\".format(player.first_name, player.last_name)\n\n teams = player.teams.all().select_related(\"league\")\n leagues = []\n for team in teams:\n if team.league not in leagues:\n leagues.append(team.league)\n\n leagues_ctx = [{\n \"name\": league.name,\n \"detail_url\": reverse(\"league-detail\", args=(league.id,))\n } for league in leagues]\n context['leagues'] = leagues_ctx\n\n teams_ctx = [{\n \"name\": team.name,\n \"detail_url\": reverse(\"team-detail\", args=(team.id,))\n } for team in teams]\n context['teams'] = teams_ctx\n\n return context\n","sub_path":"leagion/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"168712740","text":"\"\"\"Code initially taken from github.com/caogang/wgan-gp\"\"\"\n\nimport numpy as np\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nimport collections\nimport time\nimport pickle\n\n_since_beginning = collections.defaultdict(lambda: {})\n_since_last_flush = collections.defaultdict(lambda: {})\n\n_iter = [0]\ndef tick():#index incrementer\n _iter[0] += 1\n\ndef offset(val):#used when loading from checkpoint\n _iter[0] += val \n\ndef plot(name, value):#record data\n _since_last_flush[name][_iter[0]] = value\n\ndef flush(temp_save):#save and print recent averages of data\n prints = []\n \n for name, vals in _since_last_flush.items():\n prints.append(\"{:.{prec1}}\\t{:.{prec2}f}\".format(name, np.mean(list(vals.values())),prec1 = 5, prec2 = 3))\n _since_beginning[name].update(vals)\n\n print(\"iter {}\\t{}\".format(_iter[0], \"\\t\".join(prints)))\n _since_last_flush.clear()\n\n with open(temp_save + '/log.pkl', 'wb') as f:\n pickle.dump(dict(_since_beginning), f, pickle.HIGHEST_PROTOCOL)\n","sub_path":"log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"44213931","text":"# -*-coding:utf-8-*-\n\"\"\"\n@Time : 2019-02-22 10:33\n@Author : Mark\n@File : rnn_classifier_tf.py\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import OneHotEncoder\n\nTRAIN_DATA_PATH = '../data/train.csv'\nTEST_SIZE = 0.2\nBATCH_SIZE = 128\nN_STEP = 28\nN_INPUT = 28\nN_HIDDEN_UNITS = 64\nN_CLASSES = 10\nEPOCH = 100\nLR = 0.001\n\n\ndef batch_generator(X, y, batch_size):\n size = X.shape[0]\n X_copy = X.copy()\n y_copy = y.copy()\n indices = np.arange(size)\n np.random.shuffle(indices)\n X_copy = X_copy[indices]\n y_copy = y_copy[indices]\n\n idx = 0\n while True:\n if idx + batch_size <= size:\n yield X_copy[idx:idx + batch_size], y_copy[idx:idx + batch_size]\n idx += batch_size\n else:\n idx = 0\n indices = np.arange(size)\n np.random.shuffle(indices)\n X_copy = X_copy[indices]\n y_copy = y_copy[indices]\n continue\n\n\ndata = pd.read_csv(TRAIN_DATA_PATH)\n\nX = data.iloc[:, 1:data.shape[1]]\ny = data.iloc[:, 0]\n\ntrain_x_np, test_x_np, train_y_np, test_y_np = train_test_split(X.values, y.values, test_size=TEST_SIZE, shuffle=False)\ntrain_x = train_x_np.reshape(-1, N_STEP, N_INPUT)\ntrain_y = OneHotEncoder(sparse=False).fit_transform(train_y_np.reshape(-1, 1))\ntest_x = test_x_np.reshape(-1, N_STEP, N_INPUT)\ntest_y = OneHotEncoder(sparse=False).fit_transform(test_y_np.reshape(-1, 1))\n\nX = tf.placeholder(tf.float32, shape=[None, N_STEP, N_INPUT])\ny = tf.placeholder(tf.int32, shape=[None, N_CLASSES])\n\nrnn_fw = tf.contrib.rnn.LSTMCell(num_units=N_HIDDEN_UNITS)\nrnn_bw = tf.contrib.rnn.LSTMCell(num_units=N_HIDDEN_UNITS)\n\n# outputs : [64,28,64] * 2\noutputs, states = tf.nn.bidirectional_dynamic_rnn(cell_fw=rnn_fw, cell_bw=rnn_bw,\n inputs=X, dtype=tf.float32)\noutput = tf.concat([outputs[0], outputs[1]], axis=2)[:, -1, :]\npredict_y = tf.contrib.layers.fully_connected(inputs=output, num_outputs=N_CLASSES, activation_fn=None)\nloss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=predict_y))\ntrain_step = tf.train.AdamOptimizer(learning_rate=LR).minimize(loss)\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for epoch in range(EPOCH):\n for step in range(int(train_y_np.shape[0] / BATCH_SIZE)):\n data_generator = batch_generator(train_x, train_y, batch_size=BATCH_SIZE)\n b_x, b_y = next(data_generator)\n train_step.run(feed_dict={X: b_x, y: b_y})\n\n if step % 100 == 0:\n loss_value = sess.run(fetches=loss, feed_dict={X: train_x, y: train_y})\n\n predict = sess.run(predict_y, feed_dict={X: test_x, y: test_y})\n accuracy = (np.argmax(predict, axis=1) == np.argmax(test_y, axis=1)).sum() / predict.shape[0]\n\n print('EPOCH : {0} | STEP : {1} | LOSS : {2} | ACCURACY : {3}'.format(str(epoch),\n str(step),\n str(loss_value),\n str(accuracy)))\n print(np.argmax(predict[0:9, :], axis=1))\n print(np.argmax(test_y[0:9, :], axis=1))\n","sub_path":"digit_recognizer/mark/rnn_classifier_tf.py","file_name":"rnn_classifier_tf.py","file_ext":"py","file_size_in_byte":3431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"638601877","text":"# Enter your code here. Read input from STDIN. Print output to STDOUT\n# N will be the number of queries\nN = int(input())\n# l will be the list\nl =[]\n# Operations of the individual queries\nfor i in range(0,N):\n # Reading of the queries user\n l1= list(map(int,input().split()))\n # If queue is the \"1\" enqueue element x into the end of the queue.\n if l1[0]==1:\n l.append(l1[1])\n # If queue is the \"2\" dequeue element x into the front of the queue.\n elif l1[0]==2:\n l.pop(0)\n # If queue is the \"3\" print the element at the front of the queue\n else:\n print(l[0])\n \n","sub_path":"queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"253425978","text":"import json\nimport os\nimport shutil\nimport urllib\n\nimport requests\n\n\nclass API(object):\n\n def __init__(self, token):\n \"\"\"\n :param token: bot token, get it from BotFather\n \"\"\"\n self.token = token\n\n self.telegram_url = 'https://api.telegram.org/'\n self.bot_url = '/bot{}/'.format(token)\n\n self.url = urllib.parse.urljoin(self.telegram_url, self.bot_url)\n\n self.last_update_id = None # to check if is new message\n\n def get_updates(self):\n \"\"\"\n get update from telegram\n :return:\n \"\"\"\n url = urllib.parse.urljoin(self.url, 'getUpdates')\n return self.get_json(url)\n\n def get_last_update(self, updates):\n \"\"\"\n :param updates:\n :return: last update\n \"\"\"\n return updates['result'][-1]\n\n def is_new_update(self, updates):\n \"\"\"\n check if there is\n a new update\n :param updates:\n :return:\n \"\"\"\n if len(updates['result']) == 0:\n return False\n result = self.get_last_update(updates)\n update_id = result['update_id']\n\n if update_id != self.last_update_id:\n self.last_update_id = update_id\n return True\n else:\n return False\n\n def get_id_name_content_date(self, updates, content_type):\n \"\"\"\n get info from update\n :param updates:\n :param content_type: text, photo, ecc\n :return:\n \"\"\"\n result = self.get_last_update(updates)\n message = result['message']\n chat = message['chat']\n chat_id = chat['id']\n first_name = chat['first_name']\n content = message[content_type]\n date = message['date']\n return chat_id, first_name, content, date\n\n def send_file(self, chat_id, content_type, path):\n \"\"\"\n :param chat_id: id of the chat\n :param content_type: 'photo', 'voice', ... view api\n :param path: path of the file\n :return:\n \"\"\"\n data = {'chat_id': chat_id}\n file = {content_type: (path, open(path, \"rb\"))}\n url = urllib.parse.urljoin(self.url, 'send{}'.format(content_type.title()))\n response = requests.post(url, data=data, files=file)\n return response\n\n def send_message(self, chat_id, text):\n \"\"\"\n send a message to specific user\n :param chat_id: id of the chat\n :param text: message to send\n :return:\n \"\"\"\n data = {'chat_id': chat_id,\n 'text': text}\n url = urllib.parse.urljoin(self.url, 'sendMessage')\n response = requests.post(url, data=data)\n return response\n\n def download_file(self, file_id, path, name=None):\n \"\"\"\n download files\n more general function\n :param file_id: id of file\n :param path: dir to save file\n :param name: name of the file with extension\n :return: file path\n \"\"\"\n url = urllib.parse.urljoin(self.url, 'getFile?file_id={}'.format(file_id))\n js = self.get_json(url)\n path_file = js['result']['file_path']\n url = self.telegram_url + 'file' + self.bot_url\n url = urllib.parse.urljoin(url, path_file)\n response = requests.get(url, stream=True)\n\n path_file = path_file.split('/')[-1]\n\n # rename file\n if name != None:\n path_file = name\n\n path_file = os.path.join(path, path_file)\n\n with open(path_file, 'wb') as out_file:\n shutil.copyfileobj(response.raw, out_file)\n return path_file\n\n def get_type_of_response(self, updates):\n \"\"\"\n check type of update\n :param updates:\n :return:\n \"\"\"\n result = self.get_last_update(updates)\n message_type = list(result['message'].keys())[4]\n\n return message_type\n\n def get_json(self, url):\n \"\"\"\n get json from telegram server\n :param url: url\n :return:\n \"\"\"\n response = requests.post(url)\n content = response.content.decode('utf8')\n return json.loads(content)\n","sub_path":"telegram_essential/API.py","file_name":"API.py","file_ext":"py","file_size_in_byte":4150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"5021933","text":"from typing import List\n\nimport torch\nimport torch.nn as nn\n\nfrom utils import WordVocab, get_crf_constraint\nfrom .bert import BERT\nfrom .crf import CRF\n\n\nclass BiLSTM(nn.Module):\n def __init__(self, input_features, hidden_features, device='cpu'):\n super(BiLSTM, self).__init__()\n self.device = device\n self.hidden_dim = hidden_features\n self.lstm = nn.LSTM(input_features, hidden_features // 2,\n num_layers=1, bidirectional=True)\n self.to(device)\n\n def forward(self, sentence, length):\n \"\"\"\n Generate features with bidirectional LSTM.\n\n :param sentence: Input sentences as a batch. Tensor with shape (batch_size, seq_length, embedding_size).\n :param length: The length of sentences batch. Tensor with shape (batch_size).\n :return: Tensor for CRF input. Tensor with shape (seq_length, batch_size, hidden_size).\n \"\"\"\n max_length = torch.max(length)\n\n # Truncate the input for better performance.\n embeds = sentence[:, :max_length, :]\n hidden = self.init_hidden(length.size(0))\n embeds = nn.utils.rnn.pack_padded_sequence(embeds, length, batch_first=True)\n lstm_out, _ = self.lstm(embeds, hidden)\n del embeds, hidden\n lstm_out, _ = nn.utils.rnn.pad_packed_sequence(lstm_out)\n return lstm_out\n\n def init_hidden(self, batch_size):\n return (torch.randn(2, batch_size, self.hidden_dim // 2, device=self.device),\n torch.randn(2, batch_size, self.hidden_dim // 2, device=self.device))\n\n\nclass BiLSTM_CRF(nn.Module):\n def __init__(self, vocab_size, tags, embedding_dim, hidden_dim, n_layers=3, attn_heads=4, device='cpu'):\n \"\"\"\n Bidirectional LSTM with CRF layer on top.\n\n :type vocab_size: int\n :type tags: WordVocab\n :type embedding_dim: int\n :type hidden_dim: int\n\n :param vocab_size: Size of vocabulary.\n :param tags: Size of labels.\n :param embedding_dim: Dimension of embedding.\n :param hidden_dim: Dimension of hidden state.\n :param device: Device.\n \"\"\"\n super(BiLSTM_CRF, self).__init__()\n self.device = device\n self.encoder = BERT(vocab_size, hidden=embedding_dim, n_layers=n_layers, attn_heads=attn_heads)\n for p in self.parameters():\n p.requires_grad = False\n self.lstm = BiLSTM(embedding_dim, hidden_dim, device)\n\n # Maps the output of the LSTM into tag space.\n tag_size = len(tags)\n self.hidden2tag = nn.Linear(hidden_dim, tag_size)\n start_tags, constraints = get_crf_constraint(tags)\n self.crf = CRF(tag_size, constraints=constraints, start_tags=start_tags, device=device)\n self.to(device)\n\n def neg_log_likelihood(self, sentence, tags, length):\n \"\"\"\n Compute the negative log likelihood.\n\n :type sentence: torch.Tensor\n :type tags: torch.Tensor\n :type length: torch.Tensor\n :rtype: torch.Tensor\n :param sentence: Input sentences as a batch. Tensor with shape (batch_size, seq_length).\n :param tags: True labels. Tensor with shape (batch_size, seq_length).\n :param length: The length of sentences batch. Tensor with shape (batch_size).\n :return: Negative log likelihood\n \"\"\"\n max_length = torch.max(length)\n\n # Truncate the input for better performance.\n sentence = sentence[:, :max_length]\n tags = tags[:, :max_length]\n feats = self.lstm(self.encoder(sentence), length)\n feats = self.hidden2tag(feats)\n mask = torch.ones(length.size(0), max_length.item(), dtype=torch.uint8, device=self.device)\n mask[sentence[:max_length, :] == 0] = 0\n return -self.crf(feats, tags.transpose(0, 1), mask.transpose(0, 1))\n\n def forward(self, sentence, length):\n \"\"\"\n Predict the input sentence.\n\n :type sentence: torch.Tensor\n :type length: torch.Tensor\n :rtype: List[List[int]]\n :param sentence: Input sentences as a batch. Tensor with shape (batch_size, seq_length).\n :param length: The length of sentences batch. Tensor with shape (batch_size).\n :return: Predicted tags.\n \"\"\"\n # Get the emission scores from the BiLSTM\n embedding = self.encoder(sentence)\n lstm_feats = self.lstm(embedding, length)\n crf_input = self.hidden2tag(lstm_feats)\n\n # Find the best path, given the features.\n tag_seq = self.crf.decode(crf_input)\n return tag_seq\n","sub_path":"src/model/bilstm_crf.py","file_name":"bilstm_crf.py","file_ext":"py","file_size_in_byte":4560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"230938586","text":"import torch\nimport matplotlib.pyplot as plt\n\n\ndef calculate_accuracy(predictions, labels):\n\t\"\"\"Calculates the average accuracy \n\n\t\tArgs:\n\t\t\tpredictions (torch.Tensor): The predicted label values.\n\t\t\tlabels (torch.Tensor): The true label values.\n\n\t\tReturns:\n\t\t\taccuracy (float): The average accuracy for the given predicted and true labels.\n\t\"\"\"\n\n\t# Round the predictions\n\tpredicted_labels = torch.round(torch.sigmoid(predictions))\n\n\t# Compute the average accuracy\n\taccuracy = (predicted_labels == labels).sum() / len(labels)\n\n\treturn accuracy\n\t\n\ndef create_plots(train_set_loss, train_set_acc, val_set_loss, val_set_acc, test_set_loss, test_set_acc):\n\t\"\"\"Creates the plots for losses and accuracy for the train, validation, and test set.\n\t\t\n\t\tArgs:\n\t\t\ttrain_set_loss (List[float]): The loss for the training set\n\t\t\ttrain_set_acc (List[float]): The accuracy for the training set\n\t\t\tval_set_loss (List[float]): The loss for the validation set\n\t\t\tval_set_acc (List[float]): The accuracy for the validation set\n\t\t\ttest_set_loss (List[float]): The loss for the testing set\n\t\t\ttest_set_loss (List[float]): The accuracy for the testing set\n\t\"\"\"\n\n\tepochs = range(len(train_set_loss))\n\tplt.plot(epochs, train_set_loss, 'g', label=\"Training loss\")\n\tplt.plot(epochs, val_set_loss, 'b', label=\"Validation loss\")\n\tplt.plot(epochs, test_set_loss, 'r', label=\"Test loss\")\n\tplt.title(\"Train, Test and Validation Loss\")\n\tplt.xlabel(\"Epochs\")\n\tplt.ylabel(\"Loss\")\n\tplt.legend()\n\tplt.show()\n\n\tepochs = range(len(train_set_loss))\n\tplt.plot(epochs, train_set_acc, 'g', label=\"Training Accuracy\")\n\tplt.plot(epochs, val_set_acc, 'b', label=\"Validation Accuracy\")\n\tplt.plot(epochs, test_set_acc, 'r', label=\"Test Accuracy\")\n\tplt.title(\"Train, Test and Validation Accuracy\")\n\tplt.xlabel(\"Epochs\")\n\tplt.ylabel(\"Accuracy\")\n\tplt.legend()\n\tplt.show()\n","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"51051094","text":"def findNthDigit(n):\r\n if n <= 0:\r\n return False\r\n pos=0\r\n while n>pos*pow(10,pos)-(pow(10,pos)-1)/9:\r\n pos+=1\r\n newPos=pos-1\r\n nums,res=divmod((n-newPos*pow(10,newPos)+(pow(10,newPos)-1)/9),pos)\r\n if int(res)==0:\r\n targetNum=pow(10,newPos)-1+int(nums)\r\n # print(targetNum)\r\n finList=[int(i) for i in str(targetNum)]\r\n # print(finList)\r\n return finList[-1]\r\n else:\r\n targetNum=pow(10,newPos)+int(nums)\r\n # print(targetNum)\r\n finList=[int(i) for i in str(targetNum)]\r\n # print(finList)\r\n return finList[int(res)-1]\r\nprint(findNthDigit(2000))\r\n\r\n\r\ndef findNthDigit(self, n):\r\n n -= 1\r\n for digits in range(1, 11):\r\n first = 10**(digits - 1)\r\n if n < 9 * first * digits:\r\n return int(str(first + n/digits)[n%digits])\r\n n -= 9 * first * digits","sub_path":"400nDigit.py","file_name":"400nDigit.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"255371902","text":"# this py looking for lonely planlet to get a list of travel places all around the world\n# and put it inside a database table\n\n\nimport sqlite3\nimport urllib.request, urllib.parse, urllib.error\nfrom bs4 import BeautifulSoup\nimport ssl\nimport WordFilter\n\n\ndef wordcounter(_contain):\n _contain = _contain.split()\n _dict = dict()\n for _word in _contain:\n _dict[_word] = _dict.get(_word, 0) + 1\n return _dict\n\nconn = sqlite3.connect('Destinations.sqlite')\ncur = conn.cursor()\n\n#create table for storing keywords if not already exist\ncur.executescript('''\n\n CREATE TABLE IF NOT EXISTS Scratches (\n keyword TEXT NOT NULL,\n count INTEGER NOT NULL,\n destination TEXT NOT NULL,\n PRIMARY KEY ( keyword, destination )\n );\n\n ''')\n\n# Make some fresh tables using executescript()\ncur.execute('''\nSELECT count(*) from Destinations\n''')\ntotal_dest = cur.fetchone()[0]\nprint( \"Number of destinations\", total_dest)\n\n\n#ignore ssl cert errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\ncontinue_scratch = True\n#find the smallest id in the table to start scratching\ncur.execute('''SELECT min(id) from Destinations''')\nid_iter = cur.fetchone()[0]\nprint(\"The first id is:\", id_iter)\n\ndest_name = ''\n\nwhile continue_scratch:\n\n print('Start new destination scratch:', id_iter)\n # select a destination according to index from the table\n cur.execute('''\n SELECT name from Destinations\n where id = ?\n ''', (id_iter,))\n\n dest_list = cur.fetchall()\n #fetchall is returning a list of tuple, so even if there is one row one col only, i have to use [0][0] to get the thing\n\n # make sure id_iter exist in the table, if not, then move for the next one\n if len(dest_list) == 0 :\n print(\"SKIPPED ID_ITER \", id_iter)\n\n # add 1 to avoid dead loop\n id_iter += 1\n continue\n\n dest_name = str(dest_list[0][0])\n print( \"Destination\", dest_name, ' with id:', id_iter)\n\n url = 'https://google.com/search?q=' + urllib.parse.quote(dest_name)\n print(\"URL:\", url)\n\n header = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'}\n\n try:\n req = urllib.request.Request(url=url, headers=header)\n\n except OSError as err:\n print(err.reason)\n pass\n\n print(\"Please Wait.. it will take some time\")\n handle = urllib.request.urlopen(req, context=ctx)\n\n html = handle.read()\n\n soup = BeautifulSoup(html, 'html.parser')\n\n tags = soup.findAll('div', attrs={'class':'rc'})\n\n #scratch all the links from the google search,\n # should be 10 results per page, we just grab the first page\n # the url can be find inside
< div class=\"r\" >\n page_count = 0\n\n for tag in tags:\n tag.find('div', attrs={'class':'r'}).find('a').get('href').strip()\n url_dest = tag.find('div', attrs={'class':'r'}).find('a').get('href').strip()\n print(\"Scratching:\", url_dest)\n\n #get the content of this link\n try:\n req_dest = urllib.request.Request(url=url_dest, headers=header)\n\n except OSError as err:\n print(err.reason)\n continue\n\n try:\n handle_dest = urllib.request.urlopen(req_dest, context=ctx)\n\n except urllib.HTTPError as er:\n print(er.reason)\n continue\n\n html_dest = handle_dest.read()\n\n # print(\"html content:\", html)\n\n soup_dest = BeautifulSoup(html_dest, 'html.parser')\n\n\n output = \"\"\n text = soup_dest.find_all(text=True)\n\n\n blacklist = [\n '[document]',\n 'noscript',\n 'header',\n 'html',\n 'meta',\n 'head',\n 'input',\n 'script',\n # there may be more elements you don't want, such as \"style\", etc.\n ]\n\n for t in text:\n if t.parent.name not in blacklist:\n output += \"{} \".format(t.strip())\n\n\n result = wordcounter(output)\n\n # for every pair in the result, put it inside the TABLE\n\n for scratch_key in result:\n if WordFilter.CommonButUseless(scratch_key) is True:\n continue\n\n cur.execute('''SELECT count(*) from Scratches WHERE keyword = ? AND destination = ? ''', (scratch_key,dest_name) )\n\n if cur.fetchone()[0] == 0:\n cur.execute('''INSERT INTO Scratches (keyword, count, destination) VALUES ( ?, ?, ? )''', (scratch_key, result[scratch_key], dest_name))\n else:\n\n cur.execute('''SELECT count FROM Scratches WHERE destination = ? AND keyword = ?''', (dest_name, scratch_key))\n old_count = cur.fetchone()[0]\n cur.execute('''UPDATE Scratches SET count = ? WHERE keyword = ? AND destination = ?''', (result[scratch_key]+ old_count, scratch_key, dest_name) )\n\n page_count += 1\n\n #save to the DB\n conn.commit()\n\n print(\"finished one page, go for another...\")\n\n # userinput = input(\"Continue... y/n\")\n # if userinput == 'n':\n # continue_scratch = False\n # print('GOOD BYE')\n # else:\n # # move the index by 1\n # id_iter += 1\n # continue_scratch = True\n\n id_iter += 1\n continue_scratch = True\n\n\n","sub_path":"google_fromcountry.py","file_name":"google_fromcountry.py","file_ext":"py","file_size_in_byte":5375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"460272450","text":"from accounts.models import User\nfrom accounts.serializers import LoginSerializer, RegisterSerializer, UserSerializer\nfrom knox.models import AuthToken\nfrom rest_framework import generics, permissions\nfrom rest_framework.response import Response\n\n\nclass LoginAPI(generics.GenericAPIView):\n\n\t#View for login of the user.\n\n\t# Respective serializer\n\tserializer_class = LoginSerializer\n\n\tdef post(self, request, *args, **kwargs):\n\n\t\t#POST method\n\n\t\t# Validation of login\n\t\tserializer = self.get_serializer(data=request.data)\n\t\tserializer.is_valid(raise_exception=True)\n\t\tuser = serializer.validated_data\n\n\t\t# Return response with user and token\n\t\treturn Response({\n\t\t\t'user': UserSerializer(user).data,\n\t\t\t'token': AuthToken.objects.create(user)[1]\n\t\t})\n\n\nclass RegisterAPI(generics.GenericAPIView):\n\n\t#View for register a new user.\n\n\n\t# Respective serializer\n\tserializer_class = RegisterSerializer\n\n\tdef post(self, request, *args, **kwargs):\n\n\t\t#POST method\n\n\t\t# Register a new user \n\t\tprint(request.data)\n\t\tserializer = self.get_serializer(data=request.data)\n\t\tserializer.is_valid(raise_exception=True)\n\t\tuser = serializer.save()\n\n\n\t\t# Return response with user and token\n\t\treturn Response({\n\t\t\t'user': UserSerializer(user).data,\n\t\t\t'token': AuthToken.objects.create(user)[1]\n\t\t})\n\n\nclass UserAPI(generics.RetrieveAPIView):\n\n\t#View for user.\n\n\t#Authentication \n\tpermission_classes = [\n\t\tpermissions.IsAuthenticated\n\t]\n\t# Respective serializer\n\tserializer_class = UserSerializer\n\t\n\tdef get_object(self):\n\t\tself.request.user","sub_path":"QuizzBizz/accounts/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"196966609","text":"from django.urls import path\n\nfrom firstapp import views\n\nurlpatterns = {\n path(\"books/\",views.BookAPIView.as_view()),\n path(\"books//\",views.BookAPIView.as_view()),\n path(\"books1/\",views.BookGenericAPIView.as_view()),\n path(\"books1//\",views.BookGenericAPIView.as_view()),\n path(\"books2\",views.BookGenericViewSet.as_view({'get':'my_list','post':'my_create'})),\n path(\"books2//\",views.BookGenericViewSet.as_view({'get':'my_obj','post':'my_destroy'})),\n}","sub_path":"firstapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"380569847","text":"# -*- coding:utf-8 -*-\n# Author : ebbyzhang\n\nimport orm_m2m\nfrom sqlalchemy.orm import sessionmaker\n\nSession_class = sessionmaker(bind=orm_m2m.engine)\nsession = Session_class()\n#\n# b1 = orm_m2m.Book(name='learn python',pub_date='2014-5-02')\n# b2 = orm_m2m.Book(name='learn S',pub_date='2015-5-02')\n# b3 = orm_m2m.Book(name='learn h',pub_date='2016-5-02')\n#\n# a1 = orm_m2m.Author(name='prsuzy')\n# a2 = orm_m2m.Author(name='ebby')\n# a3 = orm_m2m.Author(name='stone')\n#\n# b1.authors = [a1,a3]\n# b3.authors = [a1,a2,a3]\n#\n# session.add_all([b1,b2,b3,a1,a2,a3])\nauthor_obj = session.query(orm_m2m.Author).filter(orm_m2m.Author.name=='prsuzy').first()\nprint(author_obj.books)\nbook_obj = session.query(orm_m2m.Book).filter(orm_m2m.Book.id==1).first()\nprint(book_obj.authors)\nsession.commit()","sub_path":"day12/orm_m2m_api.py","file_name":"orm_m2m_api.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"1423126","text":"\"\"\"empty message\n\nRevision ID: 584cd69775df\nRevises: 3f18fa8140c8\nCreate Date: 2015-01-04 01:47:51.452647\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '584cd69775df'\ndown_revision = '3f18fa8140c8'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('notice',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('title', sa.String(length=128), nullable=True),\n sa.Column('contents', sa.Text(), nullable=True),\n sa.Column('date_created', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('notice')\n ### end Alembic commands ###\n","sub_path":"migrations/versions/584cd69775df_.py","file_name":"584cd69775df_.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"194763334","text":"# 백준 2630 색종이 만들기\n\ndef check_blue(table, n, x, y):\n\tfor i in range(x, x+n):\n\t\tfor j in range(y, y+n):\n\t\t\tif table[i][j] == 0:\n\t\t\t\treturn False\n\treturn True\n\n\ndef check_white(table, n, x, y):\n\tfor i in range(x, x+n):\n\t\tfor j in range(y, y+n):\n\t\t\tif table[i][j] == 1:\n\t\t\t\treturn False\n\treturn True\n\ndef half(table, n, x, y):\n\tif check_blue(table, n, x, y): # 파란 종이인 경우\n\t\treturn [0, 1]\n\tif check_white(table, n, x, y):\n\t\treturn [1, 0]\n\tn = n//2\n\ttotal = [0, 0]\n\tbox1 = half(table, n, x, y)\n\tbox2 = half(table, n, x + n, y)\n\tbox3 = half(table, n, x, y + n)\n\tbox4 = half(table, n, x + n, y + n)\n\ttotal[0] = box1[0] + box2[0] + box3[0] + box4[0]\n\ttotal[1] = box1[1] + box2[1] + box3[1] + box4[1]\n\treturn total\n\n# 입력\nn = int(input())\ntable = []\nfor i in range(n):\n\ttable.append(list(map(int, input().split())))\n\n#실행\nresult = half(table, n, 0, 0)\n\nprint(result[0])\nprint(result[1])\n","sub_path":"baekjoon_python/2630.py","file_name":"2630.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"582437210","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport os\nfrom glob import glob\nimport re\nimport logging\nimport shutil\nimport time\nimport gzip\nfrom astropy.table import Table\nimport astropy.io.fits as pyfits\nimport numpy as np\nimport numpy.ma as ma\nimport argparse\nimport collections\nimport tables\nfrom itertools import count\nfrom pathlib import Path\n\nimport Ska.DBI\nimport Ska.arc5gl\nfrom Chandra.Time import DateTime\nimport Ska.File\nfrom chandra_aca.aca_image import ACAImage\n# import kadi later in obsid_times\n\nfrom mica.common import MICA_ARCHIVE, MissingDataError\n\nlogger = logging.getLogger('aca0 fetch')\nlogger.setLevel(logging.INFO)\nlogger.addHandler(logging.StreamHandler())\n\n# borrowed from eng_archive\nARCHFILES_HDR_COLS = ('tstart', 'tstop', 'startmjf', 'startmnf',\n 'stopmjf', 'stopmnf',\n 'tlmver', 'ascdsver', 'revision', 'date',\n 'imgsize')\n\nFILETYPE = {'level': 'L0',\n 'instrum': 'PCAD',\n 'content': 'ACADATA',\n 'arc5gl_query': 'ACA0',\n 'fileglob': 'aca*fits*'}\n\nACA_DTYPE = (('TIME', '>f8'), ('QUALITY', '>i4'), ('MJF', '>i4'),\n ('MNF', '>i4'),\n ('END_INTEG_TIME', '>f8'), ('INTEG', '>f4'), ('GLBSTAT', '|u1'),\n ('COMMCNT', '|u1'), ('COMMPROG', '|u1'), ('IMGFID1', '|u1'),\n ('IMGNUM1', '|u1'), ('IMGFUNC1', '|u1'), ('IMGSTAT', '|u1'),\n ('IMGROW0', '>i2'), ('IMGCOL0', '>i2'), ('IMGSCALE', '>i2'),\n ('BGDAVG', '>i2'), ('IMGFID2', '|u1'), ('IMGNUM2', '|u1'),\n ('IMGFUNC2', '|u1'), ('BGDRMS', '>i2'), ('TEMPCCD', '>f4'),\n ('TEMPHOUS', '>f4'), ('TEMPPRIM', '>f4'), ('TEMPSEC', '>f4'),\n ('BGDSTAT', '|u1'), ('IMGFID3', '|u1'), ('IMGNUM3', '|u1'),\n ('IMGFUNC3', '|u1'), ('IMGFID4', '|u1'), ('IMGNUM4', '|u1'),\n ('IMGFUNC4', '|u1'), ('IMGRAW', '>f4', (64,)),\n ('HD3TLM62', '|u1'),\n ('HD3TLM63', '|u1'), ('HD3TLM64', '|u1'), ('HD3TLM65', '|u1'),\n ('HD3TLM66', '|u1'), ('HD3TLM67', '|u1'), ('HD3TLM72', '|u1'),\n ('HD3TLM73', '|u1'), ('HD3TLM74', '|u1'), ('HD3TLM75', '|u1'),\n ('HD3TLM76', '|u1'), ('HD3TLM77', '|u1'),\n ('IMGSIZE', '>i4'), ('FILENAME', '>> from mica.archive import aca_l0\n >>> slot_data = aca_l0.get_slot_data('2012:001', '2012:002', slot=7)\n >>> temp_ccd_8x8 = aca_l0.get_slot_data('2005:001', '2005:010',\n ... slot=6, imgsize=[8],\n ... columns=['TIME', 'TEMPCCD'])\n\n :param start: start time of requested interval\n :param stop: stop time of requested interval\n :param slot: slot number integer (in the range 0 -> 7)\n :param imgsize: list of integers of desired image sizes\n (defaults to all -> [4, 6, 8])\n :param db: handle to archive lookup table\n :param data_root: parent directory that contains archfiles.db3\n (for use when db handle not available)\n :param columns: list of desired columns in the ACA0 telemetry\n (defaults to all in 8x8 telemetry)\n :param centered_8x8: boolean flag to reshape the IMGRAW field to (-1, 8, 8)\n (defaults to False)\n :returns: data structure for slot\n :rtype: numpy masked recarray\n \"\"\"\n if data_root is None:\n data_root = CONFIG['data_root']\n if columns is None:\n columns = ACA_DTYPE_NAMES\n if imgsize is None:\n imgsize = [4, 6, 8]\n if db is None:\n dbfile = os.path.join(data_root, 'archfiles.db3')\n db = dict(dbi='sqlite', server=dbfile)\n\n data_files = _get_file_records(start, stop, slots=[slot],\n imgsize=imgsize, db=db,\n data_root=data_root)\n aca_dtype = ACA_DTYPE_8x8 if centered_8x8 else ACA_DTYPE\n dtype = [k for k in aca_dtype if k[0] in columns]\n\n if not len(data_files):\n # return an empty masked array\n return ma.zeros(0, dtype=dtype)\n rows = np.sum(data_files['rows'])\n zero_row = ma.zeros(1, dtype=dtype)\n zero_row.mask = ma.masked\n all_rows = zero_row.repeat(rows)\n rowcount = 0\n for f in data_files:\n fp = os.path.join(data_root,\n str(f['year']),\n \"{0:03d}\".format(f['doy']),\n f['filename'])\n hdu = pyfits.open(fp)\n chunk = hdu[1].data\n idx0, idx1 = rowcount, (rowcount + len(chunk))\n f_imgsize = int(np.sqrt(chunk[0]['IMGRAW'].size))\n for fname in all_rows.dtype.names:\n if fname == 'IMGRAW' or fname == 'IMGSIZE':\n continue\n if fname in chunk.dtype.names:\n all_rows[fname][idx0: idx1] \\\n = chunk[fname]\n if 'IMGSIZE' in columns:\n all_rows['IMGSIZE'][idx0: idx1] = f_imgsize\n if 'FILENAME' in columns:\n all_rows['FILENAME'][idx0: idx1] = f['filename']\n if 'IMGRAW' in columns:\n if centered_8x8:\n if f_imgsize == 8:\n all_rows['IMGRAW'][idx0: idx1] = chunk['IMGRAW']\n else:\n i = (8 - f_imgsize) // 2\n all_rows['IMGRAW'][idx0: idx1, i:-i, i:-i] = \\\n chunk['IMGRAW']\n else:\n all_rows['IMGRAW'].reshape(rows, 8, 8)[\n idx0: idx1, 0:f_imgsize, 0:f_imgsize] = (\n chunk['IMGRAW'].reshape(len(chunk),\n f_imgsize, f_imgsize))\n rowcount += len(chunk)\n\n # just include the rows in the requested time range in the returned data\n oktime = ((all_rows['TIME'] >= DateTime(start).secs)\n & (all_rows['TIME'] <= DateTime(stop).secs))\n return all_rows[oktime]\n\n\ndef get_l0_images(start, stop, slot, imgsize=None, columns=None):\n \"\"\"\n Get ACA L0 images for the given ``start`` and ``stop`` times and\n the given ``slot``. Optionally filter on image size via ``imgsize``\n or change the default image metadata via ``columns``.\n\n >>> from mica.archive import aca_l0\n >>> imgs = aca_l0.get_l0_images('2012:001', '2012:002', slot=7)\n >>> imgs = aca_l0.get_l0_images('2005:001', '2005:002', slot=6, imgsize=[8])\n\n The default columns are:\n ['TIME', 'IMGROW0', 'IMGCOL0', 'BGDAVG', 'IMGSTAT', 'IMGFUNC1', 'IMGSIZE', 'IMGSCALE', 'INTEG']\n\n The image pixel values are given in units of DN. One can convert to e-/sec\n by multiplying by (5 / INTEG).\n\n :param start: start time of requested interval\n :param stop: stop time of requested interval\n :param slot: slot number integer (in the range 0 -> 7)\n :param imgsize: list of integers of desired image sizes (default=[4, 6, 8])\n :param columns: image meta-data columns\n\n :returns: list of ACAImage objects\n \"\"\"\n if columns is None:\n columns = ['TIME', 'BGDAVG', 'IMGSTAT', 'IMGFUNC1', 'IMGSIZE', 'IMGSCALE', 'INTEG']\n if 'IMGROW0' not in columns:\n columns.append('IMGROW0')\n if 'IMGCOL0' not in columns:\n columns.append('IMGCOL0')\n\n slot_columns = list(set(columns + ['QUALITY', 'IMGRAW', 'IMGSIZE']))\n dat = get_slot_data(start, stop, slot, imgsize=imgsize, columns=slot_columns)\n\n ok = dat['QUALITY'] == 0\n if not(np.all(ok)):\n dat = dat[ok]\n\n # Convert temperatures from K to degC\n for temp in ('TEMPCCD', 'TEMPHOUS', 'TEMPPRIM', 'TEMPSEC'):\n if temp in dat.dtype.names:\n dat[temp] -= 273.15\n\n # Masked array col access ~100 times slower than ndarray so convert\n dat = dat.filled(-9999)\n\n imgs = []\n imgsizes = dat['IMGSIZE']\n imgraws = dat['IMGRAW']\n cols = {name: dat[name] for name in columns}\n\n for i, row in enumerate(dat):\n imgraw = imgraws[i].reshape(8, 8)\n sz = imgsizes[i]\n if sz < 8:\n imgraw = imgraw[:sz, :sz]\n\n meta = {name: col[i] for name, col in cols.items() if col[i] != -9999}\n imgs.append(ACAImage(imgraw, meta=meta))\n\n return imgs\n\n\nclass MSID(object):\n def __init__(self, msid, slot, start, stop):\n self.tstart = DateTime(start).secs\n self.tstop = DateTime(stop).secs\n self.datestart = DateTime(self.tstart).date\n self.datestop = DateTime(self.tstop).date\n self.slot = slot\n self._check_msid(msid)\n self._get_data()\n\n def _check_msid(self, req_msid):\n if req_msid.upper() in ACA_DTYPE_NAMES:\n self.msid = req_msid.lower()\n else:\n raise MissingDataError(\"msid %s not found\" % req_msid)\n\n def _get_data(self):\n slot_data = get_slot_data(\n self.tstart, self.tstop, self.slot, imgsize=[8],\n columns=['TIME', self.msid.upper()])\n self.vals = slot_data[self.msid.upper()]\n self.times = slot_data['TIME']\n\n\nclass MSIDset(collections.OrderedDict):\n def __init__(self, msids, start, stop):\n super(MSIDset, self).__init__()\n self.tstart = DateTime(start).secs\n self.tstop = DateTime(stop).secs\n self.datestart = DateTime(self.tstart).date\n self.datestop = DateTime(self.tstop).date\n for msid in msids:\n self[msid] = MSID(msid, self.tstart, self.tstop)\n\n\ndef obsid_times(obsid):\n from kadi import events # Kadi is a big import so defer\n dwells = events.dwells.filter(obsid=obsid)\n n_dwells = len(dwells)\n tstart = dwells[0].tstart\n tstop = dwells[n_dwells - 1].tstop\n\n return tstart, tstop\n\n\ndef get_files(obsid=None, start=None, stop=None,\n slots=None, imgsize=None, db=None, data_root=None):\n \"\"\"\n Retrieve list of files from ACA0 archive lookup table that\n match arguments. The database query returns files with\n\n tstart < stop\n and\n tstop > start\n\n which returns all files that contain any part of the interval\n between start and stop. If the obsid argument is provided, the\n archived obspar tstart/tstop (sybase aca.obspar table) are used.\n\n >>> from mica.archive import aca_l0\n >>> obsid_files = aca_l0.get_files(obsid=5438)\n >>> time_files = aca_l0.get_files(start='2012:001', stop='2012:002')\n >>> time_8x8 = aca_l0.get_files(start='2011:001', stop='2011:010',\n ... imgsize=[8])\n\n :param obsid: obsid\n :param start: start time of requested interval\n :param stop: stop time of requested interval\n :param slots: list of integers of desired image slots to retrieve\n (defaults to all -> [0, 1, 2, 3, 4, 5, 6, 7, 8])\n :param imgsize: list of integers of desired image sizes\n (defaults to all -> [4, 6, 8])\n :param db: handle to archive lookup table\n :param data_root: parent directory of Ska aca l0 archive\n\n :returns: interval files\n :rtype: list\n \"\"\"\n if slots is None:\n slots = [0, 1, 2, 3, 4, 5, 6, 7]\n if data_root is None:\n data_root = CONFIG['data_root']\n if imgsize is None:\n imgsize = [4, 6, 8]\n if db is None:\n dbfile = os.path.join(data_root, 'archfiles.db3')\n db = dict(dbi='sqlite', server=dbfile)\n if obsid is None:\n if start is None or stop is None:\n raise TypeError(\"Must supply either obsid or start and stop\")\n else:\n start, stop = obsid_times(obsid)\n\n file_records = _get_file_records(start, stop,\n slots=slots, imgsize=imgsize, db=db,\n data_root=data_root)\n files = [os.path.join(data_root,\n \"%04d\" % f['year'],\n \"%03d\" % f['doy'],\n str(f['filename']))\n for f in file_records]\n return files\n\n\ndef _get_file_records(start, stop=None, slots=None,\n imgsize=None, db=None, data_root=None):\n \"\"\"\n Retrieve list of files from ACA0 archive lookup table that\n match arguments. The database query returns files with\n\n tstart < stop\n and\n tstop > start\n\n which returns all files that contain any part of the interval\n between start and stop.\n\n :param start: start time of requested interval\n :param stop: stop time of requested interval\n (default of None will get DateTime(None) which is\n equivalent to 'now')\n :param slots: list of integers of desired image slots to retrieve\n (defaults to all -> [0, 1, 2, 3, 4, 5, 6, 7, 8])\n :param imgsize: list of integers of desired image sizes\n (defaults to all -> [4, 6, 8])\n :param db: handle to archive lookup table\n :param data_root: parent directory of Ska aca l0 archive\n\n :returns: interval files\n :rtype: list\n \"\"\"\n if slots is None:\n slots = [0, 1, 2, 3, 4, 5, 6, 7]\n if data_root is None:\n data_root = CONFIG['data_root']\n if imgsize is None:\n imgsize = [4, 6, 8]\n if db is None:\n dbfile = os.path.join(data_root, 'archfiles.db3')\n db = dict(dbi='sqlite', server=dbfile)\n\n tstart = DateTime(start).secs\n tstop = DateTime(stop).secs\n imgsize_str = ','.join([str(x) for x in imgsize])\n slot_str = ','.join([str(x) for x in slots])\n # a composite index isn't as fast as just doing a padded search on one\n # index first (tstart). This gets extra files to make sure we don't\n # miss the case where tstart is in the middle of an interval, but\n # drastically reduces the size of the bsearch on the tstop index\n tstart_pad = 10 * 86400\n db_query = ('SELECT * FROM archfiles '\n 'WHERE tstart >= %f - %f '\n 'AND tstart < %f '\n 'AND tstop > %f '\n 'AND slot in (%s) '\n 'AND imgsize in (%s) '\n 'order by filetime asc '\n % (tstart, tstart_pad, tstop, tstart, slot_str, imgsize_str))\n with Ska.DBI.DBI(**db) as db:\n files = db.fetchall(db_query)\n return files\n\n\nclass Updater(object):\n def __init__(self,\n db=None,\n data_root=None,\n temp_root=None,\n days_at_once=None,\n sql_def=None,\n cda_table=None,\n filetype=None,\n start=None,\n stop=None,\n ):\n for init_opt in ['data_root', 'temp_root', 'days_at_once',\n 'sql_def', 'cda_table']:\n setattr(self, init_opt, vars()[init_opt] or CONFIG[init_opt])\n self.data_root = os.path.abspath(self.data_root)\n self.temp_root = os.path.abspath(self.temp_root)\n self.filetype = filetype or FILETYPE\n if db is None:\n dbfile = os.path.join(data_root, 'archfiles.db3')\n db = dict(dbi='sqlite', server=dbfile, autocommit=False)\n self.db = db\n self.start = start\n self.stop = stop\n\n#def _rebuild_database(db=None, db_file=None,\n# data_root=config['data_root'],\n# sql_def=config['sql_def']):\n# \"\"\"\n# Utility routine to rebuild the file lookup database using the\n# package defaults and the files in the archive.\n# \"\"\"\n# if db is None and db_file is None:\n# raise ValueError\n# if db is None and db_file is not None:\n# logger.info(\"creating archfiles db from %s\"\n# % sql_def)\n# db_sql = os.path.join(os.environ['SKA_DATA'],\n# 'mica', sql_def)\n# db_init_cmds = file(db_sql).read()\n# db = Ska.DBI.DBI(dbi='sqlite', server=db_file,\n# autocommit=False)\n# db.execute(db_init_cmds, commit=True)\n# year_dirs = sorted(glob(\n# os.path.join(data_root, '[12][0-9][0-9][0-9]')))\n# for ydir in year_dirs:\n# day_dirs = sorted(glob(\n# os.path.join(ydir, '[0-3][0-9][0-9]')))\n# for ddir in day_dirs:\n# archfiles = sorted(glob(\n# os.path.join(ddir, '*_img0*')))\n# db.execute(\"begin transaction\")\n# for i, f in enumerate(archfiles):\n# arch_info = read_archfile(i, f, archfiles, db)\n# if arch_info:\n# db.insert(arch_info, 'archfiles')\n# db.commit()\n\n def _get_missing_archive_files(self, start, only_new=False):\n ingested_files = self._get_arc_ingested_files()\n startdate = DateTime(start).date\n logger.info(\"Checking for missing files from %s\" %\n startdate)\n # find the index in the cda archive list that matches\n # the first entry with the \"start\" date\n for idate, backcnt in zip(ingested_files['ingest_date'][::-1],\n count(1)):\n if idate < startdate:\n break\n\n last_ok_date = None\n missing = []\n # for the entries after the start date, see if we have the\n # file or a later version\n with Ska.DBI.DBI(**self.db) as db:\n for file, idx in zip(ingested_files[-backcnt:], count(0)):\n filename = file['filename']\n db_match = db.fetchall(\n \"select * from archfiles where \"\n + \"filename = '%s' or filename = '%s.gz'\"\n % (filename, filename))\n if len(db_match):\n continue\n file_re = re.search(\n r'acaf(\\d+)N(\\d{3})_(\\d)_img0.fits(\\.gz)?',\n filename)\n if not file_re:\n continue\n slot = int(file_re.group(3))\n filetime = int(file_re.group(1))\n version = int(file_re.group(2))\n # if there is an old file and we're just looking for new ones\n range_match = db.fetchall(\n \"\"\"SELECT * from archfiles\n WHERE filetime = %(filetime)d\n and slot = %(slot)d\"\"\" % dict(filetime=filetime, slot=slot))\n if range_match and only_new:\n continue\n # if there is a newer file there already\n version_match = db.fetchall(\n \"\"\"SELECT * from archfiles\n WHERE filetime = %(filetime)d\n and slot = %(slot)d\n and revision >= %(version)d\"\"\"\n % dict(slot=slot, version=version, filetime=filetime))\n if version_match:\n continue\n # and if made it this far add the file to the list\n missing.append(file)\n # and update the date through which data is complete to\n # the time of the previous file ingest\n if last_ok_date is None:\n last_ok_date = \\\n ingested_files['ingest_date'][-backcnt:][idx - 1]\n\n if last_ok_date is None:\n last_ok_date = ingested_files['ingest_date'][-1]\n return missing, last_ok_date\n\n def _get_arc_ingested_files(self):\n table_file = os.path.join(self.data_root, self.cda_table)\n with tables.open_file(table_file) as h5f:\n tbl = h5f.get_node('/', 'data')\n arc_files = tbl[:]\n return Table(arc_files)\n\n def _get_archive_files(self, start, stop):\n \"\"\"\n Update FITS file archive with arc5gl and ingest files into file archive\n\n :param filetype: a dictionary (or dictionary-like) object with keys for\n 'level', 'instrum', 'content', 'arc5gl_query'\n and 'fileglob' for arc5gl. For ACA0:\n {'level': 'L0', 'instrum': 'PCAD',\n 'content': 'ACADATA', 'arc5gl_query': 'ACA0',\n 'fileglob': 'aca*fits*'}\n :param start: start of interval to retrieve (Chandra.Time compatible)\n :param stop: end of interval to retrieve (Chandra.Time compatible)\n\n :returns: retrieved file names\n :rtype: list\n \"\"\"\n\n filetype = self.filetype\n # Retrieve CXC archive files in a temp directory with arc5gl\n arc5 = Ska.arc5gl.Arc5gl()\n arc5.sendline('tstart=%s' % DateTime(start).date)\n arc5.sendline('tstop=%s' % DateTime(stop).date)\n arc5.sendline('get %s' % filetype['arc5gl_query'].lower())\n return sorted(glob(filetype['fileglob']))\n\n def _read_archfile(self, i, f, archfiles):\n \"\"\"\n Read FITS filename ``f`` with index ``i`` (position within list of\n filenames) and get dictionary of values to store in file lookup\n database. These values include all header items in\n ``ARCHFILES_HDR_COLS`` plus the header checksum, the image slot\n as determined by the filename, the imagesize as determined\n by IMGRAW, the year, day-of-year, and number of data rows in the file.\n\n :param i: index of file f within list of files archfiles\n :param f: filename\n :param archfiles: list of filenames for this batch\n :param db: database handle for file lookup database (Ska.DBI handle)\n\n :returns: info for a file.\n :rtype: dictionary\n \"\"\"\n\n # Check if filename is already in file lookup table\n # If so then delete temporary file and abort further processing.\n filename = os.path.basename(f)\n with Ska.DBI.DBI(**self.db) as db:\n if db.fetchall('SELECT filename FROM archfiles WHERE filename=?',\n (filename,)):\n logger.debug(\n 'File %s already in archfiles - unlinking and skipping' % f)\n os.unlink(f)\n return None\n\n logger.debug('Reading (%d / %d) %s' % (i, len(archfiles), filename))\n hdus = pyfits.open(f)\n hdu = hdus[1]\n\n # Accumlate relevant info about archfile that will be ingested\n # (this is borrowed from eng-archive but is set to archive to a\n # database table instead of an h5 table in this version)\n archfiles_row = dict((x, hdu.header.get(x.upper()))\n for x in ARCHFILES_HDR_COLS)\n archfiles_row['checksum'] = hdu.header.get('checksum') or hdu._checksum\n imgsize = hdu.data[0]['IMGRAW'].shape[0]\n archfiles_row['imgsize'] = int(imgsize)\n archfiles_row['slot'] = int(re.search(\n r'acaf\\d+N\\d{3}_(\\d)_img0.fits(\\.gz)?',\n filename).group(1))\n archfiles_row['filename'] = filename\n archfiles_row['filetime'] = int(\n re.search(r'(\\d+)', archfiles_row['filename']).group(1))\n filedate = DateTime(archfiles_row['filetime']).date\n year, doy = (int(x) for x in\n re.search(r'(\\d\\d\\d\\d):(\\d\\d\\d)', filedate).groups())\n archfiles_row['year'] = year\n archfiles_row['doy'] = doy\n archfiles_row['rows'] = len(hdu.data)\n hdus.close()\n\n with Ska.DBI.DBI(**self.db) as db:\n # remove old versions of this file\n oldmatches = db.fetchall(\n \"\"\"SELECT * from archfiles\n WHERE filetime = %(filetime)d\n and slot = %(slot)d\n and startmjf = %(startmjf)d and startmnf = %(startmnf)d\n and stopmjf = %(stopmjf)d and stopmnf = %(stopmnf)d \"\"\"\n % archfiles_row)\n if len(oldmatches):\n self._arch_remove(oldmatches)\n\n interval_matches = _get_file_records(archfiles_row['tstart'],\n archfiles_row['tstop'],\n slots=[archfiles_row['slot']])\n if len(interval_matches):\n # if there are files there that still overlap the new file\n # and they are all older, remove the old files.\n if np.all(interval_matches['revision']\n < archfiles_row['revision']):\n logger.info(\n \"removing overlapping files at older revision(s)\")\n logger.info(interval_matches)\n self._arch_remove(interval_matches)\n # if the overlapping files are all from the same revision\n # just ingest them and hope for the best\n elif np.all(interval_matches['revision']\n == archfiles_row['revision']):\n logger.info(\"ignoring overlap for same process revision\")\n # if the files that overlap are all newer, let's not ingest\n # the \"missing\" file\n elif np.all(interval_matches['revision']\n > archfiles_row['revision']):\n return None\n else:\n logger.error(archfiles_row)\n logger.error(interval_matches)\n # throw an error if there is still overlap\n raise ValueError(\"Cannot ingest %s, overlaps existing files\"\n % filename)\n\n return archfiles_row\n\n def _arch_remove(self, defunct_matches):\n with Ska.DBI.DBI(**self.db) as db:\n for file_record in defunct_matches:\n query = (\"\"\"delete from archfiles\n WHERE filetime = %(filetime)d\n and slot = %(slot)d\n and startmjf = %(startmjf)d\n and startmnf = %(startmnf)d\n and stopmjf = %(stopmjf)d\n and stopmnf = %(stopmnf)d \"\"\"\n % file_record)\n logger.info(query)\n db.execute(query)\n db.commit()\n archdir = os.path.abspath(os.path.join(\n self.data_root,\n str(file_record['year']),\n \"{0:03d}\".format(file_record['doy'])\n ))\n logger.info(\"deleting %s\" %\n os.path.join(archdir, file_record['filename']))\n real_file = os.path.join(archdir, file_record['filename'])\n if os.path.exists(real_file):\n os.unlink(real_file)\n\n def _move_archive_files(self, archfiles):\n \"\"\"\n Move ACA L0 files into the file archive into directories\n by YYYY/DOY under the specified data_root\n \"\"\"\n\n data_root = self.data_root\n if not os.path.exists(data_root):\n os.makedirs(data_root)\n for f in archfiles:\n if not os.path.exists(f):\n continue\n basename = os.path.basename(f)\n # use the timestamp right from the ACA0 filename\n tstart = re.search(r'(\\d+)', str(basename)).group(1)\n datestart = DateTime(tstart).date\n year, doy = re.search(r'(\\d\\d\\d\\d):(\\d\\d\\d)', datestart).groups()\n archdir = os.path.abspath(os.path.join(data_root,\n year,\n doy))\n # construct the destination filepath/name\n archfile = os.path.abspath(os.path.join(archdir, basename))\n if not os.path.exists(archdir):\n os.makedirs(archdir)\n if not os.path.exists(archfile):\n logger.debug('mv %s %s' % (os.path.abspath(f), archfile))\n os.chmod(f, 0o775)\n shutil.move(f, archfile)\n if os.path.exists(f):\n logger.info('Unlinking %s' % os.path.abspath(f))\n os.unlink(f)\n\n def _fetch_by_time(self, range_tstart, range_tstop):\n logger.info(\"Fetching %s from %s to %s\" \n % ('ACA L0 Data',\n DateTime(range_tstart).date,\n DateTime(range_tstop).date))\n archfiles = self._get_archive_files(DateTime(range_tstart),\n DateTime(range_tstop))\n return archfiles\n\n def _fetch_individual_files(self, files):\n arc5 = Ska.arc5gl.Arc5gl(echo=True)\n logger.info('********** %s %s **********'\n % (self.filetype['content'], time.ctime()))\n fetched_files = []\n ingest_dates = []\n # get the files, store in file archive, and record in database\n for file in files:\n # Retrieve CXC archive files in a temp directory with arc5gl\n missed_file = file['filename']\n arc5.sendline('dataset=flight')\n arc5.sendline('detector=pcad')\n arc5.sendline('subdetector=aca')\n arc5.sendline('level=0')\n arc5.sendline('filename=%s' % missed_file)\n arc5.sendline('version=last')\n arc5.sendline('operation=retrieve')\n arc5.sendline('go')\n have_files = sorted(glob(f\"{missed_file}*\"))\n filename = have_files[0]\n # if it isn't gzipped, just gzip it\n if re.match(r'.*\\.fits$', filename):\n f_in = open(file, 'rb')\n f_out = gzip.open(\"%s.gz\" % filename, 'wb')\n f_out.writelines(f_in)\n f_out.close()\n f_in.close()\n filename = \"%s.gz\" % filename\n fetched_files.append(filename)\n ingest_dates.append(file['ingest_date'])\n return fetched_files, ingest_dates\n\n def _insert_files(self, files):\n count_inserted = 0\n for i, f in enumerate(files):\n arch_info = self._read_archfile(i, f, files)\n if arch_info:\n self._move_archive_files([f])\n with Ska.DBI.DBI(**self.db) as db:\n db.insert(arch_info, 'archfiles')\n db.commit()\n count_inserted += 1\n logger.info(\"Ingested %d files\" % count_inserted)\n\n def update(self):\n \"\"\"\n Retrieve ACA0 telemetry files from the CXC archive, store in the\n Ska/ACA archive, and update database of files.\n \"\"\"\n contentdir = self.data_root\n if not os.path.exists(contentdir):\n os.makedirs(contentdir)\n if not os.path.exists(self.temp_root):\n os.makedirs(self.temp_root)\n archdb = os.path.join(contentdir, 'archfiles.db3')\n # if the database of the archived files does not exist,\n # or is empty, make it\n if not os.path.exists(archdb) or os.stat(archdb).st_size == 0:\n logger.info(\"creating archfiles db from %s\"\n % self.sql_def)\n db_sql = Path(__file__).parent / self.sql_def\n db_init_cmds = open(db_sql).read()\n with Ska.DBI.DBI(**self.db) as db:\n db.execute(db_init_cmds, commit=True)\n if self.start:\n datestart = DateTime(self.start)\n else:\n # Get datestart as the most-recent file time from archfiles table\n # will need min-of-max-slot-datestart\n with Ska.DBI.DBI(**self.db) as db:\n last_time = min([db.fetchone(\n \"select max(filetime) from archfiles where slot = %d\"\n % s)['max(filetime)'] for s in range(0, 8)])\n if last_time is None:\n raise ValueError(\n \"No files in archive to do update-since-last-run mode.\\n\"\n + \"Please specify a time with --start\")\n datestart = DateTime(last_time)\n datestop = DateTime(self.stop)\n padding_seconds = 10000\n # loop over the specified time range in chunks of\n # days_at_once in seconds with some padding\n for tstart in np.arange(datestart.day_start().secs,\n datestop.day_end().secs,\n self.days_at_once * 86400):\n # set times for a chunk\n range_tstart = tstart - padding_seconds\n range_tstop = tstart + self.days_at_once * 86400\n if range_tstop > datestop.day_end().secs:\n range_tstop = datestop.day_end().secs\n range_tstop += padding_seconds\n # make a temporary directory\n tmpdir = Ska.File.TempDir(dir=self.temp_root)\n dirname = tmpdir.name\n logger.debug(\"Files save to temp dir %s\" % dirname)\n # get the files, store in file archive, and record in database\n with Ska.File.chdir(dirname):\n fetched_files = self._fetch_by_time(range_tstart, range_tstop)\n self._insert_files(fetched_files)\n\n timestamp_file = os.path.join(self.data_root, 'last_timestamp.txt')\n # get list of missing files since the last time the tool ingested\n # files. If this is first run of the tool, check from the start of\n # the requested time range\n if (os.path.exists(timestamp_file)\n and os.stat(timestamp_file).st_size > 0):\n cda_checked_timestamp = open(timestamp_file).read().rstrip()\n else:\n cda_checked_timestamp = DateTime(self.start).date\n missing_datetime = DateTime(cda_checked_timestamp)\n missing_files, last_ingest_date = \\\n self._get_missing_archive_files(missing_datetime,\n only_new=True)\n # update the file to have up through the last confirmed good file\n # even before we try to fetch missing ones\n open(timestamp_file, 'w').write(\"%s\" % last_ingest_date)\n\n if len(missing_files):\n logger.info(\"Found %d missing individual files\"\n % len(missing_files))\n # make a temporary directory\n tmpdir = Ska.File.TempDir(dir=self.temp_root)\n dirname = tmpdir.name\n logger.info(\"File save to temp dir %s\" % dirname)\n with Ska.File.chdir(dirname):\n fetched_files, ingest_times = \\\n self._fetch_individual_files(missing_files)\n self._insert_files(fetched_files)\n\n last_ingest_date = missing_files[-1]['ingest_date']\n # update the file to have up through the last confirmed good file\n # even before we try to fetch missing ones\n open(timestamp_file, 'w').write(\"%s\" % last_ingest_date)\n else:\n logger.info(\"No missing files\")\n\n\ndef main():\n \"\"\"\n Command line interface to fetch ACA L0 telemetry from the CXC Archive\n and store it in the Ska archive.\n \"\"\"\n opt = get_options()\n kwargs = vars(opt)\n updater = Updater(**kwargs)\n updater.update()\n\nif __name__ == '__main__':\n main()\n","sub_path":"mica/archive/aca_l0.py","file_name":"aca_l0.py","file_ext":"py","file_size_in_byte":36563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"375142554","text":"# -*- coding: UTF-8 -*-\nfrom utils import simplify_name\nimport Command\n\nCOMMAND = '~'\nTAG = '#'\n\ndef is_command(line):\n '''Detect if the line is a command line indeed.'''\n return len(line) > 0 and line[0] == COMMAND\n\ndef bulk_commands(depth1=None, depth2=None, depth3=None):\n '''Shorthand to get a bulk list of commands from dicts(name->content).\n\n Examples:\n - bulk_commands({\"title\":\"Test\", \"include\":\"More\"})\n - bulk_commands(depth1=dict(title=\"Test\"), depth2=dict(download=None))\n '''\n result = []\n if depth1 is not None:\n for name, content in depth1.items():\n if name != \"depth2\":\n result += [Command.Command(name=name, content=content, depth=1)]\n else:\n for nn, cc in content:\n result += [Command.Command(name=nn, content=cc, depth=2)]\n if depth2 is not None:\n for name, content in depth2.items():\n result += [Command.Command(name=name, content=content, depth=2)]\n if depth3 is not None:\n for name, content in depth3.items():\n result += [Command.Command(name=name, content=content, depth=3)]\n return result\n\ndef commands_to_textnet(commands):\n \"\"\"Very simple flush of commands list to textnet string.\"\"\"\n return \"\\n\".join([c.compile() for c in commands])\n\n\ndef combine_tags(incoming1, incoming2):\n \"\"\"Concatenate two tags structures.\"\"\"\n i1 = build_tags(incoming1)\n i2 = build_tags(incoming2)\n for t in i2[\"ordered\"]:\n if simplify_name(t) not in i1[\"hash\"]:\n i1[\"ordered\"] += [t]\n i1[\"hash\"][simplify_name(t)] = t\n return i1\n\ndef build_tags(tag_list=None):\n \"\"\"Simplify tags and build them in a list of tuples and a dict.\"\"\"\n result = dict(ordered=[], hash=dict())\n if tag_list is None:\n return result\n if isinstance(tag_list, dict):\n return tag_list\n if isinstance(tag_list, basestring):\n tag_list = tag_list.split(TAG)\n for t in tag_list:\n result[\"ordered\"] += [t.strip()]\n result[\"hash\"][simplify_name(t)] = t.strip()\n return result\n\n#\n","sub_path":"filesystem/commands/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"530038755","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('statistics/', views.statistics, name='statistics'),\n path('tagger/', views.tagger, name='tagger'),\n path('demo/', views.demo, name='demo'),\n path('initialize_data_for_demo/', views.initialize_data_for_demo, name='initialize_data_for_demo'),\n path('meme_search_demo/', views.meme_search_demo, name='meme_search_demo'),\n path('tagger_statistics/', views.tagger_statistics, name='tagger_statistics'),\n path('tagger_summary/', views.tagger_summary, name='tagger_summary'),\n path('tagger_summary_csv/', views.tagger_summary_csv, name='tagger_summary_csv'),\n path('tweets_summary_csv/', views.tweets_summary_csv, name='tweets_summary_csv'),\n path('/annotate/', views.annotate, name='annotate')\n]\n","sub_path":"tweets/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"109500214","text":"import urllib.request\nimport socket\nimport urllib.error\n\"\"\"\n设置参数timeout来规定网页请求时的超时时间\nurllib.request.urlopen()中参数context必须是ssl.SSLContext类型,用来指定SSl设置,\ncafile,capath参数用来指定CA证书和它的存储路径,一般用于https类型的请求\n\"\"\"\ntry:\n reponse = urllib.request.urlopen(\"http://httpbin.org/get\",timeout=0.1)\n # 通过urllib.error模块捕获异常,当请求网页时超出规定时间捕获该异常信息并处理\nexcept urllib.error.URLError as e:\n # 判断异常的类型为socket.timeout类型,即请求网页超时\n if isinstance(e.reason,socket.timeout):\n print(\"timeout\")\nprint(\"HAHAHAHAHHAHA\")\nprint(\"Hello world!\")\n","sub_path":"http/timeout.py","file_name":"timeout.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"204708692","text":"#!/usr/bin/env python\n#\n# Extracts email addresses from one or more plain text files.\n#\n# Notes:\n# - Does not save to file (pipe the output to a file if you want it saved).\n# - Does not check for duplicates (which can easily be done in the terminal).\n#\n# (c) 2013 Dennis Ideler \n\nfrom optparse import OptionParser\nimport os.path\nimport re\n\nregex = re.compile((\"([a-z0-9!#$%&'*+\\/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+\\/=?^_`\"\n \"{|}~-]+)*(@|\\sat\\s)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(\\.|\"\n \"\\sdot\\s))+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\"))\n\nmusic_regex = re.compile((\"(songs?)|(spotify)|(music\\W)|(soundcloud)|(tracks?)\"))\n\ndef file_to_str(filename):\n \"\"\"Returns the contents of filename as a string.\"\"\"\n with open(filename) as f:\n return f.read().lower() # Case is lowered to prevent regex mismatches.\n\ndef containsMusic(s):\n\n return music_regex.search(s)\n\n\n\ndef get_emails(s):\n \"\"\"Returns an iterator of matched emails found in string s.\"\"\"\n # Removing lines that start with '//' because the regular expression\n # mistakenly matches patterns like 'http://foo@bar.com' as '//foo@bar.com'.\n i = (email[0] for email in re.findall(regex, s) if not email[0].startswith('//'))\n result = \"\"\n for email in i:\n result += str(email) \n result += \"\\n\"\n return result\n\n\n\n#s = \"check out the Music \"\n#t = s.lower()\n\n#print get_emails(\"maming@gmail.com, hahah@yahoo.com\")\n\n#print containsMusic(t) != None\n\n'''\nif __name__ == '__main__':\n parser = OptionParser(usage=\"Usage: python %prog [FILE]...\")\n # No options added yet. Add them here if you ever need them.\n options, args = parser.parse_args()\n\n if not args:\n parser.print_usage()\n exit(1)\n\n for arg in args:\n if os.path.isfile(arg):\n print get_emails(file_to_str(arg)):\n\n else:\n print '\"{}\" is not a file.'.format(arg)\n parser.print_usage()\n'''","sub_path":"src/extractEmail.py","file_name":"extractEmail.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"393798935","text":"import glob\nimport torch\nimport torch.nn.functional as F\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nimport os\n\n\nlabel = \"Intention\"\ntraj_index = 55\nspecial_flag = 'contSetSpeed_'\nimage_folder = \"trajectory_dataset/attn_figs\"\nvideo_name = 'trajectory_dataset/attn_trajectory_'+label+'Model_'+special_flag+'traj'+str(traj_index)+'.mp4'\n\nfilelist = glob.glob(os.path.join(image_folder, \"*.png\"))\nfor f in filelist:\n os.remove(f)\n\n\ndef intention_to_color(intentions):\n colors = ['r', 'orange', 'b', 'g']\n intention_colors = []\n for int in intentions:\n intention_colors.append(colors[int])\n return intention_colors\n\n\nfname = glob.glob(\"trajectory_dataset/*.npy\")[0]\ntrajectories = np.load(fname, allow_pickle=True)\n\nagent_dim = 5 # pos(2), vel(2), heading(1)\nenv_dim = 8 # four corners of the environment(4), light status(4)\nopponent_dim = 5 # pos(2), vel(2), heading(1)\nintention_dim = 4 # one-hot vector for four possible intentions(4)\nnum_opponents = 10\nhidden_size = 32\n\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nif \"no\" not in label:\n actor_critic, ob_rms = torch.load(\n \"trained_models/ppo/CarEnv-TenOpponentWithIntention-States-SpeedControl-TL-v0_\"+special_flag+\"special_s3.pt\",\n map_location=lambda storage, loc: storage\n )\n intention_multiplier = 1.0\nelse:\n actor_critic, ob_rms = torch.load(\n \"trained_models/ppo/CarEnv-TenOpponent-States-SpeedControl-TL-v0_kp150_special_s0.pt\",\n map_location=lambda storage, loc: storage\n )\n intention_multiplier = 0.0\nactor_critic.to(device)\n\nrecurrent_hidden_states = torch.zeros(1, actor_critic.recurrent_hidden_state_size).to(device)\nmasks = torch.zeros(1, 1).to(device)\n\nfor i in range(len(trajectories[traj_index])):\n datap = torch.from_numpy(np.array(trajectories[traj_index][i])).to(device).unsqueeze(0).float()\n agent_position = np.array(trajectories[traj_index][i])[:2]\n\n agent_enc = actor_critic.base.agent_model(datap[:, :agent_dim])\n env_enc = actor_critic.base.env_model(datap[:, agent_dim:agent_dim+env_dim])\n\n opponent_state = datap[:, agent_dim+env_dim:].reshape((-1, opponent_dim+intention_dim+1))\n opp_positions = opponent_state[:, :2].cpu().numpy()\n opp_velocities = opponent_state[:, 2:4].cpu().numpy()\n opponentdyn_enc = actor_critic.base.opponent_model(opponent_state[:, :opponent_dim])*opponent_state[:, -1].unsqueeze(1)\n intention = opponent_state[:, opponent_dim:opponent_dim + intention_dim]\n intention_label = np.argmax(intention.cpu().numpy(), axis=-1)\n opponent_state = torch.cat((opponentdyn_enc, intention*intention_multiplier), dim=-1).view((1, num_opponents, -1))\n\n # computing intention weights\n expanded_agentenv_state = torch.cat((agent_enc, env_enc), dim=-1).repeat(1, num_opponents).view(1, num_opponents, -1)\n agentenvopp_states = torch.cat((expanded_agentenv_state, opponent_state), dim=-1).reshape(-1, 3*hidden_size + intention_dim)\n attention_weights = F.softmax(actor_critic.base.attention_model(agentenvopp_states).view(1, -1)).unsqueeze(2)\n attn_ws = attention_weights.squeeze().cpu().detach().numpy()\n\n # getting the attended opponent encoding.\n attended_opponentdyn_enc = (opponentdyn_enc.view((1, num_opponents, -1)) * attention_weights).sum(1)\n\n x = torch.cat((agent_enc, env_enc, attended_opponentdyn_enc), dim=-1)\n\n fig, ax = plt.subplots()\n intention_colors = intention_to_color(intention_label)\n for idx in range(num_opponents):\n if not (abs(opp_positions[idx, 0]) < 0.01 and abs(opp_positions[idx, 1]) < 0.01):\n vel_norm = opp_velocities[idx] / (np.linalg.norm(opp_velocities[idx])+1e-05)\n plt.arrow(opp_positions[idx, 0] + agent_position[0], opp_positions[idx, 1] + agent_position[1],\n 0.02*np.linalg.norm(opp_velocities[idx])*vel_norm[0], 0.02*np.linalg.norm(opp_velocities[idx])*vel_norm[1],\n length_includes_head=True, head_width=0.015, head_length=0.008)\n\n plt.scatter(opp_positions[idx, 0] + agent_position[0], opp_positions[idx, 1] + agent_position[1], s=attn_ws[idx]*1000, color='w')\n plt.scatter(opp_positions[idx, 0] + agent_position[0], opp_positions[idx, 1] + agent_position[1], c=intention_colors[idx])\n\n plt.scatter(agent_position[0], agent_position[1], color='y')\n plt.axis(xmin=-0.1, xmax=1.1, ymin=0, ymax=1)\n ax.set_facecolor('gray')\n plt.title(label + \" Model - \" + special_flag + \" - Timestep \" + str(i))\n plt.savefig(\"trajectory_dataset/attn_figs/step_\"+f\"{i:05d}.png\")\n\n\nimages = sorted([img for img in os.listdir(image_folder) if img.endswith(\".png\")])\nframe = cv2.imread(os.path.join(image_folder, images[0]))\nheight, width, layers = frame.shape\n\nfourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')\nvideo = cv2.VideoWriter(video_name, fourcc, 30, (width, height))\n\nfor image in images:\n video.write(cv2.imread(os.path.join(image_folder, image)))\n\ncv2.destroyAllWindows()\nvideo.release()","sub_path":"attn_viz/attention_visualization.py","file_name":"attention_visualization.py","file_ext":"py","file_size_in_byte":5004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"214721310","text":"import numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import SGD\nfrom numpy import genfromtxt\nimport copy\nimport multiprocessing as mp\nimport time\n\n\n# Checked\ndef weights_init(weights):\n new_weights = []\n for w in weights:\n new_weights.append(np.random.laplace(0, 1, w.shape))\n return [new_weights[i] for i in range(len(new_weights))]\n\n\n# Checked\ndef define_model(population_size, neurons):\n models = []\n for i in range(0, population_size):\n model = Sequential()\n model.add(Dense(neurons[1], activation='relu', use_bias=False, input_shape=(neurons[0],)))\n model.add(Dense(neurons[2], activation='relu', use_bias=False))\n model.add(Dense(neurons[3], activation='sigmoid', use_bias=False))\n model.compile(loss='mean_squared_error', optimizer=SGD(), metrics=['accuracy'])\n models.append(model)\n return models\n\n\ndef define_single_model(neurons):\n model = Sequential()\n model.add(Dense(neurons[1], activation='relu', use_bias=False, input_shape=(neurons[0],)))\n model.add(Dense(neurons[2], activation='relu', use_bias=False))\n model.add(Dense(neurons[3], activation='sigmoid', use_bias=False))\n model.compile(loss='mean_squared_error', optimizer=SGD(), metrics=['accuracy'])\n return model\n\n\n# Checked\ndef crossover_nodes(population, neurons, weights):\n model = define_single_model(neurons)\n for i in range(0, len(population) - 1, 2):\n a = [weights[z].shape for z in range(0, len(weights))]\n m = [np.empty(a[z]) for z in range(0, len(a))]\n m1 = copy.deepcopy(population[i].get_weights())\n m2 = copy.deepcopy(population[i + 1].get_weights())\n for j in range(0, len(neurons) - 1):\n for h in range(0, neurons[j + 1]):\n if np.random.uniform(0, 1) < 0.5:\n for k in range(0, len(m1[j])):\n # print('parent 1 selected and weight is:', m1[j][k][h])\n m[j][k][h] = copy.deepcopy(m1[j][k][h])\n else:\n for k in range(0, len(m2[j])):\n # print('parent 2 selected and weight is:', m2[j][k][h])\n m[j][k][h] = copy.deepcopy(m2[j][k][h])\n model.set_weights(m)\n return model\n\n\n# Double Checked\ndef mutate_nodes(population, neurons, number_of_mutation):\n model = define_single_model(neurons)\n m1 = population.get_weights()\n m = copy.deepcopy(m1)\n for neurons_number in range(neurons[0], np.sum(neurons)):\n if np.random.uniform(0, 1) < 1/(np.sum(neurons) - neurons[0]):\n # print(neurons_number)\n first = neurons[0]\n last = neurons[0]\n for j in range(0, len(neurons) - 1):\n last += neurons[j + 1]\n # print(first, last)\n if first <= neurons_number < last:\n layers_number = j\n neurons_number = neurons_number - first\n break\n first = last\n # print(layers_number, neurons_number)\n random_number = np.random.normal(0, 0.5, 1)\n for k in range(0, len(m1[layers_number])):\n # This is working\n m[layers_number][k][neurons_number] = m1[layers_number][k][neurons_number] + random_number\n model.set_weights(m)\n return model\n\n\ndef evaluation(population, x, y):\n # result of evaluation weights network\n evaluation_result = []\n for p in population:\n evaluation_result.append(round(p.evaluate(x, y, verbose=0)[1], 5))\n return evaluation_result\n\n\n# Checked\ndef probability(fitness):\n return [round(x / np.sum(fitness), 5) for x in fitness]\n\n\n# Checked\ndef breeding(population, neurons, dicts, num, weights):\n parent = []\n if np.random.uniform(0, 1) < 0.5:\n while len(parent) < 1:\n for p in population:\n if dicts[p][1] > np.random.uniform(0, 1) and len(parent) < 1:\n parent.append(p)\n lit_child = mutate_nodes(parent[0], neurons, num)\n else:\n while len(parent) < 2:\n for p in population:\n if dicts[p][1] > np.random.uniform(0, 1) and len(parent) < 2:\n parent.append(p)\n lit_child = crossover_nodes(parent, neurons, weights)\n return lit_child\n\n\ndef child_val(child, x_test, y_test, dicts, population):\n fit_result = []\n for p in population:\n fit_result.append(dicts[p][0])\n print('The mean of fitness is:', np.mean(fit_result))\n print('The best of fitness is:', np.max(fit_result))\n child_fit = round(child.evaluate(x_test, y_test, verbose=0)[1], 5)\n child_prob = round(child_fit / (child_fit + np.sum(fit_result) - np.min(fit_result)), 5)\n return [child_fit, child_prob]\n\n\ndef discard_individual(dicts, key):\n del dicts[key]\n return dicts\n\n\ndef insert_child(dicts, key, values):\n dicts[key] = values\n return dicts\n\n\ndef multiprocess(pool, population):\n evaluation_result = pool.starmap(Sequential.evaluate, ((p, x_test, y_test) for p in population))\n return evaluation_result\n\n\nx = genfromtxt(\"E:\\\\Work\\\\GANN\\\\Data\\\\mydata.csv\", delimiter=',', skip_header=1, usecols=(1, 2, 3, 4))\ny = genfromtxt(\"E:\\\\Work\\\\GANN\\\\Data\\\\mydata.csv\", delimiter=',', skip_header=1, usecols=(0,))\n\ny_test = y[:40000]\nx_test = x[:40000]\n\ny_train = y[40000:50000]\nx_train = x[40000:50000]\n\ngenerations = 100 # Number of generation algorithm run.\npop_size = 50\nneurons = [4, 7, 10, 1]\nnumber_of_mutate_node = 2\n\npopulation = define_model(population_size=pop_size, neurons=neurons)\nsample_weights = population[0].get_weights()\n\nfit_result = evaluation(population, x_test, y_test)\n# pool = mp.Pool(4)\n# fit_result = multiprocess(pool, population)\nprob_pop = probability(fit_result)\ndicts = {population[i]: [fit_result[i], prob_pop[i]] for i in range(0, len(population))}\n\n# for p in population:\n# if dicts[p][0] == np.max(fit_result):\n# best_GA = copy.deepcopy(p)\n\nfor g in range(0, generations):\n print('The generation number is: ', g + 1)\n child = breeding(list(dicts.keys()), neurons, dicts, number_of_mutate_node, sample_weights)\n child_values = child_val(child, x_test, y_test, dicts, list(dicts.keys()))\n\n # Discarding\n for p in list(dicts.keys()):\n if dicts[p][0] == np.min(fit_result):\n discard_individual(dicts, p)\n print(child_values)\n dicts = insert_child(dicts, child, child_values)\n # Updating Probabilities in Dictionary\n for p in list(dicts.keys()):\n dicts[p][1] = round(dicts[p][0] / np.sum([dicts[p][0] for p in list(dicts.keys())]), 5)\n\n# best_GA.fit(x_train, y_train, epochs=1, validation_split=0.5)","sub_path":"MontanaV2/47101/Montana_New_Mutation.py","file_name":"Montana_New_Mutation.py","file_ext":"py","file_size_in_byte":6726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"76075862","text":"import os\n\nimport django\nfrom django.conf import settings\nfrom django.utils import six\n\ntry:\n from django.test import override_settings\nexcept ImportError:\n # Django < 1.7\n from django.test.utils import override_settings\n\n\ndef _(path):\n # Make sure the path contains only the correct separator\n return path.replace('/', os.sep).replace('\\\\', os.sep)\n\n\nclass pipeline_settings(override_settings):\n def __init__(self, **kwargs):\n if django.VERSION[:2] >= (1, 10):\n # Django 1.10's override_settings inherits from TestContextDecorator\n # and its __init__ method calls its superclass' __init__ method too,\n # so we must do the same.\n super(pipeline_settings, self).__init__()\n self.options = {'PIPELINE': kwargs}\n\n\n# Django < 1.7 (copy-pasted from Django 1.7)\nclass modify_settings(override_settings):\n \"\"\"\n Like override_settings, but makes it possible to append, prepend or remove\n items instead of redefining the entire list.\n \"\"\"\n def __init__(self, *args, **kwargs):\n if args:\n # Hack used when instantiating from SimpleTestCase._pre_setup.\n assert not kwargs\n self.operations = args[0]\n else:\n assert not args\n self.operations = list(kwargs.items())\n\n def save_options(self, test_func):\n if test_func._modified_settings is None:\n test_func._modified_settings = self.operations\n else:\n # Duplicate list to prevent subclasses from altering their parent.\n test_func._modified_settings = list(\n test_func._modified_settings) + self.operations\n\n def enable(self):\n self.options = {}\n for name, operations in self.operations:\n try:\n # When called from SimpleTestCase._pre_setup, values may be\n # overridden several times; cumulate changes.\n value = self.options[name]\n except KeyError:\n value = list(getattr(settings, name, []))\n for action, items in operations.items():\n # items my be a single value or an iterable.\n if isinstance(items, six.string_types):\n items = [items]\n if action == 'append':\n value = value + [item for item in items if item not in value]\n elif action == 'prepend':\n value = [item for item in items if item not in value] + value\n elif action == 'remove':\n value = [item for item in value if item not in items]\n else:\n raise ValueError(\"Unsupported action: %s\" % action)\n self.options[name] = value\n super(modify_settings, self).enable()\n","sub_path":"tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"479253391","text":"from rest_framework.reverse import reverse\nfrom rest_framework import status\n\nimport pytest\n\nfrom to_do.models import TaskList\nfrom utils.tests import BaseTestingClass\n\nfrom account.models import CustomUser\n\n\nclass ListEndpointTest(BaseTestingClass):\n\n def setUp(self):\n self.user = CustomUser()\n self.user.email = 'smith@mail.com'\n self.user.set_password('qwerty123')\n self.user.save()\n\n def test_get_task_list(self):\n self.client.force_authenticate(self.user)\n task_list_1 = TaskList.objects.create(name='My Day', user=self.user)\n task_list_2 = TaskList.objects.create(name='Tomorrow', user=self.user)\n\n url = reverse('list-list')\n response = self.client.get(url)\n\n assert response.status_code == status.HTTP_200_OK\n assert len(response.data) == 2\n assert sorted(map(lambda x: x['id'], response.data)) == sorted(\n [\n task_list_1.id,\n task_list_2.id\n ]\n )\n\n def test_post_task_list(self):\n self.client.force_authenticate(self.user)\n\n url = reverse('list-list')\n data = {\n 'name': 'My Day'\n }\n response = self.client.post(url, data=data)\n\n assert response.status_code == status.HTTP_201_CREATED\n task_list = TaskList.objects.get(id=response.data['id'])\n assert task_list.name == 'My Day'\n assert task_list.user == self.user\n\n def test_partial_update_task_list(self):\n task_list = TaskList.objects.create(name='My Day', user=self.user)\n\n self.client.force_authenticate(self.user)\n url = reverse(\n 'list-detail',\n kwargs={\n 'pk': task_list.id\n }\n )\n data = {\n 'name': 'Do Today'\n }\n response = self.client.patch(url, data=data)\n\n assert response.status_code == status.HTTP_200_OK\n updated_task_list = TaskList.objects.get(id=task_list.id)\n assert updated_task_list.name == 'Do Today'\n assert updated_task_list.user == self.user\n\n def test_delete_task_list(self):\n task_list = TaskList.objects.create(name='My Day', user=self.user)\n\n self.client.force_authenticate(self.user)\n url = reverse(\n 'list-detail',\n kwargs={\n 'pk': task_list.id\n }\n )\n response = self.client.delete(url)\n\n assert response.status_code == status.HTTP_204_NO_CONTENT\n with pytest.raises(TaskList.DoesNotExist):\n TaskList.objects.get(id=task_list.id)\n","sub_path":"tests/api/endpoints/test_task_list.py","file_name":"test_task_list.py","file_ext":"py","file_size_in_byte":2596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"44572828","text":"\"\"\" Sample usage:\n - Format\n $ python sentence_splitting.py -c [path_to_aws_credentials_json] -l [english | spanish] -n [any integer]\n - English documents, 5 words minimum for a sentence to be stored\n $ python sentence_splitting.py -c /Users/some_user/credentials.json -l english -n 5\n\n Expected format for JSON credentials file:\n {\n \"aws\": {\n \"id\": \"AWS ID\",\n \"secret\": \"AWS SECRET\"\n }\n }\n\"\"\"\nimport sys\n\nsys.path.append(\"../../../\")\nfrom tasks.text_preprocessing.src.utils import *\n\nimport nltk\nimport json\nimport boto3\nimport csv\nimport codecs\nimport argparse\n\nEN_TOKENIZER = nltk.data.load(\"tokenizers/punkt/english.pickle\")\nES_TOKENIZER = nltk.data.load(\"tokenizers/punkt/spanish.pickle\")\nBUCKET_NAME = \"wri-nlp-policy\"\n\n\ndef english_sents_preprocess(txt, remove_new_lines=False):\n \"\"\"\n Steps in the preprocessing of text:\n 1. Remove HTML tags\n 2. Replace URLS by a tag [URL]\n 3. Replace new lines and tabs by normal spaces - sometimes sentences have new lines in the middle\n 4. Remove excessive spaces (more than 1 occurrence)\n 5. Parse emails and abreviations\n \"\"\"\n\n if remove_new_lines:\n txt = replace_links(remove_html_tags(txt)).replace(\"\\n\", \" \").replace(\"\\t\", \" \").strip()\n else:\n txt = replace_links(remove_html_tags(txt)).strip()\n\n txt = remove_multiple_spaces(txt)\n txt = parse_emails(txt)\n txt = parse_acronyms(txt)\n\n new_txt = \"\"\n all_period_idx = set([indices.start() for indices in re.finditer(\"\\.\", txt)])\n\n for i, char in enumerate(txt):\n if i in all_period_idx:\n # Any char following a period that is NOT a space means that we should not add that period\n if i + 1 < len(txt) and txt[i + 1] != \" \":\n continue\n\n # NOTE: Any char that is a number following a period will not count.\n # For enumerations, we're counting on docs being enumerated as \"(a)\" or \"(ii)\", and if not,\n # they will be separated by the \".\" after the number:\n # \"Before bullet point. 3. Bullet point text\" will just be \"Before bullet point 3.\" and \"Bullet point text\" as the sentences\n if i + 2 < len(txt) and txt[i + 2].isnumeric():\n continue\n\n # If we wanted to have all numbered lists together, uncomment this, and comment out the previous condition\n # if i + 2 < len(txt) and not txt[i + 2].isalpha():\n # continue\n\n new_txt += char\n\n return new_txt\n\n\ndef english_sents_postprocess(sents, min_num_words=4):\n \"\"\"\n Remove sentences that are made of less than a given number of words. Default is 4\n \"\"\"\n\n return [sent for sent in sents if len(sent.split()) >= min_num_words]\n\n\ndef nltk_sents(txt, tokenizer, extra_abbreviations=None):\n if extra_abbreviations:\n tokenizer._params.abbrev_types.update(extra_abbreviations)\n\n sents = tokenizer.tokenize(txt)\n return sents\n\n\ndef format_sents_for_output(sents, doc_id):\n formatted_sents = {}\n\n for i, sent in enumerate(sents):\n formatted_sents.update({f\"{doc_id}_sent_{i}\": {\"text\": sent, \"label\": []}})\n\n return formatted_sents\n\n\ndef doc_ids_per_country(country, s3):\n \"\"\"\n Get a list of text document file IDs for a given country from the CSV database in the S3 bucket.\n In the CSV, the file id is the file name without the file extension (\"23sd45fg.txt\" without the \".txt\")\n \"\"\"\n metadata_fname = f\"metadata/{country}_metadata.csv\"\n obj = s3.Object(bucket_name=BUCKET_NAME, key=metadata_fname)\n\n doc_ids = []\n for row in csv.reader(codecs.getreader(\"utf-8\")(obj.get()['Body'])):\n # Add original file ID without the file format\n doc_ids.append(row[3][:-4])\n\n return doc_ids\n\n\ndef get_abbreviations(language, s3):\n \"\"\"\n Gets the set of abbreviations for a given language, from the text file in the S3 bucket\n \"\"\"\n abbreviations_fname = f\"abbreviations/{language}_abbreviations.txt\"\n obj = s3.Object(bucket_name=BUCKET_NAME, key=abbreviations_fname)\n abbreviations_str = obj.get()['Body'].read().decode('utf-8')\n return set(abbreviations_str.split(\"\\n\"))\n\n\ndef aws_credentials_from_file(f_name):\n \"\"\"\n Returns the id and secret for an AWS account. Expected format of input file:\n \"aws\": {\n \"id\": \"AWS ID\",\n \"secret\": \"AWS SECRET\"\n }\n }\n \"\"\"\n with open(f_name, \"r\") as f:\n creds = json.load(f)\n\n return creds[\"aws\"][\"id\"], creds[\"aws\"][\"secret\"]\n\n\ndef move_s3_object(obj_name, obj_old_folder, obj_new_folder, s3):\n \"\"\"\n Moves an object from a given S3 folder to another by copying it to the new folder it and then deleting it from the old one\n \"\"\"\n try:\n s3.Object(BUCKET_NAME, f\"{obj_old_folder}/{obj_name}\").copy_from(\n CopySource=f\"{BUCKET_NAME}/{obj_new_folder}/{obj_name}\")\n _ = s3.Object(BUCKET_NAME, f\"{obj_old_folder}/{obj_name}\").delete()\n except Exception as e:\n print(f\"Error while moving {obj_name} from {obj_old_folder} to {obj_new_folder}.\")\n print(e)\n\n\ndef output_sents(sents, f_name, f_uuid, language, s3):\n \"\"\"\n Store a JSON file containing the metadata and sentences for a given text file in the S3 bucket\n \"\"\"\n sents_json = {}\n fformat = f_name.split(\".\")[-1]\n sents_json[f_uuid] = {\"metadata\":\n {\"n_sentences\": len(sents),\n \"file_name\": f_name,\n \"file_format\": fformat},\n \"sentences\": format_sents_for_output(sents, f_uuid)}\n\n s3.Object(BUCKET_NAME, f\"{language}_documents/sentences/{f_uuid}_sents.json\").put(\n Body=(json.dumps(sents_json, indent=4)))\n\n\ndef main(credentials_fname, language, min_num_words):\n \"\"\"\n 1. Set up S3 bucket object using credentials from given file\n 2. Iterate through new text files in given language folder (i.e english_documents/text_files/new/)\n 3. For each file, split the text into sentences and store the JSON sentences file to the sentences folder in the bucket (i.e english_documents/sentences\n 4. Move the text file from the new to the processed folder (i.e english_documents/text_files/processed/)\n \"\"\"\n # Set up AWS S3 bucket info\n aws_id, aws_secret = aws_credentials_from_file(credentials_fname)\n region = 'us-east-1'\n\n s3 = boto3.resource(\n service_name='s3',\n region_name=region,\n aws_access_key_id=aws_id,\n aws_secret_access_key=aws_secret\n )\n\n # Set up abbreviations and sentence tokenizer\n abbrevs = get_abbreviations(language, s3)\n tokenizer = ES_TOKENIZER if language == \"spanish\" else EN_TOKENIZER\n\n # Get original text files, split them into sentences, and store them to the S3 bucket\n i = 0\n error_files = []\n new_text_files_folder = f\"{language}_documents/text_files/new\"\n processed_text_files_folder = f\"{language}_documents/text_files/processed\"\n for obj in s3.Bucket(BUCKET_NAME).objects.all().filter(Prefix=new_text_files_folder):\n # Don't get the directory itself\n if not obj.key.endswith(\"/\"):\n# print(\"Processing\", obj.key)\n file_id = obj.key.replace(new_text_files_folder, \"\").replace(\".txt\", \"\")\n text = obj.get()['Body'].read().decode('utf-8')\n try:\n preprocessed = english_sents_preprocess(text)\n sents = nltk_sents(preprocessed, tokenizer, abbrevs)\n post_processed_sents = english_sents_postprocess(sents, min_num_words)\n output_sents(post_processed_sents, obj.key, file_id, language, s3)\n move_s3_object(file_id + \".txt\", new_text_files_folder, processed_text_files_folder, s3)\n except Exception as e:\n error_files.append({file_id: e})\n\n i += 1\n# if i == 2:\n# break\n if i % 100 == 0:\n print(\"----------------------------------------------\")\n print(f\"Processing {i} documents...\")\n print(f\"Number of errors so far: {len(error_files)}\")\n print(\"----------------------------------------------\")\n\n with open(\"../output/sentence_splitting_errors.json\", \"w\") as f:\n json.dump(error_files, f)\n\n print(\"=============================================================\")\n print(f\"Total documents processed: {i}\")\n print(f\"Total number of documents with errors: {len(error_files)}. Stored file in ../output/sentence_splitting_errors.json\")\n print(\"=============================================================\")\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-c', '--creds_file', required=True,\n help=\"AWS credentials JSON file\")\n parser.add_argument('-l', '--language', required=True,\n help=\"Language for sentence preprocessing/splitting. Current options are: english, spanish\")\n parser.add_argument('-n', '--min_num_words', default=5,\n help=\"Minimum number of words that a sentence needs to have to be stored\")\n\n args = parser.parse_args()\n\n main(args.creds_file, args.language, int(args.min_num_words))\n","sub_path":"tasks/text_preprocessing/src/sentence_splitting.py","file_name":"sentence_splitting.py","file_ext":"py","file_size_in_byte":9259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"50028058","text":"\"\"\"\nCreated on Oct 30 2020\n\n@author: tincythomas\nJUNIT test cases to extract tweets from Twitter using Tweepy API\n\"\"\"\nimport unittest\n\nfrom ExtractTweet import *\n\nclass TestExtractTweet(unittest.TestCase):\n def setUp(self):\n self.e = ExtractTweet()\n def testgetTweets(self):\n self.e = ExtractTweet()\n result = self.e.getTweets('Ontario','Canada');\n #for ind in result.index:\n #print(\"#covid19\" in str(result['text'][ind]).casefold())\n self.assertTrue(len(result)<=20)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"TestExtractTweet.py","file_name":"TestExtractTweet.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"221688824","text":"#!/usr/bin/env python3\n\n#Credit to @Alright for the RPCs\n\nimport re\nimport os\nimport requests\nimport json\nimport platform\n\n# define function that fetchs rpc creds from .conf\ndef def_credentials(chain):\n operating_system = platform.system()\n if operating_system == 'Darwin':\n ac_dir = os.environ['HOME'] + '/Library/Application Support/Komodo'\n elif operating_system == 'Linux':\n ac_dir = os.environ['HOME'] + '/.komodo'\n elif operating_system == 'Win64':\n ac_dir = \"dont have windows machine now to test\"\n # define config file path\n if chain == 'KMD':\n coin_config_file = str(ac_dir + '/komodo.conf')\n else:\n coin_config_file = str(ac_dir + '/' + chain + '/' + chain + '.conf')\n #define rpc creds\n with open(coin_config_file, 'r') as f:\n #print(\"Reading config file for credentials:\", coin_config_file)\n for line in f:\n l = line.rstrip()\n if re.search('rpcuser', l):\n rpcuser = l.replace('rpcuser=', '')\n elif re.search('rpcpassword', l):\n rpcpassword = l.replace('rpcpassword=', '')\n elif re.search('rpcport', l):\n rpcport = l.replace('rpcport=', '')\n return('http://' + rpcuser + ':' + rpcpassword + '@127.0.0.1:' + rpcport)\n\n# define function that posts json data\ndef post_rpc(url, payload, auth=None):\n try:\n r = requests.post(url, data=json.dumps(payload), auth=auth)\n return(json.loads(r.text))\n except Exception as e:\n raise Exception(\"Couldn't connect to \" + url + \": \", e)\n\n# Return current -pubkey=\ndef getpubkey_rpc(chain):\n getinfo_payload = {\n \"jsonrpc\": \"1.0\",\n \"id\": \"python\",\n \"method\": \"getinfo\",\n \"params\": []}\n getinfo_result = post_rpc(def_credentials(chain), getinfo_payload)\n\n return(getinfo_result['result']['pubkey'])\n\n# return latest batontxid from all publishers\ndef get_latest_batontxids(chain, oracletxid):\n oraclesinfo_result = oraclesinfo_rpc(chain, oracletxid)\n latest_batontxids = {}\n # fill \"latest_batontxids\" dictionary with publisher:batontxid data\n for i in oraclesinfo_result['registered']:\n latest_batontxids[i['publisher']] = i['batontxid']\n return(latest_batontxids)\n\n#VANILLA RPC\n\ndef sendrawtx_rpc(chain, rawtx):\n sendrawtx_payload = {\n \"jsonrpc\": \"1.0\",\n \"id\": \"python\",\n \"method\": \"sendrawtransaction\",\n \"params\": [rawtx]}\n #rpcurl = def_credentials(chain)\n return(post_rpc(def_credentials(chain), sendrawtx_payload))\n\ndef signmessage_rpc(chain, address, message):\n signmessage_payload = {\n \"jsonrpc\": \"1.0\",\n \"id\": \"python\",\n \"method\": \"signmessage\",\n \"params\": [\n address,\n message\n ]\n }\n signmessage_result = post_rpc(def_credentials(chain), signmessage_payload)\n return(signmessage_result['result'])\n\ndef verifymessage_rpc(chain, address, signature, message):\n verifymessage_payload = {\n \"jsonrpc\": \"1.0\",\n \"id\": \"python\",\n \"method\": \"verifymessage\",\n \"params\": [\n address,\n signature,\n message\n ]\n }\n verifymessage_result = post_rpc(def_credentials(chain), verifymessage_payload)\n return(verifymessage_result['result'])\n\ndef kvsearch_rpc(chain, key):\n kvsearch_payload = {\n \"jsonrpc\": \"1.0\",\n \"id\": \"python\",\n \"method\": \"kvsearch\",\n \"params\": [\n key\n ]\n }\n kvsearch_result = post_rpc(def_credentials(chain), kvsearch_payload)\n return(kvsearch_result['result'])\n\ndef kvupdate_rpc(chain, key, value, days, password):\n # create dynamic oraclessamples payload\n kvupdate_payload = {\n \"jsonrpc\": \"1.0\",\n \"id\": \"python\",\n \"method\": \"kvupdate\",\n \"params\": [\n key,\n value,\n str(days),\n password]}\n # make kvupdate rpc call\n kvupdate_result = post_rpc(def_credentials(chain), kvupdate_payload)\n return(kvupdate_result)\n\ndef oraclesdata_rpc(chain, oracletxid, hexstr):\n oraclesdata_payload = {\n \"jsonrpc\": \"1.0\",\n \"id\": \"python\",\n \"method\": \"oraclesdata\",\n \"params\": [\n oracletxid,\n hexstr]}\n oraclesdata_result = post_rpc(def_credentials(chain), oraclesdata_payload)\n return(oraclesdata_result['result'])\n\ndef oraclescreate_rpc(chain, name, description, oracle_type):\n oraclescreate_payload = {\n \"jsonrpc\": \"1.0\",\n \"id\": \"python\",\n \"method\": \"oraclescreate\",\n \"params\": [\n name,\n description,\n oracle_type]}\n oraclescreate_result = post_rpc(def_credentials(chain), oraclescreate_payload)\n return(oraclescreate_result['result'])\n\ndef oraclesinfo_rpc(chain, oracletxid):\n oraclesinfo_payload = {\n \"jsonrpc\": \"1.0\",\n \"id\": \"python\",\n \"method\": \"oraclesinfo\",\n \"params\": [oracletxid]}\n oraclesinfo_result = post_rpc(def_credentials(chain), oraclesinfo_payload)\n return(oraclesinfo_result['result'])\n\ndef oracleslist_rpc(chain):\n oracleslist_payload = {\n \"jsonrpc\": \"1.0\",\n \"id\": \"python\",\n \"method\": \"oracleslist\",\n \"params\": []}\n oracleslist_result = post_rpc(def_credentials(chain), oracleslist_payload)\n return(oracleslist_result['result'])\n\ndef oraclessubscribe_rpc(chain, oracletxid, publisher, amount):\n oraclessubscribe_payload = {\n \"jsonrpc\": \"1.0\",\n \"id\": \"python\",\n \"method\": \"oraclessubscribe\",\n \"params\": [oracletxid, publisher, amount]}\n oraclessubscribe_result = post_rpc(def_credentials(chain), oraclessubscribe_payload)\n return(oraclessubscribe_result['result'])\n\ndef oraclesregister_rpc(chain, oracletxid, datafee):\n oraclesregister_payload = {\n \"jsonrpc\": \"1.0\",\n \"id\": \"python\",\n \"method\": \"oraclesregister\",\n \"params\": [\n oracletxid,\n str(datafee)]}\n oraclesregister_result = post_rpc(def_credentials(chain), oraclesregister_payload)\n return(oraclesregister_result['result'])\n\ndef oraclessamples_rpc(chain, oracletxid, batonutxo, num):\n oraclessamples_payload = {\n \"jsonrpc\": \"1.0\",\n \"id\": \"python\",\n \"method\": \"oraclessamples\",\n \"params\": [\n oracletxid,\n batonutxo,\n str(num)]}\n oraclessamples_result = post_rpc(def_credentials(chain), oraclessamples_payload)\n return(oraclessamples_result['result'])\n\ndef getlastsegidstakes_rpc(chain, depth):\n oraclessubscribe_payload = {\n \"jsonrpc\": \"1.0\",\n \"id\": \"python\",\n \"method\": \"oraclessubscribe\",\n \"params\": [depth]}\n getlastsegidstakes_result = post_rpc(def_credentials(chain), oraclessubscribe_payload)\nreturn(getlastsegidstakes_result['result'])\n","sub_path":"getconf.py","file_name":"getconf.py","file_ext":"py","file_size_in_byte":6838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"373542824","text":"# Copyright 2014 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nfrom profile_chrome import agents_unittest\nfrom profile_chrome import atrace_tracing_agent\n\n\nclass AtraceAgentTest(agents_unittest.BaseAgentTest):\n def testGetCategories(self):\n categories = \\\n atrace_tracing_agent.AtraceAgent.GetCategories(self.device)\n self.assertTrue(categories)\n assert 'gfx' in ' '.join(categories)\n\n def testTracing(self):\n categories = ['gfx', 'input', 'view']\n ring_buffer = False\n agent = atrace_tracing_agent.AtraceAgent(self.device,\n categories,\n ring_buffer)\n\n try:\n agent.StartAgentTracing(None, None)\n finally:\n agent.StopAgentTracing()\n result = agent.GetResults()\n\n self.assertFalse(agent.IsTracingOn())\n self.assertTrue('CPU#' in result.raw_data)\n","sub_path":"systrace/profile_chrome/atrace_tracing_agent_unittest.py","file_name":"atrace_tracing_agent_unittest.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"348232953","text":"import numpy\n\nfrom .gexceptions import GMixRangeError, GMixFatalError\n\ndef shear_reduced(g1, g2, s1, s2):\n \"\"\"\n addition formula for reduced shear\n\n parameters\n ----------\n g1,g2: scalar or array\n \"reduced shear\" shapes\n s1,s2: scalar or array\n \"reduced shear\" shapes to use as shear\n\n outputs\n -------\n g1,g2 after shear\n \"\"\"\n\n A = 1 + g1*s1 + g2*s2\n B = g2*s1 - g1*s2\n denom_inv = 1./(A*A + B*B)\n\n g1o = A*(g1 + s1) + B*(g2 + s2)\n g2o = A*(g2 + s2) - B*(g1 + s1)\n\n g1o *= denom_inv\n g2o *= denom_inv\n\n return g1o,g2o\n\n\nclass Shape(object):\n \"\"\"\n Shape object. Currently only for reduced shear style shapes\n\n This version is jitted, but inherits non-jitted methods\n from ShapeBase\n \"\"\"\n def __init__(self, g1, g2):\n self.g1 = g1\n self.g2 = g2\n\n # can't call the other jitted methods\n g=numpy.sqrt(g1*g1 + g2*g2)\n if g >= 1.0:\n raise GMixRangeError(\"g out of range: %.16g\" % g)\n\n def set_g1g2(self, g1, g2):\n \"\"\"\n Set reduced shear style ellipticity\n \"\"\"\n self.g1=g1\n self.g2=g2\n\n g=numpy.sqrt(g1*g1 + g2*g2)\n if g >= 1.0:\n raise GMixRangeError(\"g out of range: %.16g\" % g)\n\n def get_sheared(self, s1, s2=None):\n \"\"\"\n Get a new shape, sheared by the specified amount\n \"\"\"\n\n if isinstance(s1,Shape):\n sh = s1\n s1 = sh.g1\n s2 = sh.g2\n else:\n if s2 is None:\n raise ValueError(\"send s1,s2 or a Shape\")\n\n g1,g2 = shear_reduced(self.g1,self.g2, s1, s2)\n return Shape(g1, g2)\n\n def __neg__(self):\n \"\"\"\n get Shape(-g1, -g2)\n \"\"\"\n return Shape(-self.g1, -self.g2)\n\n def get_rotated(self, theta_radians):\n \"\"\"\n Rotate the shape by the input angle\n \"\"\"\n twotheta = 2.0*theta_radians\n\n cos2angle = numpy.cos(twotheta)\n sin2angle = numpy.sin(twotheta)\n g1rot = self.g1*cos2angle + self.g2*sin2angle\n g2rot = -self.g1*sin2angle + self.g2*cos2angle\n\n return Shape(g1rot, g2rot)\n\n def rotate(self, theta_radians):\n \"\"\"\n In-place rotation of the shape by the input angle\n\n deprecated, use get_rotated()\n \"\"\"\n twotheta = 2.0*theta_radians\n\n cos2angle = numpy.cos(twotheta)\n sin2angle = numpy.sin(twotheta)\n g1rot = self.g1*cos2angle + self.g2*sin2angle\n g2rot = -self.g1*sin2angle + self.g2*cos2angle\n\n self.set_g1g2(g1rot, g2rot)\n\n def copy(self):\n \"\"\"\n Make a new Shape object with the same ellipticity parameters\n \"\"\"\n s = Shape(self.g1, self.g2)\n return s\n\n def __repr__(self):\n return '(%.16g, %.16g)' % (self.g1,self.g2)\n\ndef g1g2_to_e1e2(g1, g2):\n \"\"\"\n convert reduced shear g1,g2 to standard ellipticity\n parameters e1,e2\n\n uses eta representation but could also use\n e1 = 2*g1/(1 + g1**2 + g2**2)\n e2 = 2*g2/(1 + g1**2 + g2**2)\n\n parameters\n ----------\n g1,g2: scalars\n Reduced shear space shapes\n\n outputs\n -------\n e1,e2: tuple of scalars\n shapes in (ixx-iyy)/(ixx+iyy) style space\n \"\"\"\n g=numpy.sqrt(g1*g1 + g2*g2)\n\n if isinstance(g1, numpy.ndarray):\n w,=numpy.where(g >= 1.0)\n if w.size != 0:\n raise GMixRangeError(\"some g were out of bounds\")\n\n eta = 2*numpy.arctanh(g)\n e = numpy.tanh(eta)\n\n numpy.clip(e, 0.0, 0.99999999, e)\n\n e1=numpy.zeros(g.size)\n e2=numpy.zeros(g.size)\n w,=numpy.where(g != 0.0)\n if w.size > 0:\n fac = e[w]/g[w]\n\n e1[w] = fac*g1[w]\n e2[w] = fac*g2[w]\n\n else:\n if g >= 1.:\n raise GMixRangeError(\"g out of bounds: %s\" % g)\n if g == 0.0:\n return (0.0, 0.0)\n\n eta = 2*numpy.arctanh(g)\n e = numpy.tanh(eta)\n if e >= 1.:\n # round off?\n e = 0.99999999\n\n fac = e/g\n\n e1 = fac*g1\n e2 = fac*g2\n \n return e1,e2\n\ndef e1e2_to_g1g2(e1, e2):\n \"\"\"\n convert e1,e2 to reduced shear style ellipticity\n\n parameters\n ----------\n e1,e2: tuple of scalars\n shapes in (ixx-iyy)/(ixx+iyy) style space\n\n outputs\n -------\n g1,g2: scalars\n Reduced shear space shapes\n\n \"\"\"\n\n e = numpy.sqrt(e1*e1 + e2*e2)\n if isinstance(e1, numpy.ndarray):\n w,=numpy.where(e >= 1.0)\n if w.size != 0:\n raise GMixRangeError(\"some e were out of bounds\")\n\n eta=numpy.arctanh(e)\n g = numpy.tanh(0.5*eta)\n\n numpy.clip(g, 0.0, 0.99999999, g)\n\n g1=numpy.zeros(g.size)\n g2=numpy.zeros(g.size)\n w,=numpy.where(e != 0.0)\n if w.size > 0:\n fac = g[w]/e[w]\n\n g1[w] = fac*e1[w]\n g2[w] = fac*e2[w]\n\n else:\n if e >= 1.:\n raise GMixRangeError(\"e out of bounds: %s\" % e)\n if e == 0.0:\n g1,g2=0.0,0.0\n\n else:\n \n eta=numpy.arctanh(e)\n g = numpy.tanh(0.5*eta)\n\n if g >= 1.:\n # round off?\n g = 0.99999999\n\n\n fac = g/e\n\n g1 = fac*e1\n g2 = fac*e2\n\n return g1,g2\n\n\ndef g1g2_to_eta1eta2_array(g1, g2):\n \"\"\"\n convert reduced shear g1,g2 to eta\n \"\"\"\n n=g1.size\n\n g=numpy.sqrt(g1*g1 + g2*g2)\n\n eta1=numpy.zeros(n) -9999.0\n eta2=eta1.copy()\n good = numpy.zeros(n, dtype='i1')\n\n w,=numpy.where(g < 1.0)\n\n if w.size > 0:\n\n eta_w = 2*numpy.arctanh(g[w])\n\n fac = eta_w/g[w]\n\n eta1[w] = fac*g1[w]\n eta2[w] = fac*g2[w]\n\n good[w] = 1\n\n return eta1,eta2, good\n\n\ndef g1g2_to_eta1eta2(g1, g2):\n \"\"\"\n convert reduced shear g1,g2 to eta style ellipticity\n\n parameters\n ----------\n g1,g2: scalars\n Reduced shear space shapes\n\n outputs\n -------\n eta1,eta2: tuple of scalars\n eta space shapes\n \"\"\"\n\n g=numpy.sqrt(g1*g1 + g2*g2)\n\n if g >= 1.:\n raise GMixRangeError(\"g out of bounds: %s converting to eta\" % g)\n if g == 0.0:\n return (0.0, 0.0)\n\n eta = 2*numpy.arctanh(g)\n\n fac = eta/g\n\n eta1 = fac*g1\n eta2 = fac*g2\n \n return eta1,eta2\n\ndef eta1eta2_to_g1g2_array(eta1,eta2):\n \"\"\"\n Perform the conversion for all elements in an array\n \"\"\"\n n=eta1.size\n g1=numpy.zeros(n) - 9999\n g2=numpy.zeros(n) - 9999\n good = numpy.zeros(n, dtype='i1')\n\n eta=numpy.sqrt(eta1*eta1 + eta2*eta2)\n\n g = numpy.tanh(0.5*eta)\n\n w,=numpy.where( g < 1.0 )\n if w.size > 0:\n fac = g[w]/eta[w]\n\n g1 = fac*eta1[w]\n g2 = fac*eta2[w]\n good[w] = 1\n\n return g1,g2,good\n\ndef eta1eta2_to_g1g2(eta1,eta2):\n \"\"\"\n convert eta style shpaes to reduced shear shapes\n\n parameters\n ----------\n eta1,eta2: tuple of scalars\n eta space shapes\n\n outputs\n -------\n g1,g2: scalars\n Reduced shear space shapes\n \"\"\"\n\n eta=numpy.sqrt(eta1*eta1 + eta2*eta2)\n\n g = numpy.tanh(0.5*eta)\n\n if g >= 1.:\n raise GMixRangeError(\"g out of bounds: %s converting \"\n \"from eta1,eta2: %s,%s\" % (g,eta1,eta2))\n if g == 0.0:\n return (0.0, 0.0)\n\n fac = g/eta\n\n g1 = fac*eta1\n g2 = fac*eta2\n\n return g1,g2\n\n\n\ndef dgs_by_dgo_jacob(g1, g2, s1, s2):\n \"\"\"\n jacobian of the transformation\n |dgs/dgo|_{shear}\n\n parameters\n ----------\n g1,g2: numbers or arrays\n shape pars for \"observed\" image\n s1,s2: numbers or arrays\n shape pars for shear, applied negative\n \"\"\"\n\n ssq = s1*s1 + s2*s2\n num = (ssq - 1)**2\n denom=(1 + 2*g1*s1 + 2*g2*s2 + g1**2*ssq + g2**2*ssq)**2\n\n jacob = num/denom\n return jacob\n\ndef get_round_factor(g1, g2):\n \"\"\"\n factor to convert T to round T under shear\n \"\"\"\n gsq = g1**2 + g2**2\n f = (1-gsq) / (1+gsq)\n return f\n\n","sub_path":"ngmix/shape.py","file_name":"shape.py","file_ext":"py","file_size_in_byte":8002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"566487561","text":"class Parent:\n def __init__(self, name):\n self.__name = name\n\n def return_name(self):\n return str(\"my name is \" + str(self.__name)) \n\n @property\n def name(self):\n return self.__name\n\nclass Son(Parent):\n def __init__(self, name):\n super().__init__(name)\n\n\nMilan = Parent(\"Milan\")\nprint(Milan.return_name())\nJan = Son(\"Jan\")\nprint(Jan.return_name())\nprint(Jan.__class__)\nprint(Jan.__class__.__bases__)\nprint(__file__)\nmy_attr = getattr(Jan, 'name')\nprint(my_attr)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"39596364","text":"import re\nimport numpy as np\nimport string\nfrom io import StringIO\nimport pandas as pd\n\ndef loadflake(xgrowstring,onlytiles=False):\n tiles = np.genfromtxt(\n StringIO( # genfromtxt needs an io object\n re.sub(r'(\\[|\\])','', # remove [ and ]\n re.sub(r'; \\.\\.\\.','',xgrowstring))), # remove ; ... at line ends\n skip_header=4, # remove first lines\n skip_footer=1, # remove end junk\n dtype='uint'\n )\n if onlytiles:\n return tiles\n data = pd.Series(\n np.genfromtxt(StringIO(xgrowstring.split('\\n')[2]))[1:-1],\n index = ['gmc','gse','k','time','tiles','mismatches','events','perimeter','g','dgbonds']\n )\n return {'data': data, 'tiles': tiles}\n","sub_path":"alhambra/xgrowoutput.py","file_name":"xgrowoutput.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"521692811","text":"from django.urls import path\n\nfrom . import views\n\n#goes to empty path\n#then goes into views file and uses index function\n#we can use this index so we can refer to it later\nurlpatterns = [\n #ex: /polls/ goes to the empty pattern after pulls, and run the function 'index'\n path('' , views.index , name = 'index'),\n #ex /polls/5/ #dynamically matches patterns with the int:\"\"\n path('/', views.detail, name='detail'),\n #ex: /polls/5/results\n path('/results/', views.results, name='results'),\n #ex: /polls/5/vote\n path('/vote/', views.vote , name='vote')\n]","sub_path":"mysite/polls/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"54926473","text":"from itertools import chain\n\nfrom django.forms import widgets\nfrom django.utils.encoding import force_text\nfrom django.utils.translation import ugettext_lazy as _\n\n\ndef get_colortag_attrs(colortag, options):\n attrs = {\n 'data-tagid': colortag.id,\n 'data-tagslug': colortag.slug,\n 'data-background': '{}'.format(colortag.color),\n }\n if not options.get('no_tooltip') and colortag.description:\n attrs.update({\n 'data-toggle': 'tooltip',\n 'data-trigger': options.get('tooltip_trigger', 'hover'),\n 'data-placement': options.get('tooltip_placement', 'top'),\n 'title': colortag.description,\n })\n return attrs\n\n\ndef get_colortag_classes(colortag, options):\n cls = set(('colortag',))\n cls.add('colortag-dark' if colortag.font_white else 'colortag-light')\n if options.get('active'):\n cls.add('colortag-active')\n if options.get('button'):\n cls.add('btn')\n if options.get('label'):\n cls.update(('label', 'label-{}'.format(options.get('size', 'xs'))))\n if options.get('class'):\n cls.update(options['class'].split(' '))\n return cls\n\n\nclass ColortagMixIn:\n option_inherits_attrs = False\n class_name = 'colortag'\n\n def __init__(self, attrs=None, choices=()):\n super().__init__(attrs=attrs, choices=choices)\n if 'class' in self.attrs:\n self.attrs['class'] += ' ' + self.class_name\n else:\n self.attrs['class'] = self.class_name\n\n\nclass ColortagSelectMultiple(ColortagMixIn, widgets.CheckboxSelectMultiple):\n class_name = 'colortag-choice'\n\n def create_option(self, name, value, label, selected, index, subindex=None, attrs=None,\n colortag_instance=None):\n # colortag_instance is a new parameter that is not used in the super class method.\n # The overridden optgroups method uses this method.\n option = super().create_option(name, value, label, selected, index, subindex=subindex, attrs=attrs)\n if colortag_instance is None:\n return option\n # Add custom attributes to the option (one checkbox) that are based on\n # the corresponding ColorTag instance.\n opts = { 'button': True }\n attrs = option['attrs']\n attrs.update(get_colortag_attrs(colortag_instance, opts))\n attrs['data-class'] = ' '.join(get_colortag_classes(colortag_instance, opts))\n return option\n\n def optgroups(self, name, value, attrs=None):\n \"\"\"Return a list of optgroups for this widget.\"\"\"\n # Copied from https://github.com/django/django/blob/stable/1.11.x/django/forms/widgets.py#L570\n # (Django 1.11 django.forms.widgets.ChoiceWidget method optgroups)\n # and then slightly modified so that self.choices includes\n # model instances in addition to the HTML input values and labels.\n # Model instances in self.choices originate from the field ColortagChoiceField.\n groups = []\n has_selected = False\n\n for index, (option_value, option_label, colortag_instance) in enumerate(chain(self.choices)):\n if option_value is None:\n option_value = ''\n\n subgroup = []\n if isinstance(option_label, (list, tuple)):\n group_name = option_value\n subindex = 0\n choices = option_label\n else:\n group_name = None\n subindex = None\n choices = [(option_value, option_label)]\n groups.append((group_name, subgroup, index))\n\n for subvalue, sublabel in choices:\n selected = (\n force_text(subvalue) in value and\n (has_selected is False or self.allow_multiple_selected)\n )\n if selected is True and has_selected is False:\n has_selected = True\n subgroup.append(self.create_option(\n name, subvalue, sublabel, selected, index,\n subindex=subindex, attrs=attrs,\n colortag_instance=colortag_instance,\n ))\n if subindex is not None:\n subindex += 1\n return groups\n\n\nclass ColortagIncludeExcludeWidget(ColortagMixIn, widgets.Select):\n class_name = 'colortag-inc-exc'\n\n def __init__(self, attrs=None, tag=None):\n assert tag, \"The choice must be defined\"\n opts = { 'button': True }\n if attrs == None:\n attrs = {}\n attrs.update(get_colortag_attrs(tag, opts))\n attrs['data-class'] = ' '.join(get_colortag_classes(tag, opts))\n choices = [\n ('', tag.name),\n ('I' + str(tag.pk), \"Include\"),\n ('E' + str(tag.pk), \"Exclude\"),\n ]\n self.__text = tag.name\n super().__init__(attrs, choices)\n\n def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):\n option = super().create_option(name, value, label, selected, index, subindex=subindex, attrs=attrs)\n option['attrs']['data-text'] = self.__text\n return option\n\n\nclass ColortagIEMultiWidget(widgets.MultiWidget):\n template_name = \"django_colortag/widgets/colortag_multiwidget.html\"\n class_name = 'colortag-ie-group'\n\n def __init__(self, attrs=None, choices=None):\n widgets = [ColortagIncludeExcludeWidget(attrs, c) for c in choices] if choices else []\n super().__init__(widgets, attrs)\n if 'class' in self.attrs:\n self.attrs['class'] += ' ' + self.class_name\n else:\n self.attrs['class'] = self.class_name\n\n def set_subwidgets(self, choices):\n self.widgets = [ColortagIncludeExcludeWidget(tag=c) for c in choices]\n\n def decompress(self, value):\n if value == None:\n return [None for w in self.widgets]\n return value\n\n\nclass AndOrWidget(widgets.CheckboxInput):\n template_name = \"django_colortag/widgets/colortag_andor.html\"\n\n def __init__(self, attrs=None, check_test=None, label=None):\n self.label = label\n if attrs == None:\n attrs = {}\n attrs.setdefault('data-off-text', _(\"Match any (OR)\"))\n attrs.setdefault('data-on-text', _(\"Match all (AND)\"))\n # TODO: generate a help text, use an info-circle and a tooltip to display\n super().__init__(attrs, check_test)\n\n def get_context(self, name, value, attrs):\n context = super().get_context(name, value, attrs)\n context['widget']['label'] = self.label\n return context\n\n\nclass ColortagIEAndOrWidget(widgets.MultiWidget):\n\n def __init__(self, attrs=None, choices=None):\n widgets = (\n AndOrWidget(label=\"Feedbacks must have all selected tags\"),\n ColortagIEMultiWidget(attrs, choices)\n )\n super().__init__(widgets, attrs)\n\n def set_subwidgets(self, choices):\n self.widgets[1].set_subwidgets(choices)\n\n def decompress(self, value):\n if value == None:\n return [None, None]\n return value\n","sub_path":"django_colortag/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":7063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"620852113","text":"# Python 3.4\n# -*- coding: utf-8 -*-\n# OS: OS 10\n# IDE: Sublime Text\n\nimport facebook\nimport requests\nimport json\nimport sqlite3\n\ndef get_all_posts(fanpageID):\n\t\"\"\"Get all posts in fanpage and write each column in dicts.\n\t Returns:\n\t\t\tpostID_list:\n\t\t\tfanpageName_list:\n\t\t\tcontent_list:\n\t\t\tcreateTime_list:\n\t\"\"\"\n\tall_posts = graph.get_connections(id = fanpageID, connection_name = 'posts', summary='true', limit = 25)\n\tfanpageName = graph.get_object(id = fanpageID, fields = 'name')['name']\n\tpostID_list = []\n\tfanpageName_list = []\n\tcontent_list = []\n\tcreateTime_list = []\n\n\tfor i in range(0,24):\n\t\tpostID_list.append(all_posts['data'][i]['id'])\n\t\tfanpageName_list.append(fanpageName)\n\t\ttry:\n\t\t\tcontent_list.append(all_posts['data'][i]['message'])\n\t\texcept:\n\t\t\tcontent_list.append(0)\n\t\tcreateTime_list.append(all_posts['data'][i]['created_time'])\n\tprint('postID: ', type(all_posts['data'][1]['id']))\n\tprint('fanpageName: ', type(fanpageName))\n\tprint('content: ', type(all_posts['data'][1]['message']))\n\tprint('createTime: ', type(all_posts['data'][1]['created_time']))\n\n\treturn postID_list, fanpageName_list, content_list, createTime_list\n\n\ndef get_activation(postID_list):\n\t\"\"\"Get likes and comments in each post and write total counts in dicts.\n\t Returns:\n\t \t\tpostLikesCount_list:\n\t \t\tpostCommentsCount_list:\n\t\"\"\"\n\turl = 'https://graph.facebook.com/v2.10/'+ fanpageID +'?fields=posts.limits(25){likes,comments,shares}&access_token=' + token\n\tresponse = requests.get(url)\n\thtml = json.loads(response.text)\n\n\tpostLikesCount_list = []\n\tpostCommentsCount_list = []\n\tpostSharesCount_list = []\n\tfor i in postID_list:\n\t\tpostLikesCount = graph.get_connections(id = i, connection_name = 'likes', summary='true')\n\t\tpostCommentsCount = graph.get_connections(id = i, connection_name = 'comments', summary='true')\n\t\tpostLikesCount_list.append(postLikesCount['summary']['total_count'])\n\t\tpostCommentsCount_list.append(postCommentsCount['summary']['total_count'])\n\t\t\n\tfor i in range(25):\n\t\tpostSharesCount = html['posts']['data'][i]['shares']['count']\n\t\tpostSharesCount_list.append(postSharesCount)\n\n\tprint('postLikesCount: ', type(postLikesCount))\n\tprint('postCommentsCount: ', type(postCommentsCount))\n\tprint('postSharesCount: ', type(postSharesCount))\n\n\treturn postLikesCount_list, postCommentsCount_list, postSharesCount_list\n\n\ndef write_sql(cursor, write_list_1, write_list_2, write_list_3, write_list_4, write_list_5, write_list_6, write_list_7):\n\tlists = write_list_1, write_list_2, write_list_3, write_list_4, write_list_5, write_list_6, write_list_7\n\tsql = \"insert into PostInfo values (?,?,?,?,?,?,?)\"\n\tfor i in range(24):\n\t\twrite_out = []\n\t\tfor li in lists:\n\t\t\twrite_out.append(li[i])\n\t\tcursor.execute(sql, write_out)\n\n\nif __name__\t== '__main__':\n\ttoken = '' #貼上token\n\tgraph = facebook.GraphAPI(access_token = token)\n\tfanpageID = '1759525920983198'\n\n\tconn = sqlite3.connect('Fanpage_data.db')\n\tcur = conn.cursor()\n\n\tpostID_list, fanpageName_list, content_list, createTime_list = get_all_posts(fanpageID)\n\tpostLikesCount_list, postCommentsCount_list, postSharesCount_list = get_activation(postID_list)\n\twrite_sql(cur, postID_list, fanpageName_list, content_list, postLikesCount_list, postCommentsCount_list, postSharesCount_list, createTime_list)\n\n\tconn.commit()\n\tconn.close()\n\n","sub_path":"facebook_to_SQLite.py","file_name":"facebook_to_SQLite.py","file_ext":"py","file_size_in_byte":3286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"529466668","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom xas.file_io import load_binned_df_from_file, save_binned_df_as_file\nimport os\n\ndef filenames_from_dir(path, base='', ext=''):\n filenames = []\n if type(base) == str:\n (_, _, all_filenames) = next(os.walk(path))\n for f in all_filenames:\n if f.startswith(base) and f.endswith(ext) and ('merge' not in f):\n filenames.append(os.path.join(path, f))\n elif type(base) == list:\n for f in base:\n filenames.append(os.path.join(path, f))\n else:\n print('Invalid file type. Return None')\n return None\n return np.sort(filenames)\n\n\n\n\n\ndef average_scans(path, base, ext=''):\n filenames = filenames_from_dir(path, base=base, ext=ext)\n header_av = '# merge\\n'\n path_av =os.path.join(path, base + ' merged' + ext)\n # define energy grid and read the data to merge\n n = len(filenames)\n energy_lo = np.zeros(n)\n energy_hi = np.zeros(n)\n df_list = []\n for i, f in enumerate(filenames):\n df, header = load_binned_df_from_file(f)\n df_list.append(df)\n energy_lo[i] = df.iloc[:, 0].min()\n energy_hi[i] = df.iloc[:, 0].max()\n _, new_line = os.path.split(f)\n header_av += '# ' + new_line + '\\n'\n\n energy_lo = energy_lo.max()\n energy_hi = energy_hi.min()\n E = np.array(df_list[0].iloc[:, 0])\n E = E[(E >= energy_lo) & (E <= energy_hi)]\n\n # create new df\n idx = pd.Index(np.arange(E.size))\n columns = df_list[0].columns\n df_av = pd.DataFrame( index=idx, columns=columns)\n df_av.iloc[:, 0] = E\n df_av.iloc[:, 1:] = 0\n\n\n # average\n for each_df in df_list:\n data = np.array(each_df.iloc[:, 1:])\n n_cols = data[0, :].size\n E_cur = np.array(each_df.iloc[:, 0])\n data_int = np.array([np.interp(E, E_cur, data[:, i]) for i in range(n_cols)]).T\n df_av.iloc[:, 1:] += data_int\n df_av.iloc[:, 1:] /= n\n\n columns_str = ' '.join(columns)\n fmt = '%12.6f ' + (' '.join(['%12.6e' for i in range(len(columns) - 1)]))\n np.savetxt(path_av,\n df_av.values,\n delimiter=\" \",\n fmt=fmt,\n header=f'# {columns_str}',\n comments=header_av)\n # dfgd\n # save_binned_df_as_file(path_av, df_av, header_av)\n\n \n # plt.figure(1)\n # plt.clf()\n # for each_df in df_list:\n # plt.plot(each_df['energy'], each_df['iff'])\n # plt.plot(df_av['energy'], df_av['iff'], 'r-')\n # dfgef\n\n\n\n# def test_interpolation(fpath):\n\n\n# def read_offsets_from_folder(folder):\n# files = filenames_from_dir(folder,base='', ext='.dat')\n# gains = np.array([3, 4, 5, 6, 7])\n# data_dict = {'apb_ave_ch1_mean' : [[], [], [], [], []],\n# 'apb_ave_ch2_mean' : [[], [], [], [], []],\n# 'apb_ave_ch3_mean' : [[], [], [], [], []],\n# 'apb_ave_ch4_mean' : [[], [], [], [], []],\n# 'apb_ave_ch5_mean' : [[], [], [], [], []],\n# 'apb_ave_ch6_mean' : [[], [], [], [], []],\n# 'apb_ave_ch7_mean' : [[], [], [], [], []],\n# 'apb_ave_ch8_mean' : [[], [], [], [], []]}\n#\n# for file in files:\n# df = pd.read_csv(file)\n# this_gain = int(file[-5])\n# idx_gain = np.where(this_gain == gains)[0][0]\n# for key in data_dict.keys():\n# offset_value = df[key].values[0]\n# # print(key, idx_gain)\n# data_dict[key][idx_gain].append(offset_value)\n#\n# return gains, data_dict\n#\n#\n#\n# ggg = dd['apb_ave_ch3_mean'][1]\n# plt.figure(1)\n# plt.close()\n# plt.plot(ggg, 'k.')\n# plt.plot([0, len(ggg)], [np.median(ggg), np.median(ggg)], 'r-')\n#\n# out_dict = {}\n# for key in dd.keys():\n# bla = {}\n# for i, gain in enumerate(gains):\n# bla[int(gain)] = float(np.median(dd[key][i]))\n# out_dict[key] = bla\n","sub_path":"xas/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":3898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"113910983","text":"from odoo import models, fields, api, _\nfrom odoo.exceptions import UserError\n\n\nclass Picking(models.Model):\n _inherit = \"stock.picking\"\n \n @api.multi\n def button_validate(self):\n\n for rec in self:\n source_location = rec.location_id\n if rec.picking_type_id and rec.picking_type_id.code == 'outgoing':\n for move_rec in rec.move_lines:\n if self.env['stock.quant']._get_available_quantity(move_rec.product_id,source_location,lot_id=None, package_id=None, owner_id=None, strict=False) < move_rec.quantity_done:\n raise UserError(_('%s quantity is not enough!' %(move_rec.product_id.name)))\n return super(Picking, self).button_validate()\n","sub_path":"de_restrict_unavaiable_stock/models/picking.py","file_name":"picking.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"86408297","text":"#Crie um programa que leia vários números inteiros pelo teclado. O programa qusó vai parar quando o usuário digitar o valor 999,\n# que é a condição de parada. No final mostre quantos números foram digitados e qual foi a soma entre eles.\nn = 0\ns = 0\nc = 0\nwhile n != 999:\n n = int(input('Digite um número: '))\n s += n\n c += 1\nprint('Foram digitados {} números, e a soma entre eles é de {}'.format(c-1, s - 999))","sub_path":"ex64.py","file_name":"ex64.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"333326022","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 25 11:40:23 2017\n\n@author: antoinemovschin\n\nRecherche de features d'intérêt\n\n\"\"\"\n\n\n\nfrom xgb1 import add_features, create_train_test_sets, crossval\n\n\n\n\ndef add_priceoverbedbath (df):\n df = add_features(df)\n df[\"price_over_bedbath\"] = df['price'] / (df['bathrooms'] + df['bedrooms'])\n df[\"price_over_bedbath\"] = [ np.min([1000000, x]) for x in df['price_over_bedbath'] ]\n return df\n\ndef add_price2 (df):\n df = add_priceoverbedbath(df)\n df[\"price2\"] = df[\"price\"].apply(lambda x: x**2)\n return df\n\ndef add_bed2 (df):\n df = add_priceoverbedbath(df)\n df[\"bedrooms2\"] = df[\"bedrooms\"].apply(lambda x: x**2)\n return df\n\ndef add_bath2 (df):\n df = add_priceoverbedbath(df)\n df[\"bathrooms2\"] = df[\"bathrooms\"].apply(lambda x: x**2)\n return df\n\ndef add_priceoverbed (df):\n df = add_priceoverbedbath(df)\n df[\"price_over_bed\"] = df['price'] / df['bedrooms']\n df[\"price_over_bed\"] = [ np.min([1000000, x]) for x in df['price_over_bed'] ]\n return df\n\ndef add_priceoverbath (df):\n df = add_priceoverbedbath(df)\n df[\"price_over_bath\"] = df['price'] / df['bathrooms']\n df[\"price_over_bath\"] = [ np.min([1000000, x]) for x in df['price_over_bath'] ]\n return df\n\n\nadders = [\n add_price2,\n add_bed2,\n add_bath2,\n add_priceoverbed,\n add_priceoverbath,\n ]\nadded = [\n [\"price_over_bedbath\", \"price2\"],\n [\"price_over_bedbath\", \"bedrooms2\"],\n [\"price_over_bedbath\", \"bathrooms2\"],\n [\"price_over_bedbath\", \"price_over_bed\"],\n [\"price_over_bedbath\", \"price_over_bath\"],\n [\"price_over_bedbath\", \"price_over_bedbath\"],\n ]\n\nres_cv = {'add_priceoverbedbath': 0.54511926214524087}\nfor n in range(len(adders)):\n fct = adders[n]\n feat = added[n]\n print(fct.func_name)\n X_train, y_train, X_test = create_train_test_sets(preprocess = fct, features_to_add = feat)\n cv_scores = crossval(X_train, y_train, 5)\n print('CV score: log_loss = ' + str(np.mean(cv_scores)))\n res_cv[fct.func_name] = np.mean(cv_scores)\n\n\n\n\n","sub_path":"xgb_feat2.py","file_name":"xgb_feat2.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"639426416","text":"#!/usr/bin/env python\n\nimport argparse\nimport csv\nimport json\nimport os\nimport sys\n\nfrom AntimicrobialResistance.Result import AntimicrobialResistanceGenomicAnalysisResult\n'''\nAminoglycoside: {\naminoglycoside: {\naac(2')-Ic_1_U72714: {\nresistance_gene: \"aac(2')-Ic\",\nidentity: 100,\nHSP_length: 546,\ntemplate_length: 546,\nposition_in_ref: \"1..546\",\ncontig_name: \"NZ_KK328502.1 Mycobacterium tuberculosis M1325 adOYl-supercont1.3, whole genome shotgun sequence\",\npositions_in_contig: \"314193..314738\",\nnote: \"1\",\naccession: \"U72714\",\npredicted_phenotype: \"Aminoglycoside resistance\",\ncoverage: 100,\nhit_id: \"NZ_KK328502.1 Mycobacterium tuberculosis M1325 adOYl-supercont1.3, whole genome shotgun sequence:314193..314738:aac(2')-Ic_1_U72714:100.000000\"\n}\n}\n},\n'''\nFIELD_MAP_RESFINDER = {\n 'resistance_gene': 'gene_symbol',\n 'identity': 'sequence_identity',\n 'HSP_length': None,\n 'template_length': None,\n 'position_in_ref': None,\n 'contig_name': 'contig_id',\n 'positions_in_contig': None,\n 'note': None,\n 'accession': 'reference_accession',\n 'predicted_phenotype': 'drug_class',\n 'coverage': 'percent_coverage',\n 'hit_id': None,\n '_start': 'start', # decomposed from positions_in_contig field e.g \"314193..314738\"\n '_stop': 'stop', # decomposed from positions_in_contig field e.g \"314193..314738\"\n '_strand': 'strand_orientation' # infered from positions_in_contig field\n}\n\ndef _parse_report(path_to_report):\n \"\"\"\n Args:\n path_to_report (str): Path to the report file.\n Returns:\n list of dict: Parsed report.\n For example:\n [\n {\n 'file': 'contigs.fa',\n ...\n },\n ...\n ]\n \"\"\"\n report_fieldnames = [\n 'resistance_gene',\n 'identity',\n 'HSP_length',\n 'template_length',\n 'position_in_ref',\n 'contig_name',\n 'positions_in_contig',\n 'note',\n 'accession',\n 'predicted_phenotype',\n 'coverage',\n 'hit_id'\n ]\n\n parsed_report = []\n with open(path_to_report) as report_file:\n reader = csv.DictReader(report_file, fieldnames=report_fieldnames, delimiter='\\t')\n next(reader) # skip header\n integer_fields = ['HSP_length', 'template_length']\n float_fields = ['identity', 'coverage']\n for row in reader:\n for key in integer_fields:\n row[key] = int(row[key])\n for key in float_fields:\n row[key] = float(row[key])\n parsed_report.append(row)\n return parsed_report\n\ndef parse_report(path_to_report):\n \"\"\"\n Args:\n path_to_report (str): Path to the report file.\n Returns:\n list of dict: Parsed report.\n For example:\n [\n {\n 'file': 'contigs.fa',\n ...\n },\n ...\n ]\n \"\"\"\n report_fieldnames = [\n 'resistance_gene',\n 'identity',\n 'HSP_length',\n 'template_length',\n 'position_in_ref',\n 'contig_name',\n 'positions_in_contig',\n 'note',\n 'accession',\n 'predicted_phenotype',\n 'coverage',\n 'hit_id'\n ]\n\n parsed_report = []\n integer_fields = ['HSP_length', 'template_length']\n float_fields = ['identity', 'coverage']\n try:\n with open(os.path.join(path_to_report), 'r') as jfile:\n j = json.load(jfile)\n except Exception as e:\n print(e)\n exit()\n row = {}\n for drug_class in j[\"resfinder\"][\"results\"]:\n if j[\"resfinder\"][\"results\"][drug_class][drug_class.lower()] != \"No hit found\":\n for k in j[\"resfinder\"][\"results\"][drug_class][drug_class.lower()]:\n for v in (j[\"resfinder\"][\"results\"][drug_class][drug_class.lower()][k]):\n if v in report_fieldnames:\n if v in integer_fields:\n row[v] = int(j[\"resfinder\"][\"results\"][drug_class][drug_class.lower()][k][v])\n elif v in float_fields:\n row[v] = float(j[\"resfinder\"][\"results\"][drug_class][drug_class.lower()][k][v])\n elif v == 'positions_in_contig':\n # decompose to get start and stop\n coordinates = j[\"resfinder\"][\"results\"][drug_class][drug_class.lower()][k][v].split(\"..\")\n _start = int(coordinates[0])\n _stop = int(coordinates[1])\n _strand = \"+\"\n if _start < _stop:\n _strand = \"-\"\n row[\"_start\"] = _start\n row[\"_stop\"] = _stop\n row[\"_strand\"] = _strand\n # print(_start, _stop, _strand)\n else:\n row[v] = j[\"resfinder\"][\"results\"][drug_class][drug_class.lower()][k][v]\n parsed_report.append(row)\n row = {}\n return parsed_report\n\ndef prepare_for_amr_class(parsed_report, additional_fields={}):\n input_for_amr_class = {}\n \n for key, value in additional_fields.items():\n input_for_amr_class[key] = value\n\n for field, amr_result_field in FIELD_MAP_RESFINDER.items():\n if amr_result_field:\n input_for_amr_class[str(amr_result_field)] = parsed_report[str(field)]\n\n return input_for_amr_class\n\n\ndef main(args):\n parsed_report = parse_report(args.report)\n # print(parsed_report)\n # exit(\"??\")\n additional_fields = {}\n additional_fields['analysis_software_name'] = \"ResFinder\"\n if args.sample_id:\n additional_fields['sample_id'] = args.sample_id\n if args.analysis_software_version:\n additional_fields['analysis_software_version'] = args.analysis_software_version\n if args.reference_database_version:\n additional_fields['reference_database_version'] = args.reference_database_version\n\n amr_results = []\n for result in parsed_report:\n amr_class_input = prepare_for_amr_class(result, additional_fields)\n amr_result = AntimicrobialResistanceGenomicAnalysisResult(amr_class_input)\n amr_results.append(amr_result)\n\n if args.format == 'tsv':\n fieldnames = amr_results[0].__dict__.keys()\n writer = csv.DictWriter(sys.stdout, delimiter='\\t', fieldnames=fieldnames, lineterminator=os.linesep)\n writer.writeheader()\n for result in amr_results:\n writer.writerow(result.__dict__)\n elif args.format == 'json':\n print(amr_results)\n else:\n print(\"Unknown output format. Valid options are: csv or json\")\n exit(1)\n\ndef create_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"report\", help=\"Input resfinder report\")\n parser.add_argument(\"--format\", default=\"tsv\", help=\"Output format (tsv or json)\")\n parser.add_argument(\"--sample_id\", help=\"An identifier for the sample that is the subject of the analysis.\")\n parser.add_argument(\"--analysis_software_version\", help=\"Version of resfinder used to generate the report\")\n parser.add_argument(\"--reference_database_version\", help=\"Database version used to generate the report\")\n return parser\n\ndef run():\n parser = create_parser()\n args = parser.parse_args()\n main(args)\n\nif __name__ == '__main__':\n run()\n","sub_path":"parsers/deprecated/resfinder_report_parser.py","file_name":"resfinder_report_parser.py","file_ext":"py","file_size_in_byte":7423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"285281133","text":"import os\nimport tornado\n\nfrom . import handlers\nfrom prophetly.utils import exceptions, sys_info, signature\n\nif sys_info.version() == 2:\n import SocketServer as socket_server\nelif sys_info.version() == 3:\n import socketserver as socket_server\n\n\nclass ApplicationServer(object):\n def __init__(self, arguments):\n self.port = 9009\n self.server = None\n\n self.settings = {\n 'static_path': os.path.join(os.path.dirname(__file__), 'static'),\n 'upload_path': os.path.join(os.getcwd(), 'uploads'),\n 'port': self.port,\n }\n\n self.initialize(arguments)\n\n def initialize(self, arguments):\n # custom 'upload_path' supplied as command line flag\n _path_arg = arguments['--upload_path']\n\n # custom 'port' supplied as command line flag\n _port_arg = arguments['--port']\n\n if _path_arg is not None:\n self.settings['upload_path'] = _path_arg\n\n if _port_arg is None:\n pass\n elif _port_arg is not None and _port_arg.isdigit():\n self.port = int(_port_arg)\n else:\n raise exceptions.PortInvalid('port \\\"{0}\\\" is invalid'.format(_port_arg))\n\n self.settings['port'] = self.port\n\n def _create_server(self):\n return tornado.web.Application([\n (r\"/\", handlers.MainHandler),\n (r\"/upload\", handlers.UploadHandler),\n (r\"/column/(.+)\", handlers.ColumnHandler),\n (r\"/data\", handlers.DataHandler),\n (r\"/filedata/(.+)\", handlers.FileDataHandler),\n ], **self.settings)\n\n def start(self):\n self.server = self._create_server()\n\n try:\n self.server.listen(self.port)\n except socket_server.socket.error as e:\n if e.args[0] == 48:\n raise exceptions.PortUnavailable('port \\\"{0}\\\" is already in use'.format(self.port))\n\n signature.package_signature(self.port)\n\n tornado.ioloop.IOLoop.instance().start()\n\n def stop(self):\n tornado.ioloop.IOLoop.instance.stop()\n","sub_path":"prophetly/server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"283187170","text":"def Map (func, ls):\n\tresult = []\n\tfor i in ls:\n\t\tresult.append(func(i))\n\treturn result\n\ndef Reduce (func, ls):\n\tresult = ls[0]\n\tfor i in ls[1:]:\n\t\tresult = func(result, i)\n\treturn result\n\ndef Filter (func, ls):\n\tresult = []\n\tfor i in ls:\n\t\tif func(i):\n\t\t\tresult.append(func(i))\n\treturn result\n\n\ndef main ():\n\n\tlst = [1, 2, 3, 4, 5, 3, 1000, 4]\n\tprint (Map(lambda a : a**2, lst))\n\n\tprint (Reduce(lambda a, b : a if a > b else b, lst))\n\n\tprint (Filter(lambda a : a if a % 2 == 0 else None, lst))\n\nmain()","sub_path":"31.py","file_name":"31.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"16143483","text":"# coding=utf-8\nimport logging.config\n\nfrom flask import g, request\ntry:\n import flask_debugtoolbar\nexcept ImportError:\n pass\n\nfrom . import (\n config,\n errors,\n auth,\n public,\n)\nfrom .app import app\n\n\n@app.before_request\ndef set_user_locale(*args, **kwargs):\n if hasattr(g, 'user') and g.user:\n request.locale = g.user.locale or config.DEFAULT_LOCALE\n request.tzinfo = g.user.tzinfo or config.DEFAULT_TIMEZONE\n else:\n request.locale = config.DEFAULT_LOCALE\n request.tzinfo = config.DEFAULT_TIMEZONE\n g.lang = request.locale.split('-')[0].lower()\n\n\napp.register_blueprint(public.views.bp.bp, url_prefix='')\n\n\napp.add_url_rule('/', 'index', build_only=True, redirect_to='/')\n\nlogging.config.dictConfig(config.LOGGING_CONFIG)\ntoolbar = flask_debugtoolbar.DebugToolbarExtension(app)\n\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"webapp/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"348821332","text":"from SubCritters import *\n\ndef main():\n\n critterType = str(input(f'what type of Critter would you like?: '))\n name = str(input('Name your Critter: '))\n\n if critterType == 'Dog':\n bob = Dog(name)\n elif critterType == 'Cat':\n bob = Cat(name)\n elif critterType == 'Rat':\n bob = Rat(name)\n\n while bob.isAlive() and bob.hasWon() != True:\n action = input(f'What would you like {name} to do?')\n if action == 'eat':\n bob.feed()\n elif action == 'sleep':\n bob.sleeps()\n elif action == 'exercise':\n bob.exercise()\n bob.display()\n\n if bob.hasWon():\n print(f'{name} has reached peak physical fitness.')\n print(f'{name} has achieved victory')\n else:\n print(f'{name} has died.')\n\nif __name__ == '__main__': # if I have started running my code from this file then run the function\n main()\n","sub_path":"App.py","file_name":"App.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"479063332","text":"import pandas as pd\nimport numpy as np\nfrom api.models import Poem, Citate\n\ndef run():\n csv_text_data = pd.read_csv('./data/poem.csv')\n data = csv_text_data.to_dict(orient='records')\n def cleaned_row(row):\n cleaned = row\n cleaned['date_to'] = int(row['date_to']) if not np.isnan(\n row['date_to']) else None\n cleaned['date_from'] = int(row['date_from']) if not np.isnan(\n row['date_from']) else None\n return cleaned\n\n bulk_data = [Poem(**cleaned_row(row)) for row in data]\n items = Poem.objects.bulk_create(\n bulk_data, batch_size=None, ignore_conflicts=True)\n\n print(f'Inserted {len(items)} poems')\n\n\n","sub_path":"scripts/init_poem.py","file_name":"init_poem.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"301654405","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport math\n\npath = r'vegeta.jpg' # enter image path here\nimg = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\nf = np.fft.fft2(img)\nfshift = np.fft.fftshift(f)\nheight = np.size(fshift, 0)\nwidth = np.size(fshift, 1)\ncenter_h, center_w = int(height/2), int(width/2)\ncutoff = 200\norder = 1\n\nH = np.zeros((height, width))\nfor h in range(height):\n\tfor w in range(width):\n\t\tH[h][w] = 1 - math.exp(-(h ** 2 + w ** 2) / (2 * (cutoff ** 2)))\n\noutput = fshift * H\noutput = np.fft.ifftshift(output)\noutput = np.fft.ifft2(output)\noutput = np.abs(output)\n\nplt.subplot(221),plt.imshow(H, cmap='gray')\nplt.title('Gaussian High Filter, cutoff=200'), plt.xticks([]), plt.yticks([])\nplt.subplot(223),plt.imshow(output, cmap='gray')\nplt.title('Output, cutoff=15'), plt.xticks([]), plt.yticks([])\n\n\nH = np.zeros((height, width))\nfor h in range(height):\n\tfor w in range(width):\n\t\tH[h][w] = 1 - math.exp(-(h ** 2 + w ** 2) / (2 * (cutoff ** 2)))\n\noutput = fshift * H\noutput = np.fft.ifftshift(output)\noutput = np.fft.ifft2(output)\noutput = np.abs(output)\n\n\nplt.subplot(222),plt.imshow(H, cmap='gray')\nplt.title('Gaussian High Pass Filter, cutoff=500'), plt.xticks([]), plt.yticks([])\nplt.subplot(224),plt.imshow(output, cmap='gray')\nplt.title('Output, cutoff=150'), plt.xticks([]), plt.yticks([])\nplt.show()","sub_path":"GaussianHighPass.py","file_name":"GaussianHighPass.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"547253901","text":"a={1:1,2:2,3:3}\nb=int(input(\"enter\"))\nprint(type(b))\nif b in a:\n\ta.pop(b)\n\nprint(a)\n\nmyDict = {'a':1,'b':2,'c':3,'d':4}\nprint(myDict)\nif 'a' in myDict: \n del myDict['a']\nprint(myDict)\n\n","sub_path":"python_practice/W3_dict/eg_12.py","file_name":"eg_12.py","file_ext":"py","file_size_in_byte":188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"493167543","text":"#\n# @lc app=leetcode id=46 lang=python\n#\n# [46] Permutations\n#\n# https://leetcode.com/problems/permutations/description/\n#\n# algorithms\n# Medium (53.51%)\n# Total Accepted: 343K\n# Total Submissions: 640.8K\n# Testcase Example: '[1,2,3]'\n#\n# Given a collection of distinct integers, return all possible permutations.\n#\n# Example:\n#\n#\n# Input: [1,2,3]\n# Output:\n# [\n# ⁠ [1,2,3],\n# ⁠ [1,3,2],\n# ⁠ [2,1,3],\n# ⁠ [2,3,1],\n# ⁠ [3,1,2],\n# ⁠ [3,2,1]\n# ]\n#\n#\n#\nclass Solution(object):\n def solver(self, nums, result, tmp_res):\n if len(nums) == 0:\n if tmp_res not in result:\n result.append(tmp_res)\n return\n pre = -9999\n for i in range(len(nums)):\n if pre == nums[i]:\n continue\n self.solver(nums[:i]+nums[i+1:], result, tmp_res+[nums[i]])\n #if i > 0:\n # self.solver(nums[:i]+nums[i+1:], result,[nums[i]]+tmp_res, length)\n\n\n def permute(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n res = []\n self.solver(nums, res, [])\n return res\n\n\n","sub_path":"46.permutations.py","file_name":"46.permutations.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"558929749","text":"import argparse\nimport os\nimport sys\n\nimport numpy as np\n\nfrom qr_imdb.models import model_lstm, model_cudnnlstm, model_qrnn, \\\n model_qrnn_alt\nfrom qr_imdb.train_eval import train_eval_loop\nfrom utils.glove_embedding import download_glove, generate_embedding\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--glovepath\",\n help=\"\"\"path to the GloVe embedding txt file.\n it is needed only when run for the first time\n to generate word embedding matrix.\"\"\",\n default='./data/glove.840B.300d.txt'\n )\n parser.add_argument(\n \"--model\",\n help=\"which NN architecture to use\",\n choices=['qrnn', 'qrnn_alt', 'lstm', 'cudnnlstm'],\n default='qrnn'\n )\n parser.add_argument(\n \"--epochs\",\n help=\"number of epoch to train for\",\n default='10',\n type=int\n )\n parser.add_argument(\n \"--logdir\",\n help=\"directory used for summaries and saves\",\n )\n args = parser.parse_args(sys.argv[1:])\n\n if args.logdir is None:\n args.logdir = 'model_' + args.model\n\n if not os.path.exists(\"./data/embedding.npy\"):\n if args.glovepath is None:\n if not os.path.exists('./data/glove.840B.300d.txt'):\n download_glove()\n generate_embedding('./data/glove.840B.300d.txt')\n else:\n generate_embedding(args.glovepath)\n embed_weights = np.load(\"./data/embedding.npy\")\n\n model_map = {\n 'qrnn': model_qrnn,\n 'qrnn_alt': model_qrnn_alt,\n 'lstm': model_lstm,\n 'cudnnlstm': model_cudnnlstm\n }\n train_eval_loop(\n args.epochs,\n embed_weights,\n model_map[args.model],\n args.logdir)\n","sub_path":"qrnn/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"123056614","text":"\"\"\"\nflat_track, part of chipFish, and glbase3\n\n2008-2019 oAxiom\n\nTODO:\n. never (?) seen in the wild, but it is presumably possible to have blocks with missing blockIDs \n that would throw an error in __Get_block()\n. Related to the above. blockID n:0 is almost always empty and not required, but gets committed anyway.\n\n\"\"\"\n\nimport pickle, sys, os, struct, configparser, math, sqlite3, zlib # renamed to configparser in >2.6\n\nfrom .location import location\nfrom .data import positive_strand_labels, negative_strand_labels\n\nfrom array import array\nfrom .base_track import base_track\nfrom .draw import draw\nfrom .progress import progressbar\nfrom . import config\n\nimport numpy\nimport matplotlib.pyplot as plot\n\nfrom .track import track # All the benefits of track.\n\nTRACK_BLOCK_SIZE = 1000000 # should go in opt, or in META? required on a per-flat basis.\nCACHE_SIZE = 100000 # maximum number of blocks to keep in memory.\n\nclass flat_track(base_track):\n def __init__(self, name=None, new=False, filename=None, bin_format=None):\n \"\"\"\n **Purpose**\n track definition, used for things like sequence reads across the genome\n\n **Arguments**\n name (string)\n name for the track, if not specified, it takes it from the meta_data\n If a new bd then it defaults to filename\n\n filename (string)\n directory location of the track file.\n only respected if dir_name is set.\n\n bin_format (Optional, default=None, required if new=False)\n the format to store the data in,\n This is the same format as the python array, so \"i\" = integer,\n \"f\" = float\n\n \"\"\"\n base_track.__init__(self, name, new, filename)\n\n if new: assert bin_format, 'if new=True you must specify a bin_format'\n\n if bin_format: # Change the bin_format of the db.\n self.meta_data[\"bin_format\"] = bin_format\n self.bin_format = bin_format\n else:\n self.bin_format = self.meta_data[\"bin_format\"] # I unload this one\n\n self.bin_len = struct.calcsize(self.bin_format)\n self.block_size = TRACK_BLOCK_SIZE # size of the blocks\n\n if new:\n self.__setup_tables(filename)\n\n # internals\n self.cache = {}\n self.cacheQ = []\n\n # Update any metadata etc, primarily the bin_format\n self._save_meta_data()\n\n def __repr__(self):\n return(\"glbase.flat_track\")\n\n def __setup_tables(self, filename):\n \"\"\"\n No pre-defined file - I want a new database track.\n \"\"\"\n # If I make it here then base_genelist has made self._connection valid.\n\n c = self._connection.cursor()\n\n c.execute(\"CREATE TABLE data (blockID TEXT PRIMARY KEY, array TEXT)\")\n\n self._connection.commit()\n c.close()\n\n def add_read(self, loc, strand=\"+\", increment=1):\n \"\"\"\n **Purpose**\n Add a location to the track.\n Increments the score by 'increment' from loc[\"left\"] to\n loc[\"right\"]\n\n **Arguments**\n loc\n\n strand\n\n increment\n\n **Returns**\n True, if completes succesfully, or exception.\n \"\"\"\n left_most_block = int(abs(math.floor(loc[\"left\"] / self.block_size)))\n right_most_block = int(abs(math.ceil((loc[\"right\"]+1) / self.block_size)))\n\n blocks_required = [\"%s:%s\" % (loc[\"chr\"], b) for b in range(left_most_block * self.block_size, right_most_block * self.block_size, self.block_size)]\n\n for blockID in blocks_required:\n # this is the span location of the block\n #block_loc = location(chr=blockID.split(\":\")[0], left=blockID.split(\":\")[1], right=int(blockID.split(\":\")[1])+self.block_size-1)\n\n # check if the block already exists\n if not self.__has_block(blockID): # not present, make a new one.\n self.__new_block(blockID)\n else:\n if not blockID in self.cacheQ: # not on cache, add it;\n self.cacheQ.insert(0, blockID) # put the ID at the front.\n self.cache[blockID] = self.__get_block(blockID)\n # block should now be on cache and accesable.\n\n bleft = int(blockID.split(\":\")[1])\n lleft = int(loc[\"left\"])\n lright = int(loc[\"right\"])\n # modify the data\n for pos in range(self.block_size): # iterate through the array.\n local_pos = bleft + pos # only require \"left\"\n # some funny stuff here:\n # right is inc'd by 1\n # as that is what is usually expected from 10-20.\n # (i.e. coords are NOT 0-based and are closed).\n if local_pos >= lleft and local_pos <= lright: # within the span to increment.\n self.cache[blockID][pos] += increment\n\n self.__flush_cache()\n return(True)\n\n def add_score(self, loc=None, chromosome=None, left=None, right=None, score=0, all_in_mem=False, **kargs):\n \"\"\"\n **Purpose**\n adds a already known score at a particular location (or span). This will overwrite any previously\n exisiting value stored in the db.\n\n **Arguments**\n loc\n location.\n\n score\n the value to insert at that location\n\n **Returns**\n Nothing\n \"\"\"\n if loc:\n chrom = loc[\"chr\"]\n left = loc[\"left\"]\n right = loc[\"right\"]\n else:\n chrom = chromosome\n lleft = int(left)\n lright = int(right)\n\n left_most_block = int(abs(math.floor(left / self.block_size)))\n right_most_block = int(abs(math.ceil((right+1) / self.block_size)))\n\n blocks_required = [\"%s:%s\" % (chrom, b) for b in range(left_most_block * self.block_size, right_most_block * self.block_size, self.block_size)]\n\n for blockID in blocks_required:\n # this is the span location of the block\n #block_loc = location(chr=blockID.split(\":\")[0], left=blockID.split(\":\")[1], right=int(blockID.split(\":\")[1])+self.block_size-1)\n\n if blockID not in self.cacheQ:\n if not self.__has_block(blockID): # A db hit, but only a check\n self.__new_block(blockID) # no db hit\n else: # retrieve from db, big db hit\n if not blockID in self.cacheQ: # not on cache, get it;\n self.cacheQ.insert(0, blockID) # put the ID at the front.\n self.cache[blockID] = self.__get_block(blockID)\n\n # block should now be on cache and accesable.\n bleft = int(blockID.split(\":\")[1])\n bright = bleft + TRACK_BLOCK_SIZE\n # modify the data\n #print blockID, lleft, lright, bleft, bright, score,\n for pos in range(lleft, lright): # iterate through the array.\n local_pos = pos - bleft # only require \"left\"\n # some funny stuff here:\n # right is inc'd by 1\n # as that is what is usually expected from 10-20.\n # (i.e. coords are NOT 0-based and are closed).\n if local_pos >= 0 and local_pos < TRACK_BLOCK_SIZE: # within the span to increment.\n self.cache[blockID][local_pos] = score\n #print local_pos, local_pos >= 0 and local_pos <= TRACK_BLOCK_SIZE\n #print self.cache[blockID]\n if not all_in_mem:\n self.__flush_cache() # I can go over the CACHE in this routine.\n # But putting this here means I don't have to hit the db every blockID\n # Should help speed where I use a lot of new blocks.\n return(None)\n\n def add_chromosome_array(self, chromosome=None, arr=None):\n '''\n **Purpose**\n Support for loading of complete chromosome arrays.\n\n This will overwrite any existing data.\n\n **Arguments**\n chromsome (Required)\n chromsome to insert array into\n\n arr (Required)\n a Python list of scores for the entire chromosome. Should start at position 0,\n and extend for the complete chromosomes.\n '''\n assert chromosome, 'You must specify a chromosome'\n assert arr, 'You must provide the chromsosome data as arr'\n\n chrom = chromosome.replace('chr', '')\n lleft = 0\n lright = len(arr)\n\n # Find the first non-zero value, and go from there.\n left_most_block = int(abs(math.floor(lleft / self.block_size))) # bodge for now\n right_most_block = int(abs(math.ceil((lright+1) / self.block_size)))\n\n blocks_required = [\"%s:%s\" % (chrom, b) for b in range(left_most_block * self.block_size, right_most_block * self.block_size, self.block_size)]\n\n for blockID in blocks_required:\n #print blockID\n #This routine should only be used at creation time, so we can assume a new block is required\n self.__new_block(blockID) # all in mem.\n\n # block should now be on cache and accesable.\n bleft = int(blockID.split(\":\")[1])\n bright = bleft + TRACK_BLOCK_SIZE\n #print blockID, bleft, bright, arr[bleft:bright], array(self.bin_format, arr[bleft:bright])\n self.cache[blockID] = array(self.bin_format, arr[bleft:bright])\n # modify the data\n #print blockID, lleft, lright, bleft, bright\n '''\n for pos in xrange(bleft, bright): # iterate through the array.\n local_pos = pos - bleft # pos in blockID coords\n # some funny stuff here:\n # right is inc'd by 1\n # as that is what is usually expected from 10-20.\n # (i.e. coords are NOT 0-based and are closed).\n if pos >= 0 and pos < lright: #stop it falling of arr\n self.cache[blockID][local_pos] = arr[pos]\n\n #print local_pos, local_pos >= 0 and local_pos <= TRACK_BLOCK_SIZE\n '''\n #print\n #print self.cache[blockID]\n self.__flush_cache(all=True) # Flush everything to help with memory usage\n # But putting this here means I don't have to hit the db every blockID\n # Should help speed where I use a lot of new blocks.\n return(None)\n\n def __has_block(self, blockID):\n \"\"\"\n checks if the data base has that block already.\n returns only True or False,\n does not return the block, you must use __get_block()\n to get the actual block.\n \"\"\"\n if blockID in self.cache:\n return(True) # on cache, so must exist.\n\n c = self._connection.cursor()\n c.execute(\"SELECT blockID FROM data WHERE blockID=?\", (blockID, ))\n result = c.fetchone()\n c.close()\n if result:\n return(True)\n return(False)\n\n def __commit_block(self, blockID, data):\n \"\"\"\n update the block with new data.\n commit block to db.\n \"\"\"\n # see if tyhe block is in the database:\n c = self._connection.cursor()\n c.execute(\"SELECT blockID FROM data WHERE blockID=?\", (blockID, ))\n result = c.fetchone()\n\n d = self._format_data(data)\n\n if result: # has a block already, modify it.\n # update the block data.\n\n c.execute(\"UPDATE data SET array=? WHERE blockID=?\", (d, blockID))\n else:\n c.execute(\"INSERT INTO data VALUES (?, ?)\", (blockID, d))\n c.close()\n\n def __new_block(self, blockID, data=None):\n \"\"\"\n add a data block to the db in data table.\n returns only True, does not return the block.\n use self.__get_block() to get a block.\n\n new_block DOES NOT WRITE INTO THE DB!\n You need to flush the cache for that to happen\n \"\"\"\n if not data: # fill a blank entry\n data = array(self.bin_format, [0 for x in range(self.block_size)]) # Numpy arrays may be faster here.\n\n if not blockID in self.cacheQ: # not on cache\n self.cacheQ.insert(0, blockID) # put the ID at the front.\n self.cache[blockID] = data\n\n return(False)\n\n def __flush_cache(self, all=False):\n \"\"\"\n check the cache is not over the size limit. If it is, take the last\n n>CACHE_SIZE entries commit to the db.\n\n \"\"\"\n while len(self.cacheQ) > CACHE_SIZE or (all and self.cacheQ):\n blockID = self.cacheQ.pop()\n self.__commit_block(blockID, self.cache[blockID])\n del self.cache[blockID]\n\n return(True)\n\n def __get_block(self, blockID):\n \"\"\"\n get the block identified by chr and left coordinates and return a Python Object.\n \"\"\"\n if blockID in self.cache:\n return(self.cache[blockID])\n\n # not on the cache. get the block and put it on the cache.\n c = self._connection.cursor()\n c.execute(\"SELECT array FROM data WHERE blockID=?\", (blockID, ))\n result = c.fetchone()\n c.close()\n\n if result:\n # Add it to the cache:\n # This seems to make little difference to speed, and consumes too much memory if >10 flats. (16Gb machine)\n #self.cache[blockID] = self._unformat_data(result[0]) # flats are never too big, so I don't bother flushing the cache\n return(self._unformat_data(result[0]))\n else:\n raise Exception(\"No Block! blockID=%s\" % blockID) # Not possible\n\n def get_total_num_reads(self):\n \"\"\"\n **Purpose**\n Get the total number of reads in this library,\n generally for normalization purposes. Number of tags must be set at creation time,\n not always avaialble for all flats\n \"\"\"\n if 'total_read_count' in self.meta_data:\n return(int(self.meta_data['total_read_count']))\n return(None)\n\n def get(self, loc, strand=\"+\", mask_zero=False, **kargs):\n \"\"\"\n **Purpose**\n get the data between location 'loc'\n\n **Arguments**\n loc (Required)\n a valid location or string location.\n\n strand (Optional, default = \"+\")\n strand, but only valid for stranded tracks\n\n mask_zero (Optional, default=False)\n return a masked numpy array with zeros masked out.\n\n **Returns**\n an 'array('i', [0, 1, 2 ... n])' contiginous array\n \"\"\"\n try:\n if loc[\"chr\"]: pass\n except TypeError: # probably a location string. try to cooerce\n loc = location(loc=loc)\n # Don't catch any exceptions here. Should break.\n\n # get is hitting location too hard. Unfold here:\n c = str(loc['chr'])\n left = int(loc['left'])\n rite = int(loc['right'])\n\n left_most_block = int(abs(math.floor(left / self.block_size)))\n right_most_block = int(abs(math.ceil((rite+1) / self.block_size)))\n\n blocks_required = [\"%s:%s\" % (c, b) for b in range(left_most_block * self.block_size, right_most_block * self.block_size, self.block_size)]\n\n ret_array = [] # faster than array\n\n for blockID in blocks_required:\n # this is the span location of the block\n #block_loc = location(chr=blockID.split(\":\")[0], left=blockID.split(\":\")[1], right=int(blockID.split(\":\")[1])+self.block_size-1)\n block_loc_left = int(blockID.split(\":\")[1]) # this is all you actually need for the block location\n # check if the block already exists\n if self.__has_block(blockID): # it does, get it.\n this_block_array_data = self.__get_block(blockID)\n else: # block not in db, fake a block instead.\n this_block_array_data = [0] * self.block_size\n\n # This feels like it would be a bit slow...\n # Work out the spans to reduce iteration:\n left_most = left - block_loc_left\n if left_most < 0: left_most = 0\n rite_most = rite - block_loc_left\n if rite_most > self.block_size: rite_most = self.block_size\n #print left_most, rite_most\n\n for pos in range(left_most, rite_most): #self.block_size): # iterate through the array.\n local_pos = block_loc_left + pos\n if local_pos >= left and local_pos <= (rite+1): # within the span to increment.\n if pos >= len(this_block_array_data): # stop edge falloffs\n ret_array.append(0)\n else:\n ret_array.append(this_block_array_data[pos])\n if mask_zero:\n mask = []\n for dd in ret_array:\n if int(dd*10000000) == 0: # delete if 10 sig figs close to 0\n mask.append(1)\n else:\n mask.append(0)\n # This may produce a warning, but apparently I can safely ignore it\n ret_array = numpy.ma.masked_array(ret_array, mask=mask)\n return(ret_array)\n\n def get_array_chromosome(self, chrom=None, **kargs): # kargs for compat with trk\n \"\"\"\n **Purpose**\n Get the enrire array for the chromosome chrom.\n\n **Arguments**\n chrom (Required)\n chromsome name to collect.\n\n \"\"\"\n #What is the maximum blockID size?\n c = self._connection.cursor()\n c.execute(\"SELECT blockID FROM data\") # get all blockIDs\n result = c.fetchall()\n # get biggest blockID:\n biggest_block = -1\n for b in result:\n bid, pos = b[0].split(':')\n pos = int(pos)\n if chrom.replace('chr', '') == bid:\n if pos > biggest_block:\n biggest_block = pos\n\n right_most_block = int(abs(math.ceil((biggest_block+1) / self.block_size)))\n\n blocks_required = [\"%s:%s\" % (chrom, b) for b in range(0, right_most_block * self.block_size, self.block_size)] # always in order?\n ret_array = [] # faster than array\n\n for blockID in blocks_required:\n # this is the span location of the block\n #block_loc = location(chr=blockID.split(\":\")[0], left=blockID.split(\":\")[1], right=int(blockID.split(\":\")[1])+self.block_size-1)\n block_loc_left = int(blockID.split(\":\")[1]) # this is all you actually need for the block location\n # check if the block already exists\n if self.__has_block(blockID): # it does, get it.\n this_block_array_data = self.__get_block(blockID)\n else: # block not in db, fake a block instead.\n this_block_array_data = [0] * self.block_size\n\n #print this_block_array_data\n ret_array += this_block_array_data\n\n return(ret_array)\n\n def finalise(self):\n \"\"\"\n {Override)\n I have to override the base_track class\n finalise the database (shrink unused edit space)\n dump useless bits etc.\n You must call this! to finalise the db.\n Or get() will not work!\n This copies the cache onto disk and closes the db.\n \"\"\"\n for blockID in self.cache:\n self.__commit_block(blockID, self.cache[blockID])\n self.cache = {} # Kill caches.\n self.cacheQ = []\n self._save_meta_data()\n self._connection.commit() # commit all the __commit_block()\n base_track.finalise(self)\n\n def pileup(self, genelists=None, filename=None, window_size=None, average=True,\n background=None, mask_zero=False, respect_strand=True, norm_by_read_count=False, **kargs):\n \"\"\"\n **Purpose**\n Draw a set of pileup count scores (averages or cumulative scores)\n\n **Arguments**\n genelists\n A list of genelist with a \"loc\" key\n\n filename\n The filename to save the image to\n\n window_size (Optional, default=None)\n the number of base pairs to use around the centre of the location\n If set to None then it will use the location as specified.\n\n average (Optional, default=True)\n use the average score if set to True (i.e. divide by the number of items)\n Or use the cumulative score (the total) if set to False\n\n background (Optional)\n You can supply a list of background coordinates if you want. The lists\n must contain a \"loc\" key.\n\n mask_zero (Optional, default=False)\n flat_tracks are continuous and must have a value at all base pairs. I fill\n that value with 0\n However, in some flat_tracks 0 actually means 'no data' and I want to ignore\n those values in the pileup. If that is the case for you, set mask_zero to\n True.\n\n \n pileup also respects:\n xlabel - x-axis label\n ylabel - y-axis label\n title - title\n\n respect_strand (Optional, default=False)\n If available, respect the orientation of the strand from the genelist.\n This is useful if you are, say, using the TSS's and want to maintain the\n orientation with respect to the transcription direction.\n\n norm_by_read_count (Optional, default=False)\n If you are not using a norm_factor for this library then you probably want to set this to True.\n It will divide the resulting number of reads by the total number of reads,\n i.e. it will account for differences in library sizes.\n\n **Returns**\n (data, back)\n The data from the line graph.\n back will be the average of the list of background peaks, but data\n will be the last entry in the peaklists (if a list of peaks) or will correspond to the\n only peaklist provided. e.g.:\n\n data, back = pileup(genelists=[data1, data2, THISDATAWILLBERETURNED] ...)\n\n or:\n\n data, back = pileup(genelists=THISDATAWILLBERETURNED ...)\n \"\"\"\n assert genelists, \"genelists is None?\"\n\n if not isinstance(genelists, list):\n genelists = [genelists] # make a one item'd list\n\n if background:\n if not isinstance(background, list):\n background = [background] # make a one item'd list\n\n read_count = 1.0\n if norm_by_read_count:\n read_count = float(self.get_total_num_reads())\n\n all_hists = {}\n\n # flats have lazy setup of draw:\n if not self._draw:\n self._draw = draw(self)\n\n fig = self._draw.getfigure(**kargs)\n ax = fig.add_subplot(111)\n\n x = None\n if window_size:\n x = numpy.arange(window_size*2) - (window_size*2)//2\n\n if window_size:\n loc_span = window_size*2\n else:\n loc_span = len(genelists[0].linearData[0][\"loc\"]) # I have to assume all locs are identical.\n\n for gl in genelists:\n if window_size:\n hist = numpy.zeros(window_size*2)\n counts = numpy.zeros(window_size*2)\n gl = gl.pointify().expand('loc', window_size)\n else:\n x = numpy.arange(loc_span) - loc_span//2\n hist = numpy.zeros(loc_span)\n counts = numpy.zeros(loc_span) # used to get the average.\n\n for i in gl:\n a = self.get(i[\"loc\"])#[0:window_size*2] # mask_zero is NOT asked of here. because I need to ignore zeros for the average calculation (below)\n\n if respect_strand:\n # positive strand is always correct, so I leave as is.\n # For the reverse strand all I have to do is flip the array.\n if i[\"strand\"] in negative_strand_labels:\n a = a[::-1]\n\n if a: # It's possible that get() will return nothing\n # For example if you send bad chromosome names or the locations are nonsensical (things like:\n # chr9_GL000201_RANDOM:-500-1500\n hist += a\n\n if mask_zero: # surely a better way of doing this...\n t = numpy.zeros(loc_span)\n for ee, xx in enumerate(a):\n if xx > 0:\n t[ee] = 1.0\n counts += t\n\n if average and mask_zero:\n hist /= counts\n elif average and not mask_zero:\n hist /= len(gl)\n\n if norm_by_read_count:\n hist /= read_count\n\n ax.plot(x, hist, label=gl.name, alpha=0.7)\n all_hists[gl.name] = hist\n\n bkgd = None\n if background:\n if window_size:\n bkgd = numpy.zeros(window_size*2)\n counts = numpy.zeros(window_size*2)\n else:\n bkgd = numpy.zeros(loc_span)\n counts = numpy.zeros(loc_span)\n\n bkgd_items = 0\n p = progressbar(len(background))\n for i, back in enumerate(background):\n for b in back:\n if window_size:\n l = b[\"loc\"].pointify()\n l = l.expand(window_size)\n a = self.get(l)[0:window_size*2]\n else:\n a = self.get(b[\"loc\"])[0:loc_span]\n bkgd_items += 1\n\n if respect_strand:\n # positive strand is always correct, so I leave as is.\n # For the reverse strand all I have to do is flip the array.\n if b[\"strand\"] in negative_strand_labels:\n a = a[::-1]\n\n bkgd += a\n if mask_zero:\n t = numpy.zeros(loc_span)\n for ee, xx in enumerate(a):\n if xx > 0:\n t[ee] = 1.0\n counts += t\n\n if average and mask_zero:\n bkgd /= counts\n elif average and not mask_zero:\n bkgd /= bkgd_items\n\n if norm_by_read_count:\n hist /= read_count\n\n if i == 0: # add only a single legend.\n ax.plot(x, bkgd, color=\"grey\", alpha=0.3, label=\"Random Background\")\n else:\n ax.plot(x, bkgd, color=\"grey\", alpha=0.3)\n\n # reset arrays\n bkgd = numpy.zeros(len(bkgd))\n counts = numpy.zeros(len(counts))\n\n p.update(i)\n\n else:\n bkgd = None\n\n ax.axvline(0, ls=\":\", color=\"grey\")\n\n leg = ax.legend()\n [t.set_fontsize(7) for t in leg.get_texts()]\n ax.set_ylabel(\"Magnitude\")\n ax.set_xlabel(\"Base pairs around centre (bp)\")\n\n self._draw.do_common_args(ax, **kargs)\n\n actual_filename = self._draw.savefigure(fig, filename)\n\n config.log.info(\"pileup(): Saved '%s'\" % actual_filename)\n\n return(all_hists, bkgd)\n\n","sub_path":"flat_track.py","file_name":"flat_track.py","file_ext":"py","file_size_in_byte":27435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"316978546","text":"import re\n\ny = 0\ni = []\n\nz = input('')\nz = re.sub(',', '', z)\nz = z.split()\n\nfor x in range(0, len(z)):\n z[y] = int(z[y])\n y += 1\n\ny = 1\n\ndef get_factors(n):\n fList = []\n \n for x in range(1, n + 1):\n if n % x == 0:\n fList.append(x)\n \n return fList\n\nwhile i != z:\n i = get_factors(y)\n y += 1\n\nprint(y - 1)\n","sub_path":"py/mainpy/factorNumber.py","file_name":"factorNumber.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"214226972","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 15 18:26:19 2021\n\n@author: Tracy\n\"\"\"\n\nimport pandas as pd\ndataset = pd.read_csv('./data/prepared.csv')\ntrain = dataset.sample(frac = 0.9)\nprint(train)\ntest = dataset.drop(train.index)\n\ntrain.to_csv('./data/train.csv', index=False)\ntest.to_csv('./data/test.csv', index=False)\n\n\n# dvc run -n split_train_test -d src/split_train_test.py -d data/preprocessed.csv -o data/train.csv -o data/test.csv python src/split_train_test.py","sub_path":"src/split_train_test.py","file_name":"split_train_test.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"390521651","text":"import string\r\n\r\nfrom ciphers import Cipher\r\n\r\n\r\nclass Affine(Cipher):\r\n\r\n def __init__(self, multiply_num=5, add_num=23):\r\n self.multiply_num = multiply_num\r\n self.add_num = add_num\r\n\r\n def __encrypt_logic(self, target_char, base_char):\r\n unicode_diff = ord(target_char) - ord(base_char)\r\n\r\n return chr(((self.multiply_num * unicode_diff + self.add_num) % 26) + ord(base_char))\r\n\r\n def __find_coprime(num):\r\n for i in range(39):\r\n if ((i * num) % 39) == 1:\r\n return i\r\n\r\n def __decrypt_logic(self, target_char, base_char):\r\n unicode_diff = ord(target_char) - ord(base_char)\r\n comprime_num = self.__find_coprime(self.multiply_num)\r\n\r\n return chr(((co_prime * (unicode_diff - self.add_num)) % 26) + ord(base_char))\r\n\r\n def encrypt(self, text):\r\n output = []\r\n\r\n for char in text:\r\n\r\n if char.islower():\r\n output.append(self.__encrypt_logic(char, 'a'))\r\n\r\n else:\r\n output.append(self.__encrypt_logic(char, 'A'))\r\n\r\n return ''.join(output)\r\n\r\n def decrypt(self, text):\r\n output = []\r\n\r\n for char in text:\r\n\r\n if char.islower(): \r\n output.append(self.__decrypt_logic(char, 'a'))\r\n\r\n else:\r\n output.append(self.__decrypt_logic(char, 'A'))\r\n\r\n return ''.join(output)","sub_path":"exam/project2/affine.py","file_name":"affine.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"152515676","text":"from bs4 import BeautifulSoup\nfrom os import listdir\nfrom os import path\n\nclass initialBookParse:\n soup = BeautifulSoup()\n input_file = \"\"\n\n def __init__(self, input):\n self.input_file = input\n\n def get_list(self):\n if not self.input_file[-5:] == \".html\":\n self.input_file = self.input_file + \".html\"\n\n with open(str(self.input_file)) as fp:\n self.soup = BeautifulSoup(fp, features=\"html.parser\")\n\n wanted_tags = {}\n for item in self.soup.find_all('a'):\n link = str(item['href'])\n title = str(item.contents)\n\n if \"lot\" in link and \"McKenzie\" in title:\n title = title.replace('\"', '')\n title = title.replace(\"'\", '')\n title = title[1:-36]\n wanted_tags[title] = link\n return (wanted_tags)\n\n def search_for(self):\n html_files = []\n files = [f for f in listdir('.') if path.isfile(f)]\n for f in files:\n if f[-5:] == \".html\":\n html_files.append(f)\n return (html_files)\n\ndef main(): \n initialBookParse(input(\"Enter a fileName\"))\n\nif __name__ == '__main__':\n main()","sub_path":"initalBookParse.py","file_name":"initalBookParse.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"546244142","text":"import os, Image\nimgs = os.listdir(os.getcwd() + '\\\\pics')\ntxt = open('ascii.txt', 'a')\nfor img in imgs:\n frame = Image.open(os.getcwd() + '\\\\pics\\\\' + img)\n rgb = frame.convert('RGB')\n for y in range(30):\n for x in range(80):\n r, g, b = rgb.getpixel((x, y))\n if r > 200 and g > 200 and b > 200:\n txt.write(' ')\n else:\n txt.write('#')\n txt.write('\\n')","sub_path":"generatetxt.py","file_name":"generatetxt.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"40656982","text":"import socket\n\n# IPV4, TCP\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# Since client is held on same laptop as code\ns.connect((socket.gethostname(), 1234))\n\n# How much data you want to recieve i.e. buffer size\nmsg = s.recv(1024)\nprint(msg.decode(\"utf-8\"))\n\nmsg = \"Real-Time-Video-Output.png\"\ns.send(msg.encode(\"utf-8\"))\n\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"570156830","text":"from typing import Dict, List, Set\nfrom collections import defaultdict\n\n\nclass ReagentList(defaultdict): # type: Dict[str, int]\n def __init__(self, input_str=''):\n defaultdict.__init__(self, lambda: 0)\n for item in input_str.split(','):\n data = item.split()\n if data:\n self[data[1]] = int(data[0])\n\n def __str__(self):\n return ', '.join(['{amt} {agent}'.format(amt=amt, agent=agent) for agent, amt in self.items()])\n\n\nclass Reaction(object):\n def __init__(self, product, amount, reagent_list):\n self.product = product\n self.amount = amount\n self.reagent_list = reagent_list # type: ReagentList\n\n @staticmethod\n def from_str(s):\n x = s.split('=>')\n product_data = x[1].strip().split()\n return Reaction(product=product_data[1], amount=int(product_data[0]), reagent_list=ReagentList(x[0]))\n\n def __str__(self):\n return '{reagents} => {amt} {agent}'.format(\n reagents=str(self.reagent_list),\n agent=self.product,\n amt=self.amount\n )\n\n\nclass ReactionDict(dict):\n \"\"\"A Dict[str, Reaction] giving the reaction producing each agent.\"\"\"\n\n def __init__(self, reaction_list: List[Reaction]):\n dict.__init__(self)\n for r in reaction_list:\n self[r.product] = r\n\n # Topologically sort the agents in our reaction list\n self.toposorted_agents = None\n self.refresh_toposorted_agents()\n\n def refresh_toposorted_agents(self):\n self.toposorted_agents = []\n unmarked_nodes = set(self.keys()) # type: Set[str]\n tempmarked_nodes = set() # type: Set[str]\n while unmarked_nodes:\n self._toposort_visit(next(iter(unmarked_nodes)), unmarked_nodes, tempmarked_nodes)\n self.toposorted_agents = list(reversed(self.toposorted_agents))\n\n def _toposort_visit(self, key, unmarked_nodes, tempmarked_nodes):\n if key not in unmarked_nodes and key not in tempmarked_nodes:\n return\n elif key in tempmarked_nodes:\n raise RuntimeError('Tried to Toposort a cyclic graph')\n\n unmarked_nodes.remove(key)\n tempmarked_nodes.add(key)\n for subagent in self[key].reagent_list.keys():\n self._toposort_visit(subagent, unmarked_nodes, tempmarked_nodes)\n tempmarked_nodes.remove(key)\n self.toposorted_agents.append(key)\n\n\ndef get_needed_ore(desired_outputs: ReagentList, reaction_dict: ReactionDict):\n if not desired_outputs:\n return 0\n\n if len(desired_outputs) == 1 and 'ORE' in desired_outputs:\n return desired_outputs['ORE']\n\n # Find \"highest\" agent in desired_outputs, turn it into reagents, modify desired_outputs, and recurse\n for primary_agent in reaction_dict.toposorted_agents:\n if primary_agent in desired_outputs.keys():\n amt_needed = desired_outputs[primary_agent]\n reaction_needed = reaction_dict[primary_agent]\n num_reactions = -(-amt_needed//reaction_needed.amount) # ceiling division\n reagents_needed = reaction_needed.reagent_list\n\n new_desired_outputs = ReagentList()\n for agent in desired_outputs.keys():\n if agent != primary_agent:\n new_desired_outputs[agent] = desired_outputs[agent]\n for agent in reagents_needed.keys():\n if agent not in new_desired_outputs:\n new_desired_outputs[agent] = 0\n new_desired_outputs[agent] += reagents_needed[agent]*num_reactions\n\n return get_needed_ore(new_desired_outputs, reaction_dict)\n\n\ndef part_1(reaction_dict):\n return get_needed_ore(ReagentList('1 FUEL'), reaction_dict)\n\n\ndef part_2(reaction_dict):\n target_ore = 10**12\n\n minval = 10**6 # Can definitely produce this much fuel\n maxval = 10**7 # Definitely can't produce this much fuel\n minore = get_needed_ore(ReagentList('{} FUEL'.format(minval)), reaction_dict)\n maxore = get_needed_ore(ReagentList('{} FUEL'.format(maxval)), reaction_dict)\n\n assert minore <= target_ore < maxore\n\n while maxval - minval > 1:\n halfval = (maxval + minval)//2\n halfore = get_needed_ore(ReagentList('{} FUEL'.format(halfval)), reaction_dict)\n if halfore > target_ore:\n maxval = halfval\n elif halfore < target_ore:\n minval = halfval\n else:\n print(halfval)\n\n return minval\n\n\ndef get_reactions():\n reaction_list = []\n with open('input/dec14.txt', 'r') as file:\n for line in file:\n reaction_list.append(Reaction.from_str(line))\n return ReactionDict(reaction_list)\n\n\ndef get_test_reactions():\n reaction_list = []\n test_str = \"\"\"157 ORE => 5 NZVS\n 165 ORE => 6 DCFZ\n 44 XJWVT, 5 KHKGT, 1 QDVJ, 29 NZVS, 9 GPVTF, 48 HKGWZ => 1 FUEL\n 12 HKGWZ, 1 GPVTF, 8 PSHF => 9 QDVJ\n 179 ORE => 7 PSHF\n 177 ORE => 5 HKGWZ\n 7 DCFZ, 7 PSHF => 2 XJWVT\n 165 ORE => 2 GPVTF\n 3 DCFZ, 7 NZVS, 5 HKGWZ, 10 PSHF => 8 KHKGT\"\"\"\n for line in test_str.splitlines():\n reaction_list.append(Reaction.from_str(line))\n return ReactionDict(reaction_list)\n\n\nif __name__ == \"__main__\":\n reactions = get_reactions()\n print('Part 1:', part_1(reactions))\n print('Part 2:', part_2(reactions))\n","sub_path":"2019/dec14.py","file_name":"dec14.py","file_ext":"py","file_size_in_byte":5356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"287676499","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 21 20:31:17 2018\n\n@author: cabrera\n\"\"\"\n\n\n'''1. \n This python code returns a line graph of the record high and record low temperatures\n by day of the year over the period 2005-2014. \n be shaded.\n \n 2. We overlay a scatter of the 2015 data for any points (highs and lows) for \n which the ten year record (2005-2014) record high or record low was broken in 2015.'''\n \n \nimport pandas as pd, numpy as np\nimport matplotlib.pyplot as plt\n\ndef read_file():\n \n # function to read in data\n \n df = pd.read_csv('weather.csv')\n df2015 = df[df['Date'] > '2014-12-31'] # data for 2015 only\n df2015.loc[:,'Data_Value'] = df2015['Data_Value']/10 # convert to Celcius\n df = df[df['Date'] < '2015-01-01'] # data for 2005-2014\n df.loc[:,'Data_Value'] = df['Data_Value']/10 # convert to Celcius\n \n return df, df2015\n \ndef record_lines():\n \n df, df2015 = read_file()\n \n #remove feb 29th from dataset (allowed for visualization)\n df = df.drop(df[df['Date'].isin(['2008-04-29','2012-04-29'])].index)\n \n \n # max and min temps for range of years 2005-2014\n tmax_df = df[df['Element'] == 'TMAX'].groupby('Date').mean().reset_index() # get mean for each day since we have multiple recordings\n tmin_df = df[df['Element'] == 'TMIN'].groupby('Date').mean().reset_index()\n \n # group by day of the year\n tmax_df['mod365'] = pd.DataFrame([x % 365 for x in tmax_df.index.tolist()], index= tmax_df.index)\n tmin_df['mod365'] = pd.DataFrame([x % 365 for x in tmin_df.index.tolist()], index= tmin_df.index)\n \n \n # create df for latest year 2015, and add extrema from range of years 2005-2014\n t2015max_df = df2015[df2015['Element'] == 'TMAX'].groupby('Date').mean().reset_index()\n t2015max_df['2005-2014_highest'] = tmax_df.groupby('mod365').max()['Data_Value']\n \n t2015min_df = df2015[df2015['Element'] == 'TMIN'].groupby('Date').mean().reset_index()\n t2015min_df['2005-2014_lowest'] = tmin_df.groupby('mod365').min()['Data_Value']\n \n print(t2015max_df.head())\n # create column containing only those values from 2015 when the records were broken\n t2015max_df['record_in_2015'] = pd.DataFrame(t2015max_df[t2015max_df['Data_Value'] == t2015max_df[['Data_Value', '2005-2014_highest']].max(axis=1) ]['Data_Value'], index= t2015max_df.index)\n t2015min_df['record_in_2015'] = pd.DataFrame(t2015min_df[t2015min_df['Data_Value'] == t2015min_df[['Data_Value','2005-2014_lowest']].min(axis=1)]['Data_Value'], index= t2015min_df.index)\n \n \n \n #graphs for range of years 2005-2014\n plt.figure(figsize=(12,8))\n plt.title('2005-2014 max and min daily temperature records. Records broken in 2015.')\n plt.plot(t2015max_df['Date'],t2015max_df['2005-2014_highest'],'-r',linewidth=1,label='2005-2014 highest record')\n plt.plot(t2015min_df['Date'],t2015min_df['2005-2014_lowest'],'-b',linewidth=1, label='2005-2014 lowest record')\n plt.xticks(np.arange(1,len(t2015max_df),33), ('Jan', 'Feb', 'Mar', 'Apr', 'May','Jun','Jul','Aug','Sep','Oct','Nov', 'Dec'))\n plt.gca().fill_between(t2015max_df['Date'], t2015min_df['2005-2014_lowest'], t2015max_df['2005-2014_highest'],facecolor='green',\n alpha=0.1)\n \n \n # plot records broken in 2015\n plt.plot(t2015max_df['Date'], t2015max_df['record_in_2015'], '*', color = 'purple', label = 'max temp broken in 2015')\n plt.plot(t2015min_df['Date'], t2015min_df['record_in_2015'], '*', color='orange', label = 'min temp broken in 2015')\n \n plt.legend(frameon=False)\n plt.xlabel('Days')\n plt.ylabel('Temperature °C')\n plt.savefig('daily_temps_and_broken_records.png')\n\n\n \n \n \nif __name__ == '__main__':\n \n record_lines()\n","sub_path":"decade_temp_Houston.py","file_name":"decade_temp_Houston.py","file_ext":"py","file_size_in_byte":3796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"521376947","text":"class edgeconnectedtwo(object):\n \"\"\"docstring for dfsrecursion\"\"\"\n\n def __init__(self, graph):\n super(edgeconnectedtwo, self).__init__()\n self.graph = graph\n self.visited = [False]*len(self.graph)\n self.time = 0\n self.start = [None]*len(self.graph)\n self.parent = [None]*len(self.graph)\n self.source = 0\n\n def edgecon(self, u):\n self.visited[u] = True\n self.start[u] = self.time\n self.time = self.time+1\n des = self.start[u]\n for x in self.graph[u]:\n if self.visited[x] == False:\n self.parent[x] = u\n des = min(self.edgecon(x), des)\n else: \n if self.parent[u] != x:\n des = min(self.start[x], des)\n else:\n print('true')\n exit()\n if self.source!=u and des=0:\n print('False')\n\nmain() \n\n","sub_path":"DSA part-2 lab/dfs/cycledfsdirected.py","file_name":"cycledfsdirected.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"485560410","text":"# Program prints actual temperature for given Polish city using API\n\nimport requests as r\n\ncity = input('Type city:\\n')\n\ntry:\n response = r.get('http://api.openweathermap.org/data/2.5/weather?q='+city+',pl&appid=524fd3d7bec2274ae22c9d6a4540f3f9')\n json = response.json()\n \n print('Actual temperature for city', city, 'is', str(round(json['main']['temp']-273.15,1))+'°C')\n print('Feels like temperature for city', city, 'is', str(round(json['main']['feels_like']-273.15,1))+'°C')\n\nexcept:\n print('Results not found.')\n","sub_path":"polish_weather.py","file_name":"polish_weather.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"401036543","text":"# coding=utf-8\nimport time\nfrom datetime import datetime\n\nfrom flask import render_template, request\nfrom flask_login import login_required\nimport pandas as pd\n\nfrom root import provozni_hodnoty # připojení složky sprava_kgj\n\nfrom database import engine\nimport xlsxwriter\nfrom root.global_functions import first_day_of_year,last_day_of_year\n\n# provázání na sprava_kgj\\__init__.py\nprovozni_hodnoty_page = provozni_hodnoty.provozni_hodnoty_page\n\n\n# nepouzívá se app.route, ale přímo název aplikce (kgj_data_page.route)\n# v html se potom volá \n@provozni_hodnoty.provozni_hodnoty_page.route(\"/provozni_hodnoty_vyhodnoceni_provoz\", methods=['GET', 'POST'])\n@login_required\ndef provozni_hodnoty_vyhodnoceni_provoz():\n global param, date_record_f, date_record_l\n if request.method == 'POST':\n year = request.form['rok']\n month = request.form['mesic']\n kgj_id = request.form['kgj']\n pwr_category = request.form['vykon']\n rv_user_id = request.form['regional']\n\n if not kgj_id:\n kgj_id = '0'\n\n # Selecting power category\n if pwr_category != '0':\n pwr_cat_f = pwr_category_select(int(pwr_category))[0]\n pwr_cat_l = pwr_category_select(int(pwr_category))[1]\n else:\n pwr_cat_f = 0\n pwr_cat_l = 0\n\n # Main decision script for Select boxes\n if month == '0':\n date_record_f = int(time.mktime(datetime(int(year), 1, 1).timetuple()))\n date_record_l = int(time.mktime(datetime(int(year), 12, 31).timetuple()))\n if kgj_id == '0':\n if pwr_category == '0':\n if rv_user_id == '0':\n param = 0\n else:\n param = 2\n else:\n if rv_user_id == '0':\n param = 3\n else:\n param = 4\n else:\n param = 1\n\n if month != '0':\n date_record_f = int(time.mktime(datetime(int(year), int(month), 1).timetuple()))\n\n if month == '12':\n date_record_l = int(time.mktime(datetime(int(year) + 1, 1, 1).timetuple()))\n else:\n date_record_l = int(time.mktime(datetime(int(year), int(month) + 1, 1).timetuple()))\n\n if kgj_id == '0':\n if pwr_category == '0':\n if rv_user_id == '0':\n param = 0\n else:\n param = 2\n else:\n if rv_user_id == '0':\n param = 3\n else:\n param = 4\n else:\n param = 1\n\n # SQL Builder\n sql = build_sql_query(kgj_id, date_record_f, date_record_l, rv_user_id, pwr_cat_f, pwr_cat_l, param)\n df = pd.read_sql(sql, engine)\n\n # DF computing\n df_vypocty = df[['vyr_cis', 'nazev', 'date_record_r', 'mth_poc', 'status', 'datetime_up_r']].copy()\n df_vypocty['v_tep_celkem'] = df['v_tep_so'] + df['v_tep_to']\n df['n_ply_fakt_kgj_kwh'] = df['n_ply_fakt_kgj_m3'].astype(float).round(0) * 0.9 * 10.67\n df['s_ply_mer_kgj_kwh'] = df['s_ply_mer_kgj_m3'].astype(float).round(0) * 0.9 * 10.67\n \n try:\n df_vypocty['prumerny_el_vykon_dod'] = round(df['p_el_ote'] / df['mth_poc'], 2)\n df_vypocty['prumerny_el_vykon_odber'] = round(df['n_el_ote'] / df['mth_poc'], 2)\n except:\n pass\n\n df_vypocty['mth_ote'] = df['v_el_celkem'] / df['lic_el']\n df_vypocty['mth_ote'] = df_vypocty['mth_ote'].apply(pd.np.ceil)\n df_vypocty['rozdil_plan_mth'] = df['plan_mth'] - df['mth_poc']\n df_vypocty['prumerny_el_vykon_gen'] = round(df['v_el_celkem'] / df['mth_poc'], 2)\n df_vypocty['prumerna_vl_spotreba'] = round(df['s_el_vskjchod'] / df['mth_poc'], 2)\n df_vypocty['prumerna_vl_spotreba_%'] = round(\n df['s_el_vskjchod'] / df['mth_poc'] / df_vypocty['prumerny_el_vykon_gen'], 2)\n df_vypocty['prumerny_tep_vykon_celkem'] = round(\n ((df['v_tep_so'] + df['v_tep_to']) / 0.0036) / df['mth_poc'], 2)\n df_vypocty['prumerny_tep_vykon_so'] = round(df['v_tep_so'] / 0.0036 / df['mth_poc'], 2)\n df_vypocty['prumerny_tep_vykon_to'] = round(df['v_tep_to'] / 0.0036 / df['mth_poc'], 2)\n df_vypocty['prumerna_spotreba_plynu_m3'] = round(df['s_ply_mer_kgj_m3'] / df['mth_poc'], 2)\n\n try:\n df_vypocty['ucinnost_celkem'] = round((((df['v_tep_so'] + df['v_tep_to']) / 0.0036) + df['v_el_celkem']) / df['s_ply_mer_kgj_kwh'] * 100, 2)\n df_vypocty['ucinnost_el'] = round((df['v_el_celkem'] / df['s_ply_mer_kgj_kwh']) * 100, 2)\n df_vypocty['ucinnost_tep'] = round((df['v_tep_so'] + df['v_tep_to']) / 0.0036 / df['s_ply_mer_kgj_kwh'] * 100, 2)\n except:\n pass\n\n return df_vypocty.to_json(orient='table')\n return render_template(\"vyhodnoceni_provoz.html\") # doplnit\n\n\ndef build_sql_query(kgj_id, date_record_f, date_record_l, rv_id, pwr_cat_f, pwr_cat_l, param):\n\n sql = \"select kgj_m_measured_val.*, \" \\\n \"concat_ws('-',\" \\\n \"LPAD(day(FROM_UNIXTIME(kgj_m_measured_val.date_record)),2,0),\" \\\n \"LPAD(month(FROM_UNIXTIME(kgj_m_measured_val.date_record)),2,0),\" \\\n \"year(FROM_UNIXTIME(kgj_m_measured_val.date_record))) as date_record_r,\" \\\n \"concat(concat_ws('-',\" \\\n \"LPAD(day(FROM_UNIXTIME(kgj_m_measured_val.datetime_up)),2,0),\" \\\n \"LPAD(month(FROM_UNIXTIME(kgj_m_measured_val.datetime_up)),2,0),\" \\\n \"year(FROM_UNIXTIME(kgj_m_measured_val.datetime_up))),' ',\" \\\n \"concat_ws(':',\" \\\n \"LPAD(hour(FROM_UNIXTIME(kgj_m_measured_val.datetime_up)),2,0),\" \\\n \"LPAD(minute(FROM_UNIXTIME(kgj_m_measured_val.datetime_up)),2,0))) as datetime_up_r, \" \\\n \"kk.nazev,\" \\\n \"kk.lic_el,\" \\\n \"kk.plan_mth,\" \\\n \"ph_m_fakt_plyn.f_plyn as n_ply_fakt_kgj_m3,\" \\\n \"ph_m_fakt_plyn.f_spaltep as spaltep,\" \\\n \"ph_m_ote_elektrina.ote_el_dodavka as p_el_ote,\" \\\n \"ph_m_ote_elektrina.ote_el_odber as n_el_ote,\" \\\n \"ph_m_spal_tep.spaltep_distrib as spal_tep_distrib \" \\\n \"FROM kgj_m_measured_val \" \\\n \"left join kgj_konstanty kk on kk.id = kgj_m_measured_val.id_kgj \" \\\n \"left join ph_m_fakt_plyn on ph_m_fakt_plyn.id_kgj = kgj_m_measured_val.id_kgj and ph_m_fakt_plyn.date_record = kgj_m_measured_val.date_record \" \\\n \"left join ph_m_ote_elektrina on ph_m_ote_elektrina.id_kgj = kgj_m_measured_val.id_kgj and ph_m_ote_elektrina.date_record = kgj_m_measured_val.date_record \" \\\n \"left join ph_m_spal_tep on kk.id_distrib_obl_ply = ph_m_spal_tep.id_distrib_obl and ph_m_spal_tep.date_record = kgj_m_measured_val.date_record \"\n\n if param == 0:\n where_param = \"where kgj_m_measured_val.date_record >= {} and kgj_m_measured_val.date_record <= {}\".format(\n date_record_f, date_record_l)\n\n if param == 1:\n where_param = \"where kk.id = {} and kgj_m_measured_val.date_record >= {} and kgj_m_measured_val.date_record <= {}\".format(\n kgj_id, date_record_f, date_record_l)\n\n if param == 2:\n where_param = \"where kk.id_regio_vedouci = {} and kgj_m_measured_val.date_record >= {} and kgj_m_measured_val.date_record <= {}\".format(\n rv_id, date_record_f, date_record_l)\n\n if param == 3:\n where_param = \"where kgj_m_measured_val.date_record >= {} and kgj_m_measured_val.date_record <= {} and kk.inst_vykon >{} and kk.inst_vykon <= {}\".format(\n date_record_f, date_record_l, pwr_cat_f, pwr_cat_l)\n\n if param == 4:\n where_param = \"where kk.id_regio_vedouci = {} and kgj_m_measured_val.date_record >= {} and kgj_m_measured_val.date_record <= {} and kk.inst_vykon >{} and kk.inst_vykon <= {}\".format(\n rv_id, date_record_f, date_record_l, pwr_cat_f, pwr_cat_l)\n\n\n return sql + where_param\n\n\ndef pwr_category_select(pwr_cat_id):\n # <100\n if pwr_cat_id == 1:\n return [0, 99]\n\n # 100-200\n if pwr_cat_id == 2:\n return [100, 200]\n\n # 400\n if pwr_cat_id == 3:\n return [201, 400]\n\n # 600\n if pwr_cat_id == 4:\n return [401, 600]\n\n # 800\n if pwr_cat_id == 5:\n return [601, 800]\n\n # 1000\n if pwr_cat_id == 6:\n return [801, 1000]\n\n # 1600\n if pwr_cat_id == 7:\n return [1001, 1600]\n\n # 2000\n if pwr_cat_id == 8:\n return [1601, 2014]\n","sub_path":"root/provozni_hodnoty/ph_data_controlling_view.py","file_name":"ph_data_controlling_view.py","file_ext":"py","file_size_in_byte":8644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"78644709","text":"\nimport sys\nfrom tp00 import Tp00\nimport json\nfrom constant import *\nimport tpUtils\nimport time\n\n\nclass TpGrvRgbLcd_out:\n \"\"\"\n TP Grove - LCD RGB Backlight\n \"\"\"\n\n # commands\n LCD_CLEARDISPLAY = 0x01\n LCD_RETURNHOME = 0x02\n LCD_ENTRYMODESET = 0x04\n LCD_DISPLAYCONTROL = 0x08\n LCD_CURSORSHIFT = 0x10\n LCD_FUNCTIONSET = 0x20\n LCD_SETCGRAMADDR = 0x40\n LCD_SETDDRAMADDR = 0x80\n\n # flags for display entry mode\n LCD_ENTRYRIGHT = 0x00\n LCD_ENTRYLEFT = 0x02\n LCD_ENTRYSHIFTINCREMENT = 0x01\n LCD_ENTRYSHIFTDECREMENT = 0x00\n\n # flags for display on/off control\n LCD_DISPLAYON = 0x04\n LCD_DISPLAYOFF = 0x00\n LCD_CURSORON = 0x02\n LCD_CURSOROFF = 0x00\n LCD_BLINKON = 0x01\n LCD_BLINKOFF = 0x00\n\n # flags for display/cursor shift\n LCD_DISPLAYMOVE = 0x08\n LCD_CURSORMOVE = 0x00\n LCD_MOVERIGHT = 0x04\n LCD_MOVELEFT = 0x00\n\n def __init__(self, slot, host=None):\n \"\"\"\n コンストラクタ\n \"\"\"\n self.slot = slot\n self.comm = I2C\n self.host = host\n\n # アドレス\n self.i2c_addr_rgb = 0x62\n self.i2c_addr_text = 0x3e\n\n self.tp00 = Tp00(self.slot, self.comm, self.host)\n self.tp00.start()\n\n def set_rgb(self, r, g, b):\n \"\"\"\n set RGB\n \"\"\"\n\n send_data = []\n send_data.append(\n {\"act\": \"w\", \"add\": self.i2c_addr_rgb, \"cmd\": 0x00, \"v\": [0x00]})\n send_data.append(\n {\"act\": \"w\", \"add\": self.i2c_addr_rgb, \"cmd\": 0x01, \"v\": [0x00]})\n send_data.append(\n {\"act\": \"w\", \"add\": self.i2c_addr_rgb, \"cmd\": 0x08, \"v\": [0xaa]})\n\n send_data.append(\n {\"act\": \"w\", \"add\": self.i2c_addr_rgb, \"cmd\": 4, \"v\": [r]})\n send_data.append(\n {\"act\": \"w\", \"add\": self.i2c_addr_rgb, \"cmd\": 3, \"v\": [g]})\n send_data.append(\n {\"act\": \"w\", \"add\": self.i2c_addr_rgb, \"cmd\": 2, \"v\": [b]})\n self.tp00.send(json.dumps(send_data))\n\n def __text_command(self, cmd):\n \"\"\"\n send command to display (no need for external use)\n \"\"\"\n send_data = []\n send_data.append(\n {\"act\": \"w\", \"add\": self.i2c_addr_text, \"cmd\": 0x80, \"v\": [cmd]})\n self.tp00.send(json.dumps(send_data))\n\n def __to_jp(self, val):\n try:\n return ord(val.encode('shift-jis'))\n except:\n raise ValueError(\"Only single-byte characters can be used.\")\n\n def set_text(self, text):\n \"\"\"\n Update the display\n \"\"\"\n self.__text_command(self.LCD_RETURNHOME) # return home\n time.sleep(.05)\n self.__text_command(self.LCD_DISPLAYCONTROL |\n self.LCD_DISPLAYON) # display on, no cursor\n self.__text_command(0x28) # 2 lines\n time.sleep(.05)\n count = 0\n row = 0\n while len(text) < 32: # clears the rest of the screen\n text += ' '\n for c in text:\n if c == '\\n' or count == 16:\n\n # 1行目もスペースで埋める\n for _ in range(16-count):\n send_data = []\n send_data.append(\n {\"act\": \"w\", \"add\": self.i2c_addr_text, \"cmd\": 0x40, \"v\": [ord(' ')]})\n self.tp00.send(json.dumps(send_data))\n\n count = 0\n row += 1\n if row == 2:\n break\n # 2行目\n self.__text_command(0xc0)\n if c == '\\n':\n continue\n count += 1\n\n send_data = []\n send_data.append(\n {\"act\": \"w\", \"add\": self.i2c_addr_text, \"cmd\": 0x40, \"v\": [self.__to_jp(c)]})\n self.tp00.send(json.dumps(send_data))\n\n def clear(self):\n \"\"\"\n clear display\n \"\"\"\n self.__text_command(self.LCD_CLEARDISPLAY)\n\n\nif __name__ == '__main__':\n\n argvs = sys.argv\n if (len(argvs) <= 1):\n tpUtils.stderr('Need argv! [1]: slot')\n sys.exit(0)\n\n try:\n slot = argvs[1]\n host = None\n if (len(argvs) > 2):\n host = argvs[2]\n tpGrvRgbLcd_out = TpGrvRgbLcd_out(slot, host)\n except Exception as e:\n tpUtils.stderr(str(e.args))\n sys.exit(0)\n\n while True:\n try:\n data = input()\n obj = json.loads(data)\n\n if (obj['act'] == 'rgb'):\n tpGrvRgbLcd_out.set_rgb(obj['r'], obj['g'], obj['b'])\n\n elif (obj['act'] == 'text'):\n tpGrvRgbLcd_out.set_text(obj['v'])\n\n elif (obj['act'] == 'clear'):\n tpGrvRgbLcd_out.clear()\n\n except KeyboardInterrupt:\n sys.exit(0)\n except Exception as e:\n tpUtils.stderr(str(e.args))\n","sub_path":"py/tpgRgbLcd_out.py","file_name":"tpgRgbLcd_out.py","file_ext":"py","file_size_in_byte":4809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"421830593","text":"from __future__ import division\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as pl\n\nfrom rat.data.raw.freeassociations.read_data import load_vocabulary\nfrom rat.algorithm.simulation import get_difficulties\nfrom rat.model.utils import nearest_value\n\nfrom simulation import simulate_test\n\n\ndef simulate_threshold(thresholds, nr_words):\n \"\"\"\n Simulations with different thresholds.\n \"\"\"\n performance = np.zeros((len(thresholds), 4))\n\n for i, th in enumerate(thresholds):\n print('Threshold = %.2f' % th)\n\n param = {'theta': th,\n 'nr_words': nr_words\n }\n\n positions, _ = simulate_test(**param)\n nr_items = len(positions)\n\n performance[i, :3] = get_difficulties(positions)\n percent_correct = 100*len(np.where(positions > -1)[0])/nr_items\n performance[i, 3] = percent_correct\n\n return performance\n\n\ndef simulate_number_of_words(nr_words):\n \"\"\"\n Simulations with a varying number of responses to a RAT problem.\n The simulation is run for the maximal number of words and based on that the\n success rates for a smaller number of words are calculated.\n \"\"\"\n\n performance = np.zeros((len(nr_words), 4))\n max_words = nr_words[-1]\n\n # load an existing file\n try:\n filename = 'nr_words_simulation.npz'\n positions = np.load(filename)['positions']\n print('Loading existing file...')\n except IOError:\n print('Running simulation!')\n positions, _ = simulate_test(**{'nr_words': max_words})\n np.savez(filename, positions=positions)\n\n nr_items = float(len(positions))\n\n for i, nr_w in enumerate(nr_words):\n print('Testing words = %d' % nr_w)\n solutions = np.where(positions < nr_w, positions, -1)\n\n performance[i, :3] = get_difficulties(solutions)\n percent_correct = 100*len(np.where(solutions > -1)[0])/nr_items\n performance[i, 3] = percent_correct\n\n return performance\n\nif __name__ == \"__main__\":\n font = {'family': 'serif',\n 'serif': 'Times New Roman',\n 'size': 28}\n legend_fs = 24\n matplotlib.rc('font', **font)\n\n # Association data, needed for statistics below\n W, ids, voc = load_vocabulary()\n weights = W[W.nonzero()]\n\n # problem difficulty labeling\n difficulties = [0, 1, 2]\n labs = ['easy', 'mid', 'hard']\n\n lw = 4\n colors = ['#4D4D4D', '#808080', '#CCCCCC', '#000000']\n alphas = [.4, .4, .6]\n ymin, ymax = -2, 105\n\n fig = pl.figure(figsize=(22, 6), dpi=80, facecolor=\"white\")\n\n # ----------------- Vary number of words -----------------\n axes = pl.subplot(121)\n min_nr_words, max_nr_words = 4, 35\n words = np.arange(min_nr_words, max_nr_words)\n try:\n filename = 'perf_words.npz'\n performance_w = np.load(filename)['performance_w']\n print('Loading existing simulation for words')\n except IOError:\n print('Running model simulation (different number of words)')\n performance_w = simulate_number_of_words(words)\n np.savez(filename, performance_w=performance_w)\n\n # Plot all results\n pl.plot(words, performance_w.T[3], label='all',\n linewidth=lw, color=colors[-1])\n\n # Plot individual curves\n for diff in difficulties:\n pl.plot(words, 100*performance_w.T[diff], label=labs[diff],\n linewidth=lw, color=colors[diff], alpha=alphas[diff])\n\n axes.grid(axis='y')\n pl.ylim(ymin, ymax)\n\n # set x-ticks\n locs, _ = pl.xticks()\n locs[0] = 1 # 4 words = 3 cues + *1* response\n\n pl.xticks(locs+3, np.array(locs, dtype=np.int))\n pl.xlim(min_nr_words, max_nr_words-1)\n\n pl.xlabel('Number of words')\n pl.ylabel('Performance (%)')\n\n axes.spines['right'].set_color('none')\n axes.spines['left'].set_color('none')\n axes.spines['top'].set_color('none')\n\n axes.xaxis.set_ticks_position('bottom')\n axes.yaxis.set_ticks_position('left')\n\n # -------------------- Vary threshold --------------------\n axes = pl.subplot(122)\n min_threshold, max_threshold = 0, .44\n step_threshold = 0.01\n words = 15\n thresholds = np.arange(min_threshold, max_threshold, step_threshold)\n try:\n filename = 'perf_thresh.npz'\n performance_t = np.load(filename)['performance_t']\n print('Loading existing simulation for thresholds.')\n except IOError:\n print('Running algorithmic simulation (different number of threshols)')\n performance_t = simulate_threshold(thresholds, words)\n np.savez(filename, performance_t=performance_t)\n\n # Plot all results\n pl.plot(thresholds, performance_t.T[3], label='all',\n linewidth=lw, color=colors[-1])\n\n # Plot individual curves\n for diff in difficulties:\n pl.plot(thresholds, 100*performance_t.T[diff], label=labs[diff],\n linewidth=lw, color=colors[diff], alpha=alphas[diff])\n\n axes.grid(axis='y')\n\n pl.ylim(ymin, ymax)\n pl.xlim(min_threshold, max_threshold-step_threshold)\n\n axes.spines['right'].set_color('none')\n axes.spines['left'].set_color('none')\n axes.spines['top'].set_color('none')\n\n axes.xaxis.set_ticks_position('bottom')\n axes.yaxis.set_ticks_position('left')\n\n pl.legend(loc='upper right', prop={'size': legend_fs})\n pl.xlabel(r'Threshold ($\\vartheta_s$)')\n\n pl.locator_params(axis='x', nbins=6)\n\n # Statistics\n percentiles = np.arange(101)\n values = np.percentile(weights, percentiles)\n\n drops = 1./np.arange(2, 11)\n\n for drop in drops:\n for lab, idx in zip(labs, difficulties):\n maxP = performance_t.T[idx].max()\n midP, idx_th = nearest_value(performance_t.T[idx], maxP*drop)\n theta = thresholds[idx_th]\n\n perc, idx_p = nearest_value(values, theta)\n p = percentiles[idx_p]\n\n print(('Drop by %.d%% for %s items at theta' +\n '= %.2f (%.0fth percentile)') %\n (drop*100, lab, theta, p))\n\n print('\\n')\n\n if 0:\n pl.savefig('performance.pdf', bbox_inches='tight')\n\n pl.show()\n","sub_path":"rat/model/run_simulation.py","file_name":"run_simulation.py","file_ext":"py","file_size_in_byte":6097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"216561125","text":"import pandas as pd\nfrom pgmpy.estimators import PC\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import ArrowStyle\nimport networkx as nx\nimport pingouin\nfrom linearmodels.system import SUR\n\ndef graph_DAG(edges, \n df, \n pp, \n edge_labels = False, \n sig_vals = [.05,.01,.001],\n title = \"\"):\n def build_edge_labels(edges, df, sig_vals):\n edge_labels = {}\n for edge in edges:\n controls = [key for key in df.keys() if key not in edge]\n controls = list(set(controls))\n keep_controls = []\n for control in controls:\n control_edges = [ctrl_edge for ctrl_edge in edges if control == ctrl_edge[0] ]\n if (control, edge[1]) in control_edges:\n keep_controls.append(control) \n# print(edge, keep_controls)\n pcorr = df.partial_corr(x = edge[0], y = edge[1], covar=keep_controls,\n method = \"pearson\")\n label = str(round(pcorr[\"r\"][0],2))\n pvalue = pcorr[\"p-val\"][0]\n# pcorr = df[[edge[0], edge[1]]+keep_controls].pcorr()\n# label = pcorr[edge[0]].loc[edge[1]]\n\n for sig_val in sig_vals:\n if pvalue < sig_val: \n label = label + \"*\" \n \n edge_labels[edge] = label\n return edge_labels\n graph = nx.DiGraph()\n if edge_labels == False:\n edge_labels = build_edge_labels(edges, \n df, \n sig_vals=sig_vals) \n graph.add_edges_from(edges)\n color_map = [\"C0\" for g in graph]\n\n fig, ax = plt.subplots(figsize = (20,20))\n graph.nodes()\n plt.tight_layout()\n pos = nx.spring_layout(graph)#, k = 5/(len(sig_corr.keys())**.5))\n\n nx.draw_networkx(graph, pos, node_color=color_map, node_size = 2500,\n with_labels=True, arrows=True,\n font_color = \"white\",\n font_size = 26, alpha = 1,\n width = 1, edge_color = \"C1\",\n arrowstyle=ArrowStyle(\"Fancy, head_length=3, head_width=1.5, tail_width=.1\"),\n connectionstyle='arc3, rad = 0.05',\n ax = ax)\n \n plt.title(title, fontsize = 30)\n# print(edge_labels)\n edge_labels2 = []\n for u, v, d in graph.edges(data=True):\n if pos[u][0] > pos[v][0]: \n if (v,u) in edge_labels.keys():\n edge_labels2.append(((u, v,), f'{edge_labels[u,v]}\\n\\n\\n{edge_labels[(v,u)]}')) \n if (v,u) not in edge_labels.keys():\n edge_labels2.append(((u,v,), f'{edge_labels[(u,v)]}'))\n edge_labels = dict(edge_labels2)\n\n nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels, font_color='C2')\n \n nx.draw_networkx_edge_labels(graph,pos,\n edge_labels=edge_labels,\n font_color='green',\n font_size=20)\n pp.savefig(fig, bbox_inches = \"tight\") \n plt.show()\n plt.close()\n\ndef DAG(dag_data, variant, ci_test, sig):\n c = PC(dag_data)\n# edges = c.skeleton_to_pdag(*c.build_skeleton())\n max_cond_vars = len(dag_data.keys()) - 2\n model = c.estimate(return_type = \"pdag\",variant= variant, \n significance_level = sig, \n max_cond_vars = max_cond_vars, \n ci_test = ci_test)\n edges = model.edges()\n \n return edges\n\n\ndef identify_sink_nodes(edges):\n unzipped_edges = list(zip(*edges))\n sink_nodes = unzipped_edges[1]\n caused_causal = {node:[] for node in sink_nodes}\n for source, sink in edges:\n caused_causal[sink].append(source)\n return caused_causal \n\n\n\ndef simultaneous_SUR(reg_data, sink_source, model_type = \"DAG\", constant = False, sig_vals = [0.05, 0.01, 0.001]):\n formulas = {}\n edge_weights = {}\n reg_data.rename(columns={key:key.replace(\"$\\pi$\",\"pi\").replace(\"/\",\"\") for key in reg_data.keys()},\n inplace = True) \n for variables in sink_source.items():\n sink, source = variables\n sink = sink.replace(\"$\\pi$\",\"pi\").replace(\"/\",\"\") \n formula = sink + \" ~\"\n i= 0\n for x in source:\n x = x.replace(\"$\\pi$\",\"pi\").replace(\"/\",\"\") \n if i == 0: \n formula = formula + \" \" + x\n else:\n formula = formula + \" + \" + x \n i=+1\n\n formulas[sink] = formula\n model = SUR.from_formula(formulas, reg_data)\n results = model.fit(cov_type=\"unadjusted\")\n #save regression results\n pd.DataFrame([results.params, results.pvalues]).to_excel(\"SUR\" + str(list(reg_data.index)[0])[:10]+\"-\"+str(list(reg_data.index)[-1])[:10]+\".xlsx\")\n for ix in results.params.keys():\n \n source, sink = ix.split(\"_\")\n sink = sink.replace(\"CA\", \"C/A\")\n source = source.replace(\"CA\", \"C/A\")\n edge_weights[(sink,source)] = str(round(results.params[ix],2))\n for sig_val in sig_vals:\n if results.pvalues[ix] < sig_val: \n edge_weights[(sink,source)] = edge_weights[(sink,source)] + \"*\" \n \n return edge_weights\n\ndef DAG_OLS(ols_data, sink_source, filename, pp, diff, dates, constant = False):\n keys = list(ols_data.keys())\n edge_weights = simultaneous_SUR(ols_data, sink_source)\n if constant: keys = keys + [\"Constant\"]\n graph_DAG(edges = list(edge_weights.keys()), \n df = None,\n edge_labels = edge_weights,\n pp = pp,\n title = \"SUR Estimates\\n\"+diff.replace(\" \", \"\") + \"\\n\" + dates)\n \ndef DAG_VAR(var_data, sink_source, filename, pp, diff, dates, sig_vals = [0.05, 0.01, 0.001]):\n reg_dict={}\n edges_weights = {}\n \n for sink, source in sink_source.items():\n variables = [sink] + source\n for k in range(len(variables)):\n key = variables[k]\n variables.append(key + \" Lag\")\n if key in sink_source.keys():\n if sink in sink_source[key] and sink not in variables:\n variables.append(key)\n select_data = var_data[variables]\n select_data.dropna(inplace = True)\n endog_keys = [key for key in variables if \"Lag\" not in key]\n exog_keys = [key for key in variables if \"Lag\" in key]\n endog = select_data[endog_keys]\n exog = select_data[exog_keys]\n reg_dict[sink] = VAR(endog, exog, sig_vals, constant = False)\n pd.DataFrame(reg_dict[sink])\n for sce in source:\n edges_weights[(sce, sink)] = reg_dict[sink][sink][sce+ \" Lag\"]\n graph_DAG(edges = list(edges_weights.keys()), \n df = select_data,\n edge_labels = edges_weights,\n pp = pp,\n title = \"VAR Estimates\\n\"+diff.replace(\" \", \"\") + \"\\n\" + dates)\n for sink, dct in reg_dict.items():\n print(sink, pd.DataFrame(dct), \"\", sep = \"\\n\")\n \n lag_keys = [key + \" Lag\" for key in dct] \n if \"Constant\" in dct: lag_keys = lag_keys + [\"Constant\"]\n excel_df = pd.DataFrame(dct).T[lag_keys].T #[\"r2\"]\n fname = sink + filename \n excel_df.to_excel(fname.replace(\"/\",\"\").replace(\"\\\\\",\"\")+\".xlsx\")\n\n\ndef VAR(endog, exog, sig_vals = [0.05, 0.01, 0.001], constant = True):\n \n if constant:\n exog[\"Constant\"] = 1\n endog_keys= list(endog.keys())\n exog_keys = list(exog.keys()) \n model = SUR.multivariate_ls(endog,exog)\n results = model.fit()\n \n # save results with columns defined by endogenous variables\n index = results.pvalues.index.str.split(\"_\")\n df = pd.DataFrame(index.to_list(), columns = [\"Sink\", \"Source\"])\n df[\"Coef\"] = results.params.values\n df[\"tstats\"]=results.tstats.values\n df[\"pvalues\"]=results.pvalues.values\n results =df.pivot(columns = \"Sink\", index = \"Source\")\n results = results.round(3)\n keys1 = list(results[\"Coef\"].keys())\n params = results[\"Coef\"].astype(str)\n for endog in keys1:\n keys2 = list(params[endog].keys())\n for sig_val in sig_vals:\n bool_index = results[\"pvalues\"][endog] stop record --> disconnect headset --> export record\nr.create_record_then_export(record_name,\n\t\t\t\t\t\t\trecord_description,\n\t\t\t\t\t\t\trecord_length_s,\n\t\t\t\t\t\t\trecord_export_folder,\n\t\t\t\t\t\t\trecord_export_data_types,\n\t\t\t\t\t\t\trecord_export_format,\n\t\t\t\t\t\t\trecord_export_version )\n# -----------------------------------------------------------\n","sub_path":"python/record.py","file_name":"record.py","file_ext":"py","file_size_in_byte":2382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"614944570","text":"import math\n\nfrom magicbot.state_machine import AutonomousStateMachine, state\n\nfrom automations.alignment import HatchDepositAligner, HatchIntakeAligner\nfrom components.hatch import Hatch\nfrom components.vision import Vision\nfrom pyswervedrive.chassis import SwerveChassis\nfrom utilities.navx import NavX\nfrom utilities.pure_pursuit import PurePursuit, Waypoint, insert_trapezoidal_waypoints\n\n\ndef reflect_y(v: Waypoint) -> Waypoint:\n return Waypoint(v.x, -v.y, v.theta, v.v)\n\n\nclass AutoBase(AutonomousStateMachine):\n\n # Here magicbot injects components\n hatch_deposit: HatchDepositAligner\n hatch_intake: HatchIntakeAligner\n\n chassis: SwerveChassis\n hatch: Hatch\n imu: NavX\n vision: Vision\n\n # This one is just a typehint\n pursuit: PurePursuit\n\n def __init__(self):\n super().__init__()\n self.front_cargo_bay = Waypoint(5.6 - SwerveChassis.LENGTH / 2, 0.2, 0, 0.75)\n self.setup_loading_bay = Waypoint(3.3, 3.3, math.pi, 2)\n self.loading_bay = Waypoint(0.2 + SwerveChassis.LENGTH / 2, 3.4, math.pi, 1)\n self.side_cargo_bay = Waypoint(\n 7, 0.8 + SwerveChassis.WIDTH / 2, -math.pi / 2, 1\n )\n self.side_cargo_bay_alignment_point = Waypoint(\n 7, 1.8 + SwerveChassis.WIDTH / 2, -math.pi / 2, 0.75\n )\n self.start_pos = Waypoint(\n 1.2 + SwerveChassis.LENGTH / 2,\n 0,\n 0,\n 2,\n # + SwerveChassis.WIDTH / 2\n )\n\n self.completed_runs = 0\n self.desired_angle = 0\n self.desired_angle_navx = 0\n self.minimum_path_completion = 0.85\n\n self.acceleration = 1\n self.deceleration = -0.5\n\n self.pursuit = PurePursuit(look_ahead=0.2, look_ahead_speed_modifier=0.25)\n\n def on_enable(self):\n super().on_enable()\n self.chassis.odometry_x = self.start_pos[0]\n self.chassis.odometry_y = self.start_pos[1]\n self.completed_runs = 0\n # print(f\"odometry = {self.current_pos}\")\n\n @state(first=True)\n def drive_to_cargo_bay(self, initial_call):\n if initial_call:\n # print(f\"odometry = {self.current_pos}\")\n if self.completed_runs == 0:\n waypoints = insert_trapezoidal_waypoints(\n (self.current_pos, self.front_cargo_bay),\n self.acceleration,\n self.deceleration,\n )\n elif self.completed_runs == 1:\n waypoints = insert_trapezoidal_waypoints(\n (\n self.current_pos,\n self.side_cargo_bay_alignment_point,\n self.side_cargo_bay,\n ),\n self.acceleration,\n self.deceleration,\n )\n else:\n self.next_state(\"drive_to_loading_bay\")\n self.completed_runs += 1\n return\n self.pursuit.build_path(waypoints)\n self.follow_path()\n if (\n self.vision.fiducial_in_sight and self.ready_for_vision()\n ) or self.pursuit.completed_path:\n self.next_state(\"deposit_hatch\")\n self.completed_runs += 1\n\n @state\n def deposit_hatch(self, initial_call):\n if initial_call:\n self.hatch_deposit.engage(initial_state=\"target_tape_align\")\n if not self.hatch.has_hatch:\n self.next_state(\"drive_to_loading_bay\")\n\n @state\n def drive_to_loading_bay(self, initial_call):\n if initial_call:\n if self.completed_runs == 1:\n waypoints = insert_trapezoidal_waypoints(\n (\n self.current_pos,\n Waypoint(\n self.current_pos[0] - 0.5,\n self.current_pos[1],\n self.imu.getAngle(),\n 1.5,\n ),\n self.setup_loading_bay,\n self.loading_bay,\n ),\n self.acceleration,\n self.deceleration,\n )\n elif self.completed_runs == 2:\n waypoints = insert_trapezoidal_waypoints(\n (self.current_pos, self.setup_loading_bay, self.loading_bay),\n self.acceleration,\n self.deceleration,\n )\n else:\n self.next_state(\"stop\")\n return\n self.pursuit.build_path(waypoints)\n self.follow_path()\n if (\n self.vision.fiducial_in_sight and self.ready_for_vision()\n ) or self.pursuit.completed_path:\n self.next_state(\"intake_hatch\")\n\n @state\n def intake_hatch(self, initial_call):\n if initial_call:\n self.hatch_intake.engage(initial_state=\"target_tape_align\")\n elif not self.hatch_intake.is_executing:\n self.next_state(\"drive_to_cargo_bay\")\n\n @state\n def stop(self):\n self.chassis.set_inputs(0, 0, 0)\n self.done()\n\n @property\n def current_pos(self):\n return Waypoint(\n self.chassis.odometry_x, self.chassis.odometry_y, self.imu.getAngle(), 2\n )\n\n def follow_path(self):\n vx, vy, heading = self.pursuit.find_velocity(self.chassis.position)\n if self.pursuit.completed_path:\n self.chassis.set_inputs(0, 0, 0, field_oriented=False)\n return\n # TODO implement a system to allow for rotation in waypoints\n self.chassis.set_velocity_heading(vx, vy, heading)\n\n def ready_for_vision(self):\n if self.pursuit.waypoints[-1][4] - self.pursuit.distance_traveled < 1:\n return True\n else:\n return False\n\n\nclass RightStartAuto(AutoBase):\n MODE_NAME = \"Right start autonomous\"\n\n def __init__(self):\n super().__init__()\n self.front_cargo_bay = reflect_y(self.front_cargo_bay)\n self.setup_loading_bay = reflect_y(self.setup_loading_bay)\n self.loading_bay = reflect_y(self.loading_bay)\n self.side_cargo_bay = reflect_y(self.side_cargo_bay)\n\n\nclass LeftStartAuto(AutoBase):\n MODE_NAME = \"Left start autonomous\"\n DEFAULT = True\n","sub_path":"autonomous/autonomous.py","file_name":"autonomous.py","file_ext":"py","file_size_in_byte":6283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"265784105","text":"from unittest import TestCase\n\nfrom week12.min_stack import MinStack\n\n\nclass TestMinStack(TestCase):\n def test_push(self):\n obj = MinStack()\n obj.push(-2)\n obj.push(0)\n obj.push(-3)\n print(obj.getMin())\n obj.pop()\n print(obj.top())\n print(obj.getMin())\n param_3 = obj.top()\n param_4 = obj.getMin()\n","sub_path":"week12/test_min_stack.py","file_name":"test_min_stack.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"323439470","text":"# -*- coding: utf-8 -*-\n\"\"\"\nadsb_logger\n\n2017.nov mlabru initial release (Linux/Python)\n\"\"\"\n# < imports >------------------------------------------------------------------\n\n# python library\nimport datetime\nimport logging\nimport argparse\nimport os\nimport subprocess\nimport sys\nimport threading\nimport time\n\n# i2c lcd\nimport logrpi.I2C_LCD_driver\n\n# local\nimport adsb.inquirer as adi\nimport gps.inquirer as gpi\n\n# < defines >------------------------------------------------------------------\n\n# logger\nM_LOG = logging.getLogger(__name__)\nM_LOG.setLevel(logging.DEBUG)\n\n# display lines\nM_LIN_SYS = 1\nM_LIN_DAT = 2\nM_LIN_GPS = 3\nM_LIN_ADS = 4\n\n# < logging >------------------------------------------------------------------\n\n# logger\nM_LOG = logging.getLogger(__name__)\nM_LOG.setLevel(logging.DEBUG)\n\n# -----------------------------------------------------------------------------\ndef get_wifi() -> str:\n \"\"\"\n get_wifi\n \"\"\"\n # logger\n M_LOG.info(\">> get_wifi\")\n\n # init SSID\n ls_ssid = \">no wifi<\"\n\n # get iwconfig output\n ls_scan_output = subprocess.check_output([\"iwconfig\", \"wlan0\"])\n M_LOG.debug(\"ls_scan_output: {}\".format(ls_scan_output))\n\n # for all output tokens...\n for ls_tok in ls_scan_output.split():\n # ESSID token ?\n if ls_tok.startswith(\"ESSID:\"):\n # get SSID\n return ls_tok.split('\"')[1]\n\n # return\n return ls_ssid\n\n# -----------------------------------------------------------------------------\ndef update_display(fthr_gpsi, fthr_adsi, fv_display: bool=True):\n \"\"\"\n update display\n \"\"\"\n # logger\n M_LOG.info(\">> update_display\")\n\n # check input\n assert fthr_gpsi\n assert fthr_adsi\n\n # no display ?\n if not fv_display:\n # return\n return\n\n # create lcd driver\n l_lcd = I2C_LCD_driver.lcd()\n assert l_lcd\n\n # clear screen\n l_lcd.lcd_clear()\n\n # forever...until\n while fthr_adsi.v_running and fthr_gpsi.v_running:\n\n # 12345678901234567890\n # icbox-21 sophosAir\n\n # show system line\n l_lcd.lcd_display_string(\" {} {}\".format(os.uname()[1], get_wifi()), M_LIN_SYS, 0)\n\n # 12345678901234567890\n # 99/99/99 99:99:99\n\n # show date line\n l_lcd.lcd_display_string(\" {}\".format(time.strftime(\"%d/%m/%y %H:%M:%S\")), M_LIN_DAT, 0)\n\n # latitude\n lf_lat = fthr_gpsi.f_latitude\n ls_lat = \"{:02.2f}\".format(lf_lat) if lf_lat is not None else \"None\"\n\n # longitude\n lf_lng = fthr_gpsi.f_longitude\n ls_lng = \"{:03.2f}\".format(lf_lng) if lf_lng is not None else \"None\"\n\n # altitude\n # lf_alt = fthr_gpsi.f_altitude\n # ls_alt = \"{:0.1f}\".format(lf_alt) if lf_alt is not None else \"None\"\n\n # 12345678901234567890\n # F:0 P:-12.34/-012.34\n\n # show gps line\n l_lcd.lcd_display_string(\"F:{} P:{}/{}\".format(fthr_gpsi.session.fix.mode, ls_lat, ls_lng), M_LIN_GPS, 0)\n\n # ajusta para display\n li_short = fthr_adsi.i_short % 10000\n li_extended = fthr_adsi.i_extended % 10000\n li_error = fthr_adsi.i_error % 10000\n\n # 12345678901234567890\n # S:0000 X:0000 S:99/9\n\n # show adsb line\n l_lcd.lcd_display_string(\"S:{:4d} X:{:4d} S:{:2d}/{:1d}\".format(li_short, li_extended, fthr_gpsi.i_sat_in_view, fthr_gpsi.i_sat_used), M_LIN_ADS, 0)\n\n # sleep (update each 4s)\n time.sleep(4)\n\n# -----------------------------------------------------------------------------\ndef main():\n \"\"\"\n drive app\n \"\"\"\n # create sys.arg parser\n l_parser = argparse.ArgumentParser()\n assert l_parser\n\n # parser options\n l_parser.add_argument(\"--display\", help=\"enable LCD display output\",\n dest=\"display\",\n action=\"store_true\")\n l_parser.add_argument(\"--no-display\", help=\"disable LCD display\",\n dest=\"display\", \n action=\"store_false\")\n l_parser.set_defaults(display=True)\n\n # get arguments\n l_args = l_parser.parse_args()\n\n # hostname\n ls_host = os.uname()[1]\n\n # data atual\n ls_date = datetime.datetime.now().strftime(\"%Y%m%d.%H%M\")\n\n # goto exec dir\n os.chdir(os.path.dirname(sys.argv[0]))\n\n # create out file: adsb_logger....dat\n lfh_dat = open(f\"logs/adsb_logger.{ls_host}.{ls_date}.dat\", \"w\")\n assert lfh_dat\n\n # create control file: adsb_logger....ctl\n lfh_ctl = open(f\"logs/adsb_logger.{ls_host}.{ls_date}.ctl\", \"w\")\n assert lfh_ctl\n\n # create the thread gps inquirer\n lthr_gpsi = gpi.GPSInquirer(lfh_ctl)\n assert lthr_gpsi\n\n # create the thread adsb inquirer\n lthr_adsi = adi.ADSBInquirer(lthr_gpsi, lfh_dat)\n assert lthr_adsi\n\n # create thread update display\n lthr_upd_dsp = threading.Thread(target=update_display,\n args=(lthr_gpsi, lthr_adsi, l_args.display))\n assert lthr_upd_dsp\n\n try:\n # start it up\n lthr_gpsi.start()\n\n # start it up\n lthr_adsi.start()\n\n # start update display\n lthr_upd_dsp.start()\n\n # forever...until\n while lthr_gpsi.v_running:\n # sleep 4s\n time.sleep(4)\n\n # em caso de erro...\n except (KeyboardInterrupt, SystemExit):\n # when you press ctrl+c\n print(\"killing threads...\")\n\n # stop running\n lthr_gpsi.v_running = False\n\n # wait for the threads to finish what it's doing\n lthr_gpsi.join()\n lthr_adsi.join()\n lthr_upd_dsp.join()\n\n # close output file\n lfh_dat.close()\n\n # close control file\n lfh_ctl.close()\n\n# -----------------------------------------------------------------------------\n# this is the bootstrap process\n\nif \"__main__\" == __name__:\n # logger\n logging.basicConfig(level=logging.DEBUG)\n\n # exec\n main()\n\n # end app\n sys.exit()\n\n# --------------------------------------------------------------------\n","sub_path":"rpilog/rpi_logger.py","file_name":"rpi_logger.py","file_ext":"py","file_size_in_byte":5998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"245165016","text":"from email.mime.text import MIMEText\nfrom email.header import Header\nimport smtplib\n\ndef email_text():\n#邮件正文,纯文本,字符编码\n message = MIMEText('python send an email to test the server',\"plain\",'utf8') #邮件正文\n message['From'] = Header('zhao@tedu.cn') #发件人\n message[\"To\"] = Header(\"zhao1991mg@163.cn\",'utf8') #收件人\n message['Subject'] = Header('test email','utf8') #主题\n smtp = smtplib.SMTP('localhost') #本机作为邮件服务器发送邮件\n sender = 'zhao@tedu.cn'\n receivers = ['zhao1991mg@qq.com','zhao1991mg@163.com'] #收件人列表,可以有很多个\n smtp.sendmail(sender,receivers,message.as_string()) #最后邮件的类型可以选bytes也可以选string类型\n\ndef teacher():\n message = MIMEText('python邮件发送测试\\n', 'plain', 'utf8')\n message['From'] = Header('zzg@tedu.cn', 'utf8') # 收件人\n message['To'] = Header('zhangzhigang79@126.com', 'utf8') # 发件人\n message['Subject'] = Header('测试邮件', 'utf8') # 主题\n smtp = smtplib.SMTP('localhost') # 本机作为邮件服务器发送邮件\n sender = 'zzg@tedu.cn' # 发件人\n receivers = ['zhangzhigang79@126.com', 'root@localhost'] # 收件人列表\n smtp.sendmail(sender,receivers,message.as_string())\n\nif __name__ == '__main__':\n email_text()","sub_path":"python/day12-mail-json-zabbix/send_email.py","file_name":"send_email.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"612603552","text":"from .models import Theory, Indicator, Strategy\nfrom django.views import generic\nfrom .methods import functions, indicators, strategies, analysis, toolFuncs\n\nfrom django.http import JsonResponse\nimport inspect\nfrom django.shortcuts import render\nimport json\n\nfrom .forms import *\n\ndef index(request):\n return render(\n request,\n 'index.html',\n )\n \nclass TheoryListView(generic.ListView):\n model = Theory\n \nclass TheoryDetailView(generic.DetailView):\n model = Theory\n \nclass IndicatorListView(generic.ListView):\n model = Indicator\n \nclass IndicatorDetailView(generic.DetailView):\n model = Indicator\n\nclass StrategyListView(generic.ListView):\n model = Strategy\n \nclass StrategyDetailView(generic.DetailView):\n model = Strategy\n \ndef Develop(request):\n developInitialForm = DevelopInitialForm()\n selectStrategyForm = SelectStrategyForm()\n return render(\n request,\n 'develop.html',\n {'developInitialForm': developInitialForm,\n 'selectStrategyForm': selectStrategyForm, \n }\n )\n\ndef Method(request):\n getDataForm = GetDataForm()\n selectIndicatorForm = SelectIndicatorForm()\n selectStrategyForm = SelectStrategyForm()\n selectAnalysisForm = SelectAnalysisForm()\n \n return render(\n request,\n 'methods.html',\n {'getDataForm': getDataForm, \n 'selectIndicatorForm': selectIndicatorForm,\n 'selectStrategyForm': selectStrategyForm, \n 'selectAnalysisForm': selectAnalysisForm, \n }\n )\n \n \ndef GetData(request):\n symbol = request.POST.get('symbol') \n start = request.POST.get('start')\n end = request.POST.get('end')\n interval = request.POST.get('interval')\n\n# =============================================================================\n# if symbol and start and end and interval:\n# stock = functions.Generic(symbol, start, end, interval)\n# data = stock._data \n# new_data = dict(data.reset_index())\n# for ele in new_data:\n# new_data[ele] = list(new_data[ele])\n# return JsonResponse(new_data)\n# else:\n# return JsonResponse({'symbol':symbol, 'start':start, 'end':end, 'interval':interval})\n# =============================================================================\n\n stock = functions.Generic(symbol, start, end, interval) \n data = stock._data \n new_data = dict(data.reset_index())\n for ele in new_data:\n new_data[ele] = list(new_data[ele])\n \n return JsonResponse(new_data)\n \ndef GetMethodArg(request):\n Name = request.POST.get('name', None)\n Type = request.POST.get('type', None) \n \n if Type == 'indicator':\n lib = indicators\n elif Type == 'strategy':\n lib = strategies\n else:\n lib = analysis\n \n for ind in inspect.getmembers(lib, inspect.isfunction):\n if ind[0] == Name:\n arg = ind[1].__code__.co_varnames[:ind[1].__code__.co_argcount]\n arg = [ele for ele in arg if ele!='data'] #remove the input 'data'\n helpText = ind[1].__doc__\n if helpText:\n helpText = [line.strip() for line in helpText.strip().splitlines()]\n # remove useless spaces, split by line \n\n return JsonResponse({'arg': arg, 'helpText': helpText})\n \ndef UseMethod(request):\n requestDic = json.loads(request.body)\n Name = requestDic.get('name', None)\n Type = requestDic.get('type', None)\n\n if Type == 'indicator':\n lib = indicators\n elif Type == 'strategy':\n lib = strategies\n else:\n lib = analysis\n\n data = {}\n data['Open'] = requestDic.get('Open', None) \n data['Close'] = requestDic.get('Close', None) \n data['High'] = requestDic.get('High', None) \n data['Low'] = requestDic.get('Low', None) \n data['Volume'] = requestDic.get('Volume', None) \n data['Date'] = requestDic.get('Date', None) \n\n kwargs = {'data': data} \n keys = requestDic.keys() - {'name', 'type', 'Open', 'Close', 'High', \n 'Low', 'Volume', 'Date', 'Adj Close', 'Amount'}\n for key in keys:\n kwargs[key] = eval(requestDic.get(key, None))\n \n for ind in inspect.getmembers(lib, inspect.isfunction):\n if ind[0] == Name:\n output = ind[1](**kwargs)\n return JsonResponse(output)\n \ndef AnalyzeStrategy(request):\n requestDic = json.loads(request.body)\n Name = requestDic.get('name', None) \n \n data = {}\n data['Open'] = requestDic.get('Open', None) \n data['Close'] = requestDic.get('Close', None) \n data['High'] = requestDic.get('High', None) \n data['Low'] = requestDic.get('Low', None) \n data['Volume'] = requestDic.get('Volume', None) \n data['Date'] = requestDic.get('Date', None)\n \n kwargs = {'data': data} \n keys = requestDic.keys() - {'name', 'interval', 'symbol', 'Open', 'Close', 'High', \n 'Low', 'Volume', 'Date', 'Adj Close', 'Amount'} \n \n for key in keys:\n kwargs[key] = eval(requestDic.get(key, None))\n \n for ind in inspect.getmembers(strategies, inspect.isfunction):\n if ind[0] == Name:\n output = ind[1](**kwargs)\n \n equity = output['equity']['data']\n positions = output['positions']['data']\n ordersData = output['ordersData']['data']\n \n data['Interval'] = requestDic.get('interval', None)\n data['Symbol'] = requestDic.get('symbol', None) \n result = toolFuncs.StrategyAnalyses(data, equity, positions, ordersData)\n return JsonResponse(result)\n \n \n \n ","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"413295974","text":"\nfrom collections import OrderedDict\nfrom enum import IntEnum\nimport copy\nimport itertools\nimport os\nimport yaml\n\nfrom . import instances\nfrom . import util\n\ndef get_aux_subdir(base_dir, experiment, variation, revision):\n\tvar = ''\n\tif variation:\n\t\tvar = '~' + ','.join(variation)\n\trev = ''\n\tif revision:\n\t\trev = '@' + revision\n\treturn os.path.join(base_dir, 'aux', experiment + var + rev)\n\ndef get_output_subdir(base_dir, experiment, variation, revision):\n\tvar = ''\n\tif variation:\n\t\tvar = '~' + ','.join(variation)\n\trev = ''\n\tif revision:\n\t\trev = '@' + revision\n\treturn os.path.join(base_dir, 'output', experiment + var + rev)\n\ndef get_aux_file_name(ext, instance, repetition):\n\t(fbase, _) = os.path.splitext(instance)\n\trep = ''\n\tif repetition > 0:\n\t\trep = '[{}]'.format(repetition)\n\treturn fbase + '.' + ext + rep\n\ndef get_output_file_name(ext, instance, repetition):\n\t(fbase, _) = os.path.splitext(instance)\n\trep = ''\n\tif repetition > 0:\n\t\trep = '[{}]'.format(repetition)\n\treturn fbase + '.' + ext + rep\n\nclass MatrixScope:\n\t@staticmethod\n\tdef walk_matrix(cfg, root_yml, expand):\n\t\toutmost = MatrixScope(cfg, None)\n\n\t\tresult = set()\n\t\tif 'matrix' not in root_yml:\n\t\t\tresult.update(expand(outmost))\n\t\telse:\n\t\t\tfor item_yml in root_yml['matrix']['include']:\n\t\t\t\tscope = MatrixScope(cfg, outmost)\n\t\t\t\tscope.select(item_yml)\n\t\t\t\tresult.update(expand(scope))\n\n\t\treturn result\n\n\tdef __init__(self, cfg, outer):\n\t\tself.cfg = cfg\n\n\t\tif outer is not None:\n\t\t\tself.selected_exps = copy.copy(outer.selected_exps)\n\t\t\tself.selected_revs = copy.copy(outer.selected_revs)\n\t\t\tself.selected_axes = copy.copy(outer.selected_axes)\n\t\t\tself.selected_variants = copy.deepcopy(outer.selected_variants)\n\t\t\tself.selected_instsets = copy.copy(outer.selected_instsets)\n\t\t\tself.num_repetitions = outer.num_repetitions\n\t\telse:\n\t\t\tself.selected_exps = None\n\t\t\tself.selected_revs = None\n\t\t\tself.selected_axes = None\n\t\t\tself.selected_variants = {}\n\t\t\tself.selected_instsets = None\n\t\t\tself.num_repetitions = None\n\n\tdef select(self, item_yml):\n\t\tif 'experiments' in item_yml:\n\t\t\tif self.selected_exps is None:\n\t\t\t\tself.selected_exps = set()\n\t\t\tself.selected_exps.update(item_yml['experiments'])\n\n\t\tif 'revisions' in item_yml:\n\t\t\tif self.selected_revs is None:\n\t\t\t\tself.selected_revs = set()\n\t\t\tself.selected_revs.update(item_yml['revisions'])\n\n\t\tif 'axes' in item_yml:\n\t\t\tif self.selected_axes is None:\n\t\t\t\tself.selected_axes = set()\n\t\t\tself.selected_axes.update(item_yml['axes'])\n\n\t\tif 'variants' in item_yml:\n\t\t\tfor name in item_yml['variants']:\n\t\t\t\tvariant = self.cfg.get_variant(name)\n\t\t\t\tif variant.axis not in self.selected_variants:\n\t\t\t\t\tself.selected_variants[variant.axis] = set()\n\t\t\t\tself.selected_variants[variant.axis].add(variant.name)\n\n\t\tif 'instsets' in item_yml:\n\t\t\tif self.selected_instsets is None:\n\t\t\t\tself.selected_instsets = set()\n\t\t\tself.selected_instsets.update(item_yml['instsets'])\n\n\t\tif 'repeat' in item_yml:\n\t\t\tself.num_repetitions = item_yml['repeat']\n\nclass Config:\n\t\"\"\"Represents the entire configuration (i.e., an experiments.yml file).\"\"\"\n\n\tdef __init__(self, basedir, yml):\n\t\tassert os.path.isabs(basedir)\n\t\tself.basedir = basedir\n\t\tself.yml = yml\n\n\t\tself._insts = OrderedDict()\n\t\tself._build_infos = OrderedDict()\n\t\tself._revisions = OrderedDict()\n\t\tself._variants = OrderedDict()\n\t\tself._exp_infos = OrderedDict()\n\n\t\tdef construct_instances():\n\t\t\tif 'instances' in self.yml:\n\t\t\t\tfor inst_yml in self.yml['instances']:\n\t\t\t\t\tfor item in inst_yml['items']:\n\t\t\t\t\t\tyield Instance(self, item, inst_yml)\n\n\t\tdef construct_variants():\n\t\t\tif 'variants' in self.yml:\n\t\t\t\tfor axis_yml in self.yml['variants']:\n\t\t\t\t\tfor variant_yml in axis_yml['items']:\n\t\t\t\t\t\tyield Variant(self, axis_yml['axis'], variant_yml)\n\n\t\tfor inst in sorted(construct_instances(), key=lambda inst: inst.filename):\n\t\t\tself._insts[inst.filename] = inst\n\n\t\tif 'builds' in self.yml:\n\t\t\tfor build_yml in sorted(self.yml['builds'], key=lambda y: y['name']):\n\t\t\t\tself._build_infos[build_yml['name']] = BuildInfo(self, build_yml)\n\n\t\tif 'revisions' in self.yml:\n\t\t\tfor revision_yml in sorted(self.yml['revisions'], key=lambda y: y['name']):\n\t\t\t\tself._revisions[revision_yml['name']] = Revision(self, revision_yml)\n\n\t\tfor variant in sorted(construct_variants(), key=lambda variant: variant.name):\n\t\t\tself._variants[variant.name] = variant\n\n\t\tif 'experiments' in self.yml:\n\t\t\tfor exp_yml in sorted(self.yml['experiments'], key=lambda y: y['name']):\n\t\t\t\tself._exp_infos[exp_yml['name']] = ExperimentInfo(self, exp_yml)\n\n\tdef instance_dir(self):\n\t\t\"\"\"Path of the directory that stores all the instances.\"\"\"\n\t\treturn os.path.join(self.basedir, self.yml['instdir'])\n\n\tdef all_instance_ids(self):\n\t\tfor inst in self.all_instances():\n\t\t\tyield inst.filename\n\n\tdef all_instances(self):\n\t\tyield from self._insts.values()\n\n\tdef get_instance(self, name):\n\t\tif name not in self._insts:\n\t\t\traise RuntimeError(\"Instance {} does not exist\".format(name))\n\t\treturn self._insts[name]\n\n\tdef get_build_info(self, name):\n\t\tif name not in self._build_infos:\n\t\t\traise RuntimeError(\"BuildInfo {} does not exist\".format(name))\n\t\treturn self._build_infos[name]\n\n\tdef all_revisions(self):\n\t\tyield from self._revisions.values()\n\n\tdef get_revision(self, name):\n\t\tif name is None: # TODO: Questionable special case.\n\t\t\treturn None\n\t\tif name not in self._revisions:\n\t\t\traise RuntimeError(\"Revision {} does not exist\".format(name))\n\t\treturn self._revisions[name]\n\n\tdef all_builds(self):\n\t\tif 'builds' in self.yml:\n\t\t\tfor build_yml in sorted(self.yml['builds'], key=lambda y: y['name']):\n\t\t\t\tfor revision in self.all_revisions():\n\t\t\t\t\tspec_set = set(revision.specified_versions)\n\t\t\t\t\tif build_yml['name'] not in spec_set:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t# TODO: Exclude the build if not all requirements are specified in spec_set.\n\t\t\t\t\tyield Build(self, self.get_build_info(build_yml['name']), revision)\n\n\tdef all_builds_for_revision(self, revision):\n\t\tfor build in self.all_builds():\n\t\t\tif build.revision == revision:\n\t\t\t\tyield build\n\n\tdef get_build(self, name, revision):\n\t\tfor build in self.all_builds(): # TODO: Avoid a quadratic blowup.\n\t\t\tif build.name == name and build.revision == revision:\n\t\t\t\treturn build\n\t\traise RuntimeError(\"Build {} does not exist\".format(name))\n\n\tdef all_variants(self):\n\t\tyield from self._variants.values()\n\n\tdef get_variant(self, name):\n\t\tif name not in self._variants:\n\t\t\traise RuntimeError(\"Variant {} does not exist\".format(name))\n\t\treturn self._variants[name]\n\n\tdef _test_variation_id_in_scope(self, variation_id, scope):\n\t\tif scope.selected_axes is not None:\n\t\t\tfor name in variation_id:\n\t\t\t\tvariant = self.get_variant(name)\n\t\t\t\tif variant.axes not in scope.selected_axes:\n\t\t\t\t\treturn False\n\t\tif scope.selected_variants is not None:\n\t\t\tfor name in variation_id:\n\t\t\t\tvariant = self.get_variant(name)\n\t\t\t\tif variant.axis in scope.selected_variants:\n\t\t\t\t\tif variant.name not in scope.selected_variants[variant.axis]:\n\t\t\t\t\t\treturn False\n\t\treturn True\n\n\t# Determine all variations selected by a scope.\n\tdef _expand_variation_ids_in_scope(self, scope):\n\t\tif scope.selected_axes is None:\n\t\t\taxes = {var.axis for var in self.all_variants()}\n\t\telse:\n\t\t\taxes = scope.selected_axes\n\n\t\tvariants = {}\n\t\tfor axis in axes:\n\t\t\tif scope.selected_variants is None or axis not in scope.selected_variants:\n\t\t\t\tvariants[axis] = {var.name for var in self.all_variants() if var.axis == axis}\n\t\t\telse:\n\t\t\t\tvariants[axis] = scope.selected_variants[axis]\n\n\t\tvariation_bundle = [ ]\n\t\tfor axis_variants in variants.values():\n\t\t\t# Sort once so that variation order is deterministic.\n\t\t\tvariant_list = sorted(axis_variants, key=lambda name: name if name is not None else '')\n\t\t\tvariation_bundle.append(variant_list)\n\n\t\t# A variation is defined as a tuple of variants.\n\t\tdef make_variation(prod):\n\t\t\tvariant_filter = filter(lambda name: name is not None, prod)\n\t\t\t# Sort again so that order of the variants does not depend on the axes.\n\t\t\tvariant_list = sorted(variant_filter)\n\t\t\treturn tuple(variant_list)\n\n\t\treturn [make_variation(prod) for prod in itertools.product(*variation_bundle)]\n\n\tdef get_experiment_info(self, name):\n\t\tif name not in self._exp_infos:\n\t\t\traise RuntimeError(\"Experiment {} does not exist\".format(name))\n\t\treturn self._exp_infos[name]\n\n\tdef all_experiments(self):\n\t\tfor exp_name, rev_name, var_names in self._expand_experiment_matrix():\n\t\t\trevision = self.get_revision(rev_name)\n\t\t\tvariation = [self.get_variant(var_name) for var_name in var_names]\n\t\t\tyield Experiment(self, self.get_experiment_info(exp_name), revision, variation)\n\n\tdef _expand_experiment_matrix(self):\n\t\tdef expand(scope):\n\t\t\t# Determine all experiments selected by this scope.\n\t\t\tif scope.selected_exps is None:\n\t\t\t\texperiments = [exp_yml['name'] for exp_yml in self.yml['experiments']]\n\t\t\telse:\n\t\t\t\texperiments = scope.selected_exps\n\n\t\t\t# Helper to find all selected revisions for a given experiment.\n\t\t\tdef revisions_for_experiment(exp_name):\n\t\t\t\tif scope.selected_revs is None:\n\t\t\t\t\tif 'use_builds' in self.get_experiment_info(exp_name)._exp_yml:\n\t\t\t\t\t\tfor revision in self.all_revisions():\n\t\t\t\t\t\t\tyield revision.name\n\t\t\t\t\telse:\n\t\t\t\t\t\tyield None\n\t\t\t\telse:\n\t\t\t\t\tyield from scope.selected_revs\n\n\t\t\tvariation_ids = self._expand_variation_ids_in_scope(scope)\n\t\t\tfor exp_name in experiments:\n\t\t\t\tyield from itertools.product([exp_name], revisions_for_experiment(exp_name),\n\t\t\t\t\t\tvariation_ids)\n\n\t\texpansion = MatrixScope.walk_matrix(self, self.yml, expand)\n\t\treturn sorted(expansion)\n\n\tdef _experiment_matches_item(self, item_yml, name, revision):\n\t\tif 'experiments' in item_yml:\n\t\t\tif name not in item_yml['experiments']:\n\t\t\t\treturn False\n\t\tif revision is None:\n\t\t\tif 'revisions' in item_yml:\n\t\t\t\treturn False\n\t\telse:\n\t\t\tif 'revisions' in item_yml:\n\t\t\t\tif revision.name not in item_yml['revisions']:\n\t\t\t\t\treturn False\n\t\treturn True\n\n\tdef discover_all_runs(self):\n\t\tfor exp in self.all_experiments():\n\t\t\tfor inst_name, rep in self._expand_run_matrix(exp):\n\t\t\t\tinstance = self.get_instance(inst_name)\n\t\t\t\tyield Run(self, exp, instance, rep)\n\n\tdef _expand_run_matrix(self, exp):\n\t\tdef expand(scope):\n\t\t\tif scope.selected_exps is not None:\n\t\t\t\tif exp.name not in scope.selected_exps:\n\t\t\t\t\treturn\n\t\t\tif scope.selected_revs is not None:\n\t\t\t\tif exp.revision.name not in scope.selected_revs:\n\t\t\t\t\treturn\n\t\t\tif scope.selected_variants is not None:\n\t\t\t\tvariation_id = tuple(var.name for var in exp.variation)\n\t\t\t\tif variation_id not in self._expand_variation_ids_in_scope(scope):\n\t\t\t\t\treturn\n\n\t\t\tif scope.selected_instsets is not None:\n\t\t\t\tinstsets = scope.selected_instsets\n\t\t\telse:\n\t\t\t\tinstset_combinations = [instance.instsets for instance in self.all_instances()]\n\t\t\t\tinstsets = set().union(*instset_combinations)\n\n\t\t\tfor instance in self.all_instances():\n\t\t\t\tif instsets.isdisjoint(instance.instsets):\n\t\t\t\t\tcontinue\n\n\t\t\t\treps = range(0, 1)\n\t\t\t\tif scope.num_repetitions is not None:\n\t\t\t\t\treps = range(0, scope.num_repetitions)\n\t\t\t\telif 'repeat' in exp.info._exp_yml:\n\t\t\t\t\treps = range(0, exp.info._exp_yml['repeat'])\n\t\t\t\tfor rep in reps:\n\t\t\t\t\tyield (instance.filename, rep)\n\n\t\texpansion = MatrixScope.walk_matrix(self, self.yml, expand)\n\t\treturn sorted(expansion)\n\n\tdef collect_successful_results(self, parse_fn):\n\t\t\"\"\"\n\t\tCollects all success runs and parses their output.\n\n\t\t:param: parse_fn: Function to parse the output. Takes two parameters\n\t\t\t(run, f) where run is a :class:`simexpal.base.Run` object and f\n\t\t\tis a Python file object.\n\t\t\"\"\"\n\n\t\tres = [ ]\n\t\tfor run in self.discover_all_runs():\n\t\t\texp = run.experiment\n\t\t\tfinished = os.access(run.output_file_path('status'), os.F_OK)\n\t\t\tif not finished:\n\t\t\t\tprint(\"Skipping unfinished run {}/{}[{}]\".format(run.experiment.name,\n\t\t\t\t\t\trun.instance.shortname, run.repetition))\n\t\t\t\tcontinue\n\n\t\t\twith open(run.output_file_path('status'), \"r\") as f:\n\t\t\t\tstatus_dict = yaml.load(f, Loader=yaml.Loader)\n\t\t\tif status_dict['timeout'] or status_dict['signal'] or status_dict['status'] > 0:\n\t\t\t\tprint(\"Skipping failed run {}/{}[{}]\".format(run.experiment.name,\n\t\t\t\t\t\trun.instance.shortname, run.repetition))\n\t\t\t\tcontinue\n\n\t\t\twith open(run.output_file_path('out'), 'r') as f:\n\t\t\t\tres.append(parse_fn(run, f))\n\t\treturn res\n\nclass Instance:\n\t\"\"\"Represents a single instance\"\"\"\n\n\tdef __init__(self, cfg, filename, inst_yml):\n\t\tself._cfg = cfg\n\t\tself.filename = filename\n\t\tself._inst_yml = inst_yml\n\n\t@property\n\tdef config(self):\n\t\treturn self._cfg\n\n\t@property\n\tdef shortname(self):\n\t\treturn os.path.splitext(self.filename)[0]\n\n\t@property\n\tdef fullpath(self):\n\t\treturn os.path.join(self._cfg.instance_dir(), self.filename)\n\n\t@property\n\tdef instsets(self):\n\t\tif 'set' not in self._inst_yml:\n\t\t\treturn set([None])\n\t\tif isinstance(self._inst_yml['set'], list):\n\t\t\treturn set(self._inst_yml['set'])\n\t\tassert isinstance(self._inst_yml['set'], str)\n\t\treturn set([self._inst_yml['set']])\n\n\t@property\n\tdef repo(self):\n\t\tif 'repo' not in self._inst_yml:\n\t\t\treturn None\n\t\treturn self._inst_yml['repo']\n\n\tdef check_available(self):\n\t\treturn os.path.isfile(os.path.join(self._cfg.instance_dir(), self.filename))\n\n\tdef install(self):\n\t\tif self.check_available():\n\t\t\treturn\n\n\t\tutil.try_mkdir(self._cfg.instance_dir())\n\n\t\tif 'repo' in self._inst_yml:\n\t\t\tif self._inst_yml['repo'] == 'local':\n\t\t\t\treturn\n\n\t\tpartial_path = os.path.join(self._cfg.instance_dir(), self.filename)\n\t\tif 'repo' in self._inst_yml:\n\t\t\tprint(\"Downloading instance '{}' from {} repository\".format(self.filename,\n\t\t\t\t\tself._inst_yml['repo']))\n\n\t\t\tinstances.download_instance(self._inst_yml,\n\t\t\t\t\tself.config.instance_dir(), self.filename, partial_path, '.post0')\n\t\telse:\n\t\t\tassert 'generator' in self._inst_yml\n\t\t\timport subprocess\n\n\t\t\tdef substitute(p):\n\t\t\t\tif p == 'INSTANCE_FILENAME':\n\t\t\t\t\treturn self.filename\n\t\t\t\traise RuntimeError(\"Unexpected parameter {}\".format(p))\n\n\t\t\tprint(\"Generating instance '{}'\".format(self.filename))\n\n\t\t\tassert isinstance(self._inst_yml['generator']['args'], list)\n\t\t\tcmd = [util.expand_at_params(arg_tmpl, substitute) for arg_tmpl\n\t\t\t\t\tin self._inst_yml['generator']['args']]\n\n\t\t\twith open(partial_path + '.gen', 'w') as f:\n\t\t\t\tsubprocess.check_call(cmd, cwd=self.config.basedir,\n\t\t\t\t\t\tstdout=f, stderr=subprocess.PIPE)\n\t\t\tos.rename(partial_path + '.gen', partial_path + '.post0')\n\n\t\tstage = 0\n\t\tif 'postprocess' in self._inst_yml:\n\t\t\tassert self._inst_yml['postprocess'] == 'to_edgelist'\n\t\t\tinstances.convert_to_edgelist(self._inst_yml,\n\t\t\t\t\tpartial_path + '.post0', partial_path + '.post1');\n\t\t\tos.unlink(partial_path + '.post0')\n\t\t\tstage = 1\n\n\t\tos.rename(partial_path + '.post{}'.format(stage), partial_path)\n\n\tdef run_transform(self, transform, out_path):\n\t\tstage = 0\n\t\tassert transform == 'to_edgelist'\n\t\tinstances.convert_to_edgelist(self._inst_yml,\n\t\t\t\tself.fullpath, out_path + '.transf1');\n\t\tstage = 1\n\n\t\tos.rename(out_path + '.transf{}'.format(stage), out_path)\n\nclass BuildInfo:\n\tdef __init__(self, cfg, build_yml):\n\t\tself._cfg = cfg\n\t\tself._build_yml = build_yml\n\n\t@property\n\tdef name(self):\n\t\treturn self._build_yml['name']\n\n\t@property\n\tdef repo_dir(self):\n\t\treturn os.path.join(self._cfg.basedir, 'builds', self.name + '.repo')\n\n\t@property\n\tdef requirements(self):\n\t\tif 'requires' in self._build_yml:\n\t\t\tif isinstance(self._build_yml['requires'], list):\n\t\t\t\tfor name in self._build_yml['requires']:\n\t\t\t\t\tyield name\n\t\t\telse:\n\t\t\t\tassert isinstance(self._build_yml['requires'], str)\n\t\t\t\tyield self._build_yml['requires']\n\n\tdef traverse_requirements(self):\n\t\t# Perform a DFS to discover all recursively required builds.\n\t\tstack = []\n\t\tvisited = set()\n\n\t\tfor req_name in self.requirements:\n\t\t\tassert req_name not in visited\n\t\t\treq_info = self._cfg.get_build_info(req_name)\n\t\t\tstack.append(req_info)\n\t\t\tvisited.add(req_name)\n\n\t\twhile len(stack):\n\t\t\tcurrent = stack.pop()\n\t\t\tyield current\n\t\t\tfor req_name in current.requirements:\n\t\t\t\tif req_name in visited:\n\t\t\t\t\tcontinue\n\t\t\t\treq_info = self._cfg.get_build_info(req_name)\n\t\t\t\tstack.append(req_info)\n\t\t\t\tvisited.add(req_name)\n\n\t@property\n\tdef exports_python(self):\n\t\tif 'exports_python' not in self._build_yml:\n\t\t\treturn []\n\t\treturn [self._build_yml['exports_python']]\n\n\t@property\n\tdef configure(self):\n\t\treturn self._build_yml.get('configure', [])\n\n\t@property\n\tdef compile(self):\n\t\treturn self._build_yml.get('compile', [])\n\n\t@property\n\tdef install(self):\n\t\treturn self._build_yml.get('install', [])\n\n\t@property\n\tdef git_repo(self):\n\t\treturn self._build_yml.get('git', '')\n\n\t@property\n\tdef recursive_clone(self):\n\t\treturn self._build_yml.get('recursive-clone', False)\n\n\t@property\n\tdef regenerate(self):\n\t\treturn self._build_yml.get('regenerate', [])\n\nclass Revision:\n\tdef __init__(self, cfg, revision_yml):\n\t\tself._cfg = cfg\n\t\tself.revision_yml = revision_yml\n\n\t@property\n\tdef name(self):\n\t\treturn self.revision_yml['name']\n\n\t@property\n\tdef specified_versions(self):\n\t\treturn self.revision_yml['build_version'].keys()\n\n\tdef version_for_build(self, build_name):\n\t\treturn self.revision_yml['build_version'][build_name]\n\nclass Build:\n\tdef __init__(self, cfg, info, revision):\n\t\tself._cfg = cfg\n\t\tself.info = info\n\t\tself.revision = revision\n\n\t@property\n\tdef name(self):\n\t\treturn self.info.name\n\n\t@property\n\tdef clone_dir(self):\n\t\trev = '@' + self.revision.name\n\t\treturn os.path.join(self._cfg.basedir, 'builds', self.name + rev + '.clone')\n\n\t@property\n\tdef compile_dir(self):\n\t\trev = '@' + self.revision.name\n\t\treturn os.path.join(self._cfg.basedir, 'builds', self.name + rev + '.compile')\n\n\t@property\n\tdef prefix_dir(self):\n\t\trev = '@' + self.revision.name\n\t\treturn os.path.join(self._cfg.basedir, 'builds', self.name + rev)\n\ndef extract_process_settings(yml):\n\tif 'num_nodes' not in yml:\n\t\treturn None\n\treturn {\n\t\t'num_nodes': yml['num_nodes'],\n\t\t'procs_per_node': yml.get('procs_per_node', None)\n\t}\n\ndef extract_thread_settings(yml):\n\tif 'num_threads' not in yml:\n\t\treturn None\n\treturn {\n\t\t'num_threads': yml['num_threads']\n\t}\n\nclass Variant:\n\tdef __init__(self, cfg, axis, variant_yml):\n\t\tself._cfg = cfg\n\t\tself.axis = axis\n\t\tself.variant_yml = variant_yml\n\n\t@property\n\tdef name(self):\n\t\treturn self.variant_yml['name']\n\n\t@property\n\tdef process_settings(self):\n\t\treturn extract_process_settings(self.variant_yml)\n\n\t@property\n\tdef thread_settings(self):\n\t\treturn extract_thread_settings(self.variant_yml)\n\nclass ExperimentInfo:\n\tdef __init__(self, cfg, exp_yml):\n\t\tself._cfg = cfg\n\t\tself._exp_yml = exp_yml\n\n\t@property\n\tdef name(self):\n\t\treturn self._exp_yml['name']\n\n\t@property\n\tdef used_builds(self):\n\t\tif 'use_builds' in self._exp_yml:\n\t\t\tfor name in self._exp_yml['use_builds']:\n\t\t\t\tyield name\n\n\t@property\n\tdef process_settings(self):\n\t\treturn extract_process_settings(self._exp_yml)\n\n\t@property\n\tdef thread_settings(self):\n\t\treturn extract_thread_settings(self._exp_yml)\n\n\t@property\n\tdef slurm_args(self):\n\t\treturn self._exp_yml.get('slurm_args',[])\n\nclass Experiment:\n\t\"\"\"\n\tRepresents an experiment (see below).\n\n\tAn experiment is defined as a combination of command line arguments\n\tand environment\n\t(from the experiment stanza in a experiments.yml file),\n\ta revision that is used to build the experiment's program\n\tand a set of variants (from the variants stanza in a experiments.yml file).\n\t\"\"\"\n\n\tdef __init__(self, cfg, info, revision, variation):\n\t\tself._cfg = cfg\n\t\tself.info = info\n\t\tself.revision = revision\n\t\tself.variation = variation\n\n\t@property\n\tdef name(self):\n\t\treturn self.info.name\n\n\t@property\n\tdef aux_subdir(self):\n\t\treturn get_aux_subdir(self._cfg.basedir, self.name,\n\t\t\t\t[variant.name for variant in self.variation],\n\t\t\t\tself.revision.name if self.revision else None)\n\n\t@property\n\tdef output_subdir(self):\n\t\treturn get_output_subdir(self._cfg.basedir, self.name,\n\t\t\t\t[variant.name for variant in self.variation],\n\t\t\t\tself.revision.name if self.revision else None)\n\n\t@property\n\tdef effective_process_settings(self):\n\t\ts = None\n\t\tfor variant in self.variation:\n\t\t\tvs = variant.process_settings\n\t\t\tif not vs:\n\t\t\t\tcontinue\n\t\t\tif s:\n\t\t\t\traise RuntimeError('Process settings overriden by multiple variants')\n\t\t\ts = vs\n\t\treturn s or self.info.process_settings\n\n\t@property\n\tdef effective_thread_settings(self):\n\t\ts = None\n\t\tfor variant in self.variation:\n\t\t\tvs = variant.thread_settings\n\t\t\tif not vs:\n\t\t\t\tcontinue\n\t\t\tif s:\n\t\t\t\traise RuntimeError('Thread settings overriden by multiple variants')\n\t\t\ts = vs\n\t\treturn s or self.info.thread_settings\n\n\t@property\n\tdef display_name(self):\n\t\tdisplay_name = self.name\n\t\tif self.variation:\n\t\t\tdisplay_name += ' ~ ' + ', '.join([variant.name for variant in self.variation])\n\t\tif self.revision:\n\t\t\tdisplay_name += ' @ ' + self.revision.name\n\t\treturn display_name\n\nclass Status(IntEnum):\n\tNOT_SUBMITTED = 0\n\tSUBMITTED = 1\n\tIN_SUBMISSION = 2\n\tSTARTED = 3\n\tFINISHED = 4\n\tTIMEOUT = 5\n\tKILLED = 6\n\tFAILED = 7\n\n\tdef __str__(self):\n\t\tif self.value == Status.NOT_SUBMITTED:\n\t\t\treturn 'not submitted'\n\t\tif self.value == Status.SUBMITTED:\n\t\t\treturn 'submitted'\n\t\tif self.value == Status.IN_SUBMISSION:\n\t\t\treturn 'in submission'\n\t\tif self.value == Status.STARTED:\n\t\t\treturn 'started'\n\t\tif self.value == Status.FINISHED:\n\t\t\treturn 'finished'\n\t\tif self.value == Status.TIMEOUT:\n\t\t\treturn 'timeout'\n\t\tif self.value == Status.KILLED:\n\t\t\treturn 'killed'\n\t\tif self.value == Status.FAILED:\n\t\t\treturn 'failed'\n\n\t@property\n\tdef is_positive(self):\n\t\treturn self.value == Status.FINISHED\n\n\t@property\n\tdef is_neutral(self):\n\t\treturn self.value in [Status.IN_SUBMISSION, Status.SUBMITTED, Status.STARTED]\n\n\t@property\n\tdef is_negative(self):\n\t\treturn self.value in [Status.TIMEOUT, Status.KILLED, Status.FAILED]\n\nclass Run:\n\tdef __init__(self, cfg, experiment, instance, repetition):\n\t\tself._cfg = cfg\n\t\tself.experiment = experiment\n\t\tself.instance = instance\n\t\tself.repetition = repetition\n\n\t@property\n\tdef config(self):\n\t\treturn self._cfg\n\n\t# Contains auxiliary files that SHOULD NOT be necessary to determine the result of the run.\n\tdef aux_file_path(self, ext):\n\t\treturn os.path.join(self.experiment.aux_subdir,\n\t\t\t\tget_aux_file_name(ext, self.instance.filename, self.repetition))\n\n\t# Contains the final output files; those SHOULD be all that is necessary to determine\n\t# if the run succeeded and to evaluate its result.\n\tdef output_file_path(self, ext):\n\t\treturn os.path.join(self.experiment.output_subdir,\n\t\t\t\tget_output_file_name(ext, self.instance.filename, self.repetition))\n\n\tdef get_status(self):\n\t\tif os.access(self.output_file_path('status'), os.F_OK):\n\t\t\twith open(self.output_file_path('status'), \"r\") as f:\n\t\t\t\tstatus_dict = yaml.load(f, Loader=yaml.Loader)\n\n\t\t\tif status_dict['timeout']:\n\t\t\t\treturn Status.TIMEOUT\n\t\t\telif status_dict['signal']:\n\t\t\t\treturn Status.KILLED\n\t\t\telif status_dict['status'] > 0:\n\t\t\t\treturn Status.FAILED\n\t\t\treturn Status.FINISHED\n\t\telif os.access(self.output_file_path('out'), os.F_OK):\n\t\t\treturn Status.STARTED\n\t\telif os.access(self.aux_file_path('run'), os.F_OK):\n\t\t\treturn Status.SUBMITTED\n\t\telif os.access(self.aux_file_path('lock'), os.F_OK):\n\t\t\treturn Status.IN_SUBMISSION\n\n\t\treturn Status.NOT_SUBMITTED\n\ndef read_and_validate_setup(basedir='.', setup_file='experiments.yml'):\n\treturn util.validate_setup_file(os.path.join(basedir, setup_file))\n\ndef config_for_dir(basedir=None):\n\tif basedir is None:\n\t\tbasedir = '.'\n\tyml = read_and_validate_setup(basedir=basedir)\n\treturn Config(os.path.abspath(basedir), yml)\n\n","sub_path":"simexpal/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":23081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"419492831","text":"# -*- coding: utf-8 -*-\n\"\"\"\n :author: ZoeLiao\n :url: https://github.com/ZoeLiao\n :copyright: © 2019 ZoeLiao\n\"\"\"\n\n\nclass Queue(list):\n \"\"\"\n Queue: FIFO (First In, First Out)\n 佇列: 先進先出,如:排隊買票、坐公車\n dequeue <- [0][1]..[n-1] <- enqueue\n (front) Queue (rear)\n \"\"\"\n def __init__(self, input_list):\n super(Queue, self).__init__(input_list)\n self.input_list = input_list\n\n def enqueue(self, val):\n self.append(val)\n return self\n\n def dequeue(self):\n return self.pop(0)\n\n @property\n def isEmpty(self):\n if self == []:\n return True\n return False\n\n @property\n def front(self):\n return self[0]\n\n\ndef main():\n print('Queue: FIFO (First In, First Out)')\n input_list = eval((input('Please input a list: '))) \n print('input_list:', input_list)\n queue = Queue(input_list)\n print('Queue:', queue)\n input_number = eval((input('Please input a number you want to insert: '))) \n print('Queue.enqueue():'.format(input_number), queue.enqueue(input_number))\n print('Queue.dequeue():', queue.dequeue())\n print('Queue:', queue)\n print('Queue.isEmpty:', queue.isEmpty)\n print('Queue.front:', queue.front)\n\n for i in range(len(queue)):\n print('Queue.dequeue():', queue.dequeue())\n print('Queue:', queue)\n print('Queue.isEmpty:', queue.isEmpty)\n print('Queue:', queue)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"data_structure/queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"462835744","text":"\n\nfrom xai.brain.wordbase.adjectives._frequent import _FREQUENT\n\n#calss header\nclass _FREQUENTING(_FREQUENT, ):\n\tdef __init__(self,): \n\t\t_FREQUENT.__init__(self)\n\t\tself.name = \"FREQUENTING\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"frequent\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_frequenting.py","file_name":"_frequenting.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"147425915","text":"### Example 6-9: Find files matching a pattern\n\nimport os.path\nimport fnmatch\n\ndef find_matching_files(startpath, pattern):\n \"\"\"Return a list of filenames that match pattern in the directory\n tree starting at startpath\"\"\"\n paths = []\n for path, dirnames, filenames in os.walk(startpath):\n for dirname in dirnames:\n if dirname[0] == '.':\n dirnames.remove(dirname)\n paths += [os.path.join(path, filename)\n for filename in fnmatch.filter(filenames, pattern)]\n return paths\n\nif __name__ == '__main__':\n print(find_matching_files('..', '*.txt'))\n","sub_path":"chapter_examples/ch06_09.py","file_name":"ch06_09.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"503365666","text":"# Ubuntu 12.10\n# sudo apt-get install ffmpeg libavcodec-extra-53\n# sudo apt-get install espeak\n\nfrom subprocess import Popen\n\nDEVNULL = open('/dev/null', 'w')\n\ndef pkg(program, package):\n\treturn('\\'%s\\' (in pkg \\'%s\\') is not installed' % (program, package))\n\ndef installed(program, package = None):\n\tif(not(package)):\n\t\tpackage = program\n\ttry:\n\t\tPopen([ program ], stderr = DEVNULL, stdout = DEVNULL)\n\texcept OSError:\n\t\terror(pkg(program, package))\n\t\treturn(False)\n\treturn(True)\n\ndef error(msg):\n\tfrom sys import stderr\n\tstderr.write('error: %s\\n' % (msg))\n","sub_path":"code/pyServer/radio/classes/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"581940803","text":"import cv2\r\nimport winsound\r\ncam = cv2.VideoCapture(0)\r\nwhile cam.isOpened():\r\n ret , frame1 =cam.read()\r\n ret , frame2 =cam.read()\r\n diff = cv2.absdiff(frame1, frame2)# creating the two frames\r\n gray = cv2.cvtColor(diff , cv2.COLOR_RGB2GRAY) # converting the coloured vision to gray or black and white\r\n blur=cv2.GaussianBlur(gray,(5,5),0)\r\n _ ,thresh = cv2.threshold(blur,20,225,cv2.THRESH_BINARY)\r\n dilated = cv2.dilate(thresh , None , iterations=3 )\r\n contours,_ =cv2.findContours(dilated,cv2.RETR_TREE , cv2.CHAIN_APPROX_SIMPLE)\r\n #cv2.drawContours(frame1 , contours , -1 , (0,255,0), 2)\r\n for c in contours: # to contour the bigger things , and ignoring the smaller things\r\n if cv2.contourArea(c) < 5000:\r\n continue\r\n x,y,w,h = cv2.boundingRect(c)\r\n cv2.rectangle(frame1,(x,y),(x+w , y+h) , (0,255,0), 2)\r\n winsound.Beep(1000,200)\r\n if cv2.waitKey(10)==ord('q'):\r\n break\r\n cv2.imshow('security cam',frame1)\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"85958463","text":"## MSR_Action3D_infer_temporal.py, a function to perform naive Bayesian spatiotemporal \n## inference on the MSR-Action3D dataset with associative memory\n## using a (pixel-wise) error metric, and save the accuracy\n## result in a text file.\n## Wesley Chavez 07-12-2016\n## Portland State University\n##\n## TODO: make it a function, arguments of: size of input images, random seed,\n## error metric (dot product or Hamming distance), percent of\n## dataset to test on, and temporal window size\n\nimport numpy as np\nimport CDI_modules as cdi\nimport scipy.misc as sm\nimport math\nimport random\nimport time\nfrom joblib import Parallel, delayed\nimport multiprocessing\n\n# Number of pixels in input images\nsizeY=15\nsizeX=20\ntemporalWindowSize = 1\nmetric = 'dp'\n# For shuffling the dataset to split into testing and stored pattern sets\nrandomSeed = 12345\n\n\nvecSize = sizeY*sizeX\n\n# 20 MSR-Action3D actions\nclasses = ['a01', 'a02', 'a03', 'a04', 'a05', 'a06', 'a07', 'a08', 'a09', 'a10', \n'a11', 'a12', 'a13', 'a14', 'a15', 'a16', 'a17', 'a18', 'a19', 'a20']\n\n# Read list of .pngs\nf = open('/stash/tlab/datasets/MSR-Action3D/SkeletonFilenames_' + str(sizeY) + 'x' + str(sizeX) + '.txt', 'r')\npngList = f.read().splitlines()\nf.close()\n\n# Allocate your stuff\ntestSetSize = int(math.floor((len(pngList)-temporalWindowSize+1)*.25))\ntrainSetSize = len(pngList)-temporalWindowSize+1-testSetSize\ndataset = np.zeros((len(pngList),vecSize))\nlabels = np.zeros((len(pngList),1))\ndataset_shuf = np.zeros((len(pngList),vecSize))\nlabels_shuf = np.zeros((len(pngList),1))\ndataset_temporal = np.zeros((len(pngList)-temporalWindowSize+1,vecSize*temporalWindowSize))\nerr = np.zeros((testSetSize))\nvidStartIndices = []\n\n# .pngs to np array, whole dataset\nprint('IMREADING THE DATASET')\nfor i in np.arange(len(pngList)):\n frameNum = int(pngList[i][65:68])\n if (frameNum == 1):\n vidStartIndices.append(i)\n img = sm.imread(pngList[i])\n dataset[i,:] = img.flatten()\n for j in np.arange(20):\n if (pngList[i].find(classes[j]) != -1):\n labels[i] = j+1;\n\n# Binary data\ndataset[dataset > 0] = 1;\ndataset[dataset <= 0] = 0;\n\n# Shuffle indices with the random seed\nshufindex = np.arange(len(vidStartIndices))\nrandom.shuffle(shufindex,random.seed(randomSeed))\n\n# Shuffle the dataset and labels, correspondingly\nprint('SHUFFLING')\nframecount = 0\nfor i in np.arange(len(vidStartIndices)):\n if(shufindex[i] == len(vidStartIndices)-1):\n vidLength = len(dataset) - vidStartIndices[shufindex[i]] \n dataset_shuf[framecount:framecount+vidLength] = dataset[vidStartIndices[shufindex[i]]:len(dataset)]\n labels_shuf[framecount:framecount+vidLength] = labels[vidStartIndices[shufindex[i]]:len(dataset)]\n else:\n vidLength = vidStartIndices[shufindex[i]+1] - vidStartIndices[shufindex[i]]\n dataset_shuf[framecount:framecount+vidLength] = dataset[vidStartIndices[shufindex[i]]:vidStartIndices[shufindex[i]+1]]\n labels_shuf[framecount:framecount+vidLength] = labels[vidStartIndices[shufindex[i]]:vidStartIndices[shufindex[i]+1]]\n framecount = framecount + vidLength\n\n# Convert to temporal format, whole dataset\nif(temporalWindowSize == 1):\n\tdataset_temporal = dataset_shuf\nelif(temporalWindowSize == 2):\n print('CONVERTING TO TEMPORAL FORMAT')\n for i in np.arange(len(pngList)-temporalWindowSize+1):\n dataset_temporal[i] = np.concatenate((dataset_shuf[i],dataset_shuf[i+1]),axis=0)\nelif(temporalWindowSize == 4):\n print('CONVERTING TO TEMPORAL FORMAT')\n for i in np.arange(len(pngList)-temporalWindowSize+1):\n dataset_temporal[i] = np.concatenate((dataset_shuf[i],dataset_shuf[i+1],dataset_shuf[i+2],dataset_shuf[i+3]),axis=0)\nelif(temporalWindowSize == 6):\n print('CONVERTING TO TEMPORAL FORMAT')\n for i in np.arange(len(pngList)-temporalWindowSize+1):\n dataset_temporal[i] = np.concatenate((dataset_shuf[i],dataset_shuf[i+1],dataset_shuf[i+2],dataset_shuf[i+3],dataset_shuf[i+4],dataset_shuf[i+5]),axis=0)\nelif(temporalWindowSize == 8):\n print('CONVERTING TO TEMPORAL FORMAT')\n for i in np.arange(len(pngList)-temporalWindowSize+1):\n dataset_temporal[i] = np.concatenate((dataset_shuf[i],dataset_shuf[i+1],dataset_shuf[i+2],dataset_shuf[i+3],dataset_shuf[i+4],dataset_shuf[i+5],dataset_shuf[i+6],dataset_shuf[i+7]),axis=0)\n\n\n# Inference with x% of the dataset as testing, and the rest as stored patterns, using the Bayesian Module (BM)\ndef infer_MSR(i):\n if(metric == 'dp'):\n error, dontcare1, dontcare2 = cdi.BM_dp(dataset_temporal[testSetSize:testSetSize+trainSetSize],dataset_temporal[i],[labels_shuf[i]],labels_shuf[testSetSize:testSetSize+trainSetSize])\n elif(metric == 'ham'):\n error, dontcare1, dontcare2 = cdi.BM_ham(dataset_temporal[testSetSize:testSetSize+trainSetSize],dataset_temporal[i],[labels_shuf[i]],labels_shuf[testSetSize:testSetSize+trainSetSize])\n return error\n\n# Call infer_MSR using all cores on the machine\nprint('PERFORMING INFERENCE')\ninferindex = np.arange(testSetSize)\nnum_cores = multiprocessing.cpu_count()\nerr = Parallel(n_jobs = num_cores)(delayed(infer_MSR)(i) for i in inferindex)\n\naccuracy = 1-sum(err)/float(testSetSize)\n\n# Print accuracy over the whole test set\nprint('Accuracy_' + str(sizeY) + 'x' + str(sizeX) + ': ')\nprint(accuracy)\n\n# Save results and parameters to file\nfid = open('MSR_results_shufflebyvideo.txt','a')\nfid.write('Size: ')\nfid.write(str(sizeY) + 'x' + str(sizeX) + '\\n')\nfid.write('Metric: ')\nfid.write(metric + '\\n')\nfid.write('Test Set Length: ')\nfid.write(str(testSetSize))\nfid.write('\\n')\nfid.write('Temporal Window Size: ' + str(temporalWindowSize) + '\\n')\nfid.write('Random Seed: ')\nfid.write(str(randomSeed))\nfid.write('\\n')\nfid.write('Accuracy: ')\nfid.write(str(accuracy))\nfid.write('\\n\\n')\nfid.close()\n","sub_path":"MSR_Action3D_infer_temporal.py","file_name":"MSR_Action3D_infer_temporal.py","file_ext":"py","file_size_in_byte":5873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"613390448","text":"from coltrane.models import Post, Category\nfrom django.contrib.sitemaps import GenericSitemap, Sitemap\n\npost_dict = {\n 'queryset': Post.live.all(),\n 'date_field': 'pub_date',\n}\n\ncategory_dict = {\n 'queryset': Category.live.all(),\n}\n\nclass AbstractSitemapClass(object):\n url = None\n \n def get_absolute_url(self):\n return self.url\n\n\nclass StaticSitemap(Sitemap):\n pages = {\n 'bio':'/who-is-ben-welsh/',\n 'colophon':'/colophon/',\n 'feeds': '/feeds/list/',\n 'apps': '/apps/',\n 'clips': '/clips/',\n 'posts': '/posts/',\n 'talks': '/talks/',\n 'ticker': '/ticker/',\n 'bring-the-news-back': '/apps/bring-the-news-back/',\n 'kennedy-name-generator': '/kennedy/',\n 'random-oscars-ballot': '/apps/random-oscars-ballot/',\n 'return-of-the-mack-ringtone': '/mack/',\n }\n main_sitemaps = []\n for page in pages.keys():\n sitemap_class = AbstractSitemapClass()\n sitemap_class.url = pages[page]\n main_sitemaps.append(sitemap_class)\n \n def items(self):\n return self.main_sitemaps\n\n\nsitemaps = {\n 'static': StaticSitemap,\n 'posts': GenericSitemap(post_dict, priority=0.9),\n 'categories': GenericSitemap(category_dict, priority=0.6),\n}\n","sub_path":"coltrane/sitemaps.py","file_name":"sitemaps.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"207910319","text":"# день в році (від 1 до 365)\nk = 9\n# день тижня з якого почався рік (від 1 до 7)\nn = 5\n# день тижня знайдений остачою від ділення на 7 числа k (від 0 до 6)\nx = k % 7\nif x == 0: x = 7\n# день тижня з врахуванням здвигу на початку року (від 0 до 6)\na = (x + n - 1) % 7\nif a == 0: a = 7\n\nprint(x, a)","sub_path":"ua/univer/base/tasks_2_Integer/28_task.py","file_name":"28_task.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"279204678","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 10 09:06:01 2020\n\n@author: tom verguts\nchapter 10: unsupervised learning: Unsupervised Hebbian learning rule\nCheck if weights converge to first eigenvector of covariance matrix\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nntrial = 100\nlrate, ndim = 0.1, 2\nw = np.random.randn(2,ntrial)\nsigma = np.array([[1, -0.7], [-0.7, 1.0]])\nX = np.linalg.cholesky(sigma) # appropriate transformation matrix given covariance sigma\ndata = np.ndarray((ntrial,ndim))\nfig, axs = plt.subplots(1)\nfor loop in range(1, ntrial):\n sample = np.dot(X,np.random.randn(ndim))\n data[loop] = sample\n y = np.dot(w[:,loop-1],sample)\n axs.scatter(sample[0], sample[1],c = \"black\")\n #w[:,loop] = w[:,loop-1] + lrate*(sample*y-(y**2)*w[:,loop]) # oja's rule\n w[:,loop] = w[:,loop-1] + lrate*sample*y # explicit normalization\n w[:,loop] = w[:,loop]/np.linalg.norm(w[:,loop])\n\n# plot stuff\nstretch = 5\naxs.set_xlim(-3, +3)\naxs.set_ylim(-3, +3)\naxs.set_xlabel(\"Dimension 1\")\naxs.set_ylabel(\"Dimension 2\")\naxs.plot(stretch*np.array([-w[0, ntrial-1], w[0, ntrial-1]]), stretch*np.array([-w[1, ntrial-1], w[1, ntrial-1]]), c = \"black\")\nprint(np.cov(data, rowvar = False)) # to check if data structure is correct; should be similar to sigma","sub_path":"code by chapter/Chapter 10/ch10_unsup_hebb.py","file_name":"ch10_unsup_hebb.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"449522790","text":"#!/usr/bin/env python\n\nimport time\n\nimport flotilla\n\n\nprint(\"\"\"This example will read the temperature and pressure from any connected weather modules.\n\nPress Ctrl+C to exit.\"\"\")\n\n\nclient = flotilla.Client()\n\ntry:\n while True:\n for module in client.available.values():\n if module.is_a(flotilla.Weather):\n print('Temp: {} Pressure: {}'.format(module.temperature, module.pressure))\n\n time.sleep(0.5)\n\nexcept KeyboardInterrupt:\n client.stop()\n\n","sub_path":"examples/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"500835912","text":"# Copyright (c) OpenMMLab. All rights reserved.\nimport numpy as np\nfrom scipy.special import comb as n_over_k\n\nfrom mmocr.utils.typing_utils import ArrayLike\n\n\ndef bezier_coefficient(n, t, k):\n return t**k * (1 - t)**(n - k) * n_over_k(n, k)\n\n\ndef bezier_coefficients(time, point_num, ratios):\n return [[bezier_coefficient(time, ratio, num) for num in range(point_num)]\n for ratio in ratios]\n\n\ndef linear_interpolation(point1: np.ndarray,\n point2: np.ndarray,\n number: int = 2) -> np.ndarray:\n t = np.linspace(0, 1, number + 2).reshape(-1, 1)\n return point1 + (point2 - point1) * t\n\n\ndef curve2bezier(curve: ArrayLike):\n curve = np.array(curve).reshape(-1, 2)\n if len(curve) == 2:\n return linear_interpolation(curve[0], curve[1])\n diff = curve[1:] - curve[:-1]\n distance = np.linalg.norm(diff, axis=-1)\n norm_distance = distance / distance.sum()\n norm_distance = np.hstack(([0], norm_distance))\n cum_norm_dis = norm_distance.cumsum()\n pseudo_inv = np.linalg.pinv(bezier_coefficients(3, 4, cum_norm_dis))\n control_points = pseudo_inv.dot(curve)\n return control_points\n\n\ndef bezier2curve(bezier: np.ndarray, num_sample: int = 10):\n bezier = np.asarray(bezier)\n t = np.linspace(0, 1, num_sample)\n return np.array(bezier_coefficients(3, 4, t)).dot(bezier)\n\n\ndef poly2bezier(poly):\n poly = np.array(poly).reshape(-1, 2)\n points_num = len(poly)\n up_curve = poly[:points_num // 2]\n down_curve = poly[points_num // 2:]\n up_bezier = curve2bezier(up_curve)\n down_bezier = curve2bezier(down_curve)\n up_bezier[0] = up_curve[0]\n up_bezier[-1] = up_curve[-1]\n down_bezier[0] = down_curve[0]\n down_bezier[-1] = down_curve[-1]\n return np.vstack((up_bezier, down_bezier)).flatten().tolist()\n\n\ndef bezier2poly(bezier, num_sample=20):\n bezier = bezier.reshape(2, 4, 2)\n curve_top = bezier2curve(bezier[0], num_sample)\n curve_bottom = bezier2curve(bezier[1], num_sample)\n return np.vstack((curve_top, curve_bottom)).flatten().tolist()\n","sub_path":"mmocr/utils/bezier_utils.py","file_name":"bezier_utils.py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"431049931","text":"# This problem was asked by Google.\n\n# Given a singly linked list and an integer k, remove the kth last element from \n# the list. k is guaranteed to be smaller than the length of the list.\n\n# The list is very long, so making more than one pass is prohibitively expensive.\n\n# Do this in constant space and in one pass.\n\nclass LinkedList:\n class Node:\n def __init__(self, value = None):\n self.value = value\n self.next = None\n \n def __init__(self):\n self.size = 0\n self.head = None\n\n def append(self, value):\n node = self.Node(value)\n if self.head == None:\n self.head = node\n else:\n tmp = self.head\n while tmp.next != None:\n tmp = tmp.next\n tmp.next = node\n self.size += 1\n \n def print_list(self):\n result = []\n tmp = self.head\n while tmp != None:\n result.append(tmp.value)\n tmp = tmp.next\n print(result)\n\n def delete(self, k):\n if k == 0:\n self.head = self.head.next\n else:\n i = 1\n tmp1 = self.head\n tmp2 = self.head.next\n while i < k:\n i += 1\n tmp1 = tmp1.next\n tmp2 = tmp2.next\n tmp1.next = tmp2.next\n self.print_list()\n\n\nl = [1,2,3,4,5,6,7]\nllist = LinkedList()\nfor i in l:\n llist.append(i)\n\nllist.print_list()\nllist.delete(2)\nllist.delete(4)","sub_path":"29122020-Google.py","file_name":"29122020-Google.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"465357289","text":"import os\nfrom bson import ObjectId\nfrom gridfs import GridFS\nfrom pymongo import MongoClient\nfilePath = 'G:\\python\\OA\\data1.txt'\n# filePath1 = 'data.txt'\n# fullpath = os.getcwd() + \"\\\\\" + filePath1\n# print(fullpath)\n# print(os.path.dirname(filePath))\n# print(os.path.split(filePath1))\n# print(os.path.basename(filePath))\n# print(os.path.dirname(filePath))\n# print(os.path.splitext(filePath))\n# print(os.path.split(filePath))\n# print(os.path.join(os.path.dirname(filePath), os.path.basename(filePath)))\n# print(os.path.basename(os.path.join(os.path.dirname(filePath), os.path.basename(filePath))))\n# print(os.path.getsize(filePath))\n# f = open(filePath, \"r\", encoding=\"utf-8\")\n# file = f.read()\n# print(file)\n# f.close()\n\nclient = MongoClient(host=\"localhost\", port=27017)\nclient.admin.authenticate(\"admin\",\"123456\")\ndb = client.oa\ngfs = GridFS(db, collection=\"oa\")\nfile = open(filePath, 'rb')\nargs = {}\nargs[\"type\"] = os.path.splitext(filePath)[1]\nargs[\"name\"] = os.path.basename(filePath)\ngfs.put(file, filename=os.path.basename(filePath), **args)\n# txt = gfs.find_one({\"_id\": ObjectId(\"5eac21f3ff46b1ca1c4419fb\")})\n# print(dir(txt))\n# print(txt.filename)\n\n# txt1 = client.oa.oa.files.find_one({\"_id\": ObjectId(\"5eac21f3ff46b1ca1c4419fb\")})\n# print(txt1)\n\n\n# data_txt = gfs.get(ObjectId(\"5eac21f3ff46b1ca1c4419fb\"))\n# new_file = open(\"test1.txt\", \"wb\")\n# new_file.write(data_txt.read())\n# new_file.close()\n# for one in txt:\n# print(one.decode(\"utf-8\"))\n\nfile.close()","sub_path":"OA/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"406273857","text":"from ev3dev.ev3 import ColorSensor\nimport move\nfrom time import time\n\nthreshold = 10\ncs = ColorSensor('in1')\ncs.mode = 'COL-COLOR'\nt0 = time()\n\n\ndef main():\n\twhile time()-t0 < 50 and not move.btn.any():\n\n\t\tif cs.value() > threshold:\n\t\t\tmove.left(.1, ratio=-.5)\n\t\telse:\n\t\t\tmove.right(.1, ratio=-.5)\n\n\texit()\n\n\nmain()\n","sub_path":"trace.py","file_name":"trace.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"547379628","text":"if __name__ == '__main__':\n import argparse\n import glob\n import os\n import random\n import sys\n\n import numpy as np\n import tensorflow as tf\n from tqdm import tqdm\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument('in_dir', type=str)\n parser.add_argument('out_dir', type=str)\n parser.add_argument('--name', type=str)\n parser.add_argument('--ext', type=str)\n parser.add_argument('--fs', type=int)\n parser.add_argument('--nshards', type=int)\n parser.add_argument('--slice_len', type=int)\n parser.add_argument('--first_only', action='store_true', dest='first_only')\n\n parser.set_defaults(\n name='train',\n ext='wav',\n fs=16000,\n nshards=1,\n slice_len=16384,\n first_only=True)\n\n args = parser.parse_args()\n\n audio_fps = glob.glob(os.path.join(args.in_dir, '*.{}'.format(args.ext)))\n from collections import Counter\n counter = Counter()\n for fps in audio_fps:\n audio_name = os.path.splitext(os.path.split(fps)[1])[0]\n traits = audio_name.split('_')[:-1]\n counter.update(traits)\n assert len(traits) > 0\n di = sorted(counter.keys())\n\n random.shuffle(audio_fps)\n\n if args.nshards > 1:\n npershard = int(len(audio_fps) // (args.nshards - 1))\n else:\n npershard = len(audio_fps)\n\n audio_fp = tf.placeholder(tf.string, [])\n audio_bin = tf.read_file(audio_fp)\n samps = tf.contrib.ffmpeg.decode_audio(audio_bin, args.ext, args.fs, 1)[:, 0]\n if args.slice_len is not None:\n if args.first_only:\n pad_end = True\n else:\n pad_end = False\n\n slices = tf.contrib.signal.frame(samps, args.slice_len, args.slice_len, axis=0, pad_end=pad_end)\n\n if args.first_only:\n slices = slices[:1]\n else:\n slices = tf.expand_dims(samps, axis=0)\n\n sess = tf.Session()\n\n if not os.path.exists(args.out_dir):\n os.makedirs(args.out_dir)\n\n for i, start_idx in tqdm(enumerate(range(0, len(audio_fps), npershard))):\n shard_name = '{}-{}-of-{}.tfrecord'.format(args.name, str(i).zfill(len(str(args.nshards))), args.nshards)\n shard_fp = os.path.join(args.out_dir, shard_name)\n\n writer = tf.python_io.TFRecordWriter(shard_fp)\n\n for _audio_fp in audio_fps[start_idx:start_idx+npershard]:\n audio_name = os.path.splitext(os.path.split(_audio_fp)[1])[0]\n splits = audio_name.split('_')\n audio_labels = splits[:-1]\n audio_id = splits[-1]\n\n label = np.zeros(len(di),)\n for l in audio_labels:\n label[di.index(l)] = 1.0\n label /= label.sum()\n\n try:\n _slices = sess.run(slices, {audio_fp: _audio_fp})\n except:\n continue\n\n if _slices.shape[0] == 0 or _slices.shape[1] == 0:\n continue\n\n for j, _slice in enumerate(_slices):\n example = tf.train.Example(features=tf.train.Features(feature={\n 'label': tf.train.Feature(float_list=tf.train.FloatList(value=label)),\n 'slice': tf.train.Feature(int64_list=tf.train.Int64List(value=[j])),\n 'samples': tf.train.Feature(float_list=tf.train.FloatList(value=_slice))\n }))\n\n writer.write(example.SerializeToString())\n\n writer.close()\n\n sess.close()\n","sub_path":"data/make_tfrecord.py","file_name":"make_tfrecord.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"216399554","text":"import pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\ndef test_click_blog_post_title_at_blog_index():\n driver = webdriver.Chrome()\n driver.get(\"http://127.0.0.1:8000/blog/\")\n blog_post_title_elem = driver.find_element_by_xpath('//*[@id=\"blog-index-container\"]/div[1]/h2/a')\n blog_post_title_elem.click()\n assert driver.title == \"Kevin's Blog | Cycling Journey: Changi towards the City\"\n\ndef test_click_blog_post_category():\n driver = webdriver.Chrome()\n driver.get(\"http://127.0.0.1:8000/blog/\")\n blog_post_category = driver.find_element_by_xpath('//*[@id=\"blog-index-container\"]/div[2]/small/a')\n blog_post_category.click()\n assert driver.title == \"Kevin's Blog | Category: School Project\"","sub_path":"test_blog_index.py","file_name":"test_blog_index.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"133678422","text":"#!flask/bin/python\nfrom dataviz import db\nfrom dataviz.models import Patient, Provider, Activity, Diagnosis, DiagnosisGroup\nfrom csv import DictReader\nfrom datetime import datetime\n\n#Format date:\ndef formatDate(in_date,preferredpattern):\n date_patterns = [\"%d/%m/%Y %H:%M\",\"%d/%m/%Y %H:%M:%S %p\", \"%d-%m-%Y\", \"%Y-%m-%d\",\"%d/%m/%Y\",\"%Y-%m-%d %H:%M:%S.%f\", \"%Y-%m-%d\", \"%d%m%Y\",\"%Y%m%d\", ]\n validformat = False\n try:\n return datetime.strptime(in_date, preferredpattern)\n validformat = True\n except:\n pass\n if not validformat:\n for pattern in date_patterns:\n if pattern != preferredpattern:\n try:\n return datetime.strptime(in_date, pattern)\n validformat = True\n except:\n pass\n if not validformat:\n out_date = None\n return out_date\n\n\n#------------------------------------------------------------------------------------------------------------\n#Patients:\n\n#Reset:\npatients = Patient.query.all()\nfor pt in patients:\n db.session.delete(pt)\n db.session.commit()\n\n##Insert:\nptfile = DictReader(open(\"../POLAR demo TXT/Patients.txt\",'r',encoding=\"utf-8\"),delimiter=\"\\t\")\nfor ptrow in ptfile:\n pt = Patient(patientid=ptrow[\"%PatientSiteKey\"], fname=ptrow[\"Firstname\"], sname=ptrow[\"Surname\"], gender=ptrow[\"%Gender ID\"], dob=formatDate(ptrow[\"DOB\"],\"%d/%m/%Y %H:%M:%S %p\"), status=ptrow[\"%Patient Status ID\"], suburb=ptrow[\"Suburb\"], sourceid=ptrow[\"%DataSource ID\"])\n db.session.add(pt)\n db.session.commit()\n\n\npatients = Patient.query.all()\nfor pt in patients:\n print (pt)\nprint (db.session.query(Patient).count())\n\n#------------------------------------------------------------------------------------------------------------\n#Providers:\n\n#Reset:\nproviders = Provider.query.all()\nfor p in providers:\n db.session.delete(p)\n db.session.commit()\n\n#Insert:\npfile = DictReader(open(\"../POLAR demo TXT/Providers.txt\",'r',encoding=\"utf-8\"),delimiter=\"\\t\")\nfor prow in pfile:\n p = Provider(siteid=prow[\"%ProviderSiteKey\"], status=prow[\"Provider Status\"], type=prow[\"Provider Type\"], sourceid=prow[\"%DataSource ID\"], fullname=prow[\"Provider\"])\n db.session.add(p)\n db.session.commit()\n\n\n#------------------------------------------------------------------------------------------------------------\n#Activities:\n\n##Reset:\nactivities = Activity.query.all()\nfor a in activities:\n db.session.delete(a)\n db.session.commit()\n\n\n#Insert:\nafile = DictReader(open(\"../POLAR demo TXT/Activities.txt\",'r',encoding=\"utf-8\"),delimiter=\"\\t\")\nfor key,arow in enumerate(afile):\n a = Activity(activityid=arow[\"%Activity ID\"], siteid=arow[\"%ActivityProviderSiteKey\"], patientid=arow[\"%PatientSiteKey\"], hour=arow[\"%Activity Hour ID\"], date=formatDate(arow[\"Activity Date\"],\"%Y-%m-%d %H:%M:%S.%f\"), last1monthflag=arow[\"Activity Last 1 Month Flag\"], last3monthsflag=arow[\"Activity Last 3 Months Flag\"], last6monthsflag=arow[\"Activity Last 6 Months Flag\"], last12monthsflag=arow[\"Activity Last 12 Months Flag\"], last13monthsflag=arow[\"Activity Last 13 Months Flag\"], over12monthsflag=arow[\"Activity Over 12 Months Flag\"], over2yearsflag=arow[\"Activity Over 2 Years Flag\"], over3yearsflag=arow[\"Activity Over 3 Years Flag\"], over5yearsflag=arow[\"Activity Over 5 Years Flag\"], count=arow[\"#Activity Count\"],sourceid=arow[\"%DataSource ID\"], type=arow[\"Activity Type\"], providertype=arow[\"Activity Provider Type\"], provider=arow[\"Activity Provider\"] )\n db.session.add(a)\n db.session.commit()\n\nactivities = Activity.query.all()\nfor a in activities:\n print (a)\n\n\n#------------------------------------------------------------------------------------------------------------\n#DiagnosisGroups:\ndgfile = DictReader(open(\"../POLAR demo TXT/Diagnosis.txt\",'r',encoding=\"windows-1250\"),delimiter=\"\\t\")\ndiagnoses = []\nfor dgrow in dgfile:\n diagnoses.append([dgrow[\"SNOMED Code\"],dgrow[\"%Diagnosis ID\"]])\n\ndef getSNOMED(diagnosis):\n result = []\n for d in diagnoses:\n if d[1] == diagnosis:\n result.append([d[0],d[1]])\n if len(result) > 0:\n return result[0][0]\n else:\n return None\n##Reset:\ndiagnosisgroups = DiagnosisGroup.query.all()\nfor dg in diagnosisgroups:\n db.session.delete(dg)\n db.session.commit()\n\n###Insert:\ndgfile = DictReader(open(\"../POLAR demo TXT/DiagnosisGroup.txt\",'r',encoding=\"windows-1250\"),delimiter=\"\\t\")\nfor key,dgrow in enumerate(dgfile):\n dg = DiagnosisGroup(diagnosis=dgrow[\"%Diagnosis ID\"], hlagroup=dgrow[\"HLA Group\"], snomedct=getSNOMED(dgrow[\"%Diagnosis ID\"]))\n db.session.add(dg)\n db.session.commit()\n\n#------------------------------------------------------------------------------------------------------------\n#Diagnoses:\n\n#Reset:\ndiagnoses = Diagnosis.query.all()\nfor d in diagnoses:\n db.session.delete(d)\n db.session.commit()\n\n##Insert:\ndfile = DictReader(open(\"../POLAR demo TXT/Diagnosis.txt\",'r',encoding=\"windows-1250\"),delimiter=\"\\t\")\nfor key,drow in enumerate(dfile):\n d = Diagnosis(siteid=drow[\"%DiagnosisProviderSiteKey\"], patientid=drow[\"%PatientSiteKey\"], statusid=drow[\"%Diagnosis Active\"], date=formatDate(drow[\"Diagnosis Date\"],\"%d/%m/%Y\"), sourceid=drow[\"%DataSource ID\"], snomedct=drow[\"SNOMED Code\"], chronicdiseasecategory=drow[\"ChronicDiseaseCategory\"], providertype=drow[\"Diagnosis Provider Type\"], provider=drow[\"Diagnosis Provider\"] )\n db.session.add(d)\n db.session.commit()\n\nprint (db.session.query(Diagnosis).count())\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":"db_populate.py","file_name":"db_populate.py","file_ext":"py","file_size_in_byte":5522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"569568103","text":"\"\"\"This module contains the functions to evaluate our hand and to compare it\nwith other hands.\n\"\"\"\n\n\nfrom collections import OrderedDict, namedtuple\nfrom poker.hand_evaluation.value_with_regards_to import ValueWithRegards\nfrom poker._constants import HandRankings as hr\nfrom poker._constants import HandRankingDescOrdering\n\n\nHandRank = namedtuple('HandRank', ['rank', 'value_in_rank'])\n\n# We are checking the values regards to rank in a descending order.\n# This might not be the most optimal order, e.g.something like first checking\n# if it has a '3 of a kind' might be better: if yes, we only need to check the\n# '4 of a kind' and 'full house'; if not we don't need to check these two.\ndef evaluate_hand(cards):\n value_with_regards = ValueWithRegards(cards)\n for rank in HandRankingDescOrdering:\n value = value_with_regards.to(rank)\n if value:\n return HandRank(rank, value)\n\n\n# When comparing a hand H with the value V of an already evaluated hand we are\n# not interested in the exact value fo H, only if it is bigger than V. So we\n# only need to check the value of H regards to ranks which are not smaller\n# than the rank of V.\n# NOTE:The check for the same rank as V will be handled separately.\n# Since the probability of having a lower ranked hand is higher than for higher\n# ranked hand, it is more efficient to do this check in an ascending order.\n# Also, some higher ranked hands contain lower ranked hands (e.g. a 'straight\n# flush' contains a 'flush' and a 'straight') so it not always necessary to\n# check all possible ranks.\nCHECKS_FOR_STR_FLUSH = []\nCHECKS_FOR_4_OF_A_KIND = [hr.STRAIGHT_FLUSH]\nCHECKS_FOR_F_HOUSE = [hr.FOUR_OF_A_KIND] + CHECKS_FOR_4_OF_A_KIND\nCHECKS_FOR_FLUSH = [hr.FULL_HOUSE] + CHECKS_FOR_F_HOUSE\n# From here on we don't need to check for 'straight flush' anymore.\nCHECKS_FOR_STR = [hr.FLUSH, hr.FULL_HOUSE, hr.FOUR_OF_A_KIND]\nCHECKS_FOR_3_OF_A_KIND = [hr.STRAIGHT] + CHECKS_FOR_STR\n# No need to check '4 of a kind' and 'full house' anymore.\nCHECKS_FOR_2_PAIRS = [hr.THREE_OF_A_KIND, hr.STRAIGHT, hr.FLUSH]\nCHECKS_FOR_PAIR = [hr.TWO_PAIRS] + CHECKS_FOR_2_PAIRS\n# No need to check 'two pairs' and '3 of a kind' anymore.\nCHECKS_FOR_NOTHING = [hr.PAIR, hr.STRAIGHT, hr.FLUSH]\n\n\nranks_to_checks_when_comparing = {\n hr.STRAIGHT_FLUSH: CHECKS_FOR_STR_FLUSH,\n hr.FOUR_OF_A_KIND: CHECKS_FOR_4_OF_A_KIND,\n hr.FULL_HOUSE: CHECKS_FOR_F_HOUSE,\n hr.FLUSH: CHECKS_FOR_FLUSH,\n hr.STRAIGHT: CHECKS_FOR_STR,\n hr.THREE_OF_A_KIND: CHECKS_FOR_3_OF_A_KIND,\n hr.TWO_PAIRS: CHECKS_FOR_2_PAIRS,\n hr.PAIR: CHECKS_FOR_PAIR,\n hr.NOTHING: CHECKS_FOR_NOTHING\n}\n\n# Instead of comparing two hands we are comparing a hand to a HandRank instance.\n# This way if we want to compare a hand H with several other hands then we don't\n# need to reevaluate H for every comparison.\ndef hand_is_better_than(hand, compare_to):\n \"\"\"Takes a list of cards and a HandRank instance as input and returns a Boolean.\"\"\"\n # We first check if `hand` is not of a higher rank than `hand_rank`.\n ranks_to_check = ranks_to_checks_when_comparing[compare_to.rank]\n value_with_regards = ValueWithRegards(hand)\n for rank in ranks_to_check:\n hand_rank = value_with_regards.to(rank)\n if hand_rank:\n return True\n # If not then we check `hand` is not of the same rank of `hand_rank` only\n # with higher value.\n hand_value_regards_to_rank = value_with_regards.to(compare_to.rank)\n if hand_value_regards_to_rank:\n if compare_to.value_in_rank >= hand_value_regards_to_rank:\n return False\n else:\n return True\n # Here `hand` is of lower rank than `hand_rank`.\n return False\n","sub_path":"poker/hand_evaluation/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":3687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"188002812","text":"from django.urls import path\r\nfrom django.conf.urls import url\r\nfrom . views import post_create,post_detail,post_list,post_update,post_delete\r\n\r\n#app_name = posts\r\n\r\nurlpatterns = [\r\n\turl(r'^$',post_list,name=\"post_list\"),\r\n\turl(r'^create/$',post_create,name=\"post_create\"),\r\n\turl(r'^(?P\\d+)/$',post_detail,name=\"post_detail\"),\r\n\turl(r'^(?P\\d+)/update/$',post_update,name=\"post_update\"),\r\n\turl(r'^delete/$',post_delete,name=\"post_delete\"),\r\n]","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"92952904","text":"import argparse\nimport logging\nimport logging.handlers\nimport os\nimport urllib.parse\nimport urllib.request\n\nfrom difflib import SequenceMatcher\nfrom tempfile import NamedTemporaryFile\nfrom zipfile import is_zipfile, ZipFile\n\nfrom bs4 import BeautifulSoup\n\nRAR_ID = bytes(\"Rar!\\x1a\\x07\\x00\",\"utf-8\")\n\nSUBDIVX_SEARCH_URL = \"http://www.subdivx.com/index.php?buscar=%s+%s&accion=5&masdesc=&subtitulos=1&realiza_b=1&oxdown=1\"\nSUBDIVX_DOWNLOAD_MATCHER = {'name':'a', 'rel':\"nofollow\", 'target': \"new\"}\n\nLOGGER_LEVEL = logging.DEBUG\nLOGGER_FORMATTER = logging.Formatter('%(asctime)-25s %(levelname)-8s %(name)-29s %(message)s', '%Y-%m-%d %H:%M:%S')\n\nclass NoResultsError(Exception):\n pass\n\n\ndef is_rarfile(fn):\n '''Check quickly whether file is rar archive.'''\n buf = open(fn, \"rb\").read(len(RAR_ID))\n return buf == RAR_ID\n\n\ndef setup_logger(level, log_file):\n global logger\n logger = logging.getLogger()\n logfile = logging.handlers.RotatingFileHandler(log_file, maxBytes=1000 * 1024, backupCount=9)\n logfile.setFormatter(LOGGER_FORMATTER)\n logger.addHandler(logfile)\n logger.setLevel(level)\n return logger\n\n\ndef get_subtitle_url(series_name, series_id, series_quality, skip=0):\n enc_series_name = urllib.parse.quote(series_name)\n enc_series_id = urllib.parse.quote(series_id)\n\n logger.debug('Starting request to subdivx.com')\n page = urllib.request.urlopen(SUBDIVX_SEARCH_URL % (enc_series_name, enc_series_id))\n logger.debug('Search Query URL: ' + page.geturl())\n\n soup = BeautifulSoup(page, features=\"html.parser\")\n\n results_descriptions = soup('div', id='buscador_detalle_sub')\n\n if not results_descriptions:\n raise(NoResultsError(' '.join(['No suitable subtitles were found for:',\n series_name,\n series_id,\n series_quality])))\n\n search_match = '%s %s %s' % (series_name, series_id, series_quality)\n matcher = SequenceMatcher(lambda x: x==\" \" or x==\".\", search_match)\n\n def calculate_ratio(seq):\n matcher.set_seq2(seq)\n\n blocks = matcher.get_matching_blocks()\n\n scores = []\n for block in blocks:\n long_start = block[1] - block[0]\n long_end = long_start + len(search_match)\n long_substr = seq[long_start:long_end]\n\n m2 = SequenceMatcher(None, search_match, long_substr)\n r = m2.ratio()\n if r > .999:\n return 100\n else:\n scores.append(r)\n result = int(100 * sorted(scores, reverse=True)[skip:][0])\n return result\n\n best_match = [calculate_ratio(''.join([e for e in description.recursiveChildGenerator() if isinstance(e,str)]))\n for description in results_descriptions]\n\n best_match_index = best_match.index(max(best_match))\n\n return results_descriptions[best_match_index].nextSibling.find(**SUBDIVX_DOWNLOAD_MATCHER)['href']\n\ndef get_subtitle(url, path, video_path):\n in_data = urllib.request.urlopen(url)\n temp_file = NamedTemporaryFile()\n\n temp_file.write(in_data.read())\n in_data.close()\n temp_file.seek(0)\n\n dest_path = os.path.dirname(os.path.abspath(video_path))\n if is_zipfile(temp_file.name):\n zip_file = ZipFile(temp_file)\n for name in zip_file.namelist():\n # don't unzip stub __MACOSX folders\n if '.srt' in name and '__MACOSX' not in name:\n logger.info(' '.join(['Unpacking zipped subtitle', name, 'to', dest_path]))\n zip_file.extract(name, dest_path)\n\n zip_file.close()\n\n elif is_rarfile(temp_file.name):\n rar_path = path + '.rar'\n logger.info('Saving rared subtitle as %s' % rar_path)\n with open(rar_path, 'wb') as out_file:\n out_file.write(temp_file.read())\n\n try:\n import subprocess\n #extract all .srt in the rared file\n ret_code = subprocess.call(['unrar', 'e', '-n*srt', rar_path, dest_path])\n if ret_code == 0:\n logger.info('Unpacking rared subtitle to %s' % dest_path)\n os.remove(rar_path)\n except OSError:\n logger.info('Unpacking rared subtitle failed.'\n 'Please, install unrar to automate this step.')\n temp_file.close()\n","sub_path":"subdivx/subdivxlib.py","file_name":"subdivxlib.py","file_ext":"py","file_size_in_byte":4356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"360372945","text":"import graphene\nfrom graphene_django.types import DjangoObjectType\nfrom ..models.address import AddressModel as Address\nfrom ..models.user import UserModel as User\nfrom ..models.store import StoreModel as Store\nfrom django.db import Error, IntegrityError\nimport shortuuid\n\n\n# Address definition using Address Model\nclass AddressType(DjangoObjectType):\n class Meta:\n model = Address\n\n\n# Mutation for create Address\nclass CreateAddress(graphene.Mutation):\n class Arguments:\n user_id = graphene.String()\n store_id = graphene.String()\n address = graphene.String(required=True)\n\n address_object = graphene.Field(AddressType)\n message = graphene.String()\n\n @staticmethod\n def mutate(self, info, address, **args):\n user_id = args.get('user_id')\n store_id = args.get('store_id')\n try:\n if address.strip():\n if (user_id and not store_id) or (store_id and not user_id):\n if user_id:\n User.objects.get(id=user_id)\n kwargs = {'user_id': user_id}\n if store_id:\n Store.objects.get(id=store_id)\n kwargs = {'store_id': store_id}\n addresses = Address.objects.filter(**kwargs)\n if len(addresses) >= 3:\n return Error('Maximum of 3 addresses allowed')\n elif len(addresses) >= 1:\n random_id = shortuuid.ShortUUID().random(length=12)\n address_object = Address(user_id=user_id,\n id=random_id,\n store_id=store_id,\n address=address,\n is_active=False)\n address_object.save()\n else:\n address_object = Address(user_id=user_id,\n store_id=store_id,\n address=address)\n address_object.save()\n return CreateAddress(message='Address added successfully')\n elif user_id and store_id:\n return Error('You can only pass either userId or storeId')\n return Error(\"Supply userId or storeId\")\n return Error(\"Address cannot be empty\")\n except User.DoesNotExist:\n return Error('User does not exist')\n except Store.DoesNotExist:\n return Error('Store does not exist')\n\n\n# Mutation to delete an Address\nclass DeleteAddress(graphene.Mutation):\n class Arguments:\n address_id = graphene.String(required=True)\n\n message = graphene.String()\n\n @staticmethod\n def mutate(self, info, address_id):\n try:\n address = Address.objects.get(id=address_id)\n address.delete()\n return DeleteAddress(message='Address Deleted Successfully')\n except Address.DoesNotExist:\n return Error(\"Address does not exist\")\n\n\n# Mutation for updating Address\nclass UpdateAddress(graphene.Mutation):\n class Arguments:\n address_id = graphene.String(required=True)\n is_active = graphene.Boolean()\n address = graphene.String()\n\n message = graphene.String()\n\n @staticmethod\n def mutate(self, info, address_id, **args):\n try:\n address_instance = Address.objects.get(id=address_id)\n if args:\n for arg in args:\n if (arg == 'address') and (not args.get(arg).strip()):\n return Error('Address cannot be empty')\n setattr(address_instance, arg, args.get(arg))\n address_instance.save()\n return UpdateAddress(message='Update successful!')\n return Error('No field(s) Provided')\n except Address.DoesNotExist:\n return Error('Address does not exist')\n\n\n# Address mutations bundled together\nclass AddressMutations(graphene.ObjectType):\n create_address = CreateAddress.Field()\n delete_address = DeleteAddress.Field()\n update_address = UpdateAddress.Field()\n\n\n# Query to get the all User and Store Addresses\nclass AddressQueries(graphene.ObjectType):\n get_user_addresses = graphene.List(AddressType,\n user_id=graphene.String())\n get_store_addresses = graphene.List(AddressType,\n store_id=graphene.String())\n\n def resolve_get_user_addresses(self, info, user_id):\n try:\n User.objects.get(id=user_id)\n return Address.objects.filter(user_id=user_id)\n except User.DoesNotExist:\n return Error('User does not exist')\n\n def resolve_get_store_addresses(self, info, store_id):\n try:\n Store.objects.get(id=store_id)\n return Address.objects.filter(store_id=store_id)\n except Store.DoesNotExist:\n return Error('Store does not exist')\n","sub_path":"food_basket/schema/address.py","file_name":"address.py","file_ext":"py","file_size_in_byte":5119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"186854626","text":"import os\n\ndirname = os.path.dirname(__file__)\n\ndef getUserInfo():\n filename = os.path.join(dirname, 'user')\n file_user = open(filename, mode='rt', encoding='utf-8')\n lines_user = file_user.readlines()\n user = list()\n for line in lines_user:\n user.append(line.replace('\\n', '').replace(' ', '').split(':'))\n return dict(user)\n\ndef getDbInfo():\n filename = os.path.join(dirname, 'profile')\n file_profile = open(filename, mode='rt', encoding='utf-8')\n liens_profile = file_profile.readlines()\n profile = list()\n for line in liens_profile:\n profile.append(line.replace('\\n', '').replace(' ', '').split(':'))\n return dict(profile)","sub_path":"util/info.py","file_name":"info.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"303670476","text":"import random\nfrom flask import render_template, redirect, url_for, abort, flash, request\nfrom flask.ext.login import login_required, current_user\nfrom werkzeug.utils import secure_filename\nfrom . import main\nfrom .forms import EditProfileForm, ProblemSubmitForm, SolutionSubmitForm\nfrom .. import db\nfrom ..models import Permission, Role, User, Problem, Submission\nfrom ..decorators import admin_required, permission_required\n\n\n@main.route('/', methods=['GET'])\ndef index():\n return render_template('index.html')\n\n@main.route('/user/')\ndef user(id):\n user = User.query.filter_by(id=id).first_or_404()\n return render_template('user.html', user=user)\n\n\n@main.route('/edit-profile', methods=['GET', 'POST'])\n@login_required\ndef edit_profile():\n form = EditProfileForm()\n if form.validate_on_submit():\n filename = secure_filename(form.photo.data.filename)\n form.photo.data.save('uploads/' + filename)\n current_user.photo = form.photo.data\n current_user.username = form.username.data\n current_user.name = form.name.data\n current_user.website = form.website.data\n current_user.occupation = form.occupation.data\n current_user.company = form.company.data\n current_user.school = form.school.data\n current_user.about_me = form.about_me.data\n db.session.add(current_user)\n db.session.commit()\n flash('Your profile has been updated.')\n return redirect(url_for('.user', id=current_user.id))\n form.name.data = current_user.name\n form.photo.data = current_user.photo\n form.username.data = current_user.username\n form.name.data = current_user.name\n form.website.data = current_user.website\n form.occupation.data = current_user.occupation\n form.company.data = current_user.company\n form.school.data = current_user.school\n form.about_me.data = current_user.about_me\n return render_template('edit_profile.html', form=form)\n\n@main.route('/problems/', methods=['GET'])\ndef problems(classification):\n problems = Problem.query.filter_by(classification=classification).all()\n return render_template('problems.html', problems=problems)\n\n@main.route('/problem/', methods=['GET', 'POST'])\n@login_required\ndef problem(id):\n problem = Problem.query.get_or_404(id)\n form = SolutionSubmitForm()\n if form.validate_on_submit():\n submission = Submission(body=form.body.data,\n problem=problem,\n author=current_user._get_current_object())\n db.session.add(submission)\n flash('Your solution has been submitted.')\n return redirect(url_for('.problem', id=problem.id))\n return render_template('problem.html', form=form, problem=problem)\n\n@main.route('/pick-one', methods=['GET'])\n@login_required\ndef pick_one():\n num_of_problems = Problem.query.count()\n id = random.sample(range(num_of_problems), 1)\n return redirect(url_for('.problem', id=id))\n\n@main.route('/mock-interview', methods=['GET'])\n@login_required\ndef mock_interview():\n num_of_problems = Problem.query.count()\n IDs = random.sample(range(num_of_problems), 10)\n problems = []\n for id in IDs:\n problem = Problem.query.filter_by(id=id)\n problems.append(problem)\n return render_template('problems.html', problems=problems)\n\n\n@main.route('/submit-problem', methods=['GET', 'POST'])\n@admin_required\ndef submit_problem():\n form = ProblemSubmitForm()\n if form.validate_on_submit():\n problem = Problem(body=form.body.data,\n difficulty=form.difficulty.data,\n solution=form.solution.data)\n db.session.add(problem)\n flash('The problem has been added.')\n return redirect(url_for('.problem', id=problem.id))\n return render_template('submit_problem.html', form=form)\n\n\n@main.route('/edit-submission/', methods=['GET', 'POST'])\n@login_required\ndef edit_submission(id):\n submission = Submission.query.get_or_404(id)\n problem = submission.problem\n if current_user != submission.author and \\\n not current_user.can(Permission.ADMINISTER):\n abort(403)\n form = SolutionSubmitForm()\n if form.validate_on_submit():\n submission.body = form.body.data\n db.session.add(submission)\n flash('The submission has been updated.')\n return redirect(url_for('.submission', id=submission.id))\n form.body.data = submission.body\n return render_template('edit_submission.html', form=form,problem=problem, submission=submission)\n\n\n@main.route('/submission/', methods=['GET'])\n@login_required\ndef submission(id):\n submission = Submission.query.get_or_404(id)\n problem = submission.problem\n return render_template('submission.html', problem=problem, submission=submission)\n\n\n@main.route('/edit-problem/', methods=['GET', 'POST'])\n@admin_required\ndef edit_problem(id):\n problem = Problem.query.get_or_404(id)\n if not current_user.can(Permission.ADMINISTER):\n abort(403)\n form = ProblemSubmitForm()\n if form.validate_on_submit():\n problem.title = form.title.data\n problem.body = form.body.data\n problem.difficulty=form.difficulty.data\n problem.solution=form.solution.data\n db.session.add(problem)\n flash('The problem has been updated.')\n return redirect(url_for('.problem', id=problem.id))\n form.title.data = problem.title\n form.body.data = problem.body\n form.difficulty.data = problem.difficulty\n form.solution.data = problem.solution\n return render_template('edit_problem.html', problem=problem, form=form)","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"9549821","text":"import numpy as np\nimport datetime\n\nclass FlpDualLSSVM(object):\n\n def __init__(self, lambd, lr=1e-2, max_iter=50, kernel=\"linear\", tolerance=1e-7, degree=None) -> None:\n super().__init__()\n self.lr = lr\n self.degree = degree\n self.lambd = lambd\n self.tolerance = tolerance\n self.kernel_type = kernel\n self.max_iter = max_iter\n\n def kernel(self, a, b):\n if self.kernel_type == \"linear\":\n return a.T.dot(b)[0][0]\n if self.kernel_type == \"poly\":\n return np.power(1 + a.T.dot(b)[0][0], self.degree)\n\n def compute_omega(self):\n omega = np.zeros(shape=(self.data.shape[0], self.data.shape[0]))\n for i in range(self.data.shape[0]):\n for j in range(self.data.shape[0]):\n Xi = np.expand_dims(self.data[i], axis=1)\n Xj = np.expand_dims(self.data[j], axis=1)\n omega[i][j] = self.y[i][0] * self.y[j][0] * self.kernel(Xi, Xj)\n return omega\n \n def predict_distance_vect(self, x):\n prediction = 0\n for i in range(self.data.shape[0]):\n Xi = np.expand_dims(self.data[i], axis=1)\n prediction += self.alphas[i][0] * self.y[i][0] * self.kernel(Xi, x)\n \n prediction += self.b\n\n return prediction\n\n def predict_distance(self, X):\n predictions = np.zeros(shape=(X.shape[0], 1))\n for i in range(X.shape[0]):\n Xi = np.expand_dims(X[i], axis=1)\n predictions[i][0] = self.predict_distance_vect(Xi)\n\n return predictions\n\n def predict(self, X):\n predictions = self.predict_distance(X)\n return np.sign(predictions)\n\n def compute_A(self, omega, y):\n omega_lamba_id = omega + self.lambd * np.identity(self.data.shape[0])\n \n upper_A = np.concatenate((np.array([[0]]), y.T), axis=1)\n lower_A = np.concatenate((y, omega_lamba_id), axis=1)\n\n A = np.concatenate((upper_A, lower_A), axis=0)\n\n return A\n\n def fit(self, X, y):\n self.data = X\n self.y = y\n\n self.info = dict()\n self.info[\"accuracy\"] = list()\n self.info[\"pk_norm\"] = list()\n \n self.steps = 0\n \n omega = self.compute_omega()\n\n A = self.compute_A(omega, y)\n\n opt_matrix = np.dot(A.T, A)\n ones_hat = np.concatenate((np.array([[0]]), np.ones(shape=(self.data.shape[0], 1))), axis=0)\n opt_vect = np.dot(A.T, ones_hat)\n\n beta_k = np.random.random(size=(self.data.shape[0] + 1, 1))\n for i in range(self.max_iter):\n p_k = opt_vect - np.dot(opt_matrix, beta_k)\n r_k = np.dot(p_k.T, p_k) / np.dot(p_k.T, np.dot(opt_matrix, p_k))\n \n beta_k = beta_k + (1 - self.lr) * r_k * p_k\n \n self.alphas = beta_k[1:]\n self.b = beta_k[0][0]\n\n self.info[\"accuracy\"].append(self.score(self.data, self.y))\n self.info[\"pk_norm\"].append(np.linalg.norm(p_k))\n \n print(\"||pk|| =\", np.linalg.norm(p_k))\n if np.linalg.norm(p_k) ** 2 < self.tolerance:\n break\n \n self.steps += 1\n \n self.alphas = beta_k[1:]\n self.b = beta_k[0][0]\n\n return self.alphas, self.b\n\n def score(self, X, y_true):\n predict = self.predict(X)\n n_correct = np.sum(predict == y_true)\n return n_correct / X.shape[0]","sub_path":"source/floating_svm/flp_dual_svm_ls.py","file_name":"flp_dual_svm_ls.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"506114783","text":"import unittest\nimport openmesh\n\nimport numpy as np\n\nclass Normals(unittest.TestCase):\n \n def setUp(self):\n self.mesh = openmesh.TriMesh()\n \n # Add some vertices\n self.vhandle = []\n \n self.vhandle.append(self.mesh.add_vertex(np.array([0, 0, 0])))\n self.vhandle.append(self.mesh.add_vertex(np.array([0, 1, 0])))\n self.vhandle.append(self.mesh.add_vertex(np.array([1, 1, 0])))\n self.vhandle.append(self.mesh.add_vertex(np.array([0, 0, 1])))\n \n # Add four faces\n face_vhandles = []\n \n face_vhandles.append(self.vhandle[0])\n face_vhandles.append(self.vhandle[1])\n face_vhandles.append(self.vhandle[2])\n self.mesh.add_face(face_vhandles)\n \n face_vhandles = []\n \n face_vhandles.append(self.vhandle[0])\n face_vhandles.append(self.vhandle[2])\n face_vhandles.append(self.vhandle[3])\n self.mesh.add_face(face_vhandles)\n \n face_vhandles = []\n \n face_vhandles.append(self.vhandle[2])\n face_vhandles.append(self.vhandle[1])\n face_vhandles.append(self.vhandle[3])\n self.mesh.add_face(face_vhandles)\n \n face_vhandles = []\n \n face_vhandles.append(self.vhandle[3])\n face_vhandles.append(self.vhandle[1])\n face_vhandles.append(self.vhandle[0])\n self.mesh.add_face(face_vhandles)\n\n def test_normal_calculations(self):\n # Check one Request only vertex normals\n # Face normals are required for vertex and halfedge normals, so\n # that prevent access to non existing properties are in place\n \n self.mesh.request_vertex_normals()\n self.mesh.request_halfedge_normals()\n\n # Check blocks\n self.mesh.update_normals()\n\n # Request required face normals\n self.mesh.request_face_normals()\n\n # Automatically compute all normals\n # As only vertex normals are requested and no face normals, this will compute nothing.\n self.mesh.update_normals()\n\n # Face normals alone\n self.mesh.update_face_normals()\n\n # Vertex normals alone (require valid face normals)\n self.mesh.update_vertex_normals()\n\n # Halfedge normals alone (require valid face normals)\n self.mesh.update_halfedge_normals()\n\n def test_calc_vertex_normal_fast(self):\n n = self.mesh.calc_vertex_normal_fast(self.vhandle[2])\n self.assertTrue(np.allclose(n, np.array([0.70710678, 0., -0.29289322])))\n\n def test_calc_vertex_normal_correct(self):\n n = self.mesh.calc_vertex_normal_correct(self.vhandle[2])\n self.assertTrue(np.allclose(n, np.array([1, 0, 0])))\n\n def test_calc_vertex_normal_loop(self):\n n = self.mesh.calc_vertex_normal_loop(self.vhandle[2])\n self.assertTrue(np.allclose(n, np.array([0.8660254, 0, 0])))\n\n\nif __name__ == '__main__':\n suite = unittest.TestLoader().loadTestsFromTestCase(Normals)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","sub_path":"tests/test_trimesh_normal_calculations.py","file_name":"test_trimesh_normal_calculations.py","file_ext":"py","file_size_in_byte":3040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"329373907","text":"# Author: toferc\n# Python=3.5\n\nimport os\nimport json\nimport csv\n\n# Enter your data directory here\ndata_dir = \"./data\"\n\n# Prepares data dictionary to include:\n'''text, intent, entities\n\tentities is a list that includes dictionaries of:\n\t\t{start: int, end: int, value: str, entity: str}\n\n\tE.g:\n\t\t{\n \"text\": \"i'm looking for a place in the north of town\",\n \"intent\": \"restaurant_search\",\n \"entities\": [\n {\n \"start\": 31,\n \"end\": 36,\n \"value\": \"north\",\n \"entity\": \"location\"\n }\n ]\n },'''\n\n\ndef open_csv():\n # Open CSV file and create or add data into JSON file\n\n infile = input(\"Please enter your input file name (.csv): \")\n outfile = input(\"Please enter your output file name (.json): \")\n\n data_output = create_load_outfile(outfile)\n\n intents = []\n\n with open(os.path.join(data_dir, infile), \"r+\") as f:\n reader = csv.reader(f, delimiter=\",\", quotechar='\"')\n for i, row in enumerate(reader):\n text, intent, *entities = row\n\n entity_list = []\n\n intents.append(intent)\n\n for entity in entities:\n start, end, value, entity_type = entity.split(\",\")\n entity_list.append(\n {\n \"start\": int(start),\n \"end\": int(end),\n \"value\": value,\n \"entity\": entity_type\n })\n\n data_output['rasa_nlu_data']['entity_examples'].append(\n {'text': text, 'intent': intent, 'entities': entity_list})\n\n save_json_file(outfile, data_output)\n\n\ndef enter_text():\n # Prompt user to enter text, identify intents, entities and values and write to rasa nlu JSON format\n\n intents = []\n entity_types = []\n\n outfile = input(\"Please enter your output file name (.json): \")\n\n data_output = create_load_outfile(outfile)\n print(data_output)\n\n print(\"Welcome. First enter your different types of intent. Just hit enter when you're finished.\\n\")\n\n while True:\n intents_input = input(\"Enter intent type: \").lower()\n if intents_input == \"\":\n break\n else:\n intents.append(intents_input)\n\n print(\"\\nEnter your entity types.\\n\")\n\n while True:\n entities_input = input(\"Enter entity type: \").lower()\n if entities_input == \"\":\n break\n else:\n entity_types.append(entities_input)\n\n print(\n \"\\nGood. Now the setup is done. You will now enter a number of phrases. Hit enter on a blank line when you are finished.\")\n\n while True:\n text = input(\"\\nEnter your text (or hit enter to end): \").lower()\n\n if text == \"\":\n break\n\n else:\n print(\"\\nNow choose your intent from the list below:\")\n for i, intent in enumerate(intents):\n print(\"{}: {}\".format(i + 1, intent))\n\n intent_choice = intents[int(input(\"\\nEnter the number corresponding to your intent: \")) - 1]\n print(\"Intent: {}\".format(intent_choice))\n\n entities = []\n\n while True:\n print(\"\")\n for i, word in enumerate(text.lower().split()):\n print(\"{}: {}\".format(i + 1, word))\n\n value = input(\"\\nEnter the number corresponding to your entity, enter a phrase or hit return to skip: \")\n\n if value == \"\": # User wants to exit\n break\n elif value in \"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\".split(): # User selected a single word\n value = text.split()[int(value) - 1]\n else: # User entered a phrase\n pass\n\n start = int(text.find(value))\n end = int(start + len(value))\n\n print(\"Choose your entity type.\")\n for i, entity in enumerate(entity_types):\n print(\"{}: {}\".format(i + 1, entity))\n\n entity_type = entity_types[\n int(input(\"\\nChoose the number for your entity type or hit enter to pass: \")) - 1]\n\n entities.append({\n \"start\": start,\n \"end\": end,\n \"value\": value,\n \"entity\": entity_type\n })\n\n data_output['rasa_nlu_data']['entity_examples'].append(\n {'text': text, 'intent': intent_choice, 'entities': entities})\n\n save_json_file(outfile, data_output)\n\n\ndef create_load_outfile(outfile):\n # type: () -> object\n\n if os.path.isfile(os.path.join(data_dir, outfile)):\n add_to_file = input(\"It looks like this file already exists. Would you like to add to it? (y/n)\")\n\n if add_to_file == \"y\":\n with open(os.path.join(data_dir, outfile)) as json_data:\n return json.load(json_data)\n\n else:\n return {\"rasa_nlu_data\": {\"entity_examples\": []}}\n\n\ndef save_json_file(outfile, data_output):\n # Save dictionary to rasa nlu JSON format\n with open(os.path.join(data_dir, outfile), 'w+') as f:\n json.dump(data_output, f, ensure_ascii=False, indent=4)\n\n\nif __name__ == \"__main__\":\n input_type = input(\"Would you like to import from a csv or enter text manually? (csv OR text) \")\n\n if input_type == \"csv\":\n open_csv()\n else:\n enter_text()\n","sub_path":"generate_rasa_json.py","file_name":"generate_rasa_json.py","file_ext":"py","file_size_in_byte":5426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"336062929","text":"from zoundry.appframework.global_services import getApplicationModel\r\nfrom zoundry.appframework.global_services import getResourceRegistry\r\nfrom zoundry.appframework.ui.widgets.controls.html import ZHTMLControl\r\nfrom zoundry.blogapp.constants import IZBlogAppServiceIDs\r\nfrom zoundry.blogapp.messages import _extstr\r\nfrom zoundry.blogapp.ui.dialogs.accountprefsdialog import ZAccountManagerDialog\r\nfrom zoundry.blogapp.ui.events.viewevents import ZEVT_VIEW_SELECTION_CHANGED\r\nfrom zoundry.blogapp.ui.util.publisherutil import ZPublisherSiteSynchUiUtil\r\nfrom zoundry.blogapp.ui.views.boxedview import ZBoxedView\r\nfrom zoundry.blogapp.ui.views.viewsel import IZViewSelectionTypes\r\nfrom zoundry.blogapp.util.viewutil import loadStaticHtml\r\nimport wx\r\n\r\n# --------------------------------------------------------------------------------------\r\n# This class implements the Standard Perspective's ContextInfo View when the user has\r\n# selected a Blog Account in the Navigator. When that selection is made, the account\r\n# summary information is shown.\r\n# --------------------------------------------------------------------------------------\r\nclass ZContextInfoAccountSummaryView(ZBoxedView):\r\n\r\n def __init__(self, parent):\r\n self.accountStore = getApplicationModel().getService(IZBlogAppServiceIDs.ACCOUNT_STORE_SERVICE_ID)\r\n self.account = None\r\n\r\n ZBoxedView.__init__(self, parent)\r\n # end __init__()\r\n\r\n def _getHeaderBitmap(self):\r\n return getResourceRegistry().getBitmap(u\"images/perspectives/standard/account_summary.png\") #$NON-NLS-1$\r\n # end _getHeaderBitmap()\r\n\r\n def _getHeaderLabel(self):\r\n return _extstr(u\"acctsummary.AccountSummary\") #$NON-NLS-1$\r\n # end _getHeaderLabel()\r\n\r\n def _createHeaderWidgets(self, parent, widgetList):\r\n pass\r\n # end _createHeaderWidgets()\r\n\r\n def _createContentWidgets(self, parent):\r\n self.htmlWidget = ZHTMLControl(parent, style = wx.NO_BORDER)\r\n self.htmlWidget.SetBorders(0)\r\n # end _createContentWidgets()\r\n\r\n def _layoutContentWidgets(self):\r\n box = wx.BoxSizer(wx.VERTICAL)\r\n box.Add(self.htmlWidget, 1, wx.EXPAND)\r\n return box\r\n # end _layoutContentWidgets()\r\n\r\n def refreshContent(self, selection):\r\n accountId = selection.getData()\r\n self.account = self.accountStore.getAccountById(accountId)\r\n self._populateWidgets()\r\n # end refreshContent()\r\n\r\n def _bindWidgetEvents(self):\r\n ZBoxedView._bindWidgetEvents(self)\r\n \r\n self.Bind(ZEVT_VIEW_SELECTION_CHANGED, self.onSelectionChanged)\r\n # end _bindWidgetEvents()\r\n\r\n def onSelectionChanged(self, event):\r\n selection = event.getSelection()\r\n if selection.getType() == IZViewSelectionTypes.ACCOUNT_SELECTION:\r\n self.refreshContent(selection)\r\n # end onSelectionChanged()\r\n\r\n def _populateWidgets(self):\r\n params = {\r\n u\"account_summary\" : _extstr(u\"acctsummary.AccountSummary\"), #$NON-NLS-1$ #$NON-NLS-2$\r\n u\"zoundry_raven\" : _extstr(u\"ZoundryRaven\"), #$NON-NLS-1$ #$NON-NLS-2$\r\n u\"view_settings_desc\" : _extstr(u\"acctsummary.ViewSettingsDesc\"), #$NON-NLS-1$ #$NON-NLS-2$\r\n u\"refresh_account\" : _extstr(u\"acctsummary.RefreshDesc\"), #$NON-NLS-1$ #$NON-NLS-2$\r\n u\"view_settings\" : _extstr(u\"acctsummary.ViewSettings\"), #$NON-NLS-1$ #$NON-NLS-2$\r\n u\"refresh\" : _extstr(u\"acctsummary.Refresh\"), #$NON-NLS-1$ #$NON-NLS-2$\r\n u\"account_name\" : self.account.getName(), #$NON-NLS-1$\r\n u\"settings_imgpath\" : getResourceRegistry().getImagePath(u\"images/perspectives/standard/contextinfo/account_summary/settings.png\"), #$NON-NLS-1$ #$NON-NLS-2$\r\n u\"refresh_imgpath\" : getResourceRegistry().getImagePath(u\"images/perspectives/standard/contextinfo/account_summary/synch.png\"), #$NON-NLS-1$ #$NON-NLS-2$\r\n }\r\n\r\n htmlPath = getResourceRegistry().getResourcePath(u\"html/perspectives/standard/contextinfo/account_summary.html\") #$NON-NLS-1$\r\n html = loadStaticHtml(htmlPath, params); #$NON-NLS-1$\r\n\r\n self.htmlWidget.SetPage(html)\r\n # end _populateWidgets()\r\n\r\n def onViewSettings(self):\r\n dialog = ZAccountManagerDialog(self, self.account)\r\n dialog.ShowModal()\r\n dialog.Destroy()\r\n # end onViewSettings()\r\n\r\n def onOnlineSync(self):\r\n ZPublisherSiteSynchUiUtil().synchronizeAccount(self, self.account)\r\n # end onOnlineSync()\r\n\r\n# end ZContextInfoAccountSummaryView\r\n","sub_path":"src/python/zoundry/blogapp/ui/views/standard/ctxview/acctsummary.py","file_name":"acctsummary.py","file_ext":"py","file_size_in_byte":4540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"44407181","text":"import json\nimport pickle\nimport numpy as np\n\ndef get_location_names():\n with open (\"artifacts/columns.json\",'r') as f:\n data_columns = json.load(f)['data_columns']\n global len_of_columns\n len_of_columns = len(data_columns)\n data_columns = data_columns[3:]\n return data_columns\n\ndef load_save_artifacts():\n model_pickle = \"artifacts/banglore_home_prices_model.pickle\"\n with open(model_pickle, 'rb') as f:\n model=pickle.load(f)\n return model\n\ndef get_estimated_price(location,sqft,bhk,bath):\n model = load_save_artifacts()\n try:\n loc_index = get_location_names().index(location.lower())\n except:\n loc_index=-1\n x =np.zeros(len_of_columns)\n x[0] = sqft\n x[1] = bath\n x[2] = bhk\n if loc_index >= 0:\n x[loc_index] = 1\n\n return model.predict([x])[0]\n\n\n\n\nif __name__ == \"__main__\":\n data_columns = get_location_names()\n\n print(data_columns)\n print(get_estimated_price('1st phase jp nagar', 1000, 2, 2))","sub_path":"real_estate_app/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"1286552","text":"from sqlalchemy import Column, Integer, String, Date, ForeignKey\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\n\n\nclass Producto(Base):\n __tablename__ = 'PRODUCTO'\n\n codProducto = Column(String, primary_key=True)\n nomProducto = Column(String)\n\n def __init__(self, codProducto, nomProducto):\n self.codProducto = codProducto\n self.nomProducto = nomProducto\n\n\nclass Entrega(Base):\n __tablename__ = 'ENTREGA'\n\n codFecha = Column(Integer, primary_key=True)\n fecPedido = Column(String)\n fecEntrega = Column(String)\n\n def __init__(self, codFecha, fecPedido, fecEntrega):\n self.codFecha = codFecha\n self.fecPedido = fecPedido\n self.fecEntrega = fecEntrega\n\n\nclass Cliente(Base):\n __tablename__ = 'CLIENTE'\n\n codCliente = Column(Integer, primary_key=True)\n nomCliente = Column(String)\n\n def __init__(self, codCliente, nomCliente):\n self.codCliente = codCliente\n self.nomCliente = nomCliente\n\n\nclass EntregaProducto(Base):\n __tablename__ = 'ENTREGAPRODUCTO'\n\n codFechaF = Column(Integer,\n ForeignKey('Entrega.codFecha'),\n primary_key=True)\n codProdutoF = Column(String,\n ForeignKey('Producto.codProducto'),\n primary_key=True)\n\n def __init__(self, codFecha, codProducto):\n self.codFechaF = codFecha\n self.codProdutoF = codProducto\n\n\nclass ProductoCliente(Base):\n __tablename__ = 'PRODUCTOCLIENTE'\n\n codProductoF = Column(String,\n ForeignKey('Producto.codProducto'),\n primary_key=True)\n codClienteF = Column(Integer,\n ForeignKey('Cliente.codCliente'),\n primary_key=True)\n\n def __init__(self, codProducto, codCliente):\n self.codProductoF = codProducto\n self.codClienteF = codCliente\n","sub_path":"datos/Tablas.py","file_name":"Tablas.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"253487478","text":"import pyodbc\n\nlote = 1000 #Quantidade de buscas por consulta\n\n#Cria conexão com o DB\nconnection = pyodbc.connect(\"Driver={SQL Server Native Client 11.0};\"\n \"Server=SERVIDOR;\"\n \"Database=DB_NAME;\"\n \"Trusted_Connection=yes;\")\n\n#Query SQL que será executada para buscar os endereços\nquery = 'SELECT CPF, ENDERECO FROM ENDERECOS WHERE CPF IN ({0})'\n\n#Lista de pessoas com CPFs distintos\nlista_pes = list(str(x) for x in pd.unique(df['CPF'][0:2000]))\n\n#Lista vazia onde serão inseridas as informações\nlista_destino = []\n\n\n#Cria os lotes das consultas, como um slicer. Ex: [0:1000] e assim vai até o tamanho total da base\nfor i in range(1, round(len(lista_pes) / lote) + 1): #lista_pes = lista com os cpfs que quero filtrar na consulta. Exemplo: [12345678901, 12345678902, ...]\n y = i * lote\n x = -lote\n x += y\n lotes = [(x, y)]\n \n #Itera pelos agrupamentos de slicers criados. Ex: [0:1000], [1000:2000]...\n for x, y in lotes:\n query_nova = query.format(', '.join('?' for _ in lista_pes[x:y])) #Insere ? de acordo com a quantidade fornecida nos lotes. Exemplo: SELECT * FROM TABELA WHERE CPF IN (?, ?, ?, ... 1000x)\n cursor = connection.cursor() #Cria cursor da conexão com o DB\n cursor.execute(query_nova, lista_pes[x:y]) #Executa a nova query trazendo apenas 1000 pessoas por vez \n for row in cursor:\n lista_destino.append(row) #Insere na tabela os dados de CPF e ENDEREÇO\n\n \n#Realiza o mesmo processo acima pro resto da base. Ex: se a minha lista_pes tiver 300.070 pessoas, o processo acima não pega as últimas 70 pessoas por causa do arredondamento. Logo esta parte final busca este restante.\nfinal = [(lotes[0][-1], len(lista_pes))]\nfor x, y in final:\n query_nova = query.format(', '.join('?' for _ in lista_pes[x:y]))\n cursor = connection.cursor()\n cursor.execute(query_nova, lista_pes[x:y])\n for row in cursor:\n lista_destino.append(row) \n","sub_path":"in_em_lotes.py","file_name":"in_em_lotes.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"561462089","text":"# -*- coding: utf-8 -*-\nimport math, io, random\nimport gym\nfrom gym import spaces\nfrom gym.utils import seeding\nimport numpy as np\nfrom PIL import Image\nfrom baselines.PythonClient import *\nfrom baselines.projection import *\n\nclass AirSimDisc(gym.Env):\n metadata = {\n 'render.modes': ['human', 'rgb_array'],\n 'video.frames_per_second': 30\n }\n\n def __init__(self):\n self.client = AirSimClient(port=41451)\n self.client.confirmConnection()\n self.client.enableApiControl(True)\n self.client.armDisarm(True)\n self.log_file = open('logs.txt', 'w')\n self.acc_file = open('accs.txt', 'w')\n\n self.min_X = 0.0\n self.max_X = 1.0\n self.min_Y = 0.0\n self.max_Y = 1.0\n self.rt2 = math.sqrt(2)\n self.episodes = 0\n self.cumulative = 0.0\n self.max_iter = 100\n\n self._reset()\n # self.min_position = -1.2\n # self.max_position = 0.6\n # self.max_speed = 0.07\n # self.goal_position = 0.45 # was 0.5 in gym, 0.45 in Arnaud de Broissia's version\n # self.power = 0.0015\n\n # self.low_state = np.array([self.min_position, -self.max_speed])\n # self.high_state = np.array([self.max_position, self.max_speed])\n\n self.viewer = None\n #elf.observation = self.image\n #self.observation = np.concatenate([self.last_image, self.image])\n # self.action_space = spaces.Box(0.0, 1.0, shape = (4,))\n #self.action_space = spaces.Box(-0.5, 0.5, shape = (2,))\n self.action_space = spaces.Discrete(9)\n\n #self.observation_space = spaces.Box(low=np.zeros(int(self.width),int(self.height),3), high=np.zeros(int(self.width),int(self.height),3)+255)\n self.observation_space = spaces.Box(low=np.zeros(self.observation.shape), high=np.zeros(self.observation.shape)+255)\n self.observation = None\n\n self._seed()\n\n def get_rbg(self, response):\n binary_rgb = response.image_data_uint8\n png = Image.open(io.BytesIO(binary_rgb)).convert('RGB')\n rgb = np.array(png)\n self.width = rgb.shape[1]\n self.height = rgb.shape[0]\n #rgb_vec = rgb.flatten()\n return rgb\n\n def get_depth(self, response):\n binary_rgb = response.image_data_uint8\n png = Image.open(io.BytesIO(binary_rgb)).convert('RGB')\n rgb = np.array(png)\n depth = np.expand_dims(rgb[:,:,0], axis=2)\n #w = Image.fromarray(depth, mode='L')\n #w.show()\n self.width = rgb.shape[1]\n self.height = rgb.shape[0]\n #depth_vec = depth.flatten()\n return depth\n\n def _seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def get_obs(self, action=None):\n if self.image is None:\n return None\n\n #self.observation = self.image\n self.observation = np.concatenate([self.last_image, self.image])\n\n #self.observation = self.observation.flatten()\n #if action is not None:\n # a = np.array(action).flatten()\n # self.observation = np.concatenate([a, self.observation])\n\n return self.observation\n\n # Mapping\n # 0 1 2\n # 3 4 5\n # 6 7 8\n def _step(self, raw_action):\n #action = np.matrix([raw_action.item(0)*float(self.width),raw_action.item(1)*float(self.height)])\n #x = self.c.item(0)/self.width\n #y = self.c.item(1)/self.height\n #self.reward = 1-((np.linalg.norm(action-self.last_loc))/self.rt2)\n action = [int(raw_action%3), int(raw_action/3)]\n self.reward = 1-((action[0]-self.last_loc[0])**2+(action[1]-self.last_loc[1])**2)\n if self.reward == 1:\n self.nb_correct += 1\n self.cumulative += self.reward\n self.iteration += 1\n #print(self.iteration)\n\n if self.episodes % 500 == 0:\n if self.fw is None:\n self.fw = open('./images/episode_'+str(self.episodes)+'/actions.txt', 'w')\n self.fw.write('('+str(raw_action)+')\\n')\n\n # An action of 0 is the NOOP\n j = 0\n while True:\n if j > 100:\n self.done = True\n\n if self.episodes % 500 == 0:\n self.fw.close()\n self.fw = None\n self.episodes+=1\n acc = float(self.nb_correct)/float(self.iteration)\n print(str(self.episodes)+': '+str(self.cumulative/float(self.iteration))+' *'+str(self.iteration))\n self.log_file.write(str(self.episodes)+': '+str(self.cumulative/float(self.iteration))+' *'+str(self.iteration)+'\\n')\n print('Accuracy: '+str(acc))\n self.acc_file.write(str(acc)+'\\n')\n self.nb_correct = 0\n self.cumulative = 0\n return self.observation, self.reward, self.done, self.info\n rot_inc = 5.0+float(j)/10.0\n vel_inc = 1.0+float(j)/10.0\n #print(rot_inc)\n dC = np.matrix([random.normalvariate(self.v.item(0),vel_inc/self.fps),\n random.normalvariate(self.v.item(1),vel_inc/self.fps),\n random.normalvariate(self.v.item(2),vel_inc/self.fps)]\n )\n dO = np.matrix([random.normalvariate(self.r.item(0),vel_inc/self.fps),\n random.normalvariate(self.r.item(1),rot_inc/self.fps),\n random.normalvariate(self.r.item(2),rot_inc/self.fps)]\n )\n newC = np.add(self.c, dC)\n newO = np.add(self.o, dO)\n d = np.linalg.norm(self.t-newC)\n (x, y) = projection(self.t, newC, newO, w=float(self.width), h=float(self.height))\n total_v = np.linalg.norm(dC)\n if x <= float(self.width)*0.95 and x >= float(self.width)*0.05 and y <= float(self.height)*0.95 and y >= float(self.height)*0.05 \\\n and d > 3 and d < 30 and newC.item(2) < -2 \\\n and total_v*self.fps <= 30:\n break\n j += 1\n self.c = newC\n self.v = dC\n self.o = newO\n self.r = dO\n x = 3*x/float(self.width)\n y = 3*y/float(self.height)\n self.last_loc = [int(x), int(y)]\n self.state = self._render()\n self.observation = self.get_obs(self.last_loc)\n self.done = (self.iteration > self.max_iter)\n info = (self.c, self.v, self.o, self.r)\n self.info = {}\n #print(action)\n #print(np.matrix([x,y]))\n #print(self.reward)\n if self.done:\n if self.episodes % 500 == 0:\n self.fw.close()\n self.fw = None\n self.episodes+=1\n acc = float(self.nb_correct)/float(self.iteration)\n print(str(self.episodes)+': '+str(self.cumulative/float(self.iteration)))\n self.log_file.write(str(self.episodes)+': '+str(self.cumulative/float(self.iteration))+'\\n')\n print('Accuracy: '+str(acc))\n self.acc_file.write(str(acc)+'\\n')\n self.nb_correct = 0\n self.cumulative = 0\n return self.observation, self.reward, self.done, self.info\n\n def _reset(self):\n self.iteration = 0\n self.t = np.matrix([-10.0, 10.0, -10.0])\n self.o = np.matrix([0.0,0.0,0.0])\n self.c = np.matrix([-20.0, 10.0, -10.0])\n self.v = np.matrix([0.0,0.0,0.0])\n self.r = np.matrix([0.0,0.0,0.0])\n self.fps = 60.0\n self.nb_correct = 0\n self.client.simSetPose(Vector3r(self.c.item(0), self.c.item(1), self.c.item(2)), \n self.client.toQuaternion(math.radians(self.o.item(1)),math.radians(self.o.item(0)),math.radians(self.o.item(2))))\n self.image = None\n self.fw = None\n #response = self.client.simGetImages([ImageRequest(0, AirSimImageType.Scene)])[0]\n #self.image = self.get_rbg(response)\n\n self._render()\n\n\n (x, y) = projection(self.t, self.c, self.o, w=float(self.width), h=float(self.height))\n x = 3*x/float(self.width)\n y = 3*y/float(self.height)\n self.last_loc = [int(x), int(y)]\n self.observation = self.get_obs(self.last_loc)\n return self.observation\n\n def _render(self, mode='human', close=False):\n self.client.simSetPose(Vector3r(self.c.item(0), self.c.item(1), self.c.item(2)),\n self.client.toQuaternion(math.radians(self.o.item(1)),math.radians(self.o.item(0)),math.radians(self.o.item(2))))\n\n self.last_image = self.image\n responses = self.client.simGetImages([ImageRequest(0, AirSimImageType.Scene),\n ImageRequest(0, AirSimImageType.DepthVis)])\n if self.episodes % 500 == 0:\n if not os.path.exists('./images/episode_'+str(self.episodes)+'/'):\n os.makedirs('./images/episode_'+str(self.episodes)+'/')\n AirSimClient.write_file(os.path.normpath('./images/episode_'+str(self.episodes)+'/'+str(self.iteration)+'.png'),\n responses[0].image_data_uint8)\n rgb = self.get_rbg(responses[0])\n #response = self.client.simGetImages([ImageRequest(0, AirSimImageType.DepthVis)])[0]\n depth = self.get_depth(responses[1])\n self.image = np.concatenate([rgb, depth], axis=2)\n #self.image = rgb\n if self.last_image is None:\n self.last_image = self.image\n\n return self.image\n\n","sub_path":"baselines/AirSimDisc (copy).py","file_name":"AirSimDisc (copy).py","file_ext":"py","file_size_in_byte":9514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"27035791","text":"\"\"\"\n1. Пользователь вводит данные о количестве предприятий, их наименования и\nприбыль за 4 квартала (т.е. 4 отдельных числа) для каждого предприятия..\nПрограмма должна определить среднюю прибыль (за год для всех предприятий) и\nвывести наименования предприятий, чья прибыль выше среднего и отдельно\nвывести наименования предприятий, чья прибыль ниже среднего.\n\nИзначальная идея состоит в том, что у каждой компании должен быть ID (уникальный ключ), по которому мы храним название\nкомпании (допускается, что оно не уникально ... всякое может случиться). Для хранения воспользуемся структурой\nданных defaultdict. Я отказался от использования последовательностей и множеств в пользу отображений Mapping так как\nID может со временем стать чем-то подобен шифру, компании могут удаляться и я не хочу сдвига ID, ну и по многим другим\nпричинам \"потнециального расширения функционала\" (объект \"Компания\" может быть очень многогранным).\n\nВсе оформим в виде функций и пока выведем в виде циклов. Среднюю прибыль каждого предприятия храним дополнительным\nзначением и одним махом выводим и первормеров и андерперформеров.\n\"\"\"\n\nimport collections\nimport random\n\ncompany_dict = collections.defaultdict(list)\n\ndef gen_of_complist(company_count):\n for i in range(1, company_count+1):\n print(\"Give me the #%d company name\" % i)\n next_name = str(input(\"Enter=\"))\n company_dict[i] = [next_name]\n\n\ndef receive_data(company_count):\n for i in range(1, company_count + 1):\n for j in range(1, 5):\n print(\"Give me the #%d quarter results for company '%s'\" % (j, str(company_dict[i][0])))\n next_result = input(\"Enter=\")\n if next_result == '':\n next_result = random.randint(10, 1000)\n print(\">> Random generated=\", next_result)\n company_dict[i].append(int(next_result))\n print(\"-------------------------\")\n\n\ndef take_data(comp_id, qrt=6):\n if qrt > 5:\n return list(company_dict[comp_id])\n else:\n return company_dict[comp_id][qrt]\n\n\ndef take_average(comp_id):\n sum = 0\n for i in range(1, 5):\n sum += int(take_data(comp_id, i))\n company_dict[comp_id].append(sum/4)\n return company_dict[comp_id][5]\n\n\ndef main():\n company_count = int(input(\"How many companies? Enter=\"))\n print(\"-------------------------\")\n gen_of_complist(company_count)\n print(\"-------------------------\")\n receive_data(company_count)\n\n # Определяем среднюю прибыль\n print(\"Averages (per enterprise):\")\n total_sum = 0\n for comp_id in company_dict.keys():\n next_sum = take_average(comp_id)\n print(\"%s = %d\" % (take_data(comp_id, 0), next_sum))\n total_sum += next_sum\n print(\"-------------------------\")\n industry_avg = int(total_sum/company_count)\n print(\"Industry Average =\", industry_avg)\n print(\"-------------------------\")\n\n # Выводим наименования предприятий, чья прибыль выше среднего\n print(\"Performers:\")\n for comp_id in company_dict.keys():\n if company_dict[comp_id][5] > industry_avg:\n print(company_dict[comp_id][0])\n print(\"-------------------------\")\n\n # Выводим наименования предприятий, чья прибыль ниже среднего\n print(\"Under-performers:\")\n for comp_id in company_dict.keys():\n if company_dict[comp_id][5] < industry_avg:\n print(company_dict[comp_id][0])\n print(\"-------------------------\")\n\n\nif __name__ == '__main__':\n main()","sub_path":"Lesson_5/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":4468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"634904502","text":"import numpy as np\n\n\nclass EckartsSpinz:\n\n def __init__(self, reference, coords, masses, planar=None):\n '''\n\n :param reference: A reference structure of the given molecule\n :type reference: np array (Natoms, 3)\n :param coords: The coordinates we want to shift to the Eckart frame\n :type coords: np array (Nwalkers, Natoms, 3)\n :param masses: The masses of each of the Natoms\n :type masses: np array (Natoms)\n :param planar: A flag to pass if the molecule can potentially be planar\n :type planar: True or None\n '''\n self.reference = reference\n self.coords = coords\n self.masses = masses\n self.planar = planar\n self.little_fs = np.zeros((len(coords), 3, 3))\n self.biggo_fs = np.zeros((len(coords), 3, 3))\n self.f_vecs = np.zeros((len(self.coords), 3, 3))\n\n def com_calc(self):\n '''\n This calculates the center of mass of both the reference structure and the coordinates of our walkers and shifts\n by that com\n '''\n com = np.dot(self.masses, self.coords)/np.sum(self.masses)\n self.coords = self.coords - com[:, None, :]\n ref_com = np.dot(self.masses, self.reference)/np.sum(self.masses)\n self.reference = self.reference - ref_com\n\n def create_f_vector_bois(self):\n '''\n This calculates the F vectors from equations 3.x of Louck and Galbraith: Eckart vectors, Eckart Frames, and\n polyatomic molecules\n '''\n mass_weight_ref = self.masses[:, None]*self.reference\n self.little_fs = np.matmul(np.transpose(self.coords, (0, 2, 1)), mass_weight_ref) # generates the F vectors\n # from equation 3.1\n self._indz = np.where(np.around(self.little_fs, 4).any(axis=1))[1][:3] # This is a check to make sure we are\n # or aren't planar\n self._missing_ind = np.setdiff1d(np.arange(3), self._indz)\n\n if self.planar is not None:\n if len(self._missing_ind) < 1:\n print(\"this bad boy isn't planar according to my algorithm. Please supply a reference geometry that \"\n \"is on a 2d plane please\")\n raise ValueError\n self._indz = self._indz[:2]\n self.little_fs = self.little_fs[:, self._indz, :]\n else:\n if len(self._missing_ind) > 0:\n print(\"This bad boy is a planar structure. Please pass the planar flag so the algorithm \"\n \"can work properly\")\n raise ValueError\n self.biggo_fs = np.matmul(self.little_fs, self.little_fs.transpose((0, 2, 1))) # calculates the F matrix\n # from equations 3.4b and 3.4e\n\n def get_eigs(self):\n '''\n This obtains the eigenvalues and eigenvectors of the F (Gram) matrix\n '''\n self.create_f_vector_bois()\n self._eigs, self._eigvs = np.linalg.eigh(self.biggo_fs) # diagonalizes the F matrix\n\n def get_transformed_fs(self):\n '''\n Calculation of the f unit vectors that act as the transformation vectors for our coordinates into the\n Eckart frame seen in equations 3.4a and 3.4d\n '''\n self.com_calc()\n self.get_eigs()\n eig_1o2 = 1/np.sqrt(self._eigs)[:, None, :]\n eigvsT = np.transpose(self._eigvs, (0, 2, 1))\n big_F_m1o2 = (eig_1o2*self._eigvs)@eigvsT # calculates F^(-1/2) through a similarity transform\n # used in equations 3.4a and 3.4d to get our f unit vectors\n if self.planar is None:\n self.f_vecs = np.matmul(self.little_fs, big_F_m1o2)\n mas = np.where(np.around(np.linalg.det(self.f_vecs)) == -1)\n if len(mas[0]) != 0:\n print(\"well, something's wrong\")\n raise ValueError\n else:\n self.f_vecs[:, :, self._indz] = np.matmul(self.little_fs.transpose((0, 2, 1)), big_F_m1o2)\n if self._missing_ind[0] == 1: # f_3 is equal to f_z cross f_x\n self.f_vecs[:, :, self._missing_ind[0]] = np.cross(self.f_vecs[:, :, self._indz[1]],\n self.f_vecs[:, :, self._indz[0]])\n else: # this is the more general formula to obtain f_3\n self.f_vecs[:, :, self._missing_ind[0]] = np.cross(self.f_vecs[:, :, self._indz[0]],\n self.f_vecs[:, :, self._indz[1]])\n mas = np.where(np.around(np.linalg.det(self.f_vecs)) == -1)\n if len(mas[0]) != 0:\n print(\"well, something's wrong\")\n raise ValueError\n\n def get_rotated_coords(self):\n '''\n Use this function if you want to obtain the already transformed coordinates so you don't have to do it\n yourself\n :return: The rotated coordinates of your molecules into the Eckart frame\n :rtype: np array\n '''\n self.get_transformed_fs()\n transform = self.f_vecs@np.transpose(self.coords, (0, 2, 1))\n # return self.coords@self.f_vecs\n return transform.transpose((0, 2, 1))\n\n def return_f_vecs(self):\n '''\n This is for the special people out there that either want to do the matrix multilation of the f vectors and\n their coordinates themselves, or for those that are just curious to see what the f vectors look like I guess\n :return: The f unit vectors that can rotate your coordinates into the Eckart frame\n :rtype: np array\n '''\n self.get_transformed_fs()\n return self.f_vecs\n\n\n","sub_path":"Imp_samp_testing/Eckart_turny_turn.py","file_name":"Eckart_turny_turn.py","file_ext":"py","file_size_in_byte":5794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"493654492","text":"# Define function \"main_loop\" - loops the over the whole programme\ndef main_loop():\n # Import datetime module\n import datetime\n\n print(\"\\n\\n===== TASK MANAGER =====\\n\")\n\n dashes = \"--------------------------------------------------\"\n\n # Assign empty list to variable \"username_stored\" - used to store the username once a person has logged in\n username_stored = []\n\n # Define function \"commands\" - contains the main menu\n def commands():\n\n # If admin logged in - display all options\n if username_stored[0] == \"admin\":\n command = input(\"\"\"Select one of the following options:\nr --> Register user\na --> Add task\nva --> View all tasks\nvm --> View my tasks\ngr --> Generate reports\nds --> Display statistics\ne --> exits\n\n> \"\"\").lower()\n\n # Call the appropriate function once the user has entered an option.\n if command == \"r\":\n reg_user()\n elif command == \"a\":\n add_task()\n elif command == \"va\":\n view_all()\n elif command == \"vm\":\n view_mine()\n elif command == \"gr\":\n reports()\n elif command == \"ds\":\n stats()\n elif command == \"e\":\n print(f\"\\n{dashes}\\n\")\n main_loop()\n else:\n print(f\"{command} is not an option.\\n\")\n commands()\n\n # If the user is not admin - allow access to only certain options\n else:\n command = input(\"\"\"Select one of the following options:\na --> Add task\nva --> View all tasks\nvm --> View my tasks\ne --> exit\n\n> \"\"\").lower()\n\n # Call appropriate function after user has entered an option.\n if command == \"a\":\n add_task()\n elif command == \"va\":\n view_all()\n elif command == \"vm\":\n view_mine()\n elif command == \"e\":\n print(f\"\\n{dashes}\\n\")\n main_loop()\n else:\n print(f\"{command} is not an option.\\n\")\n commands()\n\n # Define function \"reg_user\" - used to register a new user\n def reg_user():\n\n # Read the content from \"user.txt\" and store all usernames and passwords in variable \"users_list\"\n with open(\"user.txt\", \"r\") as users:\n users = users.read()\n\n users_list = users.replace(\",\", \"\").replace(\"\\n\", \" \").split(\" \")\n\n # In a while loop, request username of user to be registered.\n # Check if the username already exist. If it does tell user that it already exists and request username again\n while True:\n new_username = input(\"Username: \")\n\n if new_username in users_list:\n print(f\"{new_username} is already registered.\\n\")\n else:\n\n # In a while loop, request password of new user.\n # Request password confirmation. If confirmed password does not match original password - request\n # password again\n # If confirmed password matched original password - break out of while loop\n while True:\n new_password = input(\"Password: \")\n new_password_confirm = input(\"Confirm password: \")\n\n if new_password_confirm != new_password:\n print(\"Passwords do not match.\\n\")\n else:\n break\n break\n\n # Open \"user.txt\" and append the new username and password.\n with open(\"user.txt\", \"a\") as users:\n users.write(f\"\\n{new_username}, {new_password}\")\n\n print(f\"\\n{new_username} has been registered.\\n\")\n print(f\"{dashes}\\n\")\n\n commands()\n\n # Define function \"add_task\" - used to add a new task\n def add_task():\n\n # Open \"user.txt\". Read the contents and store it as a list in variable \"user_list\"\n with open(\"user.txt\", \"r\") as users:\n users = users.read()\n\n users_list = users.replace(\",\", \"\").replace(\"\\n\", \" \").split(\" \")\n\n # In a while loop request user to which the task will be assigned\n # If the username is not in \"user_list\" (not registered) - request assigned user again\n while True:\n assigned_user = input(\"Assigned to: \")\n\n if assigned_user not in users_list:\n print(f\"{assigned_user} has not been registered.\\n\")\n else:\n break\n\n # Request all information about the new added task\n task = input(\"Task: \")\n date_assigned = input(\"Date assigned (d/m/y): \")\n due_date = input(\"Due date (d/m/y): \")\n description = input(\"Task description: \")\n\n # Open \"tasks.txt\" and append all the tasks information\n with open(\"tasks.txt\", \"a\") as tasks:\n tasks.write(f\"\\nAssigned to: {assigned_user},Task: {task},\"\n f\"Date assigned: {date_assigned},Due date: {due_date},\"\n f\"Task description: {description},Task completed: No\")\n\n print(\"\\nTask added\")\n print(f\"{dashes}\\n\")\n\n commands()\n\n # Define function \"view_all\" - used to view all tasks\n def view_all():\n\n # Open \"tasks.txt\" - read all its contents and store it as a list in \"ll_tasks_list\"\n with open(\"tasks.txt\", \"r\") as tasks:\n tasks = tasks.read()\n\n all_tasks_list = tasks.replace(\"\\n\", \"\\n\\n\").replace(\",\", \"\\n\").split(\"\\n\\n\")\n\n tasks_string = \"\"\n\n # Display all the tasks\n for task in all_tasks_list:\n tasks_string += task + \"\\n\\n\" + \"**************************************************\" + \"\\n\\n\"\n\n print(f\"\\n\\n{tasks_string}\")\n print(f\"\\n{dashes}\")\n print()\n\n commands()\n\n # Define function \"view_ine\" - used to view only the logged in user's tasks\n def view_mine():\n\n # Open \"tasks.txt\" and store its contents in a list in variable \"all_tasks_list\n with open(\"tasks.txt\", \"r\") as tasks:\n tasks = tasks.read()\n\n # Loop through \"all_tasks_list\" and extract only tasks belonging to the logged in user\n # Store all the extracted tasks in \"my_tasks_list\"\n # Display all the user's tasks\n all_tasks_list = tasks.replace(\"\\n\", \"\\n\\n\").replace(\",\", \"\\n\").split(\"\\n\\n\")\n my_tasks_list = [my_tasks for my_tasks in all_tasks_list if username_stored[0] in my_tasks]\n my_tasks_list_length = len(my_tasks_list)\n my_tasks_string = \"\"\n\n count = 1\n for each_task in my_tasks_list:\n my_tasks_string += f\"{count})\\n{each_task}\\n\\n\"\n count += 1\n\n print(f\"\\n{username_stored[0]}'s Tasks:\")\n print(f\"\\n{my_tasks_string}\")\n\n print(dashes)\n\n # In a while loop, allow user to edit any of their tasks\n # Also allow option to return to main menu (\"commands()\")\n while True:\n view_mine_commands = input(f\"\\n-1 --> Return to main menu.\"\n f\"\\n1 to {my_tasks_list_length} --> Select task.\"\n f\"\\n\\n> \")\n\n if view_mine_commands == \"-1\":\n print(f\"{dashes}\\n\")\n commands()\n\n elif int(view_mine_commands) <= my_tasks_list_length:\n\n chosen_index = int(view_mine_commands) - 1\n\n all_tasks_list = tasks.split(\"\\n\")\n my_tasks_list = [my_tasks for my_tasks in all_tasks_list if username_stored[0] in my_tasks]\n task_to_edit = my_tasks_list[chosen_index]\n task_details = task_to_edit.split(\",\")\n\n all_tasks_list_index = all_tasks_list.index(task_to_edit)\n\n # If user wants to change task status to complete - update the task in [all_tasks_list]\n if task_details[5] == \"Task completed: Yes\":\n print(\"\\n>>> Task completed.\")\n print(f\"\\n{dashes}\")\n view_mine()\n else:\n while True:\n edit_command = input(\"1 --> Mark as complete.\\n2 --> Change assigned user\"\n \"\\n3 --> Change due date\"\n \"\\n\\n> \")\n\n # Define function \"task_detail_update\" - used to update any changes done to a task\n def task_detail_update():\n task_details_string = \"\"\n counter = 0\n for each_detail in task_details:\n if counter <= 4:\n task_details_string += each_detail + \",\"\n counter += 1\n else:\n task_details_string += each_detail\n\n all_tasks_list[all_tasks_list_index] = task_details_string\n\n all_tasks_list_string = \"\"\n counter = 0\n for every_task in all_tasks_list:\n if counter <= len(all_tasks_list) - 2:\n all_tasks_list_string += every_task + \"\\n\"\n counter += 1\n else:\n all_tasks_list_string += every_task\n\n with open(\"tasks.txt\", \"w\") as add_edited_task:\n add_edited_task.write(all_tasks_list_string)\n\n if edit_command == \"1\":\n task_details[5] = \"Task completed: Yes\"\n task_detail_update()\n print(f\"\\n>>> Task has been edited.\\n\\n{dashes}\")\n view_mine()\n\n # If the user chooses to change assigned user - Request assigned user and update the task\n elif edit_command == \"2\":\n with open(\"user.txt\", \"r\") as users:\n users = users.read()\n\n users_list = users.replace(\",\", \"\").replace(\"\\n\", \" \").split(\" \")\n\n while True:\n edit_detail = input(\"Assigned user: \")\n\n if edit_detail not in users_list:\n print(f\"{edit_detail} has not been registered.\\n\")\n else:\n task_details[0] = f\"Assigned to: {edit_detail}\"\n task_detail_update()\n print(f\"\\n>>> Task has been edited.\\n\\n{dashes}\")\n break\n view_mine()\n\n # If the user chooses to change the due date - Request due date and update the task\n elif edit_command == \"3\":\n edit_detail = input(\"Due date: \")\n task_details[3] = f\"Due date: {edit_detail}\"\n\n task_detail_update()\n print(f\"\\n>>> Task has been edited.\\n\\n{dashes}\")\n view_mine()\n else:\n print(f\"{edit_command} is not an option.\\n\")\n\n else:\n print(f\"{view_mine_commands} is not an option.\")\n\n # Define function \"reports\" - used to generate reports\n def reports():\n\n # Use datetime module to get the current date\n current_date = datetime.datetime.today()\n\n # Define function \"task_overview\" - used to get an overview of all the tasks\n def task_overview():\n\n # Open \"tasks.txt\" and store its contents in a list in variable \"all_tasks_list\"\n with open(\"tasks.txt\", \"r\") as tasks:\n tasks = tasks.read()\n\n all_tasks_list = tasks.split(\"\\n\")\n\n # Separate all incomplete tasks and store in in variable \"incomplete_tasks_list\" as a list\n incomplete_tasks_list = []\n for task in all_tasks_list:\n if \"Task completed: No\" in task:\n incomplete_tasks_list.append(task)\n\n # Use datetime module to check if a task is overdue - use \"overdue_task_count\" to count all overdue tasks\n overdue_task_count = 0\n for task in incomplete_tasks_list:\n details = task.split(\",\")\n edit_detail = details[3]\n date_string = edit_detail[19:]\n date = datetime.datetime.strptime(date_string, \"%d/%m/%y\")\n if current_date > date:\n overdue_task_count += 1\n\n total_num_tasks = len(all_tasks_list)\n total_num_uncompleted = len(incomplete_tasks_list)\n total_num_completed = total_num_tasks - total_num_uncompleted\n total_num_overdue = overdue_task_count\n percent_incomplete = round((100 / total_num_tasks) * total_num_uncompleted, 2)\n percent_overdue = round((100 / total_num_tasks) * total_num_overdue, 2)\n\n # Open \"task_overview.txt\" and overwrite it with all new task overview information\n with open(\"task_overview.txt\", \"w\") as blank_overview:\n blank_overview.write(f\"\"\"===== Task Overview =====\n\nTotal number of tasks: {total_num_tasks}\nCompleted tasks: {total_num_completed}\nIncomplete tasks: {total_num_uncompleted}\nIncomplete and overdue: {total_num_overdue}\nPercentage incomplete: {percent_incomplete}%\nPercentage overdue: {percent_overdue}%\"\"\")\n\n with open(\"task_overview.txt\", \"r\") as task_overview_content:\n task_overview_content = task_overview_content.read()\n\n print(f\"\\n{task_overview_content}\\n\")\n print(dashes)\n print()\n\n # Define function \"user_overview\" - used to get an overview of all the users\n def user_overview():\n with open(\"user.txt\", \"r\") as users:\n users = users.read()\n\n users_list = users.replace(\",\", \"\").replace(\"\\n\", \" \").split(\" \")\n name_list = [name for name in users_list if users_list.index(name) % 2 == 0]\n\n with open(\"tasks.txt\", \"r\") as tasks:\n tasks = tasks.read()\n all_tasks_list = tasks.split(\"\\n\")\n\n with open(\"user_overview.txt\", \"w\") as blank_overview:\n blank_overview.write(f\"\"\"===== User Overview =====\nTotal number of users: {len(name_list)}\nTotal number of tasks: {len(all_tasks_list)}\n\"\"\")\n # Use while loop and for loops to get all information about each user\n index = 0\n while index <= len(name_list) - 1:\n user_tasks = [user_tasks for user_tasks in all_tasks_list if name_list[index] in user_tasks]\n\n # Get number of completed tasks\n completed_tasks = 0\n for each_task in user_tasks:\n if \"Task completed: Yes\" in each_task:\n completed_tasks += 1\n\n # Get list of all uncompleted tasks\n uncompleted_tasks = []\n for each_task in user_tasks:\n if \"Task completed: No\" in each_task:\n uncompleted_tasks.append(each_task)\n\n # Get number of all overdue tasks\n overdue_tasks_count = 0\n for each_task in uncompleted_tasks:\n details = each_task.split(\",\")\n detail = details[3]\n date_string = detail[19:]\n date_string = datetime.datetime.strptime(date_string, \"%d/%m/%y\")\n if current_date > date_string:\n overdue_tasks_count += 1\n\n total_num_tasks = len(all_tasks_list)\n user_num_tasks = len(user_tasks)\n percent_all_tasks = round((100 / total_num_tasks) * user_num_tasks, 2)\n percent_complete = round((100 / user_num_tasks) * completed_tasks, 2)\n percent_incomplete = round((100 / user_num_tasks) * len(uncompleted_tasks), 2)\n percent_overdue = round((100 / user_num_tasks) * overdue_tasks_count, 2)\n\n # Open \"user_overview.txt\" and overwrite it with all user overview information\n with open(\"user_overview.txt\", \"a\") as blank_overview:\n blank_overview.write(f\"\"\"\n>>> {name_list[index]} <<<\nTotal number of assigned tasks: {user_num_tasks}\nTotal tasks as a percentage: {percent_all_tasks}%\nAssigned tasks completed: {percent_complete}%\nAssigned tasks incomplete: {percent_incomplete}%\nAssigned tasks overdue: {percent_overdue}%\\n\"\"\")\n\n index += 1\n\n with open(\"user_overview.txt\", \"r\") as user_overview_content:\n user_overview_content = user_overview_content.read()\n\n print(user_overview_content)\n print(f\"{dashes}\\n\")\n\n task_overview()\n\n user_overview()\n\n commands()\n\n # Define function \"stats\" - used to view task manager statistics\n def stats():\n\n # Open \"user.txt\" - Determine number of users\n with open(\"user.txt\", \"r\") as users:\n users = users.read()\n\n users_list = users.split(\"\\n\")\n num_users = len(users_list)\n print(f\"\\nTotal number of users: {num_users}\")\n\n # Open \"tasks.txt\" - Determine number of tasks\n with open(\"tasks.txt\", \"r\") as tasks:\n tasks = tasks.read()\n\n tasks_list = tasks.split(\"\\n\")\n num_tasks = len(tasks_list)\n print(f\"Total number of tasks: {num_tasks}\\n\")\n\n print(f\"{dashes}\\n\")\n\n commands()\n\n # Define function \"login\" - used to log into taskmanager\n def login():\n print(\"Please login\\n\")\n\n # In a while loop - Request username and password\n # If username or password is not in \"user.txt\" - Request username and password and again\n # If username and password is correct - allow user to login\n entry = False\n while not entry:\n\n with open(\"user.txt\", \"r\") as users:\n users = users.read()\n\n users_list = users.replace(\",\", \"\").replace(\"\\n\", \" \").split(\" \")\n\n username = input(\"Username: \")\n password = input(\"Password: \")\n\n if username not in users_list or password != users_list[users_list.index(username) + 1]:\n print(\"Incorrect username or password.\\n\")\n else:\n print(f\"\\nWelcome back {username}!\\n\")\n username_stored.append(username)\n print(f\"{dashes}\\n\")\n entry = True\n\n commands()\n\n login()\n\n\nmain_loop()\n","sub_path":"task_manager.py","file_name":"task_manager.py","file_ext":"py","file_size_in_byte":19034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"145090584","text":"def minion_game(string):\r\n vowel='AEIOU' #initializng the vowels\r\n kev=0\r\n stu=0 \r\n for i in range (len(string)): #running loop on whole String\r\n if s[i] in vowel: #if starting of the strng is a vowel\r\n kev=kev+(len(string)-i) #total number of strings that can be formed with s[i] as strt vowel\r\n else:\r\n stu=stu+(len(string)-i) #total number of consonants starting string\r\n \r\n if(kev>stu):\r\n print(\"Kevin\",kev) #if vowel count is more than the consonant count\r\n elif(kev>> split_word_into_seeds_with_length_array('356', 'migoro', [0, 1, 2, 3, 3, 2, 1])\n [set(), set(), set(), {'mig'}, set(), {'or'}, {'o'}]\n \"\"\"\n list_of_elem_v = list(v_elem)\n index_list = list(map(int, list_of_elem_v))\n seeds = prepare_initial_seeds(len(length_array))\n local_word = w_elem\n for index in index_list:\n word = local_word[ : length_array[index]]\n seeds[index].add(word)\n local_word = local_word[length_array[index] : ]\n return seeds\n\ndef verify(goro_awase_seeds, v_elem):\n \"\"\"\n >>> v = ['356', '461', '2', '12']\n >>> w = ['migoro', 'yoroi', 'ni', 'ini']\n >>> goro_awase_seeds = get_goro_awase_seeds(v, w, 6)\n >>> verify(goro_awase_seeds, v[0])\n 'migoro'\n >>> verify(goro_awase_seeds, v[1])\n 'yoroi'\n >>> verify(goro_awase_seeds, v[2])\n 'ni'\n >>> verify(goro_awase_seeds, v[3])\n 'ini'\n >>>\n >>> v = ['12211', '2121', '222221']\n >>> w = ['abcaaaaabcabc', 'aaabcaaabc', 'aaaaaaaaaaabc']\n >>> goro_awase_seeds = get_goro_awase_seeds(v, w, 2)\n >>> verify(goro_awase_seeds, v[0])\n 'abcaaaaabcabc'\n >>> verify(goro_awase_seeds, v[1])\n 'aaabcaaabc'\n >>> verify(goro_awase_seeds, v[2])\n 'aaaaaaaaaaabc'\n \"\"\"\n list_of_elem_v = list(v_elem)\n index_list = list(map(int, list_of_elem_v))\n result = functools.reduce(lambda x, y: x + y, [goro_awase_seeds[i - 1] for i in index_list])\n return result\n \nif __name__ == '__main__':\n solve()\n import doctest\n doctest.testmod()\n","sub_path":"atcoder/ABC/ABC031/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":3672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"504278372","text":"# =============================================================================\n# Dijkstra's shortest distance algorithm\n# Given a directed graph G=(V,E) and non-negative edge distance for all e in E, compute the \n# shortest distance from one given node to all nodes in G in quasi-linear time. \n# =============================================================================\n#%%\nimport heapdict #use library heap\n\n#Input: adjacency list of graph G and some node k\n#Output: shortest distance from node k to all other nodes (distance=999999 if not accessible)\n#Time complexity: O((m+n)logn), m=|E|, n=|V|\ndef Dijkstra(G,k):\n n = len(G)\n path = [0 for i in range(n)]\n scanned = [False for i in range(n)] #recording nodes scanned\n H = heapdict.heapdict() #initialize heap\n for i in range(n): #set key for each node\n if i==k:\n H[i] = 0 #starting node k has distance 0\n else:\n H[i] = 999999 #set key for other nodes temporarily as inaccessible\n while H.__len__()>0:\n node, path[node-1] = H.popitem() #get node with smallest key\n scanned[node-1] = True #set node as scanned\n nhead = len(G[node-1]['head'])\n for i in range(nhead): #update keys for all head i from node\n oldkey = H.get(G[node-1]['head'][i],'none')\n if oldkey!='none': #if head i in H, update key\n H[G[node-1]['head'][i]] = min(oldkey, path[node-1] + G[node-1]['dist'][i])\n return path\n\n\n\n# =============================================================================\n#%% function to read example graph data (in examples/)\n\n#file contains a directed graph in adjacency list representation, sorted by node index\n#e.g. a line '1 45,493 62,98' means node 1 is connected to node 45 with distance=493 inbetween \n#and to node 62 with distance=98 \nimport re\ndef loadGraph(path):\n G = []\n idx = 0\n with open(path) as file:\n for line in file:\n values = [int(n) for n in re.split('\\t|,|\\n',line) if n] #split string\n G.append({'node':values[0], 'head':[], 'dist':[]}) #append dict for each node\n if len(values)>1: #if pointing to other nodes\n G[idx]['head'] = values[1::2] #heads that node is pointing to\n G[idx]['dist'] = values[2::2] #distance from node to heads\n idx+=1\n return G #return list of dictionaries, one for each node\n\n\n#%% example\n\nG = loadGraph('examples/Dijkstra.txt') #file contains graph with 200 nodes + 1200 edges\nd = Dijkstra(G,1) #list of distance from node 1 to node v for all v in V\n\n","sub_path":"GreedyAlgorithms/Dijkstra.py","file_name":"Dijkstra.py","file_ext":"py","file_size_in_byte":2606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"156115119","text":"#-*- coding:utf-8 -*-\n__author__ = \"Ink.white\"\n\nimport urllib.request\nimport re\n\nobj = urllib.request.urlopen(\"https://read.douban.com/provider/all\").read().decode()\npat = '
(.*?)
'\nrst = re.compile(pat).findall(obj)\n\nprint(rst)\nwith open(\"info.py\",\"w\") as f:\n for i in range(0,len(rst)):\n f.write(rst[i])\n","sub_path":"Python3网络爬虫视频练习/爬虫_豆瓣阅读出版社信息.py","file_name":"爬虫_豆瓣阅读出版社信息.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"558869411","text":"import asyncio\n\nfrom asgiref.sync import sync_to_async\nfrom django.core.management.base import BaseCommand\n\nfrom coctailsapi.models import Drink, Ingredient, Measure\nfrom coctailsapi.helpers.similar_drinks_manager import SimilarDrinksManager\nfrom coctailsapi.helpers.thecoctaildb_api import TheCoctailDBAPI\n\n\nclass Command(BaseCommand):\n help = 'Loads and updates data from TheCoctailDB into the local database'\n\n def __update_ingredients(self, ingredients):\n ingredients_db = {}\n for ingredient_name, ingredient in ingredients.items():\n defaults = {\n 'is_alcoholic': True if ingredient['strAlcohol'] == 'Yes' else False,\n 'description': ingredient['strDescription'] if ingredient['strDescription'] else '',\n }\n ingredient_db, _ = Ingredient.objects.update_or_create(name=ingredient['strIngredient'], defaults=defaults)\n ingredients_db[ingredient_name] = ingredient_db\n return ingredients_db\n\n def __update_drinks(self, drinks, ingredients_db):\n for drink in drinks:\n defaults = {\n 'is_alcoholic': True if drink['strAlcoholic'] == 'Alcoholic' else False,\n 'image_url': drink['strDrinkThumb'] if drink['strDrinkThumb'] else '',\n 'instructions': drink['strInstructions'] if drink['strInstructions'] else '',\n }\n drink_db, _ = Drink.objects.update_or_create(name=drink['strDrink'], defaults=defaults)\n\n for i in range(1, 16):\n ingredient_key = 'strIngredient' + str(i)\n ingredient_name = drink[ingredient_key]\n if not ingredient_name:\n break\n\n ingredient = ingredients_db[ingredient_name]\n measure = drink['strMeasure' + str(i)] if drink['strMeasure' + str(i)] else ''\n\n Measure.objects.update_or_create(drink=drink_db, ingredient=ingredient, defaults={\n 'measure': measure\n })\n\n @sync_to_async\n def __update_db(self, ingredients, drinks):\n ingredients_db = self.__update_ingredients(ingredients)\n self.__update_drinks(drinks, ingredients_db)\n self.stdout.write('Database was updated.')\n\n SimilarDrinksManager.update()\n self.stdout.write('Similarity metrics were built.')\n\n async def __load_data(self):\n drinks_api = TheCoctailDBAPI()\n ingredients, drinks = await drinks_api.load_drinks()\n self.stdout.write('Data was downloaded from API.')\n\n await self.__update_db(ingredients, drinks)\n\n def handle(self, *args, **kwargs):\n asyncio.get_event_loop().run_until_complete(self.__load_data())\n self.stdout.write(self.style.SUCCESS('Data was successfully loaded!'))\n","sub_path":"backend/coctails/coctailsapi/management/commands/loaddata.py","file_name":"loaddata.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"9269768","text":"# coding=utf-8\nimport json\nimport re\nfrom datetime import datetime\n\nfrom lxml import etree\n\n\n__author__ = 'zephyre'\n\n\ndef poi_comments_list(body):\n \"\"\"\n 解析去哪儿POI的点评:http://travel.qunar.com/place/api/html/comments/poi/722963?sortField=1&img=false&pageSize=10&\n page=1\n \"\"\"\n data = json.loads(body)['data']\n root = etree.fromstring(data, parser=etree.HTMLParser())\n for entry in root.xpath('//ul[@id=\"comment_box\"]/li[@id]'):\n m = re.search(r'cmt_item_(\\d+)', entry.xpath('./@id')[0])\n assert m is not None\n cmt_id = int(m.group(1))\n\n title = entry.xpath('.//a[@data-beacon=\"comment_title\"]/text()')[0]\n\n tmp = entry.xpath('.//span[@class=\"total_star\"]/span[contains(@class,\"star\")]/@class')[0]\n m = re.search(r'star_(\\d)', tmp)\n assert m is not None\n rating = float(m.group(1)) / 5\n\n contents = ''.join(entry.xpath('.//div[@class=\"e_comment_content\"]')[0].itertext())\n\n comment = {'id': cmt_id, 'title': title, 'rating': rating, 'contents': contents}\n\n tmp = entry.xpath('.//div[@class=\"e_comment_add_info\"]/ul/li//a[@href and @data-beacon=\"comment_travelbook\"]')\n if tmp:\n node = tmp[0]\n note_title = node.xpath('./text()')[0]\n m = re.search(r'/gonglve/(\\d+)', node.xpath('./@href')[0])\n assert m is not None\n note_id = int(m.group(1))\n comment['note_title'] = note_title\n comment['note_id'] = note_id\n\n tmp = entry.xpath('.//div[@class=\"e_comment_add_info\"]/ul/li/text()')\n if tmp:\n comment['time'] = datetime.strptime(tmp[0], '%Y-%m-%d')\n\n yield comment\n\n pass\n\n\ndef poi_comments_max_page(body):\n \"\"\"\n 解析去哪儿POI的点评的分页:http://travel.qunar.com/place/api/html/comments/poi/722963?sortField=1&img=false&\n pageSize=10&page=1\n \"\"\"\n data = json.loads(body)['data']\n root = etree.fromstring(data, parser=etree.HTMLParser())\n page_list = set([])\n for val in root.xpath('//div[@class=\"b_paging\"]/a[@class=\"page\" and @data-url and @href]/text()'):\n m = re.match(r'\\d+', val)\n if m:\n page_list.add(int(m.group()))\n\n return max(page_list)\n","sub_path":"qunar.py","file_name":"qunar.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"161754499","text":"from math import pi, cos, sin\n\ndef distance(v):\n resultats = []\n for i in range(0, 100, 10):\n a = (pi/180)*i\n d = ((2*(v**2)) * cos(a) * sin(a))/9.8\n resultats.append(d)\n return resultats\n\ninp = float(input(\"vitesse: \"))\nreponse = distance(inp)\nfor i in range(0,10):\n print(\"Pour\", i*10,\"la réponse est:\",\n reponse[i])\n","sub_path":"labo/labo5/Q3.py","file_name":"Q3.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"643021343","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\nclass AdalineGD(object):\n\n def __init__(self, eta=0.01, n_iter=100, seed=1):\n self.eta = eta\n self.n_iter = n_iter\n self.seed = seed\n\n def fit(self, X, y):\n self.w_ = np.random.RandomState(self.seed).normal(loc=0.0, scale=1.0, size=1 + X.shape[1])\n self.cost_ = []\n for _ in range(self.n_iter):\n net_input = X.dot(self.w_[1:]) + self.w_[0]\n output = self.activation(net_input)\n errors = y - output\n self.w_[1:] += self.eta * X.T.dot(errors)\n self.w_[0] += self.eta * errors.sum()\n self.cost_.append((errors ** 2).sum() / 2.0)\n\n return self\n\n def activation(self, X):\n return X\n\n def predict(self, X):\n net_input = X.dot(self.w_[1:]) + self.w_[0]\n return np.where(net_input >= 0, 1, -1)\n\n\nplt.figure(figsize=(14, 5))\nplt.subplot(121)\ndf = pd.read_csv('data.csv')\nX = df[['0', '2']].values[:100]\nplt.scatter(X[:50, 0], X[:50, 1])\nplt.scatter(X[50:, 0], X[50:, 1])\ny = np.array([1 for t in range(50)] + [-1 for t in range(50)])\n\ni_eta = float(input('Enter the learning rate: '))\ni_n_iter = int(input('Enter the number of passes over the training dataset: '))\ni_seed = int(input('Enter the seed for the random generator: '))\n\nad_gd = AdalineGD(eta=i_eta, n_iter=i_n_iter, seed=i_seed).fit(X, y)\nrn = np.arange(X[:, 0].min(), X[:, 0].max(), 0.01)\n\n\ndef f(x): # This function represents the classification hyperplane(line)\n w = ad_gd.w_\n return (-x * w[1] - w[0]) / w[2]\n\n\nplt.plot(rn, f(rn), 'g')\nplt.xlabel('Sepal Length: cm')\nplt.ylabel('Petal length: cm')\nplt.subplot(122)\nplt.xlabel('Epoch Number')\nplt.ylabel('Logarithm(10) of Cost Function')\nplt.plot(range(1, len(ad_gd.cost_) + 1), np.log10(ad_gd.cost_))\nplt.show()\n","sub_path":"ML_Practice/adaline_gd.py","file_name":"adaline_gd.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"586775102","text":"from flask_restful import Resource\nfrom models.image import ImageModel\nfrom flask_jwt_extended import jwt_required, jwt_optional, get_jwt_identity\nfrom sqlalchemy.exc import IntegrityError\n\n\nclass Image(Resource):\n\n @classmethod\n def get(cls, name):\n image = ImageModel.find_by_name(name)\n if not image:\n return {\"message\": \"Image not found.\"}, 404\n return image.json(), 200\n\n @classmethod\n @jwt_required\n def post(cls, name):\n image = ImageModel.find_by_name(name)\n if image:\n return {\"message\": \"An image with name '{}' already exists.\".format(name)}, 400\n\n image = ImageModel(name)\n try:\n image.save_to_db()\n except IntegrityError as e:\n return {\"database_exception\": str(e)}, 400\n except:\n return {\"message\": \"Internal error occurred during insertion.\"}, 500\n\n return image.json(), 201\n\n @classmethod\n @jwt_required\n def put(cls, name):\n image = ImageModel.find_by_name(name)\n if not image:\n image = ImageModel(name)\n else:\n image.name = name\n\n try:\n image.save_to_db()\n except IntegrityError as e:\n return {\"database_exception\": str(e)}, 400\n except:\n return {\"message\": \"Internal error occurred during the update.\"}, 500\n\n return image.json(), 201\n\n @classmethod\n @jwt_required\n def delete(cls, name):\n image = ImageModel.find_by_name(name)\n\n if not image:\n return {\"message\": \"Image not found\"}, 404\n \n try:\n image.delete_from_db()\n except IntegrityError as e:\n return {\"database_exception\": str(e)}, 400\n except Exception as e:\n return {\"message\": \"Internal error occurred during deletion.\"+str(e)}, 500\n \n return {\"message\": \"Image deleted from database.\"}, 200\n\n\nclass ImageList(Resource):\n @classmethod\n def get(cls):\n return {\"images\": [image.json() for image in ImageModel.find_all()]}, 200\n","sub_path":"resources/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"248040626","text":"#!/usr/bin/env python\n\nimport io\nimport os\nimport re\nimport subprocess\nimport textwrap\nimport unittest\n\nimport quarg\n\n# Allow child processes to import quarg\nos.environ['PYTHONPATH'] = \"..:\" + os.getenv('PYTHONPATH', '')\n\n# Find the tests directory (if the current directory, make this explicit)\ntestdir = os.path.dirname(__file__) or '.'\nscriptdir = os.path.join(testdir, \"test_scripts\")\n\ndef runnable_script(scriptname):\n \"Return a function that calls the name script as a subprocess.\"\n def run(*cmd, **kwargs):\n expect_error = kwargs.pop('expect_error', False)\n try:\n output = subprocess.check_output((os.path.join(scriptdir, scriptname),) + cmd,\n stderr=subprocess.STDOUT)\n if expect_error:\n raise Exception(\"Command {} unexpectedly succeeded\".format(repr(cmd)))\n else:\n return output.decode('utf-8')\n except subprocess.CalledProcessError as e:\n if not expect_error:\n raise e\n else:\n return e.output.decode('utf-8')\n return run\n\nclass TestScriptRunners(unittest.TestCase):\n\n def test_single_function(self):\n \"\"\"\n Test that quarg correctly exposes a single top-level function.\n \"\"\"\n script = runnable_script('single_function')\n self.assertTrue(re.search(r'^usage:', script(expect_error=True)))\n self.assertTrue(re.search(r'^usage:', script('-h')))\n self.assertEqual(script('1', '-y', '2').strip(), '3')\n\n def test_suite(self):\n \"\"\"\n Test that quarg correctly exposes multiple top-level functions as commands.\n \"\"\"\n script = runnable_script('suite')\n self.assertTrue(re.search(r'^usage:', script(expect_error=True)))\n self.assertTrue(re.search(r'^usage:', script('-h')))\n self.assertEqual(script('sum', '1', '-y', '2').strip(), '3')\n\n def test_command_decorator(self):\n \"\"\"\n Test that quarg correctly exposes a single decorated top-level function.\n \"\"\"\n script = runnable_script('command_decorator')\n self.assertTrue(re.search(r'^usage:', script(expect_error=True)))\n self.assertTrue(re.search(r'^usage:', script('-h')))\n self.assertEqual(script('sum', '1', '-y', '2').strip(), '3')\n self.assertTrue(re.search(r'{prod,sum}', script('div', '1', '-y', '2', expect_error=True)))\n\nclass MockParser:\n \"\"\"\n A mock parser, allowing tests to examine the changes.\n \"\"\"\n def __init__(self, name = None, help = None):\n self.name = name\n self.help = help\n self.description = None\n self.arguments = {}\n\n def add_argument(self, *names, **params):\n for name in names:\n self.arguments[name] = params\n\nclass TestFunctionProcessing(unittest.TestCase):\n\n def test_basic_arguments(self):\n def cmd(a, b, c=None, d=None):\n \"A test function\"\n pass\n\n p = quarg.make_parser(cmd, MockParser)\n self.assertEqual(p.name, \"cmd\")\n self.assertEqual(p.description, \"A test function\")\n self.assertEqual(set(p.arguments.keys()), set(['a', 'b', '-c', '-d']))\n self.assertNotIn('default', p.arguments['a'])\n self.assertEqual(p.arguments['-c']['default'], None)\n\n def test_types(self):\n def cmd(x=1, y=\"foo\", z=None): pass\n p = quarg.make_parser(cmd, MockParser)\n self.assertEqual(p.arguments['-x']['type'], int)\n self.assertEqual(p.arguments['-y']['type'], str)\n self.assertNotIn('type', p.arguments['-z'])\n\n def test_arg_decorator(self):\n\n @quarg.arg.x(type=int)\n @quarg.arg.y(type=\"string\")\n @quarg.arg.y(help=\"Some help\")\n @quarg.arg.z(action=\"store_const\", const=\"Z\")\n def cmd(x,y,z): pass\n\n p = quarg.make_parser(cmd, MockParser)\n\n # Single arg decorator\n self.assertEqual(p.arguments['x']['type'], int)\n\n # Multiple arg decorator\n self.assertEqual(p.arguments['y']['type'], 'string')\n self.assertEqual(p.arguments['y']['help'], 'Some help')\n\n # Single arg decorator with multiple values\n self.assertEqual(p.arguments['z']['action'], 'store_const')\n self.assertEqual(p.arguments['z']['const'], 'Z')\n\ndef _pds(docstring):\n \"\"\"A utility to dedent and parse a docstring\"\"\"\n return quarg.parse_docstring(textwrap.dedent(docstring))\n\nclass TestParseDocString(unittest.TestCase):\n\n def test_multiline_arg_descriptions(self):\n help, desc, arghelp = _pds(\"\"\"\n help\n\n desc1\n desc2\n\n --x: x1\n --y: y1\n y2\n --z: z1\n \"\"\")\n self.assertEqual(help, \"help\")\n self.assertEqual(desc, \"help\\n\\ndesc1\\ndesc2\\n\")\n self.assertEqual(arghelp[\"x\"], \"x1\")\n self.assertEqual(arghelp[\"y\"], \"y1 y2\")\n self.assertEqual(arghelp[\"z\"], \"z1\")\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"589475143","text":"__author__ = 'Cynric'\n\n\ndef OPT_Prob(i, j, n):\n if i == n:\n return 1\n if j == n:\n return 0\n else:\n return 0.5 * OPT_Prob(i + 1, j, n) + 0.5 * OPT_Prob(i, j + 1, n)\n\n\ndef OPT_Card(i, j, v):\n if i == (j - 1):\n print\n i\n return max(v[i], v[j])\n else:\n return max(\n v[i] + min(OPT_Card(i + 2, j, v), OPT_Card(i + 1, j - 1, v)),\n v[j] + min(OPT_Card(i, j - 2, v), OPT_Card(i + 1, j - 1, v))\n )\n\n\ndef main():\n # print OPT_Prob(4.0, 2.0, 5.0)\n v = [5, 6, 10, 8]\n print\n OPT_Card(0, 3, v)\n return 0\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"dynamic programming/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"177424674","text":"import matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\nimport numpy as np\nimport os\nfrom pylab import *\nfrom matplotlib import ticker\nfrom matplotlib.ticker import ScalarFormatter\nsformatter=ScalarFormatter(useOffset=True,useMathText=True)\nsformatter.set_scientific(True)\nsformatter.set_powerlimits((-2,3))\n\n#plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))\n\nfont = {'family' : 'serif',\n 'weight' : 'normal',\n 'size' : 14}\nplt.rc('font', **font)\nplt.rc('text', usetex=False)\nplt.figure(figsize=(6,12))\nfig = plt.figure(1)\n\nOmega=25\nMydata25=np.loadtxt('data/sigmaeta00.3_Omega25.dat',skiprows=1,unpack=True)\nroots25=Mydata25[1]\npbar25=Mydata25[5]\nsigma2p25=Mydata25[6]\nSsigmap25=Mydata25[7]\nKsigma2p25=Mydata25[8]\nqbar25=Mydata25[9]\nsigma2q25=Mydata25[10]\nSsigmaq25=Mydata25[11]\nKsigma2q25=Mydata25[12]\nkbar25=Mydata25[17]\nsigma2k25=Mydata25[18]\nSsigmak25=Mydata25[19]\nKsigma2k25=Mydata25[20]\npibar25=Mydata25[21]\nsigma2pi25=Mydata25[22]\nSsigmapi25=Mydata25[23]\nKsigma2pi25=Mydata25[24]\nSkellampi25=sigma2pi25/(pibar25*Omega)\nSkellamk25=sigma2k25/(kbar25*Omega)\nSkellamp25=sigma2p25/(pbar25*Omega)\nSkellamq25=sigma2q25/(qbar25*Omega)\n\n\nOmega=50\nMydata50=np.loadtxt('data/sigmaeta00.3_Omega50.dat',skiprows=1,unpack=True)\nroots50=Mydata50[1]\npbar50=Mydata50[5]\nsigma2p50=Mydata50[6]\nSsigmap50=Mydata50[7]\nKsigma2p50=Mydata50[8]\nqbar50=Mydata50[9]\nsigma2q50=Mydata50[10]\nSsigmaq50=Mydata50[11]\nKsigma2q50=Mydata50[12]\nkbar50=Mydata50[17]\nsigma2k50=Mydata50[18]\nSsigmak50=Mydata50[19]\nKsigma2k50=Mydata50[20]\npibar50=Mydata50[21]\nsigma2pi50=Mydata50[22]\nSsigmapi50=Mydata50[23]\nKsigma2pi50=Mydata50[24]\nSkellampi50=sigma2pi50/(pibar50*Omega)\nSkellamk50=sigma2k50/(kbar50*Omega)\nSkellamp50=sigma2p50/(pbar50*Omega)\nSkellamq50=sigma2q50/(qbar50*Omega)\n\nOmega=100\nMydata100=np.loadtxt('data/sigmaeta00.3_Omega100.dat',skiprows=1,unpack=True)\nroots100=Mydata100[1]\npbar100=Mydata100[5]\nsigma2p100=Mydata100[6]\nSsigmap100=Mydata100[7]\nKsigma2p100=Mydata100[8]\nqbar100=Mydata100[9]\nsigma2q100=Mydata100[10]\nSsigmaq100=Mydata100[11]\nKsigma2q100=Mydata100[12]\nkbar100=Mydata100[17]\nsigma2k100=Mydata100[18]\nSsigmak100=Mydata100[19]\nKsigma2k100=Mydata100[20]\npibar100=Mydata100[21]\nsigma2pi100=Mydata100[22]\nSsigmapi100=Mydata100[23]\nKsigma2pi100=Mydata100[24]\nSkellampi100=sigma2pi100/(pibar100*Omega)\nSkellamk100=sigma2k100/(kbar100*Omega)\nSkellamp100=sigma2p100/(pbar100*Omega)\nSkellamq100=sigma2q100/(qbar100*Omega)\n\nOmega=200\nMydata200=np.loadtxt('data/sigmaeta00.3_Omega200.dat',skiprows=1,unpack=True)\nroots200=Mydata200[1]\npbar200=Mydata200[5]\nsigma2p200=Mydata200[6]\nSsigmap200=Mydata200[7]\nKsigma2p200=Mydata200[8]\nqbar200=Mydata200[9]\nsigma2q200=Mydata200[10]\nSsigmaq200=Mydata200[11]\nKsigma2q200=Mydata200[12]\nkbar200=Mydata200[17]\nsigma2k200=Mydata200[18]\nSsigmak200=Mydata200[19]\nKsigma2k200=Mydata200[20]\npibar200=Mydata200[21]\nsigma2pi200=Mydata200[22]\nSsigmapi200=Mydata200[23]\nKsigma2pi200=Mydata200[24]\nSkellampi200=sigma2pi200/(pibar200*Omega)\nSkellamk200=sigma2k200/(kbar200*Omega)\nSkellamp200=sigma2p200/(pbar200*Omega)\nSkellamq200=sigma2q200/(qbar200*Omega)\n\nOmega=400\nMydata400=np.loadtxt('data/sigmaeta00.3_Omega400.dat',skiprows=1,unpack=True)\nroots400=Mydata400[1]\npbar400=Mydata400[5]\nsigma2p400=Mydata400[6]\nSsigmap400=Mydata400[7]\nKsigma2p400=Mydata400[8]\nqbar400=Mydata400[9]\nsigma2q400=Mydata400[10]\nSsigmaq400=Mydata400[11]\nKsigma2q400=Mydata400[12]\nkbar400=Mydata400[17]\nsigma2k400=Mydata400[18]\nSsigmak400=Mydata400[19]\nKsigma2k400=Mydata400[20]\npibar400=Mydata400[21]\nsigma2pi400=Mydata400[22]\nSsigmapi400=Mydata400[23]\nKsigma2pi400=Mydata400[24]\nSkellampi400=sigma2pi400/(pibar400*Omega)\nSkellamk400=sigma2k400/(kbar400*Omega)\nSkellamp400=sigma2p400/(pbar400*Omega)\nSkellamq400=sigma2q400/(qbar400*Omega)\n\n#stardata = np.loadtxt('data/starmoments_netp.txt',skiprows=1,unpack=True)\n#roots_star=stardata[0]\n#Ksigma2=stardata[4]\n#Kerror=sqrt(stardata[5]*stardata[5]+stardata[6]*stardata[6])\n\nstardata = np.loadtxt('data/star_netprotons_c1c2c3c4.txt',unpack=False,skiprows=1)\nroots_star=stardata[0]\n\nc1_protons_star=stardata[1]\nstat1=stardata[2]\nsys1=stardata[3]\nc1_error_star=sqrt(stat1*stat1+sys1*sys1)\nc1_relerror_star=c1_error_star/c1_protons_star\n\nc2_protons_star=stardata[4]\nstat2=stardata[5]\nsys2=stardata[6]\nc2_error_star=sqrt(stat2*stat2+sys2*sys2)\nc2_relerror_star=c2_error_star/c2_protons_star\n\nc3_protons_star=stardata[7]\nstat3=stardata[8]\nsys3=stardata[9]\nc3_error_star=sqrt(stat3*stat3+sys3*sys3)\nc3_relerror_star=c3_error_star/c3_protons_star\n\nc4_protons_star=stardata[10]\nstat4=stardata[11]\nsys4=stardata[12]\nc4_error_star=sqrt(stat4*stat4+sys4*sys4)\nc4_relerror_star=c4_error_star/c4_protons_star\n\nc2c1_protons_star=c1_protons_star/c2_protons_star\nc2c1_protons_error_star=c2c1_protons_star*sqrt(c1_relerror_star*c1_relerror_star+c2_relerror_star*c2_relerror_star)\n\nc3c1_protons_star=c3_protons_star/c1_protons_star\nc3c1_protons_error_star=c3c1_protons_star*sqrt(c1_relerror_star*c1_relerror_star+c3_relerror_star*c3_relerror_star)\n\nc4c2_protons_star=c4_protons_star/c2_protons_star\nc4c2_protons_error_star=c4c2_protons_star*sqrt(c2_relerror_star*c2_relerror_star+c4_relerror_star*c4_relerror_star)\n\nc3c2_protons_star=c3_protons_star/c2_protons_star\nc3c2_protons_error_star=c3c2_protons_star*sqrt(c2_relerror_star*c2_relerror_star+c3_relerror_star*c3_relerror_star)\n\n#################################################################\n######## LOWER PANEL protons\nax = fig.add_axes([0.17,0.06,0.82,0.31])\n\n#plt.plot(roots,Ssigmap*Skellamp,linestyle='-',linewidth=2,color='r',markersize=8, marker='s', markerfacecolor=None, markeredgecolor=None,label='ETA=0.3: $C_3/C_1$')\nplt.plot(roots25,Ksigma2p25,linestyle='--',linewidth=2,color='r',markersize=10, marker='s', markerfacecolor='r', markeredgecolor='r',label='$\\Omega=25$')\nplt.plot(roots50,Ksigma2p50,linestyle='-',linewidth=2,color='k',markersize=10, marker='s', markerfacecolor='k', markeredgecolor='k',label='$\\Omega=50$')\nplt.plot(roots100,Ksigma2p100,linestyle=(0, (3, 10, 1, 10)),linewidth=2,color='g',markersize=10, marker='s', markerfacecolor='g', markeredgecolor='g',label='$\\Omega=100$')\nplt.plot(roots200,Ksigma2p200,linestyle=':',linewidth=2,color='b',markersize=10, marker='s', markerfacecolor='b', markeredgecolor='b',label='$\\Omega=200$')\nplt.plot(roots400,Ksigma2p400,linestyle=(0, (3, 1, 1, 1, 1, 1)),linewidth=2,color='cyan',markersize=10, marker='s', markerfacecolor='cyan', markeredgecolor='cyan',label='$\\Omega=400$')\nplt.errorbar(roots_star,c4c2_protons_star,c4c2_protons_error_star,linestyle=' ',linewidth=2,color='purple',markersize=11, marker='*', markerfacecolor=None, markeredgecolor=None,label='STAR\\n(preliminary)')\n\nax.tick_params(axis='both', which='major', labelsize=16)\nax.set_xticks(np.arange(0,250,50), minor=False)\nax.set_xticklabels(np.arange(0,250,50), minor=False, family='serif',fontsize=\"14\")\nax.set_xticks(np.arange(0,250,25), minor=True)\nax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%d'))\nax.xaxis.set_major_formatter(sformatter)\nplt.xlim(0,210)\n\nax.set_yticks(np.arange(-1,4,0.5), minor=False)\nax.set_yticklabels(np.arange(-1,4,0.5), minor=False, family='serif',fontsize=\"14\")\nax.set_yticks(np.arange(-1,4,0.25), minor=True)\nplt.ylim(0,3.15)\nax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1f'))\nax.yaxis.set_major_formatter(sformatter)\n\nax.legend(loc=(0.4,0.3),fontsize=18);\n\nplt.xlabel('$\\sqrt{s}_{NN}$ (GeV)',fontsize=24 , weight='normal')\n#plt.ylabel('$K\\sigma^2=C_4/C_2$', fontsize=24, weight='normal')\ntext(195,0.1,'(i) net protons',fontsize=22,ha='right')\n\n######## Middle Panel kaons\nax = fig.add_axes([0.17,0.37,0.82,0.31])\n\nstardata = np.loadtxt('data/starmoments_netk.txt',skiprows=1,unpack=True)\nroots_star=stardata[0]\nKsigma2=stardata[4]\nKerror=sqrt(stardata[5]*stardata[5]+stardata[6]*stardata[6])\n\n#plt.plot(roots,Ssigmap*Skellamp,linestyle='-',linewidth=2,color='r',markersize=8, marker='s', markerfacecolor=None, markeredgecolor=None,label='ETA=0.3: $C_3/C_1$')\nplt.plot(roots25,Ksigma2k25,linestyle='--',linewidth=2,color='r',markersize=10, marker='s', markerfacecolor='r', markeredgecolor='r',label='$\\Omega=25$')\nplt.plot(roots50,Ksigma2k50,linestyle='-',linewidth=2,color='k',markersize=10, marker='s', markerfacecolor='k', markeredgecolor='k',label='$\\Omega=50$')\nplt.plot(roots100,Ksigma2k100,linestyle=(0, (3, 10, 1, 10)),linewidth=2,color='g',markersize=10, marker='s', markerfacecolor='g', markeredgecolor='g',label='$\\Omega=100$')\nplt.plot(roots200,Ksigma2k200,linestyle=':',linewidth=2,color='b',markersize=10, marker='s', markerfacecolor='b', markeredgecolor='b',label='$\\Omega=200$')\nplt.plot(roots400,Ksigma2k400,linestyle=(0, (3, 1, 1, 1, 1, 1)),linewidth=2,color='cyan',markersize=10, marker='s', markerfacecolor='cyan', markeredgecolor='cyan',label='$\\Omega=400$')\nplt.errorbar(roots_star,Ksigma2,Kerror,linestyle=' ',linewidth=2,color='purple',markersize=11, marker='*', markerfacecolor=None, markeredgecolor=None)\n\nax.tick_params(axis='both', which='major', labelsize=14)\nax.set_xticks(np.arange(0,250,50), minor=False)\nax.set_xticklabels([])\nax.set_xticks(np.arange(0,250,50), minor=True)\n#ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%d'))\n#ax.xaxis.set_major_formatter(sformatter)\nplt.xlim(0,210)\n\nax.set_yticks(np.arange(-2,2.5,0.5), minor=False)\nax.set_yticklabels(np.arange(-2,2.5,0.5), minor=False, family='serif',fontsize=\"14\")\nax.set_yticks(np.arange(-2,2.5,0.25), minor=True)\nplt.ylim(-1.5,1.7)\nax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1f'))\nax.yaxis.set_major_formatter(sformatter)\n\n#ax.legend(loc=(0.6,0.01),fontsize=18);\n\n#plt.xlabel('$\\sqrt{s}_{NN}$ (GeV)',fontsize=18 , weight='normal')\nplt.ylabel('$C_4/C_2$', fontsize=24, weight='normal')\ntext(195,-1.3,'(h) net kaons',fontsize=22,ha='right')\n\n######## Upper Panel charge\nax = fig.add_axes([0.17,0.68,0.82,0.31])\n\nstardata = np.loadtxt('data/starmoments_netq.txt',skiprows=1,unpack=True)\nroots_star=stardata[0]\nKsigma2=stardata[4]\nKerror=sqrt(stardata[5]*stardata[5]+stardata[6]*stardata[6])\n\n#plt.plot(roots,Ssigmap*Skellamp,linestyle='-',linewidth=2,color='r',markersize=8, marker='s', markerfacecolor=None, markeredgecolor=None,label='ETA=0.3: $C_3/C_1$')\nplt.plot(roots25,Ksigma2q25,linestyle='--',linewidth=2,color='r',markersize=10, marker='s', markerfacecolor='r', markeredgecolor='r')\nplt.plot(roots50,Ksigma2q50,linestyle='-',linewidth=2,color='k',markersize=10, marker='s', markerfacecolor='k', markeredgecolor='k')\nplt.plot(roots100,Ksigma2q100,linestyle=(0, (3, 10, 1, 10)),linewidth=2,color='g',markersize=10, marker='s', markerfacecolor='g', markeredgecolor='g')\nplt.plot(roots200,Ksigma2q200,linestyle=':',linewidth=2,color='b',markersize=10, marker='s', markerfacecolor='b', markeredgecolor='b')\nplt.plot(roots400,Ksigma2q400,linestyle=(0, (3, 1, 1, 1, 1, 1)),linewidth=2,color='cyan',markersize=10, marker='s', markerfacecolor='cyan', markeredgecolor='cyan')\nplt.errorbar(roots_star,Ksigma2,Kerror,linestyle=' ',linewidth=2,color='purple',markersize=11, marker='*', markerfacecolor=None, markeredgecolor=None,label='STAR\\n(preliminary)')\n\nax.tick_params(axis='both', which='major', labelsize=14)\nax.set_xticks(np.arange(0,250,50), minor=False)\nax.set_xticklabels([])\nax.set_xticks(np.arange(0,250,50), minor=True)\n#ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%d'))\n#ax.xaxis.set_major_formatter(sformatter)\nplt.xlim(0,210)\n\nax.set_yticks(np.arange(-14,14,2), minor=False)\nax.set_yticklabels(np.arange(-14,14,2), minor=False, family='serif', fontsize=\"14\")\nax.set_yticks(np.arange(-14,14,1), minor=True)\nplt.ylim(-5,5)\nax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1f'))\nax.yaxis.set_major_formatter(sformatter)\n\n#plt.xlabel('$\\sqrt{s}_{NN}$ (GeV)',fontsize=18 , weight='normal')\n#plt.ylabel('$K\\sigma^2=C_4/C_2$', fontsize=24, weight='normal')\ntext(195,-4.7,'(g) net charge',fontsize=22,ha='right')\n\n#########################################\nplt.savefig('bw_kurtosis_omega.pdf',format='pdf')\n#os.system('xdg-open bw_kurtosis_omega.pdf')\nos.system('open -a Preview bw_kurtosis_omega.pdf')\n\n\n\n#plt.show()\nquit()\n","sub_path":"scottrun/finalfigs/bw_kurtosis_omega.py","file_name":"bw_kurtosis_omega.py","file_ext":"py","file_size_in_byte":12073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"274738646","text":"#!/usr/bin/python3\n\"\"\"\nAll default RESTFul API actions for Place objects\n\"\"\"\nfrom api.v1.views import app_views\nfrom flask import request, abort, make_response, jsonify\nfrom models import storage\nfrom models.place import Place\nfrom models.city import City\nfrom models.user import User\n\n\n@app_views.route('/cities//places', methods=['GET'],\n strict_slashes=False)\ndef get_all_places(city_id):\n \"\"\" Retrieves a list of all place objects based on the place id\"\"\"\n all_city_places = []\n city_obj = storage.get(City, city_id)\n\n if city_obj is None:\n abort(404)\n\n else:\n for place in city_obj.places:\n all_city_places.append(place.to_dict())\n\n return jsonify(all_city_places)\n\n\n@app_views.route('/places/', methods=['GET'],\n strict_slashes=False)\ndef get_place(place_id):\n \"\"\" Retrieve a place object based on the place id \"\"\"\n place_obj = storage.get(Place, place_id)\n\n if place_obj is None:\n abort(404)\n else:\n place_obj = place_obj.to_dict()\n return jsonify(place_obj)\n\n\n@app_views.route('/places/', methods=['DELETE'],\n strict_slashes=False)\ndef delete_place(place_id):\n \"\"\" Deletes a place object based on the place id \"\"\"\n place_obj = storage.get(Place, place_id)\n\n if place_obj is None:\n abort(404)\n else:\n storage.delete(place_obj)\n storage.save()\n return jsonify({}), 200\n\n\n@app_views.route('/cities//places', methods=['POST'],\n strict_slashes=False)\ndef post_place(city_id):\n \"\"\" Creates a new place object \"\"\"\n attributes = request.get_json(silent=True)\n city = storage.get(City, city_id)\n\n if not attributes:\n return make_response(jsonify({\"error\": \"Not a JSON\"}), 400)\n if not attributes[\"name\"]:\n return make_response(jsonify({\"error\": \"Missing name\"}), 400)\n if not attributes[\"user_id\"]:\n return make_response(jsonify({\"error\": \"Missing user_id\"}), 400)\n if city is None:\n abort(404)\n\n user = storage.get(User, attributes[\"user_id\"])\n\n if user is None:\n abort(404)\n else:\n attributes[\"city_id\"] = city_id\n new_place = Place(**attributes)\n new_place.save()\n return jsonify(new_place.to_dict()), 201\n\n\n@app_views.route('/places/', methods=[\"PUT\"],\n strict_slashes=False)\ndef put_place(place_id):\n \"\"\" Updates a place object based on the place id \"\"\"\n new_attributes = request.get_json(silent=True)\n place_obj = storage.get(Place, place_id)\n\n if not new_attributes:\n return make_response(jsonify({\"error\": \"Not a JSON\"}), 400)\n if place_obj is None:\n abort(404)\n\n new_attributes.pop('id', None)\n new_attributes.pop('updated_at', None)\n new_attributes.pop('created_at', None)\n new_attributes.pop('user_id', None)\n new_attributes.pop('city_id', None)\n\n for key, value in new_attributes.items():\n setattr(place_obj, key, value)\n storage.save()\n return jsonify(place_obj.to_dict()), 200\n","sub_path":"api/v1/views/places.py","file_name":"places.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"306554095","text":"# Copyright 2018 VMware, Inc.\n# All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# 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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport decorator\nimport mock\nimport testtools\n\nfrom oslo_utils import uuidutils\n\nfrom octavia_lib.api.drivers import data_models\n\ncode_ok = True\n# Skip duplications between Octavia & Neutron configurations and missing\n# configuration groups\nwith mock.patch('oslo_config.cfg.ConfigOpts.import_group'),\\\n mock.patch('oslo_config.cfg.ConfigOpts.__getattr__'):\n try:\n from vmware_nsx.services.lbaas.octavia import octavia_driver as driver\n except ImportError:\n # Octavia code not found\n # this can happen as Octavia is not in the requirements yet\n code_ok = False\n\nDRIVER = 'vmware_nsx.services.lbaas.octavia.octavia_driver.NSXOctaviaDriver'\n\n\nclass TestNsxProviderDriver(testtools.TestCase):\n \"\"\"Test the NSX Octavia driver\n\n Make sure all the relevant data is translated and sent to the listener\n \"\"\"\n def setUp(self):\n super(TestNsxProviderDriver, self).setUp()\n global code_ok\n if not code_ok:\n return\n # init the NSX driver without the RPC & certificate\n with mock.patch(DRIVER + '._init_rpc_messaging'), \\\n mock.patch(DRIVER + '._init_rpc_listener'), \\\n mock.patch(DRIVER + '._init_cert_manager'):\n self.driver = driver.NSXOctaviaDriver()\n self.driver.client = mock.Mock()\n\n self.loadbalancer_id = uuidutils.generate_uuid()\n self.vip_address = '192.0.2.10'\n self.vip_network_id = uuidutils.generate_uuid()\n self.vip_port_id = uuidutils.generate_uuid()\n self.vip_subnet_id = uuidutils.generate_uuid()\n self.listener_id = uuidutils.generate_uuid()\n self.pool_id = uuidutils.generate_uuid()\n self.member_id = uuidutils.generate_uuid()\n self.member_subnet_id = uuidutils.generate_uuid()\n self.healthmonitor_id = uuidutils.generate_uuid()\n self.l7policy_id = uuidutils.generate_uuid()\n self.l7rule_id = uuidutils.generate_uuid()\n self.project_id = uuidutils.generate_uuid()\n self.default_tls_container_ref = uuidutils.generate_uuid()\n self.sni_container_ref_1 = uuidutils.generate_uuid()\n self.sni_container_ref_2 = uuidutils.generate_uuid()\n\n self.ref_member = data_models.Member(\n address='198.51.100.4',\n admin_state_up=True,\n member_id=self.member_id,\n monitor_address='203.0.113.2',\n monitor_port=66,\n name='jacket',\n pool_id=self.pool_id,\n protocol_port=99,\n subnet_id=self.member_subnet_id,\n weight=55)\n\n self.ref_healthmonitor = data_models.HealthMonitor(\n admin_state_up=False,\n delay=2,\n expected_codes=\"500\",\n healthmonitor_id=self.healthmonitor_id,\n http_method='TRACE',\n max_retries=1,\n max_retries_down=0,\n name='doc',\n pool_id=self.pool_id,\n timeout=3,\n type='PHD',\n url_path='/index.html')\n\n self.ref_pool = data_models.Pool(\n admin_state_up=True,\n description='Olympic swimming pool',\n healthmonitor=self.ref_healthmonitor,\n lb_algorithm='A_Fast_One',\n loadbalancer_id=self.loadbalancer_id,\n members=[self.ref_member],\n name='Osborn',\n pool_id=self.pool_id,\n protocol='avian',\n session_persistence={'type': 'glue'})\n\n self.ref_l7rule = data_models.L7Rule(\n admin_state_up=True,\n compare_type='store_brand',\n invert=True,\n key='board',\n l7policy_id=self.l7policy_id,\n l7rule_id=self.l7rule_id,\n type='strict',\n value='gold')\n\n self.ref_l7policy = data_models.L7Policy(\n action='packed',\n admin_state_up=False,\n description='Corporate policy',\n l7policy_id=self.l7policy_id,\n listener_id=self.listener_id,\n name='more_policy',\n position=1,\n redirect_pool_id=self.pool_id,\n redirect_url='/hr',\n rules=[self.ref_l7rule])\n\n self.ref_listener = data_models.Listener(\n admin_state_up=False,\n connection_limit=5,\n default_pool=self.ref_pool,\n default_pool_id=self.pool_id,\n default_tls_container_data='default_cert_data',\n default_tls_container_ref=self.default_tls_container_ref,\n description='The listener',\n insert_headers={'X-Forwarded-For': 'true'},\n l7policies=[self.ref_l7policy],\n listener_id=self.listener_id,\n loadbalancer_id=self.loadbalancer_id,\n name='super_listener',\n protocol='avian',\n protocol_port=42,\n sni_container_data=['sni_cert_data_1', 'sni_cert_data_2'],\n sni_container_refs=[self.sni_container_ref_1,\n self.sni_container_ref_2])\n\n self.ref_lb = data_models.LoadBalancer(\n admin_state_up=False,\n description='One great load balancer',\n flavor={'cake': 'chocolate'},\n listeners=[self.ref_listener],\n loadbalancer_id=self.loadbalancer_id,\n name='favorite_lb',\n project_id=self.project_id,\n vip_address=self.vip_address,\n vip_network_id=self.vip_network_id,\n vip_port_id=self.vip_port_id,\n vip_subnet_id=self.vip_subnet_id)\n\n # start DB mocks\n mock.patch('octavia.db.api.get_session').start()\n mock.patch(\"octavia.api.drivers.utils.db_pool_to_provider_pool\",\n return_value=self.ref_pool).start()\n\n @decorator.decorator\n def skip_no_octavia(f, *args, **kwargs):\n global code_ok\n if not code_ok:\n obj = args[0]\n return obj.skipTest('Octavia code not found')\n return f(*args, **kwargs)\n\n @skip_no_octavia\n def test_loadbalancer_create(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.loadbalancer_create(self.ref_lb)\n cast_method.assert_called_with({}, 'loadbalancer_create',\n loadbalancer=mock.ANY)\n driver_obj = cast_method.call_args[1]['loadbalancer']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n self.assertIn('admin_state_up', driver_obj)\n self.assertIn('name', driver_obj)\n self.assertIn('listeners', driver_obj)\n self.assertEqual(1, len(driver_obj['listeners']))\n self.assertEqual(self.ref_lb.vip_address,\n driver_obj['vip_address'])\n self.assertEqual(self.ref_lb.vip_network_id,\n driver_obj['vip_network_id'])\n self.assertEqual(self.ref_lb.vip_port_id,\n driver_obj['vip_port_id'])\n self.assertEqual(self.ref_lb.vip_subnet_id,\n driver_obj['vip_subnet_id'])\n\n @skip_no_octavia\n def test_loadbalancer_delete(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.loadbalancer_delete(self.ref_lb)\n cast_method.assert_called_with({}, 'loadbalancer_delete',\n cascade=False,\n loadbalancer=mock.ANY)\n driver_obj = cast_method.call_args[1]['loadbalancer']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n\n @skip_no_octavia\n def test_loadbalancer_update(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.loadbalancer_update(self.ref_lb, self.ref_lb)\n cast_method.assert_called_with({}, 'loadbalancer_update',\n old_loadbalancer=mock.ANY,\n new_loadbalancer=mock.ANY)\n driver_obj = cast_method.call_args[1]['new_loadbalancer']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n\n @skip_no_octavia\n def test_listener_create(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.listener_create(self.ref_listener)\n cast_method.assert_called_with({}, 'listener_create', cert=None,\n listener=mock.ANY)\n driver_obj = cast_method.call_args[1]['listener']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n self.assertIn('admin_state_up', driver_obj)\n self.assertIn('name', driver_obj)\n self.assertIn('loadbalancer_id', driver_obj)\n self.assertIn('loadbalancer', driver_obj)\n self.assertEqual(self.ref_listener.protocol,\n driver_obj['protocol'])\n self.assertEqual(self.ref_listener.protocol_port,\n driver_obj['protocol_port'])\n self.assertEqual(self.ref_listener.connection_limit,\n driver_obj['connection_limit'])\n self.assertIn('l7policies', driver_obj)\n #TODO(asarfaty) add after the driver is fixed\n #self.assertIn('default_tls_container_id', driver_obj)\n\n @skip_no_octavia\n def test_listener_delete(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.listener_delete(self.ref_listener)\n cast_method.assert_called_with({}, 'listener_delete',\n listener=mock.ANY)\n driver_obj = cast_method.call_args[1]['listener']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n\n @skip_no_octavia\n def test_listener_update(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.listener_update(self.ref_listener, self.ref_listener)\n cast_method.assert_called_with({}, 'listener_update', cert=None,\n old_listener=mock.ANY,\n new_listener=mock.ANY)\n driver_obj = cast_method.call_args[1]['new_listener']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n\n @skip_no_octavia\n def test_pool_create(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.pool_create(self.ref_pool)\n cast_method.assert_called_with({}, 'pool_create', pool=mock.ANY)\n driver_obj = cast_method.call_args[1]['pool']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n self.assertIn('admin_state_up', driver_obj)\n self.assertIn('name', driver_obj)\n self.assertIn('loadbalancer_id', driver_obj)\n self.assertIn('listener', driver_obj)\n self.assertIn('listeners', driver_obj)\n self.assertEqual(self.ref_pool.lb_algorithm,\n driver_obj['lb_algorithm'])\n self.assertEqual(self.ref_pool.session_persistence,\n driver_obj['session_persistence'])\n self.assertIn('members', driver_obj)\n\n @skip_no_octavia\n def test_pool_delete(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.pool_delete(self.ref_pool)\n cast_method.assert_called_with({}, 'pool_delete', pool=mock.ANY)\n driver_obj = cast_method.call_args[1]['pool']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n\n @skip_no_octavia\n def test_pool_update(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.pool_update(self.ref_pool, self.ref_pool)\n cast_method.assert_called_with({}, 'pool_update',\n old_pool=mock.ANY,\n new_pool=mock.ANY)\n driver_obj = cast_method.call_args[1]['new_pool']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n\n @skip_no_octavia\n def test_member_create(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.member_create(self.ref_member)\n cast_method.assert_called_with({}, 'member_create',\n member=mock.ANY)\n driver_obj = cast_method.call_args[1]['member']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n self.assertIn('admin_state_up', driver_obj)\n self.assertIn('name', driver_obj)\n self.assertEqual(self.pool_id, driver_obj['pool_id'])\n self.assertIn('pool', driver_obj)\n self.assertIn('loadbalancer', driver_obj['pool'])\n #TODO(asarfaty) add when the driver is fixed\n #self.assertIn('listener', driver_obj['pool'])\n self.assertEqual(self.ref_member.subnet_id,\n driver_obj['subnet_id'])\n self.assertEqual(self.ref_member.address,\n driver_obj['address'])\n self.assertEqual(self.ref_member.protocol_port,\n driver_obj['protocol_port'])\n self.assertEqual(self.ref_member.weight,\n driver_obj['weight'])\n\n @skip_no_octavia\n def test_member_delete(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.member_delete(self.ref_member)\n cast_method.assert_called_with({}, 'member_delete',\n member=mock.ANY)\n driver_obj = cast_method.call_args[1]['member']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n\n @skip_no_octavia\n def test_member_update(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.member_update(self.ref_member, self.ref_member)\n cast_method.assert_called_with({}, 'member_update',\n old_member=mock.ANY,\n new_member=mock.ANY)\n driver_obj = cast_method.call_args[1]['old_member']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n\n @skip_no_octavia\n def test_health_monitor_create(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.health_monitor_create(self.ref_healthmonitor)\n cast_method.assert_called_with({}, 'healthmonitor_create',\n healthmonitor=mock.ANY)\n driver_obj = cast_method.call_args[1]['healthmonitor']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n self.assertIn('admin_state_up', driver_obj)\n self.assertIn('name', driver_obj)\n self.assertEqual(self.ref_healthmonitor.type,\n driver_obj['type'])\n self.assertEqual(self.ref_healthmonitor.url_path,\n driver_obj['url_path'])\n self.assertEqual(self.ref_healthmonitor.delay,\n driver_obj['delay'])\n self.assertEqual(self.ref_healthmonitor.timeout,\n driver_obj['timeout'])\n self.assertEqual(self.ref_healthmonitor.max_retries,\n driver_obj['max_retries'])\n self.assertEqual(self.ref_healthmonitor.http_method,\n driver_obj['http_method'])\n self.assertIn('pool', driver_obj)\n self.assertEqual(self.pool_id,\n driver_obj['pool']['id'])\n self.assertEqual(self.loadbalancer_id,\n driver_obj['pool']['loadbalancer_id'])\n\n @skip_no_octavia\n def test_health_monitor_delete(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.health_monitor_delete(self.ref_healthmonitor)\n cast_method.assert_called_with({}, 'healthmonitor_delete',\n healthmonitor=mock.ANY)\n driver_obj = cast_method.call_args[1]['healthmonitor']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n\n @skip_no_octavia\n def test_health_monitor_update(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.health_monitor_update(self.ref_healthmonitor,\n self.ref_healthmonitor)\n cast_method.assert_called_with({}, 'healthmonitor_update',\n old_healthmonitor=mock.ANY,\n new_healthmonitor=mock.ANY)\n driver_obj = cast_method.call_args[1]['new_healthmonitor']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n\n @skip_no_octavia\n def test_l7policy_create(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.l7policy_create(self.ref_l7policy)\n cast_method.assert_called_with({}, 'l7policy_create',\n l7policy=mock.ANY)\n driver_obj = cast_method.call_args[1]['l7policy']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n self.assertIn('admin_state_up', driver_obj)\n self.assertIn('name', driver_obj)\n self.assertIn('listener', driver_obj)\n self.assertEqual(self.listener_id, driver_obj['listener_id'])\n self.assertIn('rules', driver_obj)\n self.assertIn('position', driver_obj)\n self.assertEqual(self.ref_l7policy.action, driver_obj['action'])\n self.assertEqual(self.ref_l7policy.redirect_url,\n driver_obj['redirect_url'])\n self.assertEqual(self.ref_l7policy.redirect_pool_id,\n driver_obj['redirect_pool_id'])\n\n @skip_no_octavia\n def test_l7policy_delete(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.l7policy_delete(self.ref_l7policy)\n cast_method.assert_called_with({}, 'l7policy_delete',\n l7policy=mock.ANY)\n driver_obj = cast_method.call_args[1]['l7policy']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n\n @skip_no_octavia\n def test_l7policy_update(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.l7policy_update(self.ref_l7policy, self.ref_l7policy)\n cast_method.assert_called_with({}, 'l7policy_update',\n old_l7policy=mock.ANY,\n new_l7policy=mock.ANY)\n driver_obj = cast_method.call_args[1]['new_l7policy']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n\n @skip_no_octavia\n def test_l7rule_create(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.l7rule_create(self.ref_l7rule)\n cast_method.assert_called_with({}, 'l7rule_create',\n l7rule=mock.ANY)\n driver_obj = cast_method.call_args[1]['l7rule']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n self.assertIn('admin_state_up', driver_obj)\n self.assertIn('name', driver_obj)\n self.assertIn('policy', driver_obj)\n self.assertIn('rules', driver_obj['policy'])\n self.assertEqual(self.ref_l7rule.type, driver_obj['type'])\n self.assertEqual(self.ref_l7rule.value, driver_obj['value'])\n self.assertEqual(self.ref_l7rule.invert, driver_obj['invert'])\n\n @skip_no_octavia\n def test_l7rule_delete(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.l7rule_delete(self.ref_l7rule)\n cast_method.assert_called_with({}, 'l7rule_delete',\n l7rule=mock.ANY)\n driver_obj = cast_method.call_args[1]['l7rule']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n\n @skip_no_octavia\n def test_l7rule_update(self):\n with mock.patch.object(self.driver.client, 'cast') as cast_method:\n self.driver.l7rule_update(self.ref_l7rule, self.ref_l7rule)\n cast_method.assert_called_with({}, 'l7rule_update',\n old_l7rule=mock.ANY,\n new_l7rule=mock.ANY)\n driver_obj = cast_method.call_args[1]['new_l7rule']\n self.assertIn('id', driver_obj)\n self.assertIn('project_id', driver_obj)\n","sub_path":"vmware_nsx/tests/unit/services/lbaas/test_octavia_driver.py","file_name":"test_octavia_driver.py","file_ext":"py","file_size_in_byte":22232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"488212317","text":"# Gave a run-time ERROR but we thought it was a Time limit exceeded\n# so we switched to c++ for speed.\ndef main():\n\ti=0\n\ttestcases=int(input())\n\twhile(i 8:\n\t\t\t\tprint(\"ERROR\")\n\t\t\telse:\n\t\t\t\tsomething = \"0\" *( 8- len(d))\n\t\t\t\tprint(f+\".\"+d+something)\n\t\texcept:\n\t\t\tprint(\"ERROR\");\n\t\ti += 1\n\nmain()\n","sub_path":"Attempts During/Div 2/floating point.py","file_name":"floating point.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"87184671","text":"#!/usr/bin/python3\nimport warnings\nimport pickle\n\nimport pandas as pd\nimport numpy as np \n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn import tree\n\nimport h\n\nDATA_FOLDER = 'data/'\n\nFILE_NAMES = ['2016reg.csv', '2017reg.csv', '2018reg.csv', '2019reg.csv']\nTEST_FILES = ['2016playoffs.csv', '2017playoffs.csv', '2018playoffs.csv']\n\nFEATURES = ['elo1_pre', 'elo2_pre', 'h_Home_Scorerol', 'h_Away_Scorerol', 'Home_Scorerol', 'Away_Scorerol']\nTRAIN_COL = 'winner'\n\nHOME_PREFIX = 'h_'\nCOL_TO_GET = 'ML'\n\n\ndef get_dfs(fns):\n\tdfs = []\n\tfor fn in fns:\n\t\tfn = DATA_FOLDER + fn\n\t\tdf = pd.read_csv(fn)\n\t\tdf = df.dropna()\n\t\tdf = df.drop_duplicates()\n\t\tdfs.append(df)\n\treturn dfs\n\n\nclass Run:\n\tdef __init__(self):\n\t\tdfs = get_dfs(FILE_NAMES)\n\t\tdf = pd.concat(dfs, sort=True)\n\n\t\tx = df[FEATURES]\n\t\ty = df[TRAIN_COL]\n\n\t\tparam_dist = {'n_estimators': np.arange(1, 50),\n\t\t 'learning_rate': np.arange(1, 10)/10,\n\t\t 'max_depth': np.arange(1, 3),\n\t\t 'random_state': np.arange(0, 10)}\n\n\t\tclfgtb = GradientBoostingClassifier()\n\t\tclfgtb = RandomizedSearchCV(clfgtb, param_dist, cv=35)\n\n\t\tself.clfgtb = clfgtb.fit(x, y)\n\n\t\ttest_dfs = get_dfs(TEST_FILES)\n\t\ttest_df = pd.concat(test_dfs, sort=True)\n\n\t\tx_test = test_df[FEATURES]\n\t\ty_test = test_df[TRAIN_COL]\n\n\t\tprint(str(clfgtb.score(x_test, y_test)) + ' gdpercent on first playoffs')\n\n\t\tprobsgd = clfgtb.predict_proba(x_test)\n\t\tprobsgd = probsgd.tolist()\n\n\t\tlen_probsgd = len(probsgd)\n\n\t\twinners = test_df['winner']\n\t\twinners = list(winners)\n\n\t\th_lines = test_df['h_ML']\n\t\th_lines = list(h_lines)\n\n\t\ta_lines = test_df['ML']\n\t\ta_lines = list(a_lines)\n\n\t\ttotal = 0\n\t\tabets = []\n\t\thbets = []\n\t\tallbets = []\n\t\tfor i in range(len_probsgd):\n\n\t\t\taway_winprob = probsgd[i][0]\n\t\t\thome_winprob = probsgd[i][1]\n\n\t\t\twinner = winners[i]\n\t\t\th_line = h_lines[i]\n\t\t\ta_line = a_lines[i]\n\t\t\tevhome = home_winprob * h.calc._eq(h_line) - away_winprob \n\t\t\tevaway = away_winprob * h.calc._eq(a_line) - home_winprob\n\n\t\t\tif winner == 'H':\n\t\t\t\troi_home = h.calc._eq(h_line)\n\t\t\t\troi_away = -1\n\n\t\t\tif winner == 'A':\n\t\t\t\troi_home = -1\n\t\t\t\troi_away = h.calc._eq(a_line)\n\n\n\t\t\tif evaway > 0:\n\t\t\t\ta_bets = [away_winprob, a_line, evaway, roi_away, winner]\n\t\t\t\tabets.append(a_bets)\n\t\t\t\tallbets.append(a_bets)\n\n\t\t\tif evhome > 0:\n\t\t\t\th_bets = [home_winprob, h_line, evhome, roi_home, winner]\n\t\t\t\thbets.append(h_bets)\n\t\t\t\tallbets.append(h_bets)\n\n\n\t\tall_df = pd.DataFrame(allbets, columns = ['winprob', 'line', 'ev', 'roi', 'winner'])\n\t\thome_df = pd.DataFrame(hbets, columns = ['home_winprob', 'h_line', 'evhome', 'roi_home', 'winner'])\n\t\taway_df = pd.DataFrame(abets, columns = ['away_winprob', 'a_line', 'evaway', 'roi_away', 'winner'])\n\n\n\n\t\ttotal_roi = all_df['roi'].sum() \n\na = Run()\ng1 = [[1643, 1533, 116.5, 119, 106.5, 118.5]]\n\npred1 = a.clfgtb.predict(g1)\n\nprint(pred1)","sub_path":"sips/gym_sip/sk_model.py","file_name":"sk_model.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"18431453","text":"# from django.contrib.auth.models import User\nfrom rest_framework import serializers\nfrom .models import List, Album, Artist\n\n\n# ============== NOT CURRENTLY IN USE ==============\n\n# Will need to re-implement to add lists to UserDetailsSerializer from\n# django-rest-auth\n\n# class UserSerializer(serializers.ModelSerializer):\n# lists = serializers.PrimaryKeyRelatedField(many=True,\n# queryset=List.objects.all())\n\n# class Meta:\n# model = User\n# fields = ('id', 'username', 'lists')\n\n\nclass ArtistSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Artist\n fields = ('id', 'name')\n extra_kwargs = {'id': {'validators': []}}\n\n\nclass AlbumSerializer(serializers.ModelSerializer):\n artistCredit = ArtistSerializer(many=True, required=False)\n\n class Meta:\n model = Album\n fields = ('id', 'title', 'image', 'artistCredit')\n extra_kwargs = {'id': {'validators': []}}\n\n def create(self, validated_data):\n try:\n album = Album.objects.get(id=validated_data.get('id'))\n return album\n except Album.DoesNotExist:\n artist_credit_data = validated_data.pop('artistCredit')\n album = Album.objects.create(**validated_data)\n for artist_data in artist_credit_data:\n try:\n artist = Artist.objects.get(id=artist_data.get('id'))\n except Artist.DoesNotExist:\n artist = Artist.objects.create(**artist_data)\n artist.credits.add(album)\n return album\n\n\nclass ListSerializer(serializers.ModelSerializer):\n albums = AlbumSerializer(many=True, required=False)\n owner = serializers.CharField(source='owner.username', read_only=True)\n lastUpdate = serializers.DateTimeField(source='last_update',\n required=False)\n\n class Meta:\n model = List\n fields = ('id', 'owner', 'title', 'albums', 'public', 'created',\n 'lastUpdate')\n\n def create(self, validated_data):\n albums_data = validated_data.pop('albums')\n list = List.objects.create(**validated_data)\n for album_data in albums_data:\n\n try:\n album = Album.objects.get(id=album_data.get('id'))\n\n except Album.DoesNotExist:\n serializer = AlbumSerializer(data=album_data)\n serializer.is_valid()\n album = serializer.save()\n album.lists.add(list)\n return list\n\n def update(self, instance, validated_data):\n instance.public = validated_data.get('public', instance.public)\n instance.save()\n return instance\n","sub_path":"lists/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"141299380","text":"from scipy.stats import expon\n\n#distribución exponencial\n\nlam = 7 #tiempo estimado de espera\ndist = expon(scale = 1/lam) #guardo la distribución en el objeto dist\n\nmean, var = dist.stats(moments = 'mv')\nprint(\"La esperanza es de: %f\"%mean)\nprint(\"La varianza es de: %f\"%var)\n\nprob_acum = expon.cdf(5,1/lam)\n\nprint(\"La probabilidad de esperar 5 minutos o menos es de %f\"%prob_acum)","sub_path":"ejercicios/Tema11.Distribuciones/Ej.Distribuciones12_Exponencial.py","file_name":"Ej.Distribuciones12_Exponencial.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"178552069","text":"import unittest\nfrom src.kube.custom_object import CustomObjectManager\nfrom src.kube.crd import CRDManager\n\nclass TestCustomObjectManager(unittest.TestCase):\n\n def setUp(self):\n\n # Create crds\n self.crd_manager = CRDManager()\n self.crd_name = \"crdtests.myob.com\"\n self.crd_config = {\n \"api_version\": \"apiextensions.k8s.io/v1beta1\",\n \"kind\": \"CustomResourceDefinition\",\n \"metadata\": {\n \"name\": self.crd_name\n },\n \"spec\": {\n \"group\": \"myob.com\",\n \"version\": \"v1alpha1\",\n \"names\":{\n \"kind\": \"CRDTEST\",\n \"singular\": \"crdtest\",\n \"plural\": \"crdtests\"\n },\n \"scope\": \"Namespaced\"\n }\n }\n self.crd_manager.create_custom_resource_definition(self.crd_config)\n\n # Setup Custom Object Manager\n self.co_manager = CustomObjectManager()\n self.co_config = {\n \"group\": \"myob.com\",\n \"version\": \"v1alpha1\",\n \"plural\": \"crdtests\"\n }\n self.namespace = \"platform-enablement\"\n self.co_name = \"customized-crds\"\n self.co_test_details = {\n \"apiVersion\": \"myob.com/v1alpha1\",\n \"kind\": \"CRDTEST\",\n \"metadata\": {\n \"name\": self.co_name,\n \"namespace\": self.namespace\n },\n \"spec\":{\n \"size\": \"cache.t2.micro\"\n }\n }\n\n\n def test_create_namespaced_custom_object(self):\n self.co_manager.create_namespaced_custom_object(self.co_config, self.namespace, self.co_test_details)\n self.assertEqual(\n self.co_manager.get_namespaced_custom_object(self.co_config, self.namespace, self.co_name)[\"apiVersion\"],\n self.co_test_details[\"apiVersion\"]\n )\n self.assertTrue(self.co_manager.exist_namespaced_custom_object(self.co_config, self.namespace, self.co_name))\n\n\n def test_patch_namespaced_custom_object(self):\n self.co_manager.create_namespaced_custom_object(self.co_config, self.namespace, self.co_test_details)\n patched_co_details = {\n \"spec\":{\n \"type\": \"cache.t2.micro\",\n \"size\": \"50G\"\n },\n \"status\": [ {\"type\": \"in progress\"} ]\n }\n self.co_manager.patch_namespaced_custom_object(self.co_config, self.namespace, self.co_name, patched_co_details)\n self.assertEqual(\n self.co_manager.get_namespaced_custom_object(self.co_config, self.namespace, self.co_name)[\"spec\"],\n {\n \"type\": \"cache.t2.micro\",\n \"size\": \"50G\"\n }\n\n )\n self.assertEqual(\n self.co_manager.get_namespaced_custom_object(self.co_config, self.namespace, self.co_name)[\"status\"],\n [ {\"type\": \"in progress\"} ]\n )\n self.assertTrue(self.co_manager.exist_namespaced_custom_object(self.co_config, self.namespace, self.co_name))\n\n def tearDown(self):\n self.co_manager.delete_namespaced_custom_object(self.co_config, self.namespace, self.co_name)\n self.crd_manager.delete_custom_resource_definition(self.crd_name)\n","sub_path":"tests/kube/test_custom_object.py","file_name":"test_custom_object.py","file_ext":"py","file_size_in_byte":3253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"542525099","text":"'''\n\n@author: FangSun\n'''\n\n\nimport zstackwoodpecker.test_lib as test_lib\nimport zstackwoodpecker.test_state as test_state\n\nimport os\n\n\ntest_stub = test_lib.lib_get_test_stub()\ntest_obj_dict = test_state.TestStateDict()\n\n\ndef test():\n pub_l3_vm, flat_l3_vm, vr_l3_vm = test_stub.generate_pub_test_vm(tbj=test_obj_dict)\n\n for vm in (pub_l3_vm, flat_l3_vm, vr_l3_vm):\n for action in ('stop', 'start', 'reboot', 'suspend', 'resume'):\n getattr(vm, action)()\n\n test_lib.lib_error_cleanup(test_obj_dict)\n\n\ndef env_recover():\n test_lib.lib_error_cleanup(test_obj_dict)\n\n","sub_path":"integrationtest/vm/virtualrouter/pub_l3_vm/test_pub_vm_ops.py","file_name":"test_pub_vm_ops.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"572974820","text":"import socket\nimport time\n\n\ndef main():\n op = input(\"Welcome!!\\n\"\n \"Only host(1)\\n\"\n \"Range IP(2)\\n:\")\n if op == '1':\n hostname = input(\"host: \")\n iphost = socket.gethostbyname(hostname)\n portScan(iphost)\n elif op == '2':\n iphost = input(\"host: \")\n host = str(iphost[:-4])\n for i in range(1, 255):\n portScan('%s.%s' % (host, i))\n print(\"Exinting Scan!\")\n print(\"Thanks.\")\n\n\ndef portScan(ip):\n ports = [x for x in range(20,1024)]\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n for p in ports:\n try:\n print(p)\n s.connect((ip, p))\n resp = s.recv(1024)\n print(\"[+]Port \", p, \" open\")\n if resp:\n print(\"[+]Banner \", resp)\n except:\n pass\n\n\n\n\n\n\n#main()\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nip = socket.gethostbyname('www.pg.df.gov.br')\ns.connect((ip, 21))\nr = s.recv(4096)\ntime.sleep(1)\nprint(r)\ns.send(b'USER anonymous\\r\\n')\nr = s.recv(4096)\nprint(r)\ns.send(b'PASS\\r\\n')\nr = s.recv(4096)\nprint(r)\ns.close()\n\n","sub_path":"Testes_python-master/Testes_python-master/redes/socket/testes.py","file_name":"testes.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"109415174","text":"from mitmproxy import http\n\n\ndef request(flow: http.HTTPFlow):\n # 发起请求,判端url是不是我们预期的url\n if \"quote.json\" in flow.request.pretty_url:\n with open(\"D:\\HogwartsTest15\\mitm\\mitm_proxy\\quote.json\", encoding='utf-8') as f:\n # 创造一个response\n flow.response = http.HTTPResponse.make(\n 200,\n # 读取文件内容作为数据\n f.read(),\n {\"Content-Type\": \"application/json\"}\n )\n\n# def test_xxx():\n# with open(\"quote.json\", encoding='utf-8') as f:\n# print(f.read())\n","sub_path":"mitm/mitm_proxy/maplocal_xueqiu.py","file_name":"maplocal_xueqiu.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"148623777","text":"from os import walk\nimport fnmatch\nimport os\nimport re\nimport numpy as np\nfrom math import floor\ndef floored_percentage(val, digits):\n val *= 10 ** (digits + 2)\n return '{1:.{0}f}\\%\\pm '.format(digits, floor(val) / 10 ** digits)\npattern = '5nonIDH10.700000*'\n\nfiles = os.listdir('.')\nmyfiles = []\nfor name in files:\n if fnmatch.fnmatch(name, pattern):\n myfiles.append(name)\nRF = []\nRELF = []\nSVM = []\nRFSVM = []\nRFDIS = []\nLRF = []\nLRFDIS = []\nConcatenated = []\nfor file in myfiles:\n searchfile = open(file, \"r\")\n for line in searchfile:\n if \"AWA 0.1 RF\" in line:\n l = re.findall(\"\\d+\\.\\d+\", line)\n RF.append(float(l[1]))\n\n if \"RELF\" in line:\n l = re.findall(\"\\d+\\.\\d+\", line)\n RELF.append(float(l[0]))\n if \"SVMRFE\" in line:\n l = re.findall(\"\\d+\\.\\d+\", line)\n SVM.append(float(l[0]))\n if \"RFSVM\" in line:\n l = re.findall(\"\\d+\\.\\d+\", line)\n RFSVM.append(float(l[0]))\n if \"RFDIS\" in line:\n l = re.findall(\"\\d+\\.\\d+\", line)\n RFDIS.append(float(l[0]))\n if \"LATERF\" in line:\n l = re.findall(\"\\d+\\.\\d+\", line)\n LRF.append(float(l[0]))\n if \"LATERFDIS\" in line:\n l = re.findall(\"\\d+\\.\\d+\", line)\n LRFDIS.append(float(l[0]))\n if \"Concatenated multi view\" in line:\n l = re.findall(\"\\d+\\.\\d+\", line)\n Concatenated.append(float(l[0]))\n\n\n searchfile.close()\nprint(\"$\"+\"%.2f\" % np.mean(RF)+r\"\\%\\pm\"+\"%.2f\" % np.std(RF)+\"$\")\nprint(\"&\")\nprint(\"$\"+\"%.2f\" % np.mean(RELF)+r\"\\%\\pm\"+\"%.2f\" % np.std(RELF)+\"$\")\nprint(\"&\")\nprint(\"$\"+\"%.2f\" % np.mean(SVM)+r\"\\%\\pm\"+\"%.2f\" % np.std(SVM)+\"$\")\nprint(\"&\")\nprint(\"$\"+\"%.2f\" % np.mean(RFSVM)+r\"\\%\\pm\"+\"%.2f\" % np.std(RFSVM)+\"$\")\nprint(\"&\")\nprint(\"$\"+\"%.2f\" % np.mean(RFDIS)+r\"\\%\\pm\"+\"%.2f\" % np.std(RFDIS)+\"$\")\nprint(\"&\")\nprint(\"$\"+\"%.2f\" % np.mean(LRF)+r\"\\%\\pm\"+\"%.2f\" % np.std(LRF)+\"$\")\nprint(\"&\")\nprint(\"$\"+\"%.2f\" % np.mean(LRFDIS)+r\"\\%\\pm\"+\"%.2f\" % np.std(LRFDIS)+\"$\")\nprint(\"$\"+\"%.2f\" % np.mean(Concatenated)+r\"\\%\\pm\"+\"%.2f\" % np.std(Concatenated)+\"$\")","sub_path":"progression/MeanCalc.py","file_name":"MeanCalc.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"240804966","text":"import datetime\nimport json\nimport os\n\n\nclass Cache:\n\n path = os.path.join('cache', 'shells.json')\n\n @staticmethod\n def __read():\n \"\"\" Read from cache \"\"\"\n with open(Cache.path, 'r') as f:\n cache_content = f.read()\n\n return json.loads(cache_content)\n\n @staticmethod\n def __write(cache_content):\n \"\"\" Write to cache \"\"\"\n with open(Cache.path, 'w') as f:\n f.write(json.dumps(cache_content))\n\n @staticmethod\n def __init():\n \"\"\" Initialize cache \"\"\"\n if not os.path.exists(os.path.dirname(Cache.path)):\n os.mkdir('cache', 660)\n\n if not os.path.exists(Cache.path) or not os.path.isfile(Cache.path):\n Cache.flush()\n\n # validates JSON object in cache file\n # and clears cache if JSON object in cache file is invalid\n try:\n Cache.__read()\n except Exception:\n Cache.flush()\n\n @staticmethod\n def save(upload_url, shell_url):\n \"\"\" Save shell URL to cache \"\"\"\n target = [x for x in upload_url.split('/') if len(x) > 0][1]\n\n Cache.__init()\n\n cache_data = {\n 'date': datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S'),\n 'target': target,\n 'upload_url': upload_url,\n 'shell_url': shell_url\n }\n\n cache_content = Cache.__read()\n cache_content.append(cache_data)\n\n Cache.__write(cache_content)\n\n @staticmethod\n def get(url):\n \"\"\" Fetch shell URL from cache \"\"\"\n target = [x for x in url.split('/') if len(x) > 0][1]\n\n Cache.__init()\n\n cache_content = Cache.__read()\n\n for cache_elem in cache_content:\n if cache_elem['target'].lower() == target.lower():\n return cache_elem\n\n return None\n\n @staticmethod\n def flush():\n \"\"\" Clear cache \"\"\"\n Cache.__write([])\n","sub_path":"core/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"272141104","text":"import numpy\n\n\nclass CirclePath:\n def __init__(self, x0, r):\n self.x0 = x0\n self.r = r\n return\n\n def p(self, t):\n v = numpy.array([numpy.cos(2 * numpy.pi * t), numpy.sin(2 * numpy.pi * t)])\n return ((self.r * v).T + self.x0).T\n\n def dp_dt(self, t):\n return (\n self.r\n * 2\n * numpy.pi\n * numpy.array([-numpy.sin(2 * numpy.pi * t), numpy.cos(2 * numpy.pi * t)])\n )\n\n\nclass Circle:\n def __init__(self, x0, r):\n self.x0 = x0\n self.r = r\n self.bounding_box = [x0[0] - r, x0[0] + r, x0[1] - r, x0[1] + r]\n self.paths = [CirclePath(x0, r)]\n self.feature_points = numpy.array([[], []]).T\n return\n\n def plot(self, color=\"#1f77b4\"):\n import matplotlib.pyplot as plt\n\n t = numpy.linspace(0.0, 2 * numpy.pi, 100)\n plt.plot(\n self.x0[0] + self.r * numpy.cos(t),\n self.x0[1] + self.r * numpy.sin(t),\n \"-\",\n color=color,\n )\n return\n\n def dist(self, x):\n assert x.shape[0] == 2\n y = (x.T - self.x0).T\n return numpy.sqrt(numpy.einsum(\"ij,ij->j\", y, y)) - self.r\n\n def boundary_step(self, x):\n # simply project onto the circle\n y = (x.T - self.x0).T\n r = numpy.sqrt(numpy.einsum(\"ij,ij->j\", y, y))\n return ((y / r * self.r).T + self.x0).T\n","sub_path":"dmsh/geometry/circle.py","file_name":"circle.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"386463942","text":"#!/usr/bin/env python3\nimport argparse\nimport h5py\nimport pandas as pd\nfrom pyopls import OPLSValidator\nimport os\nimport sys\nimport numpy as np\n\nfrom joblib import parallel_backend\n\nprint(' '.join(sys.argv))\n\n\ndef load_data(filename, group_key):\n with h5py.File(filename, 'r') as file:\n description_ = file[group_key].attrs['description']\n try:\n pos_label_ = file[group_key].attrs['pos_label']\n except:\n pos_label_ = None\n try:\n neg_label_ = file[group_key].attrs['neg_label']\n except:\n neg_label_ = None\n return (pd.read_hdf(filename, f'{group_key}/X'), pd.read_hdf(filename, f'{group_key}/y'),\n description_, pos_label_, neg_label_)\n\n\ndef serialize_opls(filename, validator_: OPLSValidator, name, description_, pos_label_, neg_label_, target,\n feature_labels_):\n significant_features = feature_labels_[validator_.feature_significance_]\n with h5py.File(filename, 'a') as file:\n group = file.create_group(name)\n group.attrs['description'] = description_\n group.attrs['pos_label'] = pos_label_ if pos_label_ is not None else ''\n group.attrs['neg_label'] = neg_label_ if neg_label_ is not None else ''\n group.attrs['k'] = validator_.k\n group.attrs['n_permutations'] = validator_.n_permutations\n group.attrs['n_inner_permutations'] = validator_.n_inner_permutations\n group.attrs['n_outer_permutations'] = validator_.n_outer_permutations\n group.attrs['inner_alpha'] = validator_.inner_alpha\n group.attrs['outer_alpha'] = validator_.outer_alpha\n group.attrs['n_components'] = validator_.n_components_\n group.attrs['q_squared'] = validator_.q_squared_\n group.attrs['q_squared_p_value'] = validator_.q_squared_p_value_\n group.attrs['r_squared_Y'] = validator_.r_squared_Y_\n group.attrs['r_squared_X'] = validator_.r_squared_X_\n\n group.create_dataset('permutation_q_squared', data=validator_.permutation_q_squared_)\n group.create_dataset('permutation_loadings', data=validator_.permutation_loadings_)\n group.create_dataset('feature_p_values', data=validator_.feature_p_values_)\n\n target_dtype = h5py.special_dtype(vlen=bytes) if target.dtype.type is np.object_ else target.dtype\n group.create_dataset('target', data=target.to_numpy(), dtype=target_dtype)\n group.create_dataset('index', data=target.index.to_numpy())\n group.create_dataset('feature_labels', data=feature_labels_)\n group.create_dataset('significant_features', data=significant_features)\n\n opls_group = group.create_group('opls')\n opls_group.create_dataset('W_ortho', data=validator_.opls_.W_ortho_)\n opls_group.create_dataset('P_ortho', data=validator_.opls_.P_ortho_)\n opls_group.create_dataset('T_ortho', data=validator_.opls_.T_ortho_)\n\n pls_group = group.create_group('pls')\n pls_group.create_dataset('x_weights', data=validator_.pls_.x_weights_)\n pls_group.create_dataset('y_weights', data=validator_.pls_.y_weights_)\n pls_group.create_dataset('x_loadings', data=validator_.pls_.x_loadings_)\n pls_group.create_dataset('x_scores', data=validator_.pls_.x_scores_)\n pls_group.create_dataset('y_scores', data=validator_.pls_.y_scores_)\n pls_group.create_dataset('x_rotations', data=validator_.pls_.x_rotations_)\n pls_group.create_dataset('y_rotations', data=validator_.pls_.y_rotations_)\n pls_group.create_dataset('coef', data=validator_.pls_.coef_)\n pls_group.create_dataset('n_iter', data=validator.pls_.n_iter_)\n\n if validator_.accuracy_ is not None:\n group['transformed_target'] = validator_.binarizer_.transform(target)\n group.attrs['accuracy'] = validator_.accuracy_\n group.attrs['accuracy_p_value'] = validator_.accuracy_p_value_\n group.attrs['roc_auc'] = validator_.roc_auc_\n group.attrs['roc_auc_p_value'] = validator_.roc_auc_p_value_\n group.attrs['discriminant_q_squared'] = validator_.discriminant_q_squared_\n group.attrs['discriminant_q_squared_p_value'] = validator_.discriminant_q_squared_p_value_\n group.attrs['discriminant_r_squared'] = validator_.discriminant_r_squared_\n\n group.create_dataset('permutation_accuracy', data=validator_.permutation_accuracy_)\n group.create_dataset('permutation_roc_auc', data=validator_.permutation_roc_auc_)\n group.create_dataset('permutation_discriminant_q_squared',\n data=validator_.permutation_discriminant_q_squared_)\n\n\nparser = argparse.ArgumentParser(description='Perform Orthogonal Projection to Latent Structures')\nparser.add_argument('dataframe_filename', type=str,\n help='HDF5 file containing two pandas DataFrames, \"numeric_df\" and \"label_df\".')\nparser.add_argument('k', type=int, help='Number of cross-validation folds, -1 for leave-one-out.')\nparser.add_argument('min_n_components', type=int, help='Minimum number of orthogonal components to remove.')\nparser.add_argument('inner_test_alpha', type=float,\n help='First significance threshold, values outside of this will be '\n 'tested for outer_test_permutations')\nparser.add_argument('outer_test_alpha', type=float,\n help='Second significance threshold, applied to values tested with outer_test_permutations.')\nparser.add_argument('metric_test_permutations', type=int,\n help='Number of permutations to perform to determine significance of metrics (like R-squared).')\nparser.add_argument('inner_test_permutations', type=int,\n help='Number of permutations to perform for all features.')\nparser.add_argument('outer_test_permutations', type=int,\n help='Number of permutations to perform for features deemed significant with inner_test_alpha.')\nparser.add_argument('--force_regression', type=bool, default=False,\n help='If True, treat numeric multiclass or binary variables as continuous variables.')\nargs = parser.parse_args()\n\ngroup_keys = [key for key in h5py.File(args.dataframe_filename).keys()]\noutput_filename = os.path.splitext(os.path.basename(args.dataframe_filename))[0] + '_results.h5'\n\nwith h5py.File(output_filename, 'w') as out_file, h5py.File(args.dataframe_filename, 'r') as in_file:\n if 'collection_id' in in_file.attrs:\n out_file.attrs['input_collection_id'] = in_file.attrs['collection_id']\n out_file.attrs.update({key: value for key, value in in_file.attrs.items() if key != 'collection_id'})\n out_file.attrs['analysis_type'] = 'opls'\n\nfor key in group_keys:\n X, y, description, pos_label, neg_label = load_data(args.dataframe_filename, key)\n feature_labels = np.array([float(c) for c in X.columns])\n print(description)\n validator = OPLSValidator(args.min_n_components, args.k, False, args.force_regression,\n args.metric_test_permutations, args.inner_test_permutations, args.outer_test_permutations,\n args.inner_test_alpha, args.outer_test_alpha)\n print(f'====== Fitting {key} ======')\n with parallel_backend('threading'):\n validator.fit(X, y, pos_label=pos_label, verbose=1)\n serialize_opls(output_filename, validator, key, description, pos_label, neg_label, y, feature_labels)\n","sub_path":"modules/sbin/perform_opls.py","file_name":"perform_opls.py","file_ext":"py","file_size_in_byte":7464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"354334129","text":"import logging\nimport os\nfrom time import sleep\nfrom typing import TYPE_CHECKING\n\nimport colander\nfrom celery.utils.log import get_task_logger\nfrom owslib.util import clean_ows_url\nfrom owslib.wps import ComplexDataInput\nfrom pyramid.httpexceptions import HTTPBadRequest, HTTPNotAcceptable, HTTPNotImplemented\nfrom pyramid_celery import celery_app as app\n\nfrom weaver.database import get_db\nfrom weaver.datatype import Process, Service\nfrom weaver.execute import (\n EXECUTE_MODE_ASYNC,\n EXECUTE_MODE_AUTO,\n EXECUTE_MODE_SYNC,\n EXECUTE_RESPONSE_DOCUMENT,\n EXECUTE_TRANSMISSION_MODE_OPTIONS\n)\nfrom weaver.formats import ACCEPT_LANGUAGES, CONTENT_TYPE_APP_JSON\nfrom weaver.notify import encrypt_email, notify_job_complete\nfrom weaver.owsexceptions import OWSNoApplicableCode\nfrom weaver.processes import wps_package\nfrom weaver.processes.constants import WPS_COMPLEX_DATA\nfrom weaver.processes.convert import ows2json_output_data\nfrom weaver.processes.types import PROCESS_WORKFLOW\nfrom weaver.status import (\n JOB_STATUS_CATEGORIES,\n JOB_STATUS_CATEGORY_FAILED,\n JOB_STATUS_CATEGORY_FINISHED,\n STATUS_ACCEPTED,\n STATUS_DISMISSED,\n STATUS_FAILED,\n STATUS_RUNNING,\n STATUS_STARTED,\n STATUS_SUCCEEDED,\n map_status\n)\nfrom weaver.store.base import StoreJobs\nfrom weaver.utils import get_any_id, get_any_value, get_settings, now, raise_on_xml_exception, wait_secs\nfrom weaver.visibility import VISIBILITY_PUBLIC\nfrom weaver.wps.utils import (\n check_wps_status,\n get_wps_client,\n get_wps_local_status_location,\n get_wps_output_context,\n get_wps_output_path,\n get_wps_output_url,\n load_pywps_config\n)\nfrom weaver.wps_restapi import swagger_definitions as sd\nfrom weaver.wps_restapi.utils import get_wps_restapi_base_url\n\nLOGGER = logging.getLogger(__name__)\nif TYPE_CHECKING:\n from typing import List, Optional, Union\n from pyramid.request import Request\n from weaver.datatype import Job\n from weaver.typedefs import HeaderCookiesType, JSON, SettingsType\n\n# job process execution progress\nJOB_PROGRESS_SETUP = 1\nJOB_PROGRESS_DESCRIBE = 2\nJOB_PROGRESS_GET_INPUTS = 3\nJOB_PROGRESS_GET_OUTPUTS = 4\nJOB_PROGRESS_EXECUTE_REQUEST = 5\nJOB_PROGRESS_EXECUTE_STATUS_LOCATION = 6\nJOB_PROGRESS_EXECUTE_MONITOR_START = 7\nJOB_PROGRESS_EXECUTE_MONITOR_LOOP = 8\nJOB_PROGRESS_EXECUTE_MONITOR_DONE = 96\nJOB_PROGRESS_EXECUTE_MONITOR_END = 98\nJOB_PROGRESS_NOTIFY = 99\nJOB_PROGRESS_DONE = 100\n\n\n@app.task(bind=True)\ndef execute_process(self, job_id, wps_url, headers=None):\n \"\"\"\n Celery task that executes the WPS process job monitoring as status updates (local and remote).\n \"\"\"\n from weaver.wps.service import get_pywps_service\n\n LOGGER.debug(\"Job execute process called.\")\n\n # reset the connection because we are in a forked celery process\n db = get_db(app, reset_connection=True)\n store = db.get_store(StoreJobs)\n job = store.fetch_by_id(job_id)\n job.started = now()\n job.status = STATUS_STARTED # will be mapped to 'RUNNING'\n job.status_message = \"Job {}.\".format(STATUS_STARTED) # will preserve detail of STARTED vs RUNNING\n job.save_log(message=job.status_message)\n\n task_logger = get_task_logger(__name__)\n job.save_log(logger=task_logger, message=\"Job task setup initiated.\")\n settings = get_settings(app)\n load_pywps_config(settings)\n job.progress = JOB_PROGRESS_SETUP\n job.task_id = self.request.id\n job.save_log(logger=task_logger, message=\"Job task setup completed.\")\n job = store.update_job(job)\n\n # Flag to keep track if job is running in background (remote-WPS, CWL app, etc.).\n # If terminate signal is sent to worker task via API dismiss request while still running in background,\n # the raised exception within the task will switch the job to STATUS_FAILED, but this will not raise an\n # exception here. Since the task execution 'succeeds' without raising, it skips directly to the last 'finally'.\n # Patch it back to STATUS_DISMISSED in this case.\n task_terminated = True\n\n try:\n job.progress = JOB_PROGRESS_DESCRIBE\n job.save_log(logger=task_logger, message=\"Employed WPS URL: [{!s}]\".format(wps_url), level=logging.DEBUG)\n job.save_log(logger=task_logger, message=\"Execute WPS request for process [{!s}]\".format(job.process))\n wps_process = fetch_wps_process(job, wps_url, headers, settings)\n\n # prepare inputs\n job.progress = JOB_PROGRESS_GET_INPUTS\n job.save_log(logger=task_logger, message=\"Fetching job input definitions.\")\n wps_inputs = parse_wps_inputs(wps_process, job)\n\n # prepare outputs\n job.progress = JOB_PROGRESS_GET_OUTPUTS\n job.save_log(logger=task_logger, message=\"Fetching job output definitions.\")\n wps_outputs = [(o.identifier, o.dataType == WPS_COMPLEX_DATA) for o in wps_process.processOutputs]\n\n # if process refers to a remote WPS provider, pass it down to avoid unnecessary re-fetch request\n if job.is_local:\n process = None # already got all the information needed pre-loaded in PyWPS service\n else:\n service = Service(name=job.service, url=wps_url)\n process = Process.from_ows(wps_process, service, settings)\n\n job.progress = JOB_PROGRESS_EXECUTE_REQUEST\n job.save_log(logger=task_logger, message=\"Starting job process execution.\")\n job.save_log(logger=task_logger,\n message=\"Following updates could take a while until the Application Package answers...\")\n\n wps_worker = get_pywps_service(environ=settings, is_worker=True)\n execution = wps_worker.execute_job(job, wps_inputs=wps_inputs, wps_outputs=wps_outputs, remote_process=process)\n if not execution.process and execution.errors:\n raise execution.errors[0]\n\n # adjust status location\n wps_status_path = get_wps_local_status_location(execution.statusLocation, settings)\n job.progress = JOB_PROGRESS_EXECUTE_STATUS_LOCATION\n LOGGER.debug(\"WPS status location that will be queried: [%s]\", wps_status_path)\n if not wps_status_path.startswith(\"http\") and not os.path.isfile(wps_status_path):\n LOGGER.warning(\"WPS status location not resolved to local path: [%s]\", wps_status_path)\n job.save_log(logger=task_logger, level=logging.DEBUG,\n message=\"Updated job status location: [{}].\".format(wps_status_path))\n\n job.status = STATUS_RUNNING\n job.status_message = execution.statusMessage or \"{} initiation done.\".format(str(job))\n job.status_location = wps_status_path\n job.request = execution.request\n job.response = execution.response\n job.progress = JOB_PROGRESS_EXECUTE_MONITOR_START\n job.save_log(logger=task_logger, message=\"Starting monitoring of job execution.\")\n job = store.update_job(job)\n\n max_retries = 5\n num_retries = 0\n run_step = 0\n while execution.isNotComplete() or run_step == 0:\n if num_retries >= max_retries:\n job.save_log(errors=execution.errors, logger=task_logger)\n job = store.update_job(job)\n raise Exception(\"Could not read status document after {} retries. Giving up.\".format(max_retries))\n try:\n # NOTE:\n # Don't actually log anything here until process is completed (success or fail) so that underlying\n # WPS execution logs can be inserted within the current job log and appear continuously.\n # Only update internal job fields in case they get referenced elsewhere.\n progress_min = JOB_PROGRESS_EXECUTE_MONITOR_LOOP\n progress_max = JOB_PROGRESS_EXECUTE_MONITOR_DONE\n job.progress = progress_min\n run_delay = wait_secs(run_step)\n execution = check_wps_status(location=wps_status_path, settings=settings, sleep_secs=run_delay)\n job_msg = (execution.statusMessage or \"\").strip()\n job.response = execution.response\n job.status = map_status(execution.getStatus())\n job.status_message = (\n \"Job execution monitoring (progress: {}%, status: {}).\"\n .format(execution.percentCompleted, job_msg or \"n/a\")\n )\n\n if execution.isComplete():\n msg_progress = \" (status: {})\".format(job_msg) if job_msg else \"\"\n if execution.isSucceded():\n wps_package.retrieve_package_job_log(execution, job, progress_min, progress_max)\n job.status = map_status(STATUS_SUCCEEDED)\n job.status_message = \"Job succeeded{}.\".format(msg_progress)\n job.progress = progress_max\n job.save_log(logger=task_logger)\n job_results = [ows2json_output_data(output, process, settings)\n for output in execution.processOutputs]\n job.results = make_results_relative(job_results, settings)\n else:\n task_logger.debug(\"Job failed.\")\n wps_package.retrieve_package_job_log(execution, job, progress_min, progress_max)\n job.status_message = \"Job failed{}.\".format(msg_progress)\n job.progress = progress_max\n job.save_log(errors=execution.errors, logger=task_logger)\n task_logger.debug(\"Mapping Job references with generated WPS locations.\")\n map_locations(job, settings)\n job = store.update_job(job)\n\n except Exception as exc:\n num_retries += 1\n task_logger.debug(\"Exception raised: %s\", repr(exc))\n job.status_message = \"Could not read status XML document for {!s}. Trying again...\".format(job)\n job.save_log(errors=execution.errors, logger=task_logger)\n job = store.update_job(job)\n sleep(1)\n else:\n num_retries = 0\n run_step += 1\n finally:\n task_terminated = False # reached only if WPS execution completed (worker not terminated beforehand)\n job = store.update_job(job)\n\n except Exception as exc:\n # if 'execute_job' finishes quickly before even reaching the 'monitoring loop'\n # consider WPS execution produced an error (therefore Celery worker not terminated)\n task_terminated = False\n LOGGER.exception(\"Failed running [%s]\", job)\n LOGGER.debug(\"Failed job [%s] raised an exception.\", job, exc_info=exc)\n # note: don't update the progress here to preserve last one that was set\n job.status = map_status(STATUS_FAILED)\n job.status_message = \"Failed to run {!s}.\".format(job)\n exception_class = \"{}.{}\".format(type(exc).__module__, type(exc).__name__)\n errors = \"{0}: {1!s}\".format(exception_class, exc)\n job.save_log(errors=errors, logger=task_logger)\n job = store.update_job(job)\n finally:\n # if task worker terminated, local 'job' is out of date compared to remote/background runner last update\n job = store.fetch_by_id(job.id)\n if task_terminated and map_status(job.status) == STATUS_FAILED:\n job.status = STATUS_DISMISSED\n task_success = map_status(job.status) not in JOB_STATUS_CATEGORIES[JOB_STATUS_CATEGORY_FAILED]\n if task_success:\n job.progress = JOB_PROGRESS_EXECUTE_MONITOR_END\n job.status_message = \"Job {}.\".format(job.status)\n job.save_log(logger=task_logger)\n\n if task_success:\n job.progress = JOB_PROGRESS_NOTIFY\n send_job_complete_notification_email(job, task_logger, settings)\n\n if job.status not in JOB_STATUS_CATEGORIES[JOB_STATUS_CATEGORY_FINISHED]:\n job.status = STATUS_SUCCEEDED\n job.status_message = \"Job {}.\".format(job.status)\n job.mark_finished()\n if task_success:\n job.progress = JOB_PROGRESS_DONE\n job.save_log(logger=task_logger, message=\"Job task complete.\")\n job = store.update_job(job)\n\n return job.status\n\n\ndef fetch_wps_process(job, wps_url, headers, settings):\n \"\"\"\n Retrieves the WPS process description from the local or remote WPS reference URL.\n \"\"\"\n try:\n wps = get_wps_client(wps_url, settings, headers=headers, language=job.accept_language)\n raise_on_xml_exception(wps._capabilities) # noqa\n except Exception as ex:\n job.save_log(errors=ex, message=\"Failed WPS client creation for process [{!s}]\".format(job.process))\n raise OWSNoApplicableCode(\"Failed to retrieve WPS capabilities. Error: [{}].\".format(str(ex)))\n try:\n wps_process = wps.describeprocess(job.process)\n except Exception as ex:\n raise OWSNoApplicableCode(\"Failed to retrieve WPS process description. Error: [{}].\".format(str(ex)))\n return wps_process\n\n\ndef parse_wps_inputs(wps_process, job):\n \"\"\"\n Parses expected WPS process inputs against submitted job input values considering supported process definitions.\n \"\"\"\n complex_inputs = []\n for process_input in wps_process.dataInputs:\n if WPS_COMPLEX_DATA in process_input.dataType:\n complex_inputs.append(process_input.identifier)\n\n try:\n wps_inputs = list()\n # parse both dict and list type inputs\n job_inputs = job.inputs.items() if isinstance(job.inputs, dict) else job.get(\"inputs\", [])\n for process_input in job_inputs:\n if isinstance(process_input, tuple):\n input_id = process_input[0]\n process_value = process_input[1]\n else:\n input_id = get_any_id(process_input)\n process_value = get_any_value(process_input)\n # in case of array inputs, must repeat (id,value)\n input_values = process_value if isinstance(process_value, list) else [process_value]\n\n # we need to support file:// scheme but PyWPS doesn't like them so remove the scheme file://\n input_values = [\n # when value is an array of dict that each contain a file reference\n (get_any_value(val)[7:] if str(get_any_value(val)).startswith(\"file://\") else get_any_value(val))\n if isinstance(val, dict) else\n # when value is directly a single dict with file reference\n (val[7:] if str(val).startswith(\"file://\") else val)\n for val in input_values\n ]\n\n # need to use ComplexDataInput structure for complex input\n # need to use literal String for anything else than complex\n # TODO: BoundingBox not supported\n wps_inputs.extend([\n (input_id, ComplexDataInput(input_value) if input_id in complex_inputs else str(input_value))\n for input_value in input_values])\n except KeyError:\n wps_inputs = []\n return wps_inputs\n\n\ndef send_job_complete_notification_email(job, task_logger, settings):\n \"\"\"\n Sends the notification email of completed execution if it was requested during job submission.\n \"\"\"\n if job.notification_email is not None:\n try:\n notify_job_complete(job, job.notification_email, settings)\n message = \"Notification email sent successfully.\"\n job.save_log(logger=task_logger, message=message)\n except Exception as exc:\n exception_class = \"{}.{}\".format(type(exc).__module__, type(exc).__name__)\n exception = \"{0}: {1!s}\".format(exception_class, exc)\n message = \"Couldn't send notification email ({})\".format(exception)\n job.save_log(errors=message, logger=task_logger, message=message)\n\n\ndef make_results_relative(results, settings):\n # type: (List[JSON], SettingsType) -> List[JSON]\n \"\"\"\n Converts file references to a pseudo-relative location to allow the application to dynamically generate paths.\n\n Redefines job results to be saved in database as pseudo-relative paths to configured WPS output directory.\n This allows the application to easily adjust the exposed result HTTP path according to the service configuration\n (i.e.: relative to ``weaver.wps_output_dir`` and/or ``weaver.wps_output_url``) and it also avoids rewriting\n the database job results entry if those settings are changed later on following reboot of the web application.\n\n Only references prefixed with ``weaver.wps_output_dir``, ``weaver.wps_output_url`` or a corresponding resolution\n from ``weaver.wps_output_path`` with ``weaver.url`` will be modified to pseudo-relative paths.\n Other references (file/URL endpoints that do not correspond to `Weaver`) will be left untouched for\n literal remote reference. Results that do not correspond to a reference are also unmodified.\n\n .. note::\n\n The references are not *real* relative paths (i.e.: starting with ``./``), as those could also be specified as\n input, and there would be no way to guarantee proper differentiation from paths already handled and stored in\n the database. Instead, *pseudo-relative* paths employ an explicit *absolute*-like path\n (i.e.: starting with ``/``) and are assumed to always require to be prefixed by the configured WPS locations\n (i.e.: ``weaver.wps_output_dir`` or ``weaver.wps_output_url`` based on local or HTTP response context).\n\n With this approach, data persistence with mapped volumes into the dockerized `Weaver` service can be placed\n anywhere at convenience. This is important because sibling docker execution require exact mappings such that\n volume mount ``/data/path:/data/path`` resolve correctly on both sides (host and image path must be identical).\n If volumes get remapped differently, ensuring that ``weaver.wps_output_dir`` setting follows the same remapping\n update will automatically resolve to the proper location for both local references and exposed URL endpoints.\n\n :param results: JSON mapping of data results as ``{\"\": }`` entries where a reference can be found.\n :param settings: container to retrieve current application settings.\n \"\"\"\n wps_url = get_wps_output_url(settings)\n wps_path = get_wps_output_path(settings)\n for res in results:\n ref = res.get(\"reference\")\n if isinstance(ref, str) and ref:\n if ref.startswith(wps_url):\n ref = ref.replace(wps_url, \"\", 1)\n if ref.startswith(wps_path):\n ref = ref.replace(wps_path, \"\", 1)\n res[\"reference\"] = ref\n return results\n\n\ndef map_locations(job, settings):\n # type: (Job, SettingsType) -> None\n \"\"\"\n Maps directory locations between :mod:`pywps` process execution and produced jobs storage.\n\n Generates symlink references from the Job UUID to PyWPS UUID results (outputs directory, status and log locations).\n Update the Job's WPS ID if applicable (job executed locally).\n Assumes that all results are located under the same reference UUID.\n \"\"\"\n local_path = get_wps_local_status_location(job.status_location, settings)\n if not local_path:\n LOGGER.debug(\"Not possible to map Job to WPS locations.\")\n return\n base_dir, status_xml = os.path.split(local_path)\n job.wps_id = os.path.splitext(status_xml)[0]\n wps_loc = os.path.join(base_dir, job.wps_id)\n job_loc = os.path.join(base_dir, job.id)\n if wps_loc == job_loc:\n LOGGER.debug(\"Job already refers to WPS locations.\")\n return\n for loc_ext in [\"\", \".log\", \".xml\"]:\n wps_ref = wps_loc + loc_ext\n job_ref = job_loc + loc_ext\n if os.path.exists(wps_ref): # possible that there are no results (e.g.: failed job)\n os.symlink(wps_ref, job_ref)\n\n\ndef submit_job(request, reference, tags=None):\n # type: (Request, Union[Service, Process], Optional[List[str]]) -> JSON\n \"\"\"\n Generates the job submission from details retrieved in the request.\n\n .. seealso::\n :func:`submit_job_handler` to provide elements pre-extracted from requests or from other parsing.\n \"\"\"\n # validate body with expected JSON content and schema\n if CONTENT_TYPE_APP_JSON not in request.content_type:\n raise HTTPBadRequest(json={\n \"code\": \"InvalidHeaderValue\",\n \"name\": \"Content-Type\",\n \"description\": \"Request 'Content-Type' header other than '{}' not supported.\".format(CONTENT_TYPE_APP_JSON),\n \"value\": str(request.content_type)\n })\n try:\n json_body = request.json_body\n except Exception as ex:\n raise HTTPBadRequest(\"Invalid JSON body cannot be decoded for job submission. [{}]\".format(ex))\n # validate context if needed later on by the job for early failure\n context = get_wps_output_context(request)\n\n provider_id = None # None OK if local\n process_id = None # None OK if remote, but can be found as well if available from WPS-REST path\n tags = tags or []\n lang = request.accept_language.header_value # can only preemptively check if local process\n if isinstance(reference, Process):\n service_url = reference.processEndpointWPS1\n process_id = reference.id\n visibility = reference.visibility\n is_workflow = reference.type == PROCESS_WORKFLOW\n is_local = True\n tags += \"local\"\n if lang and request.accept_language.best_match(ACCEPT_LANGUAGES) is None:\n raise HTTPNotAcceptable(\"Requested language [{}] is not in supported languages [{}].\".format(\n lang, \", \".join(ACCEPT_LANGUAGES)\n ))\n elif isinstance(reference, Service):\n service_url = reference.url\n provider_id = reference.id\n process_id = request.matchdict.get(\"process_id\")\n visibility = VISIBILITY_PUBLIC\n is_workflow = False\n is_local = False\n tags += \"remote\"\n else:\n LOGGER.error(\"Expected process/service, got: %s\", type(reference))\n raise TypeError(\"Invalid process or service reference to execute job.\")\n tags = request.params.get(\"tags\", \"\").split(\",\") + tags\n user = request.authenticated_userid\n headers = dict(request.headers)\n settings = get_settings(request)\n return submit_job_handler(json_body, settings, service_url, provider_id, process_id, is_workflow, is_local,\n visibility, language=lang, auth=headers, tags=tags, user=user, context=context)\n\n\n# FIXME: this should not be necessary if schema validators correctly implement OneOf(values)\ndef _validate_job_parameters(json_body):\n \"\"\"\n Tests supported parameters not automatically validated by colander deserialize.\n \"\"\"\n if json_body[\"mode\"] not in [EXECUTE_MODE_ASYNC, EXECUTE_MODE_AUTO]:\n raise HTTPNotImplemented(detail=\"Execution mode '{}' not supported.\".format(json_body[\"mode\"]))\n\n if json_body[\"response\"] != EXECUTE_RESPONSE_DOCUMENT:\n raise HTTPNotImplemented(detail=\"Execution response type '{}' not supported.\".format(json_body[\"response\"]))\n\n for job_output in json_body[\"outputs\"]:\n mode = job_output[\"transmissionMode\"]\n if mode not in EXECUTE_TRANSMISSION_MODE_OPTIONS:\n raise HTTPNotImplemented(detail=\"Execute transmissionMode '{}' not supported.\".format(mode))\n\n\ndef submit_job_handler(payload, # type: JSON\n settings, # type: SettingsType\n service_url, # type: str\n provider_id=None, # type: Optional[str]\n process_id=None, # type: str\n is_workflow=False, # type: bool\n is_local=True, # type: bool\n visibility=None, # type: Optional[str]\n language=None, # type: Optional[str]\n auth=None, # type: Optional[HeaderCookiesType]\n tags=None, # type: Optional[List[str]]\n user=None, # type: Optional[int]\n context=None, # type: Optional[str]\n ): # type: (...) -> JSON\n \"\"\"\n Submits the job to the Celery worker with provided parameters.\n\n Assumes that parameters have been pre-fetched and validated, except for the input payload.\n \"\"\"\n try:\n json_body = sd.Execute().deserialize(payload)\n except colander.Invalid as ex:\n raise HTTPBadRequest(\"Invalid schema: [{}]\".format(str(ex)))\n\n # TODO: remove when all parameter variations are supported\n _validate_job_parameters(json_body)\n\n is_execute_async = json_body[\"mode\"] != EXECUTE_MODE_SYNC # convert auto to async\n notification_email = json_body.get(\"notification_email\")\n encrypted_email = encrypt_email(notification_email, settings) if notification_email else None\n\n store = get_db(settings).get_store(StoreJobs)\n job = store.save_job(task_id=STATUS_ACCEPTED, process=process_id, service=provider_id,\n inputs=json_body.get(\"inputs\"), is_local=is_local, is_workflow=is_workflow,\n access=visibility, user_id=user, execute_async=is_execute_async, custom_tags=tags,\n notification_email=encrypted_email, accept_language=language, context=context)\n job.save_log(logger=LOGGER, message=\"Job task submitted for execution.\", status=STATUS_ACCEPTED, progress=0)\n job = store.update_job(job)\n result = execute_process.delay(job_id=job.id, wps_url=clean_ows_url(service_url), headers=auth)\n LOGGER.debug(\"Celery pending task [%s] for job [%s].\", result.id, job.id)\n\n # local/provider process location\n location_base = \"/providers/{provider_id}\".format(provider_id=provider_id) if provider_id else \"\"\n location = \"{base_url}{location_base}/processes/{process_id}/jobs/{job_id}\".format(\n base_url=get_wps_restapi_base_url(settings),\n location_base=location_base,\n process_id=process_id,\n job_id=job.id)\n body_data = {\n \"jobID\": job.id,\n \"processID\": job.process,\n \"providerID\": provider_id, # dropped by validator if not applicable\n \"status\": map_status(STATUS_ACCEPTED),\n \"location\": location\n }\n return body_data\n","sub_path":"weaver/processes/execution.py","file_name":"execution.py","file_ext":"py","file_size_in_byte":26521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"484648886","text":"import arcade\nimport random\n\ndef menu():\n print(\"0. Beber de la botella (agua+70, gasta 1 turno y 1 sorbo).\\n\" \n \"1. Caminar (distancia+(6-12), gasta 1 turno y 15 de energia).\\n\"\n \"2. Correr (distancia+(15-21), gasta 1 turno y 25 de energia).\\n\"\n \"3. Descansar (energia+75, gasta 1 turno).\\n\"\n \"4. Mirar estado actual(GRATIS).\\n\"\n \"5. Salir.\")\n\ndef leerAccion():\n num_accion = int(input(\"Introduce la accion deseada: \"))\n\n return num_accion\n\ndef accion0(sorbos,sed):\n sorbos -= 1\n sed += 70\n print(\"Ahora tienes \", sed, \" de agua y te quedan \", sorbos, \" sorbos\")\n return sorbos, sed\n\ndef accion1(energia,distancia_recorrida,distancia_personaje,distancia_avanzada):\n energia -= 15\n distancia_recorrida = 0\n distancia_recorrida = random.randint(6, 12)\n distancia_personaje = distancia_personaje - distancia_recorrida\n distancia_avanzada = distancia_avanzada + distancia_recorrida\n print(\"Has avanzado \", distancia_recorrida, \"metros\")\n return energia,distancia_recorrida,distancia_personaje,distancia_avanzada\n\ndef accion2(energia,distancia_recorrida, distancia_personaje,distancia_avanzada):\n energia -= 25\n distancia_recorrida = 0\n distancia_recorrida = random.randint(15, 21)\n distancia_personaje = distancia_personaje - distancia_recorrida\n distancia_avanzada = distancia_avanzada + distancia_recorrida\n print(\"Has avanzado \", distancia_recorrida, \" metros\")\n return energia,distancia_recorrida, distancia_personaje,distancia_avanzada\n\ndef imprimirVariablesEstado(sorbos,distancia_personaje,distancia_a_nativos,energia,sed):\n\n print(\"Tienes \",sorbos,\" sorbos y \",sed,\" de agua\")\n print(\"Te falta por recorrer \",distancia_personaje,\"metros\")\n print(\"Los nativos estan a \",distancia_a_nativos,\" metros\")\n print(\"Tienes \",energia,\" energia\")\n\ndef finTurno (distancia_nativos_recorrida,sed,energia,distancia_avanzada):\n distancia_nativos_recorrida += 10\n distancia_a_nativos = distancia_avanzada-distancia_nativos_recorrida\n sed -= 20\n energia -= 10\n return distancia_nativos_recorrida,sed,energia,distancia_a_nativos\n\ndef comprobarEstado (sed,energia,aux,sorbos):\n aux_secundaria = True\n if (sed <= 0 and sorbos > 0):\n print(\"Estas sin agua, tienes que beber (pulsa '0')\")\n while aux_secundaria:\n num_accion = leerAccion()\n if num_accion == 1 or num_accion == 2:\n print(\"Estas demasiado sediento para esa accion\")\n else:\n aux_secundaria = False\n elif (sed <= 0 and sorbos == 0):\n print(\"Te has deshidratado y te queda agua, HAS PERDIDO\")\n aux = False\n if (energia <= 0):\n print(\"Estas sin energia, tienes que descansar (pulsa '3')\")\n while aux_secundaria:\n num_accion = leerAccion()\n if num_accion == 1 or num_accion == 2:\n print(\"Estas demasiado cansado para esa accion\")\n aux_secundaria = False\n if (sed > 0 and energia > 0):\n menu()\n num_accion = leerAccion()\n aux_sorbos = True\n while aux_sorbos:\n if num_accion == 0 and sorbos == 0:\n print(\"No te quedan sorbos, elige otra accion\")\n num_accion = leerAccion()\n else:\n aux_sorbos = False\n return aux,num_accion\n\n\ndef main():\n sorbos = 3\n distancia_personaje = 200\n distancia_nativos_recorrida = -30\n energia = 250\n sed = 140\n distancia_recorrida = 0\n distancia_avanzada = 0\n distancia_a_nativos = distancia_avanzada-distancia_nativos_recorrida\n aux = True\n num_accion = ''\n while (aux):\n aux,num_accion = comprobarEstado(sed,energia,aux,sorbos)\n if distancia_a_nativos <= 0:\n print(\"Los nativos te han alcanzado, HAS PERDIDO\")\n aux = False\n\n if num_accion == 0:\n sorbos, sed = accion0(sorbos, sed)\n distancia_nativos_recorrida, sed, energia, distancia_a_nativos = finTurno(distancia_nativos_recorrida, sed, energia,distancia_avanzada)\n\n elif num_accion == 1:\n energia, distancia_recorrida, distancia_personaje, distancia_avanzada = \\\n accion1(energia, distancia_recorrida, distancia_personaje, distancia_avanzada)\n distancia_nativos_recorrida, sed, energia, distancia_a_nativos = finTurno(distancia_nativos_recorrida, sed, energia, distancia_avanzada)\n\n elif num_accion == 2:\n energia, distancia_recorrida, distancia_personaje, distancia_avanzada = \\\n accion2(energia, distancia_recorrida, distancia_personaje, distancia_avanzada)\n distancia_nativos_recorrida, sed, energia,distancia_a_nativos = finTurno(distancia_nativos_recorrida, sed, energia, distancia_avanzada)\n\n elif num_accion == 3:\n energia += 75\n print(\"Tu energia actual es \", energia)\n distancia_nativos_recorrida, sed, energia,distancia_a_nativos = finTurno(distancia_nativos_recorrida, sed, energia, distancia_avanzada)\n\n elif num_accion == 4:\n imprimirVariablesEstado(sorbos,distancia_personaje,distancia_a_nativos, energia, sed)\n\n elif num_accion == 5:\n aux = False\n\n if distancia_a_nativos <= 10:\n print(\"Cuidado, los nativos te van a alcanzar\")\n\n if distancia_personaje <= 0:\n print(\"Has llegado a salvo al destino, HAS GANADO\")\n aux = False\n\nmain()\n\n","sub_path":"lab04-camel/lab04-camel.py","file_name":"lab04-camel.py","file_ext":"py","file_size_in_byte":5489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"489056751","text":"# encoding:utf-8\nfrom fxdayu_data.data.market_data import MarketDataFreq\n\n\ndef create_api(symbols, start, end, selectors):\n config = read_config()\n min_freq = str(min([Frequency(s.frequency) for s in selectors]))\n db_config = config.get('frequency', {}).get(min_freq, {})\n api = MarketDataFreq(**db_config)\n api.init(symbols, start, end, frequency=min_freq)\n return api\n\n\ndef write_config(**kwargs):\n import json\n json.dump(kwargs, open('db_config.json', 'w'))\n\n\ndef read_config():\n import json\n return json.load(open('db_config.json', 'r'))\n\n\ndef update_config(**kwargs):\n import json\n with open('db_config.json', 'r') as f:\n config = json.load(f)\n config.update(kwargs)\n\n json.dump(config, open('db_config.json', 'w'))\n\n\nclass Frequency(object):\n\n sorts = ['min', 'H', 'D', 'W']\n\n def __init__(self, freq):\n self.num, self.pos = self.split(freq)\n self.freq = freq\n\n def __str__(self):\n return self.freq\n\n @classmethod\n def split(cls, word):\n w = ''\n n = ''\n for letter in word:\n if letter.isdigit():\n n += letter\n else:\n w += letter\n return int(n) if len(n) else 1, cls.sorts.index(w)\n\n def __lt__(self, other):\n if self.pos < other.pos:\n return True\n elif self.pos == other.pos:\n if self.num < other.num:\n return True\n else:\n return False\n else:\n return False","sub_path":"fxdayu_data/selector/data_api.py","file_name":"data_api.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"175776590","text":"# -*- coding: utf-8 -*-\n'''\nA python wrapper for the Teamcity 9.x REST API\nFor more information see https://www.jetbrains.com/teamcity/\n'''\nimport requests\nfrom requests.utils import urlparse\nimport logging\n\ndef prepare_logger():\n '''Prepare module logger'''\n inner_logger = logging.getLogger(__name__)\n inner_logger.setLevel(logging.DEBUG)\n chanel = logging.StreamHandler()\n chanel.setLevel(logging.DEBUG)\n inner_logger.addHandler(chanel)\n return inner_logger\n\nLOGGER = prepare_logger()\n\nclass TeamcityAPI(object):\n '''Class for communication with teamcity'''\n def __init__(self, url):\n self.base_url = urlparse(url).netloc\n self.url = 'http://%s' % self.base_url\n self.session = requests.Session()\n self.session.headers.update({'Accept': 'application/json'})\n\n def prepare_url(self, url):\n '''Prepare url from methods url\n :return: string'''\n return '/'.join((self.url, url))\n\n def send_request(self, url=None, method=None, headers=None, data=None, auth=None):\n '''Send request and logging the response\n :return: Response Object'''\n url = self.prepare_url(url)\n LOGGER.info('Request url: %s', url)\n LOGGER.info('Request data: %s', data)\n response = self.session.request(method=method,\n url=url,\n headers=headers,\n data=data,\n auth=auth,\n verify=False)\n LOGGER.info('Response code: %s', response.status_code)\n LOGGER.info('Response text: %s', response.text)\n return response\n\n def httpauth(self, username, password):\n '''HTTP authorization'''\n auth = requests.auth.HTTPBasicAuth(username,\n password)\n url = self.prepare_url('httpAuth/')\n return self.session.post(url=url,\n auth=auth)\n\n def guestauth(self):\n '''Guest authorization'''\n url = self.prepare_url('guestAuth/')\n return self.session.post(url=url)\n\n def get_version(self):\n '''Get api version'''\n url = 'app/rest/version'\n headers = {'Accept': 'text/plain'}\n return self.send_request(url=url,\n method='GET',\n headers=headers)\n\n def get_users(self):\n '''Get all users'''\n url = 'app/rest/users'\n return self.send_request(url=url,\n method='GET')\n\n def get_projects(self):\n '''Get all projects'''\n url = 'app/rest/projects'\n return self.send_request(url=url,\n method='GET')\n\n def get_project(self, project_id):\n '''Get project by project_id'''\n url = 'app/rest/projects/id:%s' % project_id\n return self.send_request(url=url,\n method='GET')\n\n def get_build_types(self):\n '''Get all buildTypes'''\n url = 'app/rest/buildTypes'\n return self.send_request(url=url,\n method='GET')\n\n def get_build_type(self, build_type_id):\n '''Get buildType by build_id'''\n url = 'app/rest/buildTypes/id:%s' % build_type_id\n return self.send_request(url=url,\n method='GET')\n\n def get_builds(self):\n '''Get all builds'''\n url = 'app/rest/builds'\n return self.send_request(url=url,\n method='GET')\n\n def get_build(self, build_id):\n '''Get build by build_id'''\n url = 'app/rest/builds/%s' % build_id\n return self.send_request(url=url,\n method='GET')\n\n def get_tag(self, build_id):\n '''Get tags of build by build_id'''\n url = 'app/rest/builds/id:%s/tags' % build_id\n return self.send_request(url=url,\n method='GET')\n\n def get_artifact(self, build_id, artifact):\n '''Get artifact by build_id and artifact name'''\n url = self.prepare_url('app/rest/builds/id:%s/artifacts/content/%s' %\n (build_id, artifact))\n return self.session.get(url=url,\n stream=True)\n","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":4380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"8957612","text":"from slack_reminder import Slack\nfrom datetime import datetime\n\nTOKEN = \"TOKEN ID\"\nCHANNEL = \"CHANNEL ID\"\nSENDER_NAME = \"NOTINOTI\"\nTODAY = datetime.today()\nYEAR, MONTH, DAY = TODAY.year, TODAY.month, TODAY.day\n\nCONTENTS = f\"[{YEAR}년 {MONTH}월 {DAY}일 피어세션] 전날 학습 정리를 답글로 달아주세요.\"\n\nslack = Slack(token=TOKEN, channel=CHANNEL, username=SENDER_NAME)\nslack.send_slack_message(text=CONTENTS)\n","sub_path":"share_summary/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"131492297","text":"#!/usr/bin/env python3\n# xmlrpc_books_client.py - show a sample client that uses XML-RPC protocol\n# \nimport xmlrpc.client\n# if the verbose flag is True, XML output is \n# returned by the Server.\n# server = xmlrpc.client.ServerProxy(\"http://localhost:9000\", verbose=True)\nserver = xmlrpc.client.ServerProxy(\"http://localhost:9000\")\n\n# get list of books:\nprint(\"Books: \")\nbooks = server.get_books()\nfor book in books:\n print(\"%s\\t\\t%s\\n%s\\n%s\\t%d\\n\" %(book['id'], book['author'], \n book['title'], book['notes'], book['copies']))\n\n#################################################\n#\n# $ xmlrpc_books_client.py\n# Books: \n# 104\t\tBuffett, Jimmy\n# Tales From Margaritaville\n# Autobiography\t1\n# \n# 102\t\tCrichton, Michael\n# Jurassic Park\n# Science Fiction\t3\n# \n# 103\t\tGrisham, John\n# The Firm\n# Fiction\t2\n# \n# 101\t\tHugo, Victor\n# Les Miserables\n# Classic\t1\n# \n","sub_path":"py3/pgms/sec6/XML-RPC/xmlrpc_books_client.py","file_name":"xmlrpc_books_client.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"380102663","text":"#!/usr/bin/python2\n\n# Copyright 2012 Google Inc. All Rights Reserved.\n\"\"\"Tests for bisecting tool.\"\"\"\n\nfrom __future__ import print_function\n\n__author__ = 'shenhan@google.com (Han Shen)'\n\nimport os\nimport random\nimport sys\nimport unittest\n\nfrom cros_utils import command_executer\nfrom binary_search_tool import binary_search_state\nfrom binary_search_tool import bisect\n\nimport common\nimport gen_obj\n\n\ndef GenObj():\n obj_num = random.randint(100, 1000)\n bad_obj_num = random.randint(obj_num / 100, obj_num / 20)\n if bad_obj_num == 0:\n bad_obj_num = 1\n gen_obj.Main(['--obj_num', str(obj_num), '--bad_obj_num', str(bad_obj_num)])\n\n\ndef CleanObj():\n os.remove(common.OBJECTS_FILE)\n os.remove(common.WORKING_SET_FILE)\n print('Deleted \"{0}\" and \"{1}\"'.format(common.OBJECTS_FILE,\n common.WORKING_SET_FILE))\n\n\nclass BisectTest(unittest.TestCase):\n \"\"\"Tests for bisect.py\"\"\"\n\n def setUp(self):\n with open('./is_setup', 'w'):\n pass\n\n try:\n os.remove(binary_search_state.STATE_FILE)\n except OSError:\n pass\n\n def tearDown(self):\n try:\n os.remove('./is_setup')\n os.remove(os.readlink(binary_search_state.STATE_FILE))\n os.remove(binary_search_state.STATE_FILE)\n except OSError:\n pass\n\n class FullBisector(bisect.Bisector):\n \"\"\"Test bisector to test bisect.py with\"\"\"\n\n def __init__(self, options, overrides):\n super(BisectTest.FullBisector, self).__init__(options, overrides)\n\n def PreRun(self):\n GenObj()\n return 0\n\n def Run(self):\n return binary_search_state.Run(get_initial_items='./gen_init_list.py',\n switch_to_good='./switch_to_good.py',\n switch_to_bad='./switch_to_bad.py',\n test_script='./is_good.py',\n prune=True,\n file_args=True)\n\n def PostRun(self):\n CleanObj()\n return 0\n\n def test_full_bisector(self):\n ret = bisect.Run(self.FullBisector({}, {}))\n self.assertEquals(ret, 0)\n self.assertFalse(os.path.exists(common.OBJECTS_FILE))\n self.assertFalse(os.path.exists(common.WORKING_SET_FILE))\n\n def check_output(self):\n _, out, _ = command_executer.GetCommandExecuter().RunCommandWOutput(\n ('grep \"Bad items are: \" logs/binary_search_tool_tester.py.out | '\n 'tail -n1'))\n ls = out.splitlines()\n self.assertEqual(len(ls), 1)\n line = ls[0]\n\n _, _, bad_ones = line.partition('Bad items are: ')\n bad_ones = bad_ones.split()\n expected_result = common.ReadObjectsFile()\n\n # Reconstruct objects file from bad_ones and compare\n actual_result = [0] * len(expected_result)\n for bad_obj in bad_ones:\n actual_result[int(bad_obj)] = 1\n\n self.assertEqual(actual_result, expected_result)\n\n\nclass BisectingUtilsTest(unittest.TestCase):\n \"\"\"Tests for bisecting tool.\"\"\"\n\n def setUp(self):\n \"\"\"Generate [100-1000] object files, and 1-5% of which are bad ones.\"\"\"\n GenObj()\n\n with open('./is_setup', 'w'):\n pass\n\n try:\n os.remove(binary_search_state.STATE_FILE)\n except OSError:\n pass\n\n def tearDown(self):\n \"\"\"Cleanup temp files.\"\"\"\n CleanObj()\n\n try:\n os.remove(os.readlink(binary_search_state.STATE_FILE))\n except OSError:\n pass\n\n cleanup_list = ['./is_setup', binary_search_state.STATE_FILE,\n 'noinc_prune_bad', 'noinc_prune_good']\n for f in cleanup_list:\n if os.path.exists(f):\n os.remove(f)\n\n def runTest(self):\n ret = binary_search_state.Run(get_initial_items='./gen_init_list.py',\n switch_to_good='./switch_to_good.py',\n switch_to_bad='./switch_to_bad.py',\n test_script='./is_good.py',\n prune=True,\n file_args=True)\n self.assertEquals(ret, 0)\n self.check_output()\n\n def test_arg_parse(self):\n args = ['--get_initial_items', './gen_init_list.py', '--switch_to_good',\n './switch_to_good.py', '--switch_to_bad', './switch_to_bad.py',\n '--test_script', './is_good.py', '--prune', '--file_args']\n ret = binary_search_state.Main(args)\n self.assertEquals(ret, 0)\n self.check_output()\n\n def test_test_setup_script(self):\n os.remove('./is_setup')\n with self.assertRaises(AssertionError):\n ret = binary_search_state.Run(get_initial_items='./gen_init_list.py',\n switch_to_good='./switch_to_good.py',\n switch_to_bad='./switch_to_bad.py',\n test_script='./is_good.py',\n prune=True,\n file_args=True)\n\n ret = binary_search_state.Run(get_initial_items='./gen_init_list.py',\n switch_to_good='./switch_to_good.py',\n switch_to_bad='./switch_to_bad.py',\n test_script='./is_good.py',\n test_setup_script='./test_setup.py',\n prune=True,\n file_args=True)\n self.assertEquals(ret, 0)\n self.check_output()\n\n def test_bad_test_setup_script(self):\n with self.assertRaises(AssertionError):\n binary_search_state.Run(get_initial_items='./gen_init_list.py',\n switch_to_good='./switch_to_good.py',\n switch_to_bad='./switch_to_bad.py',\n test_script='./is_good.py',\n test_setup_script='./test_setup_bad.py',\n prune=True,\n file_args=True)\n\n def test_bad_save_state(self):\n state_file = binary_search_state.STATE_FILE\n hidden_state_file = os.path.basename(binary_search_state.HIDDEN_STATE_FILE)\n\n with open(state_file, 'w') as f:\n f.write('test123')\n\n bss = binary_search_state.MockBinarySearchState()\n with self.assertRaises(binary_search_state.Error):\n bss.SaveState()\n\n with open(state_file, 'r') as f:\n self.assertEquals(f.read(), 'test123')\n\n os.remove(state_file)\n\n # Cleanup generated save state that has no symlink\n files = os.listdir(os.getcwd())\n save_states = [x for x in files if x.startswith(hidden_state_file)]\n _ = [os.remove(x) for x in save_states]\n\n def test_save_state(self):\n state_file = binary_search_state.STATE_FILE\n\n bss = binary_search_state.MockBinarySearchState()\n bss.SaveState()\n self.assertTrue(os.path.exists(state_file))\n first_state = os.readlink(state_file)\n\n bss.SaveState()\n second_state = os.readlink(state_file)\n self.assertTrue(os.path.exists(state_file))\n self.assertTrue(second_state != first_state)\n self.assertFalse(os.path.exists(first_state))\n\n bss.RemoveState()\n self.assertFalse(os.path.islink(state_file))\n self.assertFalse(os.path.exists(second_state))\n\n def test_load_state(self):\n test_items = [1, 2, 3, 4, 5]\n\n bss = binary_search_state.MockBinarySearchState()\n bss.all_items = test_items\n bss.currently_good_items = set([1, 2, 3])\n bss.currently_bad_items = set([4, 5])\n bss.SaveState()\n\n bss = None\n\n bss2 = binary_search_state.MockBinarySearchState.LoadState()\n self.assertEquals(bss2.all_items, test_items)\n self.assertEquals(bss2.currently_good_items, set([]))\n self.assertEquals(bss2.currently_bad_items, set([]))\n\n def test_tmp_cleanup(self):\n bss = binary_search_state.MockBinarySearchState(\n get_initial_items='echo \"0\\n1\\n2\\n3\"',\n switch_to_good='./switch_tmp.py',\n file_args=True)\n bss.SwitchToGood(['0', '1', '2', '3'])\n\n tmp_file = None\n with open('tmp_file', 'r') as f:\n tmp_file = f.read()\n os.remove('tmp_file')\n\n self.assertFalse(os.path.exists(tmp_file))\n ws = common.ReadWorkingSet()\n for i in range(3):\n self.assertEquals(ws[i], 42)\n\n def test_verify_fail(self):\n bss = binary_search_state.MockBinarySearchState(\n get_initial_items='./gen_init_list.py',\n switch_to_good='./switch_to_bad.py',\n switch_to_bad='./switch_to_good.py',\n test_script='./is_good.py',\n prune=True,\n file_args=True,\n verify=True)\n with self.assertRaises(AssertionError):\n bss.DoVerify()\n\n def test_early_terminate(self):\n bss = binary_search_state.MockBinarySearchState(\n get_initial_items='./gen_init_list.py',\n switch_to_good='./switch_to_good.py',\n switch_to_bad='./switch_to_bad.py',\n test_script='./is_good.py',\n prune=True,\n file_args=True,\n iterations=1)\n bss.DoSearch()\n self.assertFalse(bss.found_items)\n\n def test_no_prune(self):\n bss = binary_search_state.MockBinarySearchState(\n get_initial_items='./gen_init_list.py',\n switch_to_good='./switch_to_good.py',\n switch_to_bad='./switch_to_bad.py',\n test_script='./is_good.py',\n test_setup_script='./test_setup.py',\n prune=False,\n file_args=True)\n bss.DoSearch()\n self.assertEquals(len(bss.found_items), 1)\n\n bad_objs = common.ReadObjectsFile()\n found_obj = int(bss.found_items.pop())\n self.assertEquals(bad_objs[found_obj], 1)\n\n def test_set_file(self):\n binary_search_state.Run(get_initial_items='./gen_init_list.py',\n switch_to_good='./switch_to_good_set_file.py',\n switch_to_bad='./switch_to_bad_set_file.py',\n test_script='./is_good.py',\n prune=True,\n file_args=True,\n verify=True)\n self.check_output()\n\n def test_noincremental_prune(self):\n ret = binary_search_state.Run(\n get_initial_items='./gen_init_list.py',\n switch_to_good='./switch_to_good_noinc_prune.py',\n switch_to_bad='./switch_to_bad_noinc_prune.py',\n test_script='./is_good_noinc_prune.py',\n test_setup_script='./test_setup.py',\n prune=True,\n noincremental=True,\n file_args=True,\n verify=False)\n self.assertEquals(ret, 0)\n self.check_output()\n\n def check_output(self):\n _, out, _ = command_executer.GetCommandExecuter().RunCommandWOutput(\n ('grep \"Bad items are: \" logs/binary_search_tool_tester.py.out | '\n 'tail -n1'))\n ls = out.splitlines()\n self.assertEqual(len(ls), 1)\n line = ls[0]\n\n _, _, bad_ones = line.partition('Bad items are: ')\n bad_ones = bad_ones.split()\n expected_result = common.ReadObjectsFile()\n\n # Reconstruct objects file from bad_ones and compare\n actual_result = [0] * len(expected_result)\n for bad_obj in bad_ones:\n actual_result[int(bad_obj)] = 1\n\n self.assertEqual(actual_result, expected_result)\n\n\nclass BisectStressTest(unittest.TestCase):\n \"\"\"Stress tests for bisecting tool.\"\"\"\n\n def test_every_obj_bad(self):\n amt = 25\n gen_obj.Main(['--obj_num', str(amt), '--bad_obj_num', str(amt)])\n ret = binary_search_state.Run(get_initial_items='./gen_init_list.py',\n switch_to_good='./switch_to_good.py',\n switch_to_bad='./switch_to_bad.py',\n test_script='./is_good.py',\n prune=True,\n file_args=True,\n verify=False)\n self.assertEquals(ret, 0)\n self.check_output()\n\n def test_every_index_is_bad(self):\n amt = 25\n for i in range(amt):\n obj_list = ['0'] * amt\n obj_list[i] = '1'\n obj_list = ','.join(obj_list)\n gen_obj.Main(['--obj_list', obj_list])\n ret = binary_search_state.Run(get_initial_items='./gen_init_list.py',\n switch_to_good='./switch_to_good.py',\n switch_to_bad='./switch_to_bad.py',\n test_setup_script='./test_setup.py',\n test_script='./is_good.py',\n prune=True,\n file_args=True)\n self.assertEquals(ret, 0)\n self.check_output()\n\n def check_output(self):\n _, out, _ = command_executer.GetCommandExecuter().RunCommandWOutput(\n ('grep \"Bad items are: \" logs/binary_search_tool_tester.py.out | '\n 'tail -n1'))\n ls = out.splitlines()\n self.assertEqual(len(ls), 1)\n line = ls[0]\n\n _, _, bad_ones = line.partition('Bad items are: ')\n bad_ones = bad_ones.split()\n expected_result = common.ReadObjectsFile()\n\n # Reconstruct objects file from bad_ones and compare\n actual_result = [0] * len(expected_result)\n for bad_obj in bad_ones:\n actual_result[int(bad_obj)] = 1\n\n self.assertEqual(actual_result, expected_result)\n\n\ndef Main(argv):\n num_tests = 2\n if len(argv) > 1:\n num_tests = int(argv[1])\n\n suite = unittest.TestSuite()\n for _ in range(0, num_tests):\n suite.addTest(BisectingUtilsTest())\n suite.addTest(BisectingUtilsTest('test_arg_parse'))\n suite.addTest(BisectingUtilsTest('test_test_setup_script'))\n suite.addTest(BisectingUtilsTest('test_bad_test_setup_script'))\n suite.addTest(BisectingUtilsTest('test_bad_save_state'))\n suite.addTest(BisectingUtilsTest('test_save_state'))\n suite.addTest(BisectingUtilsTest('test_load_state'))\n suite.addTest(BisectingUtilsTest('test_tmp_cleanup'))\n suite.addTest(BisectingUtilsTest('test_verify_fail'))\n suite.addTest(BisectingUtilsTest('test_early_terminate'))\n suite.addTest(BisectingUtilsTest('test_no_prune'))\n suite.addTest(BisectingUtilsTest('test_set_file'))\n suite.addTest(BisectingUtilsTest('test_noincremental_prune'))\n suite.addTest(BisectTest('test_full_bisector'))\n suite.addTest(BisectStressTest('test_every_obj_bad'))\n suite.addTest(BisectStressTest('test_every_index_is_bad'))\n runner = unittest.TextTestRunner()\n runner.run(suite)\n\n\nif __name__ == '__main__':\n Main(sys.argv)\n","sub_path":"app/src/main/java/com/syd/source/aosp/external/toolchain-utils/binary_search_tool/test/binary_search_tool_tester.py","file_name":"binary_search_tool_tester.py","file_ext":"py","file_size_in_byte":14168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"240055077","text":"import torch.nn as nn\nimport torch\n\n\nclass DPCCA(nn.Module):\n \"\"\" channels: The number of channels of S and D.\n ratio: The ratio in channel-attention mechanism. \"\"\"\n def __init__(self, channels, ratio=2):\n super(DPCCA, self).__init__()\n self.gap = nn.AdaptiveAvgPool2d(1)\n\n self.left_1 = nn.Sequential(\n nn.Linear(channels, channels // ratio),\n nn.ReLU(inplace=True)\n )\n self.right_1 = nn.Sequential(\n nn.Linear(channels, channels // ratio),\n nn.ReLU(inplace=True)\n )\n\n self.left_2 = nn.Sequential(\n nn.Linear(channels // ratio, channels),\n nn.Sigmoid()\n )\n self.right_2 = nn.Sequential(\n nn.Linear(channels // ratio, channels),\n nn.Sigmoid()\n )\n\n def forward(self, S, D):\n # S: The refined shallow feature maps from SFRTrans. D: The deep feature maps in decoder.\n left_embedding = self.gap(S).squeeze()\n right_embedding = self.gap(D).squeeze()\n\n left_embedding = left_embedding + right_embedding\n left_embedding = self.left_1(left_embedding)\n\n right_embedding = self.right_1(right_embedding)\n\n fusion_embedding = left_embedding + right_embedding\n\n left_embedding = self.left_2(fusion_embedding).unsqueeze(-1).unsqueeze(-1)\n right_embedding = self.right_2(fusion_embedding).unsqueeze(-1).unsqueeze(-1)\n\n return torch.concat([S * left_embedding, D * right_embedding], dim=1)\n\n\nif __name__ == '__main__':\n\n _S = torch.rand(3, 64, 48, 48).cuda()\n _D = torch.rand(3, 64, 48, 48).cuda()\n\n dpcca = DPCCA(channels=64, ratio=2).cuda()\n output = dpcca(_S, _D)\n\n print(output.shape)\n","sub_path":"models/dpcca.py","file_name":"dpcca.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"6853744","text":"# -*- coding: utf-8 -*-\n#pylint: skip-file\nimport numpy as np\nimport theano\nimport theano.tensor as T\nfrom utils_pg import *\n\nclass WordProbLayer(object):\n def __init__(self, layer_input, shape, is_predicting, has_lvt_trick):\n prefix = \"WordProbLayer_\"\n if has_lvt_trick:\n self.ds, self.ac, self.y_emb, self.cp_idx, self.lvt_dict = layer_input\n self.hidden_size, self.dim_ac, self.dim_y, self.dict_size, self.lvt_dict_size = shape\n else:\n self.ds, self.ac, self.y_emb, self.cp_idx = layer_input\n self.hidden_size, self.dim_ac, self.dim_y, self.dict_size = shape\n\n self.w_ds = init_weights((self.hidden_size, self.hidden_size), prefix + \"W_ds\", sample = \"xavier\")\n self.b_ds = init_bias(self.hidden_size, prefix + \"b_ds\")\n self.w_ac = init_weights((self.dim_ac, self.hidden_size), prefix + \"W_ac\", sample = \"xavier\")\n self.w_y = init_weights((self.dim_y, self.hidden_size), prefix + \"W_y\", sample = \"xavier\")\n self.w_logit = init_weights((self.hidden_size, self.dict_size), prefix + \"W_logit\", sample = \"xavier\")\n self.b_logit = init_bias(self.dict_size, prefix + \"b_logit\")\n \n self.w_ds_cp = init_weights((self.hidden_size, self.hidden_size), prefix + \"W_ds_cp\", sample = \"xavier\")\n self.b_ds_cp = init_bias(self.hidden_size, prefix + \"b_ds_cp\")\n self.w_ac_cp = init_weights((self.dim_ac, self.hidden_size), prefix + \"W_ac_cp\", sample = \"xavier\")\n self.w_y_cp = init_weights((self.dim_y, self.hidden_size), prefix + \"W_y_cp\", sample = \"xavier\")\n self.v = init_weights((self.hidden_size, 1), prefix + \"v\", sample = \"xavier\")\n \n \n self.params = [self.w_ds, self.b_ds, self.w_ac, self.w_y,\n self.w_ds_cp, self.b_ds_cp, self.w_ac_cp, self.w_y_cp, self.v]\n\n if has_lvt_trick:\n self.sub_w_logit = self.w_logit[:, self.lvt_dict]\n self.sub_b_logit = self.b_logit[self.lvt_dict]\n\n self.sub_params = [(self.w_logit, self.sub_w_logit, (self.hidden_size, self.lvt_dict_size)),\n (self.b_logit, self.sub_b_logit, (self.lvt_dict_size, ))]\n else:\n self.params += [self.w_logit, self.b_logit]\n\n \n # copy\n h_cp = T.dot(self.ds, self.w_ds_cp) + T.dot(self.y_emb, self.w_y_cp) + T.dot(self.ac, self.w_ac_cp) + self.b_ds_cp\n g = T.nnet.sigmoid(T.dot(h_cp, self.v))\n g = T.addbroadcast(g, g.ndim - 1)\n\n logit = T.dot(self.ds, self.w_ds) + T.dot(self.y_emb, self.w_y) + T.dot(self.ac, self.w_ac) + self.b_ds\n logit = T.tanh(logit)\n logit = T.dot(logit, self.sub_w_logit) + self.sub_b_logit if has_lvt_trick else T.dot(logit, self.w_logit) + self.b_logit\n\n old_shape = logit.shape\n\n copyed = T.zeros_like(logit)\n\n if is_predicting:\n copyed = T.inc_subtensor(copyed[T.arange(copyed.shape[0]), self.cp_idx], T.cast(1.0, dtype = theano.config.floatX))\n \n self.y_pred = T.nnet.softmax(logit) * g + (1 - g) * copyed\n else:\n ida = T.arange(self.cp_idx.shape[0]).reshape((-1,1))\n idb = T.arange(self.cp_idx.shape[1])\n copyed = T.inc_subtensor(copyed[ida, idb, self.cp_idx], T.cast(1.0, dtype = theano.config.floatX))\n \n y_dec_h = T.nnet.softmax(logit.reshape((old_shape[0] * old_shape[1], old_shape[2]))).reshape(old_shape)\n self.y_pred = y_dec_h * g + (1 - g) * copyed\n\n\n","sub_path":"word_prob_layer.py","file_name":"word_prob_layer.py","file_ext":"py","file_size_in_byte":3494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"625596035","text":"from datetime import *\nimport logging\nimport os\n\nclass MyLogger(object):\n\n\tlogger = None\n\tfileHandler = None\n\tlogFullName = None\n\n\tdef __init__(self, logName):\n\t \tself.logger = logging.getLogger(logName)\n\t \tlogPath = 'logs/'+logName\n\t \tif not os.path.exists(logPath):\n\t \t\tos.makedirs(logPath)\n\t \tself.logFullName = logPath + '/' + datetime.today().strftime('%Y-%m-%d')\n\n\tdef __initFileHandler(self):\n\t\tself.fileHandler = logging.FileHandler(self.logFullName)\n\t\tformatter = logging.Formatter('%(levelname)s: %(message)s, %(asctime)s', '%Y-%m-%d %H:%M:%S')\n\t\tself.fileHandler.setFormatter(formatter)\n\t\tself.logger.addHandler(self.fileHandler)\n\t\tself.logger.setLevel(logging.DEBUG)\n\n\tdef __closeFileHandler(self):\n\t\tself.fileHandler.flush()\n\t\tself.logger.removeHandler(self.fileHandler)\n\t\tself.fileHandler.close()\n\n\tdef error(self, msg):\n\t\tself.__initFileHandler()\n\t\tself.logger.error(msg)\n\t\tself.__closeFileHandler()\n\n\tdef info(self, msg):\n\t\tself.__initFileHandler()\n\t\tself.logger.info(msg)\n\t\tself.__closeFileHandler()\n\n\tdef warn(self, msg):\n\t\tself.__initFileHandler()\n\t\tself.logger.warn(msg)\n\t\tself.__closeFileHandler()\n\n# logger = MusicLogger('test')\n# logger.error('aass')\n# logger.info('aass')\n# logger.warn('aass')\n","sub_path":"python/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"563649797","text":"import pyttsx3 \r\nimport speech_recognition as sr \r\nimport datetime\r\nimport wikipedia \r\nimport webbrowser\r\nimport os\r\nimport smtplib\r\n\r\nengine = pyttsx3.init('sapi5')\r\nvoices = engine.getProperty('voices')\r\n\r\nengine.setProperty('voice', voices[0].id)\r\n\r\ndef speak(audio):\r\n engine.say(audio)\r\n engine.runAndWait()\r\n\r\ndef greet():\r\n hour = int(datetime.datetime.now().hour)\r\n if hour>=0 and hour<12:\r\n speak(\"Good Morning!\")\r\n\r\n elif hour>=12 and hour<18:\r\n speak(\"Good Afternoon!\") \r\n\r\n else:\r\n speak(\"Good Evening!\") \r\n\r\n speak(\"Hello sir I am Alpha always ready for your service. How may I help you ?\") \r\n\r\ndef order():\r\n \r\n\r\n r = sr.Recognizer()\r\n with sr.Microphone() as source:\r\n \r\n print(\"Listening...\")\r\n \r\n r.pause_threshold = 1\r\n audio = r.listen(source)\r\n\r\n try:\r\n print(\"Recognizing...\") \r\n command = r.recognize_google(audio, language='en-in')\r\n print(f\"User said: {command}\\n\")\r\n\r\n except Exception as e:\r\n \r\n print(\"please say that again\") \r\n return \"None\"\r\n return command\r\n\r\ndef sendEmail(to, content):\r\n server = smtplib.SMTP('smtp.gmail.com', 587)\r\n server.ehlo()\r\n server.starttls()\r\n server.login('anonymousguy759@gmail.com', '12345678c#')\r\n server.sendmail('anonymousguy759@gmail.com', to, content)\r\n server.close()\r\n\r\nif __name__ == \"__main__\":\r\n greet()\r\n while True:\r\n \r\n command = order().lower()\r\n\r\n \r\n if 'wikipedia' in command:\r\n speak('Searching Wikipedia...')\r\n command = command.replace(\"wikipedia\", \"\")\r\n results = wikipedia.summary(command, sentences=2)\r\n speak(\"According to Wikipedia\")\r\n print(results)\r\n speak(results)\r\n\r\n elif 'open youtube' in command:\r\n speak(\"opening youtube sir\")\r\n webbrowser.open(\"youtube.com\")\r\n\r\n elif 'open google' in command:\r\n speak(\"opening google sir\")\r\n webbrowser.open(\"google.com\")\r\n\r\n elif 'open stackoverflow' in command:\r\n webbrowser.open(\"stackoverflow.com\") \r\n\r\n \r\n\r\n elif 'time' in command:\r\n strTime = datetime.datetime.now().strftime(\"%H:%M:%S\") \r\n speak(f\"Sir, the time is {strTime}\")\r\n print(f\"Sir, the time is {strTime}\")\r\n\r\n \r\n elif 'email' in command:\r\n try:\r\n speak(\"Start dictating me your email sir\")\r\n content = order()\r\n to = input(\"Enter the email id of receiver: \") \r\n sendEmail(to, content)\r\n speak(\"Email has been sent!\")\r\n except Exception as e:\r\n print(e)\r\n speak(\"I am really very sorry sir the mail was not sent.\") \r\n elif 'mail' in command:\r\n try:\r\n speak(\"Start dictating me your email sir\")\r\n content = order()\r\n to = input(\"Enter the email id of receiver: \") \r\n sendEmail(to, content)\r\n speak(\"Email has been sent!\")\r\n except Exception as e:\r\n print(e)\r\n speak(\"I am really very sorry sir the mail was not sent.\") \r\n elif 'whatsapp' in command:\r\n speak(\"Opening whats app sir\")\r\n webbrowser.open(\"web.whatsapp.com\")\r\n elif 'music' in command:\r\n music_dir = 'C:\\\\Users\\\\rahul_qmiywj7\\\\Desktop\\\\songs'\r\n speak(\"Playing your playlist sir\")\r\n songs = os.listdir(music_dir)\r\n print(songs)\r\n os.startfile(os.path.join(music_dir , songs[0]))\r\n elif 'song' in command:\r\n music_dir = 'C:\\\\Users\\\\rahul_qmiywj7\\\\Desktop\\\\songs'\r\n speak(\"Playing your playlist sir\")\r\n songs = os.listdir(music_dir)\r\n print(songs)\r\n os.startfile(os.path.join(music_dir , songs[0]))\r\n elif 'bye' in command:\r\n speak (\"Good Bye sir and have a nice day\")\r\n quit()\r\n elif 'how are you' in command:\r\n speak(\"I AM FINE SIR, how are you..?\")\r\n elif 'good' in command:\r\n speak(\"good to hear that sir!!\")\r\n elif 'fine' in command:\r\n speak(\"good to hear that sir!!\")\r\n \r\n \r\n elif 'turn off' in command:\r\n speak(\"do you really want to turn off sir?\")\r\n reply = order()\r\n if 'yes' in reply:\r\n speak(\"Turning off your laptop sir, go take some rest and have a nice day sir, good bye\")\r\n os.system(\"shutdown /s /t 1\")\r\n else:\r\n speak(\"As you wish sir\")\r\n elif 'shutdown' in command:\r\n speak(\"do you really want to turn off sir?\")\r\n reply = order()\r\n if 'yes' in reply:\r\n speak(\"Turning off your laptop sir, go take some rest and have a nice day sir, good bye\")\r\n os.system(\"shutdown /s /t 1\")\r\n else:\r\n speak(\"As you wish sir\")\r\n \r\n elif 'open class' in command:\r\n speak(\"Opening your class sir\")\r\n webbrowser.open('https://cuchd.blackboard.com/ultra/course')\r\n elif 'restart' in command:\r\n speak(\"Do you really want to restart sir?\")\r\n reply = order()\r\n if 'yes' in reply:\r\n speak(\"Restarting your system sir, will be right back\")\r\n os.system(\"shutdown /r /t 1\")\r\n else:\r\n speak(\"As you wish sir\")\r\n\r\n","sub_path":"Alpha.py","file_name":"Alpha.py","file_ext":"py","file_size_in_byte":5612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"258703699","text":"#!/usr/bin/env python\n\nimport pygame\nfrom constants import *\nimport items\n\n# Updated to read map from file with tiles separated by spaces\n\nclass Map(object):\n def __init__(self, filename, items={}):\n # self.items format: (x, y):\"Name###\" where ### is the amount (001-999)\n self.map = self.convertfile(filename)\n self.wall = 1\n self.floor = 0\n self.size = TILESIZE\n self.items = items\n\n def convertfile(self, filename):\n file = open(filename, \"r\")\n matrix = []\n for line in file:\n line = line.strip().split(\" \")\n line = [eval(x) for x in line]\n matrix.append(line)\n file.close()\n\n return matrix\n\n def getmap(self, coords):\n return self.map[coords[1]][coords[0]]\n\n def removeitem(self, coords): \n if coords in self.items:\n del self.items[coords]\n \n def additem(self, position, item):\n self.items[position] = item # use a tuple or list for position\n \n def drawmap(self, screen):\n for y in xrange(len(self.map)):\n for x in xrange(len(self.map[0])):\n if self.map[y][x] == 1:\n coordinates = (x*self.size, y*self.size, self.size, self.size)\n pygame.draw.rect(screen, RED, coordinates)\n elif self.map[y][x] == 0:\n pass\n self.drawmapitems(screen)\n\n def drawmapitems(self, screen):\n for itemcoord in self.items:\n self.drawitem(itemcoord, screen)\n \n def drawitem(self, coords, screen):\n empty = (TILESIZE - ITEMSIZE)/2\n coordinates = (coords[0]*TILESIZE+empty, coords[1]*TILESIZE+empty, \n ITEMSIZE, ITEMSIZE)\n pygame.draw.rect(screen, BLUE, coordinates)\n","sub_path":"OldPyGame/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"153532494","text":"######################################################################################################\n#TCPserver.py\n#!/usr/bin/python \n \nimport socket \n \ns = socket.socket() \nport = 11111 \n \ns.bind(('', port)) \n \ns.listen(5) \n \nwhile True:\n c, addr = s.accept()\n data = c.recv(1024) \n print('Address:', addr, 'Data:', data)\n \n mylist = list(data.split(':'))\n intlist = list()\n for i in range(0,len(mylist)):\n intlist.append(int(mylist[i]))\n intlist.sort()\n c.send(str(intlist))\n c.close() \n#######################################################################################################\n#TCPclient.py\n#!/usr/bin/python \nimport sys\nimport socket \n \narglen = len(sys.argv)\nif arglen < 3:\n print('please run as python TCPclient.py ')\n exit()\ndata = str()\ndata = data + str(sys.argv[2])\nfor i in range(3,arglen):\n data = data + ':' + str(sys.argv[i])\n \ns = socket.socket() \n \nport = 11111 \n \ns.connect((sys.argv[1], port))\ns.send(data)\nprint(s.recv(1024))\ns.close\n#######################################################################################################\n#UDPserver.py\n#!/usr/bin/python\nimport socket\ns = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\ns.bind(('', 22222))\nwhile True:\n data,addr = s.recvfrom(1024)\n print('Address:', addr, 'Data:', data)\n mylist = list(data.split(':'))\n intlist = list()\n for i in range(0,len(mylist)):\n intlist.append(int(mylist[i]))\n intlist.sort()\n s.sendto(str(intlist),addr)\n#######################################################################################################\n#UDPclient.py\n#!/usr/bin/python\nimport socket\nimport sys\n \narglen = len(sys.argv)\nif arglen < 3:\n print('please run as python UDPclient.py ')\n exit()\n \ns = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\nport = 22222\naddr = sys.argv[1]\ndata = str()\ndata = data + sys.argv[2]\nfor i in range(3,len(sys.argv)):\n data = data + ':' + sys.argv[i]\ns.sendto(data,(addr,port))\ndata,addr = s.recvfrom(1024)\nprint(data)\n","sub_path":"network_31082013.py","file_name":"network_31082013.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"504797819","text":"import requests\r\nfrom ex_data import API_KEY, APP_ID\r\nfrom datetime import datetime\r\n\r\n\r\n#----------------------------------------------------Nutri API------------------------------------------------------#\r\nEX_ENDPOINT = \" https://trackapi.nutritionix.com/v2/natural/exercise\"\r\n\r\n\r\nresposta = input(\"Tell me which exercises you did: \")\r\n\r\nparams = {\r\n \"query\": resposta,\r\n \"gender\":\"male\",\r\n \"weight_kg\":75,\r\n \"height_cm\":175,\r\n \"age\":31\r\n}\r\n\r\nHEADERS ={\r\n \"x-app-id\": APP_ID,\r\n \"x-app-key\": API_KEY,\r\n \"Content-Type\": \"application/json\"\r\n}\r\n\r\n\r\nex_response = requests.post(url=EX_ENDPOINT, json=params, headers=HEADERS)\r\nresult = ex_response.json()\r\nprint(ex_response.text)\r\ntoday = datetime.now().strftime(\"%d/%m/%Y\")\r\ntoday_time = datetime.now().strftime(\"%H:%M\")\r\n\r\n\r\n\r\n# #----------------------------------------------------Sheety API------------------------------------------------------#\r\nSHEETY_ENDPOINT = \"https://api.sheety.co/c6ca40e3930a12e07ef9c74d91a890ff/myWorkouts/página1\"\r\n\r\n\r\nfor exercise in result[\"exercises\"]:\r\n sheet_inputs = {\r\n \"página1\": {\r\n \"date\": today,\r\n \"time\": today_time,\r\n \"exercise\": exercise[\"name\"].title(),\r\n \"duration\": exercise[\"duration_min\"],\r\n \"calories\": exercise[\"nf_calories\"]\r\n }\r\n }\r\n\r\n sheet_response = requests.post(SHEETY_ENDPOINT, json=sheet_inputs)\r\n\r\n print(sheet_response.text)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"570976713","text":"import json\n\n\nclass Lineup_Status_JSON():\n\n def __init__(self, settings, device):\n self.config = settings\n self.device = device\n\n def get_lineup_status_json(self):\n station_scanning = self.device.station_scan.scanning()\n if station_scanning:\n jsonlineup = self.scan_in_progress()\n elif not self.device.channels.get_station_total():\n jsonlineup = self.scan_in_progress()\n else:\n jsonlineup = self.not_scanning()\n return json.dumps(jsonlineup, indent=4)\n\n def scan_in_progress(self):\n channel_count = self.device.channels.get_station_total()\n jsonlineup = {\n \"ScanInProgress\": \"true\",\n \"Progress\": 99,\n \"Found\": channel_count\n }\n return jsonlineup\n\n def not_scanning(self):\n jsonlineup = {\n \"ScanInProgress\": \"false\",\n \"ScanPossible\": \"true\",\n \"Source\": self.config.dict[\"dev\"][\"reporting_tuner_type\"],\n \"SourceList\": [self.config.dict[\"dev\"][\"reporting_tuner_type\"]],\n }\n return jsonlineup\n","sub_path":"fHDHR/api/hub/files/lineup_status_json.py","file_name":"lineup_status_json.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"189867876","text":"import numpy as np\nimport threading\nimport socket\nimport numpy\nimport sys\nimport pickle\n\n\nHOST = \"localhost\"\nPORT = 5551\nMAX_AMOUNT = 50\n\n\nclass Server:\n\n def __init__(self, *args, **kwargs):\n try:\n if len(sys.argv[1:]) == 2:\n self.args = [int(x) for x in sys.argv[1:]]\n else:\n raise ValueError\n except ValueError:\n print('Usage: server.py number_of_clients seconds_for_timeout')\n return\n self.kwargs = kwargs\n self.s = socket.socket()\n self.s.bind((HOST, PORT))\n print(f'Server hostname: {HOST}:{PORT}')\n self.s.listen()\n self.initAThread()\n\n def initAThread(self):\n try:\n threads = []\n self.s.settimeout(self.args[1])\n for i in range(self.args[0]):\n (conn, addr) = self.s.accept()\n t = threading.Thread(target=self.findRequest, args=(conn,))\n threads.append(t)\n for t in threads:\n t.start()\n for t in threads:\n t.join()\n except socket.timeout:\n print(f'Connection timed out after {self.args[1]} seconds')\n return\n\n def findRequest(self, conn):\n while True:\n try:\n fromClient = pickle.loads(conn.recv(1024))\n k, lst = *fromClient, list(fromClient.values())[0]\n print(k, lst)\n if k == 'q':\n conn.close()\n break\n elif k == 'p':\n info = pickle.dumps(self.getPowerGraph(lst))\n conn.send(info)\n elif k == 's':\n info = pickle.dumps(self.getSineGraph(lst))\n conn.send(info)\n except ConnectionResetError:\n return\n except EOFError:\n break\n\n def p(self, f):\n def wrapper(*args, **kwargs):\n result = f(*args, **kwargs)\n print(np.min(result), np.max(result))\n return result\n return wrapper\n\n @p\n def getPowerGraph(self, x_lst):\n x = np.arange(x_lst[1], x_lst[2])\n y = MAX_AMOUNT * (np.power(x, x_lst[0]))\n info = [x, y]\n return info\n\n @p\n def getSineGraph(self, lst):\n x = np.arange(0, 1, 1 / MAX_AMOUNT)\n y = np.sin(x * lst * np.pi)\n info = [x, y]\n return info\n\n\nif __name__ == \"__main__\":\n Server()\n","sub_path":"3_IRC-Client/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"320541587","text":"from cli import *\nfrom ilog import log, Ilogger\nfrom dijkstra import shortestPath\n\nfrom pexpect import EOF, TIMEOUT, spawn\n\n__all__ = ['ExceptionDevice', 'Device']\n\nclass ExceptionDevice(Exception):\n '''Raised for Device exceptions.\n '''\n\nclass Device(SSH, Telnet):\n def __init__(self, device_name, mgt_method, *args, **kwargs):\n self.device_name = device_name\n self.mgt_method = mgt_method\n\n self.modes = {}\n\n self.graph = {}\n self.path_cmd = {}\n\n self.auto_response = {}\n\n self.max_timeout = 30\n\n kwargs['logger'] = Ilogger(device_name)\n self.logger = kwargs['logger']\n\n self.prompt = kwargs.get('prompt', '[#$>]')\n\n if not self.device_name:\n raise ExceptionDevice('Unknown device NAME')\n if self.mgt_method.lower() == 'ssh':\n # SSH.__init__(self, timeout=kwargs.get('timeout', 30), maxread=kwargs.get('maxread', 2000), \n # searchwindowsize=kwargs.get('searchwindowsize', None), logfile=kwargs.get('logfile', None), \n # cwd=kwargs.get('cwd', None), env=kwargs.get('env', None), ignore_sighup=kwargs.get('ignore_sighup', None), \n # echo=kwargs.get('echo', None), encoding=kwargs.get('encoding', None), \n # codec_errors=kwargs.get('codec_errors', 'strict'),\n # host=kwargs.get('host', ''), port=kwargs.get('port', '22'), \n # username=kwargs.get('username', ''), password=kwargs.get('password', ''), \n # options=kwargs.get('options', ''), prompt=kwargs.get('prompt', '[#$]'), logger=kwargs.get('logger', None))\n self.logger.debug('Connect via ssh')\n SSH.__init__(self, *args, **kwargs)\n elif self.mgt_method.lower() == 'telnet':\n # Telnet.__init__(self, timeout=kwargs.get('timeout', 30), maxread=kwargs.get('maxread', 2000), \n # searchwindowsize=kwargs.get('searchwindowsize', None), logfile=kwargs.get('logfile', None), \n # cwd=kwargs.get('cwd', None), env=kwargs.get('env', None), ignore_sighup=kwargs.get('ignore_sighup', None), \n # echo=kwargs.get('echo', None), encoding=kwargs.get('encoding', None), \n # codec_errors=kwargs.get('codec_errors', 'strict'),\n # host=kwargs.get('host', ''), port=kwargs.get('port', '23'), \n # username=kwargs.get('username', ''), password=kwargs.get('password', ''), \n # prompt=kwargs.get('prompt', '[#$>]'), logger=kwargs.get('logger', None))\n self.logger.debug('Connect via telnet')\n Telnet.__init__(self, *args, **kwargs)\n else:\n raise ExceptionDevice('Unknown MGT-METHOD for %s' % self.device_name)\n\n def connect(self):\n if self.mgt_method.lower() == 'ssh':\n self.logger.info('Connect via ssh')\n return SSH.connect(self)\n elif self.mgt_method.lower() == 'telnet':\n self.logger.info('Connect via telnet')\n return Telnet.connect(self)\n else:\n raise ExceptionDevice('Unknown MGT-METHOD for %s' % self.device_name)\n\n def disconnect(self):\n if self.mgt_method.lower() == 'ssh':\n return SSH.disconnect(self)\n elif self.mgt_method.lower() == 'telnet':\n return Telnet.disconnect(self)\n else:\n raise ExceptionDevice('Unknown MGT-METHOD for %s' % self.device_name)\n \n def is_connected(self):\n if self.mgt_method.lower() == 'ssh':\n return SSH.is_connected(self)\n elif self.mgt_method.lower() == 'telnet':\n return Telnet.is_connected(self)\n else:\n raise ExceptionDevice('Unknown MGT-METHOD for %s' % self.device_name)\n\n def add_mode(self, mode, pattern):\n '''\n Add mode for device, pattern is the prompt of the mode.\n '''\n self.modes[pattern] = mode\n\n def add_path(self, source, destination, cmd,timeout = 30):\n '''\n Provide the path from source mode to destination mode.\n source: source mode\n destination: destination mode\n timeout: the expect timeout for the path\n '''\n self.max_timeout = max(self.max_timeout, timeout)\n if self.graph.has_key(source):\n self.graph[source].update({destination: timeout})\n else:\n self.graph[source] = {destination: timeout}\n self.path_cmd[(source, destination)] = cmd\n\n def add_auto_response(self, pattern, cmd):\n '''\n if expect the pattern, cmd will be sent automatically.\n '''\n self.auto_response[pattern] = cmd\n\n def cmd(self, cmds, *args, **kwargs):\n '''\n send commands in this spawn session.\n '''\n tmp_cmd_list = cmds.splitlines()\n without_waiting = kwargs.get('without_waiting', False)\n get_mode = kwargs.get('get_mode', False)\n prompt = kwargs.get('prompt', None)\n action = kwargs.get('action', None)\n p_a_keypair = dict(zip(prompt, action)) if prompt else None\n cur_mode = None\n cur_buffer = ''\n cmd_list = [cmd.strip() for cmd in tmp_cmd_list if len(cmd.strip()) != 0 and cmd.strip()[0] != '#'] if not get_mode else ['',]\n log.debug('cmd_list %r' % cmd_list)\n exps = self.auto_response.keys() + self.modes.keys() + [EOF, TIMEOUT] if not prompt else self.auto_response.keys() + prompt + [EOF, TIMEOUT]\n for cmd in cmd_list:\n self.sendline(cmd)\n while True:\n idx = self.expect(exps, timeout = kwargs.get('timeout', self.max_timeout))\n if idx < len(self.auto_response):\n cur_buffer = cur_buffer + self.before\n self.sendline(self.auto_response[exps[idx]])\n elif prompt and idx < len(self.auto_response) + len(prompt):\n cur_buffer = cur_buffer + self.before\n if p_a_keypair[exps[idx]]:\n self.sendline(p_a_keypair[exps[idx]])\n continue\n break\n elif prompt is None and idx < len(self.auto_response) + len(self.modes):\n cur_mode = self.modes[exps[idx]]\n cur_buffer = cur_buffer + self.before\n break\n elif idx == len(exps) - 1:\n cur_buffer = cur_buffer + self.before\n raise ExceptionDevice('Timeout to hit any prompt. current buffer: \\n%s\\n' % cur_buffer)\n else:\n raise ExceptionDevice('EOF')\n return cur_mode if get_mode else cur_buffer\n\n def get_cur_mode(self):\n '''\n Return the current mode.\n '''\n return self.cmd('', get_mode=True)\n\n def to_mode(self, mode):\n '''\n Get to the mode which you want to arive, use the dijkstra algorithm to find\n the shortest path.\n '''\n cur_mode = self.get_cur_mode()\n path = shortestPath(self.graph, cur_mode, mode)\n if len(path) != 1:\n cur = path.pop(0)\n while len(path) != 0:\n next = path.pop(0)\n self.cmd(self.path_cmd[(cur, next)])\n cur = next\n cur_mode = cur\n return cur_mode\n\n","sub_path":"iut/dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":7345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"190013925","text":"# -*- coding: utf-8 -*-\r\nimport os \r\nimport skimage.io as io\r\nimport random\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport cv2\r\n\r\n\r\n\r\ndef add_layer(inputs , \r\n in_size, \r\n out_size,\r\n #n_layer, \r\n keep_prob=None,\r\n activation_function=None):\r\n ## add one more layer and return the output of this layer\r\n\r\n Weights= tf.Variable(tf.random_normal([in_size, out_size]),name='W')\r\n biases = tf.Variable(tf.zeros([out_size])+0.1, name='b')\r\n Wx_plus_b = tf.add(tf.matmul(inputs,Weights), biases)\r\n\r\n if keep_prob is not None:\r\n Wx_plus_b = tf.nn.dropout(Wx_plus_b, keep_prob)\r\n\r\n if activation_function is None:\r\n outputs=Wx_plus_b\r\n else:\r\n outputs= activation_function(Wx_plus_b)\r\n\r\n return outputs\r\n\r\n#a = [10,446,612,745,709,487]\r\n\r\ndef data_train(d):#train_size=1,test_size=1):\r\n train_image = []\r\n train_lable = []\r\n #for _ in range(0,train_size+1):\r\n #i = random.randint(1,1000)\r\n i = d#\r\n ad_im = './data/train_data_jpg/image/' + str(i)+ '.jpg' \r\n images = cv2.imread(ad_im)\r\n images_hsv = cv2.cvtColor(images,cv2.COLOR_BGR2HSV)\r\n ad_la = './data/train_data_jpg/lable/' + str(i+1)+ '.jpg'\r\n lables = cv2.imread(ad_la,0)\r\n \r\n for width in range(0, 480): \r\n for high in range(0, 640):\r\n b,g,r = images[width, high]/255.0\r\n h,s,v = images_hsv[width, high]/255.0\r\n xx = [b,g,r,h,s,v]\r\n train_image.append(xx) \r\n yu = int(lables[width, high])\r\n if yu == 0 :\r\n yy = [1.0 ,0.0 ,0.0 ,0.0 ,0.0 ]#球\r\n elif yu == 50 :\r\n yy = [0.0, 1.0, 0.0, 0.0, 0.0]#场线\r\n elif yu == 100 :\r\n yy = [0.0, 0.0, 1.0, 0.0, 0.0]#障碍物\r\n elif yu == 200 :\r\n yy = [0.0, 0.0, 0.0, 1.0, 0.0]#场地\r\n else :\r\n yy = [0.0, 0.0, 0.0, 0.0, 1.0]#其他\r\n train_lable.append(yy)\r\n\r\n #print(np.shape(train_image)) \r\n #print(np.shape(train_lable))\r\n return train_image ,train_lable\r\n\r\ndef data_test():\r\n #生成测试集\r\n test_image = []\r\n test_lable = []\r\n #for _ in range(0,test_size+1):\r\n i = random.randint(1,100)\r\n #i = d\r\n ad_im = './data/test_data/image/' + str(i)+ '.jpg' \r\n images = cv2.imread(ad_im)\r\n images_hsv = cv2.cvtColor(images,cv2.COLOR_BGR2HSV)\r\n ad_la = './data/test_data/lable/' + str(i)+ '.jpg'\r\n lables = cv2.imread(ad_la,0)\r\n \r\n for width in range(0, 480): \r\n for high in range(0, 640):\r\n b,g,r = images[width, high]/255.0\r\n h,s,v = images_hsv[width, high]/255.0\r\n xx = [b,g,r,h,s,v]\r\n test_image.append(xx) \r\n yu = int(lables[width, high])\r\n if yu == 0 :\r\n yy = [1.0 ,0.0 ,0.0 ,0.0 ,0.0 ]#球\r\n elif yu == 50 :\r\n yy = [0.0, 1.0, 0.0, 0.0, 0.0]#场线\r\n elif yu == 100 :\r\n yy = [0.0, 0.0, 1.0, 0.0, 0.0]#障碍物\r\n elif yu == 200 :\r\n yy = [0.0, 0.0, 0.0, 1.0, 0.0]#场地\r\n else :\r\n yy = [0.0, 0.0, 0.0, 0.0, 1.0]#其他\r\n test_lable.append(yy)\r\n\r\n return test_image ,test_lable \r\n\r\n\r\n\r\n\r\ndef data_train_2():#train_size=1,test_size=1):\r\n # img = cv2.imread(\"1.bmp\") \r\n \r\n train_image = []\r\n train_lable = []\r\n i = random.randint(1,1000)\r\n ad_im = './data/train_data_jpg/image/' + str(i)+ '.jpg' \r\n images = cv2.imread(ad_im)\r\n images_hsv = cv2.cvtColor(images,cv2.COLOR_BGR2HSV)\r\n ad_la = './data/train_data_jpg/lable/' + str(i+1)+ '.jpg'\r\n lables = cv2.imread(ad_la,0)\r\n\r\n for high in range(0, 480):\r\n for width in range(0, 640): \r\n b,g,r = images[high,width]/255.0\r\n h,s,v = images_hsv[high,width]/255.0\r\n xx = [b,g,r,h,s,v]\r\n train_image.append(xx) \r\n yu = int(lables[high,width])\r\n if yu >= 0 and yu < 0+25 :\r\n yy = [1.0 ,0.0 ,0.0 ,0.0 ,0.0 ]#球\r\n elif yu >= 50-25 and yu < 50+25 :\r\n yy = [0.0, 1.0, 0.0, 0.0, 0.0]#场线\r\n elif yu >= 100-25 and yu < 100+25:\r\n yy = [0.0, 0.0, 1.0, 0.0, 0.0]#障碍物\r\n elif yu >= 200-25 and yu < 200+25:\r\n yy = [0.0, 0.0, 0.0, 1.0, 0.0]#场地\r\n else :\r\n yy = [0.0, 0.0, 0.0, 0.0, 1.0]#其他\r\n train_lable.append(yy)\r\n return train_image ,train_lable\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef test(d):\r\n #生成测试集\r\n test_image = []\r\n test_lable = []\r\n #for _ in range(0,test_size+1):\r\n #i = random.randint(1,100)\r\n i = d\r\n ad_im = './data/test_data/image/' + str(i)+ '.png' \r\n images = cv2.imread(ad_im)\r\n images_b = cv2.imread(ad_im)\r\n images_g = cv2.imread(ad_im)\r\n images_r = cv2.imread(ad_im)\r\n images_h = cv2.imread(ad_im)\r\n #images_s = cv2.imread(ad_im)\r\n #images_v = cv2.imread(ad_im)\r\n\r\n\r\n images_hsv = cv2.cvtColor(images,cv2.COLOR_BGR2HSV)\r\n ad_la = './data/test_data/lable/' + str(i)+ '.png'\r\n lables = cv2.imread(ad_la,0)\r\n \r\n for width in range(0, 480): \r\n for high in range(0, 640):\r\n b,g,r = images[width, high]/255.0\r\n h,s,v = images_hsv[width, high]/255.0\r\n xx = [b,g,r,h,s,v]\r\n test_image.append(xx) \r\n yu = int(lables[width, high])\r\n if yu == 0 :\r\n yy = [1.0 ,0.0 ,0.0 ,0.0 ,0.0 ]#球\r\n elif yu == 50 :\r\n yy = [0.0, 1.0, 0.0, 0.0, 0.0]#场线\r\n elif yu == 100 :\r\n yy = [0.0, 0.0, 1.0, 0.0, 0.0]#障碍物\r\n elif yu == 200 :\r\n yy = [0.0, 0.0, 0.0, 1.0, 0.0]#场地\r\n else :\r\n yy = [0.0, 0.0, 0.0, 0.0, 1.0]#其他\r\n test_lable.append(yy)\r\n images_b[width, high] = (b*255,0,0)\r\n images_g[width, high] = (0,g*255,0)\r\n images_r[width, high] = (0,0,r*255)\r\n images_h[width, high] = (h*255,s*255,v*255)\r\n #print(np.shape(test_image)) \r\n #print(np.shape(test_lable))\r\n\r\n #del xxx[:]\r\n #del yyy[:]\r\n cv2.imshow(\"b\",images_b)\r\n cv2.imshow(\"g\",images_g)\r\n cv2.imshow(\"r\",images_r)\r\n cv2.imshow(\"hsv\",images_h)\r\n cv2.imshow(\"hsva\",images_hsv)\r\n cv2.waitKey()\r\n return test_image ,test_lable \r\n\r\n#hh = test(1)","sub_path":"Sg_demo/images.py","file_name":"images.py","file_ext":"py","file_size_in_byte":6492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"24340205","text":"# -*- coding: utf-8 -*-\n\nfrom influxdb import InfluxDBClient\nfrom odpc.echarts import *\nclient = InfluxDBClient('192.168.2.26', 8086, 'root', 'root', 'api', timeout=2)\n\n\ndef test(sql):\n result = client.query(sql)\n\n for (tablename, groups), rows in result.items():\n print(tablename, groups)\n for row in rows:\n print(row)\n\n\n# test(\"\"\"select * from static where app ='sky' and url='api/item/' and type='all' group by host;\"\"\")\n# test(\"\"\"select * from static where app ='sky' and (type = 'all' or type='hit') and url='api/item/' group by type, host;\"\"\")\n# test(\"\"\"select * from static where app ='sky' and type = 'all' group by type, host, url;\"\"\")\n\ndef test2(name=None, start=None, end=None):\n\n result = client.query(\"\"\"select * from counts where type = 'all' and time > {} and time < {} group by type, url;\"\"\"\n .format(str(start)+'000000', str(end)+'000000'))\n line_data = {}\n for (tablename, groups), rows in result.items():\n if groups['url'] in module[name]:\n if groups['url'] not in line_data:\n line_data[groups['url']] = {}\n for row in rows:\n if row['time'] in line_data[groups['url']]:\n line_data[groups['url']][row['time']] += row['value']\n else:\n line_data[groups['url']][row['time']] = row['value']\n legend_data = line_data.keys()\n xAxis_data = []\n chart_build = BasicAreaChart()\n chart_build.series = []\n for legend in legend_data:\n xAxis_data = sorted(list(line_data[legend].keys()))\n chart_build.series.append(Line([line_data[legend][x] for x in xAxis_data], name=legend, areaStyle={'normal': {}}))\n chart_build.tooltip = {'trigger': 'axis', 'axisPointer': {'type': 'cross', 'label': {'backgroundColor': '#6a7985'}}}\n chart_build.legend = Legend(data=list(legend_data))\n chart_build.grid = Grid(**{'left': '3%', 'right': '5%', 'bottom': '0'})\n chart_build.xAxis.data = [i[:10] for i in list(xAxis_data)]\n\n if len(list(xAxis_data)) > 20:\n chart_build.dataZoom = dataZoom(start=95)\n print(chart_build.output())\n return chart_build.output()\n\n\ndef test3(url='/api/item/', start=None, end=None):\n result = client.query(\"\"\"select * from counts where time > {} and time < {} and url='{}' group by type, url;\"\"\"\n .format(str(start) + '000000', str(end) + '000000',url))\n line_data = {}\n for (tablename, groups), rows in result.items():\n if 't_' in groups['type'] and groups['type'] != 't_lt_01':\n if groups['type'] not in line_data:\n line_data[groups['type']] = {}\n for row in rows:\n if row['time'] in line_data[groups['type']]:\n line_data[groups['type']][row['time']] += row['value']\n else:\n line_data[groups['type']][row['time']] = row['value']\n legend_data = line_data.keys()\n series = []\n xAxis_data = []\n for legend in legend_data:\n xAxis_data = sorted(list(line_data[legend].keys()))\n series.append([line_data[legend][x] for x in xAxis_data])\n\n return legend_data, series, xAxis_data\n # {\n # 'tooltip': {'trigger': 'axis', 'axisPointer': {'type': 'cross', 'label': {'backgroundColor': '#6a7985'}}},\n # 'legend': {'data': list(legend_data)},\n # 'toolbox': {'feature': {'saveAsImage': {}}},\n # 'grid': {'left': '3%', 'right': '5%', 'bottom': '0', 'containLabel': True},\n # 'xAxis': [{'type': 'category', 'boundaryGap': False, 'data': [i[:10] for i in list(xAxis_data)]}],\n # 'yAxis': [{'type': 'value'}],\n # 'series': series\n # }\n\n\nmodule = {\n 'all': ['/api/item/', '/api/subitem/', '/api/tv/section/', '/api/recommend/', '/api/clip/',\n '/api/tv/relate/', '/api/play/check/', '/api/get/ad/'],\n 'static': ['/api/item/', '/api/subitem/', '/api/tv/section/'],\n 'Wheat': ['/api/recommend/'],\n 'epg': ['/api/clip/', '/api/tv/relate/'],\n 'Rhododendron': ['/api/play/check/'],\n 'Clover': ['/api/get/ad/']\n}\n\n\ndef config_host():\n result = client.query(\"\"\"select * from static where app ='sky' group by host, url;\"\"\")\n config = {\n 'static': [],\n 'Wheat': [],\n 'epg': [],\n 'Rhododendron': [],\n 'Clover': []\n }\n for (tablename, groups), rows in result.items():\n for name, key_list in module.items():\n if groups['url'] in key_list:\n if groups['host'] not in config[name]:\n config[name].append(groups['host'])\n return config\n\n\nif __name__ == '__main__':\n from time import time, mktime\n from datetime import datetime, timedelta\n default = datetime.now() - timedelta(days=15)\n start = int(mktime(default.timetuple())) * 1000\n end = int(time()) * 1000\n print(test2(name='all', start=start, end=end))\n","sub_path":"e_bootstrap/base/monitor/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":4908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"252319114","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# thumbor imaging service\n# https://github.com/thumbor/thumbor/wiki\n\n# Licensed under the MIT license:\n# http://www.opensource.org/licenses/mit-license\n# Copyright (c) 2011 globo.com thumbor@googlegroups.com\n\nfrom os.path import join, abspath, dirname\nfrom preggy import expect\n\nfrom thumbor.context import Context\nfrom thumbor.config import Config\nfrom thumbor.storages.no_storage import Storage as NoStorage\nfrom tests.base import TestCase\n\n\nclass NoStorageTestCase(TestCase):\n def get_context(self):\n cfg = Config()\n return Context(None, cfg, None)\n\n def get_image_url(self, image):\n return 's.glbimg.com/some/{0}'.format(image)\n\n def get_image_path(self, image):\n return join(abspath(dirname(__file__)), image)\n\n def get_image_bytes(self, image):\n ipath = self.get_image_path(image)\n with open(ipath, 'r') as img:\n return img.read()\n\n def test_store_image_should_be_null(self):\n iurl = self.get_image_url('source.jpg')\n storage = NoStorage(None)\n stored = storage.get(iurl)\n expect(stored.result()).to_be_null()\n\n def test_store_knows_no_image(self):\n iurl = self.get_image_url('source.jpg')\n storage = NoStorage(None)\n exists = storage.exists(iurl)\n expect(exists.result()).to_be_false()\n\n def test_removes_image_should_be_null(self):\n iurl = self.get_image_url('source.jpg')\n storage = NoStorage(None)\n removed = storage.remove(iurl)\n expect(removed).to_be_null()\n\n def test_stores_crypto_should_be_null(self):\n iurl = self.get_image_url('source.jpg')\n storage = NoStorage(None)\n storage.put_crypto(iurl)\n got_crypto = storage.get_crypto(iurl)\n expect(got_crypto.result()).to_be_null()\n\n def test_detector_data_should_be_null(self):\n iurl = self.get_image_url('source.jpg')\n storage = NoStorage(None)\n storage.put_detector_data(iurl, \"some data\")\n data = storage.get_detector_data(iurl)\n expect(data.result()).to_be_null()\n","sub_path":"tests/storages/test_no_storage.py","file_name":"test_no_storage.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"210785670","text":"import os\nimport re\nimport mock\nimport warnings\n\nfrom oktest import ok\n\nfrom fabric.api import run, sudo\nfrom fabric.contrib.files import exists\n\nfrom fablib import core\nfrom config import host\n\ncore.set_hosts([host])\nip = re.compile(\"inet addr:(?P[\\d.]*?)\\s\")\n\ndef test_host_ok():\n ip_addr = run('ifconfig eth0 | grep \"inet addr\"')\n res = ip.match(str(ip_addr))\n ok(res) != None\n ok(res.group('ip')) == host.split('@')[1]\n ok(str(run('whoami'))) == host.split(':')[0]\n \n ok(core.curr_host()) == host.split('@')[1]\n \ndef test_other():\n ok(core.curr_os()) == 'ubuntu'\n \n with mock.patch('fablib.core.run', lambda x : 1 / 0):\n with mock.patch('fablib.core.sudo', lambda x : 1 / 0):\n # no system call should be made\n ok(core.curr_os()) == 'ubuntu'\n \ndef test_pkg():\n cmd_name = 'mp3blaster'\n pkg_name = 'mp3blaster'\n \n if core.check_pkg(pkg_name):\n core.uninstall(pkg_name)\n \n ok(core.pkg()) != None\n ok(core.check_pkg(pkg_name)) == False\n ok(core.check_cmd(cmd_name)) == False\n \n core.install(pkg_name) \n ok(core.check_pkg(pkg_name)) == True\n ok(core.check_cmd(cmd_name)) == True\n \n core.uninstall(pkg_name)\n ok(core.check_pkg(pkg_name)) == False\n ok(core.check_cmd(cmd_name)) == False\n \n\ndef test_get_put():\n with warnings.catch_warnings():\n fname = os.tmpnam()\n \n t1 = 'some data'\n t2 = 'other text'\n \n core.put_rf(fname, t1)\n \n try:\n ok(core.get_rf(fname)) == t1\n \n sudo('chown root.root ' + fname)\n sudo('chmod o-w ' + fname)\n \n ok(lambda : core.put_rf(fname, t2)).raises(SystemExit)\n \n core.put_rf(fname, t2, use_sudo=True)\n ok(core.get_rf(fname)) == t2\n \n with core.remote_fl(fname, use_sudo=True) as fc:\n ok(fc.getvalue()) == t2\n fc.setvalue(t1)\n\n ok(core.get_rf(fname)) == t1\n \n finally:\n sudo('rm ' + fname)\n\ndef test_replace():\n with warnings.catch_warnings():\n fname = os.tmpnam()\n \n t1 = 'some data'\n t2 = 'other text'\n header = '-' * 50\n footer = '=' * 50\n \n mkfl = lambda x : header + '\\n' + x + '\\n' + footer\n \n core.put_rf(fname, mkfl(t1))\n try:\n ok(core.replace_in_file(fname, t2, t1)) == False\n ok(core.replace_in_file(fname, t1, t2)) == True\n ok(core.get_rf(fname)) == mkfl(t2)\n \n sudo('chown root.root ' + fname)\n sudo('chmod o-w ' + fname)\n \n ok(lambda : core.replace_in_file(fname, t2, t1)).raises(SystemExit)\n \n ok(core.replace_in_file(fname, t1, t2, use_sudo=True)) == False\n ok(core.replace_in_file(fname, t2, t1, use_sudo=True)) == True\n \n ok(core.get_rf(fname)) == mkfl(t1)\n finally:\n sudo('rm ' + fname)\n\ndef test_func_decorators():\n @core.provides('ls')\n def fake():\n raise RuntimeError()\n \n fake()\n \n @core.provides('some-unknown-command')\n def fake2():\n return True\n \n ok(fake2()) == True\n\n @core.provides_pkg('coreutils')\n def fake3():\n raise RuntimeError()\n \n fake3()\n \n @core.provides_pkg('some-unknown-pkg')\n def fake4():\n return True\n \n ok(fake4()) == True\n\n\n @core.ensure_pkg('coreutils')\n def fake5():\n pass\n\n with mock.patch('fablib.core.install', lambda x : 1 / 0):\n # no system call should be made\n fake5()\n \n pkg_name = 'mp3blaster'\n\n if core.check_pkg(pkg_name):\n core.uninstall(pkg_name) \n\n @core.ensure_pkg(pkg_name)\n def fake5():\n ok(core.check_pkg(pkg_name)) == True\n core.uninstall(pkg_name)\n\n fake5() \n \ndef test_which():\n path = core.which('ls')\n ok(exists(path)) == True\n\ndef test():\n to_call = {}\n \n for key, val in globals().items():\n if key.startswith('test_') and hasattr(val, \"__call__\"):\n to_call[key] = val\n \n for name, func in to_call.items():\n func()\n \n","sub_path":"fablib/fablib/unittest/test_core.py","file_name":"test_core.py","file_ext":"py","file_size_in_byte":4061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"102627203","text":"#!/usr/bin/env python3\n\"\"\"\nAuthor : Wen Yu (Amy) Wong- wwong3\nDate : 2019-FEB-14\nPurpose: Translate Codons to Proteins\n\"\"\"\n\nimport argparse\nimport sys\nimport os\n\n# --------------------------------------------------\ndef get_args():\n \"\"\"get command-line arguments\"\"\"\n parser = argparse.ArgumentParser(\n description='Translate DNA/RNA to proteins',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument(\n 'positional', metavar='STR', help='DNA/RNA sequence')\n\n parser.add_argument(\n\t'-c',\n\t'--codons',\n\thelp='A file with codon translations',\n\tmetavar='FILE',\n\ttype=str,\n\trequired=True,\n\tdefault=None)\n\n parser.add_argument(\n '-o',\n '--output',\n help='Output filename',\n metavar='FILE',\n type=str,\n default='out.txt')\n\n \n return parser.parse_args()\n\n\n# --------------------------------------------------\ndef warn(msg):\n \"\"\"Print a message to STDERR\"\"\"\n print(msg, file=sys.stderr)\n\n\n# --------------------------------------------------\ndef die(msg='Something bad happened'):\n \"\"\"warn() and exit with error\"\"\"\n warn(msg)\n sys.exit(1)\n\n\n# --------------------------------------------------\ndef main():\n\t\"\"\"Make a jazz noise here\"\"\"\n\targs = get_args()\n\tSTR = args.positional\n\tcodon = args.codons\n\toutput = args.output\n\n# Die and exit when bad --codons are given or when codon is not a file\n\tif not os.path.isfile(codon):\n\t\tprint('--codons \"{}\" is not a file'.format(codon))\n\t\texit(1)\n\n# If given good input, write results in proper output file:\n\t\n\t# Taking string and upper case them\n\tSTR=STR.upper()\n\t\t\n\t# Splitting --codon into 3 characters and storing into var=STR\n\tn=3\n\tSTR=[STR[i:i+3] for i in range(0,len(STR), n)] \n\n\t# Splitting --codon file so you can associate sequence to protein\n\tcodon_dict={} # empty directory\n\tfor line in open (codon): # reading in line of the --codon file\n\t\tcodon,amino_acid=line.split() # split on white space, rename pieces\n\t\tcodon_dict[codon]=amino_acid # renaming \n\t\t\n\t# Matching each codon STR to --codon FILE\n\n\tprotein_list='' # Creating new empty str to later store all the codon matches\n\tfor i in STR: # Calling each index in STR list\n\t\tif i in codon_dict: # Passing those index into the codon_dict \n\t\t\tprotein=codon_dict[i] # Finding the protein matches\n\t\telse:\n\t\t\tprotein='-'\n\t\n\t\tprotein_list += protein # Adds the found protein to the protein_list\n\n\t# Creating store lists to correct output file\n\twith open (output, \"wt\") as outgoing: # Opening output file and \"wt\"=writing\n\t\tprint(protein_list, file=outgoing) # Telling it to add the protein_list to file\n\t\tprint('Output written to \"{}\"'.format(output)) # Msg, output file is written\n\t\t\n\n# --------------------------------------------------\nif __name__ == '__main__':\n main()\n","sub_path":"assignments/05-python-proteins/translate_proteins.py","file_name":"translate_proteins.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"648515480","text":"# -*- coding: UTF-8 -*-\n\nimport random\nfrom collections import defaultdict\nfrom datetime import datetime, timedelta\n\nfrom bson import ObjectId\n\nfrom wms.lib.combine_parcel.data_accessor.combine_pool_accessor import \\\n CombinePoolAccessor\nfrom wms.lib.combine_parcel.data_accessor.inbound_parcel_accessor import \\\n CPInboundParcelAccessor\nfrom wms.lib.combine_parcel.data_accessor.sort_job_accessor import \\\n SortJobAccessor\nfrom wms.lib.combine_parcel.utilities.inbound_parcel_util import \\\n InboundParcelUtil\nfrom wms.model.mongo.combine_parcel.combine_pool import (CPSortAllocateGroupId,\n CPSortPool)\nfrom wms.model.mongo.combine_parcel.inbound_parcel import CPInboundParcel\nfrom wms.model.mongo.combine_parcel.sort_job import CPSortJob\nfrom wms.model.mongo.sequence_id_generator import SequenceIdGenerator\nfrom wms.model.mongo.warehouse import Warehouse\nfrom wms.server import ConfigParser, IUWMSBackendService\n\nCONFIG_FILE = '/etc/server.yml'\n\n\ndef _setup():\n options = ConfigParser.parse_config_file(CONFIG_FILE)\n options['rate-limiter']['enable'] = False\n application = IUWMSBackendService(options)\n application.connect()\n\n\ndef create_combine_pool():\n warehouse_id = \"SHYW\"\n warehouse = Warehouse.by_warehouse_id(warehouse_id)\n job_prefix = datetime.utcnow().strftime(\"%Y%m%d\")\n job_id = SequenceIdGenerator.get_sequence_id(job_prefix)\n job = SortJobAccessor.create(\n job_id, CPSortJob.Type.AllocateCabinetLattice, \"SHYW\")\n\n inbound_parcels = CPInboundParcel.find({\n \"created_datetime\": {\n \"$gte\": datetime(2019, 4, 18, 0, 0, 0),\n \"$lte\": datetime(2019, 4, 19, 0, 0, 0)\n }\n })\n\n if not inbound_parcels:\n raise Exception(\"inbound_parcels is empty\")\n\n combine_ids = list(set(parcel.combine_id for parcel in inbound_parcels))\n parcel_groups = defaultdict(list)\n for parcel in inbound_parcels:\n parcel_groups[parcel.combine_id].append(parcel)\n\n group_ids = CPSortAllocateGroupId.allocate(len(combine_ids), warehouse.sort_batch_size)\n group_dict = dict(zip(combine_ids, group_ids))\n\n lattice_id = 1\n cabinet_id = str(ObjectId())\n for combine_id, parcels in parcel_groups.items():\n group_length = len(parcels)\n sort_type = CPSortPool.SortType.DirectShip if group_length == 1 else CPSortPool.SortType.Combined\n for parcel in parcels:\n group_id = group_dict[combine_id]\n CPSortPool.create(\n job_id=job_id,\n tracking_id=parcel.tracking_id,\n sort_type=sort_type,\n group_ids=group_id,\n cabinet_id=cabinet_id,\n lattice_id=lattice_id\n )\n lattice_id += 1\n\n\nif __name__ == \"__main__\":\n _setup()\n create_combine_pool()\n","sub_path":"wms/script/test/combine_parcel/create_combine_pool.py","file_name":"create_combine_pool.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"223387928","text":"\"\"\"\nUndulator\nAn undulator\nicons/gaussian.svg\n2\n\"\"\"\nimport sys\nfrom PyQt4.Qt import *\n\nfrom orangewidget.settings import Setting\nfrom orangewidget import gui\nfrom oasys.widgets import widget\n\nfrom orangecontrib.wanys.util.OpticalElement import OpticalElement\nfrom orangecontrib.wanys.util.OpticalBeam import OpticalBeam\nfrom orangecontrib.wanys.widgets.drivers.DriverSettingsWidget import DriverSettingsWidget\n\nfrom orangecontrib.wanys.BeamlineComponents.Source.Undulator import Undulator\n\nclass UndulatorWidget(widget.OWWidget):\n name = \"Undulator\"\n description = \"Undulator\"\n icon = \"icons/gaussian.svg\"\n\n want_main_area = False\n\n inputs = [(\"Optical beam\", OpticalBeam, \"onOpticalBeam\", widget.Multiple)]\n outputs = [(\"Optical beam\", OpticalBeam)]\n\n value_le_K_vertical = Setting(1.87)\n value_le_K_horizontal = Setting(0)\n value_le_period_length = Setting(0.035)\n value_le_period_number = Setting(14)\n\n value_le_driver_settings = Setting(\"\")\n\n def __init__(self, parent=None, signalManager=None):\n widget.OWWidget.__init__(self, parent, signalManager)\n\n self.__optical_undulator = OpticalElement(\"undulator\")\n\n\n self.le_K_vertical = gui.lineEdit(self.controlArea,\n self,\n \"value_le_K_vertical\",\n label=\"Vertical K\",\n validator=QDoubleValidator(bottom=0.0))\n\n self.le_K_horizontal = gui.lineEdit(self.controlArea,\n self,\n \"value_le_K_horizontal\",\n label=\"Horizontal K\",\n validator=QDoubleValidator(bottom=0.0))\n\n self.le_period_length = gui.lineEdit(self.controlArea,\n self,\n \"value_le_period_length\",\n label=\"period length [m]\",\n validator=QDoubleValidator(bottom=0.0))\n\n self.le_period_number = gui.lineEdit(self.controlArea,\n self,\n \"value_le_period_number\",\n label=\"number periods\",\n validator=QDoubleValidator(bottom=0.0))\n\n\n self.__driver_settings_widget = DriverSettingsWidget(self.__optical_undulator,\n self,\n \"value_le_driver_settings\",\n Undulator(1.8,1.8,0.35,100))\n\n self.__optical_undulator.setOnSynchronize(self.synchronizeToOpticalElement)\n\n def synchronizeToOpticalElement(self):\n source = self.__optical_undulator\n\n K_vertical = float(self.value_le_K_vertical)\n K_horizontal = float(self.value_le_K_horizontal)\n period_length = float(self.value_le_period_length)\n period_number =float(self.value_le_period_number)\n\n beamline_component = Undulator(K_vertical=K_vertical,\n K_horizontal=K_horizontal,\n period_length=period_length,\n periods_number=period_number)\n self.__optical_undulator.setBeamlineComponent(beamline_component=beamline_component)\n\n def onOpticalBeam(self, optical_beam, sender):\n optical_beam.sender().addOutput(self.__optical_undulator)\n\n sender = OpticalBeam(self.__optical_undulator)\n self.send(\"Optical beam\", sender)\n\n\nif __name__==\"__main__\":\n appl = QApplication(sys.argv)\n ow = UndulatorWidget()\n ow.show()\n appl.exec_()\n","sub_path":"orangecontrib/wanys/widgets/source/UndulatorWidget.py","file_name":"UndulatorWidget.py","file_ext":"py","file_size_in_byte":3999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"232222499","text":"# coding=utf-8\n#\n# Created by junn, on 2018-5-29\n#\n\n\"\"\"\n\n\"\"\"\n\nimport logging\nimport re\n\nfrom django.db import transaction\n\nfrom users.forms import UserLoginForm\nfrom utils import eggs\nfrom .models import Hospital, Department, Staff, Group, Role\nfrom base.forms import BaseForm\nfrom .consts import DPT_ATTRI_CHOICES, GROUP_CATE_NORMAL_STAFF\n\nfrom users.models import User\n\n\nlogs = logging.getLogger(__name__)\n\n\nPASSWORD_COMPILE = re.compile(r'^\\w{6,18}$')\n\n\nclass OrganSignupForm(BaseForm):\n \"\"\"\n 对企业注册信息进行表单验证\n \"\"\"\n\n ERR_CODES = {\n 'invalid_email': u'无效的Email',\n 'user_existed': u'Email已注册',\n 'err_password': u\"密码只能为6-18位英文字符或下划线组合\",\n\n 'err_organ_name': u'企业名称错误',\n 'err_organ_scale': u'企业规模错误',\n 'err_contact_name': u'联系人姓名填写错误',\n 'err_contact_phone': u'联系人电话填写错误',\n 'err_contact_title': u'联系人职位填写错误',\n\n 'params_lack': u'参数缺乏',\n }\n\n def __init__(self, req, data, *args, **kwargs):\n BaseForm.__init__(self, data, *args, **kwargs)\n self.req = req\n self.errors = {}\n\n def is_valid(self):\n valid_email = self.check_email()\n valid_organ_name = self.check_organ_name()\n valid_organ_scale = self.check_organ_scale()\n valid_contact_name = self.check_contact_name()\n valid_contact_phone = self.check_contact_phone()\n valid_contact_title = self.check_contact_title()\n\n return valid_email and valid_organ_name \\\n and valid_organ_scale and valid_contact_name \\\n and valid_contact_phone and valid_contact_title\n\n def check_email(self):\n \"\"\" 检查注册Email\n\n 检查项如下:\n 1. 格式是否正确\n 2. 是否已存在该邮箱账号\n 3. 是否有相同后缀的邮箱用户已通过申请\n \"\"\"\n email = self.data.get('email', '').strip()\n if not email or not eggs.is_email_valid(email):\n self.errors.update({'email': self.ERR_CODES['invalid_email']})\n return False\n\n try:\n user = User.objects.get(email=email)\n self.errors.update({'email': self.ERR_CODES['user_existed']})\n return False\n except User.DoesNotExist:\n pass\n return True\n\n def check_contact_name(self):\n contact_name = self.data.get('contact_name', '').strip()\n if not contact_name:\n self.errors.update({'contact_name': self.ERR_CODES['err_contact_name']})\n return False\n return True\n\n def check_contact_phone(self):\n contact_phone = self.data.get('contact_phone', '').strip()\n if not contact_phone or not eggs.is_phone_valid(contact_phone):\n self.errors.update(\n {'contact_phone': self.ERR_CODES['err_contact_phone']}\n )\n return False\n\n return True\n\n def check_contact_title(self):\n contact_title = self.data.get('contact_title', '').strip()\n if not contact_title:\n self.errors.update(\n {'contact_title': self.ERR_CODES['err_contact_title']}\n )\n return False\n return True\n\n def check_organ_name(self):\n organ_name = self.data.get('organ_name', '').strip()\n if not organ_name:\n self.errors.update(\n {'organ_name': self.ERR_CODES['err_organ_name']}\n )\n return False\n return True\n\n def check_organ_scale(self):\n organ_scale = self.data.get('organ_scale', 1)\n if not organ_scale:\n self.errors.update(\n {'organ_scale': self.ERR_CODES['err_organ_scale']}\n )\n return False\n return True\n\n def save(self):\n return None\n\n\nclass OrganLoginForm(UserLoginForm):\n \"\"\" 企业管理员登录表单验证 \"\"\"\n\n def __init__(self, req, data=None, *args, **kwargs):\n super(UserLoginForm, self).__init__(self, req, data, *args, **kwargs)\n\n # 企业管理员额外增加的验证异常类型\n self.ERR_CODES.update({\n 'not_organ_admin': u'无企业管理员权限',\n 'email_auth_checking': u'Email正在审核',\n 'email_auth_failed': u'Email未通过审核',\n })\n\n def is_valid(self):\n super_form = self.super_form()\n organ_admin = self.organ_admin()\n email_auth_check = self.email_auth_check()\n email_auth_failed = self.email_auth_failed()\n\n return super_form and organ_admin and email_auth_check and email_auth_failed\n\n def super_form(self):\n if not super(OrganLoginForm, self).is_valid():\n return False\n return True\n\n def organ_admin(self):\n if not self.user_cache.organ:\n self.update_errors('email', 'not_organ_admin')\n return False\n return True\n\n def email_auth_check(self):\n if self.user_cache.organ.is_checking():\n self.update_errors('email', 'email_auth_checking')\n return False\n return True\n\n def email_auth_failed(self):\n if self.user_cache.organ.is_auth_failed():\n self.update_errors('email', 'email_auth_failed')\n return False\n return True\n\nclass HospitalSignupForm(OrganSignupForm):\n \"\"\"\n 对医院注册信息进行表单验证\n \"\"\"\n\n def save(self):\n email = self.data.get('email')\n\n organ_name = self.data.get('organ_name')\n organ_scale = self.data.get('organ_scale')\n\n contact_name = self.data.get('contact_name')\n contact_phone = self.data.get('contact_phone')\n contact_title = self.data.get('contact_title')\n\n with transaction.atomic(): # 事务原子操作\n creator = User.objects.create_param_user(('email', email),\n is_active=False\n )\n\n # create organ\n new_organ = Hospital.objects.create_hospital(**{\n 'creator': creator,\n 'organ_name': organ_name,\n 'organ_scale': int(organ_scale) if organ_scale else 1,\n 'contact_name': contact_name,\n 'contact_phone': contact_phone,\n 'contact_title': contact_title\n })\n\n new_organ.init_default_groups()\n\n # create admin staff for the new organ\n staff = new_organ.create_staff(**{\n 'user': creator,\n 'organ': new_organ,\n\n 'name': contact_name,\n 'title': contact_title,\n 'contact': contact_phone,\n 'email': email,\n 'group': new_organ.get_admin_group()\n })\n # Folder.objects.get_or_create_system_folder(organ=new_organ) # 依赖错误!!!\n\n # create default department\n new_organ.create_department(name='默认')\n return new_organ\n\n\nclass StaffSignupForm(BaseForm):\n \"\"\"\n 新增员工表单数据验证\n \"\"\"\n ERR_CODES = {\n 'err_username': '用户名为空或格式错误',\n 'err_username_existed': '用户名已存在',\n 'err_password': '密码为空或格式错误',\n 'err_staff_name': '员工姓名错误',\n 'err_contact_phone': '联系电话格式错误',\n 'err_email': '无效邮箱',\n 'err_staff_title': '职位名为空或格式错误',\n 'err_group_is_null': '权限组为空或数据错误',\n 'err_group_not_exist': '权限组不存在',\n }\n\n def __init__(self, organ, dept, data, *args, **kwargs):\n BaseForm.__init__(self, data, *args, **kwargs)\n self.organ = organ\n self.dept = dept\n\n def is_valid(self):\n is_valid = True\n # 校验必输项\n if not self.check_username() or not self.check_password() \\\n or not self.check_staff_name() or not self.check_group():\n is_valid = False\n\n # 校验非必输项\n if self.data.get('email') and not self.check_email():\n is_valid = False\n\n if self.data.get('contact_phone') and not self.check_contact_phone():\n is_valid = False\n\n if self.data.get('group_id') and not self.check_group():\n is_valid = False\n\n return is_valid\n\n def check_username(self):\n \"\"\"校验用户名/账号\n \"\"\"\n username = self.data.get('username', '').strip()\n if not username:\n self.update_errors('username', 'err_username')\n return False\n\n if User.objects.filter(username=username):\n self.update_errors('username', 'err_username_existed')\n return False\n\n return True\n\n def check_password(self):\n \"\"\"校验密码\"\"\"\n password = self.data.get('password', '').strip()\n if not password:\n self.update_errors('password', 'err_password')\n return False\n return True\n\n def check_staff_name(self):\n \"\"\"校验员工名称\n \"\"\"\n staff_name = self.data.get('staff_name', '').strip()\n if not staff_name:\n self.update_errors('staff_name', 'err_staff_name')\n return False\n return True\n\n def check_email(self):\n \"\"\"校验邮箱\n \"\"\"\n email = self.data.get('email', '').strip()\n if not eggs.is_email_valid(email):\n self.update_errors('email', 'err_email')\n return False\n return True\n\n def check_contact_phone(self):\n \"\"\"校验手机号\n \"\"\"\n contact_phone = self.data.get('contact_phone', '').strip()\n if not eggs.is_phone_valid(contact_phone):\n self.update_errors('contact_phone', 'err_contact_phone')\n return False\n return True\n\n def check_staff_title(self):\n \"\"\"校验职位名称\"\"\"\n staff_title = self.data.get('staff_title', '').strip()\n if not staff_title:\n self.update_errors('staff_title', 'err_staff_title')\n return False\n\n return True\n\n def check_group(self):\n group_id = self.data.get('group_id')\n group = None\n if not group_id:\n group = Group.objects.filter(cate=GROUP_CATE_NORMAL_STAFF, is_admin=0).first()\n if not group:\n self.update_errors('group_id', 'err_group_not_exist')\n self.data.update({'group': group})\n return True\n group = Group.objects.get_by_id(group_id)\n if not group:\n self.update_errors('group_id', 'err_group_not_exist')\n return False\n self.data.update({'group': group})\n return True\n\n def save(self):\n data = {\n 'name': self.data.get('staff_name', '').strip(),\n 'title': self.data.get('staff_title', '').strip(),\n 'contact': self.data.get('contact_phone', '').strip(),\n 'email': self.data.get('email', '').strip(),\n 'group': self.data.get(\"group\")\n }\n\n user_data = {\n \"username\": self.data.get('username', '').strip(),\n \"password\": self.data.get('password', '').strip()\n }\n\n return Staff.objects.create_staff(self.organ, self.dept, user_data, **data)\n\n\nclass StaffUpdateForm(BaseForm):\n\n ERR_CODES = {\n 'err_staff_name': '员工姓名错误',\n 'err_contact_phone': '联系电话格式错误',\n 'err_email': '无效邮箱',\n 'err_dept': '科室信息错误',\n 'err_staff_title': '职位名为空或格式错误'\n }\n\n def __init__(self, staff, data, *args, **kwargs):\n BaseForm.__init__(self, data, *args, ** kwargs)\n self.staff = staff\n if data.get('staff_name'):\n self.data.update({'name': data.get('staff_name', '').strip()})\n if data.get('staff_title'):\n self.data.update({'title': data.get('staff_title', '').strip()})\n if data.get('contact_phone'):\n self.data.update({'contact': data.get('contact_phone', '').strip()})\n if data.get('email'):\n self.data.update({'email': data.get('email', '').strip()})\n\n def is_valid(self):\n is_valid = True\n if self.data.get('staff_name') and not self.check_staff_name():\n is_valid = False\n if self.data.get('email') and not self.check_email():\n is_valid = False\n if self.data.get('contact_phone') and not self.check_contact_phone():\n is_valid = False\n\n return is_valid\n\n def check_staff_name(self):\n \"\"\"校验员工名称\n \"\"\"\n staff_name = self.data.get('staff_name', '').strip()\n if not staff_name:\n self.update_errors('staff_name', 'err_staff_name')\n return False\n return True\n\n def check_email(self):\n \"\"\"校验邮箱\n \"\"\"\n email = self.data.get('email', '').strip()\n if not eggs.is_email_valid(email):\n self.update_errors('email', 'err_email')\n return False\n return True\n\n def check_contact_phone(self):\n \"\"\"校验手机号\n \"\"\"\n contact_phone = self.data.get('contact_phone', '').strip()\n if not eggs.is_phone_valid(contact_phone):\n self.update_errors('contact_phone', 'err_contact_phone')\n return False\n return True\n\n def check_staff_title(self):\n \"\"\"校验职位名称\"\"\"\n staff_title = self.data.get('staff_title', '').strip()\n if not staff_title:\n self.update_errors('staff_title', 'err_staff_title')\n return False\n\n return True\n\n def save(self):\n update_staff = self.staff.update(self.data)\n update_staff.cache()\n return update_staff\n\n\nclass StaffBatchUploadForm(BaseForm):\n\n ERR_CODES = {\n 'null_username': '第{0}行用户名不能为空',\n 'duplicate_username': '第{0}行和第{1}行用户名重复,请检查',\n 'username_exists': '用户名{}已存在',\n 'null_staff_name': '第{0}行员工姓名不能为空',\n 'err_contact_phone': '第{0}联系电话格式错误',\n 'err_email': '第{0}无效邮箱',\n 'empty_dept_data': '没有科室数据',\n 'err_dept': '含有不存在的科室信息',\n 'err_group_not_exist': '系统不存在普通员工权限,请先维护'\n }\n\n def __init__(self, organ, data, *args, **kwargs):\n BaseForm.__init__(self, data, *args, **kwargs)\n self.organ = organ\n self.group = None\n self.pre_data = self.init_data()\n\n def init_data(self):\n \"\"\"\n 封装各列数据, 以进行数据验证\n :return:\n \"\"\"\n pre_data = {}\n if self.data and self.data[0] and self.data[0][0]:\n sheet_data = self.data[0]\n usernames, staff_names, dept_names, emails, contact_phones = [], [], [], [], []\n for i in range(len(sheet_data)):\n usernames.append(sheet_data[i].get('username', '').strip())\n for i in range(len(sheet_data)):\n staff_names.append(sheet_data[i].get('staff_name', '').strip())\n for i in range(len(sheet_data)):\n dept_names.append(sheet_data[i].get('dept_name', '').strip())\n for i in range(len(sheet_data)):\n emails.append(sheet_data[i].get('email', '').strip())\n for i in range(len(sheet_data)):\n contact_phones.append(str(sheet_data[i].get('contact_phone', '')).strip())\n pre_data['usernames'] = usernames\n pre_data['staff_names'] = staff_names\n pre_data['dept_names'] = dept_names\n pre_data['emails'] = emails\n pre_data['contact_phones'] = contact_phones\n return pre_data\n\n def is_valid(self):\n if self.check_username() and self.check_staff_name() and self.check_dept() \\\n and self.check_email() and self.check_contact_phone() and self.check_group():\n return True\n return False\n\n def check_username(self):\n \"\"\"\n 校验用户名\n 用户名非空校验\n 用户名重复校验\n 用户名已存在校验\n \"\"\"\n usernames = self.pre_data.get('usernames')\n for i in range(len(usernames)):\n if not usernames[i]:\n self.update_errors('username', 'null_username', str(i + 2))\n return False\n\n for i in range(len(usernames)):\n usernames_tmp = usernames.copy()\n for j in range(i + 1, len(usernames_tmp)):\n if usernames[i] == usernames_tmp[j]:\n self.update_errors('username', 'duplicate_username', str(i + 2), str(j + 2))\n return False\n\n users = User.objects.filter(username__in=usernames)\n if users:\n self.update_errors('username', 'username_exists', users[0].username)\n return False\n\n return True\n\n def check_staff_name(self):\n \"\"\"\n 校验员工名称\n \"\"\"\n staff_names = self.pre_data.get('staff_names')\n for i in range(len(staff_names)):\n if not staff_names[i]:\n self.update_errors('staff_name', 'null_staff_name', str(i+2))\n return False\n\n return True\n\n def check_email(self):\n \"\"\"\n 校验邮箱\n \"\"\"\n emails = self.pre_data.get('emails')\n for i in range(len(emails)):\n if emails[i]:\n if not eggs.is_email_valid(emails[i]):\n self.update_errors('email', 'err_email', str(i+2))\n return False\n return True\n\n def check_contact_phone(self):\n \"\"\"\n 校验手机号\n \"\"\"\n contact_phones = self.pre_data.get('contact_phones')\n for i in range(len(contact_phones)):\n if contact_phones[i]:\n if not eggs.is_phone_valid(str(contact_phones[i])):\n self.update_errors('contact_phone', 'err_contact_phone', str(i+2))\n return False\n\n return True\n\n def check_dept(self):\n \"\"\"校验职位名称\"\"\"\n dept_names = self.pre_data.get('dept_names')\n if not dept_names:\n self.update_errors('dept', 'empty_dept_data')\n return False\n\n distincted_dept_names = set(dept_names)\n dept_query_set = Department.objects.filter(name__in=distincted_dept_names)\n if not dept_query_set or len(dept_query_set) < len(distincted_dept_names):\n self.update_errors('dept', 'err_dept')\n return False\n\n return True\n\n def check_group(self):\n group = Group.objects.filter(cate=GROUP_CATE_NORMAL_STAFF, is_admin=0).first()\n if not group:\n self.update_errors('group_id', 'err_group_not_exist')\n self.group = group\n return True\n\n def save(self):\n # 封装excel数据\n staffs_data = []\n if self.data and self.data[0] and self.data[0][0]:\n sheet_data = self.data[0]\n\n for row_data in sheet_data:\n staffs_data.append({\n 'username': row_data.get('username', '').strip(),\n 'staff_name': row_data.get('staff_name', '').strip(),\n 'contact_phone': row_data.get('contact_phone', '').strip(),\n 'email': row_data.get('email', '').strip(),\n 'dept_name': row_data.get('dept_name').strip(), # 将username和dept建立字典关系, 以便于批量查询dept\n 'organ': self.organ,\n 'group': self.group\n })\n\n # 建立字典结构, 以便通过dept_name快速定位dept对象: key/value: dept_name/dept\n dept_dict = {}\n dept_names = set(self.pre_data['dept_names'])\n depts = Department.objects.filter(name__in=dept_names)\n for dept in depts:\n dept_dict[dept.name] = dept\n\n for staff in staffs_data:\n staff['dept'] = dept_dict[staff['dept_name']]\n del staff['dept_name']\n\n return Staff.objects.batch_upload_staffs(staffs_data)\n\n\nclass DepartmentUpdateFrom(BaseForm):\n \"\"\"\n 对修改科室信息进行表单验证\n \"\"\"\n def __init__(self, dept, data, *args, **kwargs):\n BaseForm.__init__(self, data, *args, **kwargs)\n self.dept = dept\n\n self.ERR_CODES.update({\n 'dept_name_err': '科室名字不符合要求',\n 'dept_contact_err': '科室电话号码格式错误',\n 'dept_attri_err': '科室属性错误',\n 'dept_desc_err': '科室描述存在敏感字符',\n })\n\n def is_valid(self):\n if not self.check_contact() and not self.check_name() and not self.check_attri() and \\\n not self.check_desc():\n return False\n return True\n\n def check_contact(self):\n contact = self.data.get('contact')\n if not contact:\n return True\n\n if not eggs.is_phone_valid(contact):\n self.update_errors('dept_contact', 'err_dept_contact')\n return False\n\n return True\n\n def check_name(self):\n name = self.data.get('name')\n return True\n\n def check_desc(self):\n desc = self.data.get('desc')\n return True\n\n def check_attri(self):\n attri = self.data.get('attri')\n\n if not attri in dict(DPT_ATTRI_CHOICES).keys():\n self.update_errors('attri', 'err_dept_attri')\n return False\n return True\n\n def save(self):\n data = {}\n name = self.data.get('name', '').strip()\n contact = self.data.get('contact', '').strip()\n attri = self.data.get('attri', '').strip()\n desc = self.data.get('desc', '').strip()\n\n if name:\n data['name'] = name\n if contact:\n data['contact'] = contact\n if attri:\n data['attri'] = attri\n if desc:\n data['desc'] = desc\n\n updated_dept = self.dept.update(data)\n updated_dept.cache()\n return updated_dept\n\n\nclass DepartmentCreateForm(BaseForm):\n def __init__(self, hospital, data, *args, **kwargs):\n BaseForm.__init__(self, data, hospital, *args, **kwargs)\n self.hospital = hospital\n\n self.ERR_CODES.update({\n 'err_dept_name': '科室名字不符合要求',\n 'dept_exist': '同名科室已存在',\n 'err_dept_contact': '科室电话号码格式错误',\n 'err_dept_attri': '科室属性错误',\n 'err_dept_desc': '科室描述存在敏感字符',\n })\n\n def is_valid(self):\n if not self.check_contact() or not self.check_name() or \\\n not self.check_desc():\n return False\n return True\n\n def check_contact(self):\n contact = self.data.get('contact')\n if not contact:\n return True\n if not eggs.is_phone_valid(contact):\n self.update_errors('dept_contact', 'err_dept_contact')\n return False\n return True\n\n def check_name(self):\n dept = Department.objects.filter(name=self.data.get('name'))\n if dept:\n self.update_errors('dept_name', 'dept_exist')\n return False\n return True\n\n def check_desc(self):\n # desc = self.data.get('desc')\n return True\n\n def save(self):\n\n dept_data = {\n 'name': self.data.get('name', '').strip(),\n 'contact': self.data.get('contact', '').strip(),\n 'desc': self.data.get('desc').strip(),\n 'attri': 'OT'\n }\n\n try:\n new_dept = self.hospital.create_department(**dept_data)\n new_dept.cache()\n return new_dept\n except Exception as e:\n logging.exception(e)\n return None\n\n\nclass DepartmentBatchUploadForm(BaseForm):\n ERR_CODES = {\n 'organ_name': '第{0}行所属机构为空或不存在',\n 'error_attri': '第{0}行科室属性为空或数据错误',\n 'dept_name_duplicate': '第{0}行和第{1}行科室名称重复,请检查',\n 'dept_name_exists': '科室{}已存在',\n 'err_dept': '第{0}行科室名称为空或数据错误',\n 'desc_errr': '第{0}行职能描述数据错误'\n }\n\n def __init__(self, organ, data, *args, **kwargs):\n BaseForm.__init__(self, data, *args, **kwargs)\n self.organ = organ\n self.pre_data = self.init_data()\n\n def init_data(self):\n \"\"\"\n 封装各列数据, 以进行数据验证\n :return:\n \"\"\"\n pre_data = {}\n if self.data and self.data[0] and self.data[0][0]:\n sheet_data = self.data[0]\n dept_names, dept_attris, descs, = [], [], []\n for i in range(len(sheet_data)):\n dept_names.append(sheet_data[i].get('dept_name', '').strip())\n for i in range(len(sheet_data)):\n dept_attris.append(sheet_data[i].get('dept_attri', '').strip())\n for i in range(len(sheet_data)):\n descs.append(sheet_data[i].get('desc', '').strip())\n pre_data['dept_names'] = dept_names\n pre_data['dept_attris'] = dept_attris\n pre_data['descs'] = descs\n return pre_data\n\n def is_valid(self):\n # if self.check_username() and self.check_staff_name() and self.check_dept() \\\n # and self.check_email() and self.check_contact_phone():\n # return True\n # return False\n return True\n\n\n def check_dept(self):\n \"\"\"校验科室名称\"\"\"\n dept_names = self.pre_data['dept_names']\n if not dept_names:\n self.update_errors('dept', 'empty_dept_data')\n return False\n\n distincted_dept_names = set(dept_names)\n dept_query_set = Department.objects.filter(name__in=distincted_dept_names)\n if not dept_query_set or len(dept_query_set) < len(distincted_dept_names):\n self.update_errors('dept', 'err_dept')\n return False\n\n return True\n\n def check_dept_attri(self):\n \"\"\"\n 校验科室属性\n \"\"\"\n emails = self.pre_data['emails']\n for i in range(len(emails)):\n if emails[i]:\n if not eggs.is_email_valid(emails[i]):\n self.update_errors('email', 'err_email', str(i + 2))\n return False\n return True\n\n def check_dept_desc(self):\n \"\"\"\n 校验只能描述\n \"\"\"\n contact_phones = self.pre_data['contact_phones']\n for i in range(len(contact_phones)):\n if contact_phones[i]:\n if not eggs.is_phone_valid(str(contact_phones[i])):\n self.update_errors('contact_phone', 'err_contact_phone', str(i + 2))\n return False\n\n return True\n\n def save(self):\n # 封装excel数据\n depts_data = []\n if self.data and self.data[0] and self.data[0][0]:\n sheet_data = self.data[0]\n\n for row_data in sheet_data:\n depts_data.append({\n 'organ': self.organ,\n 'name': row_data.get('dept_name', ''),\n 'attri': row_data.get('dept_attri', ''),\n 'desc': row_data.get('desc', ''),\n })\n\n return self.organ.batch_upload_departments(depts_data)\n\n\nclass RoleCreateForm(BaseForm):\n\n def __init__(self, data, *args, **kwargs):\n BaseForm.__init__(self, data, *args, **kwargs)\n self.init_err_codes()\n\n def init_err_codes(self):\n self.ERR_CODES.update({\n 'role_name_error': '角色名称为空或数据错误',\n 'role_name_exists': '角色已存在',\n 'permission_error': '权限数据为空或错误',\n 'permission_not_exists': '数据中含有不存在的权限'\n })\n\n def is_valid(self):\n return self.check_role_name() and self.check_permission()\n\n def check_role_name(self):\n if not self.data.get('name', '').strip():\n self.update_errors('name', 'role_name_error')\n return False\n role = Role.objects.filter(name=self.data.get('name'))\n if role:\n self.update_errors('name', 'role_name_exists')\n return False\n return True\n\n def check_permission(self):\n perm_keys = self.data.get('permissions')\n if not perm_keys or len(perm_keys) <= 0:\n self.update_errors('permissions', 'permission_error')\n return False\n permissions = Group.objects.filter(id__in=perm_keys)\n if not permissions or len(permissions) < len(perm_keys):\n self.update_errors('permissions', 'permission_not_exists')\n return False\n return True\n\n def save(self):\n role_data = {\n 'name': self.data.get('name', '').strip(),\n 'codename': \"\",\n 'cate': 'GCR',\n 'desc': self.data.get('desc').strip(),\n }\n permissions = Group.objects.filter(id__in=self.data.get('permissions'))\n role_data['permissions'] = permissions\n return Role.objects.create_role(role_data)\n\n\nclass RoleUpdateForm(BaseForm):\n\n def __init__(self, old_role, data, *args, **kwargs):\n BaseForm.__init__(self, data, *args, **kwargs)\n self.old_role = old_role\n self.init_err_codes()\n\n def init_err_codes(self):\n self.ERR_CODES.update({\n 'role_name_error': '角色名称为空或数据错误',\n 'role_name_exists': '角色已存在',\n 'permission_error': '权限数据为空或错误',\n 'permission_not_exists': '数据中含有不存在的权限'\n })\n\n def is_valid(self):\n return self.check_role_name() and self.check_permission()\n\n def check_role_name(self):\n if not self.data.get('name', '').strip():\n self.update_errors('name', 'role_name_error')\n return False\n role = Role.objects.filter(name=self.data.get('name'))\n if role:\n self.update_errors('name', 'role_name_exists')\n return False\n return True\n\n def check_permission(self):\n perm_keys = self.data.get('permissions')\n if not perm_keys or len(perm_keys) <= 0:\n self.update_errors('permissions', 'permission_error')\n return False\n permissions = Group.objects.filter(id__in=perm_keys)\n if not permissions or len(permissions) < len(perm_keys):\n self.update_errors('permissions', 'permission_not_exists')\n return False\n return True\n\n def save(self):\n role_data = {\n 'name': self.data.get('name', '').strip(),\n 'codename': \"\",\n 'cate': 'GCR',\n 'desc': self.data.get('desc').strip(),\n }\n permissions = Group.objects.filter(id__in=self.data.get('permissions'))\n role_data['permissions'] = permissions\n try:\n new_role = self.old_role.update(role_data)\n new_role.cache()\n return new_role\n except Exception as e:\n logs.exception(e)\n return None\n\n","sub_path":"{{cookiecutter.project_slug}}-back/apps/{{cookiecutter.project_slug}}/hospitals/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":31692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"538751285","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('core', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Cart',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('product_amount', models.IntegerField()),\n ('client', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ('product', models.ForeignKey(to='core.Product')),\n ],\n ),\n migrations.CreateModel(\n name='Order',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('order_date', models.DateTimeField(auto_now_add=True)),\n ('address_city', models.CharField(max_length=40)),\n ('address_district', models.CharField(max_length=40, blank=True)),\n ('address_street', models.CharField(max_length=40)),\n ('address_building', models.CharField(max_length=40)),\n ('state', models.CharField(default=b'ACTIVE', max_length=200)),\n ('client', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='OrderProduct',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('product_amount', models.IntegerField()),\n ('order', models.ForeignKey(to='order.Order')),\n ('product', models.ForeignKey(to='core.Product')),\n ],\n ),\n migrations.CreateModel(\n name='OrdersByDrivers',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('driver', models.ForeignKey(related_name='orders', to=settings.AUTH_USER_MODEL)),\n ('order', models.ForeignKey(to='order.Order')),\n ],\n ),\n migrations.AddField(\n model_name='order',\n name='products',\n field=models.ManyToManyField(to='core.Product', through='order.OrderProduct'),\n ),\n ]\n","sub_path":"apps/order/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"71908359","text":"import requests\r\nimport json\r\nfrom collections import defaultdict\r\n\r\n\r\n\r\ndef ApiCall():\r\n url = \"https://utelly-tv-shows-and-movies-availability-v1.p.rapidapi.com/lookup\"\r\n query=input(\"Szukajka: \")\r\n querystring = {\"term\":query,\"country\":\"uk\"}\r\n\r\n headers = {\r\n 'x-rapidapi-host': \"utelly-tv-shows-and-movies-availability-v1.p.rapidapi.com\",\r\n 'x-rapidapi-key': \"8a2f94d881msh0cee2e1de8e452ep14186ajsnc0a39f09d0de\"\r\n }\r\n\r\n response = requests.request(\"GET\", url, headers=headers, params=querystring)\r\n resp=response.json()\r\n print(resp)\r\n\r\n with open(\"data_file.json\", \"w\") as write_file:\r\n json.dump(resp, write_file)\r\n\r\n\r\n","sub_path":"ApiConnect.py","file_name":"ApiConnect.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"611986401","text":"import logging\nimport pandas as pd\nfrom codex import CodexKg \n\n\n#Load csv data\ndf = pd.read_csv(\"sample_data/tech_companies.csv\")\n\n#Make new codex object\ncodexkg = CodexKg()\n\n#Create new keyspace\ncodexkg.create_db(\"tech_example\")\n\n#Load data into Grakn\ncodexkg.create_entity(df, \"Company\", entity_key=\"name\")\n\n# Find Company that has a name equal to Google\nans = codexkg.find(\n concept=\"Company\",\n concept_attrs=[\"name\"],\n concept_conds=[\"equals\"],\n concept_values=[\"Google\"],\n)\n\n#Display data as a DataFrame\nlogging.info(ans)\n\n# {'Company': name budget\n#\t\t\t\t0 Google 999.99}","sub_path":"codex_test1.py","file_name":"codex_test1.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"176090914","text":"\"\"\"\nBy default all loggers have the propagate flag set to True.\n\nThe propagate essentially means that each logger will handle the message\nand then pass it to the parent for further handling by it.\n\"\"\"\nimport logging\nimport sys\nfrom functools import partial\n\nhprint = partial(print, \"\\n#\")\n\n\ndef main() -> None:\n root_handler = logging.StreamHandler(sys.stdout)\n gandalf_handler = logging.StreamHandler(sys.stdout)\n kek_handler = logging.StreamHandler(sys.stdout)\n\n PRE_FORM = \"{: >10s} --> \"\n root_formatter = logging.Formatter(\n f\"{PRE_FORM.format('ROOT')}:{logging.BASIC_FORMAT}\"\n )\n gandalf_formatter = logging.Formatter(\n f\"{PRE_FORM.format('GANDALF')}:{logging.BASIC_FORMAT}\"\n )\n kek_formatter = logging.Formatter(\n f\"{PRE_FORM.format('KEK')}:{logging.BASIC_FORMAT}\"\n )\n\n root_handler.setFormatter(root_formatter)\n gandalf_handler.setFormatter(gandalf_formatter)\n kek_handler.setFormatter(kek_formatter)\n\n logging.basicConfig(\n handlers=[root_handler],\n level=1\n )\n\n hprint(\"Set up gandalf\")\n gandalf = logging.getLogger('gandalf')\n gandalf.addHandler(gandalf_handler)\n\n hprint(\"Set up gandalf.kek\")\n kek = gandalf.getChild('kek')\n kek.addHandler(kek_handler)\n\n hprint(\"Trigger fatal\")\n kek.fatal(\"BIG_PROBLEM\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"logging/p03_custom_format_per_logger/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"214322611","text":"\n \nimport smtplib \nfrom email.mime.multipart import MIMEMultipart \nfrom email.mime.text import MIMEText\n\nconf = {\n 'add': 'smtp.163.com',\n 'mime': 'vcrting@163.com',\n 'idcan': 'vcrting@163.com',\n 'idgon': 'YWAZVLLPSPJASFIT',\n 'gotter': [\n 'support@manfulls.com' \n ]\n}\n \ndef send_mail(subject, content):\n msg = MIMEMultipart('mixed') \n msg['Subject'] = subject\n msg['From'] = conf['mime'] + ' <' + conf['mime'] + '>'\n msg['To'] = \";\".join(\n conf['gotter']\n ) \n \n msg.attach( \n MIMEText(content, 'plain', 'utf-8')\n ) \n \n smtp = smtplib.SMTP() \n smtp.connect( conf['add'] )\n smtp.login(conf['idcan'], conf['idgon']) \n smtp.sendmail(conf['mime'], conf['gotter'], msg.as_string()) \n smtp.quit()\n\ndef content(success):\n res = ','.join( success )\n res = '本次成功备份的后台有: ' + res \n res = res + '。本次备份成功的时间,即邮件发送时间。'\n return res ","sub_path":"soul/Appis/backup/TOOL/email/send.py","file_name":"send.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"515811980","text":"from preserialize.serialize import serialize\r\n\r\nfrom ledger.accounts.models import EmailUser, Document\r\nfrom wildlifelicensing.apps.applications.models import Application, ApplicationCondition, AmendmentRequest, Assessment, AssessmentCondition\r\nfrom wildlifelicensing.apps.main.helpers import is_customer, is_officer\r\n\r\n\r\nPROCESSING_STATUSES = dict(Application.PROCESSING_STATUS_CHOICES)\r\nID_CHECK_STATUSES = dict(Application.ID_CHECK_STATUS_CHOICES)\r\nRETURNS_CHECK_STATUSES = dict(Application.RETURNS_CHECK_STATUS_CHOICES)\r\nCHARACTER_CHECK_STATUSES = dict(Application.CHARACTER_CHECK_STATUS_CHOICES)\r\nREVIEW_STATUSES = dict(Application.REVIEW_STATUS_CHOICES)\r\nAMENDMENT_REQUEST_REASONS = dict(AmendmentRequest.REASON_CHOICES)\r\nASSESSMENT_STATUSES = dict(Assessment.STATUS_CHOICES)\r\nASSESSMENT_CONDITION_ACCEPTANCE_STATUSES = dict(AssessmentCondition.ACCEPTANCE_STATUS_CHOICES)\r\n\r\n\r\ndef _extend_item_name(name, suffix, repetition):\r\n return '{}{}-{}'.format(name, suffix, repetition)\r\n\r\n\r\ndef create_data_from_form(form_structure, post_data, file_data, post_data_index=None):\r\n data = []\r\n\r\n for item in form_structure:\r\n data.append(_create_data_from_item(item, post_data, file_data, 0, ''))\r\n\r\n return data\r\n\r\n\r\ndef _create_data_from_item(item, post_data, file_data, repetition, suffix):\r\n item_data = {}\r\n\r\n if 'name' in item:\r\n extended_item_name = _extend_item_name(item['name'], suffix, repetition)\r\n else:\r\n raise Exception('Missing name in item %s' % item['label'])\r\n\r\n if 'children' not in item:\r\n if item['type'] in ['checkbox' 'declaration']:\r\n item_data[item['name']] = extended_item_name in post_data\r\n elif item['type'] == 'file':\r\n if extended_item_name in file_data:\r\n item_data[item['name']] = str(file_data.get(extended_item_name))\r\n elif extended_item_name + '-existing' in post_data and len(post_data[extended_item_name + '-existing']) > 0:\r\n item_data[item['name']] = post_data.get(extended_item_name + '-existing')\r\n else:\r\n item_data[item['name']] = ''\r\n else:\r\n if extended_item_name in post_data:\r\n item_data[item['name']] = post_data.get(extended_item_name)\r\n else:\r\n item_data_list = []\r\n for rep in xrange(0, int(post_data.get(extended_item_name, 1))):\r\n child_data = {}\r\n for child_item in item.get('children'):\r\n child_data.update(_create_data_from_item(child_item, post_data, file_data, 0,\r\n '{}-{}'.format(suffix, rep)))\r\n item_data_list.append(child_data)\r\n\r\n item_data[item['name']] = item_data_list\r\n\r\n if 'conditions' in item:\r\n for condition in item['conditions'].keys():\r\n for child in item['conditions'][condition]:\r\n item_data.update(_create_data_from_item(child, post_data, file_data, repetition, suffix))\r\n\r\n return item_data\r\n\r\n\r\ndef convert_documents_to_url(data, document_queryset, suffix):\r\n if isinstance(data, list):\r\n for item in data:\r\n convert_documents_to_url(item, document_queryset, '')\r\n else:\r\n for item, value in data.items():\r\n if isinstance(value, list):\r\n for rep in xrange(0, len(value)):\r\n convert_documents_to_url(value[rep], document_queryset, '{}-{}'.format(suffix, rep))\r\n else:\r\n try:\r\n # for legacy applications, need to check if there's a document where file is\r\n # named by the file name rather than the form field name\r\n data[item] = document_queryset.get(name=value).file.url\r\n except Document.DoesNotExist:\r\n try:\r\n data[item] = document_queryset.get(name='{}{}-0'.format(item, suffix)).file.url\r\n except Document.DoesNotExist:\r\n pass\r\n\r\n\r\nclass SessionDataMissingException(Exception):\r\n pass\r\n\r\n\r\ndef determine_applicant(request):\r\n if 'application' in request.session:\r\n if 'customer_pk' in request.session.get('application'):\r\n try:\r\n applicant = EmailUser.objects.get(pk=request.session['application']['customer_pk'])\r\n except EmailUser.DoesNotExist:\r\n raise SessionDataMissingException('customer_pk does not refer to existing customer')\r\n except EmailUser.MultipleObjectsReturned:\r\n raise SessionDataMissingException('customer_pk does not refer to several customers')\r\n else:\r\n raise SessionDataMissingException('customer_pk not set in session')\r\n else:\r\n raise SessionDataMissingException('application not set in session')\r\n\r\n return applicant\r\n\r\n\r\ndef set_session_application(session, application):\r\n session['application_id'] = application.id\r\n\r\n session.modified = True\r\n\r\n\r\ndef get_session_application(session):\r\n if 'application_id' in session:\r\n application_id = session['application_id']\r\n else:\r\n raise Exception('Application not in Session')\r\n\r\n try:\r\n return Application.objects.get(id=application_id)\r\n except Application.DoesNotExist:\r\n raise Exception('Application not found for application_id {}'.format(application_id))\r\n\r\n\r\ndef delete_session_application(session):\r\n if 'application_id' in session:\r\n del session['application_id']\r\n session.modified = True\r\n\r\n\r\ndef remove_temp_applications_for_user(user):\r\n if is_customer(user):\r\n Application.objects.filter(applicant=user, customer_status='temp').delete()\r\n elif is_officer(user):\r\n Application.objects.filter(proxy_applicant=user, customer_status='temp').delete()\r\n\r\n\r\ndef clone_application_with_status_reset(application, is_licence_amendment=False):\r\n application.customer_status = 'temp'\r\n application.processing_status = 'temp'\r\n\r\n application.id_check_status = 'not_checked'\r\n application.character_check_status = 'not_checked'\r\n application.returns_check_status = 'not_checked'\r\n application.review_status = 'not_reviewed'\r\n\r\n application.correctness_disclaimer = False\r\n application.further_information_disclaimer = False\r\n\r\n application.lodgement_number = ''\r\n application.lodgement_sequence = 0\r\n application.lodgement_date = None\r\n\r\n application.assigned_officer = None\r\n\r\n application.licence = None\r\n\r\n application.is_licence_amendment = is_licence_amendment\r\n\r\n if not is_licence_amendment:\r\n application.invoice_reference = ''\r\n\r\n original_application_pk = application.pk\r\n\r\n application.previous_application = Application.objects.get(pk=original_application_pk)\r\n\r\n application.pk = None\r\n\r\n application.save(no_revision=True)\r\n\r\n # clone variants\r\n for application_variant in Application.variants.through.objects.filter(application=original_application_pk):\r\n application_variant.application = application\r\n application_variant.pk = None\r\n application_variant.save()\r\n\r\n # clone documents\r\n for application_document in Application.documents.through.objects.filter(application=original_application_pk):\r\n application_document.application = application\r\n application_document.pk = None\r\n application_document.save()\r\n\r\n # clone conditions\r\n for application_condition in ApplicationCondition.objects.filter(application=original_application_pk):\r\n application_condition.application = application\r\n application_condition.pk = None\r\n application_condition.save()\r\n\r\n return application\r\n\r\n\r\ndef append_app_document_to_schema_data(schema, data, app_doc):\r\n section = {'type': 'section', 'label': 'Original Application Document', 'name': 'original_application_document'}\r\n section['children'] = [{'type': 'file', 'label': 'Application Document File', 'name': 'application_document'}]\r\n\r\n schema.append(section)\r\n\r\n data.append({'original_application_document': [{'application_document': app_doc}]})\r\n\r\n return schema, data\r\n\r\n\r\ndef get_log_entry_to(application):\r\n if application.proxy_applicant is None:\r\n return application.applicant.get_full_name()\r\n else:\r\n return application.proxy_applicant.get_full_name()\r\n\r\n\r\ndef format_application(instance, attrs):\r\n attrs['processing_status'] = PROCESSING_STATUSES[attrs['processing_status']]\r\n attrs['id_check_status'] = ID_CHECK_STATUSES[attrs['id_check_status']]\r\n attrs['returns_check_status'] = RETURNS_CHECK_STATUSES[attrs['returns_check_status']]\r\n attrs['character_check_status'] = CHARACTER_CHECK_STATUSES[attrs['character_check_status']]\r\n attrs['review_status'] = REVIEW_STATUSES[attrs['review_status']]\r\n\r\n attrs['conditions'] = serialize([ap.condition for ap in instance.applicationcondition_set.all().order_by('order')])\r\n\r\n return attrs\r\n\r\n\r\ndef format_amendment_request(instance, attrs):\r\n attrs['reason'] = AMENDMENT_REQUEST_REASONS[attrs['reason']]\r\n\r\n return attrs\r\n\r\n\r\ndef format_assessment(instance, attrs):\r\n attrs['conditions'] = serialize(instance.assessmentcondition_set.all().order_by('order'),\r\n fields=['acceptance_status', 'id', 'condition'], posthook=format_assessment_condition)\r\n attrs['status'] = ASSESSMENT_STATUSES[attrs['status']]\r\n\r\n return attrs\r\n\r\n\r\ndef format_assessment_condition(instance, attrs):\r\n attrs['acceptance_status'] = ASSESSMENT_CONDITION_ACCEPTANCE_STATUSES[attrs['acceptance_status']]\r\n\r\n return attrs\r\n","sub_path":"wildlifelicensing/apps/applications/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"189520996","text":"import serial\nimport sys\nimport math\nimport struct\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib import animation\n\n\nclass MP:\n packer = struct.Struct('b')\n ser = serial.Serial(sys.argv[1], 115200, timeout=1)\n\n def load(self, data):\n self.ser.write(self.packer.pack(int(data)))\n\n def unload(self):\n return self.packer.unpack(self.ser.read(1))[0]\n\nfig = plt.figure()\nax1 = fig.add_subplot(211, xlim=(0, 256), ylim=(-100, 100))\nline1, = ax1.plot([], [], lw=1)\nax2 = fig.add_subplot(212, xlim=(0, 256), ylim=(-100, 100))\nline2, = ax2.plot([], [], lw=1)\n\nmp = MP()\n\ny1 = np.array([], dtype=int)\ny2 = np.array([], dtype=int)\n\ndef init():\n line1.set_data([], [])\n line2.set_data([], [])\n return line1, line2, \n\ndef animate(i):\n global y1, y2\n if i == 1:\n y1 = np.array([], dtype=int)\n y2 = np.array([], dtype=int)\n x = np.arange(i)\n val = 79\n if i//32%2:\n val = -val\n mp.load(val)\n y1 = np.append(y1, val)\n y2 = np.append(y2, mp.unload())\n line1.set_data(x, y1)\n line2.set_data(x, y2)\n return line1, line2, \n\nframes = range(1, 256) \n\nanim = animation.FuncAnimation(fig, animate, init_func=init,\n frames=frames, interval=50, blit=True)\nplt.show()\n","sub_path":"src/filter_serialRect.py","file_name":"filter_serialRect.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"33400902","text":"import requests\r\nimport json\r\nimport time\r\n\r\n\r\nhost = 'http://localhost:8081'\r\n# host = 'http://192.168.1.100:5000'\r\n\r\n\r\ndef url_for(s):\r\n if s[0] == '/':\r\n return host + s\r\n else:\r\n return host + '/' + s\r\n\r\n\r\ndef post_data(url, prames):\r\n res = ''\r\n txt = '------WebKitFormBoundary7MA4YWxkTrZu0gW'\r\n for d in prames:\r\n res = res + txt + '\\r\\nContent-Disposition: form-data; name=\\\"' + d + '\\\"\\r\\n\\r\\n' + str(prames[d]) + '\\r\\n'\r\n res = res + txt + '--'\r\n headers = {'content-type': \"multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW\", 'Cache-Control': \"no-cache\"}\r\n response = requests.request(\"POST\", url, data=res, headers=headers)\r\n return response.text\r\n\r\n\r\n# 先注册一个设备,获取设备id\r\ndid = 2\r\n\r\n# 获取token\r\nform = {'did': did}\r\nurl = url_for('/get_token')\r\ntoken = post_data(url, form)\r\n\r\nprint(token)\r\n\r\n# 发送心跳\r\nform['token'] = token\r\nprint(post_data(url_for('/beat'), form))\r\n\r\n# 接收数据\r\nwhile True:\r\n task = post_data(url_for('/command_get_task'), form)\r\n time.sleep(0.1)\r\n if task != 'No task.':\r\n break\r\n\r\ntask = json.loads(task)\r\ndata = task['data']\r\nprint(data)\r\ntid = task['tid']\r\nform['tid'] = tid\r\nprint('Get Data:', data)\r\ndata = 'Success'\r\nform['data'] = data.encode()\r\n\r\n# 返回数据\r\nprint(post_data(url_for('/command_fetch'), form))\r\n\r\n\r\n\r\n\r\n","sub_path":"IOT-Noodles/Driver2/driver2.py","file_name":"driver2.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"2058996","text":"\n#Cxyz - C indicates a constant name \nC_DATASET_PATH = './data/hour.csv'\n\nC_PLOT_SIZE = \"plot_size\"\nSUB_PLOT_DIM = \"subplot_Dim\"\n\n#Dxyz - D indicates a dictType variable\nDcolRename = {'weathersit':'weather','mnth':'month','hr':'hour','hum':'humidity','cnt':'count'}\n\n#Lxyz - L indicates a ListType variable\nLcolDrop = ['instant','dteday','yr']\n\nDtypeCaseConv = {'season':'category', 'month':'category' , 'hour' : 'category' , 'holiday':'category' , 'weekday':'category' , 'workingday':'category' , 'weather':'category'}\n\nhours_data=['hour','count','weekday']\n","sub_path":"assets/codes/dataSetSpecifics.py","file_name":"dataSetSpecifics.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"329748868","text":"#!/usr/bin/env python3\r\nfrom My_List import *\r\n\r\ntemp_arr = []\r\n\r\n\r\ndef merge(x, y, comparer, swap):\r\n i, j = 0, 0\r\n result = []\r\n while i < len(x) and j < len(y):\r\n if comparer(x[i] <= y[j]):\r\n result.append(x[i])\r\n i += 1\r\n else:\r\n result.append(y[j])\r\n j += 1\r\n if i < len(x):\r\n result += x[i:]\r\n else:\r\n result += y[j:]\r\n return result\r\n\r\n\r\ndef merge_sort(array):\r\n if len(array) > 1:\r\n middle = len(array) // 2\r\n return merge(merge_sort(array[:middle]), merge_sort(array[middle:]))\r\n return array\r\n\r\n\r\ndef call_merge_sort(arr):\r\n return merge_sort(arr)\r\n\r\n\r\nif __name__ == '__main__':\r\n arr = [1, 6, 8, 9, 10, 5, 2]\r\n print(call_merge_sort(arr))\r\n","sub_path":"merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"386771191","text":"from django.shortcuts import render,redirect\nfrom django.http import HttpResponse,Http404\nfrom .models import Project,Profile,Review\nfrom django.contrib import messages\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import ProjectForm,ProfileForm,NewReviewForm\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom .serializer import ProjectSerializer\nfrom .serializer import ProfileSerializer\nfrom rest_framework import status\n\n# Create your views here.\n@login_required(login_url='/accounts/login/')\ndef index(request):\n current_user = request.user\n projects = Project.get_all()\n return render(request,'landing.html',{'projects':projects})\n\ndef project(request,project_id):\n project = Project.objects.get(id = project_id)\n reviews=Review.get_all_reviews(project_id)\n project.design=reviews['design']\n project.userinterface=reviews['userinterface']\n project.functionality=reviews['functionality']\n project.content=reviews['content']\n project.average_review=reviews['average_review']\n project.save()\n current_user=request.user\n if request.method=='POST':\n form=NewReviewForm(request.POST)\n if form.is_valid():\n review=form.save(commit=False)\n review.judge=current_user\n review.project=project\n \n review.save()\n messages.success(request,f'Review Submitted')\n return redirect('project-detail',project_id)\n else:\n form=NewReviewForm() \n return render(request,'project.html',{'form':form,'project':project})\n\n@login_required(login_url='/accounts/login/')\ndef new_project(request):\n current_user = request.user\n if request.method == 'POST':\n form = ProjectForm(request.POST, request.FILES)\n if form.is_valid():\n project = form.save(commit=False)\n project.profile = current_user\n project.save()\n return redirect('indexPage')\n\n else:\n form = ProjectForm()\n return render(request, 'new_post.html', {\"form\": form})\n\ndef profile(request):\n current_user = request.user\n projects = Project.objects.filter(profile=current_user).all()\n profile = Profile.objects.filter(profile=current_user)\n\n if len(profile)<1:\n profile = \"No profile\"\n else:\n profile = Profile.objects.get(profile=current_user)\n\n return render(request, 'profile/profile.html',{'projects':projects,'profile':profile})\n@login_required\ndef edit_profile(request):\n current_user = request.user\n if request.method == 'POST':\n form = ProfileForm(request.POST, request.FILES,instance = request.user.profile)\n if form.is_valid():\n form.save()\n return redirect('Profile')\n else:\n form = ProfileForm(instance = request.user.profile)\n return render(request,'profile/edit_profile.html',{'form':form})\n\ndef search_results(request):\n\n if 'project' in request.GET and request.GET[\"project\"]:\n search_term = request.GET.get(\"project\")\n searched_projects = Project.search_by_title(search_term)\n message = f\"{search_term}\"\n\n return render(request, 'search.html',{\"message\":message,\"projects\": searched_projects})\n\n else:\n message = \"You haven't searched for any term\"\n return render(request, 'search.html',{\"message\":message})\n\ndef search_project(request,project_id):\n try :\n project = Project.objects.get(id = project_id)\n\n except ObjectDoesNotExist:\n raise Http404()\n return render(request, 'project_details.html', {'project':project})\n\nclass ProjectList(APIView):\n def get(self,request,format=None):\n all_projects=Project.objects.all()\n serializers=ProjectSerializer(all_projects,many=True)\n return Response(serializers.data)\n\n\nclass ProfileList(APIView):\n def get(self,request,format=None):\n all_profiles=Profile.objects.all()\n serializers=ProfileSerializer(all_profiles,many=True)\n return Response(serializers.data)\n\n\n\n","sub_path":"RateInc/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"187412837","text":"import os, subprocess\ntry:\n\tfrom inits.inits import Inits\nexcept:\n\tfrom inits import Inits\n\n\nclass CreateData(object):\n\t\"\"\"\n\tWill create files nesessary to retreave bios information\n\t\"\"\"\n\n\tf=Inits()\n\n\tdef __init__(self, order_no):\n\t\tself.data_folder(order_no)\n\t\tself.master_data(order_no)\n\t\tself.hdd_data(order_no)\n\n\n\t# creates a folder with serial number of unit\n\tdef data_folder(self, order_no):\n\t\tfolder_dir=order_no+\"-\"+self.f.get_serial()+'-SYS_DATA'\n\t\tdata_folder=self.f.dirs(order_no+\"-\"+self.f.get_serial()+'-SYS_DATA')\n\n\t\tif not os.path.exists(data_folder):\n\t\t\tos.makedirs(data_folder)\n\t\t\treturn folder_dir\n\t\treturn folder_dir\n\n\n\t# Will loop trough all dmidecode options and generate files\n\tdef master_data(self, order_no):\n\t\tdata_folder=self.data_folder(order_no)\n\t\tdmidecode_options=[ \"bios\", \"system\", \"baseboard\", \"chassis\", \"processor\",\n\t\t\t\t\t\t\t\"memory\", \"cache\", \"connector\", \"slot\", \"39\", \"slot\"]\n\n\t\tls_data=[\"lsscsi\", \"lspci\", \"lsusb\"] \n\t\thard_data=\"hardinfo -ra -f text\"\n\t\twodim_data=\"wodim -inq\" \n\n\t\t# generates DMIDECODE text files\n\t\tfor option in dmidecode_options:\n\t\t\tif not os.path.exists(self.f.dirs(data_folder+\"/\")+option+\".txt\"):\n\t\t\t\tos.system(\"sudo dmidecode -t \"+option+\" > \"+self.f.dirs(data_folder+\"/\")+option+\".txt\")\n\n\t\t# generates ls suite text file\n\t\tfor option in ls_data:\n\t\t\tif not os.path.exists(self.f.dirs(data_folder+\"/\")+option+\".txt\"):\n\t\t\t\tos.system(\"sudo \"+option+\" > \"+self.f.dirs(data_folder+\"/\")+option+\".txt\")\n\n\t\t# generates wodim suite text file for optical drive\n\t\tif not os.path.exists(self.f.dirs(data_folder+\"/wodim.txt\")):\n\t\t\tos.system(\"sudo \"+wodim_data+\" > \"+self.f.dirs(data_folder+\"/wodim.txt\"))\n\n\t\t# run bench mark test and generates hardinfo file\n\t\tif not os.path.exists(self.f.dirs(data_folder+\"/hardinfo.txt\")):\n\t\t\tos.system(\"sudo \"+hard_data+\" > \"+self.f.dirs(data_folder+\"/hardinfo.txt\"))\n\t\t\tos.system('sudo clear')\n\n\n\n\tdef hdd_data(self, order_no):\n\t\tdata_folder=self.data_folder(order_no)\n\n\t\tdev_arr=[]\n\t\tserial_arr=[]\n\n\t\ttry:\n\t\t\tif not os.path.exists(self.f.dirs(data_folder+\"/HDD\")):\n\t\t\t\tos.makedirs(self.f.dirs(data_folder+\"/HDD\"))\n\n\t\t\tdevices=subprocess.Popen('sudo hdparm -I /dev/sd? | grep \"dev/sd\"', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n\t\t\tserial_No=subprocess.Popen('sudo hdparm -I /dev/sd? | grep \"Serial\\ Number\"', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n\n\t\t\t# gets HDD location\n\t\t\tfor dev in devices.stdout.readlines():\n\t\t\t\tdev=str(dev)\n\t\t\t\tif \"SG_IO:\" not in dev:\n\t\t\t\t\tdev_arr.append(dev.replace('b\\'', '').replace(\":\\\\n'\", \"\"))\n\n\t\t\t# gets HDD serial number\n\t\t\tfor serial in serial_No.stdout.readlines():\n\t\t\t\tserial=str(serial).replace('b\\'\\\\t', '').replace(\"\\\\n'\", \"\")\n\t\t\t\tserial=serial.replace(\"WD-\", \"\")\n\t\t\t\tif \"SG_IO:\" not in serial:\n\t\t\t\t\tserial=serial.split()\n\t\t\t\t\tserial_arr.append(serial[2])\n\n\n\t\t\t# saves data to file\n\t\t\tfor dev, serial in zip(dev_arr, serial_arr):\n\t\t\t\tif \"hrDvi\" not in serial:\n\t\t\t\t\tfolder=self.f.dirs(data_folder+\"/HDD/\")\n\t\t\t\t\tif self.f.dirs(data_folder+\"/HDD\"):\n\t\t\t\t\t\tos.system('sudo smartctl -a '+dev+' > '+folder+serial+\".txt\")\n\t\texcept:\n\t\t\tpass\n\n# c=CreateData()\n# c.hdd_data(\"123\")","sub_path":"inits/create_data.py","file_name":"create_data.py","file_ext":"py","file_size_in_byte":3135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"650895079","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('core', '0013_auto_20150508_1143'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='BusinessProfile',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ],\n ),\n migrations.CreateModel(\n name='Group',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=50)),\n ('group_type', models.IntegerField(choices=[(1, b'Guarantor Group'), (2, b'Savings Group')])),\n ],\n ),\n migrations.CreateModel(\n name='GroupMember',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('group', models.ForeignKey(related_name='groups', to='core.Group', unique=True)),\n ],\n ),\n migrations.CreateModel(\n name='MemberProfile',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('first_name', models.CharField(max_length=30, null=True, verbose_name=b'first name', blank=True)),\n ('middle_name', models.CharField(max_length=30, null=True, verbose_name=b'middle name', blank=True)),\n ('surname', models.CharField(max_length=30, null=True, verbose_name=b'first name', blank=True)),\n ],\n ),\n migrations.AlterModelOptions(\n name='member',\n options={'verbose_name': 'member', 'verbose_name_plural': 'members'},\n ),\n migrations.AlterModelManagers(\n name='member',\n managers=[\n ],\n ),\n migrations.RemoveField(\n model_name='member',\n name='extra_fields',\n ),\n migrations.RemoveField(\n model_name='member',\n name='first_name',\n ),\n migrations.RemoveField(\n model_name='member',\n name='last_name',\n ),\n migrations.RemoveField(\n model_name='member',\n name='meta',\n ),\n migrations.RemoveField(\n model_name='member',\n name='overdraft_credit_line',\n ),\n migrations.RemoveField(\n model_name='member',\n name='username',\n ),\n migrations.AlterField(\n model_name='member',\n name='email',\n field=models.EmailField(max_length=255, verbose_name=b'email address'),\n ),\n migrations.AlterField(\n model_name='member',\n name='member_type',\n field=models.IntegerField(default=4, choices=[(1, b'Staff'), (2, b'Customer'), (2, b'Group'), (3, b'Corporate Customer'), (4, b'Customer'), (5, b'Commitee Member')]),\n ),\n migrations.AlterField(\n model_name='member',\n name='mobile_phone_number',\n field=models.CharField(help_text=b'Mobile phone number to start with 07xx. Safaricom, Airtel and Orange Money are allowed', unique=True, max_length=10, db_index=True),\n ),\n migrations.AddField(\n model_name='memberprofile',\n name='member',\n field=models.ForeignKey(related_name='member_profile', to=settings.AUTH_USER_MODEL, unique=True),\n ),\n migrations.AddField(\n model_name='businessprofile',\n name='member',\n field=models.ForeignKey(related_name='business_profile', to=settings.AUTH_USER_MODEL),\n ),\n ]\n","sub_path":"ajabsacco/core/migrations/0014_auto_20150508_1714.py","file_name":"0014_auto_20150508_1714.py","file_ext":"py","file_size_in_byte":3909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"54029866","text":"import enum\r\nimport os\r\nimport random\r\nimport re\r\nimport time\r\nfrom typing import Optional\r\n\r\nimport yaml\r\nfrom mcdreforged.api.all import *\r\n\r\nPLUGIN_METADATA = {\r\n 'id': 'livebot_controller',\r\n 'version': '0.2.2',\r\n 'name': 'LiveBotController',\r\n 'description': \"A MCDR plugin for controlling livebot\",\r\n 'author': ['Youmiel','YehowahLiu'],\r\n 'link': 'https://github.com/FAS-Server/LiveBotController',\r\n 'dependencies': {\r\n 'mcdreforged': '>=1.0.0',\r\n }\r\n}\r\n\r\nSTATE_PATTERN = re.compile(r'Bot state: (Normal|Offline|Spectating [\\w]{3,16})')\r\n# Botstate: Offline | Normal | Spectating \r\nLIST_PATTERN = re.compile(r'There are ([0-9]+) of a max of ([0-9]+) players online:\\s?(.*)')\r\n# group(1): player number\r\n# group(2): max players\r\n# group(3): player list\r\nCONFIG_PATH = os.path.join('config', 'LiveBotController.yml')\r\nLIVEBOT_CONFIG = os.path.join('server', 'LiveBotFabric', 'config.json')\r\nLANDSCAPE_PATH = os.path.join('config', 'LiveBotLandscape.txt')\r\n\r\nPREFIX = \"!!live\"\r\n\r\ndefault_config = {\r\n 'randomTpDelay': 30,\r\n 'excludedPrefix': '',\r\n 'excludedSuffix': '',\r\n}\r\nconfig = default_config.copy()\r\n\r\n\r\n# -------------------------------------------\r\nclass PlayerStack:\r\n players: list\r\n\r\n def __init__(self) -> None:\r\n self.players = []\r\n\r\n def push(self, player: str):\r\n if player in self.players:\r\n self.players.remove(player)\r\n self.players.append(player)\r\n\r\n def pop(self) -> Optional[str]:\r\n if len(self.players) > 0:\r\n player = self.players[-1]\r\n self.players.remove(player)\r\n return player\r\n else:\r\n return None\r\n\r\n def top(self):\r\n if len(self.players) > 0:\r\n return self.players[-1]\r\n else:\r\n return None\r\n\r\n def size(self):\r\n return len(self.players)\r\n\r\nclass LiveBotController:\r\n class Mode(enum.Enum):\r\n EMPTY = 'EMPTY'\r\n OCCUPIED = 'OCCUPIED'\r\n RANDOM = 'RANDOM'\r\n\r\n def __init__(self) -> None:\r\n self.online = False\r\n self.running = False\r\n self.mode = LiveBotController.Mode.EMPTY\r\n self.occupied_players = PlayerStack()\r\n self.time_since_last_tp = time.time()\r\n\r\n def start(self) -> None:\r\n self.running = True\r\n cast('bot_start')\r\n self.tick()\r\n\r\n @new_thread('LiveBotController')\r\n def tick(self):\r\n while self.running:\r\n if self.online:\r\n if self.occupied_players.size() == 0 and self.mode != LiveBotController.Mode.RANDOM:\r\n self.mode = LiveBotController.Mode.RANDOM\r\n if self.occupied_players.size() > 0 and self.mode != LiveBotController.Mode.OCCUPIED:\r\n self.mode = LiveBotController.Mode.OCCUPIED\r\n {\r\n LiveBotController.Mode.EMPTY: self.do_empty,\r\n LiveBotController.Mode.OCCUPIED: self.do_occupied,\r\n LiveBotController.Mode.RANDOM: self.do_random,\r\n }[self.mode]()\r\n time.sleep(1)\r\n cast('bot_stop')\r\n\r\n def do_empty(self): # really empty :)\r\n pass\r\n\r\n def do_occupied(self):\r\n global plugin_fields\r\n if self.occupied_players.top() not in plugin_fields.player_list:\r\n self.occupied_players.pop()\r\n if self.occupied_players.size() != 0:\r\n plugin_fields.server.rcon_query(\"botfollow %s\" % self.occupied_players.top())\r\n\r\n def do_random(self):\r\n global plugin_fields, config\r\n if (time.time() - self.time_since_last_tp) < config['randomTpDelay']:\r\n return\r\n self.time_since_last_tp = time.time()\r\n if self.online and len(plugin_fields.player_list) <= 1:\r\n if len(plugin_fields.landscapes) > 0:\r\n index = random.randint(0, len(plugin_fields.landscapes) - 1)\r\n plugin_fields.server.rcon_query(plugin_fields.landscapes[index])\r\n elif self.online:\r\n '''\r\n pattern = plugin_fields.player_pattern\r\n while(len(plugin_fields.player_list) > 1):\r\n index = random.randint(0, len(plugin_fields.player_list) - 1)\r\n player = plugin_fields.player_list[index]\r\n if re.fullmatch(pattern, player) is None: \r\n break\r\n # old logic\r\n '''\r\n index = random.randint(0, len(plugin_fields.player_list) - 1)\r\n player = plugin_fields.player_list[index]\r\n plugin_fields.server.rcon_query(\"botfollow %s\" % player)\r\n\r\n def add_occupation(self, player: str):\r\n if self.online and self.running:\r\n self.occupied_players.push(player)\r\n plugin_fields.server.rcon_query('botfollow %s' % player)\r\n plugin_fields.server.broadcast('玩家 %s 临时获得了直播视角的控制权' % player)\r\n\r\n def copy(self):\r\n bot = LiveBotController()\r\n bot.mode = self.mode\r\n bot.occupied_players = self.occupied_players\r\n bot.online = self.online\r\n bot.running = self.running\r\n bot.time_since_last_tp = self.time_since_last_tp\r\n return bot\r\n\r\n\r\n# -------------------------------------------\r\nclass Fields:\r\n def __init__(self) -> None:\r\n self.server = None\r\n self.bot = LiveBotController()\r\n #self.player_num = 0\r\n self.player_list = []\r\n #self.landscape_num = 0\r\n self.landscapes = []\r\n self.player_pattern = None\r\n\r\n\r\nplugin_fields = Fields()\r\n\r\n\r\n# -------------------------------------------\r\ndef load_config(server: ServerInterface):\r\n global config\r\n try:\r\n config = {}\r\n with open(CONFIG_PATH) as file:\r\n conf_yaml = yaml.load(file, Loader=yaml.Loader) # idk why CLoader doesn't work\r\n for key in default_config.keys():\r\n config[key] = conf_yaml[key]\r\n server.logger.info('Config file loaded')\r\n except Exception as e:\r\n server.logger.warning('fail to read config file: %s, using default config' % e)\r\n config = default_config.copy()\r\n with open(CONFIG_PATH, 'w') as file:\r\n yaml.dump(default_config, file)\r\n\r\n\r\ndef load_landscape(server: ServerInterface):\r\n global plugin_fields\r\n try:\r\n with open(LANDSCAPE_PATH, 'r') as file:\r\n plugin_fields.landscapes = []\r\n for line in file:\r\n #plugin_fields.landscapes.append(str.removesuffix(line, '\\n'))\r\n plugin_fields.landscapes.append(line.replace('\\n', ''))\r\n server.logger.info('Landscape file loaded')\r\n except FileNotFoundError as e:\r\n server.logger.warning('fail to read landscape file: %s, creating it automatically.' % e)\r\n with open(LANDSCAPE_PATH, 'w') as file:\r\n pass\r\n\r\n\r\ndef build_command(server: ServerInterface):\r\n # register help message\r\n server.register_help_message(PREFIX, \"Control the livebot\")\r\n node = Literal(PREFIX).runs(occupy)\r\n server.register_command(node)\r\n server.register_command(Literal('!!test').requires(lambda src: src.has_permission(3)).runs(peek))\r\n\r\n\r\n@new_thread('LiveBotController_checkRcon')\r\ndef check_rcon():\r\n global plugin_fields\r\n time.sleep(1)\r\n # plugin_fields.server.logger.info('testing RCON...\\n')\r\n if plugin_fields.server.is_server_startup() and not plugin_fields.server.is_rcon_running():\r\n cast('no_rcon')\r\n plugin_fields.server.unload_plugin(PLUGIN_METADATA['id'])\r\n\r\n\r\n@new_thread('UpdatePlayer')\r\ndef update_player_list(server: ServerInterface):\r\n global plugin_fields\r\n query = server.rcon_query('list')\r\n match = re.match(LIST_PATTERN, query)\r\n if match:\r\n plugin_fields.player_list = re.split(',\\s', match.group(3))\r\n for player in plugin_fields.player_list:\r\n if plugin_fields.player_pattern is None:\r\n break\r\n if re.fullmatch(plugin_fields.player_pattern, player.lower()) is not None:\r\n plugin_fields.server.logger.info('remove %s' % player)\r\n plugin_fields.player_list.remove(player)\r\n\r\n\r\n@new_thread('UpdatePlayer')\r\ndef update_bot_state(server: ServerInterface):\r\n global plugin_fields\r\n query = server.rcon_query('botstate')\r\n match = re.match(STATE_PATTERN, query)\r\n if match:\r\n if plugin_fields.bot.online and match.group(1) == 'Offline':\r\n plugin_fields.bot.online = False\r\n elif not (plugin_fields.bot.online or match.group(1) == 'Offline'):\r\n plugin_fields.bot.online = True\r\n\r\n\r\ndef occupy(cmd_src: CommandSource):\r\n global plugin_fields\r\n if cmd_src.is_player:\r\n plugin_fields.bot.add_occupation(cmd_src.player)\r\n else:\r\n cast('console_warning')\r\n\r\n\r\ndef cast(event: str):\r\n global plugin_fields\r\n server = plugin_fields.server\r\n {\r\n 'bot_start': lambda: server.logger.info('Bot started.'),\r\n 'bot_stop': lambda: server.logger.info('Bot stopped.'),\r\n 'console_warning': lambda: server.logger.warning('Console command is not supported.'),\r\n 'no_rcon': lambda: server.logger.warning('RCON is not enabled, unloading plugin.'),\r\n 'thing': lambda: server.logger.info('something\\n')\r\n }[event]()\r\n\r\n\r\ndef peek(cmd_src: CommandSource):\r\n cmd_src.reply('plugin_fields:' + plugin_fields.player_list.__str__() + '_%d' % len(plugin_fields.player_list))\r\n cmd_src.reply('landscape:' + plugin_fields.landscapes.__str__() + '_%d' % len(plugin_fields.landscapes))\r\n cmd_src.reply('bot: mode: ' + plugin_fields.bot.mode.__str__() +\r\n ', running: ' + plugin_fields.bot.running.__str__() +\r\n ', online: ' + plugin_fields.bot.online.__str__() +\r\n ', list: ' + plugin_fields.bot.occupied_players.players.__str__() +\r\n ', count: ' + plugin_fields.bot.occupied_players.size().__str__())\r\n cmd_src.reply('config: ' + config.__str__())\r\n pass\r\n\r\n\r\n# -------------------------------------------\r\n\r\ndef on_load(server: ServerInterface, old_module):\r\n global plugin_fields, config\r\n if old_module is not None:\r\n plugin_fields = old_module.plugin_fields\r\n plugin_fields.bot = old_module.plugin_fields.bot.copy()\r\n plugin_fields.server = server\r\n load_config(server)\r\n load_landscape(server)\r\n check_rcon()\r\n if config['excludedPrefix'] != '' or config['excludedSuffix'] != '':\r\n plugin_fields.player_pattern = re.compile(\r\n r'(' + config['excludedPrefix'].lower() + r')' +\r\n r'\\w+' +\r\n r'(' + config['excludedSuffix'].lower() + r')'\r\n )\r\n else:\r\n plugin_fields.player_pattern = None\r\n build_command(server)\r\n if server.is_server_startup():\r\n plugin_fields.bot.start()\r\n\r\n\r\ndef on_unload(server: ServerInterface):\r\n global plugin_fields\r\n plugin_fields.bot.running = False\r\n\r\n\r\ndef on_server_stop(server: ServerInterface, code: int):\r\n global plugin_fields\r\n plugin_fields.bot.running = False\r\n\r\n\r\ndef on_server_startup(server: ServerInterface):\r\n global plugin_fields\r\n check_rcon()\r\n plugin_fields.bot.start()\r\n\r\n\r\ndef on_player_left(server: ServerInterface, player):\r\n update_player_list(server)\r\n update_bot_state(server)\r\n\r\n\r\ndef on_player_joined(server: ServerInterface, player: str, info: Info):\r\n update_player_list(server)\r\n update_bot_state(server)\r\n","sub_path":"LiveBotController.py","file_name":"LiveBotController.py","file_ext":"py","file_size_in_byte":11462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"617806778","text":"# coding: utf8\nfrom __future__ import unicode_literals\nfrom unittest import TestCase\nfrom collections import defaultdict\n\nfrom pycdstar.tests.util import get_api, Response\nfrom pycdstar.resource import Object\n\n\ndef args(d=None, default=None):\n return defaultdict(lambda: default, d or {})\n\n\ndef object(**kw):\n kw.setdefault('uid', 'a')\n return Object(get_api(ret=Response(kw)))\n\n\nclass Tests(TestCase):\n def test_metadata(self):\n from pycdstar.commands import c_metadata\n\n res = c_metadata(get_api(obj=object()), args({'': 'a'}))\n self.assertIn('uid', res)\n c_metadata(get_api(obj=object()), args({'': 'a', '': '{}'}))\n\n def test_delete(self):\n from pycdstar.commands import c_delete\n\n assert c_delete(get_api(obj=object()), args({'': 'a'}), verbose=True)\n\n def test_ls(self):\n from pycdstar.commands import c_ls\n\n res = c_ls(get_api(obj=object(bitstream=[])), args({'': 'a', '-s': True}))\n assert len(list(res)) == 0\n res = c_ls(\n get_api(obj=object(bitstream=[defaultdict(lambda: 1)])),\n args({'': 'a'}, default=True))\n assert len(list(res)) == 1\n\n def test_create(self):\n from pycdstar.commands import c_create\n\n res = list(c_create(\n get_api(),\n args({\n '
': '.',\n '--metadata': '{}',\n '--include': '*.py',\n '--exclude': '*.pyc'}),\n verbose=True))\n assert res\n","sub_path":"pycdstar/tests/test_commands.py","file_name":"test_commands.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"172978068","text":"import struct\nimport math\nfrom obj import Obj\n\ndef char(c):\n return struct.pack(\"=c\", c.encode('ascii'))\n\ndef word(c):\n return struct.pack(\"=h\", c)\n\ndef dword(c):\n return struct.pack(\"=l\", c)\n\ndef color(r, g, b):\n return bytes([b, g, r])\n\nclass Bitmap(object):\n def __init__(self, width, height):\n self.width = width\n self.height = height\n self.framebuffer = []\n self.newGlColor = color(255, 255, 255)\n self.clear()\n \n\n #structure image file \n def writeFile(self, filename):\n f = open(filename, \"wb\")\n # estandar\n f.write(char('B'))\n f.write(char('M'))\n # file size\n f.write(dword(14 + 40 + self.width * self.height * 3))\n # reserved\n f.write(dword(0))\n # data offset\n f.write(dword(54))\n # header size\n f.write(dword(40))\n # width\n f.write(dword(self.width))\n # height\n f.write(dword(self.height))\n # planes\n f.write(word(1))\n # bits per pixel\n f.write(word(24))\n # compression\n f.write(dword(0))\n # image size\n f.write(dword(self.width * self.height * 3))\n # x pixels per meter\n f.write(dword(0))\n # y pixels per meter\n f.write(dword(0))\n # number of colors\n f.write(dword(0))\n # important colors\n f.write(dword(0))\n # image data\n for x in range(self.height):\n for y in range(self.width):\n f.write(self.framebuffer[x][y])\n # close file\n f.close()\n \n #clear the canvas with a new color \n def clearColor(self, r, g, b): \n newR = math.floor(r*255)\n newG = math.floor(g*255)\n newB = math.floor(b*255)\n\n self.framebuffer = [\n [color(newR, newG, newB) for x in range(self.width)]\n for y in range(self.height)\n ]\n \n # Clear image \n def clear(self):\n self.framebuffer = [\n [\n #show background color \n self.color(0,0,0) for x in range(self.width)\n ]\n for y in range(self.height)\n ]\n\n # get dimension image (begin of glViewPort)\n def viewPort(self, x, y, width, height):\n self.viewPortWidth = width\n self.viewPortHeight = height\n self.xViewPort = x\n self.yViewPort = y\n \n def getRXCoord(self, x):\n dx = x * (self.viewPortWidth / 2)\n realXVP = (self.viewPortWidth / 2) + dx\n realX = realXVP + self.xViewPort\n return realX\n\n def getRYCoord(self, y):\n dy = y * (self.viewPortHeight / 2)\n realYVP = (self.viewPortHeight / 2) + dy\n realY = realYVP + self.yViewPort\n return realY\n\n def getNormXCoord(self, realX):\n realXVP = realX - self.xViewPort\n dx = realXVP - (self.viewPortWidth / 2)\n x = dx / (self.viewPortWidth / 2)\n return x\n\n def getNormYCoord(self, realY):\n realYVP = realY - self.yViewPort\n dy = realYVP - (self.viewPortHeight / 2)\n y = dy / (self.viewPortHeight / 2)\n return y\n\n # create new canvas to draw image \n def vertex(self, x, y):\n if ((x >= -1 and x <= 1) and (y >= -1 and y <= 1)):\n # x \n dx = x * (self.viewPortWidth / 2)\n realXVP = (self.viewPortWidth / 2) + dx\n\n # y\n dy = y * (self.viewPortHeight / 2)\n realYVP = (self.viewPortHeight / 2) + dy\n\n # Add new viewports \n realX = realXVP + self.xViewPort\n realY = realYVP + self.yViewPort \n\n # draw inside dimensions \n if ((realX <= self.width) and (realY <= self.height)):\n if (realX == self.width):\n realX = self.width - 1\n if (realY == self.height): \n realY = self.height - 1\n print(\"x\" , realX)\n print(\"y\", realY)\n self.framebuffer[math.floor(realY)][math.floor(realX)] = self.newGlColor\n\n def color(self, r, g, b):\n newR = math.floor(r*255)\n newG = math.floor(g*255)\n newB = math.floor(b*255)\n\n self.newGlColor = color(newR, newG, newB)\n return self.newGlColor\n\n def point(self, x, y):\n self.framebuffer[int(y)][int(x)] = self.newGlColor\n\n def load(self, filename, translate=(0, 0), scale=(1, 1)):\n model = Obj(filename)\n\n for face in model.vfaces:\n vcount = len(face)\n for j in range(vcount):\n f1 = face[j][0]\n f2 = face[(j+1)%vcount][0]\n\n v1 = model.vertices[f1 - 1]\n v2 = model.vertices[f2 - 1]\n\n # scaleX, scaleY = scale\n #translateX, translateY = translate\n\n x1 = v1[0]\n y1 = v1[1] \n x2 = v2[0] \n y2 = v2[1] \n \n self.line(x1, y1, x2, y2)\n\n def line (self, x1, y1, x2, y2): \n \n x1 = math.floor(self.getRXCoord(x1))\n x2 = math.floor(self.getRXCoord(x2))\n y1 = math.floor(self.getRYCoord(y1))\n y2 = math.floor(self.getRYCoord(y2))\n\n dy = abs(y2 - y1) \n dx = abs(x2 - x1) \n\n steep = dy > dx \n\n if steep: \n x1, y1 = y1 , x1 \n x2, y2 = y2, x2 \n\n if x1 > x2: \n x1,x2 = x2, x1 \n y1, y2 = y2, y1\n\n dy = abs(y2 - y1) \n dx = abs(x2 - x1) \n\n offset = 0 * 2 * dx\n threshold = 0.5 * 2 * dx\n\n y = y1 \n\n for x in range (x1,x2 +1): \n if steep: \n self.point(y, x)\n else: \n self.point(x, y)\n\n offset += dy * 2\n if offset >= threshold: \n y += 1 if y1 < y2 else -1 \n threshold += 1 * 2 * dx","sub_path":"libs.py","file_name":"libs.py","file_ext":"py","file_size_in_byte":5899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"195547087","text":"# -*- coding: utf-8 -*-\n\"\"\"\nFlow stats functions.\n\"\"\"\nimport os\nimport numpy as np\nimport pandas as pd\nfrom scipy.signal import argrelmax\nfrom hydropandas.tools.general.ts.misc import df_first_valid, df_last_valid, tsreg\nfrom hydropandas.tools.general.general.lm import LM\n\n###################################################\n### HydroPandas tool dict\nhp_tool_dict = {'flow_stats': {'sel_ts': {'dformat': 'wide', 'feature': 'river', 'mtype': 'flow', 'msource': ['rec', 'syth']}}}\n\n###################################################\n### Flow tools\n\n\ndef flow_stats(df, below_median=False, export_path=None):\n \"\"\"\n Function to run summary stats on time series flow data.\n\n Parameters\n ----------\n df : DataFrame or Series\n Pandas DataFrame or Series with a daily DateTimeIndex.\n below_median : bool\n Should the average number of days below the median be added?\n export_path : str\n Path where the results will be exported.\n\n Returns\n -------\n DataFrame\n \"\"\"\n\n # Make sure the object is a data frame\n if not isinstance(df, pd.DataFrame):\n raise TypeError('df must be a DataFrame')\n df = df.dropna(axis=1, how='all')\n\n # Run the stats\n zero_count = df[df == 0].count()\n d_count = df.count()\n min1 = df.min()\n max1 = df.max()\n mean1 = df.mean()\n max1 = df.max()\n median1 = df.median()\n quarter1 = df.apply(lambda x: np.nanpercentile(x, 25))\n quarter3 = df.apply(lambda x: np.nanpercentile(x, 75))\n max_time = df.idxmax()\n min_time = df.idxmin()\n first_time = df_first_valid(df)\n last_time = df_last_valid(df)\n periods = (last_time - first_time).astype('timedelta64[D]').astype('int') + 1\n mis_days = periods - d_count\n mis_days_ratio = mis_days / periods\n years = d_count / 365.25\n\n # prepare output\n row_names = [\"Min\", '25%', \"Median\", \"Mean\", '75%', \"Max\", \"Start Date\",\n \"End date\", \"Min date\", \"Max Date\", \"Zero days\", \"Missing days\",\n \"Missing ratio\", \"Tot data yrs\"]\n temp1 = pd.concat([min1, quarter1, median1, mean1, quarter3, max1], axis=1).round(3)\n temp2 = pd.concat([first_time.astype(str), last_time.astype(str), min_time.astype(str), max_time.astype(str), zero_count, mis_days, mis_days_ratio.round(3), years.round(1)], axis=1)\n df2 = pd.concat([temp1, temp2], axis=1)\n\n ### Add in the average number of days below median if specified\n if below_median:\n median_avg = median1.copy()\n row_names.extend([\"Avg_days_below_median\"])\n for i in median_avg.index:\n val = float(median_avg[i])\n t1 = df[i][df[i] <= val].count() / years[i]\n median_avg.loc[i] = t1.round(1)\n df2 = pd.concat([df2, median_avg], axis=1)\n df2.columns = row_names\n df2.index.name = 'site'\n\n # Export data and return dataframe\n if isinstance(export_path, str):\n df2.to_csv(export_path)\n return df2\n\n\ndef malf7d(df, w_month='JUN', max_missing=90, malf_min=0.9, intervals=[10, 20, 30, 40], return_alfs=False, num_years=False, export_path=None, export_name_malf='malf.csv', export_name_alf='alf.csv', export_name_mis='alf_missing_data.csv'):\n \"\"\"\n Function to create a 7 day mean annual low flow estimate from flow time\n series.\n\n Parameters\n ----------\n df : DataFrame or Series\n Pandas DataFrame or Series with a daily DateTimeIndex.\n w_month : str\n The month to start the water year in three upper case letters.\n max_missing : int\n The allowed missing data in a year for the alf7d calc.\n malf_min : float\n The minimum ratio of ALF data years to total years to calculate the MALF.\n intervals : list of int\n The intervals to calculate MALF over.\n return_alf : bool\n Should the ALFs and the number of missing days per year be returned in addition to the MALF?\n export_path : str\n The base path for the export files that will be saved.\n\n Returns\n -------\n DataFrame(s)\n When return_alfs is False, then the output is only a dataframe of the MALFs by intervals. When return_alfs is True, then the output will include the MALFs, the annual ALFs, the number of missing days per year, the number of days (out of 20) that have data surrounding the minimum flow value for that year, and the dates of the minimum flow per year.\n \"\"\"\n\n mon_day_dict = {'JAN': 1, 'FEB': 32, 'MAR': 61, 'APR': 92, 'MAY': 122, 'JUN': 182, 'JUL': 153, 'AUG': 214,\n 'SEP': 245, 'OCT': 275, 'NOV': 306, 'DEC': 336}\n\n def malf_fun(df, intervals):\n\n malfs = []\n last_yr = df[-1:].index[0]\n for i in intervals:\n first_yr = last_yr - pd.DateOffset(years=i)\n df10 = df[first_yr:]\n mis10 = np.floor(i * malf_min) <= df10.count()\n if mis10:\n malfs.extend([np.round(np.mean(df10), 3)])\n else:\n malfs.extend([np.nan])\n malfs.extend([np.round(np.mean(df), 3)])\n\n return malfs\n\n # def day_june(df, dayofyear=182):\n # day1 = df.dt.dayofyear\n # over1 = day1 >= dayofyear\n # under1 = day1 < dayofyear\n # day2 = day1.copy()\n # day2.loc[over1] = day1.loc[over1] - dayofyear\n # day2.loc[under1] = 365 - dayofyear + day1.loc[under1]\n # return(day2)\n\n ### Make sure the object is a data frame and regular\n df_temp = tsreg(pd.DataFrame(df))\n df = df_temp.dropna(axis=1, how='all')\n df.columns = df.columns.astype(int)\n\n ### Rolling mean\n df2 = df.rolling(7, center=True).mean()\n\n ## count the number of days with data\n df2_nans = df2.rolling(20, center=True).count()\n\n ### Calc and filter ALFs\n n_days_yr = df2.fillna(0).resample('A-' + w_month).count()\n day_filter = n_days_yr.iloc[:, 0] >= 275\n n_days_yr2 = n_days_yr[day_filter]\n df3_res = df2.resample('A-' + w_month)\n df4 = df3_res.min()[day_filter]\n df_count1 = df3_res.count()[day_filter]\n df_missing = n_days_yr2 - df_count1\n df4[df_missing > max_missing] = np.nan\n df_count2 = df4.count()\n\n ### Find the minimum in each water year\n min_date = df2.resample('A-' + w_month).apply(lambda x: pd.to_datetime(x.idxmin()))\n min_day = min_date.apply(lambda x: x.dt.dayofyear)\n mon_day = mon_day_dict[w_month]\n\n ## Determine if there are missing values near the min flow value\n n_days_min = min_date.copy()\n for i in df2_nans:\n index1 = min_date.loc[min_date[i].notnull(), i]\n val1 = df2_nans.loc[index1, i].resample('A-' + w_month).min()\n val1.name = i\n n_days_min.loc[:, i] = val1\n\n mis_min_bool = any(n_days_min < 13)\n\n if mis_min_bool:\n print(\n 'Warning 1 - Some sites have significant amounts of missing values near the ALF! Check the DataFrame output for further info.')\n\n ## determine the number of min days per year within a month of the water year break point\n count_min_day = min_day.apply(lambda x: (x > (mon_day - 30)) & (x < (mon_day + 30))).sum()\n ratio_min_day = (count_min_day / df_count2).round(2)\n ratio_min_day_bool = ratio_min_day >= 0.25\n\n if any(ratio_min_day_bool):\n sites_prob = ratio_min_day[ratio_min_day_bool].index.tolist()\n print('Warning 2 - Site(s) ' + str(\n sites_prob) + ' have a significant amount of ALFs that fall at the end/beginning of the water year.')\n\n # mean_date = min_date.apply(day_june, dayofyear=mon_day_dict[w_month]).mean()\n\n ## MALF calc\n malf = df4.apply(lambda x: pd.Series(malf_fun(x, intervals)), axis=0).transpose()\n malf_col_names = [\"MALF7D \" + str(i) + \" yrs\" for i in intervals]\n malf_col_names.extend([\"MALF7D all yrs\"])\n malf.columns = malf_col_names\n if num_years:\n malf['Avg_num_days'] = np.nan\n for i in malf.index:\n val = float(malf.ix[i, 4])\n t1 = df[i][df[i] <= val]\n t2 = round(t1.resample('A-' + w_month).count().mean(), 1)\n malf.loc[i, 'Avg_num_days'] = t2\n\n ## Export data and return dataframes\n if return_alfs:\n if isinstance(export_path, str):\n malf.to_csv(os.path.join(export_path, export_name_malf))\n df4.round(3).to_csv(os.path.join(export_path, export_name_alf))\n df_missing.to_csv(os.path.join(export_path, export_name_mis))\n\n return malf, df4.round(3), df_missing, n_days_min, min_date\n else:\n if isinstance(export_path, str):\n malf.to_csv(os.path.join(export_path, export_name_malf))\n\n return malf\n\n\ndef fre_accrual(csv_or_df, min_filter=False, min_yrs=4, max_missing=120, fre_mult=3, w_month='JUN', day_gap=5):\n \"\"\"\n Function to calculate the Fre3 of a flow time series.\n \"\"\"\n\n # if type(csv_or_df) is str:\n # df = rd_hydstra_csv(csv_or_df, min_filter, min_yrs)\n # df = df.dropna(axis=1, how='all')\n # else:\n\n df = csv_or_df\n df = df.dropna(axis=1, how='all')\n sites = df.columns.values\n howmany = len(sites)\n\n output = pd.DataFrame(np.nan, index=sites, columns=['fre_val', 'fre_calc', 'mean_accrual', 'n_yrs'])\n\n medians = df.median()\n fre_val = medians * fre_mult\n\n for i in range(howmany):\n site = sites[i]\n threshold = fre_val[site]\n dfsite = df[[site]]\n\n start_date = df_first_valid(dfsite)\n start = start_date.iloc[0]\n # start = to_datetime('2006-08-31')\n\n end_date = df_last_valid(dfsite)\n end = end_date.iloc[0]\n\n find_events = dfsite[start: end]\n # find_events = dfsite\n\n findgaps = find_events.dropna()\n findgaps['start_gap'] = findgaps.index\n findgaps['end_gap'] = findgaps['start_gap'].shift(periods=-1) + pd.DateOffset(-1)\n findgaps['diff'] = abs(findgaps['start_gap'] - findgaps['end_gap'])\n gaps = findgaps.loc[findgaps['diff'] > '30 days']\n\n partitions = len(gaps) + 1\n\n find_events['Exceed'] = np.where(find_events[site] >= threshold, 1, 0) # find days where threshold is exceeded\n find_events['DaysOver'] = find_events['Exceed'].rolling(\n window=6).sum() # on how many days of the last 6 has the threshold been exceeded\n\n find_events['DaysOver'] = np.where((find_events['Exceed'] == 1), find_events['DaysOver'].fillna(1),\n find_events['DaysOver'].fillna(\n 0)) # fill NaN values in DaysOver with 1 if flow over threshold, 0 if not\n\n find_events['Event'] = np.where((find_events['Exceed'] == 1) & (find_events['DaysOver'] == 1), 1,\n 0) # mark as a new event if the threshold is exceeded, and the 5 previous days were below the threshold\n\n # find the number of days in the year that are in the period of record, make sure it is at least 335\n n_days_yr = find_events[site].fillna(0).resample('A-' + w_month).count()\n day_filter = n_days_yr >= 335\n n_days_yr2 = n_days_yr[day_filter]\n\n events_year = find_events['Event'].resample('A-' + w_month).sum()[\n day_filter] # find number of events that occurred each year\n\n data_days = find_events[site].resample('A-' + w_month).count()[day_filter] # find number of days with data\n missing_days = n_days_yr2 - data_days # find number of missing days per year\n events_year[\n missing_days > max_missing] = np.nan # remove years with more than the maximum alllowance number of missing days\n n_years = events_year.count() # find the length of the record\n\n # Fre calc\n fre_calc = events_year.mean()\n\n # Accrual periods\n\n if partitions == 1:\n if sum(find_events.Exceed) > 0:\n # calculate accrual period for the whole record\n find_accrual = find_events.loc[find_events['Exceed'] == 1]\n find_accrual['start_accrual'] = find_accrual.index\n find_accrual['end_accrual'] = find_accrual['start_accrual'].shift(periods=-1) + pd.DateOffset(-1)\n find_accrual['accrual_time'] = abs(find_accrual['start_accrual'] - find_accrual['end_accrual'])\n accrual_periods = find_accrual.loc[find_accrual['accrual_time'] > (str(day_gap) + ' days')]\n mean_accrual = accrual_periods['accrual_time'].astype('timedelta64[D]').astype('int').mean()\n else:\n # split data into partitions if there are big gaps\n starts = gaps['end_gap'].tolist()\n starts.insert(0, start)\n ends = gaps['start_gap'].tolist()\n ends.insert(len(ends) + 1, end)\n storeaccrual = []\n\n for f in range(partitions):\n find_events_part = find_events[starts[f]:ends[f]]\n if sum(find_events_part.Exceed) > 0:\n find_accrual = find_events_part.loc[find_events_part['Exceed'] == 1]\n find_accrual['start_accrual'] = find_accrual.index\n find_accrual['end_accrual'] = find_accrual['start_accrual'].shift(periods=-1) + pd.DateOffset(-1)\n find_accrual['accrual_time'] = abs(find_accrual['start_accrual'] - find_accrual['end_accrual'])\n accrual_periods = find_accrual.loc[find_accrual['accrual_time'] > '5 days']\n accrual_time = (accrual_periods['accrual_time'].astype('timedelta64[D]').astype('int')).tolist()\n storeaccrual = storeaccrual + accrual_time\n mean_accrual = np.mean(storeaccrual)\n\n # Put into output df\n output.loc[site, :] = [round(fre_val[site], 3), fre_calc, round(mean_accrual, 3), n_years]\n\n return output\n\n\ndef gauge_proc(gauge_flow, day_win=3, min_gauge=15, export=False, export_path='gaugings_flow.csv'):\n \"\"\"\n Function to process gaugings data to determine the gauging periods with a minimum number of gaugings. Returns the gauging flows for those periods.\n\n Arguments:\\n\n gauge_flow -- The output of the rd_henry function with sites_by_col=True.\\n\n day_win -- The window period to look for concurrent gaugings over.\\n\n min_gauge -- The minimum number of gaugings required.\n \"\"\"\n\n ### Make the time series regular\n flow = tsreg(gauge_flow, freq='D')\n\n ### rolling window count and max\n flow_win = flow.rolling(day_win, min_periods=1, center=True).mean()\n\n flow_win_count = flow_win.count(axis=1)\n # count10 = flow_win_count[flow_win_count > min_gauge]\n\n ### Determine local max from a smoothed spline\n flow_spline = flow_win_count.resample('2H').interpolate(method='spline', order=3, s=0.2)\n loc_max = argrelmax(flow_spline.values, order=48)\n flow_spline2 = flow_spline.ix[loc_max]\n flow_spline3 = flow_spline2[flow_spline2 > min_gauge]\n\n index_max = flow_spline3.index.round('D')\n\n ### Get the count and the final data\n flow2 = flow_win[flow_win.index.isin(index_max)].dropna(how='all', axis=1)\n\n ### Remove sites with only zero flow\n with_flow = flow2.mean() > 0.01\n flow3 = flow2.ix[:, with_flow.values]\n count_tot = flow3.count(axis=1)\n\n if export:\n flow3.to_csv(export_path)\n\n return flow3, count_tot\n\n\ndef flow_reg(x, y, min_obs=10, p_val=0.05, logs=False, make_ts=False, cut_y=False, below_median=False, export=False, export_ts='est_flow.csv', export_reg='est_reg.csv'):\n \"\"\"\n Function to make a regression between recorders and gaugings and optionally create a time series for the gaugings.\n\n Arguments:\\n\n min_obs -- Minimum number of regressions values required.\\n\n p_val -- Minimum p-value for the regressions.\\n\n logs -- Should the variables be logged?\\n\n make_ts -- Should a new time series be made from the regressions?\\n\n cut -- Should the values above the max value from the regression be removed?\n \"\"\"\n\n #### Filter out data that shouldn't be correlated\n x1 = x.replace(0, np.nan)\n y1 = y.replace(0, np.nan)\n\n #### Remove values below the median if desired\n if below_median:\n median1 = x1.median()\n\n new_df = pd.DataFrame()\n for i in x1:\n med1 = median1.loc[i]\n grp = x1.loc[:, i]\n t1 = grp.loc[grp <= med1]\n new_df = pd.concat([new_df, t1], axis=1)\n x2 = new_df\n else:\n x2 = x1.copy()\n\n #### Do the regressions\n t1 = lin_reg(x2, y1, log_x=logs, log_y=logs)\n t2 = [i[(i['n-obs'] >= min_obs)] for i in t1]\n t3 = [i for i in t2 if not i.empty]\n\n site_reg = []\n for g in y1.columns:\n site_reg1 = pd.DataFrame((i[i['Y_loc'].values == g].values[0] for i in t3 if sum(i['Y_loc'].values == g)),\n columns=t3[0].columns)\n site_reg.append(site_reg1)\n\n top1 = []\n for f in site_reg:\n p_index = f['p-value'] < p_val\n if sum(p_index) > 0:\n qual = np.argmax(((f.R2 - f.MANE))[p_index])\n best1 = f.iloc[qual, :]\n top1.append(best1)\n top = pd.concat(top1, axis=1).T\n top.index = top['Y_loc']\n\n ### Create new time series from regressions\n if make_ts:\n y_new1 = []\n for i in top.index:\n reg1 = top.loc[i, :]\n if isinstance(x1, pd.DataFrame):\n flow_x = x1[reg1['X_loc']]\n else:\n flow_x = x1\n flow_y = y1[reg1['Y_loc']]\n xy = pd.concat([flow_x, flow_y], axis=1).dropna()\n\n ## Create new series\n if logs:\n y_new = np.exp(float(reg1.Slope) * np.log(flow_x) + float(reg1.Intercept))\n else:\n y_new = float(reg1.Slope) * flow_x + float(reg1.Intercept)\n\n ## remove negatives\n y_new[y_new < 0] = 0\n\n ## Remove all values above 'max_y'\n if cut_y:\n max_y = max(xy[reg1['Y_loc']]).astype('float32')\n y_new[y_new > (max_y + max_y * 0.2)] = np.nan\n\n ## Put back the original data\n y_new.loc[xy[reg1['Y_loc']].index] = y[i]\n\n ## Put into list container\n y_new.name = reg1['Y_loc']\n y_new1.append(y_new.round(3))\n\n ## Make into dataframe\n y_new2 = pd.concat(y_new1, axis=1)\n\n ## Export if desired\n if export:\n y_new2.to_csv(export_ts)\n top.to_csv(export_reg)\n return top, y_new2\n\n #### Export and return\n if export:\n top.to_csv(export_reg)\n return top\n\n\ndef est_low_flows(y, x, comp_dict, cut=True):\n \"\"\"\n Estimate flows from regressions from two sites with a dictionary of the x: [y, log?].\n \"\"\"\n\n x.columns = x.columns.astype(int)\n y.columns = y.columns.astype(int)\n df1 = pd.DataFrame(np.nan, index=x.index, columns=[i for i in comp_dict])\n\n for i in comp_dict:\n y_site = int(i)\n x_site, logs = comp_dict[i]\n x_site = int(x_site)\n xy = pd.concat([x[x_site], y[y_site]], axis=1)\n xy[xy <= 0] = np.nan\n xy = xy.dropna()\n max_y = max(xy[y_site])\n\n ## run regression and create new series\n reg1 = lin_reg(xy[x_site], xy[y_site], log_x=logs, log_y=logs)[0]\n if logs:\n y_new = np.exp(float(reg1.Slope) * np.log(x[x_site]) + float(reg1.Intercept))\n else:\n y_new = float(reg1.Slope) * x[x_site] + float(reg1.Intercept)\n\n ## remove negatives\n y_new[y_new < 0] = 0\n\n ## Remove all values about 'max_y'\n if cut:\n y_new[y_new > max_y] = np.nan\n\n ## Put back original data\n index1 = y[y_site].dropna().index\n y_new[index1] = y[y_site].dropna()\n\n df1[i] = y_new.round(3)\n\n return df1\n\n\ndef est_low_flows_reg(y, x, comp_dict, cut=True):\n \"\"\"\n Estimate flows from regressions from two sites with a dictionary of the x: [y, log?].\n \"\"\"\n\n x.columns = x.columns.astype(int)\n y.columns = y.columns.astype(int)\n df1 = []\n\n for i in comp_dict:\n y_site = int(i)\n x_site, logs = comp_dict[i]\n x_site = int(x_site)\n xy = pd.concat([x[x_site], y[y_site]], axis=1)\n xy[xy <= 0] = np.nan\n xy = xy.dropna()\n\n ## run regression and create new series\n reg1 = lin_reg(xy[x_site], xy[y_site], log_x=logs, log_y=logs)[0]\n\n df1.append(reg1)\n\n ## Concat\n df2 = pd.concat(df1)\n\n return df2\n\n\ndef flow_dur(flow, plot=False):\n \"\"\"\n Function to estimate the flow duration of flow time series and optionally plot them.\n \"\"\"\n\n flow1 = flow.dropna(how='all')\n rank1 = flow1.rank(axis=0, pct=True, ascending=False)\n\n fdc_sorted = []\n\n for i in flow1.columns:\n both2 = pd.concat([flow1[i], rank1[i]], axis=1).dropna()\n both2.columns = ['flow1', 'rank1']\n both3 = both2.sort_values('rank1')\n fdc_sorted.extend([both3])\n\n if plot:\n both2.plot(x='rank1', y='flow1', kind='scatter', xlim=[0, 1], ylim=[0, max(both2.flow1)])\n\n return fdc_sorted\n\n\n# def summ_stats(df_lst, df_names, excel_file, below_median=True, num_years=True,\n# flow_csv='S:/Surface Water/shared/base_data/flow/all_flow_data.csv'):\n# \"\"\"\n# Summary flow stats function. Exports to an excel file. Input must be a list of time series dataframe(s). df_names must be a list of names associated with each dataframe (will be column headers).\n# \"\"\"\n#\n# stats_export = 'stats'\n# ros_means_export = 'ros_means'\n# ros_partial_export = 'ros_partial'\n# ros_full_export = 'ros_full'\n# ros_partial_norm_export = 'ros_partial_norm'\n# ros_full_norm_export = 'ros_full_norm'\n#\n# ## Load all flow data\n# all_flow = rd_ts(flow_csv)\n# all_flow.columns = all_flow.columns.astype(int)\n#\n# #### Run loop for all three sets\n# excel = ExcelWriter(excel_file)\n# stats_out = []\n# ros_means_out = []\n#\n# for i in range(len(df_lst)):\n# flow = df_lst[i]\n#\n# ## Remove main sites from all flow data\n# all_flow2 = all_flow.loc[:, ~in1d(all_flow.columns, flow.columns)]\n# all_flow3 = concat([flow, all_flow2], axis=1, join='inner')\n#\n# ## Run stats for Huts and SH1 on the Pareora\n#\n# stats1 = flow_stats(flow, below_median=below_median)\n# malf, alf, alf_mising = malf7d(flow, num_years=num_years)\n# fre3 = fre_accrual(flow)\n#\n# # fdc, fdc = flow_dur(flow)\n#\n# stats2 = concat([stats1, malf.drop('MALF7D 40 yrs', axis=1), fre3], axis=1)\n# stats_out.extend([stats2])\n#\n# #######################################\n# #### Reliability of supply\n#\n# ros = flow_ros(flow.columns.values, flow_csv=all_flow3)\n# ros_partial, ros_full = ros_freq(ros, period='summer')\n# ros_partial_norm, ros_full_norm = ros_freq(ros, period='summer', norm=True)\n#\n# ros_partial_mean = ros_partial.mean().round(1)\n# ros_full_mean = ros_full.mean().round(1)\n# ros_partial_norm_mean = ros_partial_norm.mean().round(3)\n# ros_full_norm_mean = ros_full_norm.mean().round(3)\n#\n# ros_means = concat([ros_partial_mean, ros_partial_norm_mean, ros_full_mean, ros_full_norm_mean], axis=1)\n# ros_means.columns = ['ros_partial', 'ros_partial_norm', 'ros_full', 'ros_full_norm']\n#\n# ros_means_out.extend([ros_means])\n#\n# ######################################\n# #### Export results\n# out1 = df_names[i]\n#\n# stats2.to_excel(excel, out1 + '_' + stats_export)\n# ros_means.to_excel(excel, out1 + '_' + ros_means_export)\n#\n# ros_partial.to_excel(excel, out1 + '_' + ros_partial_export)\n# ros_full.to_excel(excel, out1 + '_' + ros_full_export)\n# ros_partial_norm.to_excel(excel, out1 + '_' + ros_partial_norm_export)\n# ros_full_norm.to_excel(excel, out1 + '_' + ros_full_norm_export)\n#\n# excel.save()\n# return ([stats_out, ros_means_out])\n\n\ndef malf_reg(x, y, min_yrs=10, min_obs=10, w_month='JUN', max_missing=120, malf_min=0.9, intervals=[10, 20, 30, 40]):\n \"\"\"\n A function to specifically correlate flows to estimate MALFs.\n \"\"\"\n\n ### Only use x flow series with min_yrs\n m1 = malf7d(x, w_month=w_month, max_missing=max_missing, malf_min=malf_min, intervals=[min_yrs])\n x1 = x.loc[:, m1.iloc[:, 0].notnull()]\n\n ### Rolling 7D mean on x and y\n x_roll = x1.rolling(7, center=True).mean()\n y_roll = y.rolling(7, center=True).mean()\n\n ### Run the regressions\n reg1, df2 = flow_reg(x_roll, y_roll, min_obs=min_obs, make_ts=True, logs=False)\n\n ### Calc the 7DMALF\n def malf_fun(df, intervals):\n\n malfs = []\n for i in intervals:\n df10 = df[-i:]\n mis10 = np.floor(len(df10) * round(1.0 - malf_min, 2)) >= sum(df10.isnull())\n if mis10:\n malfs.extend([np.round(np.mean(df10), 3)])\n else:\n malfs.extend([np.nan])\n malfs.extend([np.round(np.mean(df), 3)])\n\n return malfs\n\n ## Find the minimum in each water year and count the days\n n_days_yr = df2.fillna(0).resample('A-' + w_month).count()\n day_filter = n_days_yr.iloc[:, 0] >= 335\n n_days_yr2 = n_days_yr[day_filter]\n df3_res = df2.resample('A-' + w_month)\n df4 = df3_res.min()[day_filter]\n df_count1 = df3_res.count()[day_filter]\n df_missing = n_days_yr2 - df_count1\n df4[df_missing > max_missing] = np.nan\n # df_count2 = df4.count()\n\n ## MALF calc\n malf = df4.apply(lambda x: pd.Series(malf_fun(x, intervals)), axis=0).transpose()\n malf_col_names = [\"MALF7D \" + str(i) + \" yrs\" for i in intervals]\n malf_col_names.extend([\"MALF7D all yrs\"])\n malf.columns = malf_col_names\n\n ### Return results\n return reg1, malf\n","sub_path":"hydropandas/tools/river/ts/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":25605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"142999191","text":"from flask import Flask, jsonify\nfrom flask_restx import Resource, Api, fields,marshal\nfrom pymongo import MongoClient\nimport json\n\napp = Flask(__name__)\napi = Api(app, version='1.0', title='Seven API', description='API de l\\'exercice 7')\nns = api.namespace('weather', description='Weather operations')\nclient = MongoClient(\"mongodb://%s:%s@seven_mongo:27017\" % ('root', 'example'))\n\ndb = client.weather\ncollection = db.temperature\n\n\ntemperature = api.model('Temperature', {\n # '_id' : fields.String(),\n 'id_station' : fields.String(required=True, description='@MAC Station'),\n 'id_sonde' : fields.String(required=True, description='@MAC Sonde'),\n 'latitude' : fields.Float(required=True, description='Latitude'),\n 'longitude' : fields.Float(required=True, description='Longitude'),\n 'ville' : fields.String(required=True, description='ville'),\n 'timestamp' : fields.Integer(required=True, description='Timestamp'),\n 'temperature' : fields.Float(required=True, description='Temperature'),\n 'humidite' : fields.Float(required=True, description='Humidite')\n})\n\n\n@ns.route('/temperature')\nclass TempList(Resource):\n @ns.doc('list_temperature')\n @ns.marshal_with(temperature, True)\n def get(self):\n data = collection.find({}, {\"_id\" : 0})\n data_parsed = []\n for x in data:\n data_parsed.append(x)\n print(data_parsed)\n # champs = {'data' : fields.List}\n return data_parsed\n\n @ns.doc('create_temperature')\n @ns.expect(temperature)\n @ns.marshal_with(temperature, code=201)\n def post(self):\n id_res = collection.insert_one(api.payload).inserted_id\n result = collection.find_one({\"_id\" : id_res}, {\"_id\" : 0})\n return result\n\n@ns.route('/temperature/search/')\nclass ByStation(Resource):\n @ns.doc('list_temperature_by_station')\n @ns.marshal_with(temperature, True)\n def get(self, id_station):\n data = collection.find({\"id_station\" : id_station}, {\"_id\" : 0})\n data_parsed = []\n for x in data:\n data_parsed.append(x)\n print(data_parsed)\n return data_parsed\n\n \n@app.after_request\ndef after_request(response):\n response.headers.add('Access-Control-Allow-Origin', '*')\n response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')\n response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')\n return response\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"api/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"527726176","text":"import sys\nimport os\nimport zipfile\nimport subprocess\n\ncurrent_working_directory = os.getcwd()\n\ndef parse_gitignore(root_path):\n\tprint(\"\\n Processing .gitignore...\")\n\tgitignore_path = os.path.join(current_working_directory, \".gitignore\")\n\tif os.path.isfile(gitignore_path):\n\t\tgitignore = []\n\t\twith open(gitignore_path, \"r\") as f:\n\t\t\tgitignore = f.readlines()\n\t\tfolders_to_ignore = []\n\t\tfiles_to_ignore = []\n\t\tfile_patterns_to_ignore = []\n\t\tprint(\" Reading '%s'\" % os.path.relpath(gitignore_path, current_working_directory))\n\t\tfor line in gitignore:\n\t\t\tline = line.strip()\n\t\t\tpath = os.path.join(current_working_directory, line)\n\t\t\tif os.name == \"nt\":\n\t\t\t\tpath = path.replace(\"/\", \"\\\\\")\n\t\t\telse:\n\t\t\t\tpath = path.replace(\"\\\\\", \"/\")\n\t\t\tif path.find(root_path):\n\t\t\t\tprint(\" Jumping over:\", path)\n\t\t\t\tcontinue\n\t\t\tif os.path.isdir(path):\n\t\t\t\tprint(\" Folder:\", line)\n\t\t\t\tfolders_to_ignore.append(path)\n\t\t\telif os.path.isfile(path):\n\t\t\t\tprint(\" File:\", line)\n\t\t\t\tfiles_to_ignore.append(path)\n\t\t\telif path.find(\"*.\") >= 0:\n\t\t\t\tprint(\" File pattern:\", line)\n\t\t\t\tfile_patterns_to_ignore.append(path)\n\t\t\telse:\n\t\t\t\tprint(\" Unsupported:\", line)\n\t\tprint(\"\\n Folders to ignore\")\n\t\tfor line in folders_to_ignore:\n\t\t\tprint(\" '%s'\" % os.path.relpath(line, current_working_directory))\n\t\tprint(\"\\n Files to ignore\")\n\t\tfor line in files_to_ignore:\n\t\t\tprint(\" '%s'\" % os.path.relpath(line, current_working_directory))\n\t\treturn folders_to_ignore, files_to_ignore, file_patterns_to_ignore\n\treturn None, None, None\n\ndef main(root_path, releases_path, version):\n\trelease_name = \"Lauhdutin\"\n\tauthor_name = \"Kapiainen\"\n\tprint(\"\\nGenerating release: '%s - %s'\" % (release_name, version))\n\tfolders_to_ignore, files_to_ignore, file_patterns_to_ignore = parse_gitignore(root_path)\n\tprint(\"\\n Gathering stuff to include in the release...\")\n\tfiles_to_pack = []\n\tfor root, dirs, files in os.walk(root_path):\n\t\tskip = False\n\t\tfor folder in folders_to_ignore:\n\t\t\tif folder in root:\n\t\t\t\tskip = True\n\t\t\t\tbreak\n\t\tif skip:\n\t\t\tprint(\" Skipping folder:\", root)\n\t\t\tcontinue\n\t\tprint(\" Processing folder:\", root)\n\t\tfor file in files:\n\t\t\tpath = os.path.join(root, file)\n\t\t\tif path in files_to_ignore:\n\t\t\t\tprint(\" Skipping file: '%s'\" % os.path.relpath(path, root_path))\n\t\t\telse:\n\t\t\t\tskip = False\n\t\t\t\tfor pattern in file_patterns_to_ignore:\n\t\t\t\t\tfolder_path, extension = pattern.split(\"*\")\n\t\t\t\t\tif path.find(folder_path) >= 0 and path.endswith(extension):\n\t\t\t\t\t\tskip = True\n\t\t\t\t\t\tbreak\n\t\t\t\tif skip:\n\t\t\t\t\tprint(\" Skipping file based on pattern: '%s'\" % os.path.relpath(path, root_path))\n\t\t\t\telse:\n\t\t\t\t\tprint(\" Adding file: '%s'\" % os.path.relpath(path, root_path))\n\t\t\t\t\tif \"init.lua\" in path:\n\t\t\t\t\t\twith open(path, \"r\") as f:\n\t\t\t\t\t\t\tfor line in f.readlines():\n\t\t\t\t\t\t\t\tif \"RUN_TESTS\" in line and \"=\" in line:\n\t\t\t\t\t\t\t\t\tif \"true\" in line:\n\t\t\t\t\t\t\t\t\t\tprint(\"\\n Aborted build! Tests are enabled in '%s'!\" % path)\n\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\tfiles_to_pack.append(path)\n\tprint(\"\\n Files to pack:\")\n\tfor file in files_to_pack:\n\t\tprint(\" \", file)\n\n\ttry: # Check if 'zlib' module is available for 'zipfile.ZipFile' to use for compressing.\n\t\timport zlib\n\t\tcompression_type = zipfile.ZIP_DEFLATED\n\t\tprint(\"\\n Using 'zlib' module to generate a compressed archive...\")\n\texcept ImportError:\n\t\tprint(\"\\n 'zlib' module could not be imported!\")\n\t\tprint(\" Generating uncompressed archive instead...\")\n\t\tcompression_type = zipfile.ZIP_STORED\n\treadme_path = os.path.join(current_working_directory, \"Readme.md\")\n\tlicense_path = os.path.join(current_working_directory, \"License.md\")\n\tchangelog_path = os.path.join(current_working_directory, \"Changelog.md\")\n\tcontributors_path = os.path.join(current_working_directory, \"Contributors.md\")\n\tenglish_translation_path = os.path.join(current_working_directory, \"translations\", \"English.txt\")\n\twith zipfile.ZipFile(os.path.join(releases_path, \"%s - %s\" % (release_name, version)) + \".zip\", mode=\"w\", compression=compression_type) as release_archive:\n\t\trelease_archive.write(readme_path, \"Readme.md\")\n\t\trelease_archive.write(license_path, \"License.md\")\n\t\trelease_archive.write(changelog_path, \"Changelog.md\")\n\t\trelease_archive.write(contributors_path, \"Contributors.md\")\n\t\trelease_archive.write(english_translation_path, os.path.join(\"@Resources\", \"Languages\", \"English.txt\"))\n\t\tfor file in files_to_pack:\n\t\t\trelease_archive.write(file, os.path.relpath(file, root_path))\n\tprint(\"\\nSuccessfully generated the release!\")\n\ntry:\n\troot_path = os.path.join(current_working_directory, \"dist\")\n\treleases_path = os.path.join(current_working_directory, \"Releases\")\n\tif not os.path.isdir(releases_path):\n\t\tos.makedirs(releases_path)\n\t# Compile source files\n\tcompiler = subprocess.Popen([os.path.join(current_working_directory, \"compile_src.bat\")], cwd=current_working_directory)\n\tcompiler.wait()\n\tif compiler.returncode == 0:\n\t\t# Update translation file\n\t\ttranslation_updater = subprocess.Popen([\"python\", os.path.join(current_working_directory, \"update_translations.py\")], cwd=current_working_directory)\n\t\ttranslation_updater.wait()\n\t\tif translation_updater.returncode == 0:\n\t\t\tmain(root_path, releases_path, input(\"Enter release version: \"))\n\t\telse:\n\t\t\tprint(\"Failed to update the translation file!\")\n\telse:\n\t\tprint(\"Failed to compile source files!\")\nexcept:\n\timport traceback\n\ttraceback.print_exc()\n\ninput(\"\\nPress enter to exit...\")\n","sub_path":"build_release.py","file_name":"build_release.py","file_ext":"py","file_size_in_byte":5395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"629922098","text":"import pandas as pd\nimport numpy as np\nfrom random import choices\n\ndef get_filmes():\n filmes = pd.read_csv('ml-latest-small/movies.csv')\n filmes.columns = ['filmeId', 'titulo', 'generos']\n return filmes\n\ndef get_notas():\n df_notas = pd.read_csv('ml-latest-small/ratings.csv')\n df_notas.columns = ['usuarioId', 'filmeId', 'nota', 'momento']\n # ======= Ajusta as notas para a escala de PONTUAÇÃO ===================\n df_notas['nota'] = df_notas['nota'] - 3\n # Assim, filmes ruins com muitos votos não ganham de filmes bons com menos votos\n # <<--(1 péssimo)---(2 ruim)---(3 razoável)---(4 bom)---(5 ótimo)--->>\n # -2 pontos -1 ponto 0 pontos 1 ponto 2 pontos\n # ======================================================================\n return df_notas\n\ndef pontuacao_filmes(df_notas):\n result = df_notas.groupby('filmeId')['nota'].sum()\n return pd.DataFrame(result)\n\ndef assistidos_por(voce, df_notas=None):\n if df_notas is None:\n df_notas = get_notas()\n result = df_notas[\n (df_notas['usuarioId']==voce)\n ].set_index('filmeId')\n return list(result.index)\n\ndef genero_preferido(param, df_filmes):\n if isinstance(param, list):\n lista_filmes = param\n else:\n lista_filmes = assistidos_por(param)\n resumo = {}\n # --- Soma todas ocorrências de gêneros nos filmes: ---------\n generos = df_filmes[df_filmes['filmeId'].isin(lista_filmes)]['generos']\n for expr in generos:\n for nome_genero in expr.split('|'):\n ocorrencias = resumo.setdefault(nome_genero, 0) + 1\n resumo[nome_genero] = ocorrencias\n # ----- Encontra o nome do gênero com mais ocorrências ------\n encontrado = ''\n for nome_genero in resumo:\n ocorrencias = resumo[nome_genero]\n if not encontrado or ocorrencias > resumo[encontrado]:\n encontrado = nome_genero\n return encontrado\n\ndef notas_usuario(usuario_id, df_notas):\n return df_notas.query(f'usuarioId=={usuario_id}')[\n ['filmeId', 'nota']\n ].set_index('filmeId')\n\ndef distancia_usuarios(usuario_esq, usuario_dir, df_notas=None):\n if usuario_esq == usuario_dir:\n # ----> Não compara um usuário com ele mesmo!\n return None\n # ------------------------------------------- \n notas_esq = notas_usuario(usuario_esq, df_notas)\n notas_dir = notas_usuario(usuario_dir, df_notas)\n result = notas_esq.join(\n notas_dir,\n lsuffix='_esq',\n rsuffix='_dir'\n ).dropna()\n if len(result) < 3:\n # ----> Os usuários devem ter pelo menos 3 filmes em comum\n return None\n # -------------------------------------------------------------\n distancia = np.linalg.norm(result['nota_esq'] - result['nota_dir'])\n return {\n 'usuario': usuario_dir,\n 'distancia': distancia\n }\n\ndef mais_similares(voce, df_notas=None, tam_amostra=100, qtd_retornar=10):\n # --- Extrai uma amostra de todos os usuários ---\n outros_usuarios = choices(\n df_notas['usuarioId'].unique(),\n k=tam_amostra\n )\n result = []\n # -- Localiza os N mais próximos (onde N = qtd_retornar) ---\n for usuario_id in outros_usuarios:\n info = distancia_usuarios(voce, usuario_id, df_notas)\n if info is None:\n continue\n result.append(info)\n return pd.DataFrame(result).sort_values('distancia').head(qtd_retornar).set_index('usuario')\n\ndef recomendacoes(voce, df_notas=None, df_filmes=None, filtrar_genero=False):\n if df_notas is None:\n df_notas = get_notas()\n #----- Todos os filmes que vocÊ assistiu... ------\n assistidos = assistidos_por(voce, df_notas)\n #----- Lista os usuários similares a vocÊ: -----\n usuarios = list(mais_similares(voce, df_notas).index)\n #--- Filmes NÃO assistidos avaliados pelos usuários similares: ---\n result = df_notas[\n (~df_notas['filmeId'].isin(assistidos))\n &\n (df_notas['usuarioId'].isin(usuarios))\n ].drop(columns=['momento', 'usuarioId'])\n # --- Determina a pontuação dos filmes recomendados: ---\n result = pontuacao_filmes(result)\n #--- Junta com os nomes e outros dados dos filmes -----\n if df_filmes is None:\n df_filmes = get_filmes()\n if filtrar_genero:\n #=== Traz os filmes somente do gênero que vocÊ prefere ===\n df_filmes = df_filmes[df_filmes['generos'].str.contains(\n genero_preferido(assistidos, df_filmes)\n )]\n #=========================================================\n return result.join(\n df_filmes.set_index('filmeId')\n ).dropna().sort_values('nota', ascending=False).head(10)\n","sub_path":"Recomendações/movielens.py","file_name":"movielens.py","file_ext":"py","file_size_in_byte":4684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"393163151","text":"from stringParser import *\r\nfrom matcher import *\r\nimport os, sys\r\n\r\nclass Translator:\r\n def __init__(self, indoDict=\"../data/indonesia.txt\", sundaDict=\"../data/sunda.txt\"):\r\n self.libparser = LibParser(indo = indoDict, sunda = sundaDict)\r\n self.text = []\r\n self.translation = []\r\n\r\n def setText(self, text):\r\n self.text = inputParser.prefixSeparator(text.split(\" \"))\r\n self.text = inputParser.suffixSeparator(self.text)\r\n self.textLength = len(self.text)\r\n return self\r\n\r\n def getTranslation(self):\r\n return inputParser.decode(self.translation)\r\n\r\n def isRemovedWord(self, lib, word, type, method):\r\n matcher = MatcherBuilder.build(method).setPattern(word)\r\n if(type == \"sunda-indo\"):\r\n removedWords = lib.removedWordsSunda\r\n else: # type == \"indo-sunda\"\r\n removedWords = lib.removedWordsIndo\r\n \r\n for vocab in removedWords:\r\n if(matcher.setText(vocab).match()):\r\n return True\r\n return False\r\n\r\n def needPenegasanTeh(self, text, method):\r\n possibleSubject = [\"anjeun\", \"hidep\", \"maneh\", \"abdi\", \"kuring\",\\\r\n \"urang\", \"uing\", \"aing\", \"manehna\", \"arenjeun\", \"maraneh\"]\r\n matcher = MatcherBuilder.build(method).setPattern(text)\r\n for word in possibleSubject:\r\n if matcher.setText(word).match():\r\n return True\r\n return False\r\n\r\n def addPenegasanTeh(self, method):\r\n i = 0\r\n while i < len(self.translation) - 1:\r\n if(self.needPenegasanTeh(self.translation[i], method)\\\r\n and self.translation[i + 1] != \"<=>\"):\r\n self.translation.insert(i + 1, \"teh\")\r\n i += 2\r\n else:\r\n i += 1\r\n\r\n def translate(self, type, method=\"kmp\", tehOpt=False):\r\n matcher = MatcherBuilder.build(method)\r\n if(type == \"sunda-indo\"):\r\n dictionary = self.libparser.vocabSunda\r\n else: # type == \"indo-sunda\"\r\n dictionary = self.libparser.vocabIndo\r\n \r\n i, dictLength = 0, len(dictionary)\r\n while(i < self.textLength):\r\n if(type == \"sunda-indo\" and \\\r\n self.isRemovedWord(self.libparser, self.text[i], type, method)):\r\n i += 1\r\n else:\r\n textToValidate, result = \"\", \"\"\r\n j, k, isFound = 0, 0, False\r\n while(not isFound and j < dictLength):\r\n k = dictionary[j].keyLength\r\n textToValidate = \" \".join(self.text[i : min([i + k, self.textLength])])\r\n # print(textToValidate + ' ' + dictionary[j].key + ' ' + str(k))\r\n isFound = matcher.setText(textToValidate)\\\r\n .setPattern(dictionary[j].key)\\\r\n .match()\r\n if(not isFound):\r\n j += 1\r\n temp = []\r\n if(not isFound):\r\n temp = self.text[i : min([i + k, self.textLength])]\r\n i += 1\r\n else:\r\n temp = dictionary[j].data.split(\" \")\r\n i += k\r\n for word in temp:\r\n self.translation.append(word)\r\n\r\n if(type == \"indo-sunda\" and tehOpt):\r\n self.addPenegasanTeh(method)\r\n return inputParser.decode(self.translation)\r\n\r\nif __name__=='__main__':\r\n t = Translator()\r\n a = \"nami abdi Riyugan\"\r\n # t.setText(a).translate(\"indo-sunda\")\r\n t.setText(a)\r\n print(t.text)\r\n print(t.textLength)\r\n print(t.setText(a).translate(\"sunda-indo\"))\r\n\r\n\r\n","sub_path":"src/translator.py","file_name":"translator.py","file_ext":"py","file_size_in_byte":3737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"310254708","text":"# -*- coding: utf-8 -*-\n\"\"\"\nFunctions for manipulating .h5ad objects and automated processing of scRNA-seq data\n\"\"\"\nimport os, errno, argparse\nimport numpy as np\nimport scanpy as sc\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom math import ceil\nfrom matplotlib import rcParams\nfrom emptydrops import find_nonambient_barcodes\nfrom emptydrops.matrix import CountMatrix\n\nsc.set_figure_params(frameon=False, dpi=100, dpi_save=200, format=\"png\")\n\n# define cell cycle phase genes\n# human genes ('_h') from satija lab list\n# mouse genes ('_m') converted from human list using biomaRt package in R\ns_genes_h = [\n \"MCM5\",\n \"PCNA\",\n \"TYMS\",\n \"FEN1\",\n \"MCM2\",\n \"MCM4\",\n \"RRM1\",\n \"UNG\",\n \"GINS2\",\n \"MCM6\",\n \"CDCA7\",\n \"DTL\",\n \"PRIM1\",\n \"UHRF1\",\n \"MLF1IP\",\n \"HELLS\",\n \"RFC2\",\n \"RPA2\",\n \"NASP\",\n \"RAD51AP1\",\n \"GMNN\",\n \"WDR76\",\n \"SLBP\",\n \"CCNE2\",\n \"UBR7\",\n \"POLD3\",\n \"MSH2\",\n \"ATAD2\",\n \"RAD51\",\n \"RRM2\",\n \"CDC45\",\n \"CDC6\",\n \"EXO1\",\n \"TIPIN\",\n \"DSCC1\",\n \"BLM\",\n \"CASP8AP2\",\n \"USP1\",\n \"CLSPN\",\n \"POLA1\",\n \"CHAF1B\",\n \"BRIP1\",\n \"E2F8\",\n]\ns_genes_m = [\n \"Gmnn\",\n \"Rad51\",\n \"Cdca7\",\n \"Pold3\",\n \"Slbp\",\n \"Prim1\",\n \"Dscc1\",\n \"Rad51ap1\",\n \"Fen1\",\n \"Mcm4\",\n \"Ccne2\",\n \"Tyms\",\n \"Rrm2\",\n \"Usp1\",\n \"Wdr76\",\n \"Mcm2\",\n \"Ung\",\n \"E2f8\",\n \"Exo1\",\n \"Chaf1b\",\n \"Blm\",\n \"Clspn\",\n \"Cdc45\",\n \"Cdc6\",\n \"Hells\",\n \"Nasp\",\n \"Ubr7\",\n \"Casp8ap2\",\n \"Mcm5\",\n \"Uhrf1\",\n \"Pcna\",\n \"Rrm1\",\n \"Rfc2\",\n \"Tipin\",\n \"Brip1\",\n \"Gins2\",\n \"Dtl\",\n \"Pola1\",\n \"Rpa2\",\n \"Mcm6\",\n \"Msh2\",\n]\ng2m_genes_h = [\n \"HMGB2\",\n \"CDK1\",\n \"NUSAP1\",\n \"UBE2C\",\n \"BIRC5\",\n \"TPX2\",\n \"TOP2A\",\n \"NDC80\",\n \"CKS2\",\n \"NUF2\",\n \"CKS1B\",\n \"MKI67\",\n \"TMPO\",\n \"CENPF\",\n \"TACC3\",\n \"FAM64A\",\n \"SMC4\",\n \"CCNB2\",\n \"CKAP2L\",\n \"CKAP2\",\n \"AURKB\",\n \"BUB1\",\n \"KIF11\",\n \"ANP32E\",\n \"TUBB4B\",\n \"GTSE1\",\n \"KIF20B\",\n \"HJURP\",\n \"CDCA3\",\n \"HN1\",\n \"CDC20\",\n \"TTK\",\n \"CDC25C\",\n \"KIF2C\",\n \"RANGAP1\",\n \"NCAPD2\",\n \"DLGAP5\",\n \"CDCA2\",\n \"CDCA8\",\n \"ECT2\",\n \"KIF23\",\n \"HMMR\",\n \"AURKA\",\n \"PSRC1\",\n \"ANLN\",\n \"LBR\",\n \"CKAP5\",\n \"CENPE\",\n \"CTCF\",\n \"NEK2\",\n \"G2E3\",\n \"GAS2L3\",\n \"CBX5\",\n \"CENPA\",\n]\ng2m_genes_m = [\n \"Tmpo\",\n \"Smc4\",\n \"Tacc3\",\n \"Cdk1\",\n \"Ckap2l\",\n \"Cks2\",\n \"Mki67\",\n \"Ckap5\",\n \"Nusap1\",\n \"Top2a\",\n \"Ect2\",\n \"Cdca3\",\n \"Cdc25c\",\n \"Cks1b\",\n \"Kif11\",\n \"Psrc1\",\n \"Dlgap5\",\n \"Ckap2\",\n \"Aurkb\",\n \"Ttk\",\n \"Cdca8\",\n \"Cdca2\",\n \"Cdc20\",\n \"Lbr\",\n \"Birc5\",\n \"Kif20b\",\n \"Nuf2\",\n \"Anp32e\",\n \"Cenpf\",\n \"Kif2c\",\n \"Ube2c\",\n \"Cenpa\",\n \"Rangap1\",\n \"Hjurp\",\n \"Ndc80\",\n \"Ncapd2\",\n \"Anln\",\n \"Cenpe\",\n \"Cbx5\",\n \"Hmgb2\",\n \"Gas2l3\",\n \"Cks1brt\",\n \"Bub1\",\n \"Gtse1\",\n \"Nek2\",\n \"G2e3\",\n \"Tpx2\",\n \"Hmmr\",\n \"Aurka\",\n \"Ccnb2\",\n \"Ctcf\",\n \"Tubb4b\",\n \"Kif23\",\n]\n\n\ndef check_dir_exists(path):\n \"\"\"\n Checks if directory already exists or not and creates it if it doesn't\n\n Parameters\n ----------\n\n path : str\n path to directory\n\n Returns\n -------\n\n tries to make directory at `path`, unless it already exists\n \"\"\"\n try:\n os.makedirs(path)\n except OSError as exception:\n if exception.errno != errno.EEXIST:\n raise\n\n\ndef list_union(lst1, lst2):\n \"\"\"\n Combines two lists by the union of their values\n\n Parameters\n ----------\n\n lst1, lst2 : list\n lists to combine\n\n Returns\n -------\n\n final_list : list\n union of values in lst1 and lst2\n \"\"\"\n final_list = set(lst1).union(set(lst2))\n return final_list\n\n\ndef cellranger2(\n adata,\n expected=1500,\n upper_quant=0.99,\n lower_prop=0.1,\n label=\"CellRanger_2\",\n verbose=True,\n):\n \"\"\"\n Labels cells using \"knee point\" method from CellRanger 2.1\n\n Parameters\n ----------\n\n adata : anndata.AnnData\n object containing unfiltered counts\n expected : int, optional (default=1500)\n estimated number of real cells expected in dataset\n upper_quant : float, optional (default=0.99)\n upper quantile of real cells to test\n lower_prop : float, optional (default=0.1)\n percentage of expected quantile to calculate total counts threshold for\n label : str, optional (default=\"CellRanger_2\")\n how to name .obs column containing output\n verbose : bool, optional (default=True)\n print updates to console\n\n Returns\n -------\n\n adata edited in place to add .obs[label] binary label\n \"\"\"\n if \"total_counts\" not in adata.obs.columns:\n adata.obs[\"total_counts\"] = adata.X.sum(axis=1)\n tmp = np.sort(np.array(adata.obs[\"total_counts\"]))[::-1]\n thresh = np.quantile(tmp[0:expected], upper_quant) * lower_prop\n adata.uns[\"{}_knee_thresh\".format(label)] = thresh\n adata.obs[label] = \"False\"\n adata.obs.loc[adata.obs.total_counts > thresh, label] = \"True\"\n adata.obs[label] = adata.obs[label].astype(\"category\")\n if verbose:\n print(\"Detected knee point: {}\".format(round(thresh, 3)))\n print(adata.obs[label].value_counts())\n\n\ndef cellranger3(\n adata,\n init_counts=15000,\n min_umi_frac_of_median=0.01,\n min_umis_nonambient=500,\n max_adj_pvalue=0.01,\n):\n \"\"\"\n Labels cells using \"emptydrops\" method from CellRanger 3.0\n\n Parameters\n ----------\n\n adata : anndata.AnnData\n object containing unfiltered counts\n init_counts : int, optional (default=15000)\n initial total counts threshold for calling cells\n min_umi_frac_of_median : float, optional (default=0.01)\n minimum total counts for testing barcodes as fraction of median counts for \n initially labeled cells\n min_umis_nonambient : float, optional (default=500)\n minimum total counts for testing barcodes\n max_adj_pvalue : float, optional (default=0.01)\n maximum p-value for cell calling after B-H correction\n\n Returns\n -------\n\n adata edited in place to add .obs[\"CellRanger_3\"] binary label \n and .obs[\"CellRanger_3_ll\"] log-likelihoods for tested barcodes\n \"\"\"\n m = CountMatrix.from_anndata(adata) # create emptydrops object from adata\n if \"total_counts\" not in adata.obs.columns:\n adata.obs[\"total_counts\"] = adata.X.sum(axis=1)\n # label initial cell calls above total counts threshold\n adata.obs[\"CellRanger_3\"] = False\n adata.obs.loc[adata.obs.total_counts > init_counts, \"CellRanger_3\"] = True\n # call emptydrops to test for nonambient barcodes\n out = find_nonambient_barcodes(\n m,\n np.array(\n adata.obs.loc[adata.obs.CellRanger_3 == True,].index, dtype=m.bcs.dtype\n ),\n min_umi_frac_of_median=min_umi_frac_of_median,\n min_umis_nonambient=min_umis_nonambient,\n max_adj_pvalue=max_adj_pvalue,\n )\n # assign binary labels from emptydrops\n adata.obs.CellRanger_3.iloc[out[0]] = out[-1]\n adata.obs.CellRanger_3 = adata.obs.CellRanger_3.astype(str).astype(\n \"category\"\n ) # convert to category\n # assign log-likelihoods from emptydrops to .obs\n adata.obs[\"CellRanger_3_ll\"] = 0\n adata.obs.CellRanger_3_ll.iloc[out[0]] = out[1]\n\n\ndef subset_adata(adata, subset, verbose=True):\n \"\"\"\n Subsets AnnData object on one or more .obs columns\n\n Columns should contain 0/False for cells to throw out, and 1/True for cells to \n keep. Keeps union of all labels provided in subset.\n\n Parameters\n ----------\n\n adata : anndata.AnnData\n the data\n subset : str or list of str\n adata.obs labels to use for subsetting. Labels must be binary (0, \"0\", False, \n \"False\" to toss - 1, \"1\", True, \"True\" to keep). Multiple labels will keep \n intersection.\n verbose : bool, optional (default=True)\n print updates to console\n\n Returns\n -------\n\n adata : anndata.AnnData\n new anndata object as subset of `adata`\n \"\"\"\n if verbose:\n print(\"Subsetting AnnData on {}\".format(subset), end=\"\")\n if isinstance(subset, str):\n subset = [subset]\n # initialize .obs column for choosing cells\n adata.obs[\"adata_subset_combined\"] = 0\n # create label as union of given subset args\n for i in range(len(subset)):\n adata.obs.loc[\n adata.obs[subset[i]].isin([\"True\", True, 1.0, 1]), \"adata_subset_combined\"\n ] = 1\n adata = adata[adata.obs[\"adata_subset_combined\"] == 1, :].copy()\n adata.obs.drop(columns=\"adata_subset_combined\", inplace=True)\n if verbose:\n print(\" - now {} cells and {} genes\".format(adata.n_obs, adata.n_vars))\n return adata\n\n\ndef cc_score(adata, layer=None, seed=18, verbose=True):\n \"\"\"\n Calculates cell cycle scores and implied phase for each observation\n\n Parameters\n ----------\n\n adata : anndata.AnnData\n object containing transformed and normalized (arcsinh or log1p) counts in \n 'layer'.\n layer : str, optional (default=None)\n key from adata.layers to use for cc phase calculation. Default None to \n use .X\n seed : int, optional (default=18)\n random state for PCA, neighbors graph and clustering\n verbose : bool, optional (default=True)\n print updates to console\n\n Returns\n -------\n\n adata is edited in place to add 'G2M_score', 'S_score', and 'phase' to .obs\n \"\"\"\n if layer is not None:\n adata.layers[\"temp\"] = adata.X.copy()\n adata.X = adata.layers[layer].copy()\n if verbose:\n print(\"Calculating cell cycle scores using layer: {}\".format(layer))\n else:\n if verbose:\n print(\"Calculating cell cycle scores\")\n # determine if sample is mouse or human based on gene names\n if any(item in adata.var_names for item in s_genes_h + g2m_genes_h):\n s_genes, g2m_genes = s_genes_h, g2m_genes_h\n elif any(item in adata.var_names for item in s_genes_m + g2m_genes_m):\n s_genes, g2m_genes = s_genes_m, g2m_genes_m\n # score cell cycle using scanpy function\n sc.tl.score_genes_cell_cycle(\n adata,\n s_genes=s_genes, # defined at top of script\n g2m_genes=g2m_genes, # defined at top of script\n random_state=seed,\n )\n if layer is not None:\n adata.X = adata.layers[\"temp\"].copy()\n del adata.layers[\"temp\"]\n\n\ndef dim_reduce(\n adata,\n layer=None,\n use_rep=None,\n clust_resolution=1.0,\n paga=True,\n seed=18,\n verbose=True,\n):\n \"\"\"\n Reduces dimensions of single-cell dataset using standard methods\n\n Parameters\n ----------\n\n adata : anndata.AnnData\n object containing preprocessed counts matrix\n layer : str, optional (default=None)\n layer to use; default None for .X\n use_rep : str, optional (default=None)\n .obsm key to use for neighbors graph instead of PCA;\n default None, generate new PCA from layer\n clust_resolution : float, optional (default=1.0)\n resolution as fraction on [0.0, 1.0] for leiden\n clustering. default 1.0\n paga : bool, optional (default=True)\n run PAGA to seed UMAP embedding\n seed : int, optional (default=18)\n random state for PCA, neighbors graph and clustering\n verbose : bool, optional (default=True)\n print updates to console\n\n Returns\n -------\n\n adata is edited in place, adding PCA, neighbors graph, PAGA, and UMAP\n \"\"\"\n if use_rep is None:\n if layer is not None:\n if verbose:\n print(\"Using layer {} for dimension reduction\".format(layer))\n adata.X = adata.layers[layer].copy()\n if verbose:\n print(\n \"Performing PCA and building kNN graph with {} nearest neighbors\".format(\n int(np.sqrt(adata.n_obs))\n )\n )\n sc.pp.pca(adata, n_comps=50, random_state=seed)\n sc.pp.neighbors(\n adata, n_neighbors=int(np.sqrt(adata.n_obs)), n_pcs=20, random_state=seed\n )\n else:\n if verbose:\n print(\n \"Building kNN graph with {} nearest neighbors using {}\".format(\n int(np.sqrt(adata.n_obs)), use_rep\n )\n )\n sc.pp.neighbors(\n adata,\n n_neighbors=int(np.sqrt(adata.n_obs)),\n use_rep=use_rep,\n n_pcs=0,\n random_state=seed,\n )\n if verbose:\n print(\"Clustering cells using Leiden algorithm \", end=\"\")\n sc.tl.leiden(adata, random_state=seed, resolution=clust_resolution)\n if verbose:\n print(\n \"- {} clusters identified\".format(\n (len(adata.obs.leiden.cat.categories) + 1)\n )\n )\n if paga:\n if verbose:\n print(\"Building PAGA graph and UMAP from coordinates\")\n sc.tl.paga(adata)\n sc.pl.paga(adata, show=False)\n sc.tl.umap(adata, init_pos=\"paga\", random_state=seed)\n else:\n sc.tl.umap(adata, random_state=seed)\n\n\ndef plot_embedding(\n adata,\n colors=None,\n show_clustering=True,\n n_cnmf_markers=7,\n ncols=5,\n figsize_scale=1.0,\n cmap=\"Reds\",\n save_to=None,\n verbose=True,\n **kwargs,\n):\n \"\"\"\n Plots reduced-dimension embeddings of single-cell dataset\n\n Parameters\n ----------\n\n adata : anndata.AnnData\n object containing preprocessed and dimension-reduced counts matrix\n colors : list of str, optional (default=None)\n colors to plot; can be genes or .obs columns\n show_clustering : bool, optional (default=True)\n plot PAGA graph and leiden clusters on first two axes\n n_cnmf_markers : int, optional (default=7)\n number of top genes to print on cNMF plots\n ncols : int, optional (default=5)\n number of columns in gridspec\n figsize_scale : float, optional (default=1.0)\n scaler for figure size. calculated using ncols to keep each panel square. \n values < 1.0 will compress figure, > 1.0 will expand.\n cmap : str, optional (default=\"Reds\")\n valid color map for the plot\n save_to : str, optional (default=None)\n path to .png file for saving figure; default is plt.show()\n verbose : bool, optional (default=True)\n print updates to console\n **kwargs : optional\n args to pass to `sc.pl.umap` (e.g. \"size\", \"add_outline\", etc.)\n\n Returns\n -------\n\n plot of UMAP embedding with overlays from \"colors\" as matplotlib gridspec object, \n unless `save_to` is not None.\n \"\"\"\n if isinstance(colors, str): # force colors into list if single string\n colors = [colors]\n if \"paga\" in adata.uns:\n cluster_colors = [\"paga\", \"leiden\"]\n else:\n cluster_colors = [\"leiden\"]\n if colors is not None:\n # get full list of things to plot on UMAP\n if show_clustering:\n colors = cluster_colors + colors\n unique_colors = list_union(cluster_colors, colors)\n else:\n unique_colors = set(colors)\n else:\n # with no colors provided, plot PAGA graph and leiden clusters\n colors = cluster_colors\n unique_colors = set(colors)\n if verbose:\n print(\"Plotting embedding with overlays: {}\".format(list(unique_colors)))\n # set up figure size based on number of plots\n n_plots = len(unique_colors)\n if n_plots <= ncols:\n n_rows, n_cols = 1, n_plots\n else:\n n_rows, n_cols = ceil(n_plots / ncols), ncols\n fig = plt.figure(\n figsize=(ncols * n_cols * figsize_scale, ncols * n_rows * figsize_scale)\n )\n # arrange axes as subplots\n gs = gridspec.GridSpec(n_rows, n_cols, figure=fig)\n # add plots to axes\n i = 0\n for color in colors:\n if color in unique_colors:\n ax = plt.subplot(gs[i])\n if color.lower() == \"paga\":\n sc.pl.paga(\n adata,\n ax=ax,\n frameon=False,\n show=False,\n fontsize=\"large\",\n fontoutline=2.0,\n node_size_scale=2.5,\n )\n ax.set_title(label=\"PAGA\", loc=\"left\", fontweight=\"bold\", fontsize=16)\n else:\n if color in [\"leiden\", \"louvain\", \"cluster\", \"group\", \"cell_type\"]:\n leg_loc, leg_fontsize, leg_fontoutline = \"on data\", \"large\", 2.0\n else:\n leg_loc, leg_fontsize, leg_fontoutline = (\n \"right margin\",\n 12,\n None,\n )\n sc.pl.umap(\n adata,\n color=color,\n ax=ax,\n frameon=False,\n show=False,\n legend_loc=leg_loc,\n legend_fontsize=leg_fontsize,\n legend_fontoutline=leg_fontoutline,\n title=\"\",\n color_map=cmap,\n **kwargs,\n )\n # add top three gene loadings if cNMF\n if color.startswith(\"usage_\"):\n y_range = (\n adata.obsm[\"X_umap\"][:, 1].max()\n - adata.obsm[\"X_umap\"][:, 1].min()\n )\n [\n ax.text(\n x=adata.obsm[\"X_umap\"][:, 0].max(),\n y=adata.obsm[\"X_umap\"][:, 1].max() - (0.06 * y_range * x),\n s=\"\"\n + adata.uns[\"cnmf_markers\"].loc[x, color.split(\"_\")[1]],\n fontsize=12,\n fontstyle=\"italic\",\n color=\"k\",\n ha=\"right\",\n )\n for x in range(n_cnmf_markers)\n ]\n if color in adata.var_names: # italicize title if plotting a gene\n ax.set_title(\n label=color,\n loc=\"left\",\n fontweight=\"bold\",\n fontsize=16,\n fontstyle=\"italic\",\n )\n else:\n ax.set_title(label=color, loc=\"left\", fontweight=\"bold\", fontsize=16)\n unique_colors.remove(color)\n i = i + 1\n fig.tight_layout()\n if save_to is not None:\n if verbose:\n print(\"Saving embeddings to {}\".format(save_to))\n plt.savefig(save_to)\n else:\n return fig\n\n\ndef plot_genes(\n adata,\n de_method=\"t-test_overestim_var\",\n plot_type=\"heatmap\",\n groupby=\"leiden\",\n n_genes=5,\n dendrogram=True,\n ambient=False,\n cmap=\"Reds\",\n save_to=\"de.png\",\n verbose=True,\n):\n \"\"\"\n Calculates and plot `rank_genes_groups` results\n\n Parameters\n ----------\n\n adata : anndata.AnnData\n object containing preprocessed and dimension-reduced counts matrix\n de_method : str, optional (default=\"t-test_overestim_var\")\n one of \"t-test\", \"t-test_overestim_var\", \"wilcoxon\"\n plot_type : str, optional (default=\"heatmap\")\n one of \"heatmap\", \"dotplot\", \"matrixplot\"\n groupby : str, optional (default=\"leiden\")\n .obs key to group cells by\n n_genes : int, optional (default=5)\n number of top genes per group to show\n dendrogram : bool, optional (default=True)\n show dendrogram of cluster similarity\n ambient : bool, optional (default=False)\n include ambient genes as a group in the plot\n cmap : str, optional (default=\"Reds\")\n valid color map for the plot\n save_to : str, optional (default=\"de.png\")\n string to add to plot name using scanpy plot defaults\n verbose : bool, optional (default=True)\n print updates to console\n\n Returns\n -------\n\n matplotlib figure\n \"\"\"\n if verbose:\n print(\"Performing differential expression analysis...\")\n if de_method in [\"t-test\", \"t-test_overestim_var\"]:\n # rank genes with t-test and B-H correction\n sc.tl.rank_genes_groups(\n adata, groupby=groupby, layer=\"log1p_norm\", use_raw=False, method=de_method\n )\n elif de_method == \"wilcoxon\":\n # rank genes with wilcoxon rank sum test\n sc.tl.rank_genes_groups(\n adata, groupby=groupby, layer=\"raw_counts\", use_raw=False, method=de_method\n )\n else:\n print(\n \"Invalid de_method. Must be one of ['t-test','t-test_overestim_var','wilcoxon'].\"\n )\n return\n\n # calculate arcsinh counts for visualization\n adata.X = adata.layers[\"raw_counts\"].copy()\n sc.pp.normalize_total(adata)\n adata.X = np.arcsinh(adata.X)\n adata.layers[\"arcsinh\"] = adata.X.copy()\n adata.X = adata.layers[\"raw_counts\"].copy() # return raw counts to .X\n\n # adjust rcParams\n rcParams[\"figure.figsize\"] = (4, 4)\n rcParams[\"figure.subplot.left\"] = 0.18\n rcParams[\"figure.subplot.right\"] = 0.96\n rcParams[\"figure.subplot.bottom\"] = 0.15\n rcParams[\"figure.subplot.top\"] = 0.91\n\n if ambient:\n # get markers manually and append ambient genes\n markers = {}\n for clu in adata.obs[groupby].unique().tolist():\n markers[clu] = [\n adata.uns[\"rank_genes_groups\"][\"names\"][x][clu] for x in range(n_genes)\n ]\n markers[\"ambient\"] = adata.var_names[adata.var.ambient].tolist()\n\n if plot_type == \"heatmap\":\n myplot = sc.pl.heatmap(\n adata,\n markers,\n dendrogram=dendrogram,\n groupby=groupby,\n swap_axes=True,\n show_gene_labels=True,\n layer=\"arcsinh\",\n standard_scale=\"var\",\n var_group_rotation=0,\n cmap=cmap,\n show=False,\n )\n myplot[\"heatmap_ax\"].set_yticklabels(\n myplot[\"heatmap_ax\"].get_yticklabels(), fontstyle=\"italic\"\n )\n if plot_type == \"dotplot\":\n myplot = sc.pl.dotplot(\n adata,\n markers,\n dendrogram=dendrogram,\n groupby=groupby,\n layer=\"arcsinh\",\n standard_scale=\"var\",\n swap_axes=True,\n var_group_rotation=90,\n show=False,\n return_fig=True,\n )\n myplot.style(\n cmap=cmap, color_on=\"square\", dot_edge_color=None, dot_edge_lw=1\n )\n myplot.get_axes()[\"mainplot_ax\"].set_yticklabels(\n myplot.get_axes()[\"mainplot_ax\"].get_yticklabels(), fontstyle=\"italic\"\n )\n if plot_type == \"matrixplot\":\n myplot = sc.pl.matrixplot(\n adata,\n markers,\n dendrogram=dendrogram,\n groupby=groupby,\n layer=\"arcsinh\",\n standard_scale=\"var\",\n var_group_rotation=0,\n cmap=cmap,\n show=False,\n return_fig=True,\n )\n myplot.get_axes()[\"mainplot_ax\"].set_xticklabels(\n myplot.get_axes()[\"mainplot_ax\"].get_xticklabels(), fontstyle=\"italic\"\n )\n\n else:\n if plot_type == \"heatmap\":\n myplot = sc.pl.rank_genes_groups_heatmap(\n adata,\n dendrogram=dendrogram,\n groupby=groupby,\n n_genes=n_genes,\n swap_axes=True,\n show_gene_labels=True,\n layer=\"arcsinh\",\n standard_scale=\"var\",\n var_group_rotation=0,\n cmap=cmap,\n show=False,\n )\n myplot[\"heatmap_ax\"].set_yticklabels(\n myplot[\"heatmap_ax\"].get_yticklabels(), fontstyle=\"italic\"\n )\n if plot_type == \"dotplot\":\n myplot = sc.pl.rank_genes_groups_dotplot(\n adata,\n dendrogram=dendrogram,\n groupby=groupby,\n n_genes=n_genes,\n layer=\"arcsinh\",\n standard_scale=\"var\",\n swap_axes=True,\n var_group_rotation=90,\n show=False,\n return_fig=True,\n )\n myplot.style(\n cmap=cmap, color_on=\"square\", dot_edge_color=None, dot_edge_lw=1\n )\n myplot.get_axes()[\"mainplot_ax\"].set_yticklabels(\n myplot.get_axes()[\"mainplot_ax\"].get_yticklabels(), fontstyle=\"italic\"\n )\n if plot_type == \"matrixplot\":\n myplot = sc.pl.rank_genes_groups_matrixplot(\n adata,\n dendrogram=dendrogram,\n groupby=groupby,\n n_genes=n_genes,\n layer=\"arcsinh\",\n standard_scale=\"var\",\n var_group_rotation=0,\n cmap=cmap,\n show=False,\n return_fig=True,\n )\n myplot.get_axes()[\"mainplot_ax\"].set_xticklabels(\n myplot.get_axes()[\"mainplot_ax\"].get_xticklabels(), fontstyle=\"italic\"\n )\n\n if save_to is not None:\n plt.savefig(save_to, bbox_inches=\"tight\")\n else:\n return myplot\n\n\ndef plot_genes_cnmf(\n adata,\n plot_type=\"heatmap\",\n groupby=\"leiden\",\n attr=\"varm\",\n keys=\"cnmf_spectra\",\n indices=None,\n n_genes=5,\n dendrogram=True,\n cmap=\"Reds\",\n save_to=\"de_cnmf.png\",\n):\n \"\"\"\n Calculates and plots top cNMF gene loadings\n\n Parameters\n ----------\n\n adata : anndata.AnnData\n object containing preprocessed and dimension-reduced counts matrix\n plot_type : str, optional (default=\"heatmap\")\n one of \"heatmap\", \"dotplot\", \"matrixplot\"\n groupby : str, optional (default=\"leiden\")\n .obs key to group cells by\n attr : str {\"var\", \"obs\", \"uns\", \"varm\", \"obsm\"}\n attribute of adata that contains the score\n keys : str or list of str, optional (default=\"cnmf_spectra\")\n scores to look up an array from the attribute of adata\n indices : list of int, optional (default=None)\n column indices of keys for which to plot (e.g. [0,1,2] for first three keys)\n n_genes : int, optional (default=5)\n number of top genes per group to show\n dendrogram : bool, optional (default=True)\n show dendrogram of cluster similarity\n cmap : str, optional (default=\"Reds\")\n valid color map for the plot\n save_to : str, optional (default=\"de.png\")\n string to add to plot name using scanpy plot defaults\n\n Returns\n -------\n\n matplotlib figure\n \"\"\"\n # calculate arcsinh counts for visualization\n adata.X = adata.layers[\"raw_counts\"].copy()\n sc.pp.normalize_total(adata)\n adata.X = np.arcsinh(adata.X)\n adata.layers[\"arcsinh\"] = adata.X.copy()\n adata.X = adata.layers[\"raw_counts\"].copy() # return raw counts to .X\n\n # default to all usages\n if indices is None:\n indices = [x for x in range(getattr(adata, attr)[keys].shape[1])]\n # get scores for each usage\n if isinstance(keys, str) and indices is not None:\n scores = np.array(getattr(adata, attr)[keys])[:, indices]\n keys = [\"{}_{}\".format(keys, i + 1) for i in indices]\n labels = adata.var_names # search all var_names for top genes based on spectra\n # get top n_genes for each spectra\n markers = {}\n for iscore, score in enumerate(scores.T):\n markers[keys[iscore]] = []\n indices = np.argsort(score)[::-1][:n_genes]\n for x in indices[::-1]:\n markers[keys[iscore]].append(labels[x])\n\n # adjust rcParams\n rcParams[\"figure.figsize\"] = (4, 4)\n rcParams[\"figure.subplot.left\"] = 0.18\n rcParams[\"figure.subplot.right\"] = 0.96\n rcParams[\"figure.subplot.bottom\"] = 0.15\n rcParams[\"figure.subplot.top\"] = 0.91\n\n if plot_type == \"heatmap\":\n myplot = sc.pl.heatmap(\n adata,\n markers,\n dendrogram=dendrogram,\n groupby=groupby,\n swap_axes=True,\n show_gene_labels=True,\n layer=\"arcsinh\",\n standard_scale=\"var\",\n var_group_rotation=0,\n cmap=cmap,\n show=False,\n )\n myplot[\"heatmap_ax\"].set_yticklabels(\n myplot[\"heatmap_ax\"].get_yticklabels(), fontstyle=\"italic\"\n )\n if plot_type == \"dotplot\":\n myplot = sc.pl.dotplot(\n adata,\n markers,\n dendrogram=dendrogram,\n groupby=groupby,\n layer=\"arcsinh\",\n standard_scale=\"var\",\n swap_axes=True,\n var_group_rotation=90,\n show=False,\n return_fig=True,\n )\n myplot.style(cmap=cmap, color_on=\"square\", dot_edge_color=None, dot_edge_lw=1)\n myplot.get_axes()[\"mainplot_ax\"].set_yticklabels(\n myplot.get_axes()[\"mainplot_ax\"].get_yticklabels(), fontstyle=\"italic\"\n )\n if plot_type == \"matrixplot\":\n myplot = sc.pl.matrixplot(\n adata,\n markers,\n dendrogram=dendrogram,\n groupby=groupby,\n layer=\"arcsinh\",\n standard_scale=\"var\",\n var_group_rotation=0,\n cmap=cmap,\n show=False,\n return_fig=True,\n )\n myplot.get_axes()[\"mainplot_ax\"].set_xticklabels(\n myplot.get_axes()[\"mainplot_ax\"].get_xticklabels(), fontstyle=\"italic\"\n )\n\n if save_to is not None:\n plt.savefig(save_to, bbox_inches=\"tight\")\n else:\n return myplot\n\n\ndef rank_genes_cnmf(\n adata,\n attr=\"varm\",\n keys=\"cnmf_spectra\",\n indices=None,\n labels=None,\n color=\"black\",\n n_points=20,\n ncols=5,\n log=False,\n show=None,\n figsize=(5, 5),\n):\n \"\"\"\n Plots rankings. [Adapted from `scanpy.plotting._anndata.ranking`]\n\n See, for example, how this is used in `pl.pca_ranking`.\n\n Parameters\n ----------\n\n adata : anndata.AnnData\n the data\n attr : str {'var', 'obs', 'uns', 'varm', 'obsm'}\n the attribute of adata that contains the score\n keys : str or list of str, optional (default=\"cnmf_spectra\")\n scores to look up an array from the attribute of adata\n indices : list of int, optional (default=None)\n the column indices of keys for which to plot (e.g. [0,1,2] for first three \n keys)\n ncols : int, optional (default=5)\n number of columns in gridspec\n show : bool, optional (default=None)\n show figure or just return axes\n figsize : tuple of float, optional (default=(5,5))\n size of matplotlib figure\n\n Returns\n -------\n\n matplotlib gridspec with access to the axes\n \"\"\"\n # default to all usages\n if indices is None:\n indices = [x for x in range(getattr(adata, attr)[keys].shape[1])]\n # get scores for each usage\n if isinstance(keys, str) and indices is not None:\n scores = np.array(getattr(adata, attr)[keys])[:, indices]\n keys = [\"{}_{}\".format(keys, i + 1) for i in indices]\n n_panels = len(indices) if isinstance(indices, list) else 1\n if n_panels == 1:\n scores, keys = scores[:, None], [keys]\n if log:\n scores = np.log(scores)\n if labels is None:\n labels = (\n adata.var_names\n if attr in {\"var\", \"varm\"}\n else np.arange(scores.shape[0]).astype(str)\n )\n if isinstance(labels, str):\n labels = [labels + str(i + 1) for i in range(scores.shape[0])]\n if n_panels <= ncols:\n n_rows, n_cols = 1, n_panels\n else:\n n_rows, n_cols = ceil(n_panels / ncols), ncols\n fig = plt.figure(figsize=(n_cols * figsize[0], n_rows * figsize[1]))\n left, bottom = 0.1 / n_cols, 0.1 / n_rows\n gs = gridspec.GridSpec(\n nrows=n_rows,\n ncols=n_cols,\n wspace=0.1,\n left=left,\n bottom=bottom,\n right=1 - (n_cols - 1) * left - 0.01 / n_cols,\n top=1 - (n_rows - 1) * bottom - 0.1 / n_rows,\n )\n for iscore, score in enumerate(scores.T):\n plt.subplot(gs[iscore])\n indices = np.argsort(score)[::-1][: n_points + 1]\n for ig, g in enumerate(indices[::-1]):\n plt.text(\n x=score[g],\n y=ig,\n s=labels[g],\n color=color,\n # rotation=\"vertical\",\n verticalalignment=\"center\",\n horizontalalignment=\"right\",\n fontsize=\"medium\",\n fontstyle=\"italic\",\n )\n plt.title(keys[iscore].replace(\"_\", \" \"), fontsize=\"x-large\")\n plt.ylim(-0.9, ig + 0.9)\n score_min, score_max = np.min(score[indices]), np.max(score[indices])\n plt.xlim(\n (0.95 if score_min > 0 else 1.05) * score_min,\n (1.05 if score_max > 0 else 0.95) * score_max,\n )\n plt.xticks(rotation=45)\n plt.tick_params(labelsize=\"medium\")\n plt.tick_params(\n axis=\"y\", # changes apply to the y-axis\n which=\"both\", # both major and minor ticks are affected\n left=False,\n right=False,\n labelleft=False,\n )\n plt.grid(False)\n gs.tight_layout(fig)\n if show == False:\n return gs\n\n\ndef cluster_pie(\n adata, pie_by=\"batch\", groupby=\"leiden\", ncols=5, show=None, figsize=(5, 5),\n):\n \"\"\"\n Plots pie graphs showing makeup of cluster groups\n\n Parameters\n ----------\n\n adata : anndata.AnnData\n the data\n pie_by : str, optional (default=\"batch\")\n adata.obs column to split pie charts by\n groupby : str, optional (default=\"leiden\")\n adata.obs column to create pie charts for\n ncols : int, optional (default=5)\n number of columns in gridspec\n show : bool, optional (default=None)\n show figure or just return axes\n figsize : tuple of float, optional (default=(5,5))\n size of matplotlib figure\n\n Returns\n -------\n\n matplotlib gridspec with access to the axes\n \"\"\"\n if adata.obs[groupby].value_counts().min() == 0:\n print(\n \"Warning: unused categories detected in adata.obs['{}']; removing prior to building plots...\".format(\n groupby\n )\n )\n adata.obs[groupby] = adata.obs[groupby].cat.remove_unused_categories()\n # get portions for each cluster\n pies = {} # init empty dict\n for c in adata.obs[groupby].cat.categories:\n pies[c] = (\n adata.obs.loc[adata.obs[groupby] == c, pie_by].value_counts()\n / adata.obs[groupby].value_counts()[c]\n ).to_dict()\n n_panels = len(adata.obs[groupby].cat.categories)\n if n_panels <= ncols:\n n_rows, n_cols = 1, n_panels\n else:\n n_rows, n_cols = ceil(n_panels / ncols), ncols\n fig = plt.figure(figsize=(n_cols * figsize[0], n_rows * figsize[1]))\n left, bottom = 0.1 / n_cols, 0.1 / n_rows\n gs = gridspec.GridSpec(\n nrows=n_rows,\n ncols=n_cols,\n wspace=0.1,\n left=left,\n bottom=bottom,\n right=1 - (n_cols - 1) * left - 0.01 / n_cols,\n top=1 - (n_rows - 1) * bottom - 0.1 / n_rows,\n )\n # get pie chart colors\n cdict = {}\n # use existing scanpy colors, if applicable\n if \"{}_colors\".format(pie_by) in adata.uns:\n for ic, c in enumerate(adata.obs[pie_by].cat.categories):\n cdict[c] = adata.uns[\"{}_colors\".format(pie_by)][ic]\n else:\n cmap = plt.get_cmap(\"tab10\")\n for ic, c in enumerate(adata.obs[pie_by].cat.categories):\n cdict[c] = cmap(np.linspace(0, 1, len(adata.obs[pie_by].cat.categories)))[\n ic\n ]\n for ipie, pie in enumerate(pies.keys()):\n plt.subplot(gs[ipie])\n plt.pie(\n pies[pie].values(),\n labels=pies[pie].keys(),\n colors=[cdict[x] for x in pies[pie].keys()],\n radius=0.85,\n wedgeprops=dict(width=0.5),\n textprops={\"fontsize\": 12},\n )\n plt.title(\n label=\"{}_{}\".format(groupby, pie),\n loc=\"left\",\n fontweight=\"bold\",\n fontsize=16,\n )\n gs.tight_layout(fig)\n if show == False:\n return gs\n","sub_path":"kitchen/ingredients.py","file_name":"ingredients.py","file_ext":"py","file_size_in_byte":36471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"506648371","text":"import os\nimport re\n\nfrom thrift.transport import TSocket\nfrom thrift.transport import TTransport\nfrom thrift.protocol import TBinaryProtocol\n\nfrom hbase import Hbase\nfrom hbase.ttypes import *\n\n# find_path = '/var/www/html/Spark_SQL'\nfind_path = '/var/www/html/database'\n\nclass HbaseWrite():\n def __init__(self):\n self.tableName = 'database'\n self.transport = TSocket.TSocket('student62', 9090)\n self.transport = TTransport.TBufferedTransport(self.transport)\n self.transport.open()\n self.protocol = TBinaryProtocol.TBinaryProtocol(self.transport)\n self.client = Hbase.Client(self.protocol)\n\n def createTable(self):\n col1 = ColumnDescriptor(name=\"data:\", maxVersions=1)\n col2 = ColumnDescriptor(name=\"feature\", maxVersions=1)\n self.client.createTable(self.tableName, [col1, col2])\n\n def write(self, PicPath, PicName):\n row = PicName.split('.')[0]\n _data = PicName.split('.')[1]\n PicData = open('%s/%s' % (PicPath, PicName), 'rb').read()\n # TypeError: mutateRow() takes exactly 5 arguments (4 given)\n self.client.mutateRow(self.tableName, row, [Mutation(column='data:%s' % _data, value=PicData)])\n\n def read(self, tableName, PicName):\n row = PicName.split('.')[0]\n data_type = PicName.split('.')[1]\n get_data = self.client.get(tableName, row, 'data:%s' % data_type, {})[0]\n if get_data:\n return get_data.value\n else:\n return 'Error'\n\n\ndef main(_path):\n WHB = HbaseWrite()\n WHB.createTable()\n find_file = re.compile(r'^[0-9a-zA-Z\\_]*.jpg$')\n find_walk = os.walk(_path)\n for path, dirs, files in find_walk:\n for f in files:\n if find_file.search(f):\n path_name = path\n file_name = f\n WHB.write(path_name, file_name)\n\n\nif __name__ == '__main__':\n main(find_path)","sub_path":"python_img.py","file_name":"python_img.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"381494162","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: longshuicui\n@date : 2021/3/12\n@function:\n\"\"\"\nclass ListNode:\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\n\n\ndef addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode:\n dummy = ListNode(val=0)\n head = dummy\n borrow = 0\n while l1 is not None or l2 is not None:\n if not l1:\n val = l2.val\n l2 = l2.next\n elif not l2:\n val = l1.val\n l1 = l1.next\n elif l1 and l2:\n val = l1.val + l2.val\n l1 = l1.next\n l2 = l2.next\n num = (val + borrow) % 10\n node = ListNode(num)\n borrow = (val + borrow) // 10\n head.next = node\n head = head.next\n if borrow > 0:\n node = ListNode(borrow)\n head.next = node\n return dummy.next\n\n\nl1=ListNode(2, ListNode(4, ListNode(9)))\nl2=ListNode(5, ListNode(6, ListNode(4, ListNode(9))))\n\nres=addTwoNumbers(l1, l2)\n\nhead=res\nwhile head:\n print(head.val, end=\" \")\n head=head.next\n","sub_path":"10.链表/2.two sum (Medium).py","file_name":"2.two sum (Medium).py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"227316609","text":"'''\n 低级版本:\n while\n 1、用户输入一个值\n 2、判断值是多少\n if >随机数:猜对了\n else:猜错了\n'''\nimport random\n# 1.让系统产生一个随机数\n\ndata = random.randint(0,200) # 22\n# 2.循环的让用户去猜\n\ni = 1\nwhile i <= 20:\n num = input(\"请输入你要猜的数字:\") # \"22\" \"23\"\n num = int(num) # \"22\" --> 22\n if num > data:\n print(\"大了!\")\n elif num < data:\n print(\"小了!\")\n else:\n print(\"恭喜,猜对了!本次猜对数字为:\",data)\n break #终止循环\n\n\n\n\n\n","sub_path":"变量1.py","file_name":"变量1.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"426119282","text":"import argparse\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.utils.data as data\nimport numpy as np\n\nfrom complexYOLO import ComplexYOLO\nfrom kitti import KittiDataset\nfrom region_loss import RegionLoss\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='training complex yolo.')\n parser.add_argument('--dir', default='/home/m_vogel/KITTI', help='directory of KITTI')\n parser.add_argument('--batch_size', default=12, help='batch size')\n parser.add_argument('--epochs', default=200, help='number of epochs')\n\n args = parser.parse_args()\n\n dir = args.dir\n batch_size = args.batch_size\n number_epochs = args.epochs\n\n # dataset\n dataset = KittiDataset(root=dir, set='train')\n data_loader = data.DataLoader(dataset, batch_size, shuffle=True)\n\n model = ComplexYOLO()\n model.cuda()\n\n # define optimizer\n optimizer = optim.Adam(model.parameters())\n\n # define loss function\n region_loss = RegionLoss(num_classes=8, num_anchors=5)\n\n for epoch in range(number_epochs):\n\n for batch_idx, (rgb_map, target) in enumerate(data_loader):\n optimizer.zero_grad()\n\n rgb_map = rgb_map.view(rgb_map.data.size(0), rgb_map.data.size(3), rgb_map.data.size(1),\n rgb_map.data.size(2))\n output = model(rgb_map.float().cuda())\n\n loss = region_loss(output, target)\n loss.backward()\n optimizer.step()\n\n if (epoch % 10 == 0):\n torch.save(model, \"ComplexYOLO_epoch\" + str(epoch))\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"420348015","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport os\r\nimport time\r\nimport random\r\n\r\nif not os.path.exists('./pttbeauty'):\r\n os.mkdir('./pttbeauty')\r\n\r\n\r\nlist = list('[\\\\/:*?\"<>|\\r\\n.]+')\r\n\r\nurl = 'https://www.ptt.cc/bbs/Beauty/index.html'\r\nurlFirst = 'https://www.ptt.cc/ask/over18?from=%2Fbbs%2FBeauty%2Findex.html'\r\nurlSecond = 'https://www.ptt.cc/ask/over18' #點選滿18後 進入的畫面網址\r\n\r\n\r\nUserAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36'\r\n\r\nheaders = {'User-Agent' : UserAgent}\r\n\r\nss = requests.session()\r\nresFirst = ss.get(urlFirst, headers=headers)\r\nsoupFirst = BeautifulSoup(resFirst.text, 'html.parser')\r\n\r\n#data\r\n# 製作等等post要用的表單data\r\ndata =dict()\r\ndata[soupFirst.select('input')[0]['name']] = soupFirst.select('input')[0]['value']\r\ndata[soupFirst.select('button')[0]['name']] = soupFirst.select('button')[0]['value']\r\n\r\nss.post(urlSecond,headers=headers,data=data)\r\n\r\n\r\nfor i in range(0,20): \r\n res = ss.get(url, headers=headers)\r\n\r\n soup = BeautifulSoup(res.text,'html.parser')\r\n\r\n ArticleList = soup.select('div.title')\r\n #print(ArticleList)\r\n for tag in ArticleList:\r\n try:\r\n title = tag.select(\"a\")[0].text\r\n articleUrl = \"https://www.ptt.cc\" + tag.select(\"a\")[0][\"href\"]\r\n articleRes = ss.get(articleUrl, headers=headers)\r\n articleResSoup = BeautifulSoup(articleRes.text, 'html.parser')\r\n textarticleCoent = articleResSoup.select('div[id=\"main-content\"]')[0].text.split('※ 發信站')[0]\r\n try:\r\n with open('./pttbeauty/{}.txt'.format(title),'w',encoding='utf-8') as f: #以title命名檔案名稱\r\n f.write(articleUrl) #先把網址寫進文章裡\r\n except OSError:\r\n for i in list: \r\n title = title.replace(i,\"-\") #解決title有非法字元的問題\r\n with open('./pttbeauty/{}.txt'.format(title),'w',encoding='utf-8') as e:\r\n e.write(articleUrl)\r\n try:\r\n with open('./pttbeauty/{}.txt'.format(title),'a',encoding='utf-8') as f:\r\n f.write(textarticleCoent) #再把文章寫進去\r\n except OSError:\r\n for i in list:\r\n title = title.replace(i,\"-\")\r\n with open('./pttbeauty/{}.txt'.format(title),'a',encoding='utf-8') as e:\r\n e.write(textarticleCoent) \r\n except IndexError as e: #文章被刪除,會跑IndexError\r\n print(tag)\r\n url_new = \"https://www.ptt.cc\" + soup.select('a[class=\"btn wide\"]')[1]['href'] #取得上一頁的網址\r\n url = url_new \r\n time.sleep(random.randint(1,10)) ","sub_path":"practice/practice_03_ptt_beauty_practice.py","file_name":"practice_03_ptt_beauty_practice.py","file_ext":"py","file_size_in_byte":2799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"405003571","text":"\"\"\"\nConfeccionar un programa que simule tirar dos dados y luego muestre los valores que salieron. Imprimir un mensaje que ganó si la suma de los mismos es igual a 7.\n\nPara resolver este problema requerimos un algoritmo para que se genere un valor aleatorio entre 1 y 6. Como la generación de valores aleatorios es un tema muy frecuente la biblioteca estándar de Python incluye un módulo que nos resuelve la generación de valores aleatorios.\n\"\"\"\n\nimport random\ndado1 = random.randint(1, 6)\ndado2 = random.randint(1, 6)\nprint(\"Los dados son: \",dado1,\" y \",dado2,sep=(''))\n\nif dado1 + dado2 == 7:\n print(\"Usted gano\")\nelse:\n print(\"Usted perdio\")\n \n\"\"\"\nDesarrollar un programa que cargue una lista con 10 enteros.\nCargar los valores aleatorios con números enteros comprendidos entre 0 y 1000.\nMostrar la lista por pantalla.\nLuego mezclar los elementos de la lista y volver a mostrarlo.\n\"\"\"\n\ndef cargar():\n lista = []\n for i in range(10):\n lista.append(random.randint(0, 1000))\n return lista\ndef imprimir(lista):\n print(lista)\n \ndef mezclar(lista):\n random.shuffle(lista)\n\nlista=cargar()\nprint(\"Lista generada aleatoriamente\")\nimprimir(lista)\nmezclar(lista)\nprint(\"La misma lista luego de mezclar\")\nimprimir(lista)","sub_path":"pythonya/python_standard_library/python_std_lib.py","file_name":"python_std_lib.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"199168881","text":"#\n# estimate fake rate for irreducilble backgrounds \n#\n\nfrom ROOT import TFile, TTree, TH1D, TCanvas, TLorentzVector, TLatex, kRed\nimport tdrstyle \n\ndef getArgs() :\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-v\",\"--verbose\",default=0,type=int,help=\"Print level.\")\n parser.add_argument(\"-f\",\"--inFileName\",default='./VBF_sync_input.root',help=\"File to be analyzed.\")\n parser.add_argument(\"-y\",\"--year\",default=2017,type=int,help=\"Year for data.\")\n parser.add_argument(\"-l\",\"--LTcut\",default=80.,type=float,help=\"LT cut\")\n return parser.parse_args()\n\nclass dupeDetector() :\n \n def __init__(self):\n self.nCalls = 0 \n self.runEventList = []\n\n def checkEvent(self,entry) :\n self.nCalls += 1 \n runEvent = \"{0:d}:{1:d}\".format(entry.run,entry.evt)\n if runEvent in self.runEventList :\n #print(\"Event in list: runEventList={0:s}\".format(str(self.runEventList)))\n return True\n else :\n self.runEventList.append(runEvent)\n #print(\"New event: runEventList={0:s}\".format(str(self.runEventList)))\n return False\n\n def printSummary(self) :\n print(\"Duplicate Event Summary: Calls={0:d} Unique Events={1:d}\".format(self.nCalls,len(self.runEventList)))\n return\n\nargs = getArgs()\nera = str(args.year)\nnBins, xMin, xMax = 10, 0., 200.\nlumi = 1000.*41.8 \ncats = { 1:'eeet', 2:'eemt', 3:'eett', 4:'mmet', 5:'mmmt', 6:'mmtt', 7:'et', 8:'mt', 9:'tt' }\npreCutOff = False \n\n# use this utility class to screen out duplicate events\nDD = dupeDetector()\n\n# open an output file\nfOut = TFile('FakeRates.root', 'recreate' )\n\n# create histograms\nhBase, hTight = {}, {}\nhList = ['e_et','m_mt','t_et','t_mt','t1_tt','t2_tt']\nfor h in hList :\n hName = \"{0:s}Base\".format(h)\n hBase[h] = TH1D(hName,hName,10,0.,100.)\n hName = \"{0:s}Tight\".format(h)\n hTight[h] = TH1D(hName,hName,10,0.,100.)\n \n# loop over the data to fill the histograms\nfor era in ['2017B','2017C','2017D','2017E','2017F'] :\n for dataset in ['SingleElectron','SingleMuon','DoubleEG','DoubleMuon'] :\n inFileName = './data/{0:s}_Run{1:s}/{0:s}_Run{1:s}.root'.format(dataset,era)\n print(\"Opening {0:s}\".format(inFileName)) \n inFile = TFile.Open(inFileName)\n inFile.cd()\n inTree = inFile.Get(\"Events\")\n nentries = inTree.GetEntries()\n for i, e in enumerate(inTree) :\n\n # impose any common selection criteria here\n # include only same sign events \n if e.q_1*e.q_2 < 0. : continue\n if e.nbtag > 0 : continue\n \n # skip duplicate events\n if DD.checkEvent(e) : continue \n\n cat = cats[e.cat]\n if cat[2:] == 'et' :\n # apply transverse mass cut on electron-MET system\n et = TLorentzVector()\n et.SetPtEtaPhiM(e.pt_1,0.,e.phi_1,0.000511)\n ptMiss = TLorentzVector() \n ptMiss.SetPtEtaPhiM(e.met,0.,e.metphi,0.)\n eMET = et + ptMiss\n preCut = preCutOff or eMET.Mt() > 40. \n if preCut : hBase['e_et'].Fill(e.pt_1)\n hBase['t_et'].Fill(e.pt_2)\n if e.iso_1 > 0.5 :\n if preCut : hTight['e_et'].Fill(e.pt_1)\n if e.iso_2_ID > 15 :\n hTight['t_et'].Fill(e.pt_2)\n \n elif cat[2:] == 'mt' :\n # apply transverse mass cut on muon-MET system\n mut = TLorentzVector()\n mut.SetPtEtaPhiM(e.pt_1,0.,e.phi_1,0.102)\n ptMiss = TLorentzVector() \n ptMiss.SetPtEtaPhiM(e.met,0.,e.metphi,0.)\n muMET = mut + ptMiss\n preCut = preCutOff or muMET.Mt() > 40. \n if preCut : hBase['m_mt'].Fill(e.pt_1)\n hBase['t_mt'].Fill(e.pt_2)\n if e.iso_1 < 0.25 and e.iso_1_ID > 0 : \n if preCut : hTight['m_mt'].Fill(e.pt_1)\n if e.iso_2_ID > 15 :\n hTight['t_mt'].Fill(e.pt_2)\n\n else :\n H_LT = e.pt_1 + e.pt_2\n if not preCutOff and H_LT < args.LTcut : continue\n hBase['t1_tt'].Fill(e.pt_1)\n hBase['t2_tt'].Fill(e.pt_2)\n if e.iso_1_ID > 15 :\n hTight['t1_tt'].Fill(e.pt_1)\n if e.iso_2_ID > 15 : \n hTight['t2_tt'].Fill(e.pt_2)\n \n inFile.Close()\n\nDD.printSummary()\n\n\n# create a similar set of histograms for the MC\n# dictionaries where the nickName is the key\nxsec, totalWeight, sampleWeight = {}, {}, {}\nnickNames = []\n\n# 0 1 2 3 4 5 6\n# GluGluHToTauTau\tSignal\t48.58\t9259000\t198813970.4\t \t/GluGluHToTauTau_...\n# make a first pass to get the weights \nfor line in open('MCsamples_'+era+'.csv','r').readlines() :\n vals = line.split(',')\n nickName = vals[0]\n group = vals[1]\n #if not group.lower() == 'reducible' : continue \n nickNames.append(nickName) \n xsec[nickName] = float(vals[2])\n totalWeight[nickName] = float(vals[4])\n sampleWeight[nickName]= lumi*xsec[nickName]/totalWeight[nickName]\n print(\"group={0:10s} nickName={1:20s} xSec={2:10.3f} totalWeight={3:11.1f} sampleWeight={4:10.6f}\".format(\n group,nickName,xsec[nickName],totalWeight[nickName],sampleWeight[nickName]))\n\n# Stitch the DYJets and WJets samples\n\nfor i in range(1,5) :\n nn = 'DY{0:d}JetsToLL'.format(i) \n sampleWeight[nn] = lumi/(totalWeight['DYJetsToLL']/xsec['DYJetsToLL'] + totalWeight[nn]/xsec[nn])\n\nfor i in range(1,4) :\n nn = 'W{0:d}JetsToLNu'.format(i) \n sampleWeight[nn] = lumi/(totalWeight['WJetsToLNu']/xsec['WJetsToLNu'] + totalWeight[nn]/xsec[nn])\n\n# create histograms\nhBasePrompt, hTightPrompt = {}, {}\nfor h in hList :\n hName = \"{0:s}BasePrompt\".format(h)\n hBasePrompt[h] = TH1D(hName,hName,10,0.,100.)\n hName = \"{0:s}TightPrompt\".format(h)\n hTightPrompt[h] = TH1D(hName,hName,10,0.,100.)\n\nfor nickName in nickNames :\n inFileName = './MC/{0:s}/{0:s}.root'.format(nickName)\n print(\"Opening {0:s}\".format(inFileName)) \n inFile = TFile.Open(inFileName)\n inFile.cd()\n inTree = inFile.Get(\"Events\")\n nentries = inTree.GetEntries()\n \n nEvents, totalWeight = 0, 0.\n sWeight = sampleWeight[nickName]\n DYJets = (nickName == 'DYJetsToLL')\n WJets = (nickName == 'WJetsToLNu')\n \n for i, e in enumerate(inTree) :\n # impose any common selection criteria here\n # include only same sign events \n if e.q_1*e.q_2 < 0. : continue\n H_LT = e.pt_1 + e.pt_2\n if H_LT > args.LTcut : continue\n\n sw = sWeight\n if e.LHE_Njets > 0 :\n if DYJets : sw = sampleWeight['DY{0:d}JetsToLL'.format(e.LHE_Njets)]\n if WJets : sw = sampleWeight['W{0:d}JetsToLNu'.format(e.LHE_Njets)] \n weight = e.weight*sw\n \n cat = cats[e.cat]\n if cat[2:] == 'et' :\n if e.gen_match_1 == 1 or e.gen_match_1 == 15 :\n hBasePrompt['e_et'].Fill(e.pt_1,weight)\n if e.iso_1 > 0.5 : hTightPrompt['e_et'].Fill(e.pt_1,weight)\n if e.gen_match_2 == 5 :\n hBasePrompt['t_et'].Fill(e.pt_2,weight)\n if e.iso_2_ID > 15 : hTightPrompt['t_et'].Fill(e.pt_2,weight)\n elif cat[2:] == 'mt' :\n if e.gen_match_1 == 1 or e.gen_match_1 == 15 :\n hBasePrompt['m_mt'].Fill(e.pt_1,weight)\n if e.iso_1 < 0.25 and e.iso_1_ID > 0 : hTightPrompt['m_mt'].Fill(e.pt_1,weight)\n if e.gen_match_2 == 5 :\n hBasePrompt['t_mt'].Fill(e.pt_2,weight)\n if e.iso_2_ID > 15 : hTightPrompt['t_mt'].Fill(e.pt_2,weight)\n else :\n if e.gen_match_1 == 5 :\n hBasePrompt['t1_tt'].Fill(e.pt_1,weight)\n if e.iso_1_ID > 15 : hTightPrompt['t1_tt'].Fill(e.pt_1,weight)\n if e.gen_match_2 == 5 :\n hBasePrompt['t2_tt'].Fill(e.pt_2,weight)\n if e.iso_2_ID > 15 : hTightPrompt['t2_tt'].Fill(e.pt_2,weight)\n\n \n print(\"{0:30s} {1:7d} {2:10.6f} {3:5d} {4:8.3f}\".format(nickName,nentries,sampleWeight[nickName],nEvents,totalWeight))\n inFile.Close()\n\nfOut.cd()\nfor h in hList :\n hBase[h].Write()\n hTight[h].Write()\n hBasePrompt[h].Write()\n hTightPrompt[h].Write()\n \n \nexit()\n\n \n# use these histograms to calculate the fake rate factors\ngFakeRate = {} \nfor h in hList :\n gFakeRate[h] = hTight[h].Clone() \n gFakeRate[h].SetName(\"{0:s}Ratio\".format(h))\n gFakeRate[h].Sumw2()\n gFakeRate[h].Divide(hBase[h])\n\ntdrstyle.setTDRStyle()\n\nH = 600\nW = 1000\nH_ref = 600\nW_ref = 100\n\n# references for T, B, L, R\nT = 0.08*H_ref\nB = 0.12*H_ref \nL = 0.16*W_ref\nR = 0.04*W_ref\n\nc = TCanvas('c1','c1',50,50,W,H)\nc.SetFillColor(0)\nc.SetBorderMode(0)\nc.SetFrameFillStyle(0)\nc.SetFrameBorderMode(0)\n\nc.SetLeftMargin(L/W)\nc.SetRightMargin(R/W)\nc.SetTopMargin(T/H)\nc.SetBottomMargin(B/H)\n\nc.Divide(3,2)\nlTeX = {}\nxMin, xMax, yMin, yMax = 0., 80., 0., 0.25\nfor i, h in enumerate(hList) :\n c.cd(i+1)\n gFakeRate[h].GetXaxis().SetRangeUser(xMin,xMax)\n gFakeRate[h].SetMinimum(yMin)\n gFakeRate[h].SetMaximum(yMax)\n gFakeRate[h].SetLineWidth(2)\n gFakeRate[h].SetMarkerStyle(20)\n gFakeRate[h].SetMarkerSize(1.0)\n gFakeRate[h].SetMarkerColor(kRed)\n gFakeRate[h].GetXaxis().SetTitle('p_t (GeV/c)')\n gFakeRate[h].GetXaxis().SetLabelSize(0.06)\n gFakeRate[h].GetXaxis().SetTitleSize(0.06)\n gFakeRate[h].GetYaxis().SetTitle('p_fake')\n gFakeRate[h].GetYaxis().SetLabelSize(0.06)\n gFakeRate[h].GetYaxis().SetTitleSize(0.06)\n \n gFakeRate[h].Draw('e')\n lTeX[h] = TLatex(0.8*xMax,0.9*yMax,h)\n lTeX[h].SetTextSize(0.06) \n lTeX[h].Draw()\n c.Update()\n \nc.Draw()\nraw_input()\n\nfOut.cd()\nfOut.Write()\nfOut.Close() \n\n\n","sub_path":"fakes/makeFakeRateHistos.py","file_name":"makeFakeRateHistos.py","file_ext":"py","file_size_in_byte":9952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"262698749","text":"# %%\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import Pipeline\n\nfrom ChemUtils import EmscScaler, GlobalStandardScaler, SavgolFilter\nfrom CrossValPLS import (extra_plot_mse, extra_plot_variance_explained, mse_minimum, pls_regression, pls_scores, variance_explained)\nfrom ElasticNetVariableSelection import EnetSelect\nfrom ImportModule import cut_specs, importLuzCol\nfrom ValidationUtils import (cv_benchmark_model, print_cv_table, val_regression_plot)\n\n# %%\n# impor data\n\n# specs = pd.read_csv('./luzrawSpectra/nirMatrix.csv') # cut spectra\nspecs = pd.read_csv(\"/Users/maxprem/nirPy/calData_full.csv\") # full spectra\nlab = pd.read_excel(\"/Users/maxprem/nirGit/nirpy/luzrawSpectra/labData.xlsx\")\n# input wavenumber to cut spectra\nspecs = cut_specs(specs, 4100, 5500)\n\n# specs = cut_specs(specs, 4100, 5500)\n\n# %%\n\nX, y, wave_number, ref = importLuzCol(specs, lab, 2)\n\n# split dataset in train and test data\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n\n# %%\n# transformation pipeline\n\n# scale y\ny_scaler = GlobalStandardScaler()\ny_train = y_scaler.fit_transform(y_train)\ny_test = y_scaler.transform(y_test)\n\n\npip_dev0 = Pipeline(\n [\n (\"scaleing_X\", GlobalStandardScaler()),\n (\"scatter_correction\", EmscScaler()),\n (\"smmothing\", SavgolFilter(polyorder=2, deriv=0)),\n ]\n)\n\nX_train_0 = pip_dev0.fit_transform(X_train, y_train)\nX_test_0 = pip_dev0.transform(X_test)\n\n\ndata_en0 = {\"X\": X_train_0, \"y\": y_train, \"X_test\": X_test_0, \"y_test\": y_test}\n# %%\n# variable selection on whole data\n\n# scale y\ny_scaler = GlobalStandardScaler()\ny_scaled = y_scaler.fit_transform(y)\n\n\n\npip_sel = Pipeline(\n [\n (\"scaleing_X\", GlobalStandardScaler()),\n (\"scatter_correction\", EmscScaler()),\n (\"smmothing\", SavgolFilter(polyorder=2, deriv=0)),\n (\"variable_selection\", EnetSelect())\n ]\n)\n\nX_sel = pip_sel.fit_transform(X, y_scaled)\n\n#pip_sel[\"variable_selection\"].plot_feature_importance(wave_number)\n#pip_sel[\"variable_selection\"].plot(wave_number, X_train_0)\n\n\n# %%\n# to perform variable selection from regression with whole dataset\n\nX_train_0_sel = pip_sel[\"variable_selection\"].transform(X_train_0)\nX_test_0_sel = pip_sel[\"variable_selection\"].transform(X_test_0)\n\ndata_en_sel = {\"X\": X_train_0_sel, \"y\": y_train, \"X_test\": X_test_0_sel, \"y_test\": y_test}\n\n\n\n\n\n\n\n# %%\n\nvar, comp = variance_explained(X_train_0, y_train, plot=False)\nvar_2, comp_2 = variance_explained(X_test_0, y_test, plot=False)\nextra_plot_variance_explained(var, comp, var_2, comp_2)\n\nmse, comp = mse_minimum(X_train_0, y_train, plot=False)\nmase_2, comp_2 = mse_minimum(X_test_0, y_test, plot=False)\nextra_plot_mse(mse, comp, mase_2, comp_2)\n# %%\n\nvar, comp = variance_explained(X_train_0_sel, y_train, plot=False)\nvar_2, comp_2 = variance_explained(X_test_0_sel, y_test, plot=False)\nextra_plot_variance_explained(var, comp, var_2, comp_2)\n\nmse, comp = mse_minimum(X_train_0, y_train, plot=False)\nmase_2, comp_2 = mse_minimum(X_test_0, y_test, plot=False)\nextra_plot_mse(mse, comp, mase_2, comp_2)\n\n\n# %%\n\nmodel_0 = pls_regression(**data_en0, n_comp=4, plot=False)\nprint_cv_table(**data_en0, model=model_0)\n\n\nmodel_sel = pls_regression(**data_en_sel, n_comp=2, plot=False)\nprint_cv_table(**data_en_sel, model=model_sel)\n\n\n\n# %%\n\ncv_benchmark_model(**data_en0, model=model_0, y_unscaled=y, ref=ref, plot=True)\nval_regression_plot(**data_en0, model=model_0)\nval_regression_plot(**data_en_sel, model=model_sel)\n\n# %%\ncv_benchmark_model(**data_en0, y_unscaled=y, ref=ref, model=model_0)\ncv_benchmark_model(**data_en_sel, y_unscaled=y, ref=ref, model=model_sel)\ncv_benchmark_model(**data_en_sel, y_unscaled=y, ref=ref, model=model_sel)\n\n# %%\nfrom PLSfunctions import PLSOptimizer\npls_opt = PLSOptimizer()\npls_opt.fit(**data_en_sel, max_comp=10)\n","sub_path":"nirpy/pls_test.py","file_name":"pls_test.py","file_ext":"py","file_size_in_byte":3851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"316972162","text":"import sys\nimport collections\nsys.stdin = open(\"1260_DFS와 BFS.txt\", \"r\")\n\n\ndef bfs(G, v):\n visited = [0 for _ in range(V + 1)]\n deq = collections.deque()\n\n deq.append(v)\n visited[v] = 1\n print(v, end=\" \")\n while len(deq) != 0:\n v = deq.popleft()\n for w in range(1, V + 1):\n if G[v][w] == 1 and visited[w] == 0:\n deq.append(w)\n visited[w] = 1\n print(w, end=\" \")\n\ndef dfs(G, v): # small v: 시작점\n visited[v] = 1\n print(v, end=\" \")\n\n for w in range(V+1): # capital V: 총 정점 갯수\n if G[v][w] == 1 and visited[w] == 0:\n dfs(w)\n\n\nN, M, V = map(int, input().split()) # V가 정점\nG = [[0 for _ in range(N+1)] for _ in range(N+1)]\nvisited = [0 for _ in range(V + 1)]\n\nfor M_case in range(M):\n temp = list(map(int, input().split()))\n G[temp[0]][temp[1]] = 1\n G[temp[1]][temp[0]] = 1\n\ndfs(G, V)\nbfs(G, V)","sub_path":"SSAFY/이전_Pycharm_lym-master/백준/1260_DFS와 BFS.py","file_name":"1260_DFS와 BFS.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"210793010","text":"#!/usr/bin/env python\n#-*- encoding: utf8 -*-\n\nimport json\nimport rospy\nimport actionlib\n\nfrom mhri_msgs.msg import RenderItemAction, RenderItemResult, RenderItemFeedback\nfrom mhri_msgs.srv import GetInstalledGestures, GetInstalledGesturesResponse\n\nclass FakeMotionRender:\n\n def __init__(self):\n rospy.init_node('fake_renderer', anonymous=True)\n\n try:\n topic_name = rospy.get_param('~topic_name')\n except KeyError as e:\n print('[ERROR] Needed parameter for (topic_name)...')\n quit()\n\n if 'fake_render_gesture' in rospy.get_name():\n self.GetInstalledGesturesService = rospy.Service(\n \"get_installed_gestures\",\n GetInstalledGestures,\n self.handle_get_installed_gestures\n )\n\n self.motion_list = {\n 'neutral': ['neutral_motion1'],\n 'encourge': ['encourge_motion1'],\n 'attention': ['attention_motion1'],\n 'consolation': ['consolation_motion1'],\n 'greeting': ['greeting_motion1'],\n 'waiting': ['waiting_motion1'],\n 'advice': ['advice_motion1'],\n 'praise': ['praise_motion1'],\n 'command': ['command_motion1'],\n }\n\n self.server = actionlib.SimpleActionServer(\n topic_name, RenderItemAction, self.execute_callback, False)\n self.server.start()\n\n rospy.loginfo('[%s] initialized...' % rospy.get_name())\n rospy.spin()\n\n def handle_get_installed_gestures(self, req):\n result = json.dumps(self.motion_list)\n return GetInstalledGesturesResponse(result)\n\n\n def execute_callback(self, goal):\n rospy.loginfo('%s rendering requested...' % rospy.get_name())\n result = RenderItemResult()\n feedback = RenderItemFeedback()\n\n success = True\n\n while True:\n if self.server.is_preempt_requested():\n self.server.set_preempted()\n success = False\n break\n\n feedback.is_rendering = True\n self.server.publish_feedback(feedback)\n rospy.sleep(0.1)\n\n if success:\n result.result = True\n self.server.set_succeeded(result)\n rospy.loginfo('%s rendering completed...' % rospy.get_name())\n else:\n rospy.loginfo('%s rendering canceled...' % rospy.get_name())\n\n\nif __name__ == '__main__':\n m = FakeMotionRender()\n","sub_path":"motion_renderer/src/fake_renderer.py","file_name":"fake_renderer.py","file_ext":"py","file_size_in_byte":2501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"358697704","text":"import sys\nimport random\n\n\ndef simulation(people):\n birthdays = set()\n\n for _ in range(people):\n birthdays.add(random.randint(0, 365))\n\n return len(birthdays) != people\n\n\ndef print_results(people, counter, iterations):\n print()\n print('Birthday Paradox')\n print()\n print(' iterations: %8d' % (iterations))\n print()\n print(' People: %8d' % (people))\n print(' Proportion: %8.5f' % (counter / float(iterations)))\n print()\n\n\ndef main(argv):\n iterations = int(argv[0])\n people = int(argv[1])\n\n random.seed(1337)\n\n counter = 0\n for _ in range(iterations):\n if simulation(people):\n counter += 1\n\n print_results(people, counter, iterations)\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"simulations/birthday_paradox/birthday_paradox_01.py","file_name":"birthday_paradox_01.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"528995977","text":"# -*- coding: utf-8 -*-\nimport json\nimport random\nimport logging\nfrom datetime import datetime, timedelta\n\nfrom sqlalchemy import func\n\nfrom luckycommon.model import orm\nfrom luckycommon.account.model.account import Account\nfrom luckycommon.model.coupon import *\nfrom luckycommon.model.transaction import *\nfrom luckycommon.utils.tz import (now_ts, get_utc_date, utc_to_local,\n local_to_utc)\nfrom luckycommon.utils import id_generator\nfrom luckycommon.utils.decorator import sql_wrapper\nfrom luckycommon.utils.exceptions import (ResourceInsufficient,\n AuthenticateError, ServerError)\nfrom luckycommon.db.helper import list_object\n\n_LOGGER = logging.getLogger('lucky')\n_TRACKER = logging.getLogger('tracker')\n\n\n@sql_wrapper\ndef get_coupon(coupon_id, user_id, need_valid=True):\n query = AccountCoupon.query.filter(AccountCoupon.id == coupon_id)\\\n .filter(AccountCoupon.user_id == user_id)\n if need_valid:\n now = now_ts()\n query = query.filter(AccountCoupon.status == COUPON_STATUS.UNUSED)\\\n .filter(AccountCoupon.start_ts < now)\\\n .filter(AccountCoupon.expire_ts > now)\n return query.first()\n\n\n@sql_wrapper\ndef get_user_coupons(user_id, status, limit=0, offset=0):\n query = AccountCoupon.query\n count_query = orm.session.query(orm.func.count(AccountCoupon.id))\n query = query.filter(AccountCoupon.user_id == user_id)\n count_query = count_query.filter(AccountCoupon.user_id == user_id)\n if status is not None:\n junction = orm.or_\n status_filters = []\n if status & COUPON_STATUS.UNUSED:\n status_filters.append(AccountCoupon.status == COUPON_STATUS.UNUSED)\n if status & COUPON_STATUS.USED:\n status_filters.append(AccountCoupon.status == COUPON_STATUS.USED)\n if status & COUPON_STATUS.EXPIRED:\n status_filters.append(\n AccountCoupon.status == COUPON_STATUS.EXPIRED)\n query = query.filter(junction(*status_filters))\n count_query = count_query.filter(junction(*status_filters))\n count = count_query.all()[0][0]\n query = query.order_by(AccountCoupon.created_at.desc())\n if limit > 0:\n query = query.limit(limit)\n if offset > 0:\n query = query.offset(offset)\n coupons = query.all()\n return coupons, count\n\n\n@sql_wrapper\ndef list_coupon(query_dct):\n return list_object(query_dct, AccountCoupon)\n\n\n@sql_wrapper\ndef get_unused_coupons(user_id, limit=0, offset=0):\n query = AccountCoupon.query\n query = query.filter(AccountCoupon.user_id == user_id)\\\n .filter(AccountCoupon.status == COUPON_STATUS.UNUSED)\n query = query.order_by(AccountCoupon.start_ts).order_by(\n AccountCoupon.price.desc()).order_by(AccountCoupon.expire_ts)\n if limit > 0:\n query = query.limit(limit)\n if offset > 0:\n query = query.offset(offset)\n coupons = query.all()\n return coupons\n\n\n@sql_wrapper\ndef get_coupon_scope(coupon_tid):\n return CouponScope.query.filter(CouponScope.coupon_tid == coupon_tid).all()\n\n\n@sql_wrapper\ndef set_coupon_scope(coupon_tid, activity_tid):\n coupon_scope = CouponScope()\n coupon_scope.coupon_tid = coupon_tid\n coupon_scope.activity_tid = activity_tid\n coupon_scope.save()\n\n\n@sql_wrapper\ndef get_group_coupon(group_coupon_id, need_valid=True):\n query = GroupCoupon.query.filter(GroupCoupon.id == group_coupon_id)\n if need_valid:\n now = now_ts()\n query = query.filter(GroupCoupon.expire_ts > now)\n return query.first()\n\n\n@sql_wrapper\ndef get_coupon_by_id(coupon_id):\n return AccountCoupon.query.filter(AccountCoupon.id == coupon_id).first()\n\n\n@sql_wrapper\ndef expire_coupon(coupon_id):\n coupon = AccountCoupon.query.filter(AccountCoupon.id == coupon_id).one()\n if coupon.status == COUPON_STATUS.UNUSED:\n coupon.status = COUPON_STATUS.EXPIRED\n coupon.save()\n _TRACKER.info({'user_id': coupon.user_id,\n 'coupon_id': coupon.id,\n 'type': 'expire_coupon',\n 'price': coupon.price})\n\n\n@sql_wrapper\ndef use_coupon(coupon):\n res = AccountCoupon.query.filter(AccountCoupon.id == coupon.id).filter(\n AccountCoupon.status == COUPON_STATUS.UNUSED).update({\n 'status': COUPON_STATUS.USED,\n 'updated_at': datetime.utcnow()\n })\n if res:\n # add balance\n account = Account.query.filter(\n Account.id == coupon.user_id).with_lockmode('update').first()\n account.balance += coupon.price\n account.save(auto_commit=False)\n # add transaction\n transaction = Transaction()\n transaction.id = id_generator.generate_long_id('transaction')\n transaction.user_id = account.id\n transaction.type = TRANSACTION_TYPE.AWARD\n transaction.title = coupon.title\n transaction.price = coupon.price\n transaction.balance = account.balance\n transaction.status = TRANSACTION_STATUS.DONE\n transaction.save(auto_commit=False)\n orm.session.commit()\n return True\n else:\n _LOGGER.warn(\n 'use coupon fail, cocurrency occured!, coupon id[%s]' % coupon.id)\n return False\n\n\nSNATCH_COUPON_RATION = [\n {'start': 1, 'end': 20, 'tid': 87},\n {'start': 20, 'end': 55, 'tid': 88},\n {'start': 55, 'end': 70, 'tid': 89},\n {'start': 70, 'end': 90, 'tid': 90},\n {'start': 90, 'end': 100, 'tid': 91},\n]\n\n\n@sql_wrapper\ndef snatch_group_coupon(group_coupon_id, phone_number, account=None):\n group_coupon = GroupCoupon.query.filter(\n GroupCoupon.id == group_coupon_id).with_lockmode('update').one()\n if group_coupon.left_count <= 0:\n raise ResourceInsufficient('insufficient')\n group_coupon.left_count -= 1\n internal_coupons = {} if not group_coupon.coupons else json.loads(\n group_coupon.coupons)\n if phone_number in internal_coupons:\n raise AuthenticateError('no access')\n rand_int = random.randint(1, 100)\n for ratio_item in SNATCH_COUPON_RATION:\n if rand_int >= ratio_item['start'] and rand_int <= ratio_item['end']:\n tid = ratio_item['tid']\n break\n if not tid:\n raise ServerError('tid not found')\n internal_coupons.update({phone_number: tid})\n group_coupon.coupons = json.dumps(internal_coupons, ensure_ascii=False)\n template = CouponTemplate.query.filter(CouponTemplate.id == tid).one()\n if account:\n coupon = AccountCoupon.create_from_template(template, account.id)\n coupon.save(auto_commit=False)\n orm.session.flush()\n AccountCoupon.start_expire_timer(coupon.id, coupon.expire_ts)\n _TRACKER.info({'user_id': coupon.user_id,\n 'coupon_id': coupon.id,\n 'type': 'create_coupon',\n 'from': 'snatch',\n 'price': coupon.price})\n else:\n # anonymous\n awaiting_coupon = AwaitingCoupon()\n awaiting_coupon.template_id = tid\n awaiting_coupon.phone = phone_number\n awaiting_coupon.expire_ts = now_ts() + template.valid_ts\n awaiting_coupon.save(auto_commit=False)\n orm.session.commit()\n return template\n\n\n@sql_wrapper\ndef check_awaiting_coupon(user_id, phone):\n now = now_ts()\n items = AwaitingCoupon.query.filter(AwaitingCoupon.phone == phone)\\\n .filter(AwaitingCoupon.expire_ts > now)\\\n .filter(AwaitingCoupon.deleted == 0)\\\n .all()\n for item in items:\n template_id = item.template_id\n template = CouponTemplate.query.filter(\n CouponTemplate.id == template_id).one()\n coupon = AccountCoupon.create_from_template(template, user_id)\n coupon.save(auto_commit=False)\n orm.session.flush()\n AccountCoupon.start_expire_timer(coupon.id, coupon.expire_ts)\n item.deleted = 1\n item.save(auto_commit=False)\n _TRACKER.info({'user_id': coupon.user_id,\n 'coupon_id': coupon.id,\n 'type': 'create_coupon',\n 'from': 'awaiting',\n 'price': coupon.price})\n orm.session.commit()\n\n\n@sql_wrapper\ndef get_coupon_overview():\n today = get_utc_date()\n resp = {}\n resp[\"sent_count\"], resp[\"sent_price\"] = orm.session.query(\n func.count(AccountCoupon.id), func.sum(AccountCoupon.price)).filter(\n AccountCoupon.updated_at >= today).first()\n resp[\"used_count\"], resp[\"used_price\"] = orm.session.query(\n func.count(AccountCoupon.id), func.sum(AccountCoupon.price)).filter(\n AccountCoupon.status == COUPON_STATUS.USED).filter(\n AccountCoupon.updated_at >= today).first()\n resp[\"left_count\"], resp[\"left_price\"] = orm.session.query(\n func.count(AccountCoupon.id), func.sum(AccountCoupon.price)).filter(\n AccountCoupon.status == COUPON_STATUS.UNUSED).filter(\n AccountCoupon.expire_ts > now_ts()).first()\n\n for k in resp:\n if resp[k] is None:\n resp[k] = 0\n\n return resp\n\n\n@sql_wrapper\ndef get_coupon_report(date):\n report = {}\n today = get_utc_date(date)\n yesterday = today - timedelta(days=1)\n t = orm.session.query(func.count(AccountCoupon.id),\n func.sum(AccountCoupon.price)).filter(\n AccountCoupon.created_at >= yesterday).filter(\n AccountCoupon.created_at < today).first()\n report[\"last_day_sent_count\"], report[\n \"last_day_sent_price\"] = t if t[0] else (0, 0)\n t = orm.session.query(func.count(AccountCoupon.id),\n func.sum(AccountCoupon.price)).filter(\n AccountCoupon.status == COUPON_STATUS.USED).filter(\n AccountCoupon.updated_at >= yesterday).filter(\n AccountCoupon.updated_at < today).first()\n report[\"last_day_used_count\"], report[\n \"last_day_used_price\"] = t if t[0] else (0, 0)\n t = orm.session.query(func.count(AccountCoupon.id),\n func.count(AccountCoupon.price)).filter(\n AccountCoupon.status == COUPON_STATUS.UNUSED).filter(\n AccountCoupon.created_at < today).first()\n report[\"unused_count_until_today\"], report[\n \"unused_price_until_today\"] = t if t[0] else (0, 0)\n\n for k in report:\n if k.endswith('price'):\n report[k] = float(report[k])\n else:\n report[k] = int(float(report[k]))\n\n return report\n\n\n@sql_wrapper\ndef award_coupon(user_id, tid):\n template = CouponTemplate.query.filter(CouponTemplate.id == tid).first()\n coupon = AccountCoupon.create_from_template(template, user_id)\n coupon.save()\n AccountCoupon.start_expire_timer(coupon.id, coupon.expire_ts)\n return coupon\n\n\ndef award_coupon_in_transaction(user_id, tid, start_ts=None, extend=None):\n template = CouponTemplate.query.filter(CouponTemplate.id == tid).first()\n coupon = AccountCoupon.create_from_template(template, user_id, extend=extend, start_ts=start_ts)\n coupon.save(auto_commit=False)\n orm.session.flush()\n AccountCoupon.start_expire_timer(coupon.id, coupon.expire_ts)\n _LOGGER.info(\"add 1 award coupon: %s, user: %s\" % (tid, user_id))\n return coupon\n\n\n@sql_wrapper\ndef upsert_coupon_template(query_dct):\n if 'id' in query_dct:\n t = CouponTemplate.query.with_for_update().filter(\n CouponTemplate.id == query_dct.pop('id')).first()\n else:\n t = CouponTemplate()\n\n for k, v in query_dct.iteritems():\n if hasattr(CouponTemplate, k) and k not in (\n 'updated_at', 'created_at'):\n setattr(t, k, v)\n\n t.save()\n\n\n@sql_wrapper\ndef list_coupon_template(query_dct):\n return list_object(query_dct, CouponTemplate)\n\n\n@sql_wrapper\ndef get_coupon_template(id):\n return CouponTemplate.query.filter(CouponTemplate.id == id).first()\n","sub_path":"luckycommon/db/coupon.py","file_name":"coupon.py","file_ext":"py","file_size_in_byte":11949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"301976591","text":"#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n# Author = \"Hero_lws\"\r\n\r\n#_*_coding:utf-8_*_\r\n__author__ = 'Alex Li'\r\n\r\n\r\nimport socket\r\nimport sys\r\n\r\nmessages = [ b'This is the message. ',\r\n b'It will be sent ',\r\n b'in parts.',\r\n ]\r\nserver_address = ('192.168.221.130', 8000)\r\n\r\n# Create a TCP/IP socket\r\nsocks = [ socket.socket(socket.AF_INET, socket.SOCK_STREAM) for i in range(10000) ]\r\n# socks = [ socket.socket(socket.AF_INET, socket.SOCK_STREAM) for i in range(600) ]\r\n# window下1000不行,太多了会报错:ValueError: too many file descriptors in select()\r\n# 放到linux上就可以了,但是需要改参数,应为:Linux对于每个用户,系统限制其最大进程数。( 默认1024 )\r\n# 修改 ulimit -SHn 65535\r\n# 但多了还是会有问题:\r\n# OSError: [WinError 10055] 由于系统缓冲区空间不足或队列已满,不能执行套接字上的操作。( 20000个连接时挂了)\r\n\r\n# Connect the socket to the port where the server is listening\r\nprint('connecting to %s port %s' % server_address)\r\n\r\nfor s in socks:\r\n s.connect(server_address)\r\n\r\nfor message in messages:\r\n # Send messages on both sockets\r\n for s in socks:\r\n print('%s: sending \"%s\"' % (s.getsockname(), message) )\r\n s.send(message)\r\n\r\n # Read responses on both sockets\r\n for s in socks:\r\n data = s.recv(1024)\r\n print( '%s: received \"%s\"' % (s.getsockname(), data) )\r\n if not data:\r\n print(sys.stderr, 'closing socket', s.getsockname() )\r\n","sub_path":"day10_IO 操作/T1_IO多路复用/mutlti conn socket client.py","file_name":"mutlti conn socket client.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"459715923","text":"import datetime\n\nimport pytest\n\nimport pandas as pd\n\nimport ibis\nimport ibis.expr.datatypes as dt\n\n\npytestmark = pytest.mark.bigquery\npytest.importorskip('google.cloud.bigquery')\n\n\ndef test_timestamp_accepts_date_literals(alltypes):\n date_string = '2009-03-01'\n param = ibis.param(dt.timestamp).name('param_0')\n expr = alltypes.mutate(param=param)\n params = {param: date_string}\n result = expr.compile(params=params)\n expected = \"\"\"\\\nSELECT *, @param AS `param`\nFROM `ibis-gbq.testing.functional_alltypes`\"\"\"\n assert result == expected\n\n\n@pytest.mark.parametrize(\n ('distinct', 'expected_keyword'),\n [\n (True, 'DISTINCT'),\n (False, 'ALL'),\n ]\n)\ndef test_union(alltypes, distinct, expected_keyword):\n expr = alltypes.union(alltypes, distinct=distinct)\n result = expr.compile()\n expected = \"\"\"\\\nSELECT *\nFROM `ibis-gbq.testing.functional_alltypes`\nUNION {}\nSELECT *\nFROM `ibis-gbq.testing.functional_alltypes`\"\"\".format(expected_keyword)\n assert result == expected\n\n\ndef test_ieee_divide(alltypes):\n expr = alltypes.double_col / 0\n result = expr.compile()\n expected = \"\"\"\\\nSELECT IEEE_DIVIDE(`double_col`, 0) AS `tmp`\nFROM `ibis-gbq.testing.functional_alltypes`\"\"\"\n assert result == expected\n\n\ndef test_identical_to(alltypes):\n t = alltypes\n pred = t.string_col.identical_to('a') & t.date_string_col.identical_to('b')\n expr = t[pred]\n result = expr.compile()\n expected = \"\"\"\\\nSELECT *\nFROM `ibis-gbq.testing.functional_alltypes`\nWHERE (((`string_col` IS NULL) AND ('a' IS NULL)) OR (`string_col` = 'a')) AND\n (((`date_string_col` IS NULL) AND ('b' IS NULL)) OR (`date_string_col` = 'b'))\"\"\" # noqa: E501\n assert result == expected\n\n\n@pytest.mark.parametrize(\n 'timezone',\n [\n None,\n 'America/New_York'\n ]\n)\ndef test_to_timestamp(alltypes, timezone):\n expr = alltypes.date_string_col.to_timestamp('%F', timezone)\n result = expr.compile()\n if timezone:\n expected = \"\"\"\\\nSELECT PARSE_TIMESTAMP('%F', `date_string_col`, 'America/New_York') AS `tmp`\nFROM `ibis-gbq.testing.functional_alltypes`\"\"\"\n else:\n expected = \"\"\"\\\nSELECT PARSE_TIMESTAMP('%F', `date_string_col`) AS `tmp`\nFROM `ibis-gbq.testing.functional_alltypes`\"\"\"\n assert result == expected\n\n\n@pytest.mark.parametrize(\n ('case', 'expected', 'dtype'),\n [\n (datetime.date(2017, 1, 1), \"DATE '{}'\".format('2017-01-01'), dt.date),\n (\n pd.Timestamp('2017-01-01'),\n \"DATE '{}'\".format('2017-01-01'),\n dt.date\n ),\n ('2017-01-01', \"DATE '{}'\".format('2017-01-01'), dt.date),\n (\n datetime.datetime(2017, 1, 1, 4, 55, 59),\n \"TIMESTAMP '{}'\".format('2017-01-01 04:55:59'),\n dt.timestamp,\n ),\n (\n '2017-01-01 04:55:59',\n \"TIMESTAMP '{}'\".format('2017-01-01 04:55:59'),\n dt.timestamp,\n ),\n (\n pd.Timestamp('2017-01-01 04:55:59'),\n \"TIMESTAMP '{}'\".format('2017-01-01 04:55:59'),\n dt.timestamp,\n ),\n ]\n)\ndef test_literal_date(case, expected, dtype):\n expr = ibis.literal(case, type=dtype).year()\n result = ibis.bigquery.compile(expr)\n assert result == \"SELECT EXTRACT(year from {}) AS `tmp`\".format(expected)\n\n\n@pytest.mark.parametrize(\n ('case', 'expected', 'dtype', 'strftime_func'),\n [\n (\n datetime.date(2017, 1, 1),\n \"DATE '{}'\".format('2017-01-01'),\n dt.date,\n 'FORMAT_DATE'\n ),\n (\n pd.Timestamp('2017-01-01'),\n \"DATE '{}'\".format('2017-01-01'),\n dt.date,\n 'FORMAT_DATE'\n ),\n (\n '2017-01-01',\n \"DATE '{}'\".format('2017-01-01'),\n dt.date,\n 'FORMAT_DATE'\n ),\n (\n datetime.datetime(2017, 1, 1, 4, 55, 59),\n \"TIMESTAMP '{}'\".format('2017-01-01 04:55:59'),\n dt.timestamp,\n 'FORMAT_TIMESTAMP'\n ),\n (\n '2017-01-01 04:55:59',\n \"TIMESTAMP '{}'\".format('2017-01-01 04:55:59'),\n dt.timestamp,\n 'FORMAT_TIMESTAMP'\n ),\n (\n pd.Timestamp('2017-01-01 04:55:59'),\n \"TIMESTAMP '{}'\".format('2017-01-01 04:55:59'),\n dt.timestamp,\n 'FORMAT_TIMESTAMP'\n ),\n ]\n)\ndef test_day_of_week(case, expected, dtype, strftime_func):\n date_var = ibis.literal(case, type=dtype)\n expr_index = date_var.day_of_week.index()\n result = ibis.bigquery.compile(expr_index)\n assert result == \"SELECT MOD(EXTRACT(DAYOFWEEK FROM {}) + 5, 7) AS `tmp`\".format(expected) # noqa: E501\n\n expr_name = date_var.day_of_week.full_name()\n result = ibis.bigquery.compile(expr_name)\n if strftime_func == 'FORMAT_TIMESTAMP':\n assert result == \"SELECT {}('%A', {}, 'UTC') AS `tmp`\".format(\n strftime_func, expected\n )\n else:\n assert result == \"SELECT {}('%A', {}) AS `tmp`\".format(\n strftime_func, expected\n )\n\n\n@pytest.mark.parametrize(\n ('case', 'expected', 'dtype'),\n [\n (\n datetime.datetime(2017, 1, 1, 4, 55, 59),\n \"TIMESTAMP '{}'\".format('2017-01-01 04:55:59'),\n dt.timestamp,\n ),\n (\n '2017-01-01 04:55:59',\n \"TIMESTAMP '{}'\".format('2017-01-01 04:55:59'),\n dt.timestamp,\n ),\n (\n pd.Timestamp('2017-01-01 04:55:59'),\n \"TIMESTAMP '{}'\".format('2017-01-01 04:55:59'),\n dt.timestamp,\n ),\n (\n datetime.time(4, 55, 59),\n \"TIME '{}'\".format('04:55:59'),\n dt.time,\n ),\n ('04:55:59', \"TIME '{}'\".format('04:55:59'), dt.time),\n ]\n)\ndef test_literal_timestamp_or_time(case, expected, dtype):\n expr = ibis.literal(case, type=dtype).hour()\n result = ibis.bigquery.compile(expr)\n assert result == \"SELECT EXTRACT(hour from {}) AS `tmp`\".format(expected)\n\n\ndef test_window_function(alltypes):\n t = alltypes\n w1 = ibis.window(preceding=1, following=0,\n group_by='year', order_by='timestamp_col')\n expr = t.mutate(win_avg=t.float_col.mean().over(w1))\n result = expr.compile()\n expected = \"\"\"\\\nSELECT *,\n avg(`float_col`) OVER (PARTITION BY `year` ORDER BY `timestamp_col` ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS `win_avg`\nFROM `ibis-gbq.testing.functional_alltypes`\"\"\" # noqa: E501\n assert result == expected\n\n w2 = ibis.window(preceding=0, following=2,\n group_by='year', order_by='timestamp_col')\n expr = t.mutate(win_avg=t.float_col.mean().over(w2))\n result = expr.compile()\n expected = \"\"\"\\\nSELECT *,\n avg(`float_col`) OVER (PARTITION BY `year` ORDER BY `timestamp_col` ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING) AS `win_avg`\nFROM `ibis-gbq.testing.functional_alltypes`\"\"\" # noqa: E501\n assert result == expected\n\n w3 = ibis.window(preceding=(4, 2),\n group_by='year', order_by='timestamp_col')\n expr = t.mutate(win_avg=t.float_col.mean().over(w3))\n result = expr.compile()\n expected = \"\"\"\\\nSELECT *,\n avg(`float_col`) OVER (PARTITION BY `year` ORDER BY `timestamp_col` ROWS BETWEEN 4 PRECEDING AND 2 PRECEDING) AS `win_avg`\nFROM `ibis-gbq.testing.functional_alltypes`\"\"\" # noqa: E501\n assert result == expected\n\n\ndef test_range_window_function(alltypes):\n t = alltypes\n w = ibis.range_window(preceding=1, following=0,\n group_by='year', order_by='month')\n expr = t.mutate(two_month_avg=t.float_col.mean().over(w))\n result = expr.compile()\n expected = \"\"\"\\\nSELECT *,\n avg(`float_col`) OVER (PARTITION BY `year` ORDER BY `month` RANGE BETWEEN 1 PRECEDING AND CURRENT ROW) AS `two_month_avg`\nFROM `ibis-gbq.testing.functional_alltypes`\"\"\" # noqa: E501\n assert result == expected\n\n w3 = ibis.range_window(preceding=(4, 2),\n group_by='year', order_by='timestamp_col')\n expr = t.mutate(win_avg=t.float_col.mean().over(w3))\n result = expr.compile()\n expected = \"\"\"\\\nSELECT *,\n avg(`float_col`) OVER (PARTITION BY `year` ORDER BY UNIX_MICROS(`timestamp_col`) RANGE BETWEEN 4 PRECEDING AND 2 PRECEDING) AS `win_avg`\nFROM `ibis-gbq.testing.functional_alltypes`\"\"\" # noqa: E501\n assert result == expected\n\n\n@pytest.mark.parametrize(\n ('preceding', 'value'),\n [\n (5, 5),\n (ibis.nanosecond(), 0.001),\n (ibis.microsecond(), 1),\n (ibis.second(), 1000000),\n (ibis.minute(), 1000000 * 60),\n (ibis.hour(), 1000000 * 60 * 60),\n (ibis.day(), 1000000 * 60 * 60 * 24),\n (2 * ibis.day(), 1000000 * 60 * 60 * 24 * 2),\n (ibis.week(), 1000000 * 60 * 60 * 24 * 7),\n ]\n)\ndef test_trailing_range_window(alltypes, preceding, value):\n t = alltypes\n w = ibis.trailing_range_window(preceding=preceding,\n order_by=t.timestamp_col)\n expr = t.mutate(win_avg=t.float_col.mean().over(w))\n result = expr.compile()\n expected = \"\"\"\\\nSELECT *,\n avg(`float_col`) OVER (ORDER BY UNIX_MICROS(`timestamp_col`) RANGE BETWEEN {} PRECEDING AND CURRENT ROW) AS `win_avg`\nFROM `ibis-gbq.testing.functional_alltypes`\"\"\".format(value) # noqa: E501\n assert result == expected\n\n\n@pytest.mark.parametrize(\n ('preceding', 'value'),\n [\n (ibis.year(), None),\n ]\n)\ndef test_trailing_range_window_unsupported(alltypes, preceding, value):\n t = alltypes\n w = ibis.trailing_range_window(preceding=preceding,\n order_by=t.timestamp_col)\n expr = t.mutate(win_avg=t.float_col.mean().over(w))\n with pytest.raises(ValueError):\n expr.compile()\n","sub_path":"ibis/bigquery/tests/test_compiler.py","file_name":"test_compiler.py","file_ext":"py","file_size_in_byte":9790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"392805874","text":"import cv2\nimport numpy as np\n\ndef find_right_sizes(bounded_boxes, thresh, show_image):\n samples = np.empty((0,100))\n\n #loop over all digits\n for box in bounded_boxes:\n #unpack data\n x,y,w,h = box[0], box[1], box[2], box[3]\n\n #check if large enough to be digit but small enough to ignore rest\n if h>15 and h<30 and w<40 and w>7:\n\n #draw rectangle with thresh-hold and shape correct form\n roi = thresh[y:y+h,x:x+w]\n roismall = cv2.resize(roi,(10,10))\n sample = roismall.reshape((1,100))\n samples = np.append(samples,sample,0)\n\n #if user wants images shown\n if show_image:\n cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)\n cv2.namedWindow('View Power',cv2.WINDOW_NORMAL)\n cv2.resizeWindow('View Power', 1600,600)\n cv2.imshow('View Power', im)\n #show for 100 ms and check if exit called (esc key)\n key = cv2.waitKey(0)\n if key == ord('q'):\n sys.exit()\n #print what the NN would classify the digits as\n print(int(classify(samples)))\n\n return samples\n\n#takes an image and returns array with all digits pixels in it\ndef extract_digits(image, show_image=False, train=False):\n #copy becuase will be edited\n img = image.copy()\n\n #make an output, convert to grayscale and apply thresh-hold\n out = np.zeros(image.shape,np.uint8)\n gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)\n thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)\n\n #find conours\n contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)\n #create empty return list\n \n #for every contour if area large enoug to be digit add the box to list\n li = []\n for cnt in contours:\n if cv2.contourArea(cnt)>20:\n [x,y,w,h] = cv2.boundingRect(cnt)\n li.append([x,y,w,h])\n\n #sort list so it read from right to left\n li = sorted(li,key=lambda x: x[0], reverse=True)\n\n #return all digits found\n if not train:\n return find_right_sizes(li, thresh, show_image)\n return find_right_sizes_train(li, thresh, img)\n\ndef find_right_sizes_train(bounded_boxes, thresh, im):\n samples = np.empty((0,100))\n responses = []\n keys = [i for i in range(48,58)]\n\n #loop over all digits\n for box in bounded_boxes:\n #unpack data\n x,y,w,h = box[0], box[1], box[2], box[3]\n\n #check if large enough to be digit but small enough to ignore rest\n if h>15 and h<30 and w<40 and w>7:\n\n #draw rectangle with thresh-hold and shape correct form\n cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),1)\n roi = thresh[y:y+h,x:x+w]\n roismall = cv2.resize(roi,(10,10))\n\n #show digit to user\n cv2.namedWindow('View Power',cv2.WINDOW_NORMAL)\n cv2.resizeWindow('View Power', 600,600)\n cv2.imshow('View Power',im)\n key = cv2.waitKey(0)\n print(key)\n #handle user input\n if key == 27: \n sys.exit()\n elif key == 108:\n continue\n elif key in keys:\n responses.append(int(chr(key)))\n sample = roismall.reshape((1,100))\n samples = np.append(samples,sample,0)\n\n #format and return\n responses = np.array(responses,np.float32)\n return responses, samples\n\n\n#get list of found digits and runs it through NN\ndef classify(data, clf):\n # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n clas = []\n\n #run every found digit through NN\n for i in data:\n clas.append(int(clf.predict([i])[0]))\n\n #reverse list and add all together in 1 integer to find final power\n clas.reverse()\n clas = map(str, clas)\n clas = ''.join(clas)\n return clas","sub_path":"own NN/ReadPowersVideo/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":3924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"143853890","text":"import os\nimport json\nfrom concurrent import futures\n\nimport numpy as np\nimport z5py\nimport luigi\nimport nifty.tools as nt\nimport nifty.distributed as ndist\nfrom ...paintera import ConversionWorkflow\n\n\ndef to_paintera_format():\n target = 'local'\n max_jobs = 8\n\n path = './data/data.n5'\n with z5py.File(path) as f:\n ds = f['labels']\n offset = ds.attrs['offset']\n resolution = ds.attrs['resolution']\n\n config_dir = './configs'\n if not os.path.exists(config_dir):\n os.mkdir(config_dir)\n configs = ConversionWorkflow.get_config()\n\n shebang = \"#! /g/kreshuk/pape/Work/software/conda/miniconda3/envs/cluster_env/bin/python\"\n global_config = configs['global']\n global_config.update({'shebang': shebang})\n with open('./configs/global.config', 'w') as f:\n json.dump(global_config, f)\n\n sampling_config = {'library': 'vigra', 'library_kwargs': {'order': 0}}\n\n ds_config = configs['downscaling']\n ds_config.update({**sampling_config})\n with open(os.path.join(config_dir, 'downscaling.config'), 'w') as f:\n json.dump(ds_config, f)\n\n t = ConversionWorkflow(path=path,\n raw_key='volumes/raw',\n label_in_key='labels',\n label_out_key='volumes/labels/neuron_ids',\n assignment_key='',\n label_scale=0,\n offset=offset,\n resolution=resolution,\n tmp_folder='./tmp',\n max_jobs=max_jobs,\n config_dir=config_dir,\n target=target)\n luigi.build([t], local_scheduler=True)\n\n\ndef check_block_uniques(scale):\n print(\"Checking block uniques for scale\", scale)\n path = './data/data.n5'\n f = z5py.File(path)\n ds_seg = f['volumes/labels/neuron_ids/data/s%i' % scale]\n ds_uns = f['volumes/labels/neuron_ids/unique-labels/s%i' % scale]\n\n print(\"Checking shapes and chunk shapes\")\n assert ds_seg.shape == ds_uns.shape\n assert ds_seg.chunks == ds_uns.chunks\n chunks = list(ds_seg.chunks)\n\n blocking = nt.blocking([0, 0, 0], list(ds_seg.shape), chunks)\n\n def check_chunk(chunk_id):\n chunk = blocking.getBlock(chunk_id)\n chunk_coord = tuple(beg // ch for beg, ch in zip(chunk.begin, chunks))\n seg = ds_seg.read_chunk(chunk_coord)\n uns = ds_uns.read_chunk(chunk_coord)\n assert seg is not None\n assert uns is not None\n seg_uns = np.unique(seg)\n return np.allclose(uns, seg_uns)\n\n print(\"Checking correctness for %i chunks\" % blocking.numberOfBlocks)\n with futures.ThreadPoolExecutor(8) as tp:\n tasks = [tp.submit(check_chunk, chunk_id)\n for chunk_id in range(blocking.numberOfBlocks)]\n results = [t.result() for t in tasks]\n\n assert len(results) == blocking.numberOfBlocks\n\n if not all(results):\n n_failed = len(results) - sum(results)\n print(n_failed, \"/\", len(results), \"chunks falied\")\n assert False\n\n print(\"All checks passed\")\n\n\ndef check_all_uniques():\n for scale in range(3):\n check_block_uniques(scale)\n\n\ndef check_id(label_id, seg, rois):\n for roi in rois:\n bb = np.s_[roi[2]:roi[5] + 1,\n roi[1]:roi[4] + 1,\n roi[0]:roi[3] + 1]\n if label_id not in seg[bb]:\n return False\n return True\n\n\ndef check_block_mapping(scale):\n print(\"Checking block mapping for scale\", scale)\n path = './data/data.n5'\n f = z5py.File(path)\n ds_seg = f['volumes/labels/neuron_ids/data/s%i' % scale]\n ds_map = f['volumes/labels/neuron_ids/label-to-block-mapping/s%i' % scale]\n\n ds_seg.n_threads = 8\n seg = ds_seg[:]\n\n chunk_id = (0,)\n while True:\n print(\"Checking mapping chunk\", chunk_id)\n mapping = ndist.readBlockMapping(ds_map.path, chunk_id)\n\n if not mapping:\n print(\"Breaking at chunk\", chunk_id)\n break\n print(\"Chunk has %i ids\" % len(mapping))\n\n with futures.ThreadPoolExecutor(8) as tp:\n tasks = [tp.submit(check_id, label_id, seg, rois)\n for label_id, rois in mapping.items()]\n results = [t.result() for t in tasks]\n assert len(results) == len(mapping)\n\n if not all(results):\n n_failed = len(results) - sum(results)\n print(n_failed, \"/\", len(results), \"ids in chunk falied\")\n assert False\n chunk_id = (chunk_id[0] + 1,)\n\n print(\"All checks passed\")\n\n\ndef check_all_mappings():\n for scale in range(3):\n check_block_mapping(scale)\n\n\nif __name__ == '__main__':\n # check_all_mappings()\n # check_all_uniques()\n to_paintera_format()\n","sub_path":"example/paintera/paintera_conversion.py","file_name":"paintera_conversion.py","file_ext":"py","file_size_in_byte":4788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"428018475","text":"# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\n FileName : find_disappeared_numbers.py\n Author : libins\n Contact : libins810@gmail.com\n CreateDate : 2020-03-05 21:43\n SoftWare : IntelliJ IDEA\n Description : 找到所有数组中消失的数字[leetcode:448题]\n-------------------------------------------------\n\"\"\"\n\n\n# 类似布隆过滤器\ndef find_disappeared_numbers(arr):\n nums = [0] * (len(arr) + 1) # 申请一个长度为输入数组+1 ,且所有元素都是0的数组\n target_nums = [] # 最终需要返回的数组\n for a in arr:\n nums[a] = 1 # 把原数组的值当做新申请数组的下标,并且该下标的值在申请的数组里置为1\n for i in range(1, len(nums)):\n if nums[i] == 0: # 如果发现有值为0,则该值对应的下标就是原数组缺失的元素\n target_nums.append(i)\n return target_nums\n\n\narr = [4, 3, 2, 7, 8, 2, 3, 1]\n# arr = [1, 1]\nret = find_disappeared_numbers(arr)\nprint(ret)\n","sub_path":"find_disappeared_numbers.py","file_name":"find_disappeared_numbers.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"367422496","text":"# Copyright notice:\n# Copyright CERN, 2014.\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 urllib\nfrom insert_job import insert_job\n\nfrom fts3rest.tests import TestController\n\n\ndef _group_by_triplet(snapshot):\n new_snapshot = dict()\n\n for triplet_info in snapshot:\n triplet = (\n str(triplet_info['source_se']),\n str(triplet_info['dest_se']),\n str(triplet_info['vo_name'])\n )\n new_snapshot[triplet] = triplet_info\n\n return new_snapshot\n\n\nclass TestSnapshot(TestController):\n \"\"\"\n Test the snapshot API\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Insert some registers into the tables\n \"\"\"\n TestController.setUp(self)\n # Insert some values into the DB\n insert_job('dteam', 'srm://source.se', 'srm://dest.es', 'ACTIVE')\n insert_job('dteam', 'srm://source.se', 'srm://dest.es', 'SUBMITTED')\n insert_job('dteam', 'srm://source.se', 'srm://dest.es', 'SUBMITTED')\n insert_job(\n 'dteam', 'srm://source.se', 'srm://dest.es', 'FINISHED', duration=55, queued=10, thr=10\n )\n insert_job(\n 'atlas', 'srm://source.se', 'srm://dest.es', 'FINISHED', duration=100, queued=20, thr=100\n )\n insert_job(\n 'atlas', 'srm://source.se', 'srm://dest.es', 'FAILED', duration=150, queued=30, thr=200,\n reason='DESTINATION Something something'\n )\n insert_job(\n 'atlas', 'gsiftp://source.se', 'gsiftp://dest.es', 'FAILED', duration=5000, queued=0,\n reason='SOURCE Blah'\n )\n insert_job(\n 'atlas', 'srm://source.se', 'gsiftp://dest.es', 'FINISHED', duration=100, queued=20, thr=50\n )\n\n def test_query_all(self):\n \"\"\"\n Get snapshot information for all pairs and vos\n \"\"\"\n self.setup_gridsite_environment()\n snapshot_raw = self.app.get(url=\"/snapshot\", status=200).json\n snapshot = _group_by_triplet(snapshot_raw)\n\n self.assertEqual(4, len(snapshot_raw))\n\n self.assertEqual(1, snapshot[('srm://source.se', 'srm://dest.es', 'dteam')]['active'])\n self.assertEqual(2, snapshot[('srm://source.se', 'srm://dest.es', 'dteam')]['submitted'])\n self.assertEqual(1, snapshot[('srm://source.se', 'srm://dest.es', 'dteam')]['finished'])\n self.assertEqual(0, snapshot[('srm://source.se', 'srm://dest.es', 'dteam')]['failed'])\n self.assertEqual(None, snapshot[('srm://source.se', 'srm://dest.es', 'dteam')]['frequent_error'])\n self.assertEqual(10, snapshot[('srm://source.se', 'srm://dest.es', 'dteam')]['avg_queued'])\n self.assertEqual(10, snapshot[('srm://source.se', 'srm://dest.es', 'dteam')]['avg_throughput']['60'])\n self.assertEqual(1.0, snapshot[('srm://source.se', 'srm://dest.es', 'dteam')]['success_ratio'])\n\n self.assertEqual(0, snapshot[('srm://source.se', 'srm://dest.es', 'atlas')]['active'])\n self.assertEqual(0, snapshot[('srm://source.se', 'srm://dest.es', 'atlas')]['submitted'])\n self.assertEqual(1, snapshot[('srm://source.se', 'srm://dest.es', 'atlas')]['finished'])\n self.assertEqual(1, snapshot[('srm://source.se', 'srm://dest.es', 'atlas')]['failed'])\n self.assertEqual(1, snapshot[('srm://source.se', 'srm://dest.es', 'atlas')]['frequent_error']['count'])\n self.assertEqual(\n 'DESTINATION Something something',\n snapshot[('srm://source.se', 'srm://dest.es', 'atlas')]['frequent_error']['reason']\n )\n # Note that only FINISHED must be count\n self.assertEqual(25, snapshot[('srm://source.se', 'srm://dest.es', 'atlas')]['avg_queued'])\n self.assertEqual(100, snapshot[('srm://source.se', 'srm://dest.es', 'atlas')]['avg_throughput']['30'])\n self.assertEqual(0.5, snapshot[('srm://source.se', 'srm://dest.es', 'atlas')]['success_ratio'])\n\n self.assertEqual(1, snapshot[('gsiftp://source.se', 'gsiftp://dest.es', 'atlas')]['frequent_error']['count'])\n self.assertEqual(\n 'SOURCE Blah', snapshot[('gsiftp://source.se', 'gsiftp://dest.es', 'atlas')]['frequent_error']['reason']\n )\n\n def test_query_vo(self):\n \"\"\"\n Get snapshot for one specific VO\n \"\"\"\n self.setup_gridsite_environment()\n snapshot_raw = self.app.get(url=\"/snapshot?vo_name=dteam\", status=200).json\n snapshot = _group_by_triplet(snapshot_raw)\n\n self.assertEqual(1, len(snapshot_raw))\n self.assertEqual(('srm://source.se', 'srm://dest.es', 'dteam'), snapshot.keys()[0])\n self.assertEqual(1, snapshot[('srm://source.se', 'srm://dest.es', 'dteam')]['active'])\n self.assertEqual(2, snapshot[('srm://source.se', 'srm://dest.es', 'dteam')]['submitted'])\n self.assertEqual(1, snapshot[('srm://source.se', 'srm://dest.es', 'dteam')]['finished'])\n self.assertEqual(None, snapshot[('srm://source.se', 'srm://dest.es', 'dteam')]['frequent_error'])\n self.assertEqual(10, snapshot[('srm://source.se', 'srm://dest.es', 'dteam')]['avg_queued'])\n self.assertEqual(10, snapshot[('srm://source.se', 'srm://dest.es', 'dteam')]['avg_throughput']['5'])\n self.assertEqual(1.0, snapshot[('srm://source.se', 'srm://dest.es', 'dteam')]['success_ratio'])\n\n def test_query_source(self):\n \"\"\"\n Snapshot filtering by source only\n \"\"\"\n self.setup_gridsite_environment()\n snapshot_raw = self.app.get(\n url=\"/snapshot?source_se=%s\" % urllib.quote(\"srm://source.se\", \"\"),\n status=200\n ).json\n\n self.assertEqual(3, len(snapshot_raw))\n\n def test_query_destination(self):\n \"\"\"\n Snapshot filtering by destination only\n \"\"\"\n self.setup_gridsite_environment()\n snapshot_raw = self.app.get(\n url=\"/snapshot?dest_se=%s\" % urllib.quote(\"srm://dest.es\", \"\"),\n status=200\n ).json\n\n self.assertEqual(2, len(snapshot_raw))\n\n def test_query_pair(self):\n \"\"\"\n Snapshot filtering by pair\n \"\"\"\n self.setup_gridsite_environment()\n snapshot_raw = self.app.get(\n url=\"/snapshot?source_se=%s&dest_se=%s\" % (\n urllib.quote(\"srm://source.se\", \"\"), urllib.quote(\"srm://dest.es\", \"\")\n ),\n status=200\n ).json\n\n self.assertEqual(2, len(snapshot_raw))\n\n def test_query_triplet(self):\n \"\"\"\n Snapshot filtering by source, destination and vo\n \"\"\"\n self.setup_gridsite_environment()\n snapshot_raw = self.app.get(\n url=\"/snapshot?source_se=%s&dest_se=%s&vo_name=%s\" % (\n urllib.quote(\"srm://source.se\", \"\"), urllib.quote(\"srm://dest.es\", \"\"), \"atlas\"\n ),\n status=200\n ).json\n snapshot = _group_by_triplet(snapshot_raw)\n\n self.assertEqual(1, len(snapshot_raw))\n self.assertEqual(('srm://source.se', 'srm://dest.es', 'atlas'), snapshot.keys()[0])\n","sub_path":"src/fts3rest/fts3rest/tests/functional/test_snapshot.py","file_name":"test_snapshot.py","file_ext":"py","file_size_in_byte":7516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"498867484","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom uuid import UUID\n\nfrom django.db import models\nfrom django.dispatch import receiver\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.urls import reverse\n\nfrom ..abstract.helpers import time_zone_aware_now\nfrom ..abstract.models import PBSMMGenericSeason\n\nfrom ..api.api import get_PBSMM_record\nfrom ..api.helpers import check_pagination\nfrom ..asset.models import PBSMMAbstractAsset\nfrom ..asset.ingest_asset import process_asset_record\n\nfrom .ingest_season import process_season_record\nfrom .ingest_children import process_episodes\n\nPBSMM_SEASON_ENDPOINT = 'https://media.services.pbs.org/api/v1/seasons/'\n\n\nclass PBSMMSeason(PBSMMGenericSeason):\n \"\"\"\n These are the fields that are unique to PBSMMSeason\n \"\"\"\n ordinal = models.PositiveIntegerField(_('Ordinal'), null=True, blank=True)\n\n # This is the parental Show\n show_api_id = models.UUIDField(\n _('Show Object ID'),\n null=True,\n blank=True # does this work?\n )\n show = models.ForeignKey(\n 'show.PBSMMShow',\n related_name='seasons',\n on_delete=models.CASCADE, # required for Django 2.0\n null=True,\n blank=True # added for AR5 support\n )\n\n # This triggers cascading ingestion of child Episodes - set from the admin\n # before a save()\n ingest_episodes = models.BooleanField(\n _('Ingest Episodes'),\n default=False,\n help_text='Also ingest all Episodes (for each Season)'\n )\n\n class Meta:\n verbose_name = 'PBS MM Season'\n verbose_name_plural = 'PBS MM Seasons'\n # app_label = 'pbsmmapi'\n db_table = 'pbsmm_season'\n ordering = ['-ordinal']\n\n def get_absolute_url(self):\n \"\"\"\n This enables the \"Show on Site\" link on the Admin page\n \"\"\"\n return reverse('season-detail', (), {'pk': self.pk})\n\n def create_table_line(self):\n this_title = \"Season %d: %s\" % (self.ordinal, self.title)\n out = \"\"\n out += \"%s\" % (\n self.id, this_title\n )\n out += \"API\" % self.api_endpoint\n out += \"\\n\\t%d\" % self.assets.count()\n out += \"\\n\\t%s\" % self.date_last_api_update.strftime(\"%x %X\")\n out += \"\\n\\t%s\" % self.last_api_status_color()\n out += \"%s\" % self.show_publish_status()\n return mark_safe(out)\n\n def __unicode__(self):\n return \"%s | %d | %s \" % (self.object_id, self.ordinal, self.title)\n\n def __str__(self):\n return \"%s | %d | %s \" % (self.object_id, self.ordinal, self.title)\n\n def __object_model_type(self):\n \"\"\"\n This return the object type.\n \"\"\"\n # This handles the correspondence to the \"type\" field in the PBSMM JSON\n # object\n return 'season'\n\n object_model_type = property(__object_model_type)\n\n def __printable_title(self):\n \"\"\"\n This creates a human friendly title out of the Season metadata\n if an explicit title is not set from the Show title and Episode ordinal.\n \"\"\"\n if self.show:\n return '%s Season %d' % (self.show.title, self.ordinal)\n return 'Season %d' % self.ordinal\n\n printable_title = property(__printable_title)\n\n\nclass PBSMMSeasonAsset(PBSMMAbstractAsset):\n season = models.ForeignKey(\n PBSMMSeason,\n related_name='assets',\n on_delete=models.CASCADE, # required for Django 2.0\n )\n\n class Meta:\n verbose_name = 'PBS MM Season Asset'\n verbose_name_plural = 'PBS MM Seasons - Assets'\n db_table = 'pbsmm_season_asset'\n\n def __unicode__(self):\n return \"%s: %s\" % (self.season.title, self.title)\n\n\ndef process_season_assets(endpoint, this_season):\n \"\"\"\n For each Asset associated with this Season, ingest them page by page.\n \"\"\"\n keep_going = True\n scraped_object_ids = []\n while keep_going:\n (status, json) = get_PBSMM_record(endpoint)\n asset_list = json['data']\n\n for item in asset_list:\n object_id = item.get('id')\n scraped_object_ids.append(UUID(object_id))\n\n try:\n instance = PBSMMSeasonAsset.objects.get(object_id=object_id)\n except PBSMMSeasonAsset.DoesNotExist:\n instance = PBSMMSeasonAsset()\n\n instance = process_asset_record(item, instance, origin='special')\n instance.season = this_season\n\n # For now - borrow from the parent object\n instance.last_api_status = status\n instance.date_last_api_update = time_zone_aware_now()\n\n instance.ingest_on_save = True\n\n # This needs to be here because otherwise it never updates...\n instance.save()\n\n (keep_going, endpoint) = check_pagination(json)\n\n for asset in PBSMMSeasonAsset.objects.filter(season=this_season):\n if asset.object_id not in scraped_object_ids:\n asset.delete()\n\n\n################################\n# PBS MediaManager API interface\n################################\n\n# The interface/access is done with a 'pre_save' receiver based on the value of 'ingest_on_save'\n\n# That way, one can force a reingestion from the Admin OR one can do it from a management script\n# by simply getting the record, setting ingest_on_save on the record, and calling save().\n\n\n@receiver(models.signals.pre_save, sender=PBSMMSeason)\ndef scrape_PBSMMAPI(sender, instance, **kwargs):\n \"\"\"\n Get a Season's data from the PBS MM API. Either update or create a PBSMMSeason record.\n \"\"\"\n if instance.__class__ is not PBSMMSeason:\n return\n\n # If this is a new record, then someone has started it in the Admin using EITHER a legacy COVE ID\n # OR a PBSMM UUID. Depending on which, the retrieval endpoint is slightly different, so this sets\n # the appropriate URL to access.\n if instance.pk and instance.object_id and str(instance.object_id).strip():\n # Object is being edited\n if not instance.ingest_on_save:\n return # do nothing - can't get an ID to look up!\n\n else: # object is being added\n if not instance.object_id:\n return # do nothing - can't get an ID to look up!\n\n url = \"{}{}/\".format(PBSMM_SEASON_ENDPOINT, instance.object_id)\n\n # OK - get the record from the API\n (status, json) = get_PBSMM_record(url)\n\n instance.last_api_status = status\n # Update this record's time stamp (the API has its own)\n instance.date_last_api_update = time_zone_aware_now()\n\n # If we didn't get a record, abort (there's no sense crying over spilled\n # bits)\n if status != 200:\n return\n\n # Process the record (code is in ingest.py)\n instance = process_season_record(json, instance)\n\n # continue saving, but turn off the ingest_on_save flag\n instance.ingest_on_save = False # otherwise we could end up in an infinite loop!\n\n # We're done here - continue with the save() operation\n return\n\n\n@receiver(models.signals.post_save, sender=PBSMMSeason)\ndef handle_children(sender, instance, *args, **kwargs):\n \"\"\"\n If the ingest_episodes flag is set, then also ingest every episode for this Season.\n\n Also, always ingest the Assets associated with this Season.\n\n \"\"\"\n if instance.ingest_episodes:\n # This is the FIRST endpoint - there might be more, depending on\n # pagination!\n episodes_endpoint = instance.json['links'].get('episodes')\n\n if episodes_endpoint:\n process_episodes(episodes_endpoint, instance)\n\n # ALWAYS GET CHILD ASSETS\n assets_endpoint = instance.json['links'].get('assets')\n if assets_endpoint:\n process_season_assets(assets_endpoint, instance)\n\n # This is a tricky way to unset ingest_seasons without calling save()\n rec = PBSMMSeason.objects.filter(pk=instance.id)\n rec.update(ingest_episodes=False)\n","sub_path":"pbsmmapi/season/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"467299522","text":"from pathlib import Path\nfrom google.cloud import vision\n\np = Path(__file__).parent / 'load-sign.jpg'\n\nclient = vision.ImageAnnotatorClient()\n\nwith p.open('rb') as image_file:\n content = image_file.read()\n\nimage = vision.types.Image(content=content)\n\nresponse = client.text_detection(image=image)\n\nfor text in response.text_annotations:\n print(text.description)","sub_path":"visonapi/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"134593487","text":"# -*- coding: utf-8 -*-\n# pragma pylint: disable=unused-argument, no-self-use\n# (c) Copyright IBM Corp. 2010, 2020. All Rights Reserved.\n\"\"\"Function implementation\"\"\"\n\nimport logging\nfrom fn_mcafee_epo.lib.epo_helper import init_client\nfrom resilient_lib import ResultPayload, validate_fields\nfrom resilient_circuits import ResilientComponent, function, handler, StatusMessage, FunctionResult, FunctionError\n\nPACKAGE_NAME = \"fn_mcafee_epo\"\n\n\nclass FunctionComponent(ResilientComponent):\n \"\"\"Component that implements Resilient function 'mcafee_epo_find_a_system''\"\"\"\n\n def __init__(self, opts):\n \"\"\"constructor provides access to the configuration options\"\"\"\n super(FunctionComponent, self).__init__(opts)\n self.opts = opts\n self.options = opts.get(PACKAGE_NAME, {})\n\n @handler(\"reload\")\n def _reload(self, event, opts):\n \"\"\"Configuration options have changed, save new values\"\"\"\n self.opts = opts\n self.options = opts.get(PACKAGE_NAME, {})\n\n @function(\"mcafee_epo_find_a_system\")\n def _mcafee_epo_find_a_system_function(self, event, *args, **kwargs):\n \"\"\"Function: Find an ePO system based on property such as system name, tag, IP address, MAC address, etc.\"\"\"\n try:\n # Get the function parameters:\n validate_fields([\"mcafee_epo_systems\"], kwargs)\n mcafee_epo_systems = kwargs.get(\"mcafee_epo_systems\") # text\n client = init_client(self.opts, self.options)\n\n log = logging.getLogger(__name__)\n log.info(\"mcafee_epo_systems: %s\", mcafee_epo_systems)\n\n yield StatusMessage(\"Starting\")\n\n rc = ResultPayload(PACKAGE_NAME, **kwargs)\n\n params = {\"searchText\": mcafee_epo_systems.strip()}\n response = client.request(\"system.find\", params)\n\n yield StatusMessage(\"Finished\")\n\n results = rc.done(True, response)\n\n # Produce a FunctionResult with the results\n yield FunctionResult(results)\n except Exception:\n yield FunctionError()\n","sub_path":"fn_mcafee_epo/fn_mcafee_epo/components/funct_mcafee_epo_find_a_system.py","file_name":"funct_mcafee_epo_find_a_system.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"480798529","text":"#from os import makedirs\nfrom os import listdir\nfrom os.path import isfile, isdir, join, exists\nimport json\ndef calcavg(path, params):\n\tfiles = [f for f in listdir(path) if isfile(join(path, f))]\n\t#print(files)\n\tar = []\n\tti = []\n\ttrain_start = ''\n\tfor i in range(0, len(files)):\n\t\t#print(files[i])\n\t\tfullname = '%s/%s' %(path, files[i])\n\t\t#print(fullname)\n\t\twith open(fullname) as json_file:\n\t\t\tdata = json.load(json_file)\n\t\t\ttw = data.get('train_start')\n\t\t\tif i < 1:\n\t\t\t\ttrain_start = tw\n\t\t\t\t#print(tw)\n\t\t\tresults = data.get('results')\n\t\t\trmses = []\n\t\t\t#times = []\n\t\t\ttimes = data.get('time')\n\t\t\tmodel = data.get('model')\n\t\t\titis = ''\n\t\t\tfor n in range(0, len(params)):\n\t\t\t\tparam = params[n]\n\t\t\t\tpv = model.get(param)\n\t\t\t\titis += param+'='+str(pv)+','\n\t\t\tfor obj in results:\n\t\t\t\taccuracy = obj.get('accuracy')\n\t\t\t\t#time = obj.get('time')\n\t\t\t\trmse = float(accuracy.get('rmse')) \n\t\t\t\t#print('time=%f' % time)\n\t\t\t\t#times.append(time)\n\t\t\t\t#print(rmse)\n\t\t\t\trmses.append(rmse)\n\t\t\t\t#eacc = obj.get('each_sample_accuracy')\n\t\t\t\t#print(eacc)\n\t\t\t\t#print('detail:tw=%s, rmse=%f,times=%f' % (tw, rmse, times))\n\t\t#alltimes = round(sum(times)/len(times), 3)\n\t\tallrmse = round(sum(rmses)/len(rmses), 3)\n\t\t\n\t\t#print('allrmse=%d' % allrmse)\n\t\tar.append(allrmse)\n\t\tti.append(times)\n\t\tprint('=%s:tw=%s, allrmse=%f, times=%f' % (fullname, tw, allrmse, times))\n\t#print(ar)\n\tavgrmse = round(sum(ar)/len(ar), 3)\n\tavgtime = round(sum(ti)/len(ti), 3)\n\t#print('train_window=%d, avgrmse=%f' % (train_window, avgrmse))\t\n\tprint('calcavg:avgrmse=%f, train_start=%s, avgtime=%f, itis=%s' % (avgrmse, train_start, avgtime, itis))\n\treturn avgrmse, train_start, avgtime, itis \n\ndef calcall(pathes, params):\n\tprint('pathes=', pathes)\n\tavgrmses = []\n\ttrain_starts = []\n\tfits = []\n\tits = []\n\n\tfor path in pathes: \n\t\tavgrmse, train_start, avgtime, itis = calcavg(path, params)\n\t\tprint('>%s:train_start=%s, avgrmse=%f, avgtime=%f, itis=%s' % (path, train_start, avgrmse, avgtime, itis))\t\n\t\tprint('>======================================================')\n\t\tavgrmses.append(avgrmse)\n\t\ttrain_starts.append(train_start)\n\t\tfits.append(avgtime)\n\t\tits.append(itis)\n\tminrmse = min(avgrmses)\n\tj = 0\n\tfor j in range(0, len(avgrmses)):\n\t\tif minrmse == avgrmses[j]:\n\t\t\tbreak\n\tbest_train_start = train_starts[j]\n\tfit = fits[j]\n\tasis = its[j]\n\tprint('callall:best_train_start=%s, minrmse=%f, fit=%f, asis=%s' % (best_train_start, minrmse, fit, asis))\n\treturn minrmse, best_train_start, fit, asis\n#pathes = ['./_lstm/0', './_lstm/1000']#\t, './_lstm/2000'\t, './_lstm/3000'\t, './_lstm/4000'\t, './_lstm/5000'\t, './_lstm/6000'\t, './_lstm/7000'\t, './_lstm/8000'\n\ndef finddirs(path):\n\talldirs = []\n\tfor k in range(0, len(path)):\n\t\tdirs = [f for f in listdir(path[k]) if isdir(join(path[k], f))]\n\t\tfor n in range(0, len(dirs)):\n\t\t\talldirs.append(path[k]+'/'+dirs[n])\n\treturn alldirs\n#params = ['epochs', 'patience_coef']\n#params = ['dropout', 'recurrent_dropout']\n#params = ['validation_size']\n#params = ['n_steps_in']\n#params = ['batch_size', 'is_stateful']\n#params = ['units_coef']\nparams = ['train_window']\npath = ['_simple/twless']\ndirs1 = finddirs(path)\nprint(dirs1)\navgrmse, train_start, avgtime, itis = calcall(dirs1, params)\n#dirs2 = finddirs(dirs1)\n#print(dirs2)\n#avgrmse, train_start, avgtime, itis = calcall(dirs2, params)\n#print('result:train_start=%s, avgrmse=%f, avgtime=%f, itis=%s' % (train_start, avgrmse, avgtime, itis))\t\n\t","sub_path":"results/analizLSTM.py","file_name":"analizLSTM.py","file_ext":"py","file_size_in_byte":3381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"639752749","text":"\"\"\"\n情感分析实例:IMDB 影评情感分析\n\"\"\"\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nfrom keras.datasets import imdb\nimport numpy as np\nfrom keras.preprocessing import sequence\nfrom keras.layers.embeddings import Embedding\nfrom keras.layers import Dense, Flatten\nfrom keras.models import Sequential\n\nseed =7\ntop_words = 5000\nmax_words = 500\nout_dimension = 32\nbatch_size = 128\nepochs = 2\n\ndef create_model():\n model = Sequential()\n #构建嵌入层\n model.add(Embedding(\n top_words, out_dimension, input_length=max_words\n )\n )\n model.add(\n Flatten()\n )\n model.add(Dense(250, activation='relu'))\n model.add(Dense(1,activation='sigmoid'))\n model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n model.summary()\n return model\nnp.random.seed(seed)\n# 导入数据\n(x_train, y_train), (x_validation, y_validation) = imdb.load_data(num_words=top_words)\n# 限定数据集的长度\nx_train = sequence.pad_sequences(x_train, maxlen=max_words)\nx_validation = sequence.pad_sequences(x_validation, maxlen=max_words)\nmodel = create_model()\nmodel.fit(x_train,y_train,validation_data=(x_validation, y_validation), batch_size = batch_size, epochs=epochs, verbose=2)\n","sub_path":"how3/bin6.py","file_name":"bin6.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"289827869","text":"from pyspark import SparkContext\nfrom ml_utils import *\nimport argparse\n#test\n#test1\n#test2\n\nif __name__ == \"__main__\":\n sc = SparkContext(appName=\"Top10Disklike\") #define the app name \n parser = argparse.ArgumentParser() #define the things in command lines\n parser.add_argument(\"--input\", help=\"the input path\")\n parser.add_argument(\"--output\", help=\"the output path\")\n args = parser.parse_args()\n input_path = args.input\n output_path = args.output\n\n Original = sc.textFile(\"AllVideos_short.csv\") #define the input file \n filtedInfo = Original.map(filteringnDate).sortByKey() #filter the useful things out \n integrated = filtedInfo.map(countnDeleteDate) #do some count insides the record\n records = integrated.groupByKey().map(lambda x : (x[0], list(x[1]))) #get the Keys togethere\n result = records.map(countTwo).filter(lambda x : isinstance(x, tuple)) #get first two days out and do some counting\n result= result.map(changeKey).sortByKey(0).top(10) #sort the records by the value of dislike growth\n sc.parallelize(result).map(formatTrans).saveAsTextFile(output_path) #trans the format into required format\n \n","sub_path":"Top10Dislike.py","file_name":"Top10Dislike.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"126613045","text":"def reverseWords(s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n ans = []\n for i in s.split(\" \"):\n ans.append(i[::-1])\n\n return (\" \").join(ans)\n\n\nsentence_str = \"Let's take LeetCode contest\"\nres = reverseWords(sentence_str)\nprint(res)\n","sub_path":"data_structures/string_reverseWords.py","file_name":"string_reverseWords.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"144270376","text":"# 264. Ugly Number II\n\nclass Solution(object):\n def nthUglyNumber(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n def isUgly(num):\n while num>1:\n if num%2==0:\n num=num//2\n elif num%3==0:\n num=num//3\n elif num%5==0:\n num=num//5\n else:\n break\n if num==1:\n return True\n return False\n num,count_n=0,0\n while 1:\n num+=1\n u_num=isUgly(num)\n if u_num==True:\n count_n+=1\n if count_n==n:\n return num\n\nclass Solution(object):\n n_l=sorted(2**a * 3**b * 5**c for a in range(35) for b in range(25) for c in range(20))\n def nthUglyNumber(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n return self.n_l[n-1]\n ","sub_path":"Qs/264_ Ugly Number II.py","file_name":"264_ Ugly Number II.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"494457183","text":"# pylint:disable=missing-docstring,super-init-not-called\n\n__author__ = 'Chintan Shah'\n\nfrom scrapy import Spider\nfrom spiders.others.epa.items import EPAItem\nfrom helpers.string_processor import process_string\nfrom dateutil import parser\nfrom urlparse import urljoin\n\nclass EPABulletinSpider(Spider):\n\n name = \"epabulletin\"\n allowed_domains = [\"epa.gov\"]\n start_urls = (\n \"http://www.epa.gov/airtransport/CSAPR/bulletins.html\",\n )\n\n def __init__(self):\n self.duplicatecount = 0\n\n def parse(self, response):\n elements = response.css(\"div#main > p\")\n for each_elem in elements:\n item = EPAItem()\n # remove the strong element and extract only title\n title = each_elem.css(\":not(strong)::text\").extract()\n publishdate = each_elem.css(\"strong ::text\").extract()\n if '-' in title[0]:\n title[0] = title[0].lstrip().replace('-', '')\n item['title'] = process_string(''.join(title))\n item['publishdate'] = parser.parse(publishdate[0], fuzzy=True)\n links = each_elem.css(\"a::attr(href)\").extract()\n item['url'] = \"#\"\n if links:\n item['url'] = urljoin(response.url, links[0])\n item['type'] = 'CSAPR'\n yield item\n","sub_path":"spiders/others/epa/EPABulletinSpider.py","file_name":"EPABulletinSpider.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"459955353","text":"import sys\ninp = raw_input('What family would you like to analyze?\\n')\ninp2 = '/Volumes/group_dv/personal/DValenzano/Jan2014/F1_inference/Go_families/inf-fam_%s.csv' % inp\nfam = open(inp2, 'rU').read()\nfams = fam.split('\\n')[:-1]\nfams2 = [','.join(i.split(',')[:5]) +','+ i.split(',')[8]+','+','.join(i.split(',')[10:]) for i in fams[1:]]\ndef blast(input):\n ls = []\n for i in input.split(',')[6:]:\n if len(i)== 2:\n ls.append(i[0]+','+i[1])\n else:\n ls.append(i+','+i)\n return ','.join(ls)+'\\n'\npedfam = ','.join([ ','.join(i.split(',')[:6])+','+blast(i) for i in fams2 ]).replace('\\n,','\\n').replace(',','\\t')\nout0 = '/Volumes/group_dv/personal/DValenzano/Mar2014/plink/fam_%s/inf-fam_%s_w.ped' % (inp, inp)\nz = open(out0,'w')\nz.write(pedfam)\nz.close()\n","sub_path":"fam-to-plink_w.py","file_name":"fam-to-plink_w.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"93925439","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCopyright 2014 Brno University of Technology\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# Příklad načtení:\n'''\nfrom KB_shm import *\n'''\n\nimport os\nimport sys\nfrom ctypes import CDLL, c_char, c_char_p, c_int, c_uint, c_void_p, POINTER, byref\n\n# Získání absolutní cesty k adresáři ve kterém je tento soubor.\nscript_dir = os.path.dirname(os.path.abspath(__file__))\n# Načtení dynamické knihovny \"libKB_shm.so\"\nlibKB_shm_path = os.path.join(script_dir, \"libKB_shm.so\")\nif not os.path.isfile(libKB_shm_path):\n\tsys.exit(\"Could not found \" + libKB_shm_path)\nlibKB_shm = CDLL( libKB_shm_path )\n\n# Pro jazyky C/C++\n'''\nKB_shm_p = c_void_p(0)\nKB_shm_fd = c_int(-1)\nstatus = c_int(0)\n\nstatus = c_int( connectKBSharedMem( byref(KB_shm_p), byref(KB_shm_fd) ) )\nif status.value != 0:\n\tprint(\"ERROR\")\n\texit(1)\n\n. . .\n\nstatus = c_int( disconnectKBSharedMem( byref(KB_shm_p), byref(KB_shm_fd) ) )\nif status.value != 0:\n\tprint(\"ERROR\")\n\texit(1)\n\nexit(0)\n'''\nconnectKBSharedMem = libKB_shm.connectKBSharedMem\nconnectKBSharedMem.argtypes = [POINTER(c_void_p), POINTER(c_int)]\nconnectKBSharedMem.restype = c_int\n\ndisconnectKBSharedMem = libKB_shm.disconnectKBSharedMem\ndisconnectKBSharedMem.argtypes = [POINTER(c_void_p), POINTER(c_int)]\ndisconnectKBSharedMem.restype = c_int\n\n# Pro jazyky Java, Python, ...\n'''\nKB_shm_p = c_void_p(0)\nKB_shm_fd = c_int(-1)\nstatus = c_int(0)\n\nKB_shm_fd = c_int( connectKB_shm() )\nif KB_shm_fd.value < 0:\n\tprint(\"ERROR\")\n\texit(1)\n\nKB_shm_p = c_void_p( mmapKB_shm(KB_shm_fd) )\nif KB_shm_p.value == None:\n\tprint(\"ERROR\")\n\tdisconnectKB_shm(KB_shm_p, KB_shm_fd)\n\texit(1)\n\n. . .\n\nstatus = c_int( disconnectKB_shm(KB_shm_p, KB_shm_fd) )\nif status.value != 0:\n\tprint(\"ERROR\")\n\texit(1)\n\nKB_shm_p = c_void_p(0)\nKB_shm_fd = c_int(-1)\nexit(0)\n'''\nconnectKB_shm = libKB_shm.connectKB_shm\nconnectKB_shm.argtypes = []\nconnectKB_shm.restype = c_int\n\nmmapKB_shm = libKB_shm.mmapKB_shm\nmmapKB_shm.argtypes = [c_int]\nmmapKB_shm.restype = c_void_p\n\ndisconnectKB_shm = libKB_shm.disconnectKB_shm\ndisconnectKB_shm.argtypes = [c_void_p, c_int]\ndisconnectKB_shm.restype = c_int\n\n# Funkce pro získání řetězců\n'''\nKBSharedMemDataAt( KB_shm_p, 1, 1 )\nc_char_p( KBSharedMemDataAt( KB_shm_p, 1, 1 ) )\nprint( c_char_p( KBSharedMemDataAt( KB_shm_p, 1, 1 ) ).value )\n\nprint( c_char_p( KBSharedMemHeadFor( KB_shm_p, 'p', 1 ) ).value )\nprint( c_char_p( KBSharedMemHeadFor_Boost( KB_shm_p, 'p', 1, byref(line) ) ).value )\n'''\nKBSharedMemHeadAt = libKB_shm.KBSharedMemHeadAt\nKBSharedMemHeadAt.argtypes = [c_void_p, c_uint, c_uint]\nKBSharedMemHeadAt.restype = c_void_p\n\nKBSharedMemHeadFor = libKB_shm.KBSharedMemHeadFor\nKBSharedMemHeadFor.argtypes = [c_void_p, c_char, c_uint]\nKBSharedMemHeadFor.restype = c_void_p\n\nKBSharedMemHeadFor_Boost = libKB_shm.KBSharedMemHeadFor_Boost\nKBSharedMemHeadFor_Boost.argtypes = [c_void_p, c_char, c_uint, POINTER(c_uint)]\nKBSharedMemHeadFor_Boost.restype = c_void_p\n\nKBSharedMemDataAt = libKB_shm.KBSharedMemDataAt\nKBSharedMemDataAt.argtypes = [c_void_p, c_uint, c_uint]\nKBSharedMemDataAt.restype = c_void_p\n\nKBSharedMemTableRowLength = libKB_shm.KBSharedMemTableRowLength\nKBSharedMemTableRowLength.argtypes = [c_void_p, c_uint]\nKBSharedMemTableRowLength.restype = c_void_p\n\nKBSharedMemTableRowColon = libKB_shm.KBSharedMemTableRowColon\nKBSharedMemTableRowColon.argtypes = [c_void_p, c_uint, c_uint]\nKBSharedMemTableRowColon.restype = c_void_p\n\n# Příklad použití:\n'''\nKB_shm_p = c_void_p(0)\nKB_shm_fd = c_int(-1)\nstatus = c_int(0)\n\nKB_shm_fd = c_int( connectKB_shm() )\nif KB_shm_fd.value < 0:\n\tprint(\"ERROR\")\n\texit(1)\n\nKB_shm_p = c_void_p( mmapKB_shm(KB_shm_fd) )\nif KB_shm_p.value == None:\n\tprint(\"ERROR\")\n\tdisconnectKB_shm(KB_shm_p, KB_shm_fd)\n\texit(1)\n\n#. . .#\n\nraw_input(\"hit enter...\")\n\nstr = c_char_p( KBSharedMemHeadAt( KB_shm_p, 1, 1 ) ).value\ni = 1\nwhile str != None:\n\tj = 1\n\twhile str != None:\n\t\tprint(str)\n\t\tj += 1\n\t\tstr = c_char_p( KBSharedMemHeadAt( KB_shm_p, i, j ) ).value\n\ti += 1\n\tstr = c_char_p( KBSharedMemHeadAt( KB_shm_p, i, 1 ) ).value\n\nraw_input(\"hit enter...\")\n\nj = 1\nstr = c_char_p( KBSharedMemHeadFor( KB_shm_p, 'p', j ) ).value\nwhile str != None:\n\tprint(str)\n\tj += 1\n\tstr = c_char_p( KBSharedMemHeadFor( KB_shm_p, 'p', j ) ).value\n\nraw_input(\"hit enter...\")\n\nstr = c_char_p( KBSharedMemDataAt( KB_shm_p, 1, 1 ) ).value\ni = 1\nwhile str != None:\n\tj = 1\n\twhile str != None:\n\t\tprint(str)\n\t\tj += 1\n\t\tstr = c_char_p( KBSharedMemDataAt( KB_shm_p, i, j ) ).value\n\ti += 1\n\tstr = c_char_p( KBSharedMemDataAt( KB_shm_p, i, 1 ) ).value\n\nraw_input(\"hit enter...\")\n\n#. . .#\n\nstatus = c_int( disconnectKB_shm(KB_shm_p, KB_shm_fd) )\nif status.value != 0:\n\tprint(\"ERROR\")\n\texit(1)\n\nKB_shm_p = c_void_p(0)\nKB_shm_fd = c_int(-1)\nexit(0)\n'''\n\nclass KB_shm:\n\t'''\n\tTřída zastřešující KB_shm.\n\t'''\n\tdef __init__(self):\n\t\t'''\n\t\tInicializace.\n\t\t'''\n\t\tself.KB_shm_p = c_void_p(0)\n\t\tself.KB_shm_fd = c_int(-1)\n\t\tself.headFor_Boost = {}\n\t\n\tdef start(self):\n\t\t'''\n\t\tPřipojí sdílenou paměť.\n\t\t'''\n\t\tself.KB_shm_fd = c_int( connectKB_shm() )\n\t\tif self.KB_shm_fd.value < 0:\n\t\t\tRuntimeError(\"connectKB_shm\")\n\t\t\n\t\tself.KB_shm_p = c_void_p( mmapKB_shm(self.KB_shm_fd) )\n\t\tif self.KB_shm_p.value == None:\n\t\t\tdisconnectKB_shm(self.KB_shm_p, self.KB_shm_fd)\n\t\t\tRuntimeError(\"mmapKB_shm\")\n\t\n\tdef end(self):\n\t\t'''\n\t\tOdpojí sdílenou paměť.\n\t\t'''\n\t\tstatus = c_int(0)\n\t\tstatus = c_int( disconnectKB_shm(self.KB_shm_p, self.KB_shm_fd) )\n\t\tif status.value != 0:\n\t\t\tRuntimeError(\"disconnectKB_shm\")\n\t\t\n\t\tself.__init__()\n\t\n\tdef headAt(self, line, col):\n\t\treturn c_char_p( KBSharedMemHeadAt( self.KB_shm_p, line, col ) ).value\n\t\n\tdef headFor(self, prefix, col):\n\t\tif self.headFor_Boost.has_key(prefix):\n\t\t\tresult = c_char_p( KBSharedMemHeadAt( self.KB_shm_p, self.headFor_Boost[prefix], col ) ).value\n\t\telse:\n\t\t\tline = c_uint(0)\n\t\t\tresult = c_char_p( KBSharedMemHeadFor_Boost( self.KB_shm_p, prefix, col, byref(line) ) ).value\n\t\t\tself.headFor_Boost[prefix] = line\n\t\treturn result\n\t\n\tdef dataAt(self, line, col):\n\t\treturn c_char_p( KBSharedMemDataAt( self.KB_shm_p, line, col ) ).value\n\t\n\tdef getTableRowLength(self, row):\n\t\taddress = c_void_p( KBSharedMemTableRowLength(self.KB_shm_p, row) )\n\t\tif address.value == None:\n\t\t\treturn None\n\t\telse:\n\t\t\treturn c_uint.from_address( address.value ).value\n\t\n\tdef getKBRowFromTableRow(self, row, n):\n\t\taddress = c_void_p( KBSharedMemTableRowColon(self.KB_shm_p, row, n) )\n\t\tif address.value == None:\n\t\t\treturn None\n\t\telse:\n\t\t\treturn c_uint.from_address( address.value ).value\n\t\n#\n\n# konec souboru KB_shm.py\n","sub_path":"SharedKB/var3/KB_shm.py","file_name":"KB_shm.py","file_ext":"py","file_size_in_byte":6987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"439003476","text":"from typing import NamedTuple, Dict, Any\n\nimport pygame as pg\nfrom pygame.math import Vector2, Vector3\n\nimport conditions\nimport effects\nimport settings\nfrom conditions import Condition, condition_from_data\nfrom creatures.humanoids import Humanoid\nfrom creatures.players import Player\nfrom data.input_output import load_mod_data_kwargs\nfrom effects import Effects, Effect\nfrom mods import Mod, ModData\nfrom view import images\n\nAVOID_RADIUS = 50\nDETECT_RADIUS = 400\n\nBehaviorData = Dict[str, Any]\n\n\nclass BaseEnemyData(NamedTuple):\n max_speed: int\n max_health: int\n hit_rect: pg.Rect\n image_file: str\n damage: int\n knockback: int\n behavior_dict: BehaviorData\n\n\nclass EnemyData(BaseEnemyData):\n def __new__(cls, max_speed: float, max_health: int, hit_rect_width: int,\n hit_rect_height: int, image_file: str, damage: int,\n behavior: BehaviorData, knockback: int = 0) -> BaseEnemyData:\n hit_rect = pg.Rect(0, 0, hit_rect_width, hit_rect_height)\n\n return super().__new__(cls, # type:ignore\n max_speed, max_health, hit_rect, image_file,\n damage, knockback, behavior)\n\n def replace(self, **kwargs: Any) -> BaseEnemyData:\n \"\"\"Make a new EnemyData with specific parameters replaced.\n\n key word arguments must match BaseEnemyData.\n \"\"\"\n new_kwargs = self._asdict()\n for k, v in kwargs.items():\n new_kwargs[k] = v\n return super().__new__(EnemyData, **new_kwargs)\n\n\nclass Behavior(object):\n \"\"\"Represents the possible behavior of an Enemy.\n\n Behavior is state based. Behavior has a default_state, as well as other\n states (defined by string keys). Each state is assigned conditions (used in\n determine_state) and effects (used in do_state_behavior). The effects\n themselves are also assigned conditions, so that they only occur when\n their conditions are met.\n\n \"\"\"\n\n def __init__(self, behavior_dict: BehaviorData, player: Humanoid) -> None:\n\n self.default_state: Condition = None\n self._state_conditions_values: Dict[str, Dict[Condition, int]] = {}\n self._state_effects_conditions: Dict[str, Dict[Effect, Any]] = {}\n\n self._set_state_condition_values(behavior_dict, player)\n self._set_state_effects_conditions(behavior_dict, player)\n\n def determine_state(self, humanoid: Humanoid) -> str:\n\n current_state = self.default_state\n highest_priority = 0\n\n for state, state_conditions in self._state_conditions_values.items():\n priority = 0\n for cond, value in state_conditions.items():\n if cond.check(humanoid):\n priority += value\n if priority > highest_priority:\n highest_priority = priority\n current_state = state\n\n return current_state\n\n def do_state_behavior(self, humanoid: Humanoid) -> None:\n\n state = humanoid.status.state\n for effect, condition in self._state_effects_conditions[state].items():\n if condition.check(humanoid):\n effect.activate(humanoid)\n\n def _set_state_effects_conditions(self, behavior_dict: BehaviorData,\n player: Player) -> None:\n\n for state, state_data in behavior_dict.items():\n effect_datas = state_data['effects']\n state_behavior: Dict[str, Any] = {}\n\n if effect_datas is None:\n self._state_effects_conditions[state] = state_behavior\n continue\n\n for effect_label, effect_data in effect_datas.items():\n effect = self._effect_from_data(effect_data, effect_label,\n player)\n\n if effect_data is not None and 'conditions' in effect_data:\n condition = None\n for cond_data in effect_data['conditions']:\n new_cond = condition_from_data(cond_data, player)\n if condition is None:\n condition = new_cond\n else:\n condition &= new_cond\n else:\n condition = conditions.AlwaysTrue()\n\n state_behavior[effect] = condition\n self._state_effects_conditions[state] = state_behavior\n\n def _set_state_condition_values(self, behavior_dict: BehaviorData,\n player: Player) -> None:\n for state, state_data in behavior_dict.items():\n\n assert 'conditions' in state_data\n\n conditions_list = state_data['conditions']\n if 'default' in conditions_list:\n assert self.default_state is None, 'Cannot have more than ' \\\n 'one default state.'\n self.default_state = state\n else:\n condition_values = {}\n for cond_data in conditions_list:\n condition = condition_from_data(cond_data, player)\n value = self._condition_value_from_data(cond_data)\n condition_values[condition] = value\n self._state_conditions_values[state] = condition_values\n\n def _effect_from_data(self, effect_data: Dict, effect_label: str,\n player: Player) -> Effect:\n effect_label = Effects(effect_label)\n if effect_label == Effects.EQUIP_AND_USE_MOD:\n mod_label = effect_data['mod']\n mod = Mod(ModData(**load_mod_data_kwargs(mod_label)))\n effect = effects.EquipAndUseMod(mod)\n elif effect_label == Effects.RANDOM_SOUND:\n sound_files = effect_data['sound files']\n effect = effects.PlayRandomSound(sound_files)\n elif effect_label == Effects.FACE_AND_PURSUE:\n effect = effects.FaceAndPursueTarget(player)\n elif effect_label == Effects.STOP_MOTION:\n effect = effects.StopMotion()\n elif effect_label == Effects.DROP_ITEM:\n item_label = effect_data['item_label']\n effect = effects.DropItem(item_label)\n elif effect_label == Effects.KILL:\n effect = effects.Kill()\n elif effect_label == Effects.PLAY_SOUND:\n effect = effects.PlaySound(effect_data['sound_file'])\n elif effect_label == Effects.DRAW_ON_MAP:\n image_file = effect_data['image_file']\n angled = 'angled' in effect_data\n effect = effects.DrawOnScreen(image_file, angled)\n elif effect_label == Effects.FACE:\n effect = effects.FaceTarget(player)\n else:\n raise NotImplementedError(\n 'Unrecognized effect label %s' % (effect_label,))\n return effect\n\n @staticmethod\n def _condition_value_from_data(condition_data: Dict) -> int:\n assert len(condition_data.keys()) == 1\n label_str = next(iter(condition_data.keys()))\n return condition_data[label_str]['value']\n\n\nclass Enemy(Humanoid):\n def __init__(self, pos: Vector2, player: Player, data: EnemyData) -> None:\n\n self._data = data\n super().__init__(data.hit_rect, pos, data.max_health)\n\n self.damage = data.damage\n self.knockback = data.knockback\n\n mygroups = [self.groups.all_sprites, self.groups.enemies]\n\n pg.sprite.Sprite.__init__(self, mygroups)\n\n self.behavior = Behavior(data.behavior_dict, player)\n self.status.state = self.behavior.default_state\n\n self.target = player\n\n @property\n def image(self) -> pg.Surface:\n base_image = images.get_image(self._data.image_file)\n image = pg.transform.rotate(base_image, self.motion.rot)\n\n if self.status.damaged:\n self._draw_health_bar(image, base_image.get_width())\n return image\n\n def _draw_health_bar(self, image: pg.Surface, full_width: int) -> None:\n col = self._health_bar_color()\n width = int(full_width * self.status.health / self.status.max_health)\n health_bar = pg.Rect(0, 0, width, 7)\n pg.draw.rect(image, col, health_bar)\n\n def update(self) -> None:\n self.status.state = self.behavior.determine_state(self)\n self.behavior.do_state_behavior(self)\n\n self.motion.update()\n\n def _check_class_initialized(self) -> None:\n if not self.class_initialized:\n raise RuntimeError(\n 'Enemy class must be initialized before an object'\n ' can be instantiated.')\n\n def _avoid_mobs(self) -> None:\n for mob in self.groups.enemies:\n if mob is self:\n continue\n dist = self.pos - mob.pos\n if 0 < dist.length() < AVOID_RADIUS:\n self.motion.acc += dist.normalize()\n\n def update_acc(self) -> None:\n self.motion.acc = Vector2(1, 0).rotate(-self.motion.rot)\n self._avoid_mobs()\n self.motion.acc.scale_to_length(self._data.max_speed)\n self.motion.acc += self.motion.vel * -1\n\n @staticmethod\n def _target_close(target_dist: Vector2) -> bool:\n return target_dist.length() < DETECT_RADIUS\n\n def _health_bar_color(self) -> tuple:\n health_fraction = float(self.status.health) / self.status.max_health\n if health_fraction > 0.5:\n frac = 2 * (1 - health_fraction)\n vec = Vector3(settings.GREEN) * frac\n vec += Vector3(settings.YELLOW) * (1 - frac)\n col = tuple(vec)\n else:\n frac = 2 * health_fraction\n vec = Vector3(settings.YELLOW) * frac\n vec += Vector3(settings.RED) * (1 - frac)\n col = tuple(vec)\n return col\n","sub_path":"src/creatures/enemies.py","file_name":"enemies.py","file_ext":"py","file_size_in_byte":9758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"282919871","text":"\"\"\"Стекинг результатов нескольких моделей.\"\"\"\nimport logging\nimport time\n\nimport catboost\nimport pandas as pd\nimport numpy as np\n\nfrom model import conf\nfrom model import processing\nfrom model.conf import K_FOLDS\nfrom model.conf import SEED\n\nLOGGER = logging.getLogger(__name__)\n\nITERATIONS = 10000\nLEARNING_RATE = 0.04\n\nCLF_PARAMS = dict(\n loss_function=\"MAE\",\n eval_metric=None,\n random_state=SEED,\n depth=6,\n od_type=\"Iter\",\n od_wait=ITERATIONS // 10,\n verbose=ITERATIONS // 100,\n learning_rate=LEARNING_RATE,\n iterations=ITERATIONS,\n allow_writing_files=False,\n)\n\nSOURCE = [\n \"sub_2019-04-29_10-00_1.938_1.974_cat.csv\",\n \"sub_2019-04-29_10-57_1.940_1.974_lgbm.csv\",\n \"sub_2019-04-29_17-42_2.014_2.045_lgbm_rf.csv\",\n \"sub_2019-05-02_17-05_2.043_2.073_ext.csv\"\n]\n\n\nDROP = [\n \"oof_ext\", \"range\", \"mean\", \"max\", \"std\"\n]\n\n\ndef load_oof():\n \"\"\"Загрузка OOF предсказаний в единый фрейм.\"\"\"\n data = []\n for name in SOURCE:\n df = pd.read_csv(conf.DATA_PROCESSED + \"oof\" + name[3:], header=0, index_col=0)\n data.append(df)\n data = pd.concat(data, axis=1)\n return data\n\n\ndef load_sub():\n \"\"\"Загрузка тестовых предсказаний в единый фрейм.\"\"\"\n data = []\n for name in SOURCE:\n df = pd.read_csv(conf.DATA_PROCESSED + name, header=0, index_col=0)\n data.append(df)\n data = pd.concat(data, axis=1)\n return data\n\n\ndef add_stacking_feat(df):\n \"\"\"Формирование дополнительных признаков для стекинга.\"\"\"\n n_base_feat = df.shape[1]\n df[\"min\"] = df.iloc[:, :n_base_feat].min(axis=1)\n df[\"max\"] = df.iloc[:, :n_base_feat].max(axis=1)\n df[\"mean\"] = df.iloc[:, :n_base_feat].mean(axis=1)\n df[\"median\"] = df.iloc[:, :n_base_feat].median(axis=1)\n df[\"std\"] = df.iloc[:, :n_base_feat].std(axis=1)\n df[\"range\"] = df[\"max\"] - df[\"min\"]\n\n return df\n\n\ndef stack_catboost():\n \"\"\"Стекинг catboost.\"\"\"\n x_train = add_stacking_feat(load_oof())\n _, y_train = processing.train_set()\n x_test = add_stacking_feat(load_sub())\n x_test.columns = x_train.columns\n\n x_train.drop(DROP, axis=1, inplace=True)\n x_test.drop(DROP, axis=1, inplace=True)\n\n pool_test = catboost.Pool(\n data=x_test,\n label=None,\n cat_features=None,\n weight=None\n )\n y_oof = pd.Series(0, index=x_train.index, name=\"oof_y\")\n y_pred = pd.Series(0, index=x_test.index, name=\"time_to_failure\")\n trees = []\n scores = []\n feat_importance = 0\n\n for index_train, index_valid in K_FOLDS.split(x_train):\n pool_train = catboost.Pool(\n data=x_train.iloc[index_train],\n label=y_train.iloc[index_train],\n cat_features=None,\n weight=None\n )\n pool_valid = catboost.Pool(\n data=x_train.iloc[index_valid],\n label=y_train.iloc[index_valid],\n cat_features=None,\n weight=None\n )\n clf = catboost.CatBoostRegressor(**CLF_PARAMS)\n clf.fit(\n X=pool_train,\n eval_set=[pool_valid],\n )\n trees.append(clf.tree_count_)\n scores.append(clf.best_score_['validation_0']['MAE'])\n y_oof.iloc[index_valid] = clf.predict(pool_valid)\n y_pred += clf.predict(pool_test) / K_FOLDS.get_n_splits()\n feat_importance += pd.DataFrame(\n clf.get_feature_importance(prettified=True),\n columns=[\"name\", \"value\"]\n ).set_index(\"name\") / K_FOLDS.get_n_splits()\n\n LOGGER.info(f\"Количество деревьев: {sorted(trees)}\")\n LOGGER.info(f\"Среднее количество деревьев: {np.mean(trees):.0f} +/- {np.std(trees):.0f}\")\n LOGGER.info(f\"MAE на кроссвалидации: \" + str(np.round(sorted(scores), 5)))\n LOGGER.info(f\"MAE среднее: {np.mean(scores):0.3f} +/- {np.std(scores):0.3f}\")\n\n stamp = (\n f\"{time.strftime('%Y-%m-%d_%H-%M')}_\"\n f\"{np.mean(scores):0.3f}_\"\n f\"{np.mean(scores) + np.std(scores) * 2 / len(scores) ** 0.5:0.3f}_stk\")\n y_oof.to_csv(conf.DATA_PROCESSED + f\"oof_{stamp}.csv\", header=True)\n y_pred.to_csv(conf.DATA_PROCESSED + f\"sub_{stamp}.csv\", header=True)\n print(feat_importance.sort_values(\"value\", ascending=False))\n\n\nif __name__ == '__main__':\n stack_catboost()\n","sub_path":"model/staсking.py","file_name":"staсking.py","file_ext":"py","file_size_in_byte":4459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"76762418","text":"from django.core.management.base import BaseCommand, CommandError\nfrom phone.models import Phones\n\n\nclass Command(BaseCommand):\n\n def handle(self, *args, **options):\n try:\n phones_obj = Phones.objects.filter(flat=0)\n\n except Phones.DoesNotExist:\n raise CommandError('Object does not exist')\n total = phones_obj.count()\n phones_obj.delete()\n\n self.stdout.write('Successfully deleted {total} wrong values'.format(total=total))\n\n\n","sub_path":"phone/management/commands/delempty.py","file_name":"delempty.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"151058745","text":"#coding: utf-8\nfrom importlib import import_module\nfrom django.contrib import messages\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.http import HttpResponse\nimport json\nfrom django.shortcuts import render, redirect\nfrom django.template.loader import render_to_string\nimport redis\nfrom delivery.models import *\nfrom catalog.models import *\nfrom accounts.models import *\nfrom django.views.generic import ListView, DetailView\nfrom delivery.forms import *\nfrom django import forms\n\n\ndef order_view(request):\n a = ''\n if request.method == 'POST':\n if 'ts_created' in request.POST:\n a = 'ts_created'\n if 'ts_accept' in request.POST:\n a = 'ts_accept'\n if 'ts_buy' in request.POST:\n a = 'ts_buy'\n if 'ts_ended' in request.POST:\n a = 'ts_ended'\n object_list = request.user.profile.dd_client.filter(state=a)\n return render(request, 'accounts/delivery.html', {'object_list': object_list})\n else:\n object_list = request.user.profile.dd_client.all()\n return render(request, 'accounts/delivery.html', {'object_list': object_list})\n\n\nclass OrderDetail(DetailView):\n model = Delivery\n template_name = 'accounts/order_detail.html'\n\n def get_queryset(self):\n return self.model.objects.all()\n\n\ndef ajax_add_to_cart(request):\n if request.is_ajax():\n pk = int(request.GET.get('cart_part_id', None))\n obj = PartsInShop.objects.get(pk=pk)\n if not 'cart' in request.session:\n request.session['cart'] = {}\n if obj.count >= 1:\n if request.user.is_authenticated() and (obj.shop in request.user.profile.shop.all()):\n return HttpResponse(json.dumps({'error_code': 0, 'code_add': 2}), content_type='application/json')\n else:\n if str(obj.id) in request.session['cart']:\n if obj.count > request.session['cart'][str(obj.id)]['count']:\n request.session['cart'][str(obj.id)]['count'] += 1\n request.session['cart'][str(obj.id)]['price'] = request.session['cart'][str(obj.id)]['count'] * int(obj.price)\n request.session.save()\n # PartsInShop.objects.filter(pk=pk).update(count=(obj.count-1))\n else:\n return HttpResponse(json.dumps({'error_code': 0, 'code_add': 3}), content_type='application/json')\n else:\n request.session['cart'][str(obj.id)] = {'title': obj.part.title, 'count': 1, 'article': obj.part.article, 'cost': str(obj.price), 'id': obj.id}\n request.session['cart'][str(obj.id)]['price'] = request.session['cart'][str(obj.id)]['count'] * int(obj.price)\n request.session.save()\n # PartsInShop.objects.filter(pk=pk).update(count=(obj.count-1))\n return HttpResponse(json.dumps({'error_code': 0, 'code_add': 0, 'part_count': obj.count}), content_type='application/json')\n else:\n return HttpResponse(json.dumps({'error_code': 0, 'code_add': 1}), content_type='application/json')\n else:\n return redirect(reverse_lazy('account_index'))\n\n\ndef show_cart(request):\n amount = 0\n if not 'cart' in request.session:\n request.session['cart'] = {}\n request.session.save()\n object_list = request.session['cart'].values()\n for object in object_list:\n amount += int(object.get('price'))\n return render(request, 'accounts/user_cart.html', {'object_list': object_list, 'amount_list': amount})\n\n\ndef ajax_delete_to_cart(request):\n if request.is_ajax():\n pk = str(request.GET.get('cart_part_id', None))\n if pk in request.session['cart']:\n # count = request.session['cart'][pk]['count']\n # obj_count = PartsInShop.objects.get(pk=pk).count\n # PartsInShop.objects.filter(pk=pk).update(count=(obj_count+count))\n del request.session['cart'][pk]\n request.session.save()\n if request.session['cart'].__len__() == 0:\n code_a = 1\n else:\n code_a = 0\n return HttpResponse(json.dumps({'error_code': 0, 'code_del': code_a}), content_type='application/json')\n else:\n return redirect(reverse_lazy('ajax_delete_to_cart'))\n\n\ndef ajax_plus_to_cart(request):\n if request.is_ajax():\n pk = request.GET.get('cart_part_id', None)\n amount = 0\n if pk in request.session['cart']:\n if PartsInShop.objects.get(pk=int(pk)).count > request.session['cart'][pk]['count']:\n request.session['cart'][pk]['count'] += 1\n count = request.session['cart'][pk]['count']\n # obj_count = PartsInShop.objects.get(pk=pk).count\n # PartsInShop.objects.filter(pk=pk).update(count=(obj_count-1))\n price = int(PartsInShop.objects.get(pk=int(pk)).price) * count\n request.session['cart'][pk]['price'] = price\n object_list = request.session['cart'].values()\n for object in object_list:\n amount += int(object.get('price'))\n request.session.save()\n return HttpResponse(json.dumps({'error_code': 0, 'part_count': count, 'part_price': price,\n 'amount_price': amount, 'code_plus': 1}), content_type='application/json')\n else:\n return HttpResponse(json.dumps({'error_code': 0, 'code_plus': 0}), content_type='application/json')\n else:\n return redirect(reverse_lazy('ajax_plus_to_cart'))\n\n\ndef ajax_minus_to_cart(request):\n if request.is_ajax():\n amount = 0\n pk = request.GET.get('cart_part_id', None)\n if pk in request.session['cart']:\n if request.session['cart'][pk]['count'] > 1:\n request.session['cart'][pk]['count'] -= 1\n count = request.session['cart'][pk]['count']\n # obj_count = PartsInShop.objects.get(pk=pk).count\n # PartsInShop.objects.filter(pk=pk).update(count=(obj_count+1))\n price = int(PartsInShop.objects.get(pk=int(pk)).price) * count\n request.session['cart'][pk]['price'] = price\n object_list = request.session['cart'].values()\n for object in object_list:\n amount += int(object.get('price'))\n request.session.save()\n return HttpResponse(json.dumps({'error_code': 0, 'part_count': count, 'part_price': price,\n 'amount_price': amount, 'code_min': 0}), content_type='application/json')\n else:\n return HttpResponse(json.dumps({'error_code': 0, 'code_min': 1}), content_type='application/json')\n else:\n return redirect(reverse_lazy('ajax_minus_to_cart'))\n\n\ndef checkout_cart(request):\n c = 0\n shippingform = ShippingForm(request.POST or None, prefix='ShippingForm')\n paymentform = PaymentForm(request.POST or None, prefix='PaymentForm')\n addresshipform = AddressForm(request.POST or None, prefix='AddresShipForm')\n object_list = request.user.profile.addresses.all()\n if request.method == 'POST' and (shippingform.is_valid() and paymentform.is_valid()):\n ship = request.POST.get('ShippingForm-shipping')\n pay = request.POST.get('PaymentForm-payment')\n item_list = request.session['cart'].values()\n for item in item_list:\n c += int(item.get('price'))\n if ship == 'td_courier':\n if 'checkout_btn_new' in request.POST:\n if addresshipform.is_valid():\n a = addresshipform.save()\n a.profiles.add(request.user.profile)\n a.save()\n o = Delivery.objects.create(client_del=request.user.profile, amount=c, state='ts_created', payment=pay, shipping=ship, address_id=a.pk)\n else:\n messages.error(request, 'Вы ввели неправильно данные при создании адреса!')\n return render(request, 'accounts/checkout_cart.html', dict(ShippingForm=shippingform, PaymentForm=paymentform,\n AddresShipForm=addresshipform, object_list=object_list))\n else:\n for item in request.user.profile.addresses.all():\n if 'checkout_btn_'+str(item.pk) in request.POST:\n o = Delivery.objects.create(client_del=request.user.profile, amount=c, state='ts_created',\n payment=pay, shipping=ship, address_id=item.pk)\n else:\n o = Delivery.objects.create(client_del=request.user.profile, amount=c, state='ts_created', payment=pay, shipping=ship)\n for item in item_list:\n o.ps_del.create(quantity=item.get('count'), part_in_shop_id=item.get('id')).del_in_shop.add(PartsInShop.objects.filter(pk=item.get('id')).get().shop)\n o.save()\n PartsInShop.objects.filter(pk=item.get('id')).update(count=(PartsInShop.objects.get(pk=item.get('id')).count - item.get('count')))\n del request.session['cart']\n messages.success(request, 'Вы успешно создали заказ!')\n return redirect('/account/')\n else:\n return render(request, 'accounts/checkout_cart.html', dict(ShippingForm=shippingform, PaymentForm=paymentform, AddresShipForm=addresshipform, object_list=object_list))\n\n\ndef ajax_badge_cart(request):\n if request.is_ajax():\n badge_cart = ''\n if 'cart' in request.session:\n if request.session['cart']:\n badge_cart = request.session['cart'].__len__()\n else:\n request.session['cart'] = {}\n\n # Unread messages control\n try:\n chats = request.user.profile.chats.all()\n except AttributeError:\n chats = []\n r = redis.Redis('localhost')\n unread_chats = []\n chat_count = 0\n for chat in chats:\n messages_list = []\n unread_chat = {'chat_pk': chat.pk, 'count': 0}\n channel = 'channel_' + str(chat.pk)\n messages = r.lrange(channel, 0, r.llen(channel))\n for message in messages:\n messages_list.append(eval(message))\n for list_item in messages_list:\n if not request.user.profile.pk in list_item['read']:\n unread_chat['count'] += 1\n unread_chats.append(unread_chat)\n for item in unread_chats:\n if item['count'] != 0:\n chat_count += 1\n return HttpResponse(json.dumps({'error_code': 0, 'badge_cart': badge_cart, 'chat_count': chat_count, 'unread_chats': unread_chats}), content_type='application/json')\n else:\n return redirect(reverse_lazy('ajax_badge_cart'))\n\n\ndef ajax_validation_cart(request):\n if request.is_ajax():\n part_list = []\n cost_list = []\n count_list = {}\n price_list = {}\n amount = 0\n otvet = 0\n item_list = request.session['cart'].values()\n st = request.GET.get('stat', None)\n pk = request.GET.get('pk', None)\n if st == 'fail':\n for item in item_list:\n count = PartsInShop.objects.get(id=item.get('id')).count\n price = PartsInShop.objects.get(id=item.get('id')).price\n if item.get('count') > count:\n part_list.append(item.get('id'))\n count_list[item.get('id')] = count\n if item.get('cost') != str(price):\n cost_list.append(item.get('id'))\n price_list[item.get('id')] = str(price)\n if (part_list and cost_list)or(part_list or cost_list):\n return HttpResponse(json.dumps({'error_code': 0,\n 'part_list': part_list, 'count': count_list,\n 'cost_list': cost_list, 'price': price_list}), content_type='application/json')\n else:\n return HttpResponse(json.dumps({'error_code': 0, 'code_a': 1}), content_type='application/json')\n if st == 'ok':\n cost = PartsInShop.objects.get(id=pk).price\n request.session['cart'][pk]['cost'] = str(cost)\n count = request.session['cart'][pk]['count']\n price = int(PartsInShop.objects.get(pk=int(pk)).price) * count\n request.session['cart'][pk]['price'] = price\n for item in item_list:\n amount += int(item.get('price'))\n request.session.save()\n return HttpResponse(json.dumps({'error_code': 0, 'cost': str(cost), 'part_price': str(price), 'amount_price': str(amount)}), content_type='application/json')\n else:\n # return redirect(reverse_lazy('account_index'))\n return HttpResponse(json.dumps({'error_code': 1}), content_type='application/json')\n","sub_path":"delivery/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"311753244","text":"import multiprocessing as mp\nimport sys\nfrom enum import Enum\nfrom time import sleep\n\nfrom src.algorithms.direct import DirectAlgorithm, Triangle, Point3d\nfrom src.parser import parse\nfrom src.render import Renderer, pygame\nfrom src.system.periscope import Periscope, MirrorLocation, Target\nimport random\n\n\nclass SolveAlgorithm(Enum):\n DIRECT = 1\n NEURAL_NET = 2\n\n\nclass TargetMoveMode(Enum):\n KEYBOARD = 1\n RANDOM_MOVE = 2\n\n\nclass PeriscopeApplication:\n def __init__(\n self,\n input_model: str = '2d',\n algorithm: SolveAlgorithm = SolveAlgorithm.DIRECT,\n ):\n self.log_list = []\n pygame.init()\n self.input_model = input_model\n config = parse(input_model)\n\n self.periscope: Periscope = Periscope(config)\n p_target = self.periscope.ray_to_aim().intersect_plane(\n Triangle(Point3d(0.2, 0.5, 0.2),\n Point3d(0.2, 0.4, 0.1),\n Point3d(0.2, 0.3, 0.5)\n ))\n\n p_target_prev = self.periscope.ray_to_aim().intersect_plane(\n Triangle(Point3d(0.2, 0.5, 0.2),\n Point3d(0.2, 0.4, 0.1),\n Point3d(0.2, 0.3, 0.5)\n ))\n tee = Target(p_target, config[\"target_radius\"])\n tee_prev = Target(p_target_prev, config[\"prev_target_radius\"])\n\n self.periscope.set_target(tee)\n self.periscope.set_prev_target(tee_prev)\n\n self.renderer = Renderer(self.periscope)\n\n # Shared memory\n self.down_plane_points = mp.Array('d', 6)\n self.up_plane_points = mp.Array('d', 6)\n self.__init_share_memory()\n\n self.up_plane_queue = mp.Queue()\n self.down_plane_queue = mp.Queue()\n\n self.up_plane_process: mp.Process = mp.Process(target=DirectAlgorithm.plane_direct_process,\n args=(self.up_plane_queue, self.up_plane_points, self.periscope,\n MirrorLocation.UP))\n self.down_plane_process: mp.Process = mp.Process(target=DirectAlgorithm.plane_direct_process,\n args=(\n self.down_plane_queue, self.down_plane_points,\n self.periscope,\n MirrorLocation.DOWN))\n\n def __init_share_memory(self):\n self.down_plane_points[0] = self.periscope.mirror_down.triangle.point_b.x\n self.down_plane_points[1] = self.periscope.mirror_down.triangle.point_b.y\n self.down_plane_points[2] = self.periscope.mirror_down.triangle.point_b.z\n self.down_plane_points[3] = self.periscope.mirror_down.triangle.point_c.x\n self.down_plane_points[4] = self.periscope.mirror_down.triangle.point_c.y\n self.down_plane_points[5] = self.periscope.mirror_down.triangle.point_c.z\n\n self.up_plane_points[0] = self.periscope.mirror_up.triangle.point_b.x\n self.up_plane_points[1] = self.periscope.mirror_up.triangle.point_b.y\n self.up_plane_points[2] = self.periscope.mirror_up.triangle.point_b.z\n self.up_plane_points[3] = self.periscope.mirror_up.triangle.point_c.x\n self.up_plane_points[4] = self.periscope.mirror_up.triangle.point_c.y\n self.up_plane_points[5] = self.periscope.mirror_up.triangle.point_c.z\n\n\n def __move_target(self, iteration) -> (bool, bool):\n exit_app = False\n for i in pygame.event.get():\n if i.type == pygame.QUIT:\n exit_app = True\n\n #possible_move = ['up', 'down', 'left', 'right']\n #key = random.choice(possible_move)\n possible_move = ['up', 'up', 'left', 'left', 'up', 'left', 'up', 'up', 'up', 'left']\n key = possible_move[iteration]\n delta = 0.05\n self.periscope.prev_target.location.x = float(self.periscope.target.location.x)\n self.periscope.prev_target.location.y = float(self.periscope.target.location.y)\n\n if key == 'up':\n self.periscope.target.location.y += delta\n elif key == 'down':\n self.periscope.target.location.y -= delta\n elif key == 'right':\n self.periscope.target.location.x += delta\n elif key == 'left':\n self.periscope.target.location.x -= delta\n\n need_rebuild = True\n return exit_app, need_rebuild\n\n\n def run(self):\n self.up_plane_process.start()\n self.down_plane_process.start()\n tee = self.periscope.target\n prev_tee = self.periscope.prev_target\n\n str_down = f'sending 1st target coord: {self.periscope.target.get_description()} to down plane process by ' + mp.process.current_process().name + '\\n'\n print(str_down)\n with open('первый_опыт.txt', 'a') as f:\n f.write(str_down)\n self.down_plane_queue.put(self.periscope.target) # send\n\n str_up = f'sending 1st target coord: {self.periscope.target.get_description()} to up plane process by ' + mp.process.current_process().name + '\\n'\n print(str_up)\n with open('первый_опыт.txt', 'a') as f:\n f.write(str_up)\n self.up_plane_queue.put(self.periscope.target) # send\n\n exit_app = False\n iteration = 0\n max_iteration = 4\n sleep_time = 2\n while not exit_app and iteration <= max_iteration:\n\n p1_intersect = self.periscope.laser.intersect_plane(self.periscope.mirror_down.triangle)\n p2_intersect = self.periscope.laser.reflect_plane(self.periscope.mirror_down.triangle). \\\n intersect_plane(self.periscope.mirror_up.triangle)\n p_aim = self.periscope.ray_to_aim().intersect_plane(\n Triangle(Point3d(tee.location.x, 0.5, 0.2),\n Point3d(tee.location.x, 0.4, 0.1),\n Point3d(tee.location.x, 0.3, 0.5)\n ))\n self.renderer.render(p1_intersect, p2_intersect, tee, prev_tee, p_aim)\n\n if iteration == max_iteration:\n sleep(sleep_time)\n break\n\n self.update_log(iteration, p_aim, 'before move')\n exit_app, need_rebuild = self.__move_target(iteration)\n\n str_down = f'sending target coord: {self.periscope.target.get_description()} to down plane process by ' + mp.process.current_process().name + '\\n'\n print(str_down)\n with open('первый_опыт.txt', 'a') as f:\n f.write(str_down)\n self.down_plane_queue.put(self.periscope.target) # send\n\n str_up = f'sending target coord: {self.periscope.target.get_description()} to up plane process by ' + mp.process.current_process().name + '\\n'\n print(str_up)\n with open('первый_опыт.txt', 'a') as f:\n f.write(str_up)\n self.up_plane_queue.put(self.periscope.target) # send\n\n self.update_log(iteration, p_aim, 'after move')\n iteration += 1\n\n self.apply_changes(self.periscope.mirror_down.triangle, self.down_plane_points)\n self.apply_changes(self.periscope.mirror_up.triangle, self.up_plane_points)\n # update log\n sleep(sleep_time)\n\n self.up_plane_process.terminate()\n self.down_plane_process.terminate()\n self.write_log()\n exit()\n\n\n def update_log(self, iteration, p_aim, info):\n tee = self.periscope.target.location\n up = self.periscope.mirror_up.triangle\n down = self.periscope.mirror_down.triangle\n\n output_iteration_list = []\n output_iteration_list.append('-------------info: ' + info + '-------------\\n')\n output_iteration_list.append('-------------iteration: ' + str(iteration) + '-------------\\n')\n output_iteration_list.append(' '.join(['target: ', str(tee.x), str(tee.y), str(tee.z), '\\n']))\n output_iteration_list.append(' '.join(['difference: ', str(p_aim.distance_to_point(tee)), '\\n']))\n output_iteration_list.append(' '.join(['up b: ', str(up.point_b.x), str(up.point_b.y), str(up.point_b.z), '\\n']))\n output_iteration_list.append(' '.join(['up c: ', str(up.point_c.x), str(up.point_c.y), str(up.point_c.z), '\\n']))\n output_iteration_list.append(\n ' '.join(['down b: ', str(down.point_b.x), str(down.point_b.y), str(down.point_b.z), '\\n']))\n output_iteration_list.append(\n ' '.join(['down c: ', str(down.point_c.x), str(down.point_c.y), str(down.point_c.z), '\\n']))\n\n self.log_list.append(''.join(output_iteration_list))\n\n\n def write_log(self):\n f = open('/Users/epriimak/Desktop/Diplom/Periscope/logs/a.txt', 'w')\n f.writelines(self.log_list)\n f.close()\n\n\n @staticmethod\n def apply_changes(plane: Triangle, arr: mp.Array):\n plane.point_b = Point3d(arr[0], arr[1], arr[2])\n plane.point_c = Point3d(arr[3], arr[4], arr[5])\n\n\nif __name__ == '__main__':\n input_model: str = '2d'\n algorithm: SolveAlgorithm = SolveAlgorithm.DIRECT\n\n app = PeriscopeApplication(input_model, algorithm)\n app.run()\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":9243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"123464034","text":"#\n# coding: utf-8 \n# \n# Project: execPlugins / Saxs Group / saxs_mac\n# http://www.edna-site.org\n#\n# File: \"$Id$\"\n#\n# Copyright 2011 (C) ESRF\n\n# Principal author: Jérôme Kieffer\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n\n__author__ = \"Jérôme Kieffer\"\n__contact__ = \"Jerome.Kieffer@esrf.eu\"\n__license__ = \"GPLv3+\"\n__copyright__ = \"2011 ESRF\"\n\nfrom EDVerbose import EDVerbose\nfrom EDTestCasePluginUnit import EDTestCasePluginUnit\nfrom XSDataSaxsv1_0 import XSDataInputSaxsCurvesv1_0\nfrom EDFactoryPluginStatic import EDFactoryPluginStatic\n# Needed for loading the plugin...\nEDFactoryPluginStatic.loadModule(\"EDInstallNumpyv1_3\")\nEDFactoryPluginStatic.loadModule(\"EDInstallPILv1_1_7\")\nEDFactoryPluginStatic.loadModule(\"EDInstallFabio_v0_0_7\")\n\n\nclass EDTestCasePluginUnitExecSaxsCurvesv1_1(EDTestCasePluginUnit):\n \"\"\"\n Those are all units tests for the EDNA Exec plugin SaxsCurvesv1_1\n \"\"\"\n\n def __init__(self, _strTestName=None):\n \"\"\"\n \"\"\"\n EDVerbose.DEBUG(\"EDTestCasePluginUnitExecSaxsCurvesv1_1: init\")\n EDTestCasePluginUnit.__init__(self, \"EDPluginExecSaxsCurvesv1_1\")\n\n\n def testCheckParameters(self):\n EDVerbose.DEBUG(\"EDTestCasePluginUnitExecSaxsCurvesv1_1: testCheckParameters\")\n xsDataInput = XSDataInputSaxsCurvesv1_0()\n edPluginExecSaxsCurves = self.createPlugin()\n edPluginExecSaxsCurves.setDataInput(xsDataInput)\n edPluginExecSaxsCurves.checkParameters()\n\n\n\n def process(self):\n EDVerbose.DEBUG(\"EDTestCasePluginUnitExecSaxsCurvesv1_1: process\")\n self.addTestMethod(self.testCheckParameters)\n\n\n\nif __name__ == '__main__':\n\n edTestCasePluginUnitExecSaxsCurvesv1_1 = EDTestCasePluginUnitExecSaxsCurvesv1_1(\"EDTestCasePluginUnitExecSaxsCurvesv1_1\")\n edTestCasePluginUnitExecSaxsCurvesv1_1.execute()\n","sub_path":"execPlugins/plugins/EDPluginGroupSaxs-v1.0/tests/testsuite/EDTestCasePluginUnitExecSaxsCurvesv1_1.py","file_name":"EDTestCasePluginUnitExecSaxsCurvesv1_1.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"260195142","text":"\"\"\"\nhttps://leetcode.com/problems/asteroid-collision/\n\n\"\"\"\n\nfrom typing import List\n\nclass Solution:\n def asteroidCollision(self, asteroids: List[int]) -> List[int]:\n\n stack = [] ## Declare the stack\n i=0\n while i 0 and asteroids[i] > 0) or (stack[-1] < 0 and asteroids[i] > 0):\n stack.append(asteroids[i])\n\n else: ## Now we have encountered a -ve value asteriod and the stacktop is +ve, lets process the current asteriod\n while len(stack)>0 :\n # During the processing of the current asteroid, since we may be popping elements, it may so happen that\n ## stacktop and current asteroid are of same sign again. In that case just break out of the loop. to reprocess the current asteriod\n if (stack[-1] >0 and asteroids[i] >0) or (stack[-1] <0 and asteroids[i] <0):\n i-=1\n break\n\n if abs(stack[-1]) < abs(asteroids[i]): ## stack top is +ve and its value is less than absolute value of the current asteroid\n stack.pop() ## simply pop the element from the stack\n if len(stack) == 0: ## if stack is empty then there are no more elements to collide with and simply append the current asteroid. and break\n stack.append(asteroids[i])\n break\n\n elif stack[-1] == abs(asteroids[i]): ## is aboslute values are same\n stack.pop() ## pop the last element and break\n break\n\n elif stack[-1] > abs(asteroids[i]): ## Stack top is +ve and greater than the current absolute value\n break\n\n i+=1\n\n return stack\n\n\nobject=Solution()\n\narray=[5,10,-5]\nprint(object.asteroidCollision(array))\n\narray=[-2,-1,1,2]\nprint(object.asteroidCollision(array))\n\narray=[-2,-2,1,-2]\nprint(object.asteroidCollision(array))\n\n\n","sub_path":"Leetcode/python/Medium/asteroid-collision.py","file_name":"asteroid-collision.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"447573032","text":"import pandas as pd\n\ndef create_model_table(fit, dest, filter=[], decimals=2):\n \"\"\"\n Create a latex table and save it to .tex dest file\n\n Params:\n fit (StanFit4model) \n dest (str)\n filter (list[str]): names of the keys to include.\n decimals (int): number of decimals to include\n \n Returns:\n pd.DataFrame\n \"\"\"\n \n summary = fit.summary()\n df = pd.DataFrame(summary['summary'],\n index=summary['summary_rownames'],\n columns=summary['summary_colnames'])\n if filter:\n df = df.loc[filter]\n \n df = df.round(decimals)\n \n with open(dest, 'w') as f:\n f.write(df.to_latex())\n \n return df\n\n","sub_path":"ex9/my_utilities.py","file_name":"my_utilities.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"127535110","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#SYN:xloffa00\n\n#Author: Pavol Loffay, xloffa00@stud.fit.vutbr.cz\n#Date: 6.3.2012\n#Project: Projekt 2. do predmetu IPP\n# SYN: Zvyraznenie syntaxe\n\n#pouzite moduly\nimport getopt;\nimport sys;\nimport string; \nimport re; \n\n#konstanty pre navratove hodnoty\nRET_BAD_PARAMS = 1;\nRET_OK = 0;\nRET_BAD_IN_FILE = 2;\nRET_BAD_OUT_FILE = 3;\nRET_BAD_FORMAT_FILE = 4; \n\n#formatovacie prikazy\nFORMAT_PARAMS = [\"bold\", \"italic\", \"underline\", \"teletype\"];\n\ndef error_exit(exit_value, err_message):\n '''\n @brief Vypise err_message na stderr a \n ukonci skript s hodnotou exit_value\n\n @param number - navratova hodnnota skriptu\n @param string - chyba ktora sa vypise\n @return void\n '''\n sys.stderr.write(err_message);\n sys.exit(exit_value);\n\ndef print_help():\n '''\n @brief Vypise napovedu a ukonci skript\n\n @param void\n @return void\n '''\n print(\"SYN - Zvyraznenie syntaxe\\n\",\n \"--help: vypise tuto napovedu\\n\",\n \"--format=filename: urcenie formatovacieho suboru\\n\",\n \"--input=filename: urcenie vstupneho suboru v utf-8\\n\",\n \"--output=filename: urcenie vystupneho suboru v utf-8\\n\",\n \"--br: prida
na koniec kazdeho riadku povodneho vstupu\\n\",\n \"Formatovaci subor obsahuje \\n\",\n \"Ak nie je zadany vstupny subor vstup je stdin\\n\",\n \"Ak nie je zadany vystupny subor vystup ide na stdout\\n\");\n sys.exit(RET_OK);\n\ndef params():\n '''\n @brief Spracauje parametre prik. riadku\n vrati zoznam kde budu ulozene parametre\n ktore boli zadane.\n Ak ma parameter mat hodnotu bude ulozena v zozname za parametrom!\n\n @param void\n @return list - kde su ulozene parametre ktore boli zadane,\n parametre s hodnotou budu ulozene v zozname hned za\n parametrom\n '''\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"\", [\"help\", \"format=\", \"input=\",\n \"output=\", \"br\"]);\n except getopt.GetoptError as err:\n error_exit(RET_BAD_PARAMS, \"Bol zadany nespravny parameter!\\n\");\n\n params_list = [];\n params_counter = 0;\n\n #opts is list of (option, value)\n for param, value in opts:\n if (param == \"--help\"):\n if (param in params_list):\n error_exit(RET_BAD_PARAMS, \n \"Chybne parametre: dva krat zadany parameter!\\n\");\n\n params_list.append(\"--help\");\n params_counter += 1;\n elif (param == \"--format\"):\n if (param in params_list):\n error_exit(RET_BAD_PARAMS,\n \"Chybne parametre: dva krat zadany parameter!\\n\");\n if (value == \"\" ):\n error_exit(RET_BAD_PARAMS,\n \"Chybne parametre: --format vyzaduje parameter!\\n\");\n\n params_list.append(\"--format\");\n params_list.append(value);\n params_counter += 1;\n elif (param == \"--input\"):\n if (param in params_list):\n error_exit(RET_BAD_PARAMS, \n \"Chybne parametre: dva krat zadany parameter!\\n\");\n if (value == \"\"):\n error_exit(RET_BAD_PARAMS,\n \"Chybne parametre: --input vyzaduje parameter!\\n\");\n\n params_list.append(\"--input\");\n params_list.append(value);\n params_counter += 1;\n elif (param == \"--output\"):\n if (param in params_list):\n error_exit(RET_BAD_PARAMS, \n \"Chybne parametre: dva krat zadany parameter!\\n\");\n if (value == \"\"):\n error_exit(RET_BAD_PARAMS, \n \"Chybne parametre: --output vyzaduje parameter!\\n\");\n\n params_list.append(\"--output\");\n params_list.append(value);\n params_counter += 1;\n elif (param == \"--br\"):\n if (params in params_list):\n error_exit(RET_BAD_PARAMS, \n \"Chybne parametre: dva krat zadany parameter!\\n\");\n\n params_list.append(\"--br\");\n params_counter +=1;\n else:\n error_exit(RET_BAD_PARAMS,\n \"Chybne parametre: nespravny parameter!\\n\");\n \n \n if (len(sys.argv[1:]) != params_counter):\n error_exit(RET_BAD_PARAMS, \n \"Chybne parametre: nespravny parameter!\\n\");\n return params_list\n\ndef parse_format_file(format_data):\n '''\n @brief Funkcia spracuje subor --forma=filename\n Jehu struktura je:\n \\t*\n -formatovacie parametre su oddelene ciarkami \n a lubovolnym poctom medzier a \\t\n\n @param list - nacitany sobur po riadoch\n @return list - vrati list v ktorom polozky su hash\n hash ma kluc regularny vyraz a polozku\n list s dvoma polozkamy: \n Prva co sa ma pridat pri najdeny regularu na zaciatok\n Druhy co sa ma pridat na koniec.\n '''\n parsed = [];\n\n #prelistuje po riadkoch data z --format=file\n for line in format_data:\n #oddeli od \n #medzi RV a zoznamom_parametrom.. je oddelovac \\t\n #split vrati list\n\n #odstranienie ukoncovaca riadku\n pattern = re.compile(\"\\n\");\n if (pattern.search(line) != None):\n line = line[0:len(line) - 1];\n\n\n line_parsed = line.split('\\t');\n rv = line_parsed[0];\n if (len(line_parsed) < 2):\n error_exit(RET_BAD_FORMAT_FILE,\n \"Chyba: subor --format obsahuje nevalidne data!\\n\");\n \n format_params = [];\n\n #rozparsovanie prveho formatovacieho prikazu\n line_parsed = line.split(',');\n #v prvom je ulozeny aj rv - rv treba odstranit\n first = line_parsed[0];\n first = first.split('\\t');\n if (len(first) < 2):\n error_exit(RET_BAD_FORMAT_FILE,\n \"Chyba: subor --format obsahuje nevalidne data!\\n\");\n #odstrani prazdne - ked bolo zadanych viac tabulatorov medzi rv bold\n first = [x for x in first if x];\n #print(first);\n #prvy formatovaci prikaz je v liste na druhej pozicii\n first = first[1:];\n if (len(first) != 1):\n error_exit(RET_BAD_FORMAT_FILE,\n \"Chyba: subor --format obsahuje nevalidne data!\\n\");\n \n first = first[0];\n first = first.replace(\" \", \"\");\n format_params.append(first);\n\n #rozparsovanie ostatnych formatovacich prikazov\n line_parsed = line.split(',');\n line_parsed = line_parsed[1:];\n for item in line_parsed:\n pattern = re.compile(\"\\w+\\s+\\w+\");\n if (pattern.search(item) != None):\n error_exit(RET_BAD_FORMAT_FILE,\n \"Chyba: subor --format obsahuje nevalidne data!\\n\");\n item = item.replace(\" \", \"\");\n item = item.replace(\"\\t\", \"\");\n\n #ak je definovany pridam k formatovacim prikazom\n #inaksie je prazdny a je to chyba\n if (item):\n format_params.append(item);\n else:\n error_exit(RET_BAD_FORMAT_FILE,\n \"Chyba: subor --format obsahuje nevalidne data!\\n\");\n\n #print(format_params);\n\n #prelistovanie formatovacich parametrov - kontrola\n params_list = [];\n start = \"\";\n end = \"\";\n for param in format_params:\n if (((param in FORMAT_PARAMS) == False) and \n (re.search(\"^size:[1-7]$\" , param) == None) and\n (re.search(\"^color:[ABCDEF0-9]{6}$\", param) == None)):\n error_exit(RET_BAD_FORMAT_FILE, \n \"Chyba: subor --format=filename obsahuje nevalidne data!\\n\");\n \n if (param == \"bold\"):\n start = start + \"\";\n end = \"\" + end;\n if (param == \"italic\"):\n start = start + \"\";\n end = \"\" + end;\n if (param == \"underline\"):\n start = start + \"\";\n end = \"\" + end;\n if (param == \"teletype\"):\n start = start + \"\";\n end = \"\" + end;\n if (re.search(\"^size:[1-7]$\", param) != None):\n #vyparsovanie cisla\n pattern = re.compile(\"[1-7]\");\n obj = pattern.search(param);\n start = start + \"\";\n end = \"\" + end;\n if (re.search(\"^color:[ABCDEF0-9]{6}$\", param) != None):\n #vyparsovanie cisla\n pattern = re.compile(\"[ABCDEF0-9]{1,6}\");\n obj = pattern.search(param);\n start = start + \"\";\n end = \"\" + end;\n\n #v hash je kluc a list\n #prva polozka listu je zaciatocny formatovaci retazec, druha konecny\n params_list.append(start);\n params_list.append(end);\n \n if (control_rv(rv) != True):\n error_exit(RET_BAD_FORMAT_FILE, \"Chyba: nespravy regularny vyraz!\\n\");\n else:\n #uprava RV pre python\n rv = rv_modification(rv);\n \n hash_item = {rv : params_list};\n parsed.append(hash_item);\n \n return parsed;\n\ndef search_patterns(list_pattern, string):\n '''\n @brief Funkcia prejde zoznam list_pattern z kazneho prvku\n urobi RV ktory sa vyhlada v stringu, ak sa najde vrati True\n\n @param list - regularnych vyrazov\n @param string - v ktorom sa bude hladat\n @return bool - ak najde true inak false\n '''\n\n for item in list_pattern:\n #pred polozkou nesmie byt %\n item = re.escape(item);\n # druha cast je tam koli tomu ze moze byt na zaciatku retazca\n pattern = re.compile(\"([^%]{1}\"+item+\")|(^\"+item+\")\");\n obj = pattern.search(string);\n if (obj != None):\n return True;\n\n return False;\n\ndef parenthesis_control(string):\n '''\n @brief skontroluje zatvorky, ci nejaka nieje otvorena\n\n @param string - string kde mozu byt zatvorky\n @return bool - true ak su zatvorky v stringu v poriadku, inak false\n '''\n length = len(string);\n index = 0;\n\n list_brackets = \"\";\n\n while (index < length):\n if (index == 0):\n if (string[index] == '('):\n list_brackets.append('(');\n elif (string[index] == ')'):\n if (len(list_brackets) == 0):\n return False;\n list_brackets.pop();\n else:\n if (string[index] == '(' and string[index - 1] != '%'):\n list_brackets.append('(');\n elif (string[index] == ')' and string[index - 1] != '%'):\n if (len(list_brackets) == 0):\n return False;\n list_brackets.pop();\n \n index = index + 1;\n\n if (len(list_brackets) == 0):\n return True;\n\n return False;\n\ndef control_rv(rv):\n '''\n @brief Funkcia skontroluje ci RV zo suboru --fortmat=filename\n je zadany spravne.\n\n @param regularny vyraz zo zadania\n @return true ak je validny, inak false\n '''\n length = len(rv);\n\n #ak je dlzka RV jeden znak\n if (length == 1):\n pattern = re.compile(\"[\\!\\.\\+\\*\\|\\(\\)\\%]\");\n if (pattern.search(rv) != None):\n return False;\n\n #kontrola prvych - prve nemoze byt . | + * )\n if (rv[0] == '.' or rv[0] == '|' or rv[0] == '+' or\n rv[0] == '*' or rv[0] == ')'):\n return False;\n \n\n #kontrola poslednych - posledne nemoze byt . ! ( % |\n # if ((rv[length - 1] == '.' or rv[length - 1] == '!' or \n # rv[length - 1] == '(' or rv[length - 1] == '|' or\n # rv[length - 1 == '%']) and\n # (length >= 2 and rv[length - 2 ] != '%')):\n # print(\"ssa\", rv[length - 1]);\n # return False;\n\n if (length >= 2 and rv[length - 2] != \"%\"):\n if (rv[length - 1] == '.' or rv[length - 1] == '!' or \n rv[length - 1] == '(' or rv[length - 1] == '|' or\n rv[length - 1] == '%'):\n return False;\n\n #kontrola rovnakych znakov za sebou - nesmu ist .. || ** ++ !!\n if (search_patterns(['..', '||', '**', '++', '!!' ], \n rv) == True):\n return False;\n\n #kat 1: !* !+ !. !| !( !)\n #kontrola dvojznakov kategoria 1. nesmie !* !+ !. !| !( !)\n if (search_patterns(['!*', '!+', '!.', '!|', '!(', '!)'], rv) == True):\n return False;\n \n #kat 2: *! *| *. *+ *( *)\n #kontrola dvojznakov kategoria 2. nesmie *+ TODO *| *. forum opytat\n if (search_patterns(['*+'], rv) == True):\n return False;\n\n #kat 3: +! +* +| +. +( +)\n #kontrola dvojznakov kategoria 3. nesmie +* TODO +| +. forum opytat \n if (search_patterns(['+*'], rv) == True):\n return False;\n\n #kat 4: .! .* .+ .| .( .) \n #kontrola dvojznakov kategoria 4. nesmie .+ .* TODO .| (.!-toto asi moze) \n if (search_patterns(['.+', '.*', '.|', '.)'], rv) == True):\n return False;\n\n #kat 5: |! |* |+ |. |( |) \n #kontrola dvojznakov kategoria 5. nesmie |* |+ TODO |. forum opytat \n if (search_patterns(['|*', '|+', '|.', '|)'], rv) == True):\n return False;\n\n #kat 6: (. (| (! (+ (* ()\n #kontrola dvojznakov kategoria 6. nesmie (. (+ (*\n if (search_patterns(['(.', '(+', '(*', '()', '(|'], rv) == True):\n return False;\n\n #kat 7: ). )| )! )* )+ )(\n #if (search_patterns( ,rv) == True):\n # return False;\n\n #kontrola ci %[sadlLwWtn.|!*+()%]\n pattern = re.compile(\"%[^sadlLwWtn\\.\\|\\!\\*\\+\\(\\)\\%]\");\n if (pattern.search(rv) != None):\n return False;\n\n return True;\n\ndef rv_modification(rv):\n '''\n @brief Funkcia upravy regularny vyraz pre python\n Najprv vyescapuje vsetky znaky\n potom odescapuje znaky co su z hodne z IPP RV\n potom sa RV upravuje podla zadania\n\n @param string regularny vyraz\n @return string upraveny regularny vyraz\n '''\n #print(\"rv povodny = \", rv);\n\n #vyescapovanie pythonovkych znakov\n rv = re.escape(rv); \n #spatne odescapovanie niektorych znakov\n # | * + ( ) \n rv = rv.replace(\"\\|\", \"|\");\n rv = rv.replace(\"\\*\", \"*\");\n rv = rv.replace(\"\\+\", \"+\");\n rv = rv.replace(\"\\(\", \"(\");\n rv = rv.replace(\"\\)\", \")\");\n\n #odstrananie bodky\n pattern = re.compile(\"[^%]\\\\\\\\\\.\");\n obj = pattern.search(rv);\n while(obj != None):\n rv = list(rv);\n rv[obj.start() + 1] = \"\";\n rv[obj.start() + 2] = \"\";\n\n rv = \"\".join(rv);\n obj = pattern.search(rv);\n \n #uprava !A za [^A]\n pattern = re.compile(\"(\\\\\\\\\\%\\\\\\\\\\%\\\\\\\\\\!)|([^%]\\\\\\\\\\!)|(^\\\\\\\\\\!)\");\n index = 0;\n obj = pattern.search(rv, index);\n while (obj != None):\n rv = list(rv);\n\n if (obj.group(1)):\n #nasiel \\%\\%\\!\n rv[obj.start() + 4] = \"\";\n rv[obj.start() + 5] = \"[^\";\n elif(obj.group(2)):\n #nasiel a\\!\n rv[obj.start() + 1] = \"\";\n rv[obj.start() + 2] = \"[^\";\n else:\n #nasiel \\!a\n rv[obj.start()] = \"\";\n rv[obj.start() + 1] = \"[^\";\n\n\n #ak je nieco vyescapovane musi sa posunut o 2 znaky\n if (rv[obj.end()] == \"\\\\\"):\n if (len(rv) > obj.end() + 1 and rv[obj.end() + 1] == \"%\"):\n rv[obj.end() + 2] = rv[obj.end() + 2] + \"]\";\n else:\n rv[obj.end() + 1] = rv[obj.end() + 1] + \"]\";\n else:\n rv[obj.end()] = rv[obj.end()] + \"]\";\n\n rv = \"\".join(rv);\n index = obj.end();\n obj = pattern.search(rv, index);\n \n #specialne znaky %\n # %s = \\s znaky \\t\\n\\r\\f\\v\n rv = rv.replace(\"\\%s\", \"\\s\");\n # %a = . jeden lubovolny znak\n rv = rv.replace(\"\\%a\", \".\");\n # %d = \\d cisla od 0 do 9\n rv = rv.replace(\"\\%d\", \"\\d\");\n # %l = [a-z] male pismena od a do z\n rv = rv.replace(\"\\%l\", \"[a-z]\");\n # %L = [A-Z] velka pismena od A do Z\n rv = rv.replace(\"\\%L\", \"[A-Z]\");\n # %w = [a-zA-Z] male a velke pismena (%l%L)\n rv = rv.replace(\"\\%w\", \"[a-zA-Z]\");\n # %W = [0-9a-zA-Z] cisla a male a velke pismena\n rv = rv.replace(\"\\%W\", \"[0-9a-zA-Z]\");\n # %t = \\t \n rv = rv.replace(\"\\%t\", \"\\t\");\n # %n = znak \\n \n rv = rv.replace(\"\\%n\", \"\\n\");\n \n #specialne znaky . | ! * + ( ) % \n #pozor | * + ( ) nie su escapovane\n rv = rv.replace(\"\\%\\.\", \"\\.\");\n rv = rv.replace(\"\\%|\", \"\\|\" );\n rv = rv.replace(\"\\%\\!\", \"\\!\" );\n rv = rv.replace(\"\\%*\", \"\\*\");\n rv = rv.replace(\"\\%+\", \"\\+\");\n rv = rv.replace(\"\\%(\", \"\\(\");\n rv = rv.replace(\"\\%)\", \"\\)\");\n rv = rv.replace(\"\\%\\%\", \"\\%\");\n\n return rv;\n\n#####################################################################\n# Zaciatok skriptu\n#####################################################################\n\n#spracovanie parametrov\nparams_list = params();\n\ndata = \"\";\nformat_list = \"\";\n\nif (\"--help\" in params_list):\n if (len(params_list) == 1):\n print_help();\n else :\n error_exit(RET_BAD_PARAMS, \n \"Chybne parametre: parameter --help sa nesmie kombinovat\\n\");\n\n#################################################\n# Otvaranie suborov\n#otvorenie suboru na citanie dat\nif (\"--input\" in params_list):\n #subor\n try:\n file_in = open(params_list[params_list.index(\"--input\") + 1], mode = 'r', \n encoding = 'utf-8');\n data = file_in.read();\n file_in.close();\n except:\n error_exit(RET_BAD_IN_FILE, \"Chyba: pri otvarani vstupneho suboru!\\n\");\nelse:\n #stdin\n try: \n file_in = open(sys.stdin.fileno(), mode = 'r', encoding = 'utf-8',\n closefd = False);\n data = file_in.read();\n except:\n error_exit(RET_BAD_IN_FILE,\n \"Chyba: pri otvarani vstupneho suboru - STDIN!\\n\");\n\ndata_length = len(data);\nindex_hash = {};\n\n#otvorenie formatovacieho suboru\nif (\"--format\" in params_list):\n try:\n file_format = open(params_list[params_list.index(\"--format\") + 1], mode = 'r', \n encoding = 'utf-8');\n format_data = file_format.readlines();\n file_format.close();\n\n #rozparsovanie --format suboru\n format_list = parse_format_file(format_data);\n\n #Ziskanie indexov na vkladanie znaciek\n for hashes in format_list:\n for rv, value in hashes.items():\n # hladanie podla regularu v hash\n index = 0;\n pattern = re.compile(rv, re.DOTALL);\n obj = pattern.search(data, index);\n stop = re.compile('\\[\\^\\.\\]');\n obj_stop = stop.search(rv);\n if (obj_stop != None):\n continue;\n while (obj != None):\n start = obj.start();\n end = obj.end();\n\n #print(rv, \" ,index = \", index, \" ,length = \", data_length);\n #print(rv,\" ,start = \", start, \" end = \", end);\n\n #ochrana proti prazdnemu retazcu\n if (start == end):\n index = index + 1; #musi byt +1 inak najde to iste\n obj = pattern.search(data, index);\n #prazdne retazce to zabije\n if (index == data_length):\n break;\n continue;\n\n if (start in index_hash):\n index_hash[start] = index_hash[start]+value[0];\n else:\n index_hash[start] = value[0];\n\n if (end in index_hash):\n index_hash[end] = value[1]+index_hash[end];\n else:\n index_hash[end] = value[1];\n \n index = end ; #musi byt +1 inak najde to iste\n if (end == data_length):\n break;\n obj = pattern.search(data, index);\n except IOError:\n error_exit(RET_BAD_IN_FILE, \n \"Chyba: pri otvarani vstupneho suboru! --format\\n\");\n except re.error:\n error_exit(RET_BAD_FORMAT_FILE, \n \"Chyba: nevalidny regularny vyraz!\\n\");\n\n#prejdenie hash tabulky a pridanie formatovacich retazcov do textu - data\n#musi sa prejst od najvacsieho indexu\n#pretoze do suboru sa musi pridavat od konca\nkeys = list(index_hash);\nkeys.sort();\nindex_keys = len(keys) - 1;\ndata = list(data);\nwhile (index_keys >= 0):\n key = keys[index_keys];\n\n #ak sa ma ulozit nieco na koniec suboru\n #pouzije sa metoda append\n if (key == data_length):\n data.append(index_hash[key]);\n else:\n data[key] = index_hash[key] + data[key];\n index_keys = index_keys - 1;\n\ndata = \"\".join(data);\n\n#prida
na koniec kazdeho riadka\nif (\"--br\" in params_list):\n pattern = re.compile(\"\\r\\n\");\n obj = pattern.search(data);\n if (obj == None):\n pattern = re.compile(\"\\n\");\n\n #pridavenie
\n index = 0;\n obj = pattern.search(data, index);\n while (obj != None):\n data = list(data);\n data[obj.start()] = \"
\" + data[obj.start()];\n data = \"\".join(data);\n index = obj.end() + len(\"
\"); \n obj = pattern.search(data, index);\n\n#otvorenie vystupu na zapisovanie dat\nif (\"--output\" in params_list):\n try:\n file_out = open(params_list[params_list.index(\"--output\") + 1], mode = 'w', \n encoding = 'utf-8');\n file_out.write(data);\n file_out.close();\n except:\n error_exit(RET_BAD_OUT_FILE, \"Chyba: pri otvarani vystupneho suboru!\\n\");\nelse:\n try: \n file_out = open(sys.stdout.fileno(), mode = 'w', encoding = 'utf-8',\n closefd = False);\n file_out.write(data);\n except:\n error_exit(RET_BAD_OUT_FILE,\n \"Chyba: pri otvarani vystupneho suboru - STDOUT!\\n\");\n\nsys.exit(RET_OK);\n\n","sub_path":"project2/syn.py","file_name":"syn.py","file_ext":"py","file_size_in_byte":22347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"213472495","text":"from setuptools import setup, find_packages\n\ninstall_requires = [\n 'SQLAlchemy==1.0.11', 'yuicompressor==2.4.8', 'webassets==0.11.1',\n 'Routes==2.2', 'mysql-connector-python==2.0.4',\n 'python-social-auth==0.2.13', 'alembic==0.8.4', 'openpyxl==2.3.2',\n]\n\nsetup(name='GDGUkraine',\n version='1.0',\n author='Svyatoslav Sydorenko',\n author_email='svyatoslav@sydorenko.org.ua',\n package_dir={'': 'src'},\n packages=find_packages('src', exclude=[\"test**\"]),\n install_requires=install_requires,\n zip_safe=False)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"391349081","text":"#encoding:utf8\r\n'''\r\nCreated on 2016年2月28日\r\n\r\n@author: zhao\r\n'''\r\n\r\nimport math\r\nimport pygame\r\nfrom pygame.locals import *\r\nfrom random import random\r\n\r\n \r\nif __name__ == '__main__':\r\n compeleted = False\r\n blue = 0, 0, 200\r\n color = 200, 80, 60\r\n width = 4\r\n x = 300\r\n y = 250\r\n radius = 200\r\n position = x - radius, y-radius, radius*2, radius*2\r\n \r\n pygame.init()\r\n screen = pygame.display.set_mode((600,500))\r\n pygame.display.set_caption('The Pie Game')\r\n myfont = pygame.font.Font(None, 60)\r\n \r\n piece1 = False\r\n piece2 = False\r\n piece3 = False\r\n piece4 = False\r\n\r\n while True:\r\n for event in pygame.event.get():\r\n \r\n if event.type == QUIT:\r\n exit()\r\n elif event.type == KEYUP:\r\n if compeleted:\r\n color = (random()*255,random()*255,random()*255)\r\n compeleted = False\r\n piece1 = False\r\n piece2 = False\r\n piece3 = False\r\n piece4 = False\r\n else:\r\n if event.key == pygame.K_ESCAPE:\r\n exit()\r\n elif event.key == pygame.K_1:\r\n piece1 = True\r\n elif event.key == pygame.K_2:\r\n piece2 = True\r\n elif event.key == pygame.K_3:\r\n piece3 = True\r\n elif event.key == pygame.K_4:\r\n piece4 = True\r\n else:\r\n piece1 = False\r\n piece2 = False\r\n piece3 = False\r\n piece4 = False\r\n \r\n \r\n #clear screen\r\n screen.fill(blue)\r\n \r\n #draw the four numbers\r\n textImg1 = myfont.render(\"1\", True, color)\r\n screen.blit(textImg1, (x+radius/2-20, y-radius/2))\r\n \r\n textImg2 = myfont.render(\"2\", True, color)\r\n screen.blit(textImg2, (x-radius/2, y-radius/2))\r\n \r\n textImg3 = myfont.render(\"3\", True, color)\r\n screen.blit(textImg3, (x-radius/2, y+radius/2-20))\r\n \r\n textImg4 = myfont.render(\"4\", True, color)\r\n screen.blit(textImg4, (x+radius/2-20, y+radius/2-20))\r\n \r\n #should the picece be drawn?\r\n if piece1:\r\n start_angle = math.radians(0)\r\n end_angle = math.radians(90)\r\n pygame.draw.arc(screen, color, position, start_angle, end_angle, width)\r\n pygame.draw.line(screen, color, (x, y), (x,y-radius), width)\r\n pygame.draw.line(screen, color, (x, y), (x+radius, y), width)\r\n \r\n if piece2:\r\n start_angle = math.radians(90)\r\n end_angle = math.radians(180)\r\n pygame.draw.arc(screen, color, position, start_angle, end_angle, width)\r\n pygame.draw.line(screen, color, (x, y), (x,y-radius), width)\r\n pygame.draw.line(screen, color, (x, y), (x-radius, y), width)\r\n \r\n if piece3:\r\n start_angle = math.radians(180)\r\n end_angle = math.radians(270)\r\n pygame.draw.arc(screen, color, position, start_angle, end_angle, width)\r\n pygame.draw.line(screen, color, (x, y), (x-radius,y), width)\r\n pygame.draw.line(screen, color, (x, y) , (x, y+radius), width)\r\n \r\n if piece4:\r\n start_angle = math.radians(270)\r\n end_angle = math.radians(360)\r\n pygame.draw.arc(screen, color, position, start_angle, end_angle, width)\r\n pygame.draw.line(screen, color, (x, y), (x,y+radius), width)\r\n pygame.draw.line(screen, color, (x, y), (x+radius, y), width)\r\n \r\n pygame.display.update()\r\n \r\n if piece1 and piece2 and piece3 and piece4:\r\n compeleted = True\r\n \r\n \r\n ","sub_path":"pie/PieGame.py","file_name":"PieGame.py","file_ext":"py","file_size_in_byte":3979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"77372950","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport xgboost\n\nnp.random.seed(42)\nX = np.random.rand(500, 1) - 0.5\nY = 3 * X[:, 0] ** 2 + 0.05 * np.random.randn(500)\n\nX_train, X_test, Y_train, Y_test = X[:400], X[400:], Y[:400], Y[400:]\nplt.scatter(X, Y)\nplt.show()\n\nxgb_reg = xgboost.XGBRegressor()\nxgb_reg.fit(X_train, Y_train)\nprint(xgb_reg.score(X_test, Y_test))\n\n#can handle early stopping by itself\n\nxgb_reg = xgboost.XGBRegressor(n_estimators=200)\nxgb_reg.fit(X_train, Y_train,\n eval_set=[(X_test,Y_test)],early_stopping_rounds=5)\nprint(xgb_reg.score(X_test, Y_test))\n","sub_path":"Chapter7_Emsemble_learning/XGBoost.py","file_name":"XGBoost.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"226523889","text":"import requests\nimport json\n\ndef get_countries():\n headers = {'Content-Type': 'application/json'}\n api_url = \"https://restcountries.eu/rest/v2/all\"\n\n response = requests.get(api_url, headers=headers)\n\n if response.status_code == 200:\n return json.loads(response.content.decode('utf-8'))\n else:\n return None\n\ndef get_country_code(countries: list, country_name: str):\n for country in countries:\n if country['name'] == country_name:\n return country['alpha3Code']\n return None\n\ndef get_country_currency(countries: list, country_name: str):\n for country in countries:\n if country['name'] == country_name:\n return country['currencies'][0]['code']\n return None\n\ndef transform(name: str):\n countries = get_countries()\n code = get_country_code(countries, name)\n currency = get_country_currency(countries, name)\n\n return {\"name\": name, \"country_code\": code, \"currency_code\": currency}\n\ndef show_country_info():\n idx = 0\n countries = get_countries()\n\n for country in countries:\n print(idx, country['name'])\n idx += 1\n\n print()\n\n selected_country_idx = int(input(\"Please choose a country: \"))\n name = countries[selected_country_idx]['name']\n result = transform(name)\n print(result)\n","sub_path":"mockstub.py","file_name":"mockstub.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"23838306","text":"\n__doc__=\"\"\"N-step Q-learning implementation.\"\"\"\n\nimport theano.tensor as T\nimport theano\nimport numpy as np\n\nfrom lasagne.objectives import squared_error\n\nfrom ..utils.mdp import get_end_indicator, get_action_Qvalues\nfrom ..utils.grad import consider_constant\nfrom ..utils import create_shared, append_dim\n\n\ndefault_gamma = create_shared('n_step_qlearning_gamma_default',np.float32(0.99), theano.config.floatX)\n \ndef get_reference_Qvalues(Qvalues,actions,rewards,is_alive=\"always\",\n qvalues_after_end = \"zeros\",\n n_steps = None,\n gamma_or_gammas = default_gamma,\n aggregation_function = lambda qv:T.max(qv,axis=-1),\n dependencies=[],strict = True):\n \"\"\" computes Qvalues using an N-step q-learning algorithm. \n If n_steps is None, computes \"naive\" RL reference, assuming all actions optimal.\n \n params:\n Qvalues: predicted Qvalues floatx[batch_size,time,action]. \n If n_steps is None(see next), they're unused so you can provide arbitrary(e.g. zero) tensor of that shape.\n \n rewards: immediate rewards floatx[batch_size,time]\n \n is_alive: whether the session is still active int/bool[batch_size,time]\n \n qvalues_after_end - symbolic expression for \"next state q-values\" for last tick used for reference only. \n Defaults at T.zeros_like(Qvalues[:,0,None,:])\n If you wish to simply ignore the last tick, use defaults and crop output's last tick ( qref[:,:-1] )\n \n n_steps: if an integer is given, the references are computed in loops of 3 states.\n Defaults to None: propagating rewards throughout the whole session.\n If n_steps equals 1, this works exactly as Q-learning (though less efficient one)\n If you provide symbolic integer here AND strict = True, make sure you added the variable to dependencies.\n \n \n gamma_or_gammas: delayed reward discount number, scalar or vector[batch_size]\n \n aggregation_function - a function that takes all Qvalues for \"next state qvalues\" term and \n returns what is the \"best next Qvalue\" at the END of n-step cycle. \n Normally you should not touch it.\n Takes input of [batch,n_actions] Qvalues\n\n dependencies: everything you need to evaluate first 3 parameters (only if strict==True)\n strict: whether to evaluate Qvalues using strict theano scan or non-strict one\n returns:\n Q reference [batch,action_at_tick] according to N-step Q_learning\n mentioned here http://arxiv.org/pdf/1602.01783.pdf as Algorithm 3\n\n \"\"\"\n \n if is_alive == \"always\":\n is_alive = T.ones_like(rewards)\n \n if qvalues_after_end == \"zeros\":\n qvalues_after_end = T.zeros_like(Qvalues[:,0,None,:])\n \n\n # Qvalues for \"next\" states (padded with zeros at the session end): float[batch,tick,action]\n next_Qvalues_predicted = T.concatenate(\n [\n Qvalues[:,1:] * append_dim(is_alive[:,1:]),\n qvalues_after_end,\n ],\n axis=1\n )\n \n \n \n \n #recurrent computation of Qvalues reference (backwards through time)\n \n outputs_info = [T.zeros_like(rewards[:,0]),] #start each reference with ZEROS after the end\n \n \n non_seqs = [gamma_or_gammas]+dependencies\n \n time_ticks = T.arange(rewards.shape[1])\n\n sequences = [rewards.T,is_alive.T,\n next_Qvalues_predicted.dimshuffle(1,0,2),#transpose to iterate over time, not over batch\n time_ticks] \n\n def backward_qvalue_step(rewards,is_alive,next_Qpredicted,time_i, \n next_Qref,*args):\n \n \n \n propagated_Qvalues = T.switch(is_alive,\n rewards + gamma_or_gammas * next_Qref, #assumes optimal next action\n 0.\n )\n \n if n_steps is None:\n this_Qref = propagated_Qvalues\n else:\n \n qvalues_at_tmax = T.switch(is_alive,\n rewards + gamma_or_gammas * aggregation_function(next_Qpredicted),\n 0.\n )\n \n this_Qref = T.switch(T.eq(time_i % n_steps,0), #if Tmax\n qvalues_at_tmax, #use special case Qvalues\n propagated_Qvalues #else use generic ones\n )\n \n \n \n \n \n return this_Qref\n\n reference_Qvalues = theano.scan(backward_qvalue_step,\n sequences=sequences,\n non_sequences=non_seqs,\n outputs_info=outputs_info,\n go_backwards=True,\n strict = strict\n )[0] #shape: [time_seq_inverted,batch]\n \n reference_Qvalues = reference_Qvalues.T[:,::-1] #[batch,time_seq]\n \n\n return reference_Qvalues\n\n \ndef get_elementwise_objective(Qvalues,actions,rewards,\n is_alive = \"always\",\n n_steps = None,\n gamma_or_gammas = 0.95,\n force_qvalues_after_end = True,\n qvalues_after_end = \"zeros\",\n consider_reference_constant = True,\n aggregation_function = lambda qv:T.max(qv,axis=-1),\n scan_dependencies = [], scan_strict = True):\n \"\"\"\n Returns squared error between predicted and reference Qvalues according to Q-learning algorithm\n \n Qreference(state,action) = reward(state,action) + gamma* max[next_action]( Q(next_state,next_action) \n loss = mean over (Qvalues - Qreference)**2\n \n parameters:\n \n Qvalues [batch,tick,action_id] - predicted qvalues\n actions [batch,tick] - commited actions\n rewards [batch,tick] - immediate rewards for taking actions at given time ticks\n \n is_alive [batch,tick] - whether given session is still active at given tick. Defaults to always active.\n Default value of is_alive implies a simplified computation algorithm for Qlearning loss\n \n n_steps: if an integer is given, the references are computed in loops of 3 states.\n Defaults to None: propagating rewards throughout the whole session.\n If n_steps equals 1, this works exactly as Q-learning (though less efficient one)\n If you provide symbolic integer here AND strict = True, make sure you added the variable to dependencies.\n \n gamma_or_gammas - a single value or array[batch,tick](can broadcast dimensions) of delayed reward discounts \n \n force_qvalues_after_end - if true, sets reference Qvalues at session end to rewards[end] + qvalues_after_end\n \n qvalues_after_end [batch,1,n_actions] - symbolic expression for \"next state q-values\" for last tick used for reference only. \n Defaults at T.zeros_like(Qvalues[:,0,None,:])\n If you wish to simply ignore the last tick, use defaults and crop output's last tick ( qref[:,:-1] )\n\n consider_reference_constant - whether or not zero-out gradient flow through reference_Qvalues (True highly recommended)\n\n aggregation_function - a function that takes all Qvalues for \"next state qvalues\" term and returns what \n is the \"best next Qvalue\". Normally you should not touch it. Defaults to max over actions.\n Normaly you shouldn't touch this\n Takes input of [batch,n_actions] Qvalues\n\n scan_dependencies: everything you need to evaluate first 3 parameters (only if strict==True)\n scan_strict: whether to evaluate Qvalues using strict theano scan or non-strict one\n Returns:\n \n mean squared error over Qvalues (using formua above for loss)\n\n \"\"\"\n \n #get reference Qvalues via Q-learning algorithm\n reference_Qvalues = get_reference_Qvalues(Qvalues,actions,rewards, is_alive,\n n_steps = n_steps,\n qvalues_after_end = qvalues_after_end,\n gamma_or_gammas = gamma_or_gammas,\n aggregation_function = aggregation_function,\n dependencies = scan_dependencies,\n strict = scan_strict\n )\n \n if consider_reference_constant:\n #do not pass gradient through reference Qvalues (since they DO depend on Qvalues by default)\n reference_Qvalues = consider_constant(reference_Qvalues)\n \n #get predicted qvalues for commited actions (to compare with reference Qvalues)\n action_Qvalues = get_action_Qvalues(Qvalues,actions)\n \n \n \n #if agent is always alive, return the simplified loss\n if is_alive == \"always\":\n \n #tensor of elementwise squared errors\n elwise_squared_error = squared_error(reference_Qvalues,action_Qvalues)\n\n \n \n else: #we are given an is_alive matrix : uint8[batch,tick] \n\n #if asked to force reference_Q[end_tick+1,a] = 0, do it\n #note: if agent is always alive, this is meaningless\n \n if force_qvalues_after_end:\n #set future rewards at session end to rewards+qvalues_after_end\n end_ids = get_end_indicator(is_alive,force_end_at_t_max = True).nonzero()\n\n if qvalues_after_end == \"zeros\":\n # \"set reference Qvalues at end action ids to just the immediate rewards\"\n reference_Qvalues = T.set_subtensor(reference_Qvalues[end_ids],\n rewards[end_ids]\n )\n else:\n last_optimal_rewards = aggregation_function(qvalues_after_end)\n \n # \"set reference Qvalues at end action ids to the immediate rewards + qvalues after end\"\n reference_Qvalues = T.set_subtensor(reference_Qvalues[end_ids],\n rewards[end_ids] + gamma_or_gammas*last_optimal_rewards[end_ids[0],0]\n )\n \n \n #tensor of elementwise squared errors\n elwise_squared_error = squared_error(reference_Qvalues,action_Qvalues)\n\n #zero-out loss after session ended\n elwise_squared_error = elwise_squared_error * is_alive\n\n \n return elwise_squared_error\n ","sub_path":"agentnet/learning/qlearning_n_step.py","file_name":"qlearning_n_step.py","file_ext":"py","file_size_in_byte":11184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"242552451","text":"import argparse\nimport os\nimport sys\nimport random\n\nsys.path.insert(0, os.path.abspath('.'))\nsys.path.insert(0, os.path.abspath('../'))\nsys.path.append(os.pardir)\n\nfrom bilm.training import test, load_options_latest_checkpoint, load_vocab\nfrom bilm.data import LMDataset, BidirectionalLMDataset\nfrom train_config import config\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '1'\n\n\ndef main(args):\n options, ckpt_file = load_options_latest_checkpoint(args.save_dir)\n\n # load the vocab\n if 'char_cnn' in options:\n max_word_length = options['char_cnn']['max_characters_per_token']\n if not options['char_cnn']['n_characters']:\n options['char_cnn']['n_characters'] = 62\n else:\n max_word_length = None\n vocab = load_vocab(args.vocab_file, max_word_length)\n\n test_prefix = args.test_prefix\n\n kwargs = {\n 'test': True,\n 'shuffle_on_load': False,\n }\n\n if options.get('bidirectional'):\n data = BidirectionalLMDataset(test_prefix, vocab, with_tab=True, **kwargs)\n else:\n data = LMDataset(test_prefix, vocab, with_tab=True, **kwargs)\n\n test(options, ckpt_file, data, batch_size=args.batch_size)\n\n\nif __name__ == '__main__':\n test_dir = '/media/scatter/scatterdisk/pingpong/raw_corpus/identified_corpus_20171212/textat/messages.org/00/'\n # test_candidates = random.sample(os.listdir(test_dir), 1)\n # test_prefix = [os.path.join(test_dir, cand, '*') for cand in test_candidates]\n test_sub_dir = os.path.join(test_dir, '73')\n fnames = os.listdir(test_sub_dir)[:10]\n test_prefix = [os.path.join(test_sub_dir, fname) for fname in fnames]\n\n parser = argparse.ArgumentParser(description='Compute test perplexity')\n parser.add_argument('--save_dir', help='Location of checkpoint files')\n parser.add_argument('--vocab_file', help='Vocabulary file', default=config['vocab_file'])\n parser.add_argument('--test_prefix', help='Prefix for test files', default=test_prefix)\n parser.add_argument('--batch_size', type=int, default=64, help='Batch size')\n\n args = parser.parse_args()\n main(args)\n","sub_path":"bin/run_test.py","file_name":"run_test.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"441858911","text":"import os\nimport pandas as pd\n\nurl = 'https://www.openml.org/data/get_csv/20757277/aws-spot-pricing-market.arff'\n\npath = 'data/aws/'\n\nos.makedirs(path, mode=0o777, exist_ok=True)\n\ndf = pd.read_csv(url).query(\"region=='sa-east-1b' and \"\n \"operating_system=='Linux/UNIX' and \"\n \"instance_type=='m3.medium'\")\\\n .drop(['region', 'operating_system',\n 'instance_type'],axis=1)\ndf['year'] = 2017\ndf['date'] = pd.to_datetime(df[['year', 'month', 'day', 'hour', 'minute']])\ndf.set_index('date', inplace=True)\ndf.sort_index(inplace=True)\ndel df['year']\nperiods = 10\ndf['mean'] = df.price.rolling('1H', min_periods=periods,\n closed='right').mean()\ndf['std'] = df.price.rolling('1H', min_periods=periods,\n closed='right').std()\ndf['class'] = (df.price > df['mean'] + df['std']).astype(int)\ndf = df.iloc[periods - 1:]\ndel df['price']\n\nprint(df.head())\nprint(df.tail())\n\ndf.dropna(inplace=True)\nprint(\"Dataframe shape {}\".format(df.shape))\n\ndf.to_csv(path + 'data.csv', index=False)\n","sub_path":"metastream/aws/datawragling.py","file_name":"datawragling.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"195849399","text":"class Solution(object):\n def lengthOfLastWord(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n s = s.strip()\n return len(s.split(' ')[-1]) if s.split(' ')[-1]!='' else 0\n\n# jianchao.li.fighter \n# Reputation: 4,277\n# Well, the basic idea is very simple. Start from the tail of s and move backwards to find \n# the first non-space character. Then from this character, move backwards and count the number \n# of non-space characters until we pass over the head of s or meet a space character. The count \n# will then be the length of the last word.\nclass Solution(object):\n def lengthOfLastWord(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n length = 0\n tail = len(s) - 1\n while (tail >= 0 and s[tail] == ' '):\n tail -=1\n while (tail >= 0 and s[tail] != ' '):\n length+=1\n tail-=1\n return length\n \n","sub_path":"58 Length of Last Word.py","file_name":"58 Length of Last Word.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"352474445","text":"#!/usr/bin/python\n# -*- coding: latin-1 -*-\n\nimport hashlib\nimport base64\nimport datetime\nfrom string import count\n\nclass sensorCrypt(object):\n def __init__(self, vPassword):\n vSalt = 'Qr1#Y'\n vManualKey = vPassword+vSalt\n #self.__lenManKey = len(vManualKey)\n self.__crypt_position = 0\n self.__crypt_position1 = 0\n self.__crypt_position2 = 0\n (self.__crypt_position, self.__crypt_position1, self.__crypt_position2) = self.__GetCryptPosition(len(vManualKey))\n \n print('0: '+ str(self.__crypt_position) + ' # 1: ' + str(self.__crypt_position1) + ' # 2: ' + str(self.__crypt_position2) )\n \n self.__key1 = ''\n self.__key2 = ''\n \n (self.__key1, self.__key2) = self.__EncryptKey(vManualKey+str(self.__crypt_position)) \n\n self.__lenKey1 = len(self.__key1)\n self.__lenKey2 = len(self.__key2)\n\n def Encrypt(self, vString):\n # print'######'\n #print vString\n encrypted1 = base64.b64encode(vString)\n encrypted = encrypted1[:self.__crypt_position1] + self.__key1 + encrypted1[self.__crypt_position1:self.__crypt_position2] + self.__key2 + encrypted1[self.__crypt_position2:]\n #print encrypted\n # print'######'\n return str(encrypted)\n \n def Decrypt(self, vString):\n #ilenMesg = len(vString)\n vBase64a = vString[:self.__crypt_position1] + vString[self.__crypt_position1+self.__lenKey1:]\n vBase64 = vBase64a[:self.__crypt_position2] + vBase64a[self.__crypt_position2+self.__lenKey2:-1]\n #print vBase64\n messageData = base64.b64decode(vBase64)\n # print messageData\n# ilenMesg = len(messageData)\n# message = messageData[self.__lenCryptKey:(ilenMesg-self.__lenCryptKey)]\n# print message\n return messageData\n \n def __GetCryptPosition(self, lenKey):\n vDate1 = datetime.datetime.now().strftime('%d%m')\n vDate2 = datetime.datetime.now().strftime('%Y')\n # print str(vDate1) + '#' + str(vDate2)\n qs0 = self.__querSum(vDate1 + vDate2)\n qs1 = self.__querSum(vDate1)\n #qs2 = self.__querSum(vDate2)\n qs3 = self.__querSum(lenKey)\n # print str(qs0) + '#' + str(qs1) + '#' + str(qs2) + '#' + str(qs3)\n variant1 = int(round(qs0/9))\n variant2 = int(round(int(vDate1)/qs1))\n variant3 = int(round(variant2/(variant1+qs1)))\n # print str(variant1) + '#' + str(variant2) + '#' + str(variant3)\n vResult = qs0 + variant1 + variant3 + qs3\n # print vResult\n if vResult > 150:\n vResult = str(vResult)[-2:]\n # print vResult\n vResult = int(vResult)+7\n vPos1 = int(round(vResult/3))\n vPos2 = int(round(vPos1*2))\n return (vResult, vPos1, vPos2)\n \n def __EncryptKey(self, vManKey):\n # Hash Key\n vEncryptedKey = hashlib.sha512(vManKey).hexdigest()\n # base64 key\n vEncryptedKey = base64.b64encode(vEncryptedKey)\n # Count =\n vCountParts = count(vEncryptedKey,'=')\n # Cut =\n vEncryptedKey = vEncryptedKey[:len(vEncryptedKey)-vCountParts]\n # If needed add filling\n if vCountParts == 1:\n vEncryptedKey += 'A'\n elif vCountParts == 2:\n vEncryptedKey += 'AC'\n elif vCountParts == 3:\n vEncryptedKey += 'iAC'\n \n # Split Key \n viDivider = int(round(len(vEncryptedKey)/3))\n vKeyPart1 = vEncryptedKey[:viDivider]\n vKeyPart2 = vEncryptedKey[viDivider:]\n \n return (vKeyPart1, vKeyPart2)\n \n \n def __querSum(self, vZahl):\n zahlString=str(vZahl)\n querSumme=0\n for zifferBuchstabe in zahlString:\n querSumme=querSumme+int(zifferBuchstabe)\n return querSumme\n \n# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n","sub_path":"python/sensorCrypt.py","file_name":"sensorCrypt.py","file_ext":"py","file_size_in_byte":4295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"417959847","text":"from flask import Blueprint, jsonify, request\n\nfrom project import db\n\nfrom project.api.models import User, Tag, Rating\nfrom project.api.auth import authenticate\n\napp_blueprint = Blueprint(\"app_blueprint\", __name__)\n\n\n@app_blueprint.route(\"/tags\")\ndef tags():\n tags = Tag.query.all()\n response = [tag.to_json() for tag in tags]\n return jsonify(response)\n\n\n@app_blueprint.route(\"/users\")\ndef users():\n users = User.query.all()\n response = [user.to_json() for user in users]\n return jsonify(response)\n\n\n@app_blueprint.route(\"/user/\")\ndef user(user_id):\n user = User.query.filter_by(user_id=user_id).first()\n if user is None:\n response = {}\n response[\"message\"] = \"Invalid user id\"\n return jsonify(response), 404\n return jsonify(user.to_json())\n\n\n@app_blueprint.route(\"/rating\", methods=[\"POST\"])\n@authenticate\ndef rating(user_id):\n response = {}\n request_json = request.get_json()\n\n # Validation\n keys = [\"fromUserId\", \"toUserId\", \"stars\", \"comment\"]\n for key in keys:\n if key not in request_json:\n response[\"message\"] = \"Missing {} key in request body\".format(key)\n return jsonify(response), 400\n\n from_user_id = request_json[\"fromUserId\"]\n to_user_id = request_json[\"toUserId\"]\n if from_user_id == to_user_id or user_id != from_user_id:\n response[\"message\"] = \"Invalid user id\"\n return jsonify(response), 401\n\n from_user = User.query.filter_by(user_id=from_user_id).first()\n to_user = User.query.filter_by(user_id=to_user_id).first()\n if from_user is None or to_user is None:\n response[\"message\"] = \"Invalid user id\"\n return jsonify(response), 404\n\n # Create or Update rating\n rating = Rating.query.filter_by(from_user_id=from_user_id, to_user_id=to_user_id).first()\n create = rating is None\n if create:\n rating = Rating()\n rating.from_user_id = from_user_id\n rating.to_user_id = to_user_id\n rating.stars = request_json[\"stars\"]\n rating.comment = request_json[\"comment\"]\n if create:\n db.session.add(rating)\n response[\"message\"] = \"Rating created successfully\"\n else:\n response[\"message\"] = \"Rating updated successfully\"\n db.session.commit()\n\n return jsonify(response), 200\n","sub_path":"server/project/api/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"280943347","text":"# _*_ coding:utf-8 _*_\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\n\ndef output(movie):\n with open('d:\\\\best250.txt', 'a', encoding='utf-8') as f:\n f.write(\"Rank: %s\\n\" % movie.find('em').text)\n title = movie.find_all('span', class_='title')\n # print(title)\n f.write(\"title: %s\\n\" % title[0].text)\n if len(title) != 1:\n f.write(\"title(en):%s\\n\" % title[1].text)\n f.write(\"other:%s\\n \"% movie.find('span', class_='other'))\n f.write(\"info:%s\\n\" % movie.find('div', class_='bd').find('p').text)\n f.write(\"star:%s\\n\" % movie.find('span', class_='rating_num').text)\n f.write(\"comments:%s\\n\" % movie.find('div', class_='star').find_all('span')[3].text)\n # print(movie.find('span',class_='inq'))\n # print(len(movie.find('span',class_='inq')))\n if movie.find('span',class_='inq') is not None:\n f.write(\"quote:%s\\n\" % movie.find('span',class_='inq').text)\n f.write(\"\\n\\n\")\n\ndef main():\n # headers = {'content-type': 'application/json',\n # 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'}\n for i in range(10):\n print(\"get content from page%i\" % (i+1))\n text = requests.get('https://movie.douban.com/top250?start=%i&filter=&type=' % (i*25))\n text.encoding = 'utf-8'\n soup = BeautifulSoup(text.text, 'lxml')\n soup = soup.find_all('div', class_ ='item')\n # print(soup[1])\n # output(soup[1])\n # break\n for j in range(25):\n # print(movie)\n # print(\"title: %s\\n\" % movie.find('span', class_='title').text)\n # output(soup[j])\n print(soup[j])\n print(soup[j].find('div', class_='bd').find('p').text)\n director = re.compile('导演(.*?)'+'主演(.*?)')\n print(director.findall(soup[j].find('div', class_='bd').find('p').text))\n # print(soup[j].find(text=u'导演'))\n break\n break\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"douban.py","file_name":"douban.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"55734800","text":"import os\nimport numpy as np\n\nimport MapExtrackt\n\nclass ExtractFeatureMaps:\n\n def __init__(self, model ,display_every_n = 10):\n\n self.model = model\n self.display_every_n = display_every_n\n\n #self._extraction()\n\n\n def extraction(self, image_name):\n self.image_name = image_name\n fe = MapExtrackt.FeatureExtractor(self.model)\n fe.set_image(self.image_name)\n\n conv2d_layers_indexes = [i for i,x in enumerate(fe.layer_names) if x == \"Conv2d\"]\n\n desired_indexes = conv2d_layers_indexes[::self.display_every_n]\n\n all_images = []\n\n for index in desired_indexes:\n\n all_images.append(np.array(fe[index]))\n\n\n # print(\"from within map extract, type all images\", type(all_images_stacked))\n return np.asarray(all_images)\n\n\n\n\n","sub_path":"feature_maps_extractor.py","file_name":"feature_maps_extractor.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"611040172","text":"def wildcardmatch_dp(s, p):\n # The DP table and the string s and p use the same indexes i and j, but\n # table[i][j] means the match status between p[:i] and s[:j], i.e.\n # table[0][0] means the match status of two empty strings, and\n # table[1][1] means the match status of p[0] and s[0]. Therefore, when\n # refering to the i-th and the j-th characters of p and s for updating\n # table[i][j], we use p[i - 1] and s[j - 1].\n\n # Initialize the table with False. The first row is satisfied.\n table = [[False] * (len(s) + 1) for _ in range(len(p) + 1)]\n\n # Update the corner case of matching two empty strings.\n table[0][0] = True\n\n for i in range(1, len(p) + 1):\n table[i][0] = table[i - 1][0] and p[i - 1] == '*'\n\n for i in range(1, len(p) + 1):\n for j in range(1, len(s) + 1):\n if p[i - 1] != \"*\":\n # Update the table by referring the diagonal element.\n table[i][j] = table[i - 1][j - 1] and \\\n (p[i - 1] == s[j - 1] or p[i - 1] == '?')\n else:\n # a* or ?* => * matches zero chars\n table[i][j] = table[i - 1][j-1] or table[i][j-1] or table[i-1][j]\n\n for row in table:\n print(row)\n\n return table[-1][-1]\n\n\ns = 'a'\np = 'a*'\n\nprint(wildcardmatch_dp(s, p))\n","sub_path":"datastructures_algorithms/String/String-WildcardPatternMatch.py","file_name":"String-WildcardPatternMatch.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"598063617","text":"import csv\nimport logging\nimport datetime\nimport re\nfrom StringIO import StringIO\n\nimport httplib2\nfrom github2.client import Github\nfrom BeautifulSoup import BeautifulSoup\n\noptions = None\n\nlogging.basicConfig(level=logging.DEBUG)\n\ng_statusre = \\\n '^(' + \\\n 'Issue has not had initial review yet' + '|' + \\\n 'Problem reproduced \\/ Need acknowledged' + '|' + \\\n 'Work on this issue has begun' + '|' + \\\n 'Waiting on feedback or additional information' + '|' + \\\n 'Developer made source code changes, QA should verify' + '|' + \\\n 'QA has verified that the fix worked' + '|' + \\\n 'This was not a valid issue report' + '|' + \\\n 'Unable to reproduce the issue' + '|' + \\\n 'This report duplicates an existing issue' + '|' + \\\n 'We decided to not take action on this issue' + '|' + \\\n 'The requested non-coding task was completed' + \\\n ')$'\n\ndef get_url_content(url):\n h = httplib2.Http(\".cache\")\n resp, content = h.request(url, \"GET\")\n return content\n\nclass IssueComment(object):\n def __init__(self, date, author, body):\n self.created_at = date\n self.body_raw = body\n self.author = author\n self.user = options.github_user_name\n\n @property \n def body (self):\n return (\"%s - %s \\n%s\" % (self.author, self.created_at, self.body_raw)).encode('utf-8')\n\n def __repr__(self):\n return self.body.encode('utf-8')\n \nclass Issue(object):\n\n def __init__(self, issue_line):\n for k,v in issue_line.items():\n setattr(self, k.lower(), v)\n logging.info(\"Issue #%s: %s\" % (self.id, self.summary))\n self.get_original_data() \n\n def parse_date(self, node):\n datenode = node.find(attrs={'class' : 'date'})\n datestring = datenode['title']\n try:\n return datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')\n except ValueError: # if can't parse time, just assume now\n return datetime.datetime.now\n\n def get_user(self, node):\n authornode = node.find(attrs={'class' : 'author'})\n userhrefnode = authornode.find(attrs={'href' : re.compile('^\\/u\\/')})\n return userhrefnode.string\n\n def get_body(self,node):\n comment = unicode(node.find('pre').renderContents(), 'utf-8', 'replace')\n return comment\n\n def get_labels(self, soup):\n self.labels = []\n self.milestones = [] # Milestones are a form of label in googlecode\n for node in soup.findAll(attrs = { 'class' : 'label' }):\n label = unicode(re.sub('<\\/?b>', '', node.renderContents()))\n if re.match('^Milestone-', label):\n self.milestones.append(re.sub('^Milestone-', '', label))\n else:\n self.labels.append(label)\n return\n\n def get_status(self, soup):\n node = soup.find(name = 'span', attrs = { 'title' : re.compile(g_statusre) })\n self.status = unicode(node.string)\n self.labels.append(\"Status-%s\" % self.status)\n return\n\t\n \n def get_original_data(self):\n logging.info(\"GET %s\" % self.original_url)\n content = get_url_content(self.original_url)\n soup = BeautifulSoup(content)\n descriptionnode = soup.find(attrs={'class' : \"cursor_off vt issuedescription\"})\n descriptionstring = unicode(descriptionnode.find('pre').renderContents(), 'utf-8', 'replace')\n self.body = unicode(\"%s
Original link: %s\" % (descriptionstring , self.original_url))\n datenode = descriptionnode.find(attrs={'class' : 'date'})\n datestring = datenode['title']\n try:\n self.created_at = datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')\n except ValueError: # if can't parse time, just assume now\n self.created_at = datetime.datetime.now\n comments = []\n for node in soup.findAll(attrs={'class' : \"cursor_off vt issuecomment\"}):\n try:\n date = self.parse_date(node)\n author = self.get_user(node)\n body = self.get_body(node)\n if not re.match('^\\\\n\\(No comment was entered for this change\\.\\)<\\/i>\\\\n$', body):\n comments.append(IssueComment(date, author, body))\n except:\n pass\n self.comments = comments \n logging.info('got comments %s' % len(comments))\n self.get_labels(soup)\n logging.info('got labels %s' % len(self.labels))\n logging.info('got milestones %s' % len(self.milestones))\n self.get_status(soup)\n\n @property\n def original_url(self): \n gcode_base_url = \"http://code.google.com/p/%s/\" % options.google_project_name\n return \"%sissues/detail?id=%s\" % (gcode_base_url, self.id)\n \n def __repr__(self):\n return u\"%s - %s \" % (self.id, self.summary)\n \ndef download_issues():\n url = \"http://code.google.com/p/\" + options.google_project_name + \"/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary\"\n logging.info('Downloading %s' % url)\n content = get_url_content(url) \n f = StringIO(content)\n return f\n\ndef post_to_github(issue, sync_comments=True):\n logging.info('should post %s', issue)\n github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)\n if issue.status.lower() in \"invalid closed fixed wontfix verified worksforme duplicate done\".lower():\n issue.status = 'closed'\n else:\n issue.status = 'open'\n try: \n git_issue = github.issues.show(options.github_project, int(issue.id))\n logging.warn( \"skipping issue : %s\" % (issue))\n except RuntimeError:\n title = \"%s\" % issue.summary\n logging.info('will post issue:%s' % issue) \n logging.info(\"issue did not exist\")\n git_issue = github.issues.open(options.github_project, \n title = title,\n body = issue.body\n )\n if issue.status == 'closed':\n github.issues.close(options.github_project, git_issue.number)\n if sync_comments is False:\n return git_issue\n old_comments = github.issues.comments(options.github_project, git_issue.number)\n for i,comment in enumerate(issue.comments):\n\n exists = False\n for old_c in old_comments: \n # issue status changes have empty bodies in google code , exclude those:\n if bool(old_c.body) or old_c.body == comment.body :\n exists = True\n logging.info(\"Found comment there, skipping\")\n break\n if not exists:\n #logging.info('posting comment %s', comment.body.encode('utf-8'))\n try:\n github.issues.comment(options.github_project, git_issue.number, comment)\n except:\n logging.exception(\"Failed to post comment %s for issue %s\" % (i, issue))\n \n return git_issue \n \ndef process_issues(issues_csv, sync_comments=True):\n reader = csv.DictReader(issues_csv)\n issues = [Issue(issue_line) for issue_line in reader]\n [post_to_github(i, sync_comments) for i in issues]\n \n\nif __name__ == \"__main__\":\n import optparse \n import sys \n usage = \"usage: %prog [options]\"\n parser = optparse.OptionParser(usage)\n parser.add_option('-g', '--google-project-name', action=\"store\", dest=\"google_project_name\", help=\"The project name (from the URL) from google code.\")\n parser.add_option('-t', '--github-api-token', action=\"store\", dest=\"github_api_token\", help=\"Yout Github api token\")\n parser.add_option('-u', '--github-user-name', action=\"store\", dest=\"github_user_name\", help=\"The Github username\")\n parser.add_option('-p', '--github-project', action=\"store\", dest=\"github_project\", help=\"The Github project name:: user-name/project-name\")\n global options\n options, args = parser.parse_args(args=sys.argv, values=None)\n try: \n issues_data = download_issues()\n process_issues(issues_data)\n except:\n parser.print_help() \n raise","sub_path":"migrateissues.py","file_name":"migrateissues.py","file_ext":"py","file_size_in_byte":8351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"583222125","text":"from typing import TypeVar, NewType\nfrom Cinema.BuildingBlocks import _Foundation, Film, Gebruiker, Reservatie, Vertoning, Zaal\n\n\n_BuildingBlock = TypeVar(\"_BuildingBlock\", bound=_Foundation)\n_FilmType = NewType('_FilmType', Film)\n_GebruikerType = NewType('_GebruikerType', Gebruiker)\n_ReservatieType = NewType('_ReservatieType', Reservatie)\n_VertoningType = NewType('_VertoningType', Vertoning)\n_ZaalType = NewType('_ZaalType', Zaal)","sub_path":"Robin/Types.py","file_name":"Types.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"651920576","text":"'''\nGym[atari]確認用プログラム(パックマン)\nCopyright(c) 2020 Koji Makino and Hiromitsu Nishizaki All Rights Reserved.\n'''\nimport gym\nenv = gym.make('MsPacman-v0')\nenv.reset()\nfor _ in range(1000):\n env.render()\n env.step(env.action_space.sample())\n","sub_path":"tensor_flow/program/ch1/Openai_test_pm/openai_test_pm.py","file_name":"openai_test_pm.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"283614752","text":"#!/usr/bin/env python\n#\n\"\"\"\nprovides two classes:\n MotorPanel: a wx panel for an Epics Motor, ala medm Motor row\n\n makes use of these modules\n wxlib: extensions of wx.TextCtrl, etc for epics PVs\n Motor: Epics Motor class\n\"\"\"\n# Aug 21 2004 M Newville: initial working version.\n#\nimport wx\nfrom wx._core import PyDeadObjectError\nimport epics\nfrom epics.wx.wxlib import PVText, PVFloatCtrl, PVButton, PVComboBox, \\\n DelayedEpicsCallback, EpicsFunction\n\nfrom epics.wx.motordetailframe import MotorDetailFrame\n\nfrom epics.wx.utils import LCEN, RCEN, CEN, LTEXT, RIGHT, pack, add_button\n\nclass MotorPanel(wx.Panel):\n \"\"\" MotorPanel a simple wx windows panel for controlling an Epics Motor\n\n use psize='full' (defaiult) for full capabilities, or\n 'medium' or 'small' for minimal version\n \"\"\"\n __motor_fields = ('SET', 'disabled', 'LLM', 'HLM', 'LVIO', 'TWV',\n 'HLS', 'LLS', 'SPMG', 'DESC')\n\n def __init__(self, parent, motor=None, psize='full',\n messenger=None, prec=None, **kw):\n\n wx.Panel.__init__(self, parent, style=wx.TAB_TRAVERSAL)\n self.parent = parent\n\n if hasattr(messenger, '__call__'):\n self.__messenger = messenger\n\n self.format = None\n if prec is not None:\n self.format = \"%%.%if\" % prec\n\n self.motor = None\n self._size = 'full'\n if psize in ('medium', 'small'):\n self._size = psize\n self.__sizer = wx.BoxSizer(wx.HORIZONTAL)\n self.CreatePanel()\n\n if motor is not None:\n try:\n self.SelectMotor(motor)\n except PyDeadObjectError:\n pass\n\n\n\n @EpicsFunction\n def SelectMotor(self, motor):\n \" set motor to a named motor PV\"\n if motor is None:\n return\n\n epics.poll()\n try:\n if self.motor is not None:\n for i in self.__motor_fields:\n self.motor.clear_callback(attr=i)\n except PyDeadObjectError:\n return\n\n if isinstance(motor, (str, unicode)):\n self.motor = epics.Motor(motor)\n elif isinstance(motor, epics.Motor):\n self.motor = motor\n self.motor.get_info()\n\n\n if self.format is None:\n self.format = \"%%.%if\" % self.motor.PREC\n self.FillPanel()\n for attr in self.__motor_fields:\n self.motor.get_pv(attr).add_callback(self.OnMotorEvent,\n wid=self.GetId(),\n field=attr)\n if self._size == 'full':\n self.SetTweak(self.format % self.motor.TWV)\n\n @EpicsFunction\n def FillPanelComponents(self):\n epics.poll()\n try:\n if self.motor is None:\n return\n except PyDeadObjectError:\n return\n\n self.drive.SetPV(self.motor.PV('VAL'))\n self.rbv.SetPV(self.motor.PV('RBV'))\n self.desc.SetPV(self.motor.PV('DESC'))\n\n descpv = self.motor.PV('DESC').get()\n self.desc.Wrap(45)\n if self._size == 'full':\n self.twf.SetPV(self.motor.PV('TWF'))\n self.twr.SetPV(self.motor.PV('TWR'))\n elif len(descpv) > 20:\n font = self.desc.GetFont()\n font.PointSize -= 1\n self.desc.SetFont(font)\n\n self.info.SetLabel('')\n for f in ('SET', 'LVIO', 'SPMG', 'LLS', 'HLS', 'disabled'):\n uname = self.motor.PV(f).pvname\n wx.CallAfter(self.OnMotorEvent,\n pvname=uname, field=f)\n\n def CreatePanel(self):\n \" build (but do not fill in) panel components\"\n wdesc, wrbv, winfo, wdrv = 200, 105, 90, 120\n if self._size == 'medium':\n wdesc, wrbv, winfo, wdrv = 140, 85, 80, 100\n elif self._size == 'small':\n wdesc, wrbv, winfo, wdrv = 70, 60, 30, 80\n\n self.desc = PVText(self, size=(wdesc, 25), style=LTEXT)\n self.desc.SetForegroundColour(\"Blue\")\n font = self.desc.GetFont()\n font.PointSize -= 1\n self.desc.SetFont(font)\n\n self.rbv = PVText(self, size=(wrbv, 25), fg='Blue', style=RCEN)\n self.info = wx.StaticText(self, label='',\n size=(winfo, 25), style=RCEN)\n self.info.SetForegroundColour(\"Red\")\n\n self.drive = PVFloatCtrl(self, size=(wdrv, -1), style = wx.TE_RIGHT)\n\n try:\n self.FillPanelComponents()\n except PyDeadObjectError:\n return\n\n spacer = wx.StaticText(self, label=' ', size=(5, 5), style=RIGHT)\n self.__sizer.AddMany([(spacer, 0, CEN),\n (self.desc, 1, LCEN),\n (self.info, 0, CEN),\n (self.rbv, 0, CEN),\n (self.drive, 0, CEN)])\n\n if self._size == 'full':\n self.twk_list = ['','']\n self.__twkbox = wx.ComboBox(self, value='', size=(100, -1),\n choices=self.twk_list,\n style=wx.CB_DROPDOWN|wx.TE_PROCESS_ENTER)\n self.__twkbox.Bind(wx.EVT_COMBOBOX, self.OnTweakBoxComboEvent)\n self.__twkbox.Bind(wx.EVT_TEXT_ENTER, self.OnTweakBoxEnterEvent)\n\n self.twr = PVButton(self, label='<', size=(30, 30))\n self.twf = PVButton(self, label='>', size=(30, 30))\n\n self.stopbtn = add_button(self, label=' Stop ', action=self.OnStopButton)\n self.morebtn = add_button(self, label=' More ', action=self.OnMoreButton)\n\n self.__sizer.AddMany([(self.twr, 0, CEN),\n (self.__twkbox, 0, CEN),\n (self.twf, 0, CEN),\n (self.stopbtn, 0, CEN),\n (self.morebtn, 0, CEN)])\n\n self.SetAutoLayout(1)\n pack(self, self.__sizer)\n\n @EpicsFunction\n def FillPanel(self):\n \" fill in panel components for motor \"\n try:\n if self.motor is None:\n return\n self.FillPanelComponents()\n self.drive.Update()\n self.desc.Update()\n self.rbv.Update()\n if self._size == 'full':\n self.twk_list = self.make_step_list()\n self.UpdateStepList()\n except PyDeadObjectError:\n pass\n\n @EpicsFunction\n def OnStopButton(self, event=None):\n \"stop button\"\n if self.motor is None:\n return\n\n curstate = str(self.stopbtn.GetLabel()).lower().strip()\n if curstate == 'stop':\n self.motor.stop()\n epics.poll()\n else:\n self.motor.SPMG = 3\n \n @EpicsFunction\n def OnMoreButton(self, event=None):\n \"more button\"\n if self.motor is not None:\n MotorDetailFrame(parent=self, motor=self.motor)\n\n @DelayedEpicsCallback\n def OnTweakBoxEnterEvent(self, event=None):\n val = float(self.__twkbox.GetValue())\n wx.CallAfter(self.motor.PV('TWV').put, val)\n\n @DelayedEpicsCallback\n def OnTweakBoxComboEvent(self, event=None):\n val = float(self.__twkbox.GetValue())\n wx.CallAfter(self.motor.PV('TWV').put, val)\n\n @DelayedEpicsCallback\n def OnMotorEvent(self, pvname=None, field=None, event=None, **kws):\n if pvname is None:\n return None\n\n field_val = self.motor.get(field)\n field_str = self.motor.get(field, as_string=True)\n\n if field == 'LLM':\n self.drive.SetMin(self.motor.LLM)\n elif field == 'HLM':\n self.drive.SetMax(self.motor.HLM)\n\n elif field in ('LVIO', 'HLS', 'LLS'):\n s = 'Limit!'\n if field_val == 0:\n s = ''\n self.info.SetLabel(s)\n\n elif field == 'SET':\n label, color = 'Set:','Yellow'\n if field_val == 0:\n label, color = '','White'\n self.info.SetLabel(label)\n self.drive.bgcol_valid = color\n self.drive.SetBackgroundColour(color)\n self.drive.Refresh()\n\n elif field == 'disabled':\n label = ('','Disabled')[field_val]\n self.info.SetLabel(label)\n\n elif field == 'DESC':\n font = self.rbv.GetFont()\n if len(field_str) > 20:\n font.PointSize -= 1\n self.desc.SetFont(font)\n\n elif field == 'TWV' and self._size == 'full':\n self.SetTweak(field_str)\n\n elif field == 'SPMG' and self._size == 'full':\n label, info, color = 'Stop', '', 'White'\n if field_val == 0:\n label, info, color = ' Go ', 'Stopped', 'Yellow'\n elif field_val == 1:\n label, info, color = ' Resume ', 'Paused', 'Yellow'\n elif field_val == 2:\n label, info, color = ' Go ', 'Move Once', 'Yellow'\n self.stopbtn.SetLabel(label)\n self.info.SetLabel(info)\n self.stopbtn.SetBackgroundColour(color)\n self.stopbtn.Refresh()\n\n else:\n pass\n\n @EpicsFunction\n def SetTweak(self, val):\n if not isinstance(val, str):\n val = self.format % val\n try:\n if val not in self.twk_list:\n self.UpdateStepList(value=val)\n self.__twkbox.SetValue(val)\n except PyDeadObjectError:\n pass\n\n def make_step_list(self):\n \"\"\" create initial list of motor steps, based on motor range\n and precision\"\"\"\n if self.motor is None:\n return []\n return [self.format % i for i in self.motor.make_step_list()]\n\n def UpdateStepList(self, value=None):\n \"add a value and re-sort the list of Step values\"\n if value is not None:\n self.twk_list.append(value)\n x = [float(i) for i in self.twk_list]\n x.sort()\n self.twk_list = [self.format % i for i in x]\n # remake list in TweakBox\n self.__twkbox.Clear()\n self.__twkbox.AppendItems(self.twk_list)\n","sub_path":"Python/epics/wx/motorpanel.py","file_name":"motorpanel.py","file_ext":"py","file_size_in_byte":10164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"14580674","text":"import requests\nfrom urllib.parse import urlencode\nimport traceback\nimport os\nfrom hashlib import md5\n\n\nbase_url = \"https://www.toutiao.com/search_content/?\"\n\n\namount_size = 20\n\ndef get_page(offset):\n\tparams = {\n\t\t'offset' : offset,\n\t\t'format' : 'json',\n\t\t'keyword' : '街拍',\n\t\t'autoload' : 'true',\n\t\t'count' : '20',\n\t\t'cur_tab' : '1',\n\t\t'from' : 'search_tab',\n\t\t}\t\n\turl = base_url + urlencode(params)\n\ttry:\n\t\tresponse = requests.get(url)\n\t\tif response.status_code == 200:\n\t\t\treturn response.json()\n\texcept requests.ConnectionError as e:\n\t\ttraceback.print_exc()\n\t\treturn\n\ndef get_images(json):\n\tif json.get(\"data\"):\n\t\tfor item in json.get(\"data\"):\n\t\t\tif item.get(\"cell_type\") is not None:\n\t\t\t\tcontinue\n\t\t\ttitle = item.get(\"title\")\n\t\t\timages = item.get(\"image_list\")\n\t\t\ttry:\n\t\t\t\tfor image in images:\n\t\t\t\t\tyield{\n\t\t\t\t\t\t\"image\":image.get(\"url\"),\n\t\t\t\t\t\t\"title\":title\n\t\t\t\t \t}\n\t\t\texcept TypeError:\n\t\t\t\tcontinue\n\ndef save_image(item):\n\tif not os.path.exists(item.get(\"title\")):\n\t\tos.mkdir(item.get(\"title\"))\n\ttry:\n\t#这里要加一个http:要不然会报错requests.exceptions.MissingSchema: Invalid URL 'xxxxxxxxxxxxx': No schema supplied. Perhaps you meant xxxxxxxxxxxxx\n\t\tresponse = requests.get(\"http:\" + item.get(\"image\"))\n\t\tif response.status_code == 200:\n\t\t\tfile_path = \"{0}/{1}.{2}\".format(item.get(\"title\"), md5(response.content).hexdigest(), \"jpg\")\n\t\t\tif not os.path.exists(file_path):\n\t\t\t\twith open(file_path, \"wb\") as f:\n\t\t\t\t\tf.write(response.content)\n\t\t\telse:\n\t\t\t\tprint(\"Already Downloaded\", file_path)\n\texcept requests.ConnectionError as e:\n\t\ttracebace.print_exc()\n\n\ndef main():\n\tfor page in range(1, amount_size):\n\t\tjson = get_page(page)\n\t\tfor item in get_images(json):\n\t\t\tprint(item)\n\t\t\tsave_image(item)\n\t\t\n\t\n\nif __name__ == \"__main__\":\n\tmain()\n\n","sub_path":"tupian.py","file_name":"tupian.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"478202549","text":"from math import sqrt\n\n\ndef is_divisible(n, primes):\n \"\"\"\n Checks wether a given number n is divisible by all the numbers in a list\n smaller than the square root of itself. Return True if n is divisible by at\n least one element and False if it's not divisible by any of them\n\n Arguments:\n n = given number to check\n primes = list of numbers to check the divisibility by\n \"\"\"\n check = False\n Max = sqrt(n)\n for i in primes:\n\n if i > Max:\n return False\n\n if n % i == 0:\n check = True\n break\n else:\n check = False\n\n return check\n\n\ndef find_primes(N):\n \"\"\"\n Returns a list of prime numbers up to a given number N.\n\n It uses the is_divisible function to check, for every number between 3 and\n N, if it's divisible by any other prime in the list, if it doesn't it's\n appended to the 'primes' list\n \"\"\"\n if N < 2:\n ret = \"There are no prime numbers smaller than \" + str(N)\n return ret\n\n primes = [2]\n for i in range(3, N + 1, 2):\n if not is_divisible(i, primes): # not divisible by any other prime\n primes.append(i) # append it to the list\n return primes\n\n\ndef brun(N):\n \"\"\"\n Returns the Brun's constant calculated used the primes up to a given N\n\n The Brun's constant is calculated as the sum of the reciprocal of all pairs\n of twin prime numbers (difference 2)\n \"\"\"\n sum = 0\n lastP = 1\n primes = find_primes(N) # creates the list of prime up to N\n for i in primes:\n if i - lastP == 2: # checks for two consecutive elements if they're twin primes\n sum = sum + (1/lastP + 1/i)\n lastP = i\n return sum # the returned sum is the Brun's constant requested\n\n\nprint(find_primes(200))\nprint()\nprint(brun(10**6))\n","sub_path":"Python/Coursework1/brun.py","file_name":"brun.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"333816427","text":"import random\nimport pathlib\nimport json\nimport itertools\nimport numpy as np\nimport pickle\nimport math\nimport torch\nimport jellyfish\nimport pickle\nfrom os import path\n\nimport os, shutil\n\nfrom imgCls import *\n\n\n# a helper function..\ndef pt_info(ot):\n print(\"Size: \",ot.size(),\" Data type: \", ot.dtype,\" Device: \",ot.device, \" Requires grad: \", ot.requires_grad)\n return\n\nclass DeepSpellingChecker:\n #ky_dct = load_keys(dr_lc)\n def __init__(self,encode_dir,net_dir):\n self.encode_dir = encode_dir\n self.net_dir = net_dir\n self.ky_dct = load_keys(encode_dir)\n self.mapp = None\n return\n def encode_image(self,wrd):\n return encode_word(wrd,self.ky_dct)\n def create_word_mistake(self,wrd):\n return word_mix(wrd)\n def can_use_gpu(self):\n return torch.cuda.is_available()\n def train_words(self,wrd_list):\n rt_name = \"mdl_spelling\"\n dcMapping = {}\n maxDepth = 30\n wrl = WordManage()\n wrl.set_words(wrd_list,0)\n # clean out the network directory\n delete_files_dir(self.net_dir)\n # \n train_and_choose(rt_name,wrl,dcMapping,maxDepth,self.net_dir)\n \n file_path = self.mapping_file()\n \n save_json(dcMapping,file_path)\n \n self.mapp = dcMapping\n return \n \n def mapping_file(self):\n return os.path.join(self.net_dir, \"word_tree_mapping.json\")\n \n def best_word_match(self,wrd,dbg=False):\n \n file_path = self.mapping_file()\n \n if self.mapp == None:\n self.mapp = load_json(file_path)\n \n rt_name = \"mdl_spelling\"\n \n wd = spell_word(wrd,rt_name,self.mapp,self.net_dir, dbg)\n \n if len(wd) > 1:\n srt = sorted(wd,key=lambda ky : jellyfish.damerau_levenshtein_distance(wrd,ky))\n if dbg:\n print(\"matches... \",srt)\n return srt[0]\n else:\n return wd[0]\n \n def print_network_layout(self):\n print(ImgNet(5))\n return\n\n \n\n# This class manages the list of words that are being trained..\nclass WordManage():\n # load a file of words to train.\n def load(self,flnm):\n self._wrds = {}\n with open(flnm,\"r\") in fl:\n self._wrds = { wrd : 0 for wrd in fl.readlines() }\n return\n \n # choose n words from the list\n def choose_words(self,nm):\n lst = [wrd for wrd in self._wrds.keys()]\n return random.sample(lst,min(nm,len(lst)))\n \n # filter by a category\n def filter_list(self, category):\n wrd = WordManage()\n dc = { wrd : category for (wrd,itm) in self._wrds.items() if itm == category }\n wrd.set_dic(dc)\n return wrd\n \n # set the hidden dictionary for the managed list\n def set_dic(self,dc):\n self._wrds = dc\n return\n \n # get a list of available words\n def all_words(self):\n return [k for k in self._wrds.keys()]\n \n # set category value for a list of words (alternative to load method)\n def set_words(self,wrds,category):\n self._wrds = { wrd : category for wrd in wrds }\n return\n \n # sets a words category\n def set_category(self,wrd,vlu):\n if not type(wrd)==str:\n raise Exception(\"Bad set type\",str(type(wrd)))\n \n self._wrds[wrd] = vlu\n return\n \n # number of words\n def word_count(self):\n return len(self._wrds.keys())\n \ndef load_keys(dr_loc=\"\"):\n kvy = None\n pth = \"\"\n if len(dr_loc) == 0: \n pth = pathlib.Path(__file__).parent.absolute()\n pth = str(pth) + \"/encoding_keys.json\"\n else:\n pth = pth + \"/encoding_keys.json\"\n \n with open(pth,\"r\") as fl:\n data = fl.read()\n kyv = json.loads(data)\n \n return kyv\n\n\ndef delete_files_dir(folder):\n for filename in os.listdir(folder):\n file_path = os.path.join(folder, filename)\n try:\n if os.path.isfile(file_path) or os.path.islink(file_path):\n os.unlink(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path)\n except Exception as e:\n print('Failed to delete %s. Reason: %s' % (file_path, e))\n \n\ndef encode_word_keys(txt,k1,k2,k3):\n c,c2,c3 = \"\",\"\",\"\"\n WIDTH = 256\n lyr = np.zeros((3,WIDTH),np.float32)\n txt = txt.lower()\n ln = len(txt)\n \n if ln > WIDTH - 1:\n raise Exception(\"text to long..\")\n \n strt = int((WIDTH/2)-(ln/2)) \n \n mnv,mxv = min(k1.values()),max(k1.values())\n \n mnv2,mxv2 = min(k2.values()),max(k2.values())\n \n mnv3,mxv3 = min(k3.values()),max(k3.values())\n \n for c in txt:\n if not c in k1:\n c2 = \"\"\n c3 = \"\"\n strt = strt + 1\n continue\n #print(c, \" = \", math.log(k1[c]))\n \n nv = -2 + (4.0 / (mxv - mnv)) * (k1[c] - mnv)\n lyr[1][strt] = nv\n \n #lyr[1][strt] = math.log(k1[c])/(-7.0)\n \n #enc.append(math.log(k1[c])/(-7.0))\n c2 = c2 + c\n c3 = c3 + c\n if len(c2) > 2:\n c2 = c2[1:]\n if len(c3) > 3:\n c3 = c3[1:]\n \n if len(c2) == 2: # and math.log(k2[c2]) < -5.5:\n #vl = math.log(k2[c2]) / (-15.0)\n #print(\"somewhat rare\",c2, \" = \",math.log(k2[c2]), \" vl = \",vl)\n \n vl = -1 + (2.0 / (mxv2 - mnv2)) * (k2[c2] - mnv2)\n \n lyr[0][strt-1] = lyr[0][strt-1] + vl\n lyr[0][strt] = lyr[0][strt] + vl\n \n #enc.append(math.log(k2[c2])/(-15.0))\n \n if len(c3) == 3: # and math.log(k3[c3]) < -7.5:\n #vl = math.log(k3[c3]) / (-16.0)\n vl = -1 + (2.0 / (mxv3 - mnv3)) * (k3[c3] - mnv3)\n #print(\"rare..\",c3, \" \", math.log(k3[c3]), \" vl = \",vl)\n lyr[2][strt-2] = lyr[2][strt-2] + vl\n lyr[2][strt-1] = lyr[2][strt-1] + vl\n lyr[2][strt] = lyr[2][strt]\n #enc.append(math.log(k3[c3])/(-16.0))\n \n strt = strt + 1\n return lyr\n\n\nky_dct = None\n\ndef encode_word(wrd,ky_dct=None,dr_lc=\"\"):\n #global ky_dct\n \n if ky_dct is None:\n ky_dct = load_keys(dr_lc)\n \n return encode_word_keys(wrd,ky_dct['ky'],ky_dct['ky2'],ky_dct['ky3'])\n\ndef best_device():\n return torch.device(type= \"cuda\" if torch.cuda.is_available() else \"cpu\")\n\ndef tensor_info(tn):\n return (tn.device,tn.shape,tn.dtype)\n\ndef best_move(tn): \n return tn.to(best_device())\n\ndef numpy_to_tensor(nn_ar):\n ar = torch.from_numpy(nn_ar)\n ar = best_move(ar)\n return ar\n\ndef remove_letter(wd):\n if len(wd) < 5:\n return wd\n cs = random.randint(0,len(wd)-1)\n return wd[0:cs] + wd[cs+1:]\n\ndef swap_letter(wd):\n if len(wd) < 3:\n return wd\n cs = random.randint(0,len(wd)-2)\n wd = list(wd)\n t = wd[cs]\n wd[cs] = wd[cs+1]\n wd[cs+1] = t\n \n tmp = \"\"\n \n return tmp.join(wd)\n\ndef change_letter(wd): \n if len(wd) < 4:\n return wd\n \n alpha = ['a','b','c','d','e','f','g', \\\n 'h','i','j','k','l','m','n','o','p','q','r', \\\n 's','t','u','v','w','x','y','z']\n cs = random.randint(0,len(wd)-1)\n\n wd = list(wd)\n \n wd[cs] = alpha[random.randint(0,25)]\n \n tmp = \"\"\n \n return tmp.join(wd)\n\n\ndef drop_letter(wd):\n if len(wd) < 5:\n return wd\n cs = random.randint(0,len(wd)-2)\n \n wd = list(wd)\n \n wd[cs] = ' '\n \n tmp = \"\"\n \n return tmp.join(wd)\n\ndef add_letter(wd):\n if len(wd) < 3:\n return wd\n \n #print(\"add letter\")\n cs = random.randint(0,len(wd)-2)\n \n #wd = [w for w in wd]\n \n alpha = ['a','b','c','d','e','f','g', \\\n 'h','i','j','k','l','m','n','o','p','q','r', \\\n 's','t','u','v','w','x','y','z']\n \n #ln = len(wd)\n wd = wd[0:cs] + alpha[random.randint(0,25)] + wd[cs:] \n \n return wd \n\n\ndef word_mix(wd):\n fc_ar = [remove_letter,swap_letter,change_letter,drop_letter,add_letter]\n #wd = wd\n \n if random.random() < 0.50:\n wd = fc_ar[random.randint(0,4)](wd)\n \n if random.random() < 0.30:\n wd = fc_ar[random.randint(0,4)](wd)\n \n if random.random() < 0.20:\n wd = fc_ar[random.randint(0,4)](wd)\n \n if random.random() < 0.1:\n wd = fc_ar[random.randint(0,4)](wd)\n \n return wd\n\n\ndef name_path(name):\n return \"./net_data/\" + name + \".bin\"\n\ndef save_network(ntwrk,name,pth=None):\n \n if pth==None:\n nt_path = name_path(name)\n else:\n nt_path = os.path.join(pth, (name + \".bin\"))\n \n torch.save(ntwrk.state_dict(),nt_path)\n return\n\ndef load_network(name,pth=None):\n \n if pth==None:\n nt_path = name_path(name)\n else:\n nt_path = os.path.join(pth, filename)\n \n return torch.load(nt_pth)\n\n\ndef load_data_into(model,name):\n model.load_state_dict(load_network(name))\n model.eval()\n return\n\n\ndef load_file_into_model(mdl,pth):\n data = torch.load(pth)\n mdl.load_state_dict(data)\n mdl.eval()\n return\n\ndef get_category(ntwrk,wrds,btch=64,dbg=False):\n ntwrk.eval()\n tmp = []\n with torch.no_grad():\n for b in batch(wrds,btch):\n #print(b)\n if dbg:\n print(\"batch.. \",b)\n \n bts = word_batch(b)\n tn_bts = numpy_to_tensor(bts)\n #print(tensor_info(tn_bts))\n rslts = ntwrk(tn_bts)\n if dbg:\n print(\"result..\")\n print(rslts)\n #rv = rslts.argmax(dim=1)\n #print(rv)\n tmp.append(rslts.argmax(dim=1).cpu().numpy())\n \n return np.concatenate(tmp,axis=0)\n\ndef batch(iterable, n=1):\n l = len(iterable)\n for ndx in range(0, l, n):\n yield iterable[ndx:min(ndx + n, l)]\n \ndef word_batch(wrds):\n tmp = []\n for wr in wrds:\n \n #print(type(wr))\n \n wrd = encode_word(wr)\n wrd = np.expand_dims(wrd,axis=0)\n tmp.append(wrd)\n \n return np.stack(tmp,axis=0)\n \ndef total_string_distance(t):\n tmp = []\n for a,b in itertools.permutations(t,2):\n tmp.append(jellyfish.damerau_levenshtein_distance(a,b) ** 2) \n return sum(tmp)\n\ndef choose_spread_combo(nm,wrl):\n bts = []\n sms = []\n for i in range(75):\n t = wrl.choose_words(nm)\n bts.append(t)\n sms.append(total_string_distance(t))\n # print(sms,np.argmax(sms))\n return bts[np.argmax(sms)]\n \n \ndef build_net_opt_schedule(out_cat=5):\n ntwrk = ImgNet(out_cat)\n ntwrk = best_move(ntwrk)\n optimizer = optim.Adadelta(ntwrk.parameters(), lr=0.80)\n scheduler = StepLR(optimizer, step_size=1, gamma=0.965)\n \n return (ntwrk,optimizer,scheduler)\n\ndef train_loop(epoch,tn_in,tn_arg, model, optimizer, scheduler,dbg): \n \n example_size = tn_arg.shape[0]\n example_indexes = [x for x in range(example_size)]\n for i in range(epoch):\n for b in batch(example_indexes,512):\n #print(b[0],b[-1])\n \n optimizer.zero_grad()\n \n data = tn_in[b[0]:b[-1]]\n target = tn_arg[b[0]:b[-1]]\n \n #print(\"training data \",data.shape)\n \n data = numpy_to_tensor(data)\n target = numpy_to_tensor(target)\n \n output = model(data)\n \n loss = F.nll_loss(output,target)\n loss.backward()\n \n optimizer.step()\n \n scheduler.step()\n if dbg:\n print(\"lr.. \",scheduler.get_lr())\n \n\ndef build_choose_and_train(wrl,dbg=False,out_cat=5):\n out_num = 5\n targ_arr = []\n in_arr = []\n wrds = choose_spread_combo(out_num, wrl)\n \n for en,v in enumerate(wrds):\n targ_arr.append(en)\n wrd = encode_word(v)\n wrd = np.expand_dims(wrd,axis=0)\n in_arr.append(wrd)\n if dbg:\n print(\"word \",v,\" category \",en)\n \n \n for i in range(400):\n for en,v in enumerate(wrds):\n targ_arr.append(en)\n wd = word_mix(v)\n #if dbg:\n # print(\"word \",v,\" mix \",wd,\" category \",en)\n wrd = encode_word(wd)\n wrd = np.expand_dims(wrd,axis=0)\n in_arr.append(wrd)\n \n \n if dbg:\n print(\"length of input.. \",len(in_arr))\n \n tn_in, tn_trg = np.stack(in_arr),np.array(targ_arr,dtype=np.long)\n \n epoch = 5\n \n # example_size = len(targ_arr)\n # example_indexes = [x for x in range(example_size)]\n \n model, optimizer, scheduler = build_net_opt_schedule(out_cat)\n \n train_loop(epoch,tn_in,tn_trg, model, optimizer, scheduler,dbg)\n \n \n if dbg:\n print(\"second half training..\")\n \n # choose category based on the partially trained model..\n \n \n for i in range(4):\n all_wrds = wrl.all_words()\n cat_w = get_category(model,all_wrds)\n \n #for i,ct in enumerate(cat_w):\n cat_list = [[all_wrds[v] for v,ct in enumerate(cat_w) if ct == i ] for i in range(out_cat)]\n \n in_arr = []\n targ_arr = []\n \n epoch = 5\n \n for _ in range(125):\n for i in range(out_cat):\n #print(\"lenght list \",len(cat_list[i]))\n lst = random.sample(cat_list[i], k=min(len(cat_list[i]),30))\n #print(len(lst))\n \n for w in lst:\n targ_arr.append(i)\n wd = word_mix(w)\n wrd = encode_word(wd)\n wrd = np.expand_dims(wrd,axis=0)\n in_arr.append(wrd)\n \n tn_in, tn_trg = np.stack(in_arr),np.array(targ_arr,dtype=np.long)\n \n if dbg:\n print(\"input shape.. \",tn_in.shape)\n \n train_loop(epoch,tn_in,tn_trg, model, optimizer, scheduler,dbg)\n \n \n if dbg:\n model.eval()\n with torch.no_grad():\n example_size = tn_trg.shape[0]\n example_indexes = [x for x in range(example_size)]\n \n for b in batch(example_indexes,256):\n data = tn_in[b[0]:b[-1]]\n target = tn_trg[b[0]:b[-1]]\n \n data = numpy_to_tensor(data)\n target = numpy_to_tensor(target)\n output = model(data)\n \n # test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss\n pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n correct = pred.eq(target.view_as(pred)).sum().item()\n \n print(\"correct on batch.. \", (100.0 * correct) / len(b))\n return model\n\n\n# rtTreeName contains the name of the network to load \n# avWords (instance of WordManage) contains the list of available words.\n# wdDic contains the chosen words root network choice\n# maxDepth\ndef train_and_choose(rtTreeName, avWords, wdDic, maxDepth,pth=None,dbg=False):\n '''\n \n '''\n print(\"train tree..\")\n mdl = build_choose_and_train(avWords)\n \n # write the code to save the model..\n \n # saving the tree trained above.\n save_network(mdl,rtTreeName,pth)\n\n # get all the words to see there categories\n all_wrds = avWords.all_words()\n\n # find the categories for the words\n cat_w = get_category(mdl,all_wrds)\n\n for i,wrd in enumerate(all_wrds):\n #print(wrd,\" \",cat_w[i])\n avWords.set_category(wrd,cat_w[i])\n \n \n if len(all_wrds) < 20:\n vv = -1\n stp = True\n for w in cat_w:\n if vv == -1:\n vv = w\n elif not vv == w: \n stp = False\n break\n \n if stp:\n if dbg:\n print(\"not seperating for words .. \", all_wrds)\n return\n \n \n # stops run away code and infinite recursion. Can't think of reason it should happen but..\n if maxDepth <= 0:\n print(\"max depth exceeded..\")\n return\n\n for i in range(5):\n sb_tree = rtTreeName + \"_\" + str(i)\n nw_wrl = avWords.filter_list(i)\n \n for w in nw_wrl.all_words():\n wdDic[w] = sb_tree\n \n print(\"category \",i,\" total word count \",len(nw_wrl.all_words()))\n \n # recurse..\n wrds = nw_wrl.all_words()\n if len(wrds) > 1:\n # recurse..\n print(\"recursing on \",sb_tree,\" total words.. \", len(wrds)) \n if len(wrds) < 5:\n print(\"Words..\",wrds)\n train_and_choose(sb_tree, nw_wrl, wdDic, maxDepth - 1,pth)\n return\n\n# saves a structure to file.\ndef save_json(sjn,flnm):\n data = json.dumps(sjn)\n with open(flnm,\"w\") as fl:\n fl.write(data)\n return\n\n# load json to dictionary\ndef load_json(flnm):\n data = None\n with open(flnm,\"r\") as fl:\n data = fl.read()\n return json.loads(data)\n\n# display the encoding image.\ndef display_im(im):\n plt.figure(figsize=(25, 25),dpi=80)\n plt.imshow(im)\n\n# check word spelling.\ndef spell_word(wrd,ntwrk_name,mmp,dr, dbg=False): \n \n # load the network\n mdl = best_move(ImgNet(5))\n \n fl = os.path.join(dr, (ntwrk_name + \".bin\")) #dr + \"/\" + ntwrk_name + \".bin\"\n \n nt = torch.load(fl)\n \n mdl.load_state_dict(nt)\n mdl.eval()\n \n cats = get_category(mdl,[wrd]) \n \n if dbg:\n print(\"category.. \",cats)\n \n sb_ntwrk = ntwrk_name + \"_\" + str(cats[0])\n\n word = [k for k,v in mmp.items() if v == sb_ntwrk]\n \n if len(word) > 0:\n if dbg:\n for k,v in mmp.items():\n if v == sb_ntwrk:\n print(\"key \",k, \" value \", v)\n return word\n \n nt_nm = dr + \"/\" + sb_ntwrk + \".bin\"\n \n if path.exists(nt_nm):\n if dbg:\n print(\"traverse down.. \",nt_nm)\n return spell_word(wrd,sb_ntwrk,mmp,dr,dbg)\n else:\n if dbg:\n print(\"network file not found. not found..\")\n return \"Not found..\"\n","sub_path":"core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":18298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"641512697","text":"#!/usr/bin/python\n\nimport logging\nimport os\nimport unittest\n\nfrom model_vtpr import VTPR\n\n# --- logging setup ---\nlogging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')\nlog = logging.getLogger(os.path.splitext(os.path.basename(__file__))[0])\nlog.setLevel(logging.DEBUG)\n\nmodel = None\n\ndef setUpModule():\n global model\n model = VTPR('VTPR_Test_Modell', 'mappings_vtpr', 3, 32, logger=log)\n return\n\ndef tearDownModule():\n global model\n return\n\n# @unittest.skip(\"Skipping Test01\")\nclass Test01(unittest.TestCase):\n \n def setUp(self):\n global model\n self.model = model\n\n def test_constructor(self):\n self.assertIsNotNone(self.model)\n\n# @unittest.skip(\"Skipping Test02\")\nclass Test02(unittest.TestCase):\n \n def setUp(self):\n global model\n self.model = model\n \n\n def test_model_results(self):\n self.model.calc_model_results()\n \n\n@unittest.skip(\"Skipping Test03\")\nclass Test03(unittest.TestCase):\n \n def setUp(self):\n global model\n self.model = model\n \n\n def test_model_results(self):\n res, exp_res , model_res = self.model.check_possible_calculations()\n self.assertIsNotNone(exp_res)\n self.assertIsNotNone(model_res)\n self.assertIsNotNone(res)\n\n@unittest.skip(\"Skipping Test04\")\nclass Test04(unittest.TestCase):\n \n def setUp(self):\n global model\n self.model = model\n \n\n def test_sys_diag(self):\n\n self.model.delete_diags = True\n\n system = ['CARBON DISULFIDE', 'ACETONE']\n self.model.create_system_diags(system)\n\n system = ['WATER', 'ACETONE']\n self.model.create_system_diags(system)\n\n system = ['CARBON DIOXIDE', 'ETHANE']\n self.model.create_system_diags(system)\n \n system = ['CHLORODIFLUOROMETHANE','CARBON DIOXIDE']\n self.model.create_system_diags(system)\n \n system = ['ETHANE','PROPANE']\n self.model.create_system_diags(system)\n\n\n@unittest.skip(\"Skipping Test05\")\nclass Test05(unittest.TestCase):\n \n def setUp(self):\n global model\n self.model = model\n \n\n def test_diag(self):\n self.model.delete_diags = False\n\n self.model.create_diags()\n\n\n@unittest.skip(\"Skipping Test06\")\nclass Test06(unittest.TestCase):\n \n def setUp(self):\n global model\n self.model = model\n \n\n def test_system_results(self):\n\n res = {}\n\n system = ['ACETONE', 'N-PENTANE']\n\n sys_file_name = '_'.join(system) + '.json'\n\n\n res = self.model.calc_system_results(system)\n if res != {}:\n self.model.write_results(sys_file_name, res)\n\n self.model.create_system_diags(system)\n\n \n@unittest.skip(\"Skipping Test07\")\nclass Test07(unittest.TestCase):\n \n def setUp(self):\n global model\n self.model = model\n \n\n def test_model_backup(self):\n self.model.do_model_backup()\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)","sub_path":"Software/dev/test_vtpr_model.py","file_name":"test_vtpr_model.py","file_ext":"py","file_size_in_byte":3056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"49136119","text":"import streamlit as st\nimport base64\nimport re\nimport string\nimport pandas as pd\nimport numpy as np\nimport nltk\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.stem.snowball import SnowballStemmer\nfrom sklearn.preprocessing import MultiLabelBinarizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.metrics import f1_score\nimport plotly.express as px\nfrom random import randrange\n\nTRAIN_FILE = 'train.csv'\nTEST_FILE = 'test.csv'\nBG_IMAGE = \"background.jpg\"\nBG_IMAGE_EXT = \"jpg\"\n\ndef main():\n st.markdown(\n f\"\"\"\n \n \"\"\",\n unsafe_allow_html=True\n ) \n\n st.markdown('

Movie genre recognition demo

', unsafe_allow_html=True)\n grid_search, multilabel_binarizer = get_grid_search_and_multilabel_binarizer()\n random_inputs = read_test_data()\n st.markdown('
Enter citation from your favourite movie or choose at random
', unsafe_allow_html=True)\n placeholder = st.empty()\n input = placeholder.text_input(\"\")\n if st.button(\"I'm feeling lucky\"):\n input = placeholder.text_input(\"\", value=random_inputs[randrange(len(random_inputs))])\n if input:\n predict(grid_search, multilabel_binarizer, input)\n\ndef predict(grid_search, multilabel_binarizer, input):\n input = clean_x(input)\n input = pd.Series(input)\n vect = grid_search.best_estimator_.named_steps['vect']\n input = vect.transform(input)\n tfidf = grid_search.best_estimator_.named_steps['tfidf']\n input = tfidf.transform(input)\n clf = grid_search.best_estimator_.named_steps['clf']\n decision_function_output = clf.decision_function(input)\n sizes, lables = get_pie_sizes_and_lables(multilabel_binarizer, decision_function_output)\n print(lables)\n main_genres = []\n add_genres = []\n reply_message = ''\n for i in range(len(sizes)):\n if sizes[i] >= 0.4:\n main_genres.append(lables[i])\n else:\n add_genres.append(lables[i])\n if len(main_genres) > 0:\n if len(add_genres) > 0:\n reply_message = \"This is \" + ' and '.join(main_genres) + \" with the elements of \" + ' and '.join(add_genres) + '.'\n else:\n reply_message = \"This is \" + ' and '.join(main_genres) + '.'\n elif len(add_genres) > 0:\n reply_message = \"This is the movie with the elements of \" + ' and '.join(add_genres) + '.'\n else:\n reply_message = \"Oops! It seems that we are unable to recognize the movie. Please try another citation.\"\n st.markdown('
' + reply_message + '
', unsafe_allow_html=True)\n if len(sizes) > 1:\n placeholder = st.empty()\n with placeholder.beta_expander(\"See details\"):\n show_pie_chart(sizes, lables)\n\ndef show_pie_chart(sizes, lables):\n fig = px.pie(sizes, values=sizes, names=lables)\n fig.update_layout(\n paper_bgcolor='rgba(0,0,0,0)',\n plot_bgcolor='rgba(0,0,0,0)',\n legend = dict(font = dict(size = 20, color = \"#FFF\"))\n )\n st.plotly_chart(fig)\n\ndef get_pie_sizes_and_lables(multilabel_binarizer, decision_function_output):\n has_class = decision_function_output > 0\n lables = np.array([multilabel_binarizer.classes_])\n return decision_function_output[has_class]/decision_function_output[has_class].sum(), lables[has_class]\n\n@st.cache(suppress_st_warning=True, show_spinner=False)\ndef get_grid_search_and_multilabel_binarizer():\n x, y, multilabel_binarizer = read_train_data()\n grid_search = train(x, y)\n return grid_search, multilabel_binarizer\n\ndef train(x, y):\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)\n pipeline = Pipeline([\n ('vect', CountVectorizer()),\n ('tfidf', TfidfTransformer()),\n ('clf', OneVsRestClassifier(SGDClassifier())),\n ])\n parameters = {\n 'vect__max_df': ([0.9]),\n 'vect__max_features': ([8000]),\n 'vect__ngram_range': ([(1, 1)]),\n 'tfidf__use_idf': ([False]),\n 'tfidf__norm': (['l2'])\n }\n grid_search = GridSearchCV(pipeline, parameters, n_jobs=-1, verbose=3, cv=2)\n grid_search.fit(x_train, y_train)\n print(grid_search.best_params_)\n res = grid_search.refit\n y_pred = grid_search.predict(x_test)\n y_pred = (y_pred >= 0.6).astype(int)\n print(f1_score(y_test, y_pred, average=\"micro\"))\n return grid_search\n\ndef read_train_data():\n data = pd.read_csv(TRAIN_FILE)\n data = data.groupby('movie').agg({'genres':', '.join,'dialogue':' '.join})\n x = process_x(data['dialogue'])\n y, multilabel_binarizer = process_y(data['genres'])\n return x, y, multilabel_binarizer\n\n@st.cache(suppress_st_warning=True, show_spinner=False)\ndef read_test_data():\n data = pd.read_csv(TEST_FILE)\n return data['dialogue']\n\ndef process_x(text):\n nltk.download('stopwords')\n return text.apply(lambda x: clean_x(x))\n\ndef process_y(text):\n text = text.apply(lambda x: clean_y(x))\n multilabel_binarizer = MultiLabelBinarizer()\n multilabel_binarizer.fit(text)\n return multilabel_binarizer.transform(text), multilabel_binarizer\n\ndef clean_x(text):\n text = text.lower()\n text = text.translate(str.maketrans('', '', string.punctuation))\n tokens = word_tokenize(text)\n stop_words = set(stopwords.words('english'))\n stop_words.add('u')\n stop_words.add('br')\n tokens = [w for w in tokens if not w in stop_words]\n stemmer = SnowballStemmer(\"english\")\n stems = []\n for t in tokens: \n stems.append(stemmer.stem(t))\n return ' '.join(stems)\n\ndef clean_y(text):\n text = text[1:-1]\n text = re.sub(\"\\[\", \"\", text)\n text = re.sub(\"\\]\", \"\", text)\n text = re.sub(\"u'\", \"\", text)\n text = re.sub(\"\\'\", \"\", text)\n return text.split(', ')\n\nif __name__ == \"__main__\":\n main()","sub_path":"genres.py","file_name":"genres.py","file_ext":"py","file_size_in_byte":7837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"84950757","text":"\"\"\"\ntwosheds.shell\n~~~~~~~~~~~~~~\n\nThis module implements the central user interface for access to an\noperating system's kernel services.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport atexit\nimport os\nimport readline\nimport sys\n\nfrom .cli import CommandLineInterface\nfrom .completer import Completer\nfrom .grammar import Grammar\nfrom .language import Language\nfrom .semantics import Semantics\nfrom .transform import AliasTransform, TildeTransform, VariableTransform\n\nDEFAULT_HISTFILE = os.path.expanduser(\"~/.console-history\")\n\n\nclass Shell(CommandLineInterface):\n \"\"\"\n A facade encapsulating the high-level logic of a command language\n interpreter.\n\n :param aliases: dictionary of aliases\n :param builtins: dictionary of builtins\n :param echo: set True to print commands immediately before execution\n :param prompt: the string which is printed before reading each command\n from the terminal.\n :param histfile: the location in which to look for a history file. if\n unset, ``DEFAULT_HISTFILE`` is used. histfile is useful\n when sharing the same home directory between different\n machines, or when saving separate histories on different\n terminals.\n :param use_suffix: add a ``/`` to completed directories and a space to the\n end of other completed words, to speed typing and\n provide a visual indicator of successful completion.\n :param exclude: list of regexes to be ignored by completion.\n\n Usage::\n\n >>> import twosheds\n >>> shell = twosheds.Shell()\n >>> shell.interact() # doctest: +SKIP\n \"\"\"\n def __init__(self,\n aliases=None,\n builtins=None,\n echo=False,\n prompt=None,\n histfile=None,\n use_suffix=True,\n exclude=None,\n ):\n super(Shell, self).__init__(prompt)\n\n transforms = [\n AliasTransform(aliases),\n TildeTransform(VariableTransform(os.environ)),\n ]\n grammar = Grammar(echo=echo, transforms=transforms)\n semantics = Semantics(builtins)\n self.language = Language(grammar, semantics)\n self.completer = Completer(grammar, use_suffix=use_suffix,\n exclude=exclude)\n self.histfile = histfile or DEFAULT_HISTFILE\n\n def _save_history(self):\n readline.write_history_file(self.histfile)\n\n def eval(self, text):\n \"\"\"Interpret and respond to user input. Optionally returns a string to\n print to standard out.\n \n :param text: the user's input\n \"\"\"\n return self.language.interpret(text)\n\n def interact(self, banner=None):\n \"\"\"Interact with the user.\n \n :param banner: (optional) the banner to print before the first\n interaction. Defaults to ``None``.\n \"\"\"\n readline.parse_and_bind(\"bind ^I rl_complete\" if sys.platform == 'darwin'\n else \"tab: complete\")\n readline.set_completer(self.completer.complete)\n if hasattr(readline, \"read_history_file\"):\n try:\n readline.read_history_file(self.histfile)\n except IOError:\n pass\n atexit.register(self._save_history)\n super(Shell, self).interact(banner)\n","sub_path":"twosheds/shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":3466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"254315747","text":"\"\"\"\nReference:\nhttps://github.com/awslabs/amazon-sagemaker-examples/blob/master/introduction_to_amazon_algorithms/xgboost_abalone/xgboost_abalone_dist_script_mode.ipynb\nhttps://sagemaker.readthedocs.io/en/stable/frameworks/xgboost/using_xgboost.html\n\n\nTest:\nLocal test on train.py\npython train.py --train \"../../test_data/train/\" --validation \"../../test_data/val/\" --model-dir \"../../test_data/\"\n\nvscode launch.json\n{\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"name\": \"Python: Current File\",\n \"type\": \"python\",\n \"request\": \"launch\",\n \"program\": \"${file}\",\n \"console\": \"integratedTerminal\",\n \"cwd\": \"${fileDirname}\",\n \"args\": [\n \"--train\",\n \"../../test_data/train/\",\n \"--validation\",\n \"../../test_data/val/\",\n \"--model-dir\",\n \"../../test_data/\"\n ]\n }\n ]\n}\n\n\"\"\"\n\nimport os\nimport argparse\nfrom xgboost import XGBClassifier\nfrom utils import print_files_in_path\nimport pickle\nfrom multiprocessing import cpu_count\nfrom sklearn.metrics import classification_report, confusion_matrix, precision_score\nimport pandas as pd\n\n\ndef model_fn(model_dir):\n filename = os.path.join(model_dir, \"model.pth\")\n with open(filename, \"rb\") as f:\n model = pickle.load(f)\n\n print(model)\n return model\n\n\ndef save_model(model, model_dir):\n \"\"\"Save xgb's Booster. Model function should return a xgboost.Booster object.\"\"\"\n print(\"save booster\")\n filename = os.path.join(model_dir, \"model.pth\")\n with open(filename, \"wb\") as f:\n pickle.dump(model._Booster, f)\n\n\ndef get_data(train_channel, validation_channel):\n \"\"\"Retrieve data based on channel dir provided.\"\"\"\n train_df = pd.read_csv(os.path.join(train_channel, \"train.csv\"), header=0, index_col=None)\n test_df = pd.read_csv(os.path.join(validation_channel, \"test.csv\"), header=0, index_col=None)\n X_train, y_train = train_df.iloc[:, 1:], train_df.iloc[:, 0]\n X_test, y_test = test_df.iloc[:, 1:], test_df.iloc[:, 0]\n print(f\"X_train: {X_train.shape}, y_train:{y_train.shape}\")\n print(f\"X_test: {X_test.shape}, y_test:{y_test.shape}\")\n return X_train, X_test, y_train, y_test\n\n\ndef train(train_channel, validation_channel, model_dir, epochs):\n \"\"\"\n SM_CHANNEL does not contain backward slash:\n SM_CHANNEL_TRAIN=/opt/ml/input/data/train\n SM_CHANNEL_VALIDATION=/opt/ml/input/data/validation\n\n Training job name:\n script-mode-container-xgb-2020-08-10-13-29-15-756\n\n \"\"\"\n print(\"\\nList of files in train channel: \")\n print_files_in_path(train_channel)\n\n print(\"\\nList of files in validation channel: \")\n print_files_in_path(validation_channel)\n\n X_train, X_test, y_train, y_test = get_data(train_channel, validation_channel)\n\n n_jobs = cpu_count() - 1\n\n parameters = {\n \"min_child_weight\": 5,\n \"max_depth\": 5,\n \"learning_rate\": 0.0001,\n \"objective\": \"multi:softprob\",\n \"n_estimators\": epochs,\n }\n\n model = XGBClassifier(\n base_score=0.5,\n booster=\"gbtree\",\n colsample_bylevel=1,\n colsample_bynode=1,\n colsample_bytree=1,\n gamma=0,\n max_delta_step=0,\n missing=None,\n n_jobs=n_jobs, # From version 1.1.1, cant use -1 for all cores\n nthread=None,\n random_state=0,\n reg_alpha=0,\n reg_lambda=1,\n # scale_pos_weight=1,\n subsample=1,\n verbosity=1,\n **parameters,\n )\n print(model)\n fit_params = {\n # \"sample_weight\": df_train_w[\"sample_weight\"],\n \"early_stopping_rounds\": 10,\n \"eval_metric\": \"mlogloss\",\n \"eval_set\": [(X_train, y_train), (X_test, y_test)],\n }\n model.fit(X_train, y_train, **fit_params)\n # model.fit(X_train, y_train)\n\n # Evaluation\n preds = model.predict(X_test)\n print(classification_report(y_test, preds))\n print(confusion_matrix(y_test, preds, labels=[0, 1, 2]))\n print(precision_score(y_test, preds, average=\"weighted\"))\n\n save_model(model, model_dir)\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n\n # sagemaker-containers passes hyperparameters as arguments\n parser.add_argument(\"--hp1\", type=str)\n parser.add_argument(\"--hp2\", type=int, default=50)\n parser.add_argument(\"--hp3\", type=float, default=0.1)\n parser.add_argument(\"--epochs\", type=int, default=50)\n\n # This is a way to pass additional arguments when running as a script\n # and use sagemaker-containers defaults to set their values when not specified.\n local_train = \"\"\n parser.add_argument(\"--train\", type=str, default=os.getenv(\"SM_CHANNEL_TRAIN\", None))\n parser.add_argument(\"--validation\", type=str, default=os.getenv(\"SM_CHANNEL_VALIDATION\", None))\n parser.add_argument(\"--model-dir\", type=str, default=os.getenv(\"SM_MODEL_DIR\", None))\n\n args = parser.parse_args()\n print(args)\n train(args.train, args.validation, args.model_dir, args.epochs)\n","sub_path":"script-mode-xgb/docker/code/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"641750078","text":"from unittest import TestCase\nimport os\nimport sys\n\nsys.path.append(os.path.dirname(__file__) + '/../')\n\ntry:\n from PathPlanning.AStar import a_star_searching_from_two_side as m\nexcept ImportError:\n raise\n\n\nclass Test(TestCase):\n\n def test1(self):\n m.show_animation = False\n m.main(800)\n\n def test2(self):\n m.show_animation = False\n m.main(5000) # increase obstacle number, block path\n\n\nif __name__ == '__main__':\n test = Test()\n test.test1()\n test.test2()\n","sub_path":"tests/test_a_star_searching_two_side.py","file_name":"test_a_star_searching_two_side.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"469150083","text":"import boto3\nimport json\nimport pprint\n\nsession = boto3.Session(profile_name='master')\nclient = session.client('s3')\n\nresponse = client.list_buckets()\npprint.pprint(response)\n\nbucket_names = []\nfor bucket in response['Buckets']:\n bucket_names.append(bucket['Name'])\n print(bucket_names)\n\n# Create a dictionary to hold the lists of object (file) names\nbucket_objects = {}\n# Loop through each bucket we found\nfor bucket in bucket_names:\n # Run our first API call to pull in the objects\n response = client.list_objects_v2(Bucket=bucket, MaxKeys=1000)\n # Check if there are any objects returned (none will return if no objects are in the bucket)\n if response.get('Contents'):\n # Store the fetched set of objects\n bucket_objects[bucket] = response['Contents']\n else:\n bucket_objects[bucket] = []\n continue\n \nwhile response['IsTruncated']:\n response = client.list_objects_v2(Bucket=bucket, MaxKeys=1000,\n continuationToken=response['NextContinuationToken'])\n bucket_objects[bucket].extend(response['Contents'])\n\n # We know bucket_objects has a key for each bucket so let's iterate that\n\nfor bucket in bucket_names:\n # Open up a local file with the name of the bucket\n with open('./{}.txt'.format(bucket), 'w+') as f:\n # Iterate through each object in the bucket\n for bucket_object in bucket_objects[bucket]:\n # Write a line to our file with the object details we are\n # interested in (file name and size)\n f.write('{} ({} bytes)\\n'.format(bucket_object['Key'],\n bucket_object['Size']))\n\n\n","sub_path":"iam/s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"572177195","text":"import random\r\n\r\nfrom flask import session\r\nfrom flask_socketio import emit\r\n\r\n\r\ndef register_handlers(socketio):\r\n @socketio.on('check_my_sanity')\r\n def sanity_handler():\r\n response = f'{random.choice([\"green\", \"red\", \"yellow\"])} {random.choice([\"dog\", \"cat\", \"goose\"])}'\r\n print(f'[INFO] You are sane! Response: {response}')\r\n emit('sanity_response', {'sane_animal': response})\r\n\r\n\r\n @socketio.on('check_user_sanity')\r\n def user_sanity_handler():\r\n user = session.get('username', 'unknown')\r\n if user == 'unknown':\r\n print(f'[WARN] User unknown!')\r\n else:\r\n print(f'[INFO] User {user} seems to be sane!')\r\n emit('sanity_response', {'username': user})\r\n","sub_path":"app/server/ws_sanity_check.py","file_name":"ws_sanity_check.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"398419416","text":"import hashlib\nfrom collections import OrderedDict\nfrom random import random, randint\n\nfrom InternalLogger.internallogger import InternalLogger\nfrom controller.ph_function.iphfunction import IPhFunction\nfrom datetime import datetime\n\n\nclass RpahFunction(IPhFunction):\n \"\"\"\n RPAH inspired Port Hopping Function\n \"\"\"\n def __init__(self, hopping_period, max_buffer):\n \"\"\"\n\n :param hopping_period: Hopping Period in Seconds\n :param max_buffer: Maximum Hash Buffer\n \"\"\"\n super().__init__()\n self._hopping_period = hopping_period\n self._hash_buffer = OrderedDict()\n self._max_buffer = max_buffer\n\n def real_port_to_vport(self, r_port, client_ip, client_key):\n \"\"\"\n\n :param r_port: Int, Real Port\n :param client_ip: String, Client IP Address\n :param client_key: String, Client PreShared Key\n :return: Virtual Port, Int\n \"\"\"\n t = self.get_T()\n h = self.get_hash(t, client_key, client_ip)\n v_port = h ^ r_port\n InternalLogger.get().debug(\"RPAH vPort =\" + str(v_port))\n return v_port\n\n def virtual_port_to_rport(self, v_port, client_ip, client_key):\n \"\"\"\n\n :param v_port: Int, Virtual Port\n :param client_ip: String, Client IP Address\n :param client_key: String, Client PreShared Key\n :return: Real Port, Int\n \"\"\"\n t = self.get_T()\n h = self.get_hash(t, client_key, client_ip)\n r_port = h ^ v_port\n InternalLogger.get().debug(\"RPAH rPort =\" + str(r_port))\n return r_port\n\n def get_T(self):\n \"\"\"\n get T, time interval value\n :return: T\n \"\"\"\n now = datetime.now()\n timestamp = datetime.timestamp(now)\n #random time\n #timestamp = timestamp + (randint(-3, 3) / 10)\n\n return int(timestamp / self._hopping_period)\n\n def get_hash(self, t, key, client_ip):\n \"\"\"\n\n :param t: t = T = Time Interval Value\n :param key: PSK\n :param client_ip: IP of the Client\n :return: Hash\n \"\"\"\n\n #Search in Buffer first\n InternalLogger.get().debug(\"Searching for hash in buffer\")\n hash_int = self._hash_buffer.get((t, key, client_ip))\n if hash_int is not None:\n InternalLogger.get().debug(\"Found hash in buffer\")\n self._hash_buffer.move_to_end((t, key, client_ip), last=False)\n return hash_int\n\n # Generate\n InternalLogger.get().debug(\"Trying to generate hash\")\n h = hashlib.blake2b(digest_size=2) # optimized for 64 bit\n h.update(bytes(t))\n h.update(key.encode())\n h.update(client_ip.encode())\n hash_result = h.digest()\n hash_int = int.from_bytes(hash_result, byteorder='big', signed=False)\n\n # Save to buffer\n self._hash_buffer[(t, key, client_ip)] = hash_int\n self._hash_buffer.move_to_end((t, key, client_ip), last=False) # move to the beginning\n # Cleanup\n while(len(self._hash_buffer) > self._max_buffer):\n #remove first element(s)\n self._hash_buffer.popitem(last=True)\n return hash_int\n","sub_path":"MTG/controller/ph_function/rpahfunction.py","file_name":"rpahfunction.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"185678419","text":"s = input().split()\n\na = int(s[0])\nb = int(s[1])\nc = int(s[2])\n\ncheck = False\n\nfor i in range(b):\n p = a * i\n if p % b == c:\n check = True\n break\n\nif check:\n print('YES')\nelse:\n print('NO')\n","sub_path":"Python_codes/p03730/s219610080.py","file_name":"s219610080.py","file_ext":"py","file_size_in_byte":216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"598706773","text":"# 动态规划,最长上升子序列\ndef DynamicProgramming(nums: list[int]):\n if not nums:\n return 0\n n = len(nums)\n dp = [1] * (n + 1)\n # 首先考虑前i个的最大dp\n for i in range(n):\n for j in range(i):\n dp[i] = max(dp[i], dp[j] + 1)\n\n return max(dp)\n\n\n# 贪心+二分查找,要使得上升序列尽可能长,就要让序列上升的尽可能慢\n# 求子序列长度,而不是顺序输出,所以可以插入,结果还是长度3。\nclass Solution:\n def lengthOfLIS(self, nums: List[int]) -> int:\n ans = []\n for n in nums:\n if not ans or n > ans[-1]:\n ans.append(n)\n else:\n left = 0\n right = len(ans) - 1\n pos = right\n\n while left <= right:\n mid = left + (right - left) // 2\n if ans[mid] >= n:\n pos = mid\n right = mid - 1\n else:\n left = mid + 1\n\n ans[pos] = n\n\n return len(ans)\n","sub_path":"DP&Greddy/lengthOfLIS.py","file_name":"lengthOfLIS.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"533931850","text":"# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def partition(self, head,x):\n # 双链表实现,小于x的组成一���表,大于x的组成另一链表,然后两链表拼接\n if not head:\n return None\n #初始化\n fnode = ListNode(-1)\n snode = ListNode(-1)\n first = fnode\n second = snode\n while head:\n if head.val < x:\n first.next = head\n first = first.next\n else:\n second.next = head\n second = second.next\n #在原始的列表中继续\n head = head.next\n #如果分配正确后,组合成一个列表并返回。\n first.next = snode.next\n #second的最后一个节点修改为节点的结束\n second.next = None\n\n return fnode.next\n\nif __name__==\"__main__\":\n S=Solution()\n head=[1,2,2,3,5,2]\n x=3\n print(S.partition(head,x))","sub_path":"lianbiao/fenge_Link/fenge.py","file_name":"fenge.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"335086713","text":"import NeuralNet\nimport Game\n\n\nclass AI:\n def __init__(self):\n self.net = NeuralNet.NeuralNet()\n self.game = Game.Game()\n\n def randomize(self):\n self.net.randomize()\n\n def mutate(self):\n self.net.mutate()\n\n def reset(self):\n self.game.score = 0\n self.game = Game.Game()\n\n def evaluate(self):\n out = self.net.calculate(self.game.gridsinglearray())\n maximum = -1\n action = \"\"\n if out[0] > maximum:\n action = \"right\"\n maximum = out[0]\n if out[1] > maximum:\n action = \"left\"\n maximum = out[1]\n if out[2] > maximum:\n action = \"up\"\n maximum = out[2]\n if out[3] > maximum:\n action = \"down\"\n\n if action == \"right\":\n output = self.game.right()\n if action == \"left\":\n output = self.game.left()\n if action == \"up\":\n output = self.game.up()\n if action == \"down\":\n output = self.game.down()\n\n return output\n","sub_path":"AI.py","file_name":"AI.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"128366021","text":"import configparser\nimport typer\nimport os\nfrom pygit2 import discover_repository\nimport collections\nfrom pygit2 import Repository, Commit\nfrom pygit2 import GIT_SORT_TOPOLOGICAL\nimport git_lint_branch.cfg as cfg\nfrom git_lint_branch.linter_output import *\nfrom git_lint_branch.single import single_linters\nfrom git_lint_branch.multi import multi_linters\n\n\napp = typer.Typer()\n\n\"\"\"\nFrom: https://stackoverflow.com/questions/16108285/correct-way-to-iterate-twice-over-a-list?rq=1\n\"\"\"\n\n\ndef tosequence(it):\n \"\"\"Turn iterable into a sequence, avoiding a copy if possible.\"\"\"\n if not isinstance(it, collections.Sequence):\n it = list(it)\n return it\n\nclass Printer:\n def __init__(self, verbose: bool = True):\n # self._single_data = typer.style('+++ ', fg=typer.colors.CYAN)\n # self._single_data += typer.style('Linting your commits:\\n', fg=typer.colors.BRIGHT_CYAN, bold=True, underline=True)\n self._verbose = verbose\n\n self._single_data = ''\n self._commit_str = ''\n\n self._multiple_data = ''\n\n def add_commit(self, commit: Commit):\n self._commit_str = typer.style(f'\\nCOMMIT: {commit.id}\\n', fg=typer.colors.BRIGHT_CYAN, bold=True)\n self._commit_str += typer.style(f'TITLE: {commit.message.splitlines()[0]}\\n', fg=typer.colors.BRIGHT_CYAN, bold=True)\n\n def add_single_linter(self, linter: LinterOutput):\n self._single_data += self._commit_str\n self._commit_str = ''\n\n self._single_data += linter.pretty_str(self._verbose)\n\n def add_multiple_linter(self, linter: LinterOutput):\n self._multiple_data += linter.pretty_str(self._verbose)\n\n def show(self):\n final_str = ''\n if len(self._single_data) > 0:\n final_str += typer.style('+++ ', fg=typer.colors.GREEN)\n final_str += typer.style('Linting your commits:\\n', fg=typer.colors.BRIGHT_GREEN, bold=True, underline=True)\n\n final_str += self._single_data\n\n if len(self._multiple_data) > 0:\n final_str += typer.style('\\n+++ ', fg=typer.colors.GREEN)\n final_str += typer.style('Linting your commit history:\\n', fg=typer.colors.BRIGHT_GREEN, bold=True, underline=True)\n\n final_str += self._multiple_data\n\n typer.echo(final_str)\n\n\n@app.command()\ndef main(\n upstream: str,\n verbose: bool = typer.Option(True, help=\"Display suggestions on how to fix issues\")\n ):\n \"\"\"\n Lints the commit history reachable from the current HEAD that is not\n on UPSTREAM (i.e., the current branch).\n \"\"\"\n repo_path = discover_repository(os.getcwd())\n if repo_path is None:\n typer.echo('fatal: not a git repository (or any of the parent directories)', err=True)\n raise typer.Exit(code=1)\n cfg.repo = Repository(repo_path)\n config_file_path = os.path.join(repo_path, \"..\", \".git-lint-branch\")\n if os.path.isfile(config_file_path):\n cfg.config = configparser.ConfigParser()\n cfg.config.read(config_file_path, encoding=\"utf-8\")\n else:\n cfg.config = configparser.ConfigParser()\n\n try:\n cfg.upstream = cfg.repo.revparse_single(upstream)\n except KeyError:\n typer.echo(f'fatal: UPSTREAM {upstream} not found or not reachable', err=True)\n raise typer.Exit(code=1)\n\n walker = cfg.repo.walk(cfg.repo.head.target, GIT_SORT_TOPOLOGICAL)\n walker.hide(cfg.upstream.id)\n walker = tosequence(walker)\n\n printer = Printer(verbose=verbose)\n\n for commit in walker:\n printer.add_commit(commit)\n\n for linter in single_linters:\n lint_result = linter(commit)\n if lint_result.level is not LinterLevel.Empty:\n printer.add_single_linter(lint_result)\n\n\n for linter in multi_linters:\n lint_result = linter(walker)\n if lint_result.level is not LinterLevel.Empty:\n printer.add_multiple_linter(lint_result)\n\n printer.show()\n","sub_path":"git_lint_branch/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"14525049","text":"import sys\n\nsys.stdin = open(\"4875.txt\")\n\nt = int(input())\n\ndy = [-1,1,0,0]\ndx = [0,0,-1,1]\n\ndef issafe(y,x):\n\tglobal n\n\tif y >= 0 and y < n and x >=0 and x < n and data[y][x] != 1:\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef miro(start_y,start_x):\n\tqueue = []\n\n\tqueue.append((start_y,start_x))\n\n\twhile queue:\n\t\ttemp = queue.pop(0)\n\t\ty = temp[0]\n\t\tx = temp[1]\n\t\tprint(y,x)\n\t\tif data[y][x] != 1:\n\t\t\tdata[y][x] = 1\n\n\t\tfor dir in range(4):\n\t\t\tif issafe(y + dy[dir], x + dx[dir]) and (y + dy[dir], x + dx[dir]) not in queue:\n\t\t\t\tqueue.append((y + dy[dir], x + dx[dir]))\n\nfor tc in range(1,t+1):\n\n\tn = int(input())\n\tdata = []\n\tfor i in range(n):\n\t\tdata.append(list(map(int,input())))\n\n\tfor y in range(5):\n\t\tfor x in range(5):\n\t\t\tif data[y][x] == 2:\n\t\t\t\tstart_y = y\n\t\t\t\tstart_x = x\n\t\t\telif data[y][x] == 3:\n\t\t\t\tend_y = y\n\t\t\t\tend_x = x\n\n\tmiro(start_y, start_x)\n\n\tif data[end_y][end_x] == 1:\n\t\tprint(f'#{tc} 1')\n\telse:\n\t\tprint(f'#{tc} 0')","sub_path":"algo/190226/4_swea_4875_mirobfs.py","file_name":"4_swea_4875_mirobfs.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"418469287","text":"# -*- coding: utf-8 -*-\n\nfrom setuptools import setup, find_packages\n\n\nwith open('README.md') as f:\n readme = f.read()\n\nsetup(\n name='sample',\n version='0.1.0',\n description='Sample package for Verificacion y Desarrollo',\n long_description=readme,\n author='Enrique Sanchez',\n author_email='enrique.sanchez@u-tad.live.com',\n packages=find_packages(exclude=('tests', 'docs'))\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"547395279","text":"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n\n@torch.no_grad()\ndef convert_to_one_hot(x, minleng, ignore_idx=-1):\n '''\n encode input x into one hot\n inputs:\n x: tensor of shape (N, ...) with type long\n minleng: minimum length of one hot code, this should be larger than max value in x\n ignore_idx: the index in x that should be ignored, default is 255\n\n return:\n tensor of shape (N, minleng, ...) with type float\n '''\n device = x.device\n # compute output shape\n size = list(x.size())\n size.insert(1, minleng)\n assert x[x != ignore_idx].max() < minleng, \"minleng should larger than max value in x\"\n\n if ignore_idx < 0:\n out = torch.zeros(size, device=device).scatter_(1, x.unsqueeze(1), 1)\n else:\n # overcome ignore index\n x = x.clone().detach()\n ignore = x == ignore_idx\n x[ignore] = 0\n out = torch.zeros(size, device=device).scatter_(1, x.unsqueeze(1), 1)\n ignore = ignore.nonzero(as_tuple=False)\n _, M = ignore.size()\n a, *b = ignore.chunk(M, dim=1)\n out[[a, torch.arange(minleng), *b]] = 0\n return out\n\n\ndef convert_to_one_hot_cu(x, minleng, smooth=0., ignore_idx=-1):\n '''\n cuda version of encoding x into one hot, the difference from above is that, this support label smooth.\n inputs:\n x: tensor of shape (N, ...) with type long\n minleng: minimum length of one hot code, this should be larger than max value in x\n smooth: sets positive to **1. - smooth**, while sets negative to **smooth / minleng**\n ignore_idx: the index in x that should be ignored, default is 255\n\n return:\n tensor of shape (N, minleng, ...) with type float32\n '''\n import one_hot_cpp\n return one_hot_cpp.label_one_hot(x, ignore_idx, smooth, minleng)\n\n\n\nclass OnehotEncoder(nn.Module):\n\n def __init__(\n self,\n n_classes,\n lb_smooth=0.,\n ignore_idx=-1,\n ):\n super(OnehotEncoder, self).__init__()\n self.n_classes = n_classes\n self.lb_smooth = lb_smooth\n self.ignore_idx = ignore_idx\n\n @ torch.no_grad()\n def forward(self, label):\n return convert_to_one_hot_cu(\n label, self.n_classes, self.lb_smooth, self.ignore_idx).detach()\n\n\nif __name__ == \"__main__\":\n x = torch.randint(0, 3, (3, 4))\n print(x)\n x[1, 1] = 4\n print(x)\n out = convert_to_one_hot(x, minleng=4, ignore_idx=4)\n print(out)\n\n x = torch.randint(0, 3, (3, 4)).cuda()\n smooth = 0.1\n out = convert_to_one_hot_cu(x, minleng=4, smooth=smooth, ignore_idx=4)\n print(out)\n","sub_path":"pytorch_loss/one_hot.py","file_name":"one_hot.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"83979561","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\ndriver = webdriver.Chrome()\ndriver.get(\"https://login.taobao.com/?style=mini&full_redirect=true&newMini2=true&from=databank&sub=true&redirectURL=https://databank.tmall.com/\")\nelemButton = driver.find_element_by_xpath('//*[@id=\"J_Quick2Static\"]')\nelemButton.click()\nelem = driver.find_element_by_id(\"TPL_username_1\")\nelem.clear()\nelem.send_keys(\"pycon\")\nelem.send_keys(Keys.RETURN)\nassert \"No results found.\" not in driver.page_source\n","sub_path":"pythonOrg.py","file_name":"pythonOrg.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"203637110","text":"from django.urls import path\nfrom . import views\nfrom django.conf.urls import include, url\n\nfrom connectedwe.users.views import (\n user_list_view,\n user_redirect_view,\n user_update_view,\n user_detail_view,\n)\n\napp_name = \"users\"\nurlpatterns = [\n path(\"\", view=user_list_view, name=\"list\"),\n path(\"explore/\", views.UserView.as_view(), name=\"explore_user\"),\n path(\"new/\", views.CreateNewUser.as_view(), name=\"create_new_user\"),\n path(\"followers/\", views.GetFollowersList.as_view(), name=\"followerlist\"),\n path(\"following/\", views.GetFollowingList, name=\"followinglist\"),\n path(\"search/\", views.SearchByUsername.as_view(), name=\"searchByUsername\"),\n path(\"id/\", views.UserIdView.as_view(), name=\"getMyUserId\"),\n path(\"notifications/\", views.NotificationView.as_view(), name=\"get_notification_count\"),\n path(\"~redirect/\", view=user_redirect_view, name=\"redirect\"),\n path(\"~update/\", view=user_update_view, name=\"update\"),\n path(\"/\", view=user_detail_view, name=\"detail\"),\n path(\"/profile/\", views.ProfileView.as_view(), name=\"user_profile\"),\n path(\"/follow/\", views.FollowView.as_view(), name=\"follow_user\"),\n path(\"/unfollow/\", views.FollowView.as_view(), name=\"unfollow_user\"),\n path(\"/edit/\", views.ProfileView.as_view(), name=\"edit_user_profile\"),\n path(\"/password/\", views.PasswordView.as_view(), name=\"edit_password\"),\n \n \n]\n\n\n#\n\n#{\n# \"username\": \"username\",\n# \"name\": \"name\",\n# \"password1\": \"password1\",\n# \"password2\": \"password2\",\n# \"phone\": \"01012341234\",\n# \"gender\": \"male\"\n#}\n#\n","sub_path":"connectedwe/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"600377048","text":"import sys\ninput = raw_input\ndef answer0(n, k, c):\n answer = 0\n for i in range(1, n):\n for j in range(i + 1, n + 1):\n answer += (j - i) * k + c\n return answer\n\ndef answer(n, k, c):\n '''sum1 = k * (n * (n ** 2 - 1) / 2)\n print(sum1)\n sum1 -= k * (n * (n - 1) / 4)\n print(sum1)\n sum1 -= k * (n * (n - 1) * (2 * n - 1) / 12)\n print(sum1)\n '''\n sum1 = k * (n * (n ** 2 - 1)) // 2\n #print(sum1)\n sum1 -= k * n * (n - 1) * (2 * n + 2) // 12\n #print(sum1)\n #print('=' * 10)\n sum2 = (- 1) * k * (n ** 2 * (n - 1) // 2)\n sum2 += k * (n * (n - 1) * (2 * n - 1) // 6)\n sum3 = c * (n * (n - 1) / 2)\n #print(sum1, sum2, sum3)\n return int(sum1 + sum2 + sum3)\n\nT = int(input().strip())\nfor a0 in range(T):\n N,K,C = input().strip().split(' ')\n N,K,C = [int(N),int(K),int(C)]\n print(answer(N, K, C) % (10 ** 9 + 9))","sub_path":"competitions/old_competitions/holiday_cup_2/super_highways.py","file_name":"super_highways.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"306158639","text":"from os import getenv\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nDB_NAME = getenv(\"DB_NAME\")\nDB_USER = getenv(\"DB_USER\")\nDB_HOST = getenv(\"DB_HOST\")\nDB_PSWD = getenv(\"DB_PSWD\")\nSENDGRID_API_KEY = getenv(\"SENDGRID_API_KEY\")","sub_path":"app/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"382565377","text":"from eve import Eve\nimport json\nimport psutil\n\nguide = \"Eve REST\\n\"\\\n \"System info that is available:\\n\"\\\n \" all\\n mem\\n disk\\n user\\n\"\\\n \"Example: http://127.0.0.1:5000/info/disk \"\\\n\nprint(guide)\n\napp = Eve()\n\n\n#Format data for output\ndef output(data):\n format = json.dumps(data, indent=4)+\"\\n\"\n return format\n\n\n# Returns all information\n@app.route('/info/all', methods=['GET'])\ndef all():\n ALL = {\n \"TOTAL RAM\": psutil.virtual_memory().total,\n \"USED RAM\": psutil.virtual_memory().used,\n \"AVAILABLE RAM\": psutil.virtual_memory().available,\n \"TOTAL DISK\": psutil.disk_usage('/').total,\n \"USED DISK\": psutil.disk_usage('/').used,\n \"AVAILABLE DISK\": psutil.disk_usage('/').free,\n \"CPU CORES\": psutil.cpu_count(),\n \"USED CPU\": str(psutil.cpu_percent()) + \"%\",\n \"USER NAME\": psutil.users()[0].name,\n \"USER TERMINAL\": psutil.users()[0].terminal\n }\n return output(ALL)\n\n\n# Returns USER info\n@app.route(\"/info/user\", methods=['GET'])\ndef user():\n user = {\n \"USER NAME\": psutil.users()[0].name,\n \"USER TERMINAL\": psutil.users()[0].terminal\n }\n return output(user)\n\n# Returns RAM info\n@app.route('/info/mem', methods=['GET'])\ndef mem():\n mem = {\n \"TOTAL RAM\": psutil.virtual_memory().total,\n \"USED RAM\": psutil.virtual_memory().used,\n \"AVAILABLE RAM\": psutil.virtual_memory().available\n }\n return output(mem)\n\n# Returns DISK info\n@app.route(\"/info/disk\", methods=['GET'])\ndef disk():\n disk = {\n \"TOTAL DISK\": psutil.disk_usage('/').total,\n \"USED DISK\": psutil.disk_usage('/').used,\n \"AVAILABLE DISK\": psutil.disk_usage('/').free\n }\n \n return output(disk)\n\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"rest/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"312281177","text":"#!/usr/bin/env conda-execute\n\n# conda execute\n# env:\n# - python\n# - conda-smithy\n# - gitpython\n# - pygithub\n# channels:\n# - conda-forge\n# run_with: python\n\nimport os\nimport time\nimport argparse\nfrom contextlib import contextmanager\nimport textwrap\nimport random\nimport re\n\nimport git\nimport github\n\nimport conda_smithy.github\nimport conda_smithy.configure_feedstock\nimport conda_smithy\n\nimport conda_smithy.feedstocks as feedstocks\n\n\npinned = {\n 'boost': 'boost 1.61.*',\n 'bzip2': 'bzip2 1.0.*',\n 'fontconfig': 'fontconfig 2.11.*',\n 'freetype': 'freetype 2.6.*',\n 'hdf5': 'hdf5 1.8.17|1.8.17.*',\n 'icu': 'icu 56.*',\n 'jpeg': 'jpeg 9*',\n 'libnetcdf': 'libnetcdf 4.4.*',\n 'libpng': 'libpng >=1.6.21,<1.7',\n 'libtiff': 'libtiff 4.0.*',\n 'ncurses': 'ncurses 5.9*',\n 'openssl': 'openssl 1.0.*',\n 'readline': 'readline 6.2*',\n 'sqlite': 'sqlite 3.13.*',\n 'tk': 'tk 8.5.*',\n 'xz': 'xz 5.2.*',\n 'zlib': 'zlib 1.2.*',\n }\n\nparser = argparse.ArgumentParser(description='Propose a feedstock update.')\nparser.add_argument('--feedstocks-dir', help=\"The location of the feedstocks.\",\n default=\"~/dev/conda-forge/feedstocks\")\nparser.add_argument('--regexp', help=\"Regexp of feedstocks to consider.\",\n default=\".*\")\nparser.add_argument('--limit', help=\"Limit the number of packages to propose changes for (0 is unlimited).\",\n default=1, type=int)\nargs = parser.parse_args()\n\nfeedstocks_dir = os.path.expanduser(args.feedstocks_dir)\nchange_limit = args.limit\n\n#feedstocks.clone_all('conda-forge', feedstocks_dir)\n#feedstocks.fetch_feedstocks(feedstocks_dir)\n\nregexp = re.compile(args.regexp)\nrandomised_feedstocks = [feedstock for feedstock in feedstocks.cloned_feedstocks(feedstocks_dir)\n if regexp.match(feedstock.package)]\nrandomised_feedstocks = [feedstock for feedstock in randomised_feedstocks if feedstock.package not in ['boost', 'gdal', 'git', 'pandoc']]\n# Shuffle is in-place. :(\nrandom.shuffle(randomised_feedstocks)\n\ngh_token = conda_smithy.github.gh_token()\ngh = github.Github(gh_token)\n\ngh_me = gh.get_user()\n\nif gh_me.login != 'conda-forge-admin':\n raise ValueError(\"The github token isn't that of conda-forge-admin (it's \"\n \"for {}), I'm going to have to bail.\".format(gh_me.login))\n\ngh_forge = gh.get_organization('conda-forge')\n\n\ndef my_repos(gh_user):\n \"\"\"\n List all of my repos.\n See https://github.com/PyGithub/PyGithub/issues/390 for rationale.\n\n \"\"\"\n return github.PaginatedList.PaginatedList(\n github.Repository.Repository,\n gh_user._requester,\n gh_user.url + \"/repos\",\n dict(affiliation=\"owner\"))\n\n\ndef list_pulls(repo, state='open', head=None):\n \"\"\"\n List all of the pull requests that match the given critera.\n\n At the time of writing, pygithub doesn't allow you to specify the head,\n so I had to create this function.\n\n \"\"\"\n url_parameters = dict(state=state)\n if head:\n url_parameters['head'] = head\n return github.PaginatedList.PaginatedList(\n github.PullRequest.PullRequest,\n repo._requester,\n repo.url + \"/pulls\",\n url_parameters\n )\n\n\n# Set to false to debug.\nif True:\n print(\"Collecting list of conda-forge-admin repos...\")\n my_repos = {repo.name: repo for repo in my_repos(gh_me)}\n print(\"Collecting list of conda-forge repos...\")\n forge_repos = {repo.name: repo for repo in gh_forge.get_repos()}\n\n # TODO: Maybe we should sort the feedstocks into dependency order.\nelse:\n # For debugging, we turn our attention to a single feedstock.\n debug_name = 'libtiff-feedstock'\n debug_name = 'bob.io.image-feedstock'\n debug_name = 'expat-feedstock'\n try:\n my_repos = {debug_name: gh_me.get_repo(debug_name)}\n except github.UnknownObjectException:\n # We haven't forked it yet!\n my_repos = {}\n forge_repos = {debug_name: gh_forge.get_repo(debug_name)}\n randomised_feedstocks = [feedstock for feedstock in randomised_feedstocks\n if feedstock.name == debug_name]\n\n\n@contextmanager\ndef tmp_remote(repo, remote_name, url):\n if remote_name in [remote.name for remote in repo.remotes]:\n repo.delete_remote(remote_name)\n remote = repo.create_remote(remote_name, url)\n yield remote\n repo.delete_remote(remote_name)\n\n\n@contextmanager\ndef create_update_pr(clone, remote_head, fork_remote, upstream_remote):\n target_branch = 'feedstock_version_pin_{}'.format(remote_head)\n if target_branch in clone.heads:\n # Detatch the head\n clone.head.reference = clone.commit('upstream/master')\n clone.delete_head(target_branch, '-D')\n clone.create_head(target_branch, upstream_remote.refs[remote_head]).set_tracking_branch(upstream_remote.refs[remote_head])\n\n # Reset the working tree to a clean state.\n clone.head.reset(index=True, working_tree=True)\n clone.heads[target_branch].checkout()\n\n # It is at this point we pass context back to the caller so that they can\n # do whatever they like to the repo (like rerender the feedstock).\n context = []\n yield context\n\n # If nothing was done, don't need a PR!\n has_change = True\n if not clone.is_dirty():\n # We don't need this feedstock - it is slap-bang up to date. :)\n print(\"{} was checked, and is up-to-date\".format(feedstock.name))\n has_change = False\n\n if has_change:\n clone.git.add('-A')\n author = git.Actor(gh_me.login, gh_me.email)\n commit = clone.index.commit(\"MNT: Updated some of the pinned versions\",\n author=author)\n\n change_from_remote_branch = True\n full_ref = '{}/{}'.format(fork_remote.name, target_branch)\n\n if full_ref in [ref.name for ref in fork_remote.refs]:\n diff = commit.diff(fork_remote.refs[target_branch])\n if not diff:\n # There were no differences between this and the remote targt branch, so just continue.\n print(\"{} was checked, and whilst there are changes needed, the branch ({}) is up-to-date\".format(feedstock.name, target_branch))\n change_from_remote_branch = False\n\n fork_remote.push('+{}'.format(target_branch))\n\n if change_from_remote_branch:\n fork_remote.push('+{}'.format(target_branch))\n\n pull_requests = list(list_pulls(forge_feedstock, state='open', head='{}:{}'.format(gh_me.login, target_branch)))\n\n if pull_requests:\n pull = pull_requests[0]\n msg = textwrap.dedent(\"\"\"\n It's the friendly automated conda-forge-admin here again.\n\n Just to let you know, I've updated this PR so that it has the latest pinned versions.\n\n If there are no problems with it, please consider merging this PR.\n If there are concerns about it, please ping the 'conda-forge/core' team (using the @ notation in a comment).\n\n Thanks!\n \"\"\".format(conda_smithy.__version__))\n pull.create_issue_comment(msg)\n print('Updated PR on {}'.format(pull.html_url))\n else:\n msg = textwrap.dedent(\"\"\"\n Hi! This is the friendly conda-forge-admin automated user.\n\n I've bumped some of the conda-forge pinned versions, and noticed that it impacts this feedstock.\n If the changes look good, then please go ahead and merge this PR.\n If you have any questions about the changes though, please feel free to ping the 'conda-forge/core' team (using the @ notation in a comment).\n\n Thanks!\n\n \"\"\")\n\n pull = forge_feedstock.create_pull(title='MNT: Update pinned versions.',\n body=msg,\n head=\"{}:{}\".format(gh_me.login, target_branch), base=remote_head)\n print('Opened PR on {}'.format(pull.html_url))\n context.append(pull)\n\n\nfrom ruamel.yaml.comments import CommentedBase\ndef set_start_comment(self, comment, indent=0):\n \"\"\"overwrites any preceding comment lines on an object expects comment to be without `#` and possible have mutlple lines \"\"\"\n from ruamel.yaml.error import Mark\n from ruamel.yaml.tokens import CommentToken\n if self.ca.comment is None:\n pre_comments = []\n self.ca.comment = [None, pre_comments]\n else:\n pre_comments = self.ca.comments[1]\n\n if comment[-1] == '\\n':\n comment = comment[:-1]\n # strip final newline if there\n start_mark = Mark(None, None, None, indent, None, None)\n for com in comment.split('\\n'):\n pre_comments.append(CommentToken('# ' + com + '\\n', start_mark, None))\n\nif not hasattr(CommentedBase, 'set_start_comment'):\n CommentedBase.set_start_comment = set_start_comment\n\nimport jinja2\nclass NullUndefined(jinja2.Undefined):\n def __unicode__(self):\n return unicode(self._undefined_name)\n\n def __getattr__(self, name):\n return unicode('{}.{}'.format(self, name))\n\n def __getitem__(self, name):\n return '{}[\"{}\"]'.format(self, name)\nenv = jinja2.Environment(undefined=NullUndefined)\n\ncount = 0\nfor feedstock in randomised_feedstocks:\n print('Checking {}'.format(feedstock.name))\n if feedstock.name not in forge_repos:\n raise ValueError(\"There exists a feedstock ({}) which isn't in the \"\n \"conda-forge org.\".format(feedstock.name))\n\n if feedstock.name not in my_repos:\n forge_repo = gh_forge.get_repo(feedstock.name)\n print('Forking {}'.format(feedstock.name))\n gh_me.create_fork(forge_repo)\n my_repos[feedstock.name] = gh_me.get_repo(feedstock.name)\n\n clone = git.Repo(feedstock.directory)\n admin_fork = my_repos[feedstock.name]\n forge_feedstock = forge_repos[feedstock.name]\n\n skip_after_package = False\n\n # Put an appropriate conda-forge-admin remote in place.\n with tmp_remote(clone, gh_me.login,\n admin_fork.clone_url.replace('https://',\n 'https://{}@'.format(gh_token))) as remote:\n remote.fetch()\n clone.remotes.upstream.fetch()\n for branch in clone.remotes['upstream'].refs:\n remote_branch = branch.remote_head.replace('{}/'.format(gh_me.login), '')\n with create_update_pr(clone, remote_branch, remote, clone.remotes['upstream']) as pr:\n\n # Technically, we can do whatever we like to the feedstock now. Let's just\n # update the feedstock though. For examples of other things that *have* been\n # done here - once upon a time @pelson modified the conda-forge.yaml config\n # item for every single feedstock, and submitted PRs for every project.\n# conda_smithy.configure_feedstock.main(feedstock.directory)\n\n import ruamel.yaml\n forge_yaml = os.path.join(feedstock.directory, 'recipe', 'meta.yaml')\n with open(forge_yaml, 'r') as fh:\n content = ''.join(fh)\n parsable_content = env.from_string(content).render(os=os)\n code = ruamel.yaml.load(parsable_content, ruamel.yaml.RoundTripLoader)\n\n replacements = {}\n for section_name in ['run', 'build']:\n requirements = code.get('requirements')\n if requirements is None:\n break\n section = requirements.get(section_name)\n if not section:\n continue\n\n for pos, dep in enumerate(section):\n for name, pin in pinned.items():\n if dep.startswith(name) and dep != pin:\n replacements['- ' + str(dep)] = '- ' + pin\n if replacements:\n current_build_number = code['build']['number']\n replacements['number: {}'.format(current_build_number)] = 'number: {}'.format(current_build_number + 1)\n for orig, new in replacements.items():\n content = content.replace(orig, new)\n with open(forge_yaml, 'w') as fh:\n fh.write(content)\n if pr:\n skip_after_package = True\n # Stop processing any more feedstocks until the next time the script is run.\n if skip_after_package:\n count += 1\n\n if change_limit > 0 and count >= change_limit:\n break\n","sub_path":"scripts/pin_the_slow_way.py","file_name":"pin_the_slow_way.py","file_ext":"py","file_size_in_byte":12685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"189113466","text":"from __future__ import print_function\n\nimport rospy\nimport robot_smach_states as states\nimport robot_smach_states.util.designators as ds\nimport smach\nfrom robocup_knowledge import load_knowledge\nfrom robot_skills.util.entity import Entity\nfrom math import radians\n\nchallenge_knowledge = load_knowledge('challenge_receptionist')\n\n\nclass GuestDescriptionStrDesignator(ds.Designator):\n def __init__(self, guest_name_des, drinkname, name=None):\n super(GuestDescriptionStrDesignator, self).__init__(resolve_type=str, name=name)\n\n ds.check_type(guest_name_des, str)\n ds.check_type(drinkname, str)\n\n self.guest_name_des = guest_name_des\n self.drinkname = drinkname\n\n def _resolve(self):\n name = self.guest_name_des.resolve()\n drinkname = self.drinkname.resolve()\n return \"This is {name} whose favourite drink is {drink}\".format(name=name, drink=drinkname)\n\n\nclass IntroduceGuest(smach.StateMachine):\n def __init__(self, robot, guest_ent_des, guest_name_des, guest_drinkname_des, assume_john=False):\n smach.StateMachine.__init__(self, outcomes=['succeeded', 'abort'])\n\n ds.check_type(guest_name_des, str)\n ds.check_type(guest_drinkname_des, str)\n ds.check_type(guest_ent_des, Entity)\n\n all_old_guests = ds.VariableDesignator(resolve_type=[Entity], name='all_old_guests')\n current_old_guest = ds.VariableDesignator(resolve_type=Entity, name='current_old_guest')\n\n # For each person:\n # 0. Go to the person (old guest)\n # 1. Look at the person and point at the guest\n # 2. Say 'Hi , this is \n\n with self:\n smach.StateMachine.add('SAY_INTRO',\n states.SayFormatted(robot,\n [\"Hi {name}, let me introduce you our new guest {guest_name}. I'll show you in a bit\"],\n name=ds.Designator(challenge_knowledge.operator_name) if assume_john else ds.Designator(\"folks\"),\n guest_name=guest_name_des,\n block=False),\n transitions={'spoken': 'FIND_OLD_GUESTS'})\n\n smach.StateMachine.add('FIND_OLD_GUESTS',\n states.FindPeopleInRoom(robot,\n room=challenge_knowledge.waypoint_livingroom['id'],\n found_people_designator=all_old_guests.writeable),\n transitions = {'found': 'ITERATE_OLD_GUESTS',\n 'not_found': 'ITERATE_OLD_GUESTS'})\n\n smach.StateMachine.add('ITERATE_OLD_GUESTS',\n states.IterateDesignator(all_old_guests,\n current_old_guest.writeable),\n transitions={'next': 'GOTO_OPERATOR',\n 'stop_iteration': 'succeeded'})\n\n smach.StateMachine.add('GOTO_OPERATOR',\n states.NavigateToObserve(robot,\n current_old_guest,\n radius=1.0,\n margin=1.0), # Makes the robot go within 2m of current_old_guest\n transitions={'arrived': 'SAY_LOOK_AT_GUEST',\n 'unreachable': 'SAY_LOOK_AT_GUEST',\n 'goal_not_defined': 'SAY_LOOK_AT_GUEST'})\n\n smach.StateMachine.add('SAY_LOOK_AT_GUEST',\n states.SayFormatted(robot,\n [\"Hi {name}, let me show you our guest\"],\n name=ds.Designator(challenge_knowledge.operator_name) if assume_john else ds.AttrDesignator(current_old_guest, \"person_properties.name\", resolve_type=str),\n block=True),\n transitions={'spoken': 'TURN_TO_GUEST'})\n\n smach.StateMachine.add('TURN_TO_GUEST',\n states.Turn(robot=robot,\n radians=radians(180)),\n transitions={\"turned\": \"FIND_GUEST\"})\n\n smach.StateMachine.add('FIND_GUEST',\n states.FindPerson(robot=robot,\n person_label=guest_name_des,\n search_timeout=30,\n found_entity_designator=guest_ent_des.writeable,\n speak_when_found=False),\n transitions={\"found\": \"POINT_AT_GUEST\",\n \"failed\": \"INTRODUCE_GUEST_WITHOUT_POINTING\"})\n\n smach.StateMachine.add('POINT_AT_GUEST',\n states.PointAt(robot=robot,\n arm_designator=ds.UnoccupiedArmDesignator(robot,{'required_goals':['point_at']}),\n point_at_designator=guest_ent_des,\n look_at_designator=current_old_guest),\n transitions={\"succeeded\": \"INTRODUCE_GUEST_BY_POINTING\",\n \"failed\": \"INTRODUCE_GUEST_WITHOUT_POINTING\"})\n\n smach.StateMachine.add('INTRODUCE_GUEST_BY_POINTING',\n states.Say(robot, GuestDescriptionStrDesignator(guest_name_des, guest_drinkname_des),\n block=True,\n look_at_standing_person=True),\n transitions={'spoken': 'RESET_ARM'})\n\n smach.StateMachine.add('INTRODUCE_GUEST_WITHOUT_POINTING',\n states.SayFormatted(robot,\n \"Our new guest is {name} who likes {drink}\",\n name=guest_name_des, drink=guest_drinkname_des,\n block=True,\n look_at_standing_person=True),\n transitions={'spoken': 'RESET_ARM'})\n\n smach.StateMachine.add('RESET_ARM',\n states.ResetArms(robot),\n transitions={'done': 'succeeded' if assume_john else 'ITERATE_OLD_GUESTS'})\n\n\nif __name__ == \"__main__\":\n import sys\n from robot_skills import get_robot\n\n if len(sys.argv) < 3:\n print(\"Please provide robot_name, room and seats_to_inspect as arguments. Eg. 'hero livingroom dinner_table bar dinnertable\")\n sys.exit(1)\n\n robot_name = sys.argv[1]\n room = sys.argv[2]\n seats_to_inspect = sys.argv[3:]\n\n rospy.init_node('test_find_emtpy_seat')\n robot = get_robot(robot_name)\n\n guest_entity_des = ds.VariableDesignator(resolve_type=Entity, name='guest_entity')\n guest_name_des = ds.VariableDesignator('dummy_guest', name='guest_name')\n guest_drinkname_des = ds.VariableDesignator('dummy_drink', name='guest_drinkname')\n\n sm = IntroduceGuest(robot,\n guest_entity_des,\n guest_name_des,\n guest_drinkname_des)\n\n sm.execute()\n\n rospy.loginfo(\"Guest is {}\".format(guest_entity_des.resolve()))\n","sub_path":"challenge_receptionist/src/challenge_receptionist/introduce_guest.py","file_name":"introduce_guest.py","file_ext":"py","file_size_in_byte":8005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"101068091","text":"# Copyright 2021 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# ==============================================================================\n\"\"\"Tests for lit_nlp.lib.image_utils.\"\"\"\n\nfrom absl.testing import absltest\nfrom lit_nlp.lib import image_utils\nimport numpy as np\nfrom PIL import Image as PILImage\n\n\nclass CachingTest(absltest.TestCase):\n\n def test_format_conversions(self):\n # Create a PIL image.\n image_array = np.zeros(shape=(100, 70, 3), dtype=np.uint8)\n for i in range(1000):\n image_array[i % 100, i % 70, i % 3] = i % 256\n pil_image = PILImage.fromarray(image_array)\n\n # Test conversion of the PIL image to string.\n image_str = image_utils.convert_pil_to_image_str(pil_image)\n self.assertIsNotNone(image_str)\n\n # Test conversion of the string back to PIL image.\n pil_image_2 = image_utils.convert_image_str_to_pil(image_str)\n image_array_2 = np.asarray(pil_image_2)\n np.testing.assert_array_equal(image_array, image_array_2)\n\n # Test conversion of the string back to array.\n image_array_3 = image_utils.convert_image_str_to_array(\n image_str, shape=(100, 70, 3))\n np.testing.assert_array_almost_equal(image_array / 255, image_array_3)\n\n def test_clip_unsigned_saliency(self):\n a = np.linspace(0, 100, num=101, endpoint=True)\n a_clipped = image_utils.clip_unsigned_saliency(a, fraction=0.1)\n self.assertEqual(a_clipped.min(), 0)\n self.assertEqual(a_clipped.max(), 90)\n self.assertLen(np.argwhere(a_clipped == 0), 1)\n self.assertLen(np.argwhere(a_clipped == 90), 11)\n\n def test_clip_signed_saliency(self):\n a = np.linspace(-50, 100, num=151, endpoint=True)\n a_clipped = image_utils.clip_signed_saliency(a, fraction=0.1)\n self.assertEqual(a_clipped.min(), -42)\n self.assertEqual(a_clipped.max(), 92)\n self.assertLen(np.argwhere(a_clipped == -42), 9)\n self.assertLen(np.argwhere(a_clipped == 92), 9)\n\n def test_normalize_unsigned_saliency(self):\n a = np.linspace(10, 100, num=101, endpoint=True)\n a_norm = image_utils.normalize_unsigned_saliency(a)\n self.assertAlmostEqual(a_norm.max(), 1.0)\n self.assertAlmostEqual(a_norm.min(), 0.0)\n\n def test_normalize_signed_saliency(self):\n # Test the case when the magnitude of positive numbers is higher.\n a = np.linspace(-10, 100, num=101, endpoint=True)\n a_norm = image_utils.normalize_signed_saliency(a)\n self.assertAlmostEqual(a_norm.max(), 1.0)\n self.assertAlmostEqual(a_norm.min(), 0.45)\n\n # Test the case when the magnitude of negative numbers is higher.\n a = np.linspace(-100, 10, num=101, endpoint=True)\n a_norm = image_utils.normalize_signed_saliency(a)\n self.assertAlmostEqual(a_norm.max(), 0.55)\n self.assertAlmostEqual(a_norm.min(), 0.0)\n\n def test_overlay_pixel_saliency(self):\n # Crate url encoded image representation.\n image_array = np.zeros(shape=(100, 70, 3), dtype=np.uint8)\n pil_image = PILImage.fromarray(image_array)\n image_str = image_utils.convert_pil_to_image_str(pil_image)\n\n # Create saliency.\n saliency = np.ones(shape=(50, 20), dtype=np.uint8)\n\n overlay_image = image_utils.overlay_pixel_saliency(\n image_str=image_str,\n saliency=saliency,\n cm_name='bwr',\n clip_fraction=0.01,\n alpha_mul=0.90,\n signed=True,\n pixel_saliency=True)\n self.assertIsNotNone(overlay_image)\n self.assertSequenceEqual((100, 70, 3), np.asarray(overlay_image).shape)\n\n def test_overlay_area_saliency(self):\n # Crate url encoded image representation.\n image_array = np.zeros(shape=(90, 70, 3), dtype=np.uint8)\n pil_image = PILImage.fromarray(image_array)\n image_str = image_utils.convert_pil_to_image_str(pil_image)\n\n # Create saliency.\n saliency = np.ones(shape=(50, 30), dtype=np.uint8)\n\n overlay_image = image_utils.overlay_pixel_saliency(\n image_str=image_str,\n saliency=saliency,\n cm_name='bwr',\n clip_fraction=0.01,\n alpha_mul=0.90,\n signed=False,\n pixel_saliency=False)\n self.assertIsNotNone(overlay_image)\n self.assertSequenceEqual((90, 70, 3), np.asarray(overlay_image).shape)\n\n\nif __name__ == '__main__':\n absltest.main()\n","sub_path":"lit_nlp/lib/image_utils_test.py","file_name":"image_utils_test.py","file_ext":"py","file_size_in_byte":4691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"190789319","text":"#TASKS (4p)\n\n#1 calculate & print the value of function y = 2x^2 + 2x + 2 for x=[56, 57, ... 100] (0.5p)\n\nprint(\"\\nTask 1:\")\ny = lambda x: 2*x**2 + 2*x + 2\nfor i in range(56,101):\n print(f\"y({i}) = {y(i)}\")\n\n\n#2 ask the user for a number and print its factorial (1p)\n\nwhile True:\n try:\n x = input(\"\\nTask 2:\\nInsert the natural number: \")\n try: x = float(x)\n except: raise ValueError(\"Your input is not a number.\")\n if (x % 1) != 0: raise ValueError(\"Your number is not of integer type.\")\n x = int(x)\n if x < 0: raise ValueError(\"Your integer is less than 0.\")\n y = 1\n for i in range(2,x+1):\n y *= i\n print(f\"{x}! = \",y)\n break\n except ValueError as err: print(\"Error: \", err)\n\n\n#3 write a function which takes an array of numbers as an input and finds the lowest value. Return the index of that element and its value (1p)\n\ndef f3(x):\n min = x[0]\n ind = 0\n for i in range(1,len(x)):\n if x[i] < min:\n min = x[i]\n ind = i\n return ind, min\nx = [1, 3, -9, 5, 0, -0.2, 101, -20]\nprint(\"\\nTask 3:\\n(index, value) = \", f3(x))\n\n\n#4 looking at lab1-input and lab1-plot files create your own python script that takes a number and returns any chart of a given length.\n#the length of a chart is the input to your script. The output is a plot (it doesn't matter if it's a y=x or y=e^x+2x or y=|x| function, use your imagination)\n#test your solution properly. Look how it behaves given different input values. (1p)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx = int(input(\"\\nTask 4:\\nInsert the natural number: \"))\ny = []\nfor i in range(x): y.append(i + 5 + np.random.randn())\nplt.scatter(np.arange(1,x+1),y)\nplt.title(\"Function f(x) = x + 5 with noisy data.\")\nplt.grid()\nplt.show()\n\n\n#5 upload the solution as a Github repository. I suggest creating a directory for the whole python course and subdirectories lab1, lab2 etc. (0.5p)\n#Ad 5 Hint write in Google \"how to create a github repo\". There are plenty of tutorials explaining this matter.\n\nprint(\"\\nDone.\")\n","sub_path":"lab1/lab1_solutions.py","file_name":"lab1_solutions.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"299844693","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass TA(object):\n def __init__(self, ohlcv):\n self.ohlcv = pd.DataFrame(data=ohlcv)\n\n # deconstuct ohlcv\n self.open = np.array(ohlcv['open'])\n self.high = np.array(ohlcv['high'])\n self.low = np.array(ohlcv['low'])\n self.close = np.array(ohlcv['close'])\n self.volume = np.array(ohlcv['volume'])\n\n def EMA(self, period, column='close'):\n \"\"\"\n Exponential Moving Average\n \"\"\"\n return self.ohlcv[column].ewm(ignore_na=False,\n min_periods=period - 1,\n span=period).mean()\n\n def DEMA(self, period, column='close'):\n \"\"\"\n Double Exponential Moving Average\n \"\"\"\n return 2 * self.EMA(period, column) - self.EMA(period, column).ewm(ignore_na=False,\n min_periods=period - 1,\n span=period).mean()\n\n def MACD(self, period_fast=12, period_slow=26, signal=9, column='close'):\n \"\"\"\n MACD Signal and MACD difference\n \"\"\"\n EMA_fast = self.ohlcv[column].ewm(ignore_na=False, min_periods=period_slow - 1, span=period_fast).mean()\n EMA_slow = self.ohlcv[column].ewm(ignore_na=False, min_periods=period_slow - 1, span=period_slow).mean()\n MACD = pd.Series(EMA_fast - EMA_slow, name='macd')\n MACD_signal = pd.Series(MACD.ewm(ignore_na=False, span=signal).mean(), name='signal')\n MACD_histo = pd.Series(MACD - MACD_signal, name='histo')\n\n return pd.concat([MACD, MACD_signal, MACD_histo], axis=1)\n\n def PPO(self, period_fast=12, period_slow=26, signal=9, column='close'):\n \"\"\"\n PPO\n \"\"\"\n EMA_fast = self.ohlcv[column].ewm(ignore_na=False, min_periods=period_slow - 1, span=period_fast).mean()\n EMA_slow = self.ohlcv[column].ewm(ignore_na=False, min_periods=period_slow - 1, span=period_slow).mean()\n\n PPO = pd.Series(((EMA_fast - EMA_slow)/EMA_slow) * 100, name='ppo')\n PPO_signal = pd.Series(PPO.ewm(ignore_na=False, span=signal).mean(), name='signal')\n PPO_histo = pd.Series(PPO - PPO_signal, name='histo')\n\n return pd.concat([PPO, PPO_signal, PPO_histo], axis=1)\n\n def RSI(self, period=14, column='close'):\n \"\"\"\n Relative Strength Index\n \"\"\"\n delta = self.ohlcv[column].diff()[1:]\n up, down = delta.copy(), delta.copy()\n up[up < 0] = 0\n down[down > 0] = 0\n\n gain = up.ewm(span=period, min_periods=period - 1).mean()\n loss = down.abs().ewm(span=period, min_periods=period - 1).mean()\n\n return 100 - (100 / (1 + (gain / loss)))\n\n def STOCHRSI(self, rsi_period=14, stoch_period=14, column='close'):\n \"\"\"\n Stochatic RSI\n \"\"\"\n rsi = self.RSI(rsi_period, column)\n\n return ((rsi - rsi.min()) / (rsi.max() - rsi.min())).rolling(window=stoch_period).mean()\n\n def STOCH(self, period=14, d_period=3, column='close'):\n \"\"\"\n Stochastic Oscillator\n \"\"\"\n highest_high = self.ohlcv['high'].rolling(center=False, window=period).max()\n lowest_low = self.ohlcv['low'].rolling(center=False, window=period).min()\n\n stoch_k = pd.Series((highest_high - self.ohlcv['close']) / (highest_high - lowest_low), name='stoch_k') * 100\n stoch_d = pd.Series(stoch_k.rolling(center=False, window=period, min_periods=period - 1).mean(), name='stoch_d')\n ratio = pd.Series(stoch_k - stoch_d, name='ratio')\n\n return pd.concat([stoch_k, stoch_d, ratio], axis=1)\n\n def FISH(self, period=10):\n \"\"\"\n Fisher Transform\n \"\"\"\n med = (self.ohlcv['high'] + self.ohlcv['low']) / 2\n low = med.rolling(window=period).min()\n high = med.rolling(window=period).max()\n raw = (2 * ((med - low) / (high - low))) - 1\n smooth = raw.ewm(span=5).mean()\n\n fisher = pd.Series((np.log((1 + smooth) / (1 - smooth))).ewm(span=3).mean(), name='fisher')\n trigger = pd.Series(np.concatenate([[np.nan], fisher[:-1]]), name='trigger')\n histo = pd.Series(fisher - trigger, name='histo')\n\n return pd.concat([fisher, trigger, histo], axis=1)\n\n def SAR(self, acceleration_factor=0.02, acc_max=0.2):\n \"\"\"\n Stop and Reverse\n \"\"\"\n # signal, extreme-point, acceleration factor\n sig0, xpt0, af0 = True, self.high[0], acceleration_factor\n sar = [self.low[0] - (self.high - self.low).std()]\n\n for i in range(1, len(self.high)):\n sig1, xpt1, af1 = sig0, xpt0, af0\n\n lmin = min(self.low[i - 1], self.low[i])\n lmax = max(self.high[i - 1], self.high[i])\n\n if sig1:\n sig0 = self.low[i] > sar[-1]\n xpt0 = max(lmax, xpt1)\n else:\n sig0 = self.high[i] >= sar[-1]\n xpt0 = min(lmin, xpt1)\n\n if sig0 == sig1:\n sari = sar[-1] + (xpt1 - sar[-1])*af1\n af0 = min(acc_max, af1 + acceleration_factor)\n\n if sig0:\n af0 = af0 if xpt0 > xpt1 else af1\n sari = min(sari, lmin)\n else:\n af0 = af0 if xpt0 < xpt1 else af1\n sari = max(sari, lmax)\n else:\n af0 = acceleration_factor\n sari = xpt0\n\n sar.append(sari)\n\n return pd.Series(sar, name='sar')\n\n def TR(self):\n \"\"\"\n True Range\n \"\"\"\n tr1 = pd.Series(self.ohlcv['high'] - self.ohlcv['low']).abs()\n tr2 = pd.Series(self.ohlcv['high'] - self.ohlcv['close'].shift()).abs()\n tr3 = pd.Series(self.ohlcv['close'].shift() - self.ohlcv['low']).abs()\n\n tr = pd.concat([tr1, tr2, tr3], axis=1)\n\n return tr.max(axis=1)\n\n def VORTEX(self, period=14):\n \"\"\"\n Vortex\n \"\"\"\n VMP = pd.Series(self.ohlcv['high'] - self.ohlcv['low'].shift(-1).abs())\n VMM = pd.Series(self.ohlcv['low'] - self.ohlcv['high'].shift(-1).abs())\n\n VMPx = VMP.rolling(window=period).sum()\n VMMx = VMM.rolling(window=period).sum()\n\n VIp = pd.Series(VMPx / self.TR(), name='VI+').interpolate(method='index')\n VIm = pd.Series(VMMx / self.TR(), name='VI-').interpolate(method='index')\n pm_ratio = pd.Series(VIp + VIm, name='ratio')\n\n # remove bad values\n pm_ratio[np.isnan(pm_ratio)] = 0\n\n return pd.concat([VIm, VIp, pm_ratio], axis=1)\n\n def BASP(self, period=40):\n \"\"\"\n Buy and Sell Pressure\n \"\"\"\n sp = self.ohlcv['high'] - self.ohlcv['close']\n bp = self.ohlcv['close'] - self.ohlcv['low']\n sp_avg = sp.ewm(span=period, min_periods=period - 1).mean()\n bp_avg = bp.ewm(span=period, min_periods=period - 1).mean()\n\n v_avg = self.ohlcv['volume'].ewm(span=period, min_periods=period - 1).mean()\n nv = self.ohlcv['volume'] / v_avg\n\n buy_press = pd.Series(bp / bp_avg * nv, name='buy')\n sell_press = pd.Series(sp / sp_avg * nv, name='sell')\n press_ratio = pd.Series(buy_press - sell_press, name='ratio')\n\n return pd.concat([buy_press, sell_press, press_ratio], axis=1)\n\n def graph(self,\n include_open=False,\n include_high=False,\n include_low=False,\n include_close=False,\n **kwargs):\n\n if include_open: plt.plot(self.open, label='open')\n if include_high: plt.plot(self.high, label='high')\n if include_low: plt.plot(self.low, label='low')\n if include_close: plt.plot(self.close, label='close')\n\n for key, value in kwargs.items():\n plt.plot(value, label=key)\n\n leg = plt.legend(loc='best', shadow=True)\n leg.get_frame().set_alpha(0.5)\n\n plt.show()\n\n def remove_NaN(self, inputs):\n valid_idx = 0\n for check in np.isnan(inputs):\n if True in check: valid_idx += 1\n else: break\n\n return valid_idx\n\n\nif __name__ == '__main__':\n data = {'open': [32, 33, 19, 25, 29, 37, 38, 35, 32, 38, 42, 49],\n 'high': [36, 35, 25, 29, 31, 40, 41, 39, 33, 45, 50, 51],\n 'low': [32, 33, 19, 25, 29, 37, 38, 35, 32, 38, 42, 49],\n 'close':[31, 31, 14, 24, 25, 32, 37, 32, 29, 31, 40, 45],\n 'volume': [150, 200, 172, 177, 163, 189, 111, 98, 211, 215, 70, 98]}\n\n ta = TA(data)\n ema_3 = ta.EMA(3).values\n ema_5 = ta.EMA(5).values\n dema_3 = ta.DEMA(3).values\n\n ta.graph(include_close=True,\n EMA_3=ema_3,\n EMA_5=ema_5,\n DEMA_3=dema_3)\n","sub_path":"ta/ta.py","file_name":"ta.py","file_ext":"py","file_size_in_byte":8779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"354066052","text":"# -*- coding: utf-8 -*- #\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\"\"\"Integration tests for set-service-account command.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.calliope import base as calliope_base\nfrom tests.lib.surface.compute import e2e_instances_test_base\nfrom tests.lib.surface.compute import e2e_test_base\n\n\nclass SetServiceAccountTest(e2e_instances_test_base.InstancesTestBase):\n\n def SetUp(self):\n self.track = calliope_base.ReleaseTrack.GA\n\n def testInstanceSetServiceAccount(self):\n self.GetInstanceName()\n self.Run('compute instances create {} --zone {} '.format(\n self.instance_name, self.zone))\n self.Run('compute instances stop --zone {} {}'.format(\n self.zone, self.instance_name))\n self.Run('compute instances set-service-account --scopes \"\" --zone {} {}'\n .format(self.zone, self.instance_name))\n result = self.Run('compute instances describe {} --zone {} --format=disable'\n .format(self.instance_name, self.zone))\n self.assertEqual(result.serviceAccounts[0].scopes, [],\n result.serviceAccounts[0].scopes)\n\n def testRemoveServiceAccount(self):\n self.GetInstanceName()\n self.Run('compute instances create {} --zone {} '.format(\n self.instance_name, self.zone))\n self.Run('compute instances stop --zone {} {}'.format(\n self.zone, self.instance_name))\n self.Run('compute instances set-service-account '\n '--no-service-account '\n '--no-scopes '\n ' --zone {} {}'.format(self.zone, self.instance_name))\n result = self.Run('compute instances describe {} --zone {} --format=disable'\n .format(self.instance_name, self.zone))\n self.assertEqual(result.serviceAccounts, [], result.serviceAccounts)\n\n def testChangeServiceAccounts(self):\n new_service_account = ('cloud-sdk-integration-testing'\n '@appspot.gserviceaccount.com')\n self.GetInstanceName()\n self.Run('compute instances create {} --zone {} '.format(\n self.instance_name, self.zone))\n self.Run('compute instances stop --zone {} {}'.format(\n self.zone, self.instance_name))\n self.Run('compute instances set-service-account '\n '--service-account {}'\n ' --zone {} {}'.format(new_service_account, self.zone,\n self.instance_name))\n result = self.Run('compute instances describe {} --zone {} --format=disable'\n .format(self.instance_name, self.zone))\n self.assertEqual(new_service_account, result.serviceAccounts[0].email)\n\n def testAttemptChangeServiceAccountOnRunningInstance(self):\n self.GetInstanceName()\n self.Run('compute instances create {} --zone {} '.format(\n self.instance_name, self.zone))\n with self.AssertRaisesToolExceptionRegexp(\n r'.*The instance must be stopped before the service account can be '\n r'changed\\..*'):\n self.Run('compute instances set-service-account '\n '--service-account {}'\n ' --zone {} {}'.format(\n 'cloud-sdk-integration-testing@appspot.gserviceaccount.com',\n self.zone, self.instance_name))\n\n\nif __name__ == '__main__':\n e2e_test_base.main()\n","sub_path":"google-cloud-sdk/lib/tests/e2e/surface/compute/instances/set_service_account_test.py","file_name":"set_service_account_test.py","file_ext":"py","file_size_in_byte":3910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"525937599","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 ('environments', '0001_initial'),\n ('companies', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Environmentsvariables',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('variables', models.TextField()),\n ('company', models.ForeignKey(related_name='environmentsvariables_fk_to_companies', to='companies.Companies')),\n ('environment', models.ForeignKey(related_name='environmentsvariables_fk_to_environments', to='environments.Environments')),\n ],\n options={\n 'ordering': ('-id',),\n 'db_table': 'environmentsvariables',\n },\n ),\n migrations.AlterUniqueTogether(\n name='environmentsvariables',\n unique_together=set([('company', 'environment')]),\n ),\n ]\n","sub_path":"apps/tmt/environmentsvariables/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"250048954","text":"from iseprobe import iseprobe\n\nPROBE_MV_TO_PH = 59.2\nTEMP_CORRECTION_FACTOR = 0.03\n\n\nclass ise_ph(iseprobe):\n pH = 0\n pOH = 0\n\n def measurepH(self):\n self.measuremV()\n if self.mV == -1:\n self.pH = -1\n self.pOH = -1\n return -1\n\n self.pH = abs(7.0 - (self.mV / PROBE_MV_TO_PH))\n self.pOH = abs(self.pH - 14)\n\n if self.usingTemperatureCompensation() is True:\n self.measureTemp()\n\n distance_from_7 = abs(7 - round(self.pH))\n distance_from_25 = floor(abs(25 - round(temp)) / 10)\n temp_multiplier = (distance_from_25 * distance_from_7) * TEMP_CORRECTION_FACTOR\n\n if (self.pH >= 8.0) and (self.tempC >= 35):\n temp_multiplier *= -1\n if (self.pH <= 6.0) and (temp <= 15):\n temp_multiplier *= -1\n\n self.pH += temp_multiplier\n\n if self.pH <= 0.0 or self.pH >= 14.0:\n self.pH = -1\n self.pOH = -1\n if math.isnan(self.pH):\n self.pH = -1\n self.pOH = -1\n if math.isinf(mV):\n self.pH = -1\n self.pOH = -1\n return self.pH\n\n def calibrateSingle(self, solutionpH):\n super(iseprobe, self).calibrateSingle(pHtomV(solutionpH))\n\n def calibrateProbeHigh(self, solutionpH):\n super(iseprobe, self).calibrateProbeHigh(pHtomV(solutionpH))\n\n def calibrateProbeLow(self, solutionpH):\n super(iseprobe, self).calibrateProbeLow(pHtomV(solutionpH))\n\n def pHtomV(self, pH):\n return (7 - pH) * PROBE_MV_TO_PH\n","sub_path":"python/RaspberryPi/ise_ph.py","file_name":"ise_ph.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"625107081","text":"# imports\nimport django\nfrom elasticsearch import Elasticsearch\nimport json\nimport os\nimport re\nimport sys\n\n# import Row from pyspark\ntry:\n from pyspark.sql import Row\n from pyspark.sql.types import StringType, IntegerType\n from pyspark.sql.functions import udf, lit\nexcept:\n pass\n\n# pylint: disable=wrong-import-position\n# check for registered apps signifying readiness, if not, run django.setup() to run as standalone\nif not hasattr(django, 'apps'):\n os.environ['DJANGO_SETTINGS_MODULE'] = 'combine.settings'\n sys.path.append('/opt/combine')\n django.setup()\n\n# import django settings\nfrom django.conf import settings\n\n# import xml2kvp\ntry:\n from core.xml2kvp import XML2kvp\nexcept:\n from xml2kvp import XML2kvp\n\n\nclass ESIndex():\n\n \"\"\"\n Class to organize methods for indexing mapped/flattened metadata into ElasticSearch (ES)\n \"\"\"\n\n @staticmethod\n def index_job_to_es_spark(spark, job, records_df, field_mapper_config):\n \"\"\"\n Method to index records dataframe into ES\n\n Args:\n spark (pyspark.sql.session.SparkSession): spark instance from static job methods\n job (core.models.Job): Job for records\n records_df (pyspark.sql.DataFrame): records as pyspark DataFrame\n field_mapper_config (dict): XML2kvp field mapper configurations\n\n Returns:\n None\n - indexes records to ES\n \"\"\"\n\n # init logging support\n spark.sparkContext.setLogLevel('INFO')\n log4jLogger = spark.sparkContext._jvm.org.apache.log4j\n logger = log4jLogger.LogManager.getLogger(__name__)\n\n # get index mapper\n index_mapper_handle = globals()['XML2kvpMapper']\n\n # create rdd from index mapper\n def es_mapper_pt_udf(pt):\n\n # init mapper once per partition\n mapper = index_mapper_handle(\n field_mapper_config=field_mapper_config)\n\n for row in pt:\n yield mapper.map_record(\n record_string=row.document,\n db_id=row._id.oid,\n combine_id=row.combine_id,\n record_id=row.record_id,\n publish_set_id=job.publish_set_id,\n fingerprint=row.fingerprint\n )\n\n logger.info('###ES 1 -- mapping records')\n mapped_records_rdd = records_df.rdd.mapPartitions(es_mapper_pt_udf)\n\n # attempt to write index mapping failures to DB\n # filter our failures\n logger.info('###ES 2 -- filtering failures')\n failures_rdd = mapped_records_rdd.filter(lambda row: row[0] == 'fail')\n\n # if failures, write\n if not failures_rdd.isEmpty():\n logger.info('###ES 3 -- writing indexing failures')\n\n failures_df = failures_rdd.map(lambda row: Row(\n db_id=row[1]['db_id'],\n record_id=row[1]['record_id'],\n mapping_error=row[1]['mapping_error']\n )).toDF()\n\n # add job_id as column\n failures_df = failures_df.withColumn('job_id', lit(job.id))\n\n # write mapping failures to DB\n failures_df.select(['db_id', 'record_id', 'job_id', 'mapping_error'])\\\n .write.format(\"com.mongodb.spark.sql.DefaultSource\")\\\n .mode(\"append\")\\\n .option(\"uri\", \"mongodb://127.0.0.1\")\\\n .option(\"database\", \"combine\")\\\n .option(\"collection\", \"index_mapping_failure\").save()\n\n # retrieve successes to index\n logger.info('###ES 4 -- filtering successes')\n to_index_rdd = mapped_records_rdd.filter(\n lambda row: row[0] == 'success')\n\n # create index in advance\n index_name = 'j%s' % job.id\n es_handle_temp = Elasticsearch(hosts=[settings.ES_HOST])\n if not es_handle_temp.indices.exists(index_name):\n # put combine es index templates\n template_body = {\n 'template': '*',\n 'settings': {\n 'number_of_shards': 1,\n 'number_of_replicas': 0,\n 'refresh_interval': -1\n },\n 'mappings': {\n \"dynamic_templates\": [\n {\n \"strings\": {\n \"match_mapping_type\": \"string\",\n \"mapping\": {\n \"type\": \"text\",\n \"fields\": {\n \"keyword\": {\n \"type\": \"keyword\"\n }\n }\n }\n }\n }\n ],\n 'date_detection': False,\n 'properties': {\n 'combine_db_id': {\n 'type': 'integer'\n }\n }\n }\n }\n es_handle_temp.indices.put_template(\n 'combine_template', body=json.dumps(template_body))\n\n # create index\n es_handle_temp.indices.create(index_name)\n\n # index to ES\n logger.info('###ES 5 -- writing to ES')\n to_index_rdd.saveAsNewAPIHadoopFile(\n path='-',\n outputFormatClass=\"org.elasticsearch.hadoop.mr.EsOutputFormat\",\n keyClass=\"org.apache.hadoop.io.NullWritable\",\n valueClass=\"org.elasticsearch.hadoop.mr.LinkedMapWritable\",\n conf={\n \"es.resource\": \"%s/_doc\" % index_name,\n \"es.nodes\": \"%s:9200\" % settings.ES_HOST,\n \"es.nodes.wan.only\": \"true\",\n \"es.mapping.exclude\": \"temp_id,__class__\",\n \"es.mapping.id\": \"temp_id\",\n }\n )\n\n # refresh index\n es_handle_temp.indices.refresh(index_name)\n\n # return\n return to_index_rdd\n\n @staticmethod\n def copy_es_index(\n source_index=None,\n target_index=None,\n create_target_index=True,\n refresh=True,\n wait_for_completion=True,\n add_copied_from=None):\n \"\"\"\n Method to duplicate one ES index to another\n\n Args:\n create_target_index (boolean): If True, check for target and create\n source_index (str): Source ES index to copy from\n target_index (str): Target ES index to copy to\n\n Returns:\n (dict): results of reindex via elasticsearch client reindex request\n \"\"\"\n\n # get ES handle\n es_handle_temp = Elasticsearch(hosts=[settings.ES_HOST])\n\n # put/confirm combine es index templates\n template_body = {\n 'template': '*',\n 'settings': {\n 'number_of_shards': 1,\n 'number_of_replicas': 0,\n 'refresh_interval': -1\n },\n 'mappings': {\n 'date_detection': False,\n 'properties': {\n 'combine_db_id': {\n 'type': 'integer'\n }\n }\n }\n }\n es_handle_temp.indices.put_template(\n 'combine_template', body=json.dumps(template_body))\n\n # if creating target index check if target index exists\n if create_target_index and not es_handle_temp.indices.exists(target_index):\n es_handle_temp.indices.create(target_index)\n\n # prepare reindex query\n dupe_dict = {\n 'source': {\n 'index': source_index,\n 'query': {}\n },\n 'dest': {\n 'index': target_index\n }\n }\n\n # if add_copied_from, include in reindexed document\n if add_copied_from:\n dupe_dict['script'] = {\n 'inline': 'ctx._source.source_job_id = %s' % add_copied_from,\n 'lang': 'painless'\n }\n\n # reindex using elasticsearch client\n params = {'wait_for_completion': wait_for_completion, 'refresh': refresh}\n reindex = es_handle_temp.reindex(body=dupe_dict, params=params)\n return reindex\n\n\nclass BaseMapper():\n\n \"\"\"\n All mappers extend this BaseMapper class.\n\n Contains some useful methods and attributes that other mappers may use\n\n Mappers expected to contain following methods:\n - map_record()\n \"\"\"\n\n # pre-compiled regex\n blank_check_regex = re.compile(r\"[^ \\t\\n]\") # checker for blank spaces\n namespace_prefix_regex = re.compile(r'(\\{.+\\})?(.*)') # element tag name\n\n def get_namespaces(self):\n \"\"\"\n Method to parse namespaces from XML document and save to self.nsmap\n \"\"\"\n\n nsmap = {}\n for ns in self.xml_root.xpath('//namespace::*'):\n if ns[0]:\n nsmap[ns[0]] = ns[1]\n self.nsmap = nsmap\n\n # set inverted nsmap\n self.nsmap_inv = {v: k for k, v in self.nsmap.items()}\n\n\nclass XML2kvpMapper(BaseMapper):\n \"\"\"\n Map XML to ElasticSearch friendly fields with XML2kvp\n \"\"\"\n\n def __init__(self, field_mapper_config=None):\n\n self.field_mapper_config = field_mapper_config\n\n def map_record(self,\n record_string=None,\n db_id=None,\n combine_id=None,\n record_id=None,\n publish_set_id=None,\n fingerprint=None\n ):\n \"\"\"\n Map record\n\n Args:\n record_string (str): string of record document\n db_id (str): mongo db id\n combine_id (str): combine_id id\n record_id (str): record id\n publish_set_id (str): core.models.RecordGroup.published_set_id, used to build publish identifier\n fingerprint (str): fingerprint\n\n Returns:\n (tuple):\n 0 (str): ['success','fail']\n 1 (dict): details from mapping process, success or failure\n \"\"\"\n\n try:\n\n # prepare literals\n if 'add_literals' not in self.field_mapper_config.keys():\n self.field_mapper_config['add_literals'] = {}\n\n # add literals\n self.field_mapper_config['add_literals'].update({\n\n # add temporary id field\n 'temp_id': db_id,\n\n # add combine_id field\n 'combine_id': combine_id,\n\n # add record_id field\n 'record_id': record_id,\n\n # add publish set id\n 'publish_set_id': publish_set_id,\n\n # add record's Combine DB id\n 'db_id': db_id,\n\n # add record's crc32 document hash, aka \"fingerprint\"\n 'fingerprint': fingerprint,\n\n })\n\n # map with XML2kvp\n kvp_dict = XML2kvp.xml_to_kvp(\n record_string, **self.field_mapper_config)\n\n return (\n 'success',\n kvp_dict\n )\n\n except Exception as e:\n\n return (\n 'fail',\n {\n 'db_id': db_id,\n 'record_id': record_id,\n 'mapping_error': str(e)\n }\n )\n","sub_path":"core/spark/es.py","file_name":"es.py","file_ext":"py","file_size_in_byte":11830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"629863906","text":"import pytest\n\nfrom powersimdata.design.investment.inflation import calculate_inflation\nfrom powersimdata.design.investment.investment_costs import (\n _calculate_ac_inv_costs,\n _calculate_dc_inv_costs,\n _calculate_gen_inv_costs,\n)\nfrom powersimdata.tests.mock_grid import MockGrid\n\n# bus_id is the index\nmock_bus = {\n \"bus_id\": [2010228, 2021106, 2010319, 2010320],\n \"lat\": [47.6146, 37.7849, 47.6408, 47.6408],\n \"lon\": [-122.326, -122.407, -122.339, -122.339],\n \"baseKV\": [100, 346, 230, 800],\n}\n\n# branch 10-12 from Seattle (s3, p1, NWPP Coal) to San Francisco (s25, p9, NP15) (~679 miles)\n# branch 13-14 are transformers (0 miles)\nmock_branch = {\n \"branch_id\": [10, 11, 12, 13, 14],\n \"rateA\": [0, 10, 1100, 30, 40],\n \"from_bus_id\": [2010228, 2010228, 2010319, 2010319, 2021106],\n \"to_bus_id\": [2021106, 2021106, 2021106, 2010320, 2021106],\n \"branch_device_type\": 3 * [\"Line\"] + 2 * [\"Transformer\"],\n}\nmock_branch[\"from_lat\"] = [\n mock_bus[\"lat\"][mock_bus[\"bus_id\"].index(bus)] for bus in mock_branch[\"from_bus_id\"]\n]\nmock_branch[\"from_lon\"] = [\n mock_bus[\"lon\"][mock_bus[\"bus_id\"].index(bus)] for bus in mock_branch[\"from_bus_id\"]\n]\nmock_branch[\"to_lat\"] = [\n mock_bus[\"lat\"][mock_bus[\"bus_id\"].index(bus)] for bus in mock_branch[\"to_bus_id\"]\n]\nmock_branch[\"to_lon\"] = [\n mock_bus[\"lon\"][mock_bus[\"bus_id\"].index(bus)] for bus in mock_branch[\"to_bus_id\"]\n]\n\nmock_plant = {\n \"plant_id\": [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\"],\n \"bus_id\": [2010228, 2010228, 2021106, 2010319, 2010319, 2010319, 2010320, 2021106],\n \"type\": [\"solar\", \"coal\", \"wind\", \"solar\", \"solar\", \"ng\", \"wind\", \"nuclear\"],\n \"Pmax\": [15, 30, 10, 12, 8, 20, 15, 1000],\n}\nmock_plant[\"lat\"] = [\n mock_bus[\"lat\"][mock_bus[\"bus_id\"].index(bus)] for bus in mock_plant[\"bus_id\"]\n]\nmock_plant[\"lon\"] = [\n mock_bus[\"lon\"][mock_bus[\"bus_id\"].index(bus)] for bus in mock_plant[\"bus_id\"]\n]\n\nmock_dcline = {\n \"dcline_id\": [5],\n \"Pmax\": [10],\n \"from_bus_id\": [2010228],\n \"to_bus_id\": [2021106],\n}\n\nmock_storage_gen = {\n \"Pmax\": [100, 200],\n \"bus_id\": [2010228, 2021106],\n \"type\": [\"storage\"] * 2,\n}\n\ngrid_attrs = {\n \"plant\": mock_plant,\n \"bus\": mock_bus,\n \"branch\": mock_branch,\n \"dcline\": mock_dcline,\n \"storage_gen\": mock_storage_gen,\n}\n\n\n@pytest.fixture\ndef mock_grid():\n return MockGrid(grid_attrs)\n\n\ndef test_calculate_ac_inv_costs(mock_grid):\n expected_ac_cost = {\n # ((reg_mult1 + reg_mult2) / 2) * sum(basecost * rateA * miles)\n \"line_cost\": (\n ((1 + 2.25) / 2)\n * (3666.67 * 10 * 679.179925842 + 1500 * 1100 * 680.986501516)\n * calculate_inflation(2010)\n ),\n # for each: rateA * basecost * regional multiplier\n \"transformer_cost\": ((30 * 7670 * 1) + (40 * 8880 * 2.25))\n * calculate_inflation(2020),\n }\n ac_cost = _calculate_ac_inv_costs(mock_grid)\n assert ac_cost.keys() == expected_ac_cost.keys()\n for k in ac_cost.keys():\n assert ac_cost[k] == pytest.approx(expected_ac_cost[k])\n\n\ndef test_calculate_dc_inv_costs(mock_grid):\n expected_dc_cost = (\n # lines\n 10 * 679.1799258421203 * 457.1428571 * calculate_inflation(2015)\n # terminals\n + 135e3 * 10 * 2 * calculate_inflation(2020)\n )\n dc_cost = _calculate_dc_inv_costs(mock_grid)\n assert dc_cost == pytest.approx(expected_dc_cost)\n\n\ndef test_calculate_gen_inv_costs_2030(mock_grid):\n gen_inv_cost = _calculate_gen_inv_costs(mock_grid, 2030, \"Moderate\").to_dict()\n expected_gen_inv_cost = {\n # for each: capacity (kW) * regional multiplier * base technology cost\n \"solar\": sum(\n [\n 15e3 * 1.01701 * 836.3842785,\n 12e3 * 1.01701 * 836.3842785,\n 8e3 * 1.01701 * 836.3842785,\n ]\n ),\n \"coal\": 30e3 * 1.05221 * 4049.047403,\n \"wind\": 10e3 * 1.16979 * 1297.964758 + 15e3 * 1.04348 * 1297.964758,\n \"ng\": 20e3 * 1.050755 * 983.2351768,\n \"storage\": 100e3 * 1.012360 * 817 + 200e3 * 1.043730 * 817,\n \"nuclear\": 1000e3 * 1.07252 * 6727.799801,\n }\n inflation = calculate_inflation(2018)\n expected_gen_inv_cost = {k: v * inflation for k, v in expected_gen_inv_cost.items()}\n assert gen_inv_cost.keys() == expected_gen_inv_cost.keys()\n for k in gen_inv_cost.keys():\n assert gen_inv_cost[k] == pytest.approx(expected_gen_inv_cost[k])\n","sub_path":"powersimdata/design/investment/tests/test_investment_costs.py","file_name":"test_investment_costs.py","file_ext":"py","file_size_in_byte":4429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"440335910","text":"# -*- coding: utf-8 -*-\n\nfrom datetime import datetime, timedelta\n\nfrom pytz import timezone\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.utils import translation\nfrom django.utils.translation import ugettext as _\n\nfrom apps.competition.models import Activity, Competition, Participant\nfrom apps.lan.models import LAN, Attendee\nfrom apps.team.models import Team\nfrom apps.lottery.models import Lottery\n\nimport challonge\n\ndef main(request):\n lans = LAN.objects.filter(end_date__gte=datetime.now())\n if lans:\n next_lan = lans[0]\n return redirect('competitions_show_lan', lan_id=next_lan.id)\n else:\n context = {}\n competitions = Competition.objects.all()\n competitions = shorten_descriptions(competitions, 200)\n\n context['activities'] = Activity.objects.all()\n context['competitions'] = competitions\n context['active'] = 'all'\n\n breadcrumbs = (\n (settings.SITE_NAME, '/'),\n (_(u'Competitions'), ''),\n )\n context['breadcrumbs'] = breadcrumbs\n\n return render(request, 'competition/competitions.html', context)\n\n\ndef main_filtered(request, lan_id):\n lan = get_object_or_404(LAN, pk=lan_id)\n\n context = {}\n competitions = Competition.objects.filter(lan=lan)\n competitions = shorten_descriptions(competitions, 200)\n\n context['activities'] = Activity.objects.all()\n context['competitions'] = competitions\n context['active'] = 'all'\n context['lan'] = lan\n context['lotteries'] = Lottery.objects.filter(lan=lan)\n\n breadcrumbs = (\n (settings.SITE_NAME, '/'),\n (_(u'Competitions'), reverse('competitions')),\n (lan, '')\n )\n context['breadcrumbs'] = breadcrumbs\n\n return render(request, 'competition/competitions.html', context)\n\n\ndef activity_details(request, activity_id):\n lans = LAN.objects.filter(end_date__gte=datetime.now())\n if lans:\n next_lan = lans[0]\n return redirect('activity_details_show_lan', lan_id=next_lan.id, activity_id=activity_id)\n else:\n activity = get_object_or_404(Activity, pk=activity_id)\n\n context = {}\n competitions = Competition.objects.filter(activity=activity)\n competitions = shorten_descriptions(competitions, 200)\n\n context['active'] = activity.id\n context['activities'] = Activity.objects.all()\n context['competitions'] = competitions\n\n breadcrumbs = (\n (settings.SITE_NAME, '/'),\n ('Competitions', reverse('competitions')),\n (activity, ''),\n )\n context['breadcrumbs'] = breadcrumbs\n\n return render(request, 'competition/competitions.html', context)\n\n\ndef activity_details_filtered(request, lan_id, activity_id):\n lan = get_object_or_404(LAN, pk=lan_id)\n activity = get_object_or_404(Activity, pk=activity_id)\n\n context = {}\n competitions = Competition.objects.filter(lan=lan, activity=activity)\n competitions = shorten_descriptions(competitions, 200)\n\n context['active'] = activity.id\n context['activities'] = Activity.objects.all()\n context['competitions'] = competitions\n context['lan'] = lan\n\n breadcrumbs = (\n (settings.SITE_NAME, '/'),\n (_(u'Competitions'), reverse('competitions')),\n (lan, reverse('lan_details', kwargs={'lan_id': lan.id})),\n (activity, ''),\n )\n context['breadcrumbs'] = breadcrumbs\n\n return render(request, 'competition/competitions.html', context)\n\n\ndef shorten_descriptions(competitions, length):\n for c in competitions:\n if len(c.get_translation().translated_description) > length:\n c.get_translation().translated_description = c.get_translation().translated_description[:length-3] + '...'\n return competitions\n\n\ndef competition_details(request, competition_id):\n challonge.set_credentials('tordsk', 'nJPg1DF7ZxCjPHs3C58BYlrtGh2XG3tWxBLciigZ')\n context = {}\n competition = get_object_or_404(Competition, pk=competition_id)\n\n breadcrumbs = (\n (settings.SITE_NAME, '/'),\n (_(u'Competitions'), reverse('competitions')),\n (competition, ''),\n )\n\n context['breadcrumbs'] = breadcrumbs\n\n\n if request.user.is_superuser and len(competition.get_participants()[0])>1 or len(competition.get_participants()[1])>1:\n if request.method=='POST':\n if request.POST.get('op') =='s_checkin':\n #start check in\n competition.status = 2\n competition.save()\n dt = datetime.now(timezone('US/Eastern')) + timedelta(hours=1)\n challonge.tournaments.update(competition.challonge_url, start_at=dt, check_in_duration=60)\n elif request.POST.get('op') == 's_tourney':\n #start compo\n competition.status = 3\n competition.save()\n challonge.api.fetch_and_parse('POST', 'tournaments/'+str(competition.challonge_url)+'/process_check_ins')\n if len(competition.get_participants()[0])>1 or len(competition.get_participants()[1])>1:\n messages.info(request, 'Tournament has started!')\n challonge.tournaments.start(competition.challonge_url)\n for participant in Participant.objects.filter(competition=competition, checked_in=False):\n participant.delete()\n else:\n messages.error(request, 'Tournament must have at least 2 participants')\n elif request.POST.get('op') == 'f_tourney':\n #finalize competition\n competition.status = 4\n competition.save()\n challonge.api.fetch_and_parse('POST', 'tournaments/'+str(competition.challonge_url)+'/finalize')\n context['state'] = challonge.tournaments.show(competition.challonge_url)['state']\n\n teams, users = competition.get_participants()\n context['teams'] = teams\n context['users'] = users\n\n if competition.has_participant(request.user):\n if request.user in users:\n context['participating'] = 'solo'\n context['participant'] = get_object_or_404(Participant, user=request.user, competition=competition)\n\n else:\n context['participating'] = 'team'\n for team in teams:\n if request.user == team.leader:\n context['participant'] = Participant.objects.get(team=team, competition=competition)\n\n if competition.status > 2 and 'participant' in context:\n open_m = challonge.api.fetch_and_parse('GET', 'tournaments/'+str(competition.challonge_url)+'/matches',\n state='open', participant_id=str(context['participant'].challonge_id))\n\n\n for match in open_m:\n if match['state'] == 'open':\n context['open_match'] = match\n\n if competition.status == 3:\n if context['participant'].current_score < 0:\n messages.warning(request, \"You have not reported your score yet. Finish the match and report your score below\")\n else:\n messages.success(request, \"Your reported score is: \" + str(context['participant'].current_score) +\n \". Waiting for opponent to submit score\")\n\n\n #Insert placeholder image if the image_url is empty\n if not competition.activity.image_url:\n competition.activity.image_url = 'http://placehold.it/150x150'\n\n if request.user.is_authenticated():\n owned_teams = Team.objects.filter(leader=request.user)\n\n context['owned_teams'] = owned_teams\n else:\n messages.warning(request, _(u\"Please log in to register for the competition.\"))\n context['competition'] = competition\n\n return render(request, 'competition/competition.html', context)\n\n\n@login_required\ndef join(request, competition_id):\n competition = get_object_or_404(Competition, pk=competition_id)\n teams, users = competition.get_participants()\n challonge.set_credentials('tordsk', 'nJPg1DF7ZxCjPHs3C58BYlrtGh2XG3tWxBLciigZ')\n\n # Checks if the user is already in the competition with a team, solo queue should be\n # overridden by team signup, but not other way around\n for team in teams:\n if request.user == team.leader or request.user in team.members.all():\n messages.error(request, _(u\"You are already in this competition with \") + unicode(team))\n return redirect(competition)\n\n # Checks that a form was posted, and if it contains a team id\n if request.method == 'POST':\n team_id = request.POST.get('team')\n if team_id:\n team = get_object_or_404(Team, pk=team_id)\n\n # Check if team restrictions are in place\n if competition.enforce_team_size:\n if team.number_of_team_members() + 1 < competition.team_size:\n messages.error(request, _(unicode(team) + u\" does not have enough members (\") +\n str(team.number_of_team_members() + 1) + u\"/\" + str(competition.team_size) + u\")\")\n return redirect(competition)\n\n if competition.enforce_payment:\n paid = 0\n leader_attendee = Attendee.objects.get(lan=competition.lan, user=team.leader)\n if leader_attendee.has_paid or competition.lan.has_ticket(team.leader):\n paid += 1\n for member in team.members.all():\n if member not in competition.lan.attendees:\n messages.error(request, _(unicode(team) + u\" has at least one member that is not signed up for \"+\n unicode(competition.lan)))\n return redirect(competition)\n\n attendee = Attendee.objects.filter(lan=competition.lan, user=member.user)\n if attendee.has_paid or competition.lan.has_ticket(member.user):\n paid += 1\n if paid < competition.team_size:\n messages.error(request, _(unicode(team) + u\" does not have enough members that have paid (\") +\n str(paid) + u\"/\" + str(competition.team_size) + u\")\")\n return redirect(competition)\n\n # Go through all members of the team and delete their individual participation entries\n if request.user in users:\n participant = Participant.objects.get(user=request.user, competition=competition)\n participant.delete()\n\n members = team.members.all()\n participants = Participant.objects.filter(user__in=members)\n\n for participant in participants:\n participant.delete()\n\n # Add the team\n participant = Participant(team=team, competition=competition)\n participant.challonge_id = challonge.participants.create(competition.challonge_url,\n participant.team.title)['id']\n participant.save()\n\n else:\n # If solo signup and already signed\n if request.user in users:\n messages.error(request, _(u\"You are already in this competition as a solo player.\"))\n return redirect(competition)\n else:\n participant = Participant(user=request.user, competition=competition)\n if not competition.use_teams:\n participant.challonge_id = challonge.participants.create(competition.challonge_url,\n participant.user.username)['id']\n participant.save()\n messages.success(request, _(u\"You have been signed up for \") + unicode(competition))\n return redirect(competition)\n\n\n@login_required\ndef leave(request, competition_id):\n competition = get_object_or_404(Competition, pk=competition_id)\n\n # If not participating, do nothing\n if not competition.has_participant(request.user):\n messages.error(request, _(u\"You are not participating in this competition.\"))\n else:\n if request.method == 'POST':\n if request.user in competition.get_users():\n participant = Participant.objects.get(user=request.user, competition=competition)\n if participant.challonge_id:\n challonge.participants.destroy(competition.challonge_url, participant.challonge_id)\n participant.delete()\n messages.success(request, _(u\"You are no longer participating in \") + unicode(competition))\n else:\n was_leader = False\n for team in competition.get_teams():\n if request.user == team.leader:\n was_leader = True\n participant = Participant.objects.get(team=team, competition=competition)\n challonge.participants.destroy(competition.challonge_url, participant.challonge_id)\n participant.delete()\n messages.success(request, _(u\"You have removed \") + unicode(team) + _(u\" from \") + unicode(competition))\n if not was_leader:\n messages.error(request, \"You cannot remove %s from %s, you are not the team leader.\" % (team, competition))\n\n return redirect(competition)\n\n\n@login_required\ndef forfeit(request, competition_id):\n competition = get_object_or_404(Competition, pk=competition_id)\n messages.error(request, 'Forfeit not yet implemented!')\n return redirect(competition)\n\n\ndef translate_competitions(competitions):\n translated_competitions = []\n for competition in competitions:\n translated_competitions.append(competition.get_translation(language=translation.get_language()))\n return translated_competitions\n\n\ndef check_in(request, competition_id):\n competition = get_object_or_404(Competition, pk=competition_id)\n challonge.set_credentials('tordsk', 'nJPg1DF7ZxCjPHs3C58BYlrtGh2XG3tWxBLciigZ')\n if competition.has_participant(request.user):\n if competition.use_teams:\n for team in competition.get_teams():\n if request.user == team.leader:\n participant = get_object_or_404(Participant, team=team, competition=competition)\n else:\n participant = get_object_or_404(Participant, user=request.user, competition=competition)\n if participant.challonge_id:\n participant.checked_in = True\n participant.save()\n challonge.fetch('POST', 'tournaments/'+str(competition.challonge_url)+'/participants/'+ str(participant.challonge_id) + '/check_in')\n return redirect(competition)\n\ndef report_result(request, competition_id):\n competition = get_object_or_404(Competition, pk=competition_id)\n challonge.set_credentials('tordsk', 'nJPg1DF7ZxCjPHs3C58BYlrtGh2XG3tWxBLciigZ')\n open_matches = challonge.api.fetch_and_parse('GET', 'tournaments/'+str(competition.challonge_url)+'/matches',\n state='open')\n user_score = request.POST.get('user_score')\n csv = ''\n winner = ''\n user_position = 0\n current_match = ''\n other_player = ''\n\n if competition.use_teams:\n for team in competition.get_teams():\n if request.user == team.leader:\n user_part = Participant.objects.get(team=team, competition=competition)\n else:\n user_part = get_object_or_404(Participant, user=request.user, competition=competition)\n user_part.current_score = int(user_score)\n user_part.save()\n for match in open_matches:\n if str(match['player1-id']) == str(user_part.challonge_id):\n other_player = match['player2-id']\n user_position = 1\n current_match = match['id']\n else:\n if str(match['player2-id']) == str(user_part.challonge_id):\n other_player = match['player1-id']\n user_position = 2\n current_match = match['id']\n other_part = get_object_or_404(Participant, challonge_id=other_player, competition=competition)\n\n if other_part.current_score < 0:\n return redirect(competition)\n\n if other_part.current_score > user_part.current_score:\n winner = other_player\n else:\n winner = user_part.challonge_id\n\n if user_position == 1:\n csv = str(user_part.current_score) +'-'+ str(other_part.current_score)\n else:\n csv = str(other_part.current_score) +'-'+ str(user_part.current_score)\n\n #oppdater challonge matchen med resultat og vinner\n\n challonge.matches.update(competition.challonge_url, current_match, scores_csv =csv, winner_id = winner)\n\n #klargjør neste runde\n user_part.current_score = -1\n user_part.save()\n other_part.current_score = -1\n other_part.save()\n return redirect(competition)","sub_path":"apps/competition/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":17144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"571454375","text":"import os\nimport re\nimport yaml\nfrom datetime import datetime, timedelta\nfrom discord import Embed, channel, member, message\nfrom discord.ext import commands\nfrom apscheduler.schedulers.asyncio import AsyncIOScheduler\n\nbot = commands.Bot(command_prefix=\"!\")\nconfig = {}\nscheduler = AsyncIOScheduler()\nscheduler.start()\n# TODO aliases were never fully implemented in jerbot2, figure this out\n\n\ndef list_prettyprint(old_list: list):\n \"\"\"\n Prepares a list for easier viewing on Discord.\n Example:\n list_prettyprint([foo, bar])\n Returns:\n `foo, bar`\n \"\"\"\n return f'`{\", \".join(old_list)}`'\n\n\ndef load_config():\n successful = []\n with open('config.yaml') as cfg:\n try:\n config['main'] = yaml.safe_load(cfg)\n successful.append('main')\n except Exception as e:\n print(f'Failed to load main configuration. ({e})')\n\n for name in os.listdir('config'):\n if name.startswith('config') and name.endswith('yaml'):\n server_id = re.sub(r'\\D', '', name)\n with open('config/' + name) as cfg:\n try:\n config[server_id] = yaml.safe_load(cfg)\n successful.append(server_id)\n except Exception as e:\n print(f'Failed to load {name}. ({e})')\n return successful\n\n\ndef load_modules():\n successful = []\n for extension in sorted(config['main']['extensions']):\n try:\n bot.load_extension(f'modules.{extension}')\n successful.append(extension)\n except Exception as e:\n print(f'Failed to load {extension}. ({e})')\n return successful\n\n\nasync def write_embed(channel: channel, member: member, color, title, event='', avatar=True, footer=None, fields=None,\n message=None, description=None):\n \"\"\"\n :param channel: ID of the channel to send the log embed in.\n :param member: Member that is being referenced in this embed.\n :param color: Color of the embed.\n :param title: Title of the embed.\n :param event: Event that is triggering the embed write: Member Joined, Member Left, Member Banned, etc. Optional.\n :param avatar: If avatar should be displayed in moderation logs. Default: True\n :param fields: Optional. [[title, content]]\n :param footer: Optional. Footer for the embed.\n :param message: Optional. Message string to send alongside the embed.\n :param description: Optional. Description of the embed.\n :returns Sent message\n \"\"\"\n if fields is None:\n fields = []\n embed = Embed(color=color, title=title, description=description)\n embed.set_author(name=event)\n if avatar:\n embed.set_thumbnail(url=member.avatar_url if member.avatar_url else member.default_avatar_url)\n if fields:\n for field in fields:\n embed.add_field(name=field[0], value=field[1], inline=True)\n if footer:\n embed.set_footer(text=footer)\n return await bot.get_channel(channel).send(message, embed=embed)\n\nasync def write_message(channel: channel, message: message):\n \"\"\"\n :param channel: ID of the channel to send a message in.\n :param message: Message to send.\n \"\"\"\n await bot.get_channel(channel).send(message)\n\n\ndef check_roles(command: str, ctx = None):\n \"\"\"\n Custom check. Checks if a the user has a role for the command in the config.\n :param command: Category in the YAML to look under\n :param ctx: discord.py context\n :return: boolean\n \"\"\"\n\n def predicate(ctx):\n for role in ctx.message.author.roles:\n if role.name.lower() in {i.lower() for i in config[str(ctx.guild.id)][command]['roles']}:\n return True\n return False\n\n if ctx:\n return predicate(ctx)\n else:\n return commands.check(predicate)\n\n\nasync def module_enabled(command: str, id: int or str):\n \"\"\"\n Custom check. Checks if the module is enabled for the server in the config.\n :param command: Category in the YAML to look under\n :param id: server ID\n :return: boolean\n \"\"\"\n return config[str(id)][command]['enabled']\n\nasync def parse_time(time: str):\n \"\"\"\n Takes an input String and parses it into a usable timedelta.\n :param parsestring: Input string\n :return: timedelta\n \"\"\"\n case = dict(d=timedelta(days=int(re.sub(r'\\D', '', time))), h=timedelta(hours=int(re.sub(r'\\D', '', time))),\n m=timedelta(minutes=int(re.sub(r'\\D', '', time))),\n s=timedelta(seconds=int(re.sub(r'\\D', '', time))))\n return case.get(time[-1])\n\n\nasync def schedule_task(task, time: timedelta, id: str, args: list = None):\n '''\n Schedules a task to be ran at the provided time delta.\n :param task: Task to be ran\n :param time: Timedelta\n :param id: ID for the task. This will be needed to remove the task later.\n :param args: Arguments to pass to the task. Optional.\n '''\n scheduler.add_job(task, 'date', run_date=datetime.now() + time, args=args, id=id)\n\n\nasync def remove_task(id):\n '''\n Removes a task from the queue.\n :param id: ID of the task to be deleted,\n '''\n scheduler.remove_job(id)\n","sub_path":"modules/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":5160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"247928879","text":"#coding:utf-8\n\nfrom pwn import *\nfrom LibcSearcher import *\n\np = process('./slot_machine')\n\nif args['REMOTE']:\n p = remote('arcade.fluxfingers.net',1815)\nelf = ELF(\"slot_machine\")\nlibc = ELF(\"./libc.so.6\")\n\nru = lambda x : p.recvuntil(x)\nsl = lambda x : p.sendline(x)\nsd = lambda x : p.send(x)\n\nru(\"Here is system : \")\nsyst = ru(\"\\n\").replace(\"\\n\",\"\")\nsuccess(\"system addr == > \"+syst)\n\nbase = int(syst,16) - libc.symbols['system']\nsuccess(\"base == > \" +hex(base))\n\n#obj = LibcSearcher('system',int(syst,16))\n#obj.dump('gets')\n\ndef debug(msg=''):\n gdb.attach(p,msg)\n raw_input()\n\ndef malloc(sz):\n ru(\"[ 4 ] : bye!\")\n sl(\"1\")\n ru(\"How much?\")\n sl(str(sz))\n \n\ndef free(offset):\n ru(\"[ 4 ] : bye!\")\n sl(\"2\")\n ru(\"where?\")\n sl(str(offset))\n\ndef write(cont):\n ru(\"[ 4 ] : bye!\")\n sl(\"3\")\n ru(\"what?\")\n sl(cont)\n\ndef exploit():\n malloc(0x60)\n malloc(0x60)\n #\n free(-0x70)\n malloc(0x60)\n write(\"1234\")\n #free(0)\n #write(\"1234\")\n #free(-0x70)\n \n \n debug(\"b *0x5555555553C5\\nb *0x55555555540E\\nb *0x555555555394\\nb *0x5555555553EE\")\n\n p.interactive()\n \nif __name__ == \"__main__\":\n exploit()","sub_path":"pwn_exec/slot_machin/slot_machine.py","file_name":"slot_machine.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"511669563","text":"\"\"\"\nRun migrations\n\nBy default runs all migrations in order. If arguments are provided then\nonly migration files that match the arguments are run.\n\nFor example:\n\npython run_migrations.py 001_add_week_start.py\n\nWould only run the first migration.\n\"\"\"\nimport imp\nimport os\nimport sys\nfrom os.path import join\nimport logging\nfrom backdrop.core.database import Database\n\nlogging.basicConfig(level=logging.DEBUG)\nlog = logging.getLogger(__name__)\n\nROOT_PATH = os.path.abspath(os.path.dirname(__file__))\n\n\ndef load_config(env):\n config_path = os.path.join(ROOT_PATH, 'backdrop', 'write', 'config')\n fp = None\n try:\n sys.path.append(config_path)\n fp, pathname, description = imp.find_module(\n \"backdrop/write/config/%s\" % env)\n return imp.load_module(env, fp, pathname, description)\n finally:\n sys.path.pop()\n if fp:\n fp.close()\n\n\ndef get_database(config):\n return Database(\n config.MONGO_HOSTS, config.MONGO_PORT, config.DATABASE_NAME)\n\n\ndef get_migrations(migration_files):\n migrations_path = join(ROOT_PATH, 'migrations')\n for migration_file in os.listdir(migrations_path):\n if not migration_file.endswith('.py'):\n continue\n if migration_files is None or migration_file in migration_files:\n migration_path = join(migrations_path, migration_file)\n\n yield imp.load_source('migration', migration_path)\n\n\nif __name__ == '__main__':\n\n config = load_config(os.getenv('GOVUK_ENV', 'development'))\n database = get_database(config)\n\n migration_files = sys.argv[1:] or None\n\n for migration in get_migrations(migration_files):\n log.info(\"Running migration %s\" % migration)\n migration.up(database)\n","sub_path":"run_migrations.py","file_name":"run_migrations.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"298405751","text":"import pandas as pd\nimport arff\nimport copy\nfrom config import ALL_FILES\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.model_selection import cross_val_score\nimport numpy as np\n\nnp.random.seed(42)\n#It is highly recommended to parallel this script by running it on different files at the same time\nFILES = ALL_FILES\n\nfor file in FILES:\n f = open(file[:-5]+'.txt','w')\n data = arff.load(open('./Datasets/'+file, 'r'))\n \n #This ugly block is here because in some datasets downloaded from OpenML the target column is not the last one.\n #It forces to write a lot of exceptions like these to move the target column to the last place in order to\n #process all the files in the same way with target column in behind.\n if file in ['prnn_crabs.arff','profb.arff','sleuth_ex2015.arff','sleuth_ex2016.arff','analcatdata_asbestos.arff',\n 'Australian.arff','dataset_106_molecular-biology_promoters.arff','dataset_114_shuttle-landing-control.arff',\n 'kdd_internet_usage.arff','molecular-biology_promoters.arff','monks-problems-1.arff','monks-problems-2.arff',\n 'monks-problems-3.arff','oil_spill.arff','SPECT.arff']:\n data['attributes'].append(data['attributes'][0])\n del data['attributes'][0]\n data['data'] = np.hstack((np.array(data['data'])[:, 1:], np.array(data['data'])[:, 0].reshape(-1, 1))).tolist()\n if file == 'analcatdata_whale.arff':\n data['data'] = data['data'][:-5]\n if file in ['analcatdata_japansolvent.arff','lungcancer_GSE31210.arff','lupus.arff',]:\n data['attributes'].append(data['attributes'][1])\n del data['attributes'][1]\n data['data'] = np.hstack((np.array(data['data'])[:, [0] + list(range(2, len(data['data'][0])))],\n np.array(data['data'])[:, 1].reshape(-1, 1))).tolist()\n if file == 'dataset_25_colic.ORIG.arff':\n data['attributes'].append(data['attributes'][23])\n del data['attributes'][23]\n data['data'] = np.hstack((np.array(data['data'])[:, list(range(23)) + list(range(24, len(data['data'][0])))],\n np.array(data['data'])[:, 23].reshape(-1, 1))).tolist()\n if file == 'irish.arff':\n data['attributes'].append(data['attributes'][3])\n del data['attributes'][3]\n data['data'] = np.hstack((np.array(data['data'])[:, list(range(3)) + list(range(4, len(data['data'][0])))],\n np.array(data['data'])[:, 3].reshape(-1, 1))).tolist()\n if file == 'wholesale-customers.arff':\n data['attributes'].append(data['attributes'][7])\n del data['attributes'][7]\n data['data'] = np.hstack((np.array(data['data'])[:, list(range(7)) + list(range(8, len(data['data'][0])))],\n np.array(data['data'])[:, 7].reshape(-1, 1))).tolist()\n \n #Here we understand which features are categorical and which are numerical\n categorical_cols = []\n numeric_cols = []\n for i in range(len(data['attributes'])):\n if type(data['attributes'][i][1]) != str and i != len(data['attributes'])-1: \n categorical_cols.append(i)\n elif i != len(data['attributes'])-1:\n numeric_cols.append(i)\n \n #Here we make one hot encoding of categorical features and normalize numerical features\n data = pd.DataFrame(data=data['data'],index=None)\n for categorical_col in categorical_cols:\n col = copy.deepcopy(data[categorical_col])\n del data[categorical_col]\n data = pd.concat([pd.get_dummies(col),data],axis=1)\n for numeric_col in numeric_cols:\n data[numeric_col] = pd.to_numeric(data[numeric_col])\n if data[numeric_col].max() - data[numeric_col].min() != 0:\n data[numeric_col] = (data[numeric_col] - data[numeric_col].min()) / (data[numeric_col].max() - data[numeric_col].min())\n else:\n data[numeric_col] = 0.\n data = data.sample(frac=1) #shuffle rows\n data = data.reset_index(drop=True)\n X = data.iloc[:, :-1].fillna(0)\n y = data.iloc[:,-1]\n clf = SVC()\n f.write('0, '+str(cross_val_score(clf,X,y,cv=10,scoring='accuracy',n_jobs=10).mean())+'\\n')\n clf = LinearSVC()\n f.write('1, '+str(cross_val_score(clf,X,y,cv=10,scoring='accuracy',n_jobs=10).mean())+'\\n')\n f.close()\n","sub_path":"SVMlinearRBF.py","file_name":"SVMlinearRBF.py","file_ext":"py","file_size_in_byte":4326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"377842992","text":"#! /usr/bin/env python\n\nfrom collections import defaultdict\nimport logging\nimport os\nimport shutil\nimport tempfile\n\nfrom celery import shared_task\nimport docker\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\nfrom cnc_grader import models\n\n\nlogger = logging.getLogger()\n\n\n@receiver(post_save, sender=models.Submission)\ndef submit_execute(signal, sender, instance, created, **kwargs):\n if created:\n logging.info(\"Submitting test run for instance id %d\", instance.id)\n execute_submission.delay(instance.id)\n\n\n@shared_task()\ndef execute_submission(submission_id):\n submission = models.Submission.objects.get(id=submission_id)\n inputs_dir = tempfile.mkdtemp()\n outputs_dir = tempfile.mkdtemp()\n submission_dir = tempfile.mkdtemp()\n c = docker.Client()\n result = 1\n logger.info(\"Grading submission %d for team %s\",\n submission_id, submission.team.user.username)\n try:\n for testcase in submission.problem.testcase_set.all():\n infile = os.path.join(inputs_dir, '%d' % testcase.id)\n outfile = os.path.join(outputs_dir, '%d' % testcase.id)\n with open(infile, 'w') as f:\n f.write(testcase.input)\n\n with open(outfile, 'w') as f:\n f.write(testcase.output)\n\n submission_file = os.path.join(submission_dir,\n os.path.basename(submission.file.name))\n with open(submission_file, 'w') as f:\n f.write(submission.file.read())\n\n container_id = c.create_container(\n 'crashandcompile',\n command=('/test_executor.py'\n ' --inputsdir /inputs'\n ' --outputsdir /outputs'\n ' --submission ' +\n os.path.join('/submission',\n os.path.basename(submission.file.name))),\n volumes=['/inputs/', '/outputs', '/submission'],\n network_disabled=True)\n logger.debug(\"Created container %s to execute submission %d\",\n container_id, submission_id)\n stdout = c.logs(container_id, stdout=True, stderr=True, stream=True)\n c.start(container_id,\n binds={inputs_dir: '/inputs',\n outputs_dir: '/outputs',\n submission_dir: '/submission'})\n # TODO: needs timeout\n result = c.wait(container_id)\n passed = (result == 0)\n notes = ''\n if not passed:\n logger.info('\\n'.join(list(stdout)))\n\n if result == 1:\n notes = \"Compiled failed\"\n elif result == 2:\n notes = \"Test case failed\"\n elif result == 3:\n notes = \"Bad extension\"\n\n\n finally:\n shutil.rmtree(inputs_dir)\n shutil.rmtree(outputs_dir)\n shutil.rmtree(submission_dir)\n submission.graded = True\n submission.passed = passed\n submission.note = notes\n submission.save()\n\n if submission.passed:\n # this is rather naive and easily abused...\n calculate_team_scores.delay()\n\n\n@shared_task()\ndef calculate_team_scores():\n max_winners = 3\n submissions = models.Submission.objects.order_by('submission_time').all()\n teams = models.Team.objects.all()\n\n correct_for_problem = defaultdict(int)\n score_for_team = defaultdict(int)\n # problem -> team -> bool\n points_awarded_for_problem = defaultdict(lambda: defaultdict(bool))\n\n for submission in submissions:\n if not submission.passed:\n continue\n\n if points_awarded_for_problem[submission.problem][submission.team]:\n continue\n\n if correct_for_problem[submission.problem] >= max_winners:\n continue\n\n award_points = max_winners - correct_for_problem[submission.problem]\n logger.info(\"Awarding team %s %d points for problem %s\",\n submission.team, award_points, submission.problem)\n score_for_team[submission.team] += award_points\n correct_for_problem[submission.problem] += 1\n points_awarded_for_problem[submission.problem][submission.team] = True\n\n for team in teams:\n team.score = score_for_team[team]\n team.save()\n","sub_path":"cnc_grader/docker_worker/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":4299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"204565382","text":"from hexical import layout, algorithms, tile\n\nimport random\nimport pygame\n\ndef initpygame():\n \"\"\"Initialises the pygame environment and returns a gameDisplay and\n display_info object.\n\n \"\"\"\n pygame.init()\n pygame.font.init()\n gameDisplay = pygame.display.set_mode((0,0), pygame.FULLSCREEN)\n display_info = pygame.display.Info()\n pygame.display.set_caption('Graphical Hex Test')\n\n return (gameDisplay, display_info)\n\ndef main():\n\n gameDisplay, display_info = initpygame()\n WIDTH = display_info.current_w\n HEIGHT = display_info.current_h\n\n lay = layout.Layout((50,50), (WIDTH/2, HEIGHT/2), random.choice(['p','f']))\n starthex = tile.Hex(0,0,0)\n\n quitting = False\n while not quitting:\n\n for event in pygame.event.get():\n\n if event.type == pygame.QUIT:\n quitting = True\n\n if event.type == pygame.KEYDOWN:\n\n if event.key == pygame.K_ESCAPE:\n quitting = True\n\n gameDisplay.fill((0,0,0))\n h = tile.point_to_hex(pygame.mouse.get_pos(), lay, rounding = True)\n mousehex = tile.Hex(int(h.a), int(h.b), int(h.c))\n\n for h in algorithms.hexline(starthex, mousehex):\n corners = h.corners(lay)\n pygame.draw.aalines(gameDisplay,\n (255,255,255),\n True,\n corners)\n\n pygame.display.update()\n\n\nif __name__ == '__main__':\n main()\n pygame.quit()\n quit()\n","sub_path":"graphicaltests/linegenerator.py","file_name":"linegenerator.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"91764811","text":"\"\"\"Utility and helper functions for MNE-BIDS.\"\"\"\nimport os\nimport errno\nfrom collections import OrderedDict\nimport json\nimport shutil as sh\nfrom mne.externals.six import string_types\nfrom .config import BIDS_VERSION\nfrom os.path import splitext\n\n\ndef _mkdir_p(path, overwrite=False, verbose=False):\n \"\"\"Create a directory, making parent directories as needed.\n\n From stackoverflow.com/questions/600268/mkdir-p-functionality-in-python\n \"\"\"\n # why would you want to do this?!\n # If another run exists in the same folder then it will be overidden!\n if overwrite is True and os.path.isdir(path):\n sh.rmtree(path)\n if verbose is True:\n print('Overwriting path: %s' % path)\n\n try:\n os.makedirs(path, exist_ok=True)\n if verbose is True:\n print('Creating folder: %s' % path)\n except OSError as exc: # Python >2.5\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else:\n raise\n\n\ndef make_bids_filename(subject=None, session=None, task=None,\n acquisition=None, run=None, processing=None,\n recording=None, space=None, suffix=None, prefix=None):\n \"\"\"Create a BIDS filename from its component parts.\n\n BIDS filename prefixes have one or more pieces of metadata in them. They\n must follow a particular order, which is followed by this function. This\n will generate the *prefix* for a BIDS file name that can be used with many\n subsequent files, or you may also give a suffix that will then complete\n the file name.\n\n Note that all parameters are not applicable to each kind of data. For\n example, electrode location TSV files do not need a task field.\n\n Parameters\n ----------\n subject : str | None\n The subject ID. Corresponds to \"sub\".\n session : str | None\n The session for a item. Corresponds to \"ses\".\n task : str | None\n The task for a item. Corresponds to \"task\".\n acquisition: str | None\n The acquisition parameters for the item. Corresponds to \"acq\".\n run : int | None\n The run number for this item. Corresponds to \"run\".\n processing : str | None\n The processing label for this item. Corresponds to \"proc\".\n recording : str | None\n The recording name for this item. Corresponds to \"recording\".\n space : str | None\n The coordinate space for an anatomical file. Corresponds to \"space\".\n suffix : str | None\n The suffix of a file that begins with this prefix. E.g., 'audio.wav'.\n prefix : str | None\n The prefix for the filename to be created. E.g., a path to the folder\n in which you wish to create a file with this name.\n\n Returns\n -------\n filename : str\n The BIDS filename you wish to create.\n\n Examples\n --------\n >>> print(make_bids_filename(subject='test', session='two', task='mytask', suffix='data.csv')) # noqa\n sub-test_ses-two_task-mytask_data.csv\n \"\"\"\n order = OrderedDict([('sub', subject),\n ('ses', session),\n ('task', task),\n ('acq', acquisition),\n ('run', run),\n ('proc', processing),\n ('space', space),\n ('recording', recording)])\n if order['run'] is not None and not isinstance(order['run'], string_types):\n # Ensure that run is a string\n order['run'] = '{:02}'.format(order['run'])\n\n _check_types(order.values())\n\n if not any(isinstance(ii, string_types) for ii in order.keys()):\n raise ValueError(\"At least one parameter must be given.\")\n\n filename = []\n for key, val in order.items():\n if val is not None:\n _check_key_val(key, val)\n filename.append('%s-%s' % (key, val))\n\n if isinstance(suffix, string_types):\n filename.append(suffix)\n\n filename = '_'.join(filename)\n if isinstance(prefix, string_types):\n filename = os.path.join(prefix, filename)\n return filename\n\n\ndef make_bids_folders(subject, session=None, kind=None, root=None,\n make_dir=True, overwrite=False, verbose=False):\n \"\"\"Create a BIDS folder hierarchy.\n\n This creates a hierarchy of folders *within* a BIDS dataset. You should\n plan to create these folders *inside* the root folder of the dataset.\n\n Parameters\n ----------\n subject : str\n The subject ID. Corresponds to \"sub\".\n kind : str\n The kind of folder being created at the end of the hierarchy. E.g.,\n \"anat\", \"func\", etc.\n session : str | None\n The session for a item. Corresponds to \"ses\".\n root : str | None\n The root for the folders to be created. If None, folders will be\n created in the current working directory.\n make_dir : bool\n Whether to actually create the folders specified. If False, only a\n path will be generated but no folders will be created.\n overwrite : bool\n If `make_dir` is True and one or all folders already exist,\n this will overwrite them with empty folders.\n verbose : bool\n If verbose is True, print status updates\n as folders are created.\n\n Returns\n -------\n path : str\n The (relative) path to the folder that was created.\n\n Examples\n --------\n >>> print(make_bids_folders('sub_01', session='my_session',\n kind='meg', root='path/to/project', make_dir=False)) # noqa\n path/to/project/sub-sub_01/ses-my_session/meg\n \"\"\"\n _check_types((subject, kind, session, root))\n if session is not None:\n _check_key_val('ses', session)\n\n path = ['sub-%s' % subject]\n if isinstance(session, string_types):\n path.append('ses-%s' % session)\n if isinstance(kind, string_types):\n path.append(kind)\n path = os.path.join(*path)\n if isinstance(root, string_types):\n path = os.path.join(root, path)\n\n if make_dir is True:\n _mkdir_p(path, overwrite=overwrite, verbose=verbose)\n return path\n\n\ndef make_dataset_description(path, name=None, data_license=None,\n authors=None, acknowledgements=None,\n how_to_acknowledge=None, funding=None,\n references_and_links=None, doi=None,\n verbose=False):\n \"\"\"Create json for a dataset description.\n\n BIDS datasets may have one or more fields, this function allows you to\n specify which you wish to include in the description. See the BIDS\n documentation for information about what each field means.\n\n Parameters\n ----------\n path : str\n A path to a folder where the description will be created.\n name : str | None\n The name of this BIDS dataset.\n data_license : str | None\n The license under which this datset is published.\n authors : str | None\n Authors who contributed to this dataset.\n acknowledgements : str | None\n Acknowledgements for this dataset.\n how_to_acknowledge : str | None\n Instructions for how acknowledgements/credit should be given for this\n dataset.\n funding : str | None\n Funding sources for this dataset.\n references_and_links : str | None\n References or links for this dataset.\n doi : str | None\n The DOI for the dataset.\n \"\"\"\n fname = os.path.join(path, 'dataset_description.json')\n description = OrderedDict([('Name', name),\n ('BIDSVersion', BIDS_VERSION),\n ('License', data_license),\n ('Authors', authors),\n ('Acknowledgements', acknowledgements),\n ('HowToAcknowledge', how_to_acknowledge),\n ('Funding', funding),\n ('ReferencesAndLinks', references_and_links),\n ('DatasetDOI', doi)])\n pop_keys = [key for key, val in description.items() if val is None]\n for key in pop_keys:\n description.pop(key)\n _write_json(description, fname, verbose=verbose)\n\n\ndef make_readme(path, text=\"\"):\n \"\"\"\n Writes the free-form readme files\n Parameters:\n ----------\n path : str\n A path to a folder where the readme will be created.\n text : str\n The entire contents ofthe readme file to be written to path.\n \"\"\"\n fname = os.path.join(path, 'README.txt')\n with open(fname, 'w') as f:\n f.write(text)\n\n\ndef _check_types(variables):\n \"\"\"Make sure all variables are strings or None.\"\"\"\n types = set(type(ii) for ii in variables)\n for itype in types:\n if not isinstance(itype, type(str)) and itype is not None:\n raise ValueError(\"All values must be either None or strings. \"\n \"Found type %s.\" % itype)\n\n\ndef _write_json(dictionary, fname, verbose=False):\n \"\"\"Write JSON to a file.\"\"\"\n json_output = json.dumps(dictionary, indent=4)\n with open(fname, 'w') as fid:\n fid.write(json_output)\n fid.write('\\n')\n\n if verbose is True:\n print(os.linesep + \"Writing '%s'...\" % fname + os.linesep)\n print(json_output)\n\n\ndef _check_key_val(key, val):\n \"\"\"Perform checks on a value to make sure it adheres to the spec.\"\"\"\n if any(ii in val for ii in ['-', '_', '/']):\n raise ValueError(\"Unallowed `-`, `_`, or `/` found in key/value pair\"\n \" %s: %s\" % (key, val))\n return key, val\n\ndef _get_ext(fname):\n \"\"\" Get the extension for the file specified by fname \"\"\"\n name, ext = splitext(fname)\n if ext == '':\n # in this case fname is simply the extension (possibly without the period, so fix this if needed)\n if name[0] == '.':\n return name\n else:\n return '.{0}'.format(name)\n else:\n return ext","sub_path":"mne_bids/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"116427028","text":"# coding:iso-8859-9 Türkçe\r\n# p_20404a.py: İnternet ip adresleriyle iletişim kontrolü örneği.\r\n\r\nimport os, re # threading/ipsiz kontrol...\r\n\r\nalınanPaketler = re.compile (r\"(\\d) alındı\")\r\ndurum = (\"cevapsız\", \"canlı fakat kayıp\", \"canlı\")\r\n\r\nfor sonek in range (20,30):\r\n ip = \"192.168.178.\" + str (sonek)\r\n kontrol = os.popen (\"çınlattı -q -c2 \" + ip, \"r\")\r\n print (\"...çınlatıyor \", ip)\r\n while True:\r\n satır = kontrol.readsatır()\r\n if not satır: break\r\n alınan = alınanPaketler.findall (satır)\r\n if alınan: print (ip + \": \" + durum[int (alınan[0])])\r\n\r\n\r\n#İnternet açık olmalı ve ilgili ip adresleri kontrol edilmeli...","sub_path":"Bernd Klein (520) ile Python/p_20404a.py","file_name":"p_20404a.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"444717655","text":"import pytest\nfrom numpy import linspace, exp, allclose, meshgrid\nfrom scipy.ndimage.interpolation import shift\nfrom SimpleITK import ImageRegistrationMethod, TranslationTransform\nfrom registration import SimpleITK_Registration\n\npytestmark = pytest.mark.usefixtures(\"eng\")\n\ndef test_fit(eng):\n x, y = meshgrid(linspace(-4,4,100), linspace(-4,4,100))\n reference = exp(-x**2 + -y**2)\n r = ImageRegistrationMethod()\n r.SetMetricAsCorrelation()\n r.SetOptimizerAsRegularStepGradientDescent(learningRate=0.1,\n minStep=1e-5,\n numberOfIterations=10000,\n gradientMagnitudeTolerance=1e-8)\n r.SetInitialTransform(TranslationTransform(len(reference.shape)), inPlace=False)\n algorithm = SimpleITK_Registration(r)\n deltas = [[1.5, -10], [-1.5, 10]]\n shifted = [shift(reference, delta) for delta in deltas]\n model = algorithm.fit(shifted, reference=reference)\n # flip the dimensions of model.toarray() before comparing to deltas because SimpleITK uses xy ordering.\n model_deltas = map(lambda v: v[::-1], model.toarray())\n assert allclose(model_deltas, deltas)","sub_path":"test/test_sitk_registration.py","file_name":"test_sitk_registration.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"501103794","text":"#!/usr/bin/env python\n\n# Author: Venkata chandrasekhar Nainala \n# Version: 0.1.0\n# Email: mailcs76@gmail.com / venkata@ebi.ac.uk\n# Date: 19 May 2016\n\n\"\"\" \n Dependencies:\n Python 2.7\n\"\"\"\nimport sys\nimport argparse\nimport utils\nimport logging\nimport os\nimport time\nimport datetime\nimport json\nfrom random import randint\n\ndestinationDirectory = \"\"\nworkingDirectory = \"\"\nmlSCMappingFile = \"\"\nreactomeJSONFile = \"\"\n\nreactomeData = {}\nmlMapping = {}\nrequestedCompound = \"\"\n\ndef main(arguments):\n parser = argparse.ArgumentParser(description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument(\"workingdirectory\", help=\"- Working directory location\")\n parser.add_argument(\"destinationdirectory\", help=\"- Destination Directory\")\n parser.add_argument(\"compound\", help=\"- MetaboLights Compound Identifier\", default=\"all\")\n args = parser.parse_args(arguments)\n global workingDirectory\n global destinationDirectory\n global requestedCompound\n workingDirectory = args.workingdirectory\n destinationDirectory = args.destinationdirectory\n requestedCompound = args.compound.replace('\"','')\n\n # Check if the folder structure exist and create if it doesn't\n if not os.path.exists(workingDirectory):\n os.makedirs(workingDirectory)\n\n # log file configuration\n ts = time.time()\n st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d_%H-%M-%S')\n randomInt = str(randint(1, 1000))\n logDirectory = workingDirectory+\"/logs/\" + st \n if not os.path.exists(logDirectory):\n os.makedirs(logDirectory)\n logging.basicConfig(filename= logDirectory + \"/log_\" +randomInt +\".log\",level=logging.DEBUG)\n utils.init(logging)\n logging.info(\"-----------------------------------------------\")\n logging.info('# Run started -' + utils.getDateAndTime())\n\n logging.info('Generating MetaboLights Study - Compound Mapping file')\n\n global mlSCMappingFile\n mlSCMappingFile = workingDirectory + \"/mapping.json\"\n\n global reactomeJSONFile\n reactomeJSONFile = workingDirectory + \"/reactome.json\"\n\n with open(reactomeJSONFile) as reactome_file:\n global reactomeData\n reactomeData = json.load(reactome_file)\n \n with open(mlSCMappingFile) as mapping_file: \n global mlMapping\n mlMapping = json.load(mapping_file)\n\n if (requestedCompound != \"all\") :\n requestCompoundsList = requestedCompound.split(\",\")\n for compound in requestCompoundsList:\n utils.fetchCompound(compound.strip(), workingDirectory, destinationDirectory, reactomeData, mlMapping)\n else:\n MLCompoundsList = utils.fetchMetaboLightsCompoundsList()\n for compound in MLCompoundsList:\n utils.fetchCompound(compound, workingDirectory, destinationDirectory, reactomeData, mlMapping)\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv[1:]))","sub_path":"MetCompoundBot/MLCompoundsBot.py","file_name":"MLCompoundsBot.py","file_ext":"py","file_size_in_byte":2917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"204156255","text":"from selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime, timedelta\n\nfrom flask import Flask, render_template, jsonify, request\napp = Flask(__name__)\n\nfrom pymongo import MongoClient # pymongo를 임포트 하기(패키지 인스톨 먼저 해야겠죠?)\nclient = MongoClient('mongodb://test:test@localhost', 27017) # mongoDB는 27017 포트로 돌아갑니다. ec2까지\ndb = client.dbsparta # 'dbsparta'라는 이름의 db를 만듭니다.\n\nimport requests\n\nfrom pytz import timezone\nfrom datetime import datetime\n\n\ndef maxnum(a,b):\n if(a>b):\n return a\n else:\n return b\n\ndef todayATRcalc(yesterdayATR,todayTR):\n return(yesterdayATR*16 + todayTR*2)/18\n\ndef todayunitcalc(investment,todayATR):\n return(investment*0.01)/todayATR\n\n\n### option 적용 ###\noptions = webdriver.ChromeOptions()\noptions.add_argument(\"--no-sandbox\")\noptions.add_argument(\"--remote-debugging-port=9222\")\noptions.headless = True\n###################\n\n# HTML을 주는 부분\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n@app.route('/view',methods=['GET'])\ndef viewdata():\n datas = list(db.helloinvestment.find({},{'_id':0}))\n #현재가격을 가지고있는 리스트를 보내주자 어차피 순번은 같다.\n #datas의 name에 있는 코드를 가져와서 현재가격만 크롤링 하여 리스트에 저장후 해당 리스트를 클라이언트에 반환\n #최상단 종가가 현재가격 (계속 변동됨 주식시장 개장때는)\n nowprices = []\n\n driver = webdriver.Chrome(options=options)\n for i in range(0,len(datas)):\n url = datas[i]['url']\n driver.get(url)\n time.sleep(0.3)\n soup = BeautifulSoup(driver.page_source, 'html.parser')\n current_price = soup.select_one('#header > div.end_header_topinfo > div.flick-container.major_info_wrp > div > div:nth-child(2) > div > div.stock_wrp > div.price_wrp > strong').text\n #print(current_price)\n nowprices.append(current_price.replace(\",\",\"\"))\n \n driver.quit()\n return jsonify({'result': 'success','datas':datas,'nowprices':nowprices})\n\n@app.route('/search', methods=['POST'])\ndef unitcalc():\n\n driver = webdriver.Chrome(options=options)\n ##################\n \t# 1. 클라이언트로부터 종목코드,투자금 받기\n\t\t# 2. url페이지 크롤링후 1유닛 계산\n\t\t# 3. 클라이언트에게 1유닛 반환\n namecode_receive = request.form['namecode_give']\n investment_receive =int(request.form['investment_give'])\n\n url = 'https://m.stock.naver.com/item/main.nhn#/stocks/' + namecode_receive + '/price'\n # 네이버 주식페이지 url을 입력합니다.\n\n # 크롬을 통해 네이버 주식페이지에 접속합니다.\n driver.get(url)\n\n # 정보를 받아오기까지 2초를 잠시 기다립니다.\n time.sleep(0.3)\n\n # 크롬에서 HTML 정보를 가져오고 BeautifulSoup을 통해 검색하기 쉽도록 가공합니다.\n soup = BeautifulSoup(driver.page_source, 'html.parser')\n\n # 종목이름 가져오기\n findcodename = soup.select_one('meta[property=\"og:title\"]')['content']\n findcodename = findcodename.split()[0]\n #삼성전자 - 네이버 증권/005930 공백기준으로 문자열 분리후 index : 0 값이 종목이름값\n\n\n #20일치만 가능하니 ATR 기준을 18로 놓고 한다.\n #20일치 ATR은 20일 동안의 TR의 평균값이다 따라서 제일 최근날짜를 제외한 18일 평균으로 계산한다.\n #20일치의 날짜 종가 고가 저가를 뽑아왔다.\n\n date_list =[]\n ncv_list = []\n hv_list = []\n lv_list = []\n trA_list = []\n trB_list = []\n trC_list = []\n #제일 큰 tr값이 들어감\n tr_list = [] \n # trA = todayhv-yesterdayncv \n # trB = yesterdayncv - todaylv \n # trC = todayhv - todaylv\n # today = i 가정시 \n # trA = hv_list[i] - ncv_list[i-1]\n # trB = ncv_list[i-1] - lv_list[i]\n # trC = hv_list[i] - lv_list[i]\n for i in range(0,19):\n finddata = soup.find(\"tr\",{\"data-index\":i}).text.split()\n date_list.append(finddata[0])\n ncv_list.append(int(finddata[1].replace(\",\",\"\")))\n hv_list.append(int(finddata[5].replace(\",\",\"\")))\n lv_list.append(int(finddata[6].replace(\",\",\"\")))\n date_list.reverse()\n ncv_list.reverse()\n hv_list.reverse()\n lv_list.reverse()\n #TR 계산식\n for i in range(1,19):\n trA_list.append(hv_list[i] - ncv_list[i-1])\n trB_list.append(hv_list[i-1] - ncv_list[i])\n trC_list.append(hv_list[i] - ncv_list[i])\n #콤마를 최대 2개는 지워줘야한다 1,000,000 백만단위 이상 주식이 한국엔 없기때문\n for i in range(0,18):\n tr = maxnum(trA_list[i],trB_list[i])\n tr_list.append(maxnum(tr,trC_list[i]))\n #전날 ATR\n ATRSum = 0\n for i in range(0,16):\n ATRSum = ATRSum + tr_list[i]\n yesterdayATR = ATRSum/16\n #당일 ATR\n todayATR = todayATRcalc(yesterdayATR,tr_list[17])\n \n unit = todayunitcalc(investment_receive,todayATR)\n unitshare = round(unit)\n unitwon = unitshare*ncv_list[18]\n \n #print(unitshare,unitwon)\n \n driver.quit()\n\n resultcodename = findcodename +\"/\"+ namecode_receive\n resultunit = str(unitwon) + \"/\" + str(unitshare)\n \n fmt = \"%Y-%m-%d %H:%M:%S\"\n KST = datetime.now(timezone('Asia/Seoul'))\n\n doc = {\n 'date' : KST.strftime(fmt),\n 'name' : resultcodename,\n 'investment' : investment_receive,\n 'unit' : resultunit,\n 'searchprice' : ncv_list[18],\n 'url' : url\n }\n\n db.helloinvestment.insert_one(doc)\n return jsonify({'result': 'success', 'msg': '계산 완료!','unitshare':unitshare,'unitwon':unitwon})\n\nif __name__ == '__main__':\n app.run('0.0.0.0',port=5000,debug=True)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"projects/helloinvestingserver/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"177377659","text":"from datetime import datetime\n\ndef busca(coluna,aux):\n \n for linha in coluna:\n linha = linha.rstrip()\n \n if aux == 1:\n n = linha\n elif aux == 2:\n t = int(linha) + 2\n else:\n if aux < t:\n if linha == n:\n return(True, aux -2)\n elif aux == t and linha ==n:\n return(True, aux -2)\n else:\n return(False, -1)\n\n aux= aux +1\n\n\n\narq = open('dataset-1-c.csv', 'r')\ninicio = datetime.now()\ndados = busca(arq,1)\nfim = datetime.now()\narq.close()\n\ntempo = str((fim-inicio))[8:14] + ' Mircrosegundos'\n\narq_w = open('resposta-dataset-1-c.txt','w')\narq_w.writelines(str(dados[0])+ \"\\n\")\narq_w.writelines(str(dados[1])+ \"\\n\")\narq_w.writelines(tempo)\narq_w.close()","sub_path":"Atividade1/buscaNumero.py","file_name":"buscaNumero.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"438154007","text":"class Solution(object):\r\n def rotate(self, nums, k):\r\n \"\"\"\r\n :type nums: List[int]\r\n :type k: int\r\n :rtype: void Do not return anything, modify nums in-place instead.\r\n \"\"\"\r\n n=len(nums)\r\n k=k%n\r\n copy=nums[:]\r\n for i in nums:\r\n \tcopy.append(i)\r\n # nums=copy[n-k:2*n-k]\r\n for i in range(n):\r\n \tnums[i]=copy[n-k+i]\r\n \r\nSolution().rotate([1,2,3,4,5,6,7],3) ","sub_path":"python/189.Rotate Array.py","file_name":"189.Rotate Array.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"437907357","text":"# '''\n# Linked List hash table key/value pair\n# '''\nclass LinkedPair:\n def __init__(self, key, value):\n self.key = key\n self.value = value\n self.next = None\n\nclass HashTable:\n '''\n A hash table that with `capacity` buckets\n that accepts string keys\n '''\n def __init__(self, capacity):\n self.capacity = capacity # Number of buckets in the hash table\n self.storage = [None] * capacity\n # self.length = 0\n\n\n def _hash(self, key):\n '''\n Hash an arbitrary key and return an integer.\n\n You may replace the Python hash with DJB2 as a stretch goal.\n '''\n print(hash(key))\n return hash(key)\n\n\n def _hash_djb2(self, key):\n '''\n Hash an arbitrary key using DJB2 hash\n\n OPTIONAL STRETCH: Research and implement DJB2\n '''\n pass\n\n\n def _hash_mod(self, key):\n '''\n Take an arbitrary key and return a valid integer index\n within the storage capacity of the hash table.\n '''\n return self._hash(key) % self.capacity\n\n\n def insert(self, key, value):\n\n # this doesn't put anything in order\n # self.head = self.capacity -1 # the 'head starts from the right side\n # hash(key)\n # cap = self.capacity\n # for i in range(cap-1 , 0 ,-1):\n # # print(i, i-1 )\n # self.storage[ i] = self.storage[i -1 ]\n # # print(i , i-1)\n\n # pair = {hash(key):value}\n # self.storage[0] = pair\n # print(self.storage)\n index = self._hash_mod(key)\n if self.storage[index] is not None:\n print('Collision for key '+ key)\n self.storage[index] = LinkedPair(key,value)\n\n\n\n def get(self):\n print( self.storage )\n return\n\n\n def remove(self, key):\n # for i in self.storage:\n # if i == key:\n # self.storage[i] = None\n # print(self.storage[i])\n # else:\n # print('no key or wrong key')\n index = self._hash_mod(key)\n self.storage[index] = None\n\n def retrieve(self, key):\n\n # hkey = hash(key)\n # print(hkey,'107')\n # for i in range(0, self.capacity-1):\n # if self.storage[i].get(hkey) != hkey:\n # print(self.storage[i].get(hash(key)))\n # else:\n # None\n\n index = self._hash_mod(key)\n if self.storage[index] is None:\n return None\n return self.storage[index].value\n\n def resize(self):\n cap = self.capacity *2\n print(cap )\n '''\n Doubles the capacity of the hash table and\n rehash all key/value pairs.\n\n Fill this in.\n '''\n # pass\n \n# one = HashTable(5)\n# one.resize()\n\n\nif __name__ == \"__main__\":\n ht = HashTable(2)\n\n ht.insert(\"line_1\", \"Tiny hash table\")\n ht.insert(\"line_2\", \"Filled beyond capacity\")\n ht.insert(\"line_3\", \"Linked list saves the day!\")\n\n print(\"\")\n\n # Test storing beyond capacity\n print(ht.retrieve(\"line_1\"))\n print(ht.retrieve(\"line_2\"))\n print(ht.retrieve(\"line_3\"))\n\n # Test resizing\n old_capacity = len(ht.storage)\n ht.resize()\n new_capacity = len(ht.storage)\n\n print(f\"\\nResized from {old_capacity} to {new_capacity}.\\n\")\n\n # Test if data intact after resizing\n print(ht.retrieve(\"line_1\"))\n print(ht.retrieve(\"line_2\"))\n print(ht.retrieve(\"line_3\"))\n\n print(\"\")","sub_path":"src/hashtable.py","file_name":"hashtable.py","file_ext":"py","file_size_in_byte":3459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"461316396","text":"from django.conf import settings\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\nfrom django.views import static\n\n\nurlpatterns = [\n url(r'^', include('home.urls')),\n url(r'^portfolio/', include('portfolio.urls')),\n url(r'^contact/', include('contact.urls')),\n url(r'^admin/', include(admin.site.urls)),\n]\n\n\nif settings.DEBUG:\n urlpatterns += [\n url(r'^static/(?P.*)$',\n static.serve,\n {'document_root': settings.STATIC_ROOT}),\n\n url(r'^media/(?P.*)$',\n static.serve,\n {'document_root': settings.MEDIA_ROOT,\n 'show_indexes': True, }),\n ]\n","sub_path":"kamilasliwinska/kamilasliwinska/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"207215653","text":"\n\n#calss header\nclass _SIFT():\n\tdef __init__(self,): \n\t\tself.name = \"SIFT\"\n\t\tself.definitions = [u'to put flour, sugar, etc. through a sieve (= wire net shaped like a bowl) to break up large pieces: ', u'to make a close examination of all the parts of something in order to find something or to separate what is useful from what is not: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_sift.py","file_name":"_sift.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"550756559","text":"import os\nimport yaml\nimport spikeinterface.extractors as se\nimport spikeinterface.sorters as ss\nimport spikeinterface.comparison as sc\nimport spikeinterface.toolkit as st\nimport spikeinterface.widgets as sw\nimport matplotlib.pylab as plt\nimport numpy as np\nimport seaborn as sns\nimport pandas as pd\nimport h5py\nimport numpy as np\nimport json\nimport pickle\n\ndef extract_matchings(confusion_matrix):\n\tprint(confusion_matrix)\n\tmatchings = {}\n\ttrue_to_predicted_matchings = {}\n\tdiscovered_neurons = confusion_matrix.axes[1]\n\tdiscovered_neurons = list(discovered_neurons[:len(discovered_neurons)-1])\n\ttrue_neurons = confusion_matrix.axes[0]\n\ttrue_neurons = list(true_neurons[:len(true_neurons)-1])\n\t#true_neurons.sort()\n\tovershoot = len(discovered_neurons)-len(true_neurons)\n\tfabricated_neurons = []\n\tfabricated_matchings = {}\n\tif overshoot > 0:\n\t\tfabricated_neurons = discovered_neurons[len(discovered_neurons)-overshoot:len(discovered_neurons)]\n\t\tdiscovered_neurons = discovered_neurons[:len(discovered_neurons)-overshoot] \n\t\tfor k in range(len(fabricated_neurons)):\n\t\t\tfabricated_matchings[str(fabricated_neurons[k])] = str(-2 - k)\n\tfor k in range(len(discovered_neurons)):\n\t\tmatchings[str(discovered_neurons[k])] = str(true_neurons[k])\n\t\ttrue_to_predicted_matchings[str(true_neurons[k])] = str(discovered_neurons[k])\n\n\treturn true_to_predicted_matchings,matchings,fabricated_matchings\n\ndef assess_true_spikes(true_spikes,predicted_spikes,matchings):\n\tall_predicted_spikes = predicted_spikes\n\ttemp_predicted_spikes = {}\n\tfor k in matchings.keys():\n\t\ttemp_predicted_spikes[k] = predicted_spikes[k]\n\tpredicted_spikes = temp_predicted_spikes\n\tassessed_true_spikes = []\n\tfor k in true_spikes.keys():\n\t\tassessed_true_spikes += [[int(spike_time), k,'-1'] for spike_time in true_spikes[k]]\n\tassessed_true_spikes.sort(key=lambda el: el[0])\n\tframe_window = 8 #16 frame range implies .5ms detection window\n\t#print(assessed_true_spikes[:100])\n\n\tpred_spikes_remaining = {}\n\tfor k in matchings.keys():\n\t\tpred_spikes_remaining[k] = []\n\n\thit_count = [0]*len(true_spikes.keys()) #I think it will be more straight forward to store the true neuron number\n\tps_keys = predicted_spikes.keys()\n\tarray_indices = [0]*len(ps_keys)\n\tfor true_spike_index,el in enumerate(assessed_true_spikes):\n\t\tcur_spike_time = el[0]\n\t\tfor (index,my_key) in enumerate(ps_keys):\n\t\t\tif matchings[my_key] == el[1]:\n\t\t\t\tpred_neuron_spikes = predicted_spikes[my_key]\n\t\t\t\twhile (array_indices[index] < len(pred_neuron_spikes)) and (pred_neuron_spikes[array_indices[index]] <= cur_spike_time+frame_window):\n\t\t\t\t\tif pred_neuron_spikes[array_indices[index]] >= cur_spike_time-frame_window:\n\t\t\t\t\t\tassessed_true_spikes[true_spike_index][2] = (matchings[my_key])\n\t\t\t\t\t\tarray_indices[index] += 1\n\t\t\t\t\t\thit_count[int(matchings[my_key])] += 1\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tpred_spikes_remaining[my_key].append(pred_neuron_spikes[array_indices[index]])\n\t\t\t\t\t\tarray_indices[index] += 1\n\n\n\n\tps_keys = predicted_spikes.keys()\n\tarray_indices = [0]*len(ps_keys)\n\tfor true_spike_index,el in enumerate(assessed_true_spikes):\n\t\tcur_spike_time = el[0]\n\t\tfor (index,my_key) in enumerate(ps_keys):\n\t\t\tpred_neuron_spikes = pred_spikes_remaining[my_key]\n\t\t\tif (el[2] == \"-1\") and (matchings[my_key] != el[1]):\n\t\t\t\twhile (array_indices[index] < len(pred_neuron_spikes)) and (pred_neuron_spikes[array_indices[index]] <= cur_spike_time+frame_window):\n\t\t\t\t\tif pred_neuron_spikes[array_indices[index]] >= cur_spike_time-frame_window:\n\t\t\t\t\t\tassessed_true_spikes[true_spike_index][2] = (matchings[my_key])\n\t\t\t\t\t\tarray_indices[index] += 1\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tarray_indices[index] += 1\n\n\ttotal_true_positive_rate = sum(hit_count)/len(assessed_true_spikes)\n\ttotal_false_positive_rate = (len(assessed_true_spikes)-sum(hit_count))/len(assessed_true_spikes)\n\t#num_predictions = sum([len(all_predicted_spikes[key]) for key in matchings.keys()])\n\tnum_predictions = sum([len(all_predicted_spikes[k]) for k in all_predicted_spikes.keys()])\n\t#need to pass fabricated matchings to this method\n\tnum_bad_predictions = num_predictions-sum(hit_count)\n\ttotal_false_predicition_rate = num_bad_predictions/num_predictions\n\ttotal_statistics = [total_true_positive_rate,total_false_positive_rate,total_false_predicition_rate]\n\n\n\ttrue_positive_rates = [hit_count[k]/len(true_spikes[str(k)]) if hit_count[k] > 0 else -1 for k in range(len(hit_count))]\n\tfalse_negative_rates = [1 - tp for tp in true_positive_rates]\n\tfalse_prediction_rates = []\n\tfor index in range(len(hit_count)):\n\t\tpredicted_neuron = -1\n\t\tfor k in matchings.keys():\n\t\t\tif matchings[k] == str(index):\n\t\t\t\tpredicted_neuron = int(k)\n\t\t\t\tbreak\n\t\tif (predicted_neuron == -1):\n\t\t\tfalse_prediction_rates.append(-1)\n\t\telse:\n\t\t\trate = (len(predicted_spikes[str(predicted_neuron)]) - hit_count[index])/len(predicted_spikes[str(predicted_neuron)])\n\t\t\tfalse_prediction_rates.append(rate)\n\n\treturn total_statistics,true_positive_rates,false_negative_rates,false_prediction_rates,assessed_true_spikes\n\ndef check_for_fabricated(assessed_true_spikes,predicted_spikes,fabricated_matchings):\n\tps_keys = fabricated_matchings.keys()\n\tprint(predicted_spikes.keys())\n\tarray_indices = [0]*len(ps_keys)\n\tframe_window = 8\n\tfor true_spike_index,el in enumerate(assessed_true_spikes):\n\t\tcur_spike_time = el[0]\n\t\tfor (index,my_key) in enumerate(ps_keys):\n\t\t\tpred_neuron_spikes = predicted_spikes[my_key]\n\t\t\tif (el[2] == \"-1\"):\n\t\t\t\twhile (array_indices[index] < len(pred_neuron_spikes)) and (pred_neuron_spikes[array_indices[index]] <= cur_spike_time+frame_window):\n\t\t\t\t\tif pred_neuron_spikes[array_indices[index]] >= cur_spike_time-frame_window:\n\t\t\t\t\t\tassessed_true_spikes[true_spike_index][2] = (fabricated_matchings[my_key])\n\t\t\t\t\t\tarray_indices[index] += 1\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tarray_indices[index] += 1\n\treturn assessed_true_spikes\n\ndef assess_no_neurons(true_spikes):\n\tassessed_true_spikes = []\n\tfor k in true_spikes.keys():\n\t\tassessed_true_spikes += [[int(spike_time), k,'-1'] for spike_time in true_spikes[k]]\n\tassessed_true_spikes.sort(key=lambda el: el[0])\n\treturn assessed_true_spikes\n\n##################################################\n#Generate Consolidated Templates \n##################################################\n\nbase_directory = os.getcwd()+'/' #NEED TO CHANGE THIS FOR WEB DEPLOYMENT!\nparameters = yaml.full_load(open('client_parameters.yaml'))\nselected_probe = parameters['probe_type']\ntemplate_creation_folder = 'template_creation/'\nos.system('mkdir '+template_creation_folder)\n\n\nfor cell_id in parameters['cells'].keys():\n\tcell = parameters['cells'][cell_id]\n\tindividual_model_folder = cell_id+'_template'\n\tos.system('mkdir '+base_directory+individual_model_folder)\n\tos.system('cp -r '+base_directory+'all_models/'+cell['model']+' '+individual_model_folder)\n\tos.system('./mearec gen-templates -fn '+base_directory+template_creation_folder+'/'+cell_id+'.h5 '+' -cf '+base_directory+individual_model_folder+' -prb '+selected_probe+ ' -r norot -n 1'+\n\t\t\t ' -prm '+base_directory+'templates_params.yaml'+\n\t\t ' -xl '+cell['position']['xpos']+' '+cell['position']['xpos']+'.01'+\n\t\t ' -yl '+cell['position']['ypos']+' '+cell['position']['ypos']+'.01'+\n\t\t ' -zl '+cell['position']['zpos']+' '+cell['position']['zpos']+'.01'+' -v') #added verbose mode\n\tos.system('rm -rf '+individual_model_folder)\n\nos.system('python3 build_h5.py')\n\n\n\n##############################################\n#Generate Recording\n##############################################\nparameters = yaml.full_load(open('client_parameters.yaml'))\nrecordings_parameters = yaml.full_load(open('default_recordings_parameters.yaml'))\t\n\nmy_rates = []\nmy_types = []\nfor cell_id in parameters['cells'].keys():\n\tmy_rates.append(parameters['cells'][cell_id]['rate'])\n\nrecordings_parameters['spiketrains']['rates'] = my_rates\n\nfor cell_id in parameters['cells'].keys():\n\tmy_types.append(parameters['cell_categories'][parameters['cells'][cell_id]['model']])\n\nrecordings_parameters['spiketrains']['types'] = my_types\n\n\n# Noise Parameters\nrecordings_parameters['recordings']['noise_mode'] = parameters['noise']['type']\nrecordings_parameters['recordings']['noise_level'] = parameters['noise']['standard_deviation']\n\nyaml.dump(recordings_parameters, open('my_recordings_parameters.yaml','w')) #default_flow_style=False ???\n\nos.system('./mearec gen-recordings -fn '+base_directory+'new_recording.h5 -t '+base_directory+'combined_templates.h5 '\n\t+' -prm '+base_directory+'my_recordings_parameters.yaml'+' -d '+parameters['duration']+' -v')\n\n\n\n\n###############################################\n# Run Analysis\n##############################################\nsynth_output = {}\nsorting_algorithm_choices = ['tridesclous','ironclust','klusta']\nrecording = se.MEArecRecordingExtractor('new_recording.h5')\nsorting_GT = se.MEArecSortingExtractor('new_recording.h5')\nfor el in sorting_algorithm_choices:\n\tsorting_algorithm = el\n\n\tif sorting_algorithm == 'tridesclous':\n\t\tsorting_result = ss.run_tridesclous(recording)\n\telif sorting_algorithm == 'klusta':\n\t\tavg_accuracy = -1\n\t\tfor k in range(7):\n\t\t\ttemp_sorting_result = ss.run_klusta(recording)\n\t\t\tcomp = sc.compare_sorter_to_ground_truth(sorting_GT, temp_sorting_result)\n\t\t\tperf = str(comp.get_performance())\n\t\t\tperf = perf.split('\\n')\n\t\t\tperf = perf[2:len(perf)]\n\t\t\taccuracies = []\n\t\t\tfor line in perf:\n\t\t\t\taccuracies.append( float((line.split())[1]) )\n\t\t\ttemp_avg_accuracy = sum(accuracies)/len(accuracies)\n\t\t\tif(temp_avg_accuracy > avg_accuracy):\n\t\t\t\tavg_accuracy = temp_avg_accuracy\n\t\t\t\tsorting_result = temp_sorting_result\n\telif sorting_algorithm == 'herdingspikes':\n\t\tsorting_result = ss.run_herdingspikes(recording)\n\telif sorting_algorithm == 'ironclust':\n\t\tsorting_result = ss.run_ironclust(recording)\n\telif sorting_algorithm == 'kilosort':\n\t\tsorting_result = ss.run_kilosort(recording)\n\telif sorting_algorithm == 'waveclus':\n\t\tsorting_result = ss.run_waveclus(recording)\n\n\tcomp = sc.compare_sorter_to_ground_truth(sorting_GT, sorting_result)\n\tdata = h5py.File('new_recording.h5','r')\n\n\ttrue_spikes = {}\n\n\tfor neuron_id in sorting_GT.get_unit_ids():\n\t\ttrue_spikes[str(neuron_id)] = (sorting_GT.get_unit_spike_train(unit_id=neuron_id))\n\n\n\ttrue_to_predicted_matchings,matchings,fabricated_matchings = extract_matchings(comp.get_confusion_matrix())\n\tprint(\"matchings:\")\n\tprint(matchings)\n\tprint(\"fabricated_matchings:\")\n\tprint(fabricated_matchings)\n\n\tpredicted_spikes = {}\n\n\tfor my_key in fabricated_matchings.keys():\n\t\tpredicted_spikes[my_key] = sorting_result.get_unit_spike_train(unit_id=int(my_key))\n\n\tfor my_key in matchings.keys():\n\t\tpredicted_spikes[my_key] = sorting_result.get_unit_spike_train(unit_id=int(my_key))\n\n\n\n\tnumpy_traces = recording.get_traces()\n\tvoltage_traces = []\n\tfor k in range(4):\n\t\tvoltage_traces.append([int(el) for el in numpy_traces[k]])\n\n\n\n\tif (predicted_spikes == {}):\n\t\tsummary_statistics = []\n\t\ttotal_statistics = [0]*5\n\t\tfor k in range(len(sorting_GT.get_unit_ids())):\n\t\t\tnew_entry = [len(true_spikes[str(k)]),-1,-1,-1,-1]\n\t\t\tsummary_statistics.append(new_entry)\n\t\t\ttotal_statistics[0] += new_entry[0]\n\n\n\t\tnum_predicted = [len(predicted_spikes[k]) for k in predicted_spikes.keys()]\n\t\ttotal_statistics[1] = -1\n\t\ttotal_statistics[2] = -1\n\t\ttotal_statistics[3] = -1\n\t\ttotal_statistics[4] = -1\n\n\t\tassessed_true_spikes = assess_no_neurons(true_spikes)\n\n\n\t\tsynth_output[sorting_algorithm] = {'voltage_traces':voltage_traces,'performance_trace':assessed_true_spikes, 'results':'no spikes', 'discovered_neurons':len(sorting_GT.get_unit_ids())\n\t\t\t\t\t\t\t\t\t\t\t\t\t,'num_fabricated':0,'fabricated_spikes':{},'summary_statistics':summary_statistics,'total_statistics':total_statistics}\n\t\tcontinue\n\n\t(my_total_statistics,true_positive_rates,false_negative_rates,false_prediction_rates,assessed_true_spikes) = assess_true_spikes(true_spikes,predicted_spikes,matchings)\n\n\tassessed_true_spikes = check_for_fabricated(assessed_true_spikes,predicted_spikes,fabricated_matchings)\n\t \n\tsummary_statistics = []\n\ttotal_statistics = [0]*5\n\ttrue_neurons_discovered = [matchings[k] for k in matchings.keys()]\n\tfor k in range(len(sorting_GT.get_unit_ids())):\n\t\tpred_spikes = -1\n\t\tif str(k) in true_to_predicted_matchings.keys():\n\t\t\tpred_spikes = len(predicted_spikes[true_to_predicted_matchings[str(k)]])\n\t\tnew_entry = [len(true_spikes[str(k)]),pred_spikes,true_positive_rates[k],false_negative_rates[k],false_prediction_rates[k]]\n\t\tsummary_statistics.append(new_entry)\n\t\ttotal_statistics[0] += new_entry[0]\n\n\n\tnum_predicted = [len(predicted_spikes[k]) for k in predicted_spikes.keys()]\n\ttotal_statistics[1] = sum(num_predicted)\n\ttotal_statistics[2] = my_total_statistics[0]\n\ttotal_statistics[3] = my_total_statistics[1]\n\ttotal_statistics[4] = my_total_statistics[2]\n\n\tfabricated_spikes = {}\n\tfor k in fabricated_matchings.keys():\n\t\tfabricated_spikes[fabricated_matchings[k]] = len(predicted_spikes[k])\n\n\tnum_fabricated = len(fabricated_matchings.keys())\n\n\tsynth_output[sorting_algorithm] = {'voltage_traces':voltage_traces,'performance_trace':assessed_true_spikes, 'results':str(comp.get_performance()), 'discovered_neurons':len(sorting_GT.get_unit_ids())\n\t\t\t\t\t\t\t\t\t\t\t\t\t,'num_fabricated':num_fabricated,'fabricated_spikes':fabricated_spikes,'summary_statistics':summary_statistics,'total_statistics':total_statistics}\n\n\npickle.dump(synth_output, open('synth_output.pickle','wb'))\n###############################################\n# CLEAN UP\n##############################################\nos.system('rm client_parameters.yaml')\nos.system('rm new_recording.h5')\nos.system('rm -rf template_creation/')\nos.system('rm combined_templates.h5')\nos.system('rm my_recordings_parameters.yaml')\n\n\n\n\n\n\n\n\n\t\n","sub_path":"synth.py","file_name":"synth.py","file_ext":"py","file_size_in_byte":13570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"283515272","text":"dataset_type = 'VisualDialogDatasetDense'\ndata_root = '/home/datasets/mix_data/iMIX/'\nfeature_path = 'data/datasets/visdial_data/features/'\nannotation_path = 'data/datasets/visdial_data/annotations_npy/'\ntokenizer_path = '/home/datasets/mix_data/torch/pytorch_transformers/bert/bert-base-uncased/bert-base-uncased-vocab.txt'\n\ntrain_datasets = ['train']\ntest_datasets = ['val']\n\nimg_feature_reader = dict(type='ImageFeaturesH5Reader', )\n\ntrain_reader_cfg = dict(\n type='VisDiaReader',\n mix_features=dict(train=data_root + feature_path + 'visdial_img_feat.lmdb', ),\n mix_annotations=dict(\n train=data_root + annotation_path + 'visdial_1.0_train_dense_processed.npy',\n dense=data_root + annotation_path + 'visdial_1.0_train_dense_annotations_processed.json'),\n image_feature_max_regions=37,\n datasets=train_datasets, # used datasets\n image_feature_reader=img_feature_reader,\n mask_img_probability=0,\n)\n\ntest_reader_cfg = dict(\n type='VisDiaReader',\n mix_features=dict(val=data_root + feature_path + 'visdial_img_feat.lmdb', ),\n mix_annotations=dict(\n val=data_root + annotation_path + 'visdial_1.0_val_processed.npy',\n # val=data_root + annotation_path + 'visdial_1.0_val_processed_small64.npy',\n dense=data_root + annotation_path + 'visdial_1.0_val_dense_annotations_processed.json'),\n image_feature_max_regions=37,\n datasets=test_datasets, # used datasets\n image_feature_reader=img_feature_reader,\n mask_img_probability=0,\n)\n\ntrain_info_cpler_cfg = dict(\n type='VisualDialogDenseInfoCpler',\n tokenizer=dict(path=tokenizer_path),\n num_options=100, # number of options to use. [2,100]\n num_negative_samples=1, # number of negative samples for every positive sample for the nsp loss\n visual_dialog_tot_rounds=11,\n # number of rounds to use in visdial,caption is counted as a separate round, therefore a maximum of 11\n # rounds possible\n max_sequence_len=256, # maximum sequence length for the dialog sequence\n # sequences_per_image=8, # number of sequences sampled from an image during training\n mask_probability=0, # probability used to sample masked tokens\n has_bert=True,\n)\ntest_info_cpler_cfg = dict(\n type='VisDiaInfoCpler',\n tokenizer=dict(path=tokenizer_path),\n num_options=100, # number of options to use. [2,100]\n num_negative_samples=1, # number of negative samples for every positive sample for the nsp loss\n visual_dialog_tot_rounds=11,\n # number of rounds to use in visdial,caption is counted as a separate round, therefore a maximum of 11\n # rounds possible\n max_sequence_len=256, # maximum sequence length for the dialog sequence\n sequences_per_image=8, # number of sequences sampled from an image during training\n mask_probability=0, # probability used to sample masked tokens\n has_bert=True,\n)\n\ntrain_data = dict(\n samples_per_gpu=1, # 16\n workers_per_gpu=0,\n data=dict(type=dataset_type, reader=train_reader_cfg, info_cpler=train_info_cpler_cfg),\n drop_last=True,\n pin_memory=False,\n)\n\ntest_data = dict(\n samples_per_gpu=2,\n workers_per_gpu=0,\n data=dict(type='VisDialDataset', reader=test_reader_cfg, info_cpler=test_info_cpler_cfg),\n sampler='DistributedSampler',\n drop_last=True,\n is_run_eval=False,\n)\n\npost_processor = dict(\n type='Evaluator', metrics=[dict(type='VisDialMetric')], dataset_converters=[dict(type='VisDialDatasetConverter')])\n","sub_path":"configs/_base_/datasets/visual-dialog/visual_dialog_with_dense_annotations.py","file_name":"visual_dialog_with_dense_annotations.py","file_ext":"py","file_size_in_byte":3451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"427353221","text":"\nimport math\nimport turtle\n\nwn = turtle.Screen()\nwn.bgcolor('lightblue')\n\nPI=3.14\nangle=2*PI/72\n\nfred = turtle.Turtle()\nfred.speed(99999)\nR1 = 200\nR2 = 100\ncycle=1\ntotal_steps=360\nsteps=1\nalpha=2*PI/8\n\ni=0\nwhile i <= 10000:\n t = math.radians(i)\n x = R1*math.cos(3*t)\n y = R1*math.sin(3*t)\n x1 = 100+R2*math.cos(7*t+alpha)*math.cos(t)\n y1 = 100+R2*math.sin(7*t+alpha)*math.sin(t)\n fred.penup()\n fred.goto(x,y)\n fred.pendown()\n fred.goto(x1,y1)\n fred.penup()\n i = i+steps\n\nwn.exitonclick()\n##a = raw_input()\n","sub_path":"src/double_circle_ray3.py","file_name":"double_circle_ray3.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"120352715","text":"''' Configparserの代わりにYAML形式で保存する場合\n\npip install pyyaml\n\nimport yaml\n\nYAMLファイルを読み込む際には脆弱性の観点からLoaderオプションを使うことを推奨\nまた読み込み時に型が全てStringであることに注意\n\nhttps://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation\n\n'''\n\nimport yaml\n\nwith open('parse.yaml', 'w') as yaml_file:\n yaml.dump({\n 'Server': {\n 'ip': '192.168.0.1',\n 'port': 3306\n },\n 'User1': {\n 'id': 1,\n 'name': 'user1',\n 'attend': False\n }\n }, yaml_file)\n\nwith open('parse.yaml', 'r') as yaml_file:\n config = yaml.load(yaml_file, Loader=yaml.BaseLoader)\n print(config['Server']['ip'])\n print(config['Server']['port'], type(config['Server']['port']))\n print(config['User1']['attend'], type(config['User1']['attend']))\n","sub_path":"Python/configparser/parse_by_yaml.py","file_name":"parse_by_yaml.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"340215839","text":"#\n# Joel Labbe\n#\n# invest.py\n#\n# A program that uses a while loop to determine how long it takes for an investment\n# to double at a given interest rate. \n#\n# Input: Annualized interest rate\n#\n# Processing: 1. Set up primers and accumulators\n# 2. Prompt user for the annual interest rate\n# 3. Use a while loop to calculate how long it takes to double money ($1)\n# 4. Display result\n#\n# Output: Years to double an account balance\n#\n\ndef main():\n print(\"Number of years for an investment to double\")\n print()\n\n # Set up primers and accumulators\n initial = 1\n count = 0\n\n # Prompt user for the annual interest rate\n interest = eval(input(\"What is the annual interest rate? \"))\n\n # Use a while loop to calculate how long it takes to double money ($1)\n while (initial < 2):\n initial = initial + (initial * (interest/100))\n count = count + 1\n # Display result\n print(\"Years to double:\", count)\n\nmain()\n \n \n \n \n","sub_path":"Labs/Chapter 8/invest.py","file_name":"invest.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"509123013","text":"import random\n\ndef exclude_minimal_triforce_hunt(weight_dict, random_settings):\n \"\"\" If triforce hunt is enabled, reroll the item pool excluding minimal. \"\"\"\n weights = weight_dict['item_pool_value']\n if 'minimal' in weights.keys() and random_settings['triforce_hunt'] == \"true\":\n weights.pop('minimal')\n random_settings['item_pool_value'] = random.choices(list(weights.keys()), weights=list(weights.values()))[0]\n\ndef exclude_ice_trap_misery(weight_dict, random_settings):\n \"\"\" If the damage multiplier is quad or OHKO, exclude ice trap onslaught and mayhem. \"\"\"\n weights = weight_dict['junk_ice_traps']\n if 'mayhem' in weights.keys() and random_settings['damage_multiplier'] in ['quadruple', 'ohko']:\n weights.pop('mayhem')\n if 'onslaught' in weights.keys() and random_settings['damage_multiplier'] in ['quadruple', 'ohko']:\n weights.pop('onslaught')\n random_settings['junk_ice_traps'] = random.choices(list(weights.keys()), weights=list(weights.values()))[0]\n\ndef exclude_overworld_mixed_pools(random_settings):\n \"\"\" If Overworld ER is enabled, mixed entrance pools should be disabled. \"\"\"\n if random_settings['shuffle_overworld_entrances'] == \"true\":\n random_settings['mix_entrance_pools'] = \"false\"\n","sub_path":"Conditionals.py","file_name":"Conditionals.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"159642602","text":"'''\nCreated on 28 Feb 2018\n\n@author: jerald\n'''\nimport h5py\nfilename = 'my_model.h5'\nf = h5py.File(filename, 'r')\n\n# List all groups\nprint(\"Keys: %s\" % f.keys())\na_group_key = list(f.keys())[0]\n\n# Get the data\ndata = list(f[a_group_key])\nprint(data)","sub_path":"ReadHDF5.py","file_name":"ReadHDF5.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"581006700","text":"import datetime\nimport json\nimport logging\nimport tempfile\nimport uuid\nimport traceback\nimport os\n\nfrom constance import config\nfrom django.core.paginator import Paginator\nfrom django.conf import settings\nfrom django.contrib.auth import authenticate\nfrom django.db.models import Q\nfrom django.http import JsonResponse, HttpResponseBadRequest, HttpResponseServerError, HttpResponseNotAllowed, \\\n StreamingHttpResponse\nfrom django.utils import timezone\nfrom django.utils.encoding import escape_uri_path\nfrom django.utils.module_loading import import_string\nfrom django.shortcuts import redirect\n\nfrom account.decorators import require_jwt_auth, require_permission\nfrom account.models import Court, Position\nfrom docx_factory.compiler import get_plain_text\nfrom history.models import log_user_operation, OperationHistory\nfrom main.models import Case, CaseDetail, CollectedCase, CollectedFile, UniqueCode, UniqueCodeRule, \\\n UniqueCodeGenerateError, Stage\nfrom main.file_types import *\nfrom main.xlsx_util import Writer as XlsxWriter\nfrom main.utils import str2int, get_tilde_splitted_date_range, str2bool, file_iterator\nfrom s3.client import get_minio_client, check_bucket_existence\n\nlogger = logging.getLogger('server')\n\n\n# 返回收案列表\n@require_jwt_auth()\n@require_permission('view_case_collect_info')\ndef collected(request):\n user = request.user\n\n court_ids = request.GET.getlist('court[]', []) # 机构 id\n collect_types = request.GET.getlist('collect_type[]', []) # 收案类型, smart / manual\n\n status = request.GET.get('status', 'new') # 案件状态, 默认为新收案件\n date_range = request.GET.get('date_range') # 日期范围\n keyword = request.GET.get('key', '') # 关键字\n page = str2int(request.GET.get('page', 1)) # 页码\n\n export = request.GET.get('export', '')\n\n # - 组装查询参数 开始 -\n # - 组装默认查询参数 -\n # 默认参数是收案状态\n q = Q(status=status)\n # 按照用户权限组装查询参数\n if user.perm_src:\n user_perm_src_view = user.perm_src['view_case_collect_info']\n\n if user_perm_src_view[0] == 0: # 本人 (0, user)\n q = q & Q(creator=user_perm_src_view[1])\n\n elif user_perm_src_view[0] == 3: # 本部门\n q = q & Q(department=user_perm_src_view[1])\n elif user_perm_src_view[0] == 5: # 本部门及下属部门\n q = q & Q(department__in=user_perm_src_view[1])\n\n elif user_perm_src_view[0] == 7: # 本机构\n q = q & Q(court=user_perm_src_view[1])\n elif user_perm_src_view[0] == 9: # 本机构及下属机构\n q = q & Q(court__in=user_perm_src_view[1])\n # 按照用户权限组装查询参数 结束\n\n exclude_q = Q(status=CollectedCase.DELETED) & Q(status=CollectedCase.COMPLETELY_DELETED)\n\n if court_ids:\n court = Court.objects.filter(pk__in=court_ids).all()\n if court:\n q = q & Q(court__in=court)\n\n if collect_types:\n q = q & Q(collect_type__in=collect_types)\n\n if date_range:\n min_, max_ = get_tilde_splitted_date_range(date_range)\n if min_:\n q = q & Q(created__gte=min_, created__lte=max_)\n\n if keyword:\n q = q & Q(unique_code__code__icontains=keyword)\n # - 组装查询参数 结束 -\n\n logger.debug(q)\n\n query_set = CollectedCase.objects.filter(q).order_by('-created').exclude(exclude_q)\n collected_ = query_set.all().select_related('creator', 'last_modifier', 'unique_code')\n total = query_set.count()\n\n # 导出 xlsx (忽略分页)\n if export == 'xlsx':\n headers = ['序号', '案件唯一码', '所属机构', '所属部门', '收案类型', '智能识别状态', '经办人', '创建时间']\n data = []\n for index, i in enumerate(collected_):\n if not hasattr(i, 'case'):\n continue\n court = i.court.name if i.court else ''\n dept = i.department.name if i.department else ''\n\n data.append([\n index + 1, # 序号\n i.unique_code.code, # 案件唯一码\n court, # 所属机构\n dept, # 所属部门\n i.get_collect_type_display(), # 收案类型\n i.get_recognition_status_display(), # 智能识别状态\n i.creator.first_name if i.creator else '', # 经办人\n timezone.localtime(i.created).strftime('%Y-%m-%d'), # 创建时间\n ])\n\n filename = XlsxWriter('收案列表').set_header(headers).write(data).save_tmp()\n with open(filename, 'r') as output:\n file_name = '收案列表.xlsx'\n\n response = StreamingHttpResponse(file_iterator(output.name))\n response['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'\n response['Content-Length'] = os.path.getsize(output.name)\n response['Content-Disposition'] = 'attachment; filename*=\"{0}\"'.format(escape_uri_path(file_name))\n return response\n # 返回 json 数据\n else:\n # - 分页 开始 -\n paginator = Paginator(collected_, settings.PER_PAGE)\n collected_ = paginator.page(page).object_list\n # - 分页 结束 -\n\n # 组��数据\n data = []\n for i in collected_:\n if not hasattr(i, 'case'):\n continue\n court = i.court.name if i.court else ''\n dept = i.department.name if i.department else ''\n data.append({\n 'id': i.id,\n 'case_id': i.case.id if i.case else None,\n 'unique_code': i.unique_code.code,\n 'court': court,\n 'dept': dept,\n 'case_status': i.case.status if i.case else '',\n 'collect_type': i.collect_type,\n 'recognition_status': i.recognition_status,\n 'operator': i.creator.first_name if i.creator else '',\n 'created': timezone.localtime(i.created).strftime('%Y-%m-%d %H:%M')\n })\n return JsonResponse({\n 'status': 'ok',\n 'total': total,\n 'data': data\n })\n\n\n# 返回某个收案信息\ndef info(request):\n case_id = str2int(request.GET.get('case'))\n\n files_only = str2bool(request.GET.get('files_only', False))\n files_type = request.GET.get('files_type', CollectedFile.APPLICANT)\n\n collected_case = CollectedCase.objects.filter(case_id=case_id) \\\n .exclude(status__in=[CollectedCase.DELETED, CollectedCase.COMPLETELY_DELETED]) \\\n .select_related('creator', 'unique_code', 'creator__profile__court').first()\n if not collected_case:\n return HttpResponseBadRequest('该案件对应的收案信息不存在')\n\n applicants = collected_case.collectedfile_set.filter(type=CollectedFile.APPLICANT,\n status=CollectedFile.REFERENCED).all()\n dossiers = collected_case.collectedfile_set.filter(type=CollectedFile.DOSSIER,\n status=CollectedFile.REFERENCED).all()\n\n court = ''\n if hasattr(collected_case.creator, 'profile') and collected_case.creator.profile:\n if collected_case.creator.profile.court:\n court = collected_case.creator.profile.court.name\n\n data = {\n 'id': collected_case.id,\n 'unique_code': collected_case.unique_code.code,\n 'status': collected_case.status,\n 'recognition_status': collected_case.recognition_status,\n 'operator': collected_case.creator.first_name if collected_case.creator else '',\n 'collect_type': collected_case.collect_type,\n 'court': court,\n 'created': timezone.localtime(collected_case.created).strftime('%Y-%m-%d %H:%M:%S'),\n 'last_modified': timezone.localtime(collected_case.last_modified).strftime('%Y-%m-%d %H:%M:%S'),\n 'applicants': [{\n 'id': x.id,\n 'name': x.name,\n 'type': x.file_type,\n 'created': timezone.localtime(x.created).strftime('%Y-%m-%d %H:%M:%S'),\n 'url': x.url,\n } for x in applicants],\n 'dossiers': [{\n 'id': x.id,\n 'name': x.name,\n 'type': x.file_type,\n 'created': timezone.localtime(x.created).strftime('%Y-%m-%d %H:%M:%S'),\n 'url': x.url,\n } for x in dossiers]\n }\n\n resp = {\n 'status': 'ok',\n 'data': data,\n }\n\n if files_only:\n data = data.get(files_type + 's')\n resp = {\n 'status': 'ok',\n 'data': data,\n 'total': len(data)\n }\n\n return JsonResponse(resp)\n\n\n# 修改收案状态\n@require_jwt_auth()\ndef change_status(request):\n user = authenticate(request)\n if not user:\n return HttpResponseBadRequest('用户不存在!')\n\n collected = request.POST.getlist('cases[]')\n collected = [str2int(x) for x in collected]\n status = request.POST.get('status')\n\n if status not in [CollectedCase.TRANSFORMING, CollectedCase.FINISHED, CollectedCase.DELETED]:\n return HttpResponseBadRequest('指定修改的状态不存在')\n\n if status == CollectedCase.TRANSFORMING:\n # 转立案, 案件状态 -> 收案, 案件阶段 -> 案前\n # 在接下来的异步任务里请求审理系统新建案件,如果新建案件,更新案件状态为 立案,更新案件名称,案件号\n case_status = Case.RECEIVED\n case_stage = Stage.objects.order_by('index').first()\n operation = OperationHistory.TRANSFORM\n elif status == CollectedCase.FINISHED:\n # 办结, 案件状态 -> 结案, 案件阶段 -> 归档\n case_status = Case.FINISHED\n case_stage = Stage.objects.order_by('-index').first()\n operation = OperationHistory.FINISH\n else:\n # 删除\n case_status = Case.NONE\n case_stage = Stage.objects.order_by('index').first()\n operation = OperationHistory.DELETE\n\n try:\n changed = CollectedCase.objects.filter(id__in=collected) \\\n .update(status=status,\n last_modified=timezone.now(),\n last_modifier=user)\n\n Case.objects.filter(collectedcase__in=collected).update(status=case_status, stage=case_stage)\n # TODO: 在这里处理收案转立案, 或立案转办结的逻辑\n # 应该采用异步更新的策略来推送或同步案件信息\n # - 收案转立案的模拟逻辑 -\n if case_status == Case.RECEIVED:\n # 转立案,这里我们给定一个模拟的案号,给定立案日期\n try:\n cases = Case.objects.filter(collectedcase__in=collected).all()\n import random\n for c in cases:\n c.status = Case.ACCEPTED\n c.current_id = 'X民一立字(2018){}号'.format(random.randint(1000, 9999))\n if hasattr(c, 'detail') and c.detail:\n c.detail.accepted_rejected = timezone.localtime(timezone.now())\n c.detail.save()\n c.save()\n except Exception as e:\n logger.error(e)\n\n except Exception as e:\n return HttpResponseServerError('修改收案信息状态失败, 原因是 {}'.format(e))\n\n # - 记录用户操作 开始 -\n collected_cases = CollectedCase.objects.filter(id__in=collected).all()\n for i in collected_cases:\n log_user_operation(user, operation, i)\n # - 记录用户操作 结束 -\n\n return JsonResponse({\n 'status': 'ok',\n 'success': changed\n })\n\n\n# ----------------------------------------------\n# 智能收案 和 填表收案\n# ----------------------------------------------\n\n\n# 智能收案\n@require_jwt_auth()\ndef smart_collect(request):\n user = request.user\n\n applicants = request.POST.getlist('applicants[]', []) # 申请书卷宗文件 id\n applicants = [str2int(x) for x in applicants]\n dossiers = request.POST.getlist('dossiers[]', []) # 其他卷宗材料文件 id\n dossiers = [str2int(x) for x in dossiers]\n\n # - 生成案件唯一码 开始 -\n if not hasattr(user, 'profile') or not user.profile:\n return HttpResponseBadRequest('操作用户非普通用户, 无法保存机构和部门信息, 因此无法创建收案信息, 请切换为普通用户')\n position = user.profile.login_as\n if not position:\n return HttpResponseBadRequest('操作用户没有主要职务, 无法保存机构和部门信息, 因此无法创建收案信息, 请切换为普通用户')\n if not position.court:\n return HttpResponseBadRequest('操作用户不属于任何机构, 无法保存机构和部门信息, 因此无法创建收案信息, 请切换为普通用户')\n\n #\n # TODO: 检查用户权限\n #\n unique_code_rule = UniqueCodeRule.objects.filter(court=position.court, status=UniqueCodeRule.ENABLED).first()\n try:\n unique_code = unique_code_rule.generate_unique_code(position.department)\n except Exception as e:\n # 两种异常可能, 生成错误或规则不存在\n msg = 'Generating unique code failed, creator is {}, error: {}'.format(user.id, e)\n logger.error(msg)\n unique_code = str(uuid.uuid4())\n\n unique_code_obj = UniqueCode.objects.create(code=unique_code)\n # - 生成案件唯一码 结束 -\n\n # - 新建收案信息记录 开始 -\n try:\n case = Case.objects.create(create_user=user, status=Case.RECEIVED, court=position.court,\n unique_code=unique_code_obj)\n case_detail = CaseDetail.objects.create(case=case)\n case.detail = case_detail\n case.save()\n except Exception as e:\n msg = 'Save case collect/receive info failed while smart collect case, error: {}'.format(e)\n logger.error(msg)\n return HttpResponseServerError('收案失败, 案件信息无法保存. 错误原因: {}'.format(e))\n collected_case = CollectedCase.objects.create(\n unique_code=unique_code_obj,\n collect_type=CollectedCase.SMART,\n recognition_status=CollectedCase.PROCESSING,\n creator=user,\n court=position.court,\n department=position.department,\n last_modifier=user,\n case=case\n )\n # - 新建收案信息记录 结束 -\n\n # - 记录用户操作历史 -\n log_user_operation(user, OperationHistory.CREATE, collected_case)\n\n # - 更新文件引用 开始 -\n try:\n CollectedFile.objects.filter(id__in=applicants).update(collected_case=collected_case,\n type=CollectedFile.APPLICANT,\n status=CollectedFile.REFERENCED)\n CollectedFile.objects.filter(id__in=dossiers).update(collected_case=collected_case,\n type=CollectedFile.DOSSIER,\n status=CollectedFile.REFERENCED)\n except Exception as e:\n return HttpResponseServerError('收案信息记录已创建 (id: {}, 案件唯一码: {}), 但无法引用文件, 错误原因: {}' \\\n .format(collected_case.id, collected_case.unique_code.code, e))\n # - 更新文件引用 结束 -\n\n # - 识别文件 开始 -\n from interfaces.tasks import push_dossiers\n types = request.POST.getlist('type[]', [])\n system_from = request.POST.get('from', config.FROM)\n\n if not types:\n pass\n if system_from == 'court' and len(types) == 2:\n # 法院的数据\n # qss 指 起诉状\n push_dossiers.delay(user.id, collected_case.id, int(types[0]), int(types[1]), applicants, dossiers, type_='qss')\n elif system_from == 'arbitration':\n # 仲裁院的数据\n # 87, 87 是固定的劳动仲裁的案件类型和审判程序 id\n # sqs 指 申请书\n push_dossiers.delay(user.id, collected_case.id, 87, 87, applicants, dossiers, type_='sqs')\n # - 识别文件 结束 -\n\n return JsonResponse({\n 'status': 'ok',\n 'data': {\n 'id': collected_case.id,\n 'unique_code': collected_case.unique_code.code\n }\n })\n\n\n# 填表收案\n@require_jwt_auth()\ndef manual_collect(request):\n user = request.user\n\n # - 生成案件唯一码 开始 -\n if not hasattr(user, 'profile') or not user.profile:\n return HttpResponseBadRequest('操作用户非普通用户, 无法保存机构和部门信息, 因此无法创建收案信息, 请切换为普通用户')\n position = user.profile.login_as\n if not position:\n return HttpResponseBadRequest('收案用户没有主要职务, 无法保存机构和部门信息, 因此无法创建收案信息, 请切换为普通用户')\n if not position.court:\n return HttpResponseBadRequest('收案用户没有归属的机构, 无法保存机构和部门信息, 因此无法创建收案信息, 请切换为普通用户')\n\n #\n # TODO: 检查用户权限\n #\n unique_code_rule = UniqueCodeRule.objects.filter(court=position.court, status=UniqueCodeRule.ENABLED).first()\n try:\n unique_code = unique_code_rule.generate_unique_code(position.department)\n except Exception as e:\n # 两种异常可能, 生成错误或规则不存在\n msg = 'Generating unique code failed, creator is {}, error: {}'.format(user.id, e)\n logger.error(msg)\n unique_code = str(uuid.uuid4())\n\n unique_code_obj = UniqueCode.objects.create(code=unique_code)\n # - 生成案件唯一码 结束 -\n\n # - 新建收案信息记录 开始 -\n try:\n case = Case.objects.create(create_user=user, status=Case.RECEIVED, court=position.court,\n unique_code=unique_code_obj)\n case_detail = CaseDetail.objects.create(case=case)\n case.detail = case_detail\n case.save()\n except Exception as e:\n msg = 'Save case collect/receive info failed while manually collect case, error: {}'.format(e)\n logger.error(msg)\n return HttpResponseServerError('收案失败, 案件信息无法保存. 错误原因: {}'.format(e))\n\n collected_case = CollectedCase.objects.create(\n unique_code=unique_code_obj,\n collect_type=CollectedCase.MANUAL,\n creator=user,\n court=position.court,\n department=position.department,\n last_modifier=user,\n case=case\n )\n\n # - 新建收案信息记录 结束 -\n\n # - 记录用户操作历史 -\n log_user_operation(user, OperationHistory.CREATE, collected_case)\n\n return JsonResponse({\n 'status': 'ok',\n 'data': {\n 'id': case.id,\n 'unique_code': collected_case.unique_code.code\n }\n })\n\n\n# ----------------------------------------------\n# 收案相关卷宗文件操作\n# ----------------------------------------------\n\n# 收案文件上传或返回列表\n@require_jwt_auth()\ndef files(request):\n user = authenticate(request)\n if not user:\n return HttpResponseBadRequest('用户不存在!')\n\n if request.method == 'POST':\n # 上传文件\n file = request.FILES.get('file')\n\n # - 上传文件至存储 开始 -\n minio = get_minio_client()\n bucket = timezone.now().strftime('%Y%m')\n object_name = '收案文件/{}/{}/{}' \\\n .format(timezone.now().strftime('%Y%m%d'), uuid.uuid4(), file.name.replace('/', '-'))\n\n exists, e = check_bucket_existence(bucket)\n if e:\n logger.error('Upload files to minio failed while receiving collected case file, error: {}'.format(e))\n return HttpResponseServerError('文件无法在后台上传至存储服务器, 原因是: {}'.format(e))\n try:\n minio.put_object(bucket, object_name, file, file.size, file.content_type)\n except Exception as e:\n logger.error('Upload files to minio failed while receiving collected case file, error: {}'.format(e))\n return HttpResponseServerError('文件无法在后台上传至存储服务器, 原因是: {}'.format(e))\n # - 上传文件至存储 结束 -\n\n # - 新建文件记录 开始 -\n collected_file = CollectedFile.objects.create(\n name=file.name.replace('/', '-'),\n bucket=bucket,\n path=object_name\n )\n # - 新建文件记录 结束 -\n\n return JsonResponse({\n 'status': 'ok',\n 'data': {\n 'id': collected_file.id,\n 'name': collected_file.name,\n 'url': collected_file.url\n }\n })\n\n else:\n # 获取文件\n file_id = str2int(request.GET.get('id'))\n collected_file = CollectedFile.objects.filter(pk=file_id).exclude(status=CollectedFile.DELETED).first()\n if not collected_file:\n return HttpResponseBadRequest('指定的文件不存在或已经删除')\n else:\n return redirect(to=collected_file.url)\n\n\n# 解除文件引用(删除)\n@require_jwt_auth()\ndef unreference(request):\n user = authenticate(request)\n if not user:\n return HttpResponseBadRequest('用户不存在!')\n\n file_ids = request.POST.getlist('id[]')\n file_ids = [str2int(x) for x in file_ids]\n\n success = CollectedFile.objects.filter(id__in=file_ids).update(\n status=CollectedFile.UNREFERENCED\n )\n\n return JsonResponse({\n 'status': 'ok',\n 'data': {\n 'success': success\n }\n })\n\n\n# 为已有收案信息追加上传文件\n@require_jwt_auth()\ndef append_files(request):\n user = request.user\n\n collected_case_id = str2int(request.POST.get('id'))\n type_ = request.POST.get('type', CollectedFile.APPLICANT)\n file = request.FILES.get('file')\n\n collected_case = CollectedCase.objects.filter(pk=collected_case_id) \\\n .exclude(status__in=[CollectedCase.DELETED, CollectedCase.COMPLETELY_DELETED]).first()\n if not collected_case:\n return HttpResponseBadRequest('指定的收案信息不存在或已删除')\n\n if not type_ in [CollectedFile.APPLICANT, CollectedFile.DOSSIER]:\n return HttpResponseBadRequest('指定的文件类型不正确')\n\n # - 上传文件至存储 开始 -\n minio = get_minio_client()\n bucket = timezone.now().strftime('%Y%m')\n object_name = '收案文件/{}/{}/{}' \\\n .format(timezone.now().strftime('%Y%m%d'), uuid.uuid4(), file.name.replace('/', '-'))\n\n exists, e = check_bucket_existence(bucket)\n if e:\n logger.error('Upload files to minio failed while receiving collected case file, error: {}'.format(e))\n return HttpResponseServerError('文件无法在后台上传至存储服务器, 原因是: {}'.format(e))\n try:\n minio.put_object(bucket, object_name, file, file.size, file.content_type)\n except Exception as e:\n logger.error('Upload files to minio failed while receiving collected case file, error: {}'.format(e))\n return HttpResponseServerError('文件无法在后台上传至存储服务器, 原因是: {}'.format(e))\n # - 上传文件至存储 结束 -\n\n # - 新建文件记录 开始 -\n collected_file = CollectedFile.objects.create(\n name=file.name.replace('/', '-'),\n bucket=bucket,\n path=object_name,\n status=CollectedFile.REFERENCED,\n type=type_,\n collected_case=collected_case\n )\n # - 新建文件记录 结束 -\n\n return JsonResponse({\n 'status': 'ok',\n 'data': {\n 'id': collected_file.id,\n 'name': collected_file.name,\n 'url': collected_file.url\n }\n })\n","sub_path":"backend/main/api/collect_case.py","file_name":"collect_case.py","file_ext":"py","file_size_in_byte":23771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"43995057","text":"\"\"\"\nxbox.py\n\nHTTP requests for the unofficial xbox api (xboxapi.com)\n\"\"\"\n\nimport json\nimport requests\nimport os\n\nimport achieves\nimport api_keys as keys\n\n############### XBOX ###############\nXBOX_ID = '2533274805585086'\n\ndef get_my_games():\n \"\"\"\n get_my_games\n\n return a dict of all owned games as {title_id: name, ...} pairs\n \"\"\"\n ret = dict()\n req = requests.get('https://xboxapi.com/v2/'\n + XBOX_ID + '/xboxonegames',\n headers={'X-AUTH': keys.XBOX_KEY})\n if req.ok:\n for game in req.json()['titles']:\n ret[game['titleId']] = game['name']\n return ret\n\ndef get_my_achieves(title_id):\n \"\"\"\n get_my_achieves\n\n return the list of achievements for the title_id\n \"\"\"\n ret = list()\n req = requests.get('https://xboxapi.com/v2/'\n + XBOX_ID + '/achievements/' + str(title_id),\n headers={'X-AUTH': keys.XBOX_KEY})\n if req.ok:\n ret = req.json()\n return ret\n\ndef get_game_info(title_id, games):\n \"\"\"\n get_game_info\n\n return the game info for the title_id\n \"\"\"\n ret = dict()\n\n ret['name'] = games[title_id]\n\n # Get the achievements and format them to be similar to the steam\n # achievements\n raw_achievements = get_my_achieves(title_id)\n formatted_achievements = list()\n for ach in raw_achievements:\n ach['name'] = ach['name']\n ach['description'] = ach['lockedDescription']\n ach['achieved'] = int(ach['progressState'] == 'Achieved')\n ach['percent'] = ach['rarity']['currentPercentage']\n ach['icon'] = \"\"\n if 'mediaAssets' in ach:\n icons = [x['url'] for x in ach['mediaAssets'] if x['type'] == 'Icon']\n if icons:\n ach['icon'] = icons[0]\n formatted_achievements.append(ach)\n\n ret['achievements'] = formatted_achievements\n\n return ret\n\ndef load_json():\n \"\"\"\n load_json\n\n Open the saved data and return the content\n \"\"\"\n # Open the xbox games json file\n json_file = None\n try:\n json_file = open(os.path.join(os.path.dirname(__file__), 'xbox_games.json'))\n except IOError:\n achieves.run_xbox()\n json_file = open(os.path.join(os.path.dirname(__file__), 'xbox_games.json'))\n\n # Decode the json\n games = json.load(json_file)\n\n return games\n","sub_path":"xbox.py","file_name":"xbox.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"545650203","text":"\"\"\"This file is a PeopleSoftSickKids spider created on top of the PeopleSoft\nscrapy crawl peoplesoft_sickkids -a url=\"https://career.sickkids.ca/\" -a mining_job_id=999 -a iteration=1 -a extract=1\nsample url:\n https://career.sickkids.ca/\n\"\"\"\n\nfrom scrapy.http import FormRequest\nfrom scrapy.selector import Selector\nfrom scrapy.conf import settings\nfrom urlparse import urlparse\n\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, ConvertDateString, HtmlFormatter, RemoveBadElements, Strip, MapJobTypes\nfrom brightcorp.spiders.peoplesoft import PeopleSoft\n\n\nclass PeopleSoftSickKids(PeopleSoft):\n\n name = \"peoplesoft_sickkids\"\n job_count = 0\n domain = ''\n\n def __init__(self, *args, **kwargs):\n super(PeopleSoftSickKids, self).__init__(*args, **kwargs)\n settings.set('CONCURRENT_REQUESTS', 16)\n if 'url' in kwargs:\n match = urlparse(kwargs['url']).netloc.split('.')\n if len(match) >= 2:\n self.domain = match[1]\n\n def parse(self, response):\n sel = Selector(response)\n jobs = sel.xpath(\n \"//table[@id='tdgbrHRS_CE_JO_EXT_I$0']/tr[%s]\" % (self.job_count+1)\n )\n if jobs:\n job = jobs[0]\n meta = {\n 'date': job.xpath(\"./td[2]//text()\").extract(),\n 'title': job.xpath(\"./td[3]//text()\").extract(),\n 'id': job.xpath(\"./td[4]//text()\").extract(),\n 'location': job.xpath(\"./td[5]//text()\").extract(),\n 'cat': job.xpath(\"./td[6]//text()\").extract(),\n }\n formdata = {'ICAction': \"POSTINGTITLE$%s\" % self.job_count}\n yield FormRequest(\n response.url, formdata=formdata, meta=meta,\n callback=self.parse_job_callback()\n )\n self.job_count += 1\n\n def parse_job(self, response):\n sel = Selector(response)\n loader = BrightcorpItemLoader(response=response)\n loader.add_value('title', response.meta.get('title'))\n loader.add_value('location', response.meta.get('location'))\n loader.add_value('jobcategory', response.meta.get('cat'))\n loader.add_value(\n 'date', response.meta.get('date'), Strip(), ConvertDateString('%Y/%m/%d')\n )\n loader.add_value(\n 'referencenumber', response.meta.get('id'), Strip(),\n Prefix('%s-' % self.domain)\n )\n loader.add_xpath(\n 'description', '//div[contains(@id, \"DESCRLONG\")]',\n RemoveBadElements(['a']), HtmlFormatter()\n )\n loader.add_xpath(\n 'workhours', '//span[contains(@id, \"_WRK_STD_HOURS\")]/text()'\n )\n loader.add_xpath(\n 'duration', '//span[contains(@id, \"_WRK_HSC_CONLENGHT\")]/text()'\n )\n loader.add_xpath(\n 'jobtype',\n '//span[contains(@id, \"HRS_FULL_PART_TIME\")]/text()',\n MapJobTypes()\n )\n loader.add_xpath(\n 'expiration_date', '//span[contains(@id, \"_JO_PST_CLS_DT\")]/text()',\n ConvertDateString('%Y/%m/%d')\n )\n\n email_option = sel.xpath(\n \"//input[@name='HRS_CE_WRK2_HRS_CE_EML_FRND']\"\n )\n if email_option:\n formdata = {\n \"ICAction\": \"HRS_CE_WRK2_HRS_CE_EML_FRND\"\n }\n meta = {\"loader\": loader}\n yield FormRequest(\n response.url, formdata=formdata, meta=meta,\n callback=self.parse_mail, dont_filter=True\n )\n else:\n # individual job pages cannot be accessed through a URL\n loader.add_value('url', response.url)\n yield loader.load_item()\n\n def parse_goback(self, response):\n \"\"\"go back to job listing page,from job details page\"\"\"\n formdata = {'ICAction': \"HRS_CE_WRK2_HRS_REF_JB_RETURN\"}\n yield FormRequest(response.url, formdata=formdata, priority=5,\n callback=self.parse, dont_filter=True)\n","sub_path":"brightcorp/brightcorp/spiders/peoplesoft_sickkids.py","file_name":"peoplesoft_sickkids.py","file_ext":"py","file_size_in_byte":4086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"377771708","text":"#!/usr/bin/env python\n\"\"\"\nBinary stream representing persistent objects\n\"\"\"\n\nfrom struct import unpack, error\nimport binascii\nfrom datetime import datetime, timedelta\nimport os\nfrom typing import Optional\nfrom slyr_community.parser.object_registry import ObjectRegistry, REGISTRY\nfrom slyr_community.parser.object import Object\nfrom slyr_community.parser.exceptions import UnsupportedVersionException, UnreadableSymbolException, \\\n CustomExtensionClsidException\n\n\nclass Stream:\n \"\"\"\n An input stream for object parsing\n \"\"\"\n\n VBEMPTY = 0\n VBNULL = 1\n VBINTEGER = 2\n VBLONG = 3\n VBSINGLE = 4\n VBDOUBLE = 5\n VBCURRENCY = 6\n VBDATE = 7\n VBSTRING = 8\n VBOBJECT = 9\n VBERROR = 10\n VBBOOLEAN = 11\n VBVARIANT = 12\n VBDATAOBJECT = 13\n VBDECIMAL = 14\n VBBYTE = 17\n VBLONGLONG = 20\n VBUSERDEFINEDTYPE = 36\n VBARRAY = 8192\n USER_PASSWORD = 8209 # byte array\n\n def __init__(self,\n io_stream,\n debug: bool = False,\n offset: int = 0,\n force_layer=False, # pylint: disable=unused-argument\n extract_doc_structure=True, # pylint: disable=unused-argument\n parse_doc_structure_only=False, # pylint: disable=unused-argument\n tolerant=True,\n path=''): # pylint: disable=unused-argument\n \"\"\"\n Constructor for Streams\n :param io_stream: input stream, usually a file handle\n :param debug: true if debugging output should be created during object read\n :param offset: offset to start reading at\n \"\"\"\n self._io_stream = io_stream\n self.debug = debug\n self.debug_depth = 0\n self.allow_shortcuts = True\n self.tolerant = tolerant\n\n current = io_stream.tell()\n io_stream.seek(0, os.SEEK_END)\n self.end = io_stream.tell()\n io_stream.seek(current)\n\n if offset > 0:\n self._io_stream.seek(offset)\n\n def tell(self) -> int:\n \"\"\"\n Returns the current position within the stream.\n \"\"\"\n return self._io_stream.tell()\n\n def read(self, length: int) -> bin:\n \"\"\"\n Reads the from the stream for the given length and returns\n the binary result.\n \"\"\"\n return self._io_stream.read(length)\n\n def seek(self, offset: int):\n \"\"\"\n Seeks for the given offset.\n \"\"\"\n self._io_stream.seek(offset)\n\n def rewind(self, length):\n \"\"\"\n Rewinds by the given length\n \"\"\"\n self._io_stream.seek(self._io_stream.tell() - length)\n\n def log(self, message: str, offset: int = 0):\n \"\"\"\n Logs a debug message\n \"\"\"\n if self.debug:\n print('{}{} at {}'.format(' ' * self.debug_depth, message, hex(self._io_stream.tell() - offset)))\n\n def read_uchar(self, debug_string: str = '', expected=None) -> int:\n \"\"\"\n Reads a uchar from the stream.\n :return:\n \"\"\"\n res = unpack(\" float:\n \"\"\"\n Reads a double from the stream.\n :return:\n \"\"\"\n res = unpack(\" int:\n \"\"\"\n Reads an int from the stream.\n :return:\n \"\"\"\n try:\n res = unpack(\" int:\n \"\"\"\n Reads an uint from the stream.\n :return:\n \"\"\"\n res = unpack(\" int:\n \"\"\"\n Reads a signed int from the stream.\n :return:\n \"\"\"\n res = unpack(\" int:\n \"\"\"\n Reads an ulong from the stream.\n :return:\n \"\"\"\n res = unpack(\" int:\n \"\"\"\n Reads an unsigned short from the stream.\n :return:\n \"\"\"\n res = unpack(\" str:\n \"\"\"\n Reads a CLSID from the stream\n \"\"\"\n clsid_bin = binascii.hexlify(self._io_stream.read(16))\n\n clsid = ObjectRegistry.hex_to_clsid2(clsid_bin)\n if debug_string and clsid != '00000000-0000-0000-0000-000000000000':\n self.log('Found {} clsid of {}'.format(debug_string, clsid), 16)\n return clsid\n\n def read_raw_clsid(self, debug_string: str = '', expected=None) -> str:\n \"\"\"\n Reads a CLSID from the stream\n \"\"\"\n clsid_bin = binascii.hexlify(self._io_stream.read(16))\n clsid = ObjectRegistry.hex_to_clsid(clsid_bin)\n if debug_string and clsid != '00000000-0000-0000-0000-000000000000':\n self.log('Found {} clsid of {}'.format(debug_string, clsid), 16)\n\n if not self.tolerant and expected is not None:\n if isinstance(expected, (tuple, list)):\n assert clsid in expected, 'Got {}, expected {}'.format(clsid, expected)\n else:\n assert clsid == expected, 'Got {}, expected {}'.format(clsid, expected)\n\n return clsid\n\n def read_string(self, debug_string: str = '', expected=None, size=None) -> str:\n \"\"\"\n Decodes a string from the binary\n\n From the .dot BinaryWriter code: 'This method first writes the length of the string as\n a four-byte unsigned integer, and then writes that many characters\n to the stream'\n \"\"\"\n if debug_string:\n self.log('start {}'.format(debug_string))\n\n length = size if size is not None else self.read_uint('{} string length'.format(debug_string))\n if length < 2:\n raise UnreadableSymbolException('Invalid length of string {}'.format(length))\n\n self.log('string of length {}'.format(int(length / 2 - 1)), 4)\n buffer = self._io_stream.read(length - 2)\n string = buffer.decode('utf-16')\n terminator = binascii.hexlify(self._io_stream.read(2))\n if not terminator == b'0000':\n raise UnreadableSymbolException('Invalid string terminator')\n\n self.log('found string \"{}\"'.format(string))\n\n if not self.tolerant and expected is not None:\n if isinstance(expected, (tuple, list)):\n assert string in expected, 'Got {}, expected {}'.format(string, expected)\n else:\n assert string == expected, 'Got {}, expected {}'.format(string, expected)\n\n return string\n\n def read_stringv2(self, debug_string: str = '', expected=None) -> str:\n \"\"\"\n Decodes a string from the binary, alternative method\n \"\"\"\n if debug_string:\n self.log('start {}'.format(debug_string))\n\n length = self.read_uint('{} string length'.format(debug_string))\n if length < 0:\n raise UnreadableSymbolException('Invalid length of string {}'.format(length))\n\n self.log('string of length {}'.format(length), 4)\n if length != 0:\n buffer = self._io_stream.read(length * 2)\n string = buffer.decode('utf-16')\n terminator = binascii.hexlify(self._io_stream.read(2))\n\n self.log('found string \"{}\"'.format(string))\n if not terminator == b'0000':\n raise UnreadableSymbolException('Invalid string terminator')\n else:\n string = ''\n\n if not self.tolerant and expected is not None:\n if isinstance(expected, (tuple, list)):\n assert string in expected, 'Got \"{}\", expected {}'.format(string, expected)\n else:\n assert string == expected, 'Got \"{}\", expected {}'.format(string, expected)\n\n return string\n\n def read_string_terminated(self, debug_string: str = '', expected=None) -> str:\n \"\"\"\n Decodes a string from the binary, with no length but scanning for terminators\n \"\"\"\n if debug_string:\n self.log('start {}'.format(debug_string))\n\n string = ''\n res = self.read(2)\n while res != b'\\x00\\x00':\n string += res.decode('utf-16')\n res = self.read(2)\n\n self.log('found string \"{}\"'.format(string))\n\n if not self.tolerant and expected is not None:\n if isinstance(expected, (tuple, list)):\n assert string in expected, 'Got \"{}\", expected {}'.format(string, expected)\n else:\n assert string == expected, 'Got \"{}\", expected {}'.format(string, expected)\n\n return string\n\n def read_ascii(self, debug_string: str = '', expected=None, length=None) -> str:\n \"\"\"\n Decodes an ascii string from the binary\n \"\"\"\n if debug_string:\n self.log('start {}'.format(debug_string))\n\n length = length if length is not None else unpack(\" Optional[Object]:\n \"\"\"\n Creates and reads a new object from the stream\n \"\"\"\n clsid = self.read_clsid(debug_string)\n try:\n res = REGISTRY.create_object(clsid)\n except CustomExtensionClsidException as e:\n self.debug_depth += 1\n self.log('!!!Custom extension encountered -- cannot read ({})'.format(e), 16)\n self.debug_depth -= 1\n raise e\n\n if res is not None:\n self.log('** {} **'.format(res.__class__.__name__), 16)\n else:\n self.log('{} not found'.format(debug_string), 16)\n\n if res is not None:\n self.debug_depth += 1\n\n version = 1\n compatible_versions = res.compatible_versions()\n if compatible_versions is not None:\n version = self.read_ushort('version')\n if version not in res.compatible_versions():\n supported_versions = ','.join([str(v) for v in res.compatible_versions()])\n raise UnsupportedVersionException(\n 'Cannot read {} version {}, only support version(s): {}'.format(\n res.__class__.__name__, version, supported_versions))\n\n res.version = version\n try:\n res.read(self, version)\n except CustomExtensionClsidException as e:\n self.log('!!!Custom extension encountered -- only partial read of {}'.format(res.__class__.__name__),\n 16)\n e.custom_object = res\n self.debug_depth -= 1\n raise e\n self.log('ended {}'.format(res.__class__.__name__))\n\n if self.debug:\n print('')\n self.debug_depth -= 1\n\n return res\n\n def read_variant(self, variant_type=None, debug_string: str = '', expected=None): # pylint: disable=too-many-branches\n \"\"\"\n Reads a variant value from the stream\n \"\"\"\n if debug_string:\n self.log('reading variant {}'.format(debug_string))\n if variant_type is None:\n variant_type = self.read_ushort('type')\n if variant_type == Stream.VBSTRING:\n value = self.read_string('value')\n elif variant_type == Stream.VBLONG:\n value = self.read_ulong('value')\n elif variant_type == Stream.VBSINGLE:\n value = self.read_int('value')\n elif variant_type == Stream.VBINTEGER:\n value = self.read_ushort('value')\n elif variant_type in (Stream.VBNULL, Stream.VBEMPTY):\n value = None\n elif variant_type == Stream.VBDOUBLE:\n value = self.read_double('value')\n elif variant_type == Stream.VBBOOLEAN:\n value = self.read_ushort('value') != 0\n elif variant_type == Stream.VBDATE:\n value = datetime.strftime(\n datetime(year=100, month=1, day=1) + timedelta(days=self.read_double('value') + 657434),\n '%Y-%m-%d %H:%M:%S')\n elif variant_type == Stream.USER_PASSWORD:\n length = self.read_uint('password length')\n value = '*' * length\n self.read(length)\n elif variant_type == Stream.VBDATAOBJECT:\n value = self.read_object('value')\n else:\n raise UnreadableSymbolException('Unknown property type {}'.format(variant_type))\n\n if not self.tolerant and expected is not None:\n if isinstance(expected, (tuple, list)):\n assert value in expected, 'Got {}, expected {}'.format(value, expected)\n else:\n assert value == expected, 'Got {}, expected {}'.format(value, expected)\n\n return value\n","sub_path":"slyr_community/parser/stream.py","file_name":"stream.py","file_ext":"py","file_size_in_byte":16507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"16483647","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.linux-x86_64/egg/nushell/examples/pokemon/nu_plugin_pokemon.py\n# Compiled at: 2019-10-24 11:59:16\n# Size of source mod 2**32: 3232 bytes\nfrom nushell.sink import SinkPlugin\nfrom pokemon.master import get_pokemon, catch_em_all\nfrom pokemon.skills import get_ascii, get_avatar\n\ndef list_pokemon(do_sort=False):\n \"\"\"print list of all names of pokemon in database\n\n Parameters\n ==========\n do_sort: return list of sorted pokemon (ABC)\n \"\"\"\n names = catch_em_all(return_names=True)\n if do_sort:\n names.sort()\n for name in names:\n try:\n print(name)\n except:\n pass\n\n\ndef catch_pokemon():\n \"\"\"use the get_pokemon function to catch a random pokemon, return it\n (along with stats!) as a single string\n \"\"\"\n catch = get_pokemon()\n for pokemon_id, meta in catch.items():\n response = meta['ascii']\n response = '%s\\n%s %s' % (response, meta['name'], meta['link'])\n print(response)\n\n\ndef sink(plugin, params):\n \"\"\"sink will be executed by the calling SinkPlugin when method is \"sink\"\n and should be able to parse the dictionary of params and respond\n appropriately. Since this is a sink, whatever you print to stdout\n will show for the user. Useful functions:\n\n plugin.logger.\n \"\"\"\n if params.get('catch', False):\n plugin.logger.info('We want to catch a random pokemon!')\n catch_pokemon()\n else:\n if params.get('list', False):\n plugin.logger.info('We want to list Pokemon names.')\n list_pokemon()\n else:\n if params.get('list-sorted', False):\n plugin.logger.info('We want to list sorted Pokemon names.')\n list_pokemon(do_sort=True)\n else:\n if params.get('avatar', '') != '':\n plugin.logger.info('We want a pokemon avatar!')\n catch = get_avatar(params['avatar'])\n else:\n if params.get('pokemon', '') != '':\n get_ascii(name=(params['pokemon']))\n else:\n print(plugin.get_help())\n\n\ndef main():\n plugin = SinkPlugin(name='pokemon', usage='Catch an asciinema pokemon on demand.')\n plugin.add_named_argument('catch', 'Switch', usage='catch a random pokemon')\n plugin.add_named_argument('list', 'Switch', usage='list pokemon names')\n plugin.add_named_argument('list-sorted', 'Switch', usage='list sorted names')\n plugin.add_named_argument('avatar', 'Optional', 'String', 'generate avatar')\n plugin.add_named_argument('pokemon', 'Optional', 'String', 'get pokemon')\n plugin.run(sink)\n\n\nif __name__ == __main__:\n main()","sub_path":"pycfiles/nushell-0.0.16-py3.7/nu_plugin_pokemon.cpython-37.py","file_name":"nu_plugin_pokemon.cpython-37.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"106032121","text":"import logging\nimport sys\nimport os\nimport unittest\nsys.path.insert(0, os.path.abspath('.'))\nsys.path.insert(0, os.path.abspath('../'))\nfrom analyze.effects import introduced_total_effect, total_effect\nfrom analyze.value_of_information import admits_voi, admits_voi_list\nfrom core.cpd import FunctionCPD\nfrom examples.simple_cids import get_minimal_cid, get_trim_example_cid\nfrom examples.story_cids import get_introduced_bias, get_content_recommender, get_fitness_tracker, \\\n get_modified_content_recommender, get_grade_predictor\nfrom analyze.requisite_graph import requisite, requisite_graph\nfrom analyze.value_of_control import admits_voc, admits_voc_list, admits_indir_voc, admits_indir_voc_list, \\\n admits_dir_voc, admits_dir_voc_list\nfrom analyze.response_incentive import admits_ri, admits_ri_list\nfrom analyze.instrumental_control_incentive import admits_ici, admits_ici_list\nfrom core.macid import MACID\n\n\nclass TestAnalyze(unittest.TestCase):\n\n def setUp(self) -> None:\n logging.disable()\n\n # @unittest.skip(\"\")\n def test_value_of_information(self) -> None:\n cid = get_introduced_bias()\n self.assertTrue(admits_voi(cid, 'D', 'A'))\n self.assertEqual(set(admits_voi_list(cid, 'D')), {'A', 'X', 'Z', 'Y'})\n cid2 = get_grade_predictor()\n self.assertCountEqual(admits_voi_list(cid2, 'P'), ['HS', 'E', 'Gr'])\n self.assertFalse(admits_voi(cid2, 'P', 'Ge'))\n with self.assertRaises(Exception):\n admits_voi(cid2, 'P', 'A')\n with self.assertRaises(Exception):\n admits_voi(cid2, 'B', 'Ge')\n cid2.remove_edge('HS', 'P')\n self.assertCountEqual(admits_voi_list(cid2, 'P'), ['R', 'HS', 'E', 'Gr'])\n\n # @unittest.skip(\"\")\n def test_total_effect(self) -> None:\n cid = get_minimal_cid()\n cid.impute_random_policy()\n self.assertEqual(total_effect(cid, 'A', 'B', 0, 1), 1)\n cid = get_introduced_bias()\n cid.impute_random_policy()\n self.assertEqual(total_effect(cid, 'A', 'X', 0, 1), 0.5)\n self.assertEqual(total_effect(cid, 'A', 'D', 0, 1), 0)\n self.assertEqual(total_effect(cid, 'A', 'Y', 0, 1), 0.5)\n\n # @unittest.skip(\"\")\n def test_introduced_total_effect(self) -> None:\n cid = get_introduced_bias()\n cid.impute_random_policy()\n self.assertEqual(introduced_total_effect(cid, 'A', 'D', 'Y', 0, 1), -0.5)\n cid.impute_conditional_expectation_decision('D', 'Y')\n self.assertAlmostEqual(introduced_total_effect(cid, 'A', 'D', 'Y', 0, 1), 0.3333, 2)\n # Try modified model where X doesn't depend on Z\n cid = get_introduced_bias()\n cid.impute_random_policy()\n cid.add_cpds(FunctionCPD('X', lambda a, z: a, evidence=['A', 'Z']))\n cid.impute_conditional_expectation_decision('D', 'Y')\n self.assertAlmostEqual(introduced_total_effect(cid, 'A', 'D', 'Y', 0, 1), 0, 2)\n # Try modified model where Y doesn't depend on Z\n cid = get_introduced_bias()\n cid.impute_random_policy()\n cid.add_cpds(FunctionCPD('Y', lambda x, z: x, evidence=['X', 'Z']))\n cid.impute_conditional_expectation_decision('D', 'Y')\n self.assertAlmostEqual(introduced_total_effect(cid, 'A', 'D', 'Y', 0, 1), 0, 2)\n # Try modified model where Y doesn't depend on X\n cid = get_introduced_bias()\n cid.impute_random_policy()\n cid.add_cpds(FunctionCPD('Y', lambda x, z: z, evidence=['X', 'Z']))\n cid.impute_conditional_expectation_decision('D', 'Y')\n self.assertAlmostEqual(introduced_total_effect(cid, 'A', 'D', 'Y', 0, 1), 0.333, 2)\n\n def test_requisite_graph(self) -> None:\n cid = get_trim_example_cid()\n self.assertFalse(requisite(cid, 'D2', 'D1'))\n self.assertTrue(requisite(cid, 'D2', 'Y2'))\n self.assertCountEqual(cid.get_parents('D2'), ['Y1', 'Y2', 'D1', 'Z1', 'Z2'])\n self.assertEqual(len(cid.edges), 12)\n req_graph = requisite_graph(cid)\n self.assertEqual(len(req_graph.edges), 7)\n self.assertCountEqual(req_graph.get_parents('D2'), ['Y2'])\n\n def test_value_of_control(self) -> None:\n cid = get_content_recommender()\n self.assertCountEqual(admits_voc_list(cid), ['O', 'I', 'M', 'C'])\n cid2 = get_modified_content_recommender()\n self.assertCountEqual(admits_voc_list(cid2), ['O', 'M', 'C'])\n self.assertTrue(admits_voc(cid2, 'M'))\n self.assertFalse(admits_voc(cid2, 'I'))\n with self.assertRaises(Exception):\n admits_voc(cid2, 'A')\n with self.assertRaises(Exception):\n admits_voc(cid2, 'J')\n macid = MACID([('D1', 'D2'),\n ('D1', 'U1'),\n ('D1', 'U2'),\n ('D2', 'U2'),\n ('D2', 'U1')],\n {0: {'D': ['D1'], 'U': ['U1']},\n 1: {'D': ['D2'], 'U': ['U2']}})\n with self.assertRaises(Exception):\n admits_voc(macid, 'D2')\n with self.assertRaises(Exception):\n admits_voc_list(macid)\n\n def test_instrumental_control_incentive(self) -> None:\n cid = get_content_recommender()\n self.assertTrue(admits_ici(cid, 'P', 'I'))\n self.assertFalse(admits_ici(cid, 'P', 'O'))\n self.assertCountEqual(admits_ici_list(cid, 'P'), ['I', 'P', 'C'])\n with self.assertRaises(Exception):\n admits_ici(cid, 'P', 'A')\n with self.assertRaises(Exception):\n admits_ici(cid, 'B', 'O')\n macid = MACID([('D1', 'D2'),\n ('D1', 'U1'),\n ('D1', 'U2'),\n ('D2', 'U2'),\n ('D2', 'U1')],\n {0: {'D': ['D1'], 'U': ['U1']},\n 1: {'D': ['D2'], 'U': ['U2']}})\n with self.assertRaises(Exception):\n admits_ici(macid, 'D2', 'D1')\n with self.assertRaises(Exception):\n admits_ici_list(macid, 'D2')\n\n def test_response_incentive(self) -> None:\n cid = get_grade_predictor()\n self.assertCountEqual(admits_ri_list(cid, 'P'), ['R', 'HS'])\n self.assertFalse(admits_ri(cid, 'P', 'E'))\n self.assertTrue(admits_ri(cid, 'P', 'R'))\n cid.remove_edge('HS', 'P')\n self.assertEqual(admits_ri_list(cid, 'P'), [])\n with self.assertRaises(Exception):\n admits_ri(cid, 'P', 'A')\n with self.assertRaises(Exception):\n admits_ri(cid, 'B', 'E')\n macid = MACID([('D1', 'D2'),\n ('D1', 'U1'),\n ('D1', 'U2'),\n ('D2', 'U2'),\n ('D2', 'U1')],\n {0: {'D': ['D1'], 'U': ['U1']},\n 1: {'D': ['D2'], 'U': ['U2']}})\n with self.assertRaises(Exception):\n admits_ri(macid, 'D2', 'D1')\n with self.assertRaises(Exception):\n admits_ri_list(macid, 'D2')\n\n def test_indirect_value_of_control(self) -> None:\n cid = get_fitness_tracker()\n self.assertFalse(admits_indir_voc(cid, 'C', 'TF'))\n self.assertTrue(admits_indir_voc(cid, 'C', 'SC'))\n self.assertCountEqual(admits_indir_voc_list(cid, 'C'), ['SC'])\n with self.assertRaises(Exception):\n admits_indir_voc(cid, 'C', 'A')\n with self.assertRaises(Exception):\n admits_indir_voc(cid, 'B', 'TF')\n macid = MACID([('D1', 'D2'),\n ('D1', 'U1'),\n ('D1', 'U2'),\n ('D2', 'U2'),\n ('D2', 'U1')],\n {0: {'D': ['D1'], 'U': ['U1']},\n 1: {'D': ['D2'], 'U': ['U2']}})\n with self.assertRaises(Exception):\n admits_indir_voc(macid, 'D2', 'D1')\n with self.assertRaises(Exception):\n admits_indir_voc_list(macid, 'D2')\n\n def test_direct_value_of_control(self) -> None:\n cid = get_fitness_tracker()\n self.assertFalse(admits_dir_voc(cid, 'TF'))\n self.assertTrue(admits_dir_voc(cid, 'F'))\n self.assertCountEqual(admits_dir_voc_list(cid), ['F', 'P'])\n with self.assertRaises(Exception):\n admits_dir_voc(cid, 'B')\n macid = MACID([('D1', 'D2'),\n ('D1', 'U1'),\n ('D1', 'U2'),\n ('D2', 'U2'),\n ('D2', 'U1')],\n {0: {'D': ['D1'], 'U': ['U1']},\n 1: {'D': ['D2'], 'U': ['U2']}})\n with self.assertRaises(Exception):\n admits_dir_voc(macid, 'D2')\n with self.assertRaises(Exception):\n admits_dir_voc_list(macid)\n\n\nif __name__ == \"__main__\":\n suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestAnalyze)\n unittest.TextTestRunner().run(suite)\n\n# %%\n","sub_path":"test/test_analyze.py","file_name":"test_analyze.py","file_ext":"py","file_size_in_byte":8819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"495664656","text":"\nimport subprocess as subp\nimport sys\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Input handling\nif len(sys.argv) != 1 + 1:\n print('One argument required.\\n'\n 'Usage: %s ' % sys.argv[0])\n sys.exit(1)\ntry:\n n = int(sys.argv[1])\nexcept ValueError:\n print('Invalid argument. Int expected.')\n sys.exit(1)\n\n# Extract output\nd = np.arange(2, n)\ntime_own = np.zeros(n - 2)\ntime_arma = np.zeros(n - 2)\nfor i in range(len(d)):\n try:\n lines = subp.check_output(['./timing', str(d[i])]).decode('utf-8').split('\\n')\n time_own[i], time_arma[i] = lines\n except subp.CalledProcessError as e:\n print('Command \"%s\" failed with error:\\n %s' % (' '.join(e.cmd),\n e.stdout.decode()))\n sys.exit(1)\n\n# Plot\nplt.rc('text', usetex=True)\nplt.rc('font', family='serif')\n\nplt.plot(d, 1e3 * time_own, label='own implementation')\nplt.plot(d, 1e3 * time_arma, label='Armadillo implementation')\n\nfit_own = np.polyfit(d, time_own, 2)\nfit_own_x = np.linspace(2, n, 1000)\nfit_own_y = np.poly1d(fit_own)\nplt.plot(fit_own_x, 1e3 * fit_own_y(fit_own_x), '--',\n label=r'own fit: $%.1fx^2%+.1fx%+.1f$' % tuple(1e3 * fit_own))\n\nfit_arma = np.polyfit(d, time_arma, 2)\nfit_arma_x = np.linspace(2, n, 1000)\nfit_arma_y = np.poly1d(fit_arma)\nplt.plot(fit_arma_x, 1e3 * fit_arma_y(fit_arma_x), '--',\n label=r'Armadillo fit: $%.1fx^2%+.1fx%+.1f$' % tuple(1e3 * fit_arma))\n\nplt.xlabel('number of discretization points')\nplt.ylabel(r'$\\mathrm{time/ms}$')\nplt.legend()\nplt.show()\n","sub_path":"project2/analyse_timing.py","file_name":"analyse_timing.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"411744321","text":"#!/usr/bin/env python\n\nfrom __future__ import division\n\nimport argparse\nimport os.path as osp\n\nimport chainer\nimport scipy.misc\n\nimport fcn\n\nfrom dataset import APC2015Dataset\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--gpu', default=0, type=int,\n help='if -1, use cpu only (default: 0)')\n parser.add_argument('-c', '--chainermodel', required=True)\n parser.add_argument('-i', '--img-files', nargs='+', required=True)\n args = parser.parse_args()\n\n img_files = args.img_files\n gpu = args.gpu\n chainermodel = args.chainermodel\n save_dir = chainer.dataset.get_dataset_directory(\n 'fcn/examples/apc2015/inference')\n\n dataset = APC2015Dataset('val')\n\n model = fcn.models.FCN32s(n_class=len(dataset.label_names))\n chainer.serializers.load_hdf5(chainermodel, model)\n\n infer = fcn.Inferencer(dataset, model, gpu)\n for img_file in img_files:\n img, label = infer.infer_image_file(img_file)\n out_img = infer.visualize_label(img, label)\n\n out_file = osp.join(save_dir, osp.basename(img_file))\n scipy.misc.imsave(out_file, out_img)\n print('- out_file: {0}'.format(out_file))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/apc2015/infer.py","file_name":"infer.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"356980129","text":"class User:\n def __init__(self, name):\n self.name = name\n\n enter = input(f\"{self.name} enter choice... \")\n\n if enter == \"1\" or enter == \"2\" or enter == \"3\":\n self.choice = enter - 1\n else:\n print(\"Введите число от 1 до 3\")\n exit()\n","sub_path":"kanobu/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"295174957","text":"\ntry:\n from djangoappengine.settings_base import *\n has_djangoappengine = True\nexcept ImportError:\n has_djangoappengine = False\n DEBUG = True\n TEMPLATE_DEBUG = DEBUG\n \nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nimport os\n\nSERVE_FILE_BACKEND = 'filetransfers.backends.blobsendfile.serve_file'\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'djangotoolbox',\n 'filetransfers',\n 'search',\n 'gmp',\n 'gmpadmin',\n 'openid_login',\n)\n\nUSE_I18N = False\n\nif has_djangoappengine:\n INSTALLED_APPS = ('djangoappengine',) + INSTALLED_APPS\n\nADMIN_MEDIA_PREFIX = '/media/admin/'\nMEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media')\nTEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'),)\n\nROOT_URLCONF = 'urls'\n\nSECRET_KEY = '=r-$b*8hglm+858&9t043hlm6-&6-3d3vfc4((7yd0dbrakhvi'\n\n# Activate django-dbindexer if available\ntry:\n import dbindexer\n DATABASES['native'] = DATABASES['default']\n DATABASES['default'] = {'ENGINE': 'dbindexer', 'TARGET': 'native'}\n INSTALLED_APPS += ('dbindexer',)\nexcept ImportError:\n pass\n\nCACHE_BACKEND = 'memcached://?timeout=0'\n\n# Green Mountain Project settings\nTHUMBNAIL_GEOMETRY_16_9 = (160, 90)\nTHUMBNAIL_GEOMETRY_1_1 = (128, 128)\nPREVIEW_GEOMETRY = (660, 540)\nMIN_GEOMETRY = (640, 480)\n\n\nDEFAULT_PREVIEW_WIDTH = 660\nDEFAULT_PREVIEW_HEIGHT = 540\nMIN_PHOTO_WIDTH = 640\nMIN_PHOTO_HEIGHT = 480\n\nAUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend',\n 'openid_login.gae_federated_backend.GAEFederatedBackend',\n 'openid_login.facebook_backend.FacebookBackend',\n)\n \nLOGIN_URL = '/openid_login/'\nLOGOUT_URL = '/openid_login/logout'\n \nAPI_VERSION = '12'\n\nADMINS = (\n ('Dan Julius', 'dan.julius@gmail.com'),\n)\n \nMANAGERS = ADMINS\n \nAUTH_PROFILE_MODULE = 'gmp.UserProfile'\n\nFACEBOOK_APP_ID='186932087992297'\nFACEBOOK_API_KEY='a6cc04e8b615f93260862be5942a2743'\nFACEBOOK_SECRET_KEY='efb45e58dd894c3bf17371f08546eecc'\nFACEBOOK_INTERNAL = False\n\n","sub_path":"main/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"49361284","text":"#!/usr/bin/python3\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom statistics import mean\nfrom collections import Counter\n# #from sklearn.linear_model import LinearRegression\n# from sklearn import linear_model\n# from sklearn.metrics import mean_squared_error, r2_score\n\n\ndata_1 = np.loadtxt('3_c_dataStrong.dat')\ndata_2 = np.loadtxt('3_c_dataWeak.dat')\n# data_3 = np.loadtxt('trap_ompl2.dat')\n\n\nN = data_1[:, 0]\nerr = data_1[:, 2]\nerr_1 = data_2[:, 2]\n\n\n# Plotting\nfig = plt.figure()\nplt.loglog(N, err, 'black', label='Abs Error: Serial Data',\n marker='o', markerfacecolor='red', markersize=4)\nplt.loglog(N, err_1, 'blue', label='Abs Error: Parallel Data', marker='o',\n markerfacecolor='black', markersize=4)\n## Theoritical error of MC: err is proportional to Itr ^ (-1/2) ###\nplt.loglog(N, 1000/np.sqrt(N), 'green', label='Theory:'r'$E(N)\\propto N^{-1/2}$', marker='o',\n markerfacecolor='black', markersize=4)\n# plt.loglog(N, y_3, 'green', label='trap_ompl2 Error', marker='o',\n# markerfacecolor='red', markersize=4)\n\nplt.legend()\nplt.grid(True)\nplt.minorticks_on()\n# Customize the major grid\nplt.grid(which='major', linestyle='-', linewidth='0.5', color='black')\n# Customize the minor grid\nplt.grid(which='minor', linestyle='--', linewidth='0.5', color='black')\n\nplt.xlabel('Iteration, N')\nplt.ylabel('Abs Error')\n# plt.title('Numerical Intergration: Err vs Iteration')\n# plt.show()\nfig.savefig(\"Comparison between serial and parallel_1.png\",\n bbox_inches=\"tight\")\nplt.show()\n","sub_path":"Home Works/HW_3/Code/Task 3/plotAbs.py","file_name":"plotAbs.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"525174030","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nCreated on 2020-03-27 01:23 \n\n@author: congyingxu\n\"\"\"\n\nimport os\nimport random\nimport time\n\nimport requests\nfrom urllib3.exceptions import InsecureRequestWarning\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\nimport UserAgents\n\ndef request_url(url):\n print('------------------------- url:' + url)\n headers = {'User-Agent': random.choice(UserAgents.agents)}\n url_content = requests.get(url, headers=headers, verify=False)\n # requests.\n return url_content\n\n\ndef session_get_url(url):\n # 参考博客 https://segmentfault.com/q/1010000008473868\n print('------------------------- url:' + url)\n session = requests.Session()\n session.headers = {\n 'User-Agent': random.choice(UserAgents.agents),\n 'Host': 'api.sourceclear.com',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Connection': 'keep-alive',\n 'Cookie': 'sp_collector=430868eb-0555-41b2-b1a1-2f81d74b93f5',\n 'Upgrade-Insecure-Requests': '1'\n }\n\n\n try :\n url_content = session.get(url,timeout=10)\n except:\n print(\"requests.exceptions.ReadTimeout\")\n for i in range(130):\n print(i)\n time.sleep(1)\n print(\"requests.exceptions.ReadTimeout. sleep over\")\n url_content = session.get(url, timeout=10)\n return url_content\n\n\ndef save_file_from_url(url, path):\n if os.path.exists(path):\n return\n time.sleep(random.randint(1, 3))\n headers = {'User-Agent': random.choice(UserAgents.agents)}\n package = requests.get(url, headers=headers)\n with open(path, \"wb\") as f:\n f.write(package.content)\n f.close()","sub_path":"CVE_HW_DatasetComparison/CrawlVearcode/CrawlUtil.py","file_name":"CrawlUtil.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"124316790","text":"from datetime import datetime, timezone\nfrom django.contrib.auth import get_user_model\nfrom django.test import TestCase\nfrom freemoney.models import (ApplicantProfile,\n Application,\n Award,\n CustomValidationIssueSet,\n Essay,\n EssayPrompt,\n Semester)\n\n\nclass EssayPromptTests(TestCase):\n \"\"\"Test the validation of Essay responses within an Application\"\"\"\n\n def setUp(self):\n self.applicant = ApplicantProfile.objects.create(\n user=get_user_model().objects.create_user(\n username='test1234@example.com',\n password='pass1234'\n ),\n must_change_password=False\n )\n self.application = Application.objects.create(\n applicant=self.applicant,\n due_at = datetime(2016, 11, 15, tzinfo=timezone.utc)\n )\n\n def test_max_length(self):\n \"\"\"Verify that the word count is enforced\"\"\"\n prompt = EssayPrompt.objects.create(\n identifier='test',\n prompt='This is a test!',\n word_limit=6,\n previous_version=None\n )\n essay = Essay.objects.create(\n application=self.application,\n prompt=prompt,\n response = \"\"\"lorem ipsum! facto blargson\n\n test text\"\"\"\n )\n\n issues = CustomValidationIssueSet()\n self.application.custom_validate(issues)\n found_issues = issues.search(section='essay',\n code='max-length')\n self.assertEqual(len(found_issues), 0)\n\n # Only one more word is needed to meet the advertised limit, but the\n # code is generous and makes this a \"soft\" limit; add several more\n # words to test the \"hard\" limit\n essay.response += ' anotherword!' * 6\n essay.full_clean()\n essay.save()\n self.application.custom_validate(issues)\n found_issues = issues.search(section='essay',\n code='max-length')\n self.assertEqual(len(found_issues), 1)\n first_iter = iter(found_issues)\n self.assertNotEqual(next(first_iter).subfield, None)\n\n\nclass EssayPromptAvailabilityTests(TestCase):\n \"\"\"Verify that EssayPrompts are available under specific circumstances\"\"\"\n\n def setUp(self):\n self.old = EssayPrompt.objects.create(\n identifier='test',\n prompt='This is a test!',\n word_limit=500,\n previous_version=None\n )\n self.mid = EssayPrompt.objects.create(\n identifier='test',\n prompt='This is a newer test!',\n word_limit=500,\n previous_version=self.old\n )\n self.new = EssayPrompt.objects.create(\n identifier='test',\n prompt='This is the newest test!',\n word_limit=500,\n previous_version=self.mid\n )\n\n def test_latest_essay_prompt_nominal(self):\n \"\"\"Check that the latest version of an essay prompt is returned\"\"\"\n self.assertEqual(self.new,\n EssayPrompt.objects.latest_version_of('test'))\n\n def test_latest_essay_prompt_with_cycle(self):\n \"\"\"Verify graceful handling of an infinite foreign key loop\"\"\"\n\n self.old.previous_version = self.new\n self.old.full_clean()\n self.old.save()\n with self.assertRaises(ValueError):\n EssayPrompt.objects.latest_version_of('test')\n\n def test_latest_essay_prompt_with_split(self):\n \"\"\"Verify graceful handling of a *split* or *branched* prompt\"\"\"\n\n self.mid.previous_version = None\n self.mid.full_clean()\n self.mid.save()\n with self.assertRaises(ValueError):\n EssayPrompt.objects.latest_version_of('test')\n\n def test_latest_essay_prompt_with_selfcycles(self):\n \"\"\"The worst case: each prompt points to itself, independently\"\"\"\n\n for essay in EssayPrompt.objects.filter(identifier='test'):\n essay.previous_version = essay\n essay.save()\n with self.assertRaises(ValueError):\n EssayPrompt.objects.latest_version_of('test')\n","sub_path":"freemoney/models/test_essay.py","file_name":"test_essay.py","file_ext":"py","file_size_in_byte":4397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"537356571","text":"\"\"\"\n 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。\n 例如���给出 n = 3,生成结果为:\n [\n \"((()))\",\n \"(()())\",\n \"(())()\",\n \"()(())\",\n \"()()()\"\n ]\n\n\"\"\"\n\nfrom typing import List\n\n\nclass Solution:\n def generateParenthesis(self, n: int) -> List[str]:\n res = []\n if n > 0:\n self.recursive(0, 0, n, \"\", res)\n return res\n\n @classmethod\n def recursive(cls, left: int, right: int, n: int, s: str, res: List[str]) -> None:\n # terminator\n if left == right == n:\n res.append(s)\n return\n\n # code logic\n if left < n:\n # drill down\n cls.recursive(left + 1, right, n, s + \"(\", res)\n\n if right < left:\n # drill down\n cls.recursive(left, right + 1, n, s + \")\", res)\n\n\nif __name__ == \"__main__\":\n print(Solution().generateParenthesis(3))\n","sub_path":"Week_03/G20200343030545/LeetCode_22_545.py","file_name":"LeetCode_22_545.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"167755759","text":"''' 1. function untuk convert kelvin ke celsius dan sebaliknya. \n data type -> \n parameter: \n temperature: float\n unit: string\n return: float\n'''\ndef convert_kelvin_celsius(temperature, unit): \n ''' rumus convert celsius -> kelvin\n return -> float ''' \n if unit.lower() == 'c':\n return temperature + 273.15\n \n ''' rumus convert kelvin -> celsius\n return -> float '''\n if unit.lower() == 'k':\n return temperature - 273.15 \n\n ''' return apabila nilai unit bukan k atau c ''' \n return temperature \n\n\n''' 2. function untuk convert kelvin / celsius -> fahrenheit. \n data type -> \n parameter: \n temperature: float\n unit: string\n return: float \n'''\ndef convert_to_fahrenheit(temperature, unit): \n temp = temperature\n\n ''' return apabila nilai unit bukan k atau c ''' \n if unit.lower() != 'k' and unit.lower() != 'c': \n return temp\n\n ''' apabila parameter unit bernilai kelvin (K/k), \n maka suhu diconvert dulu ke celcius (C/c) '''\n if unit.lower() == 'k': \n temp = convert_kelvin_celsius(temperature, unit)\n\n ''' return convert celsius -> fahrenheit '''\n return (temp * 9 / 5) + 32 \n\n\n''' 3. function untuk convert fahrenheit -> kelvin / celsius. \n data type -> \n parameter: \n temperature: float\n unit: string\n return: float \n'''\ndef convert_from_fahrenheit(temperature, unit):\n ''' convert fahrenheit -> celcius '''\n if unit.lower() == 'c':\n return ((temperature - 32) * 5 / 9)\n ''' convert fahrenheit -> kelvin '''\n if unit.lower() == 'k':\n return ((temperature - 32) * 5 / 9 + 273.15)\n ''' return temperature awal, apabila nilai unit bukan c atau k '''\n return temperature\n\n\n\n# tes\nresult1 = convert_kelvin_celsius(100, 'C')\nresult2 = convert_to_fahrenheit(373.15, 'K')\nresult3 = convert_to_fahrenheit(100, 'C')\nresult4 = convert_from_fahrenheit(32, 'C')\n\nprint(result1)\nprint(result2)\nprint(result3)\nprint(result4)\n\n","sub_path":"sesi-03/027_h8ocbc_converter.py","file_name":"027_h8ocbc_converter.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"349014623","text":"import urllib.request\nimport os\nimport time\nimport pymysql\nimport pdb;\nimport sys;\nfrom crop import crop_img\nfrom env_setting import host, user, password, db\n\n# DOWNLOAD_PATH = sys.argv[1]\nCROP_PATH = sys.argv[1]\n\n\n# 각각의 카테고리 마다 몇개 다운받았는지 DB에 저장\nclass ImageDownloader:\n def __init__(self):\n self.get_connection()\n self.sharding_no = '0/'\n self.index_no = 0\n # ong = sorted(glob.glob(CROP_PATH+\"/*\"))\n\n def get_connection(self):\n is_conn_success = False\n while not is_conn_success:\n try:\n self.conn = pymysql.connect(host=host,\n user=user,\n password=password,\n db=db,\n charset='utf8',\n cursorclass=pymysql.cursors.DictCursor)\n except Exception as e:\n print(\"db connection exception occures\")\n print(e)\n continue\n\n if self.conn is not None:\n is_conn_success = True\n\n return self.conn\n\n def disconnect_connection(self):\n self.conn.close()\n\n def __del__(self):\n self.disconnect_connection()\n\n def get_all_urls(self, size=1000,offset=0):\n get_all_url_sql = 'SELECT image_idx, image_url, file_address FROM image_info WHERE status = 1 LIMIT %s OFFSET %s'\n result = list()\n\n read_success = False\n while not read_success:\n try:\n conn = self.conn\n cursor = conn.cursor()\n\n cursor.execute(get_all_url_sql, (size,offset))\n\n result = cursor.fetchall()\n\n except Exception as e:\n print(e)\n continue\n finally:\n cursor.close()\n\n read_success = True\n\n return result\n\n def get_specific_urls(self, keyword, size=1000):\n get_url_sql = 'SELECT image_idx,file_address FROM image_info WHERE status = 1 and search_keyword = %s LIMIT %s'\n result = list()\n read_success = False\n\n while not read_success:\n try:\n conn = self.conn\n cursor = conn.cursor()\n\n cursor.execute(get_url_sql, (keyword, size))\n\n result = cursor.fetchall()\n\n except Exception as e:\n print(e)\n continue\n finally:\n cursor.close()\n\n read_success = True\n\n return result\n\n def download_crop(self, addr_list):\n self.sharding_no = str(self.index_no // 1000) + \"/\"\n for url_info in addr_list:\n if url_info['image_idx'] is not None :\n file_address = url_info['file_address']\n else:\n continue\n\n # 파일명은 image_idx로 지정\n filename = str(self.index_no) + \".jpg\"\n\n\n path = os.getcwd() + CROP_PATH + \"/\" + self.sharding_no\n\n file_path = path + filename\n\n # Create when directory does not exist\n if not os.path.isdir(path):\n os.makedirs(path)\n\n # download\n is_download_success = False\n try_count = 0\n\n\n while not is_download_success:\n try:\n # download img using url\n #pdb.set_trace()\n crop_img(os.getcwd()+\"/\"+file_address,file_path,224)\n except Exception as e:\n print(e)\n # 5회 다운로드 시도 후 실패하면 다음 이미지로 넘어감\n if try_count < 5:\n print(\"download failed. try again...\")\n try_count = try_count + 1\n continue\n else:\n break\n\n is_download_success = True\n # 폴더명과 파일 이름 지정\n\n if self.index_no%100==0: print(\"%s is downloading.. \" %(file_path))\n self.sharding_no = str(self.index_no // 1000) + \"/\"\n self.index_no+=1\n\n def run_download(self, keyword=\"all\", size=1000):\n offset=0\n while True:\n start_time = time.time()\n if keyword == \"all\":\n addr_list = self.get_all_urls(size,offset)\n else:\n addr_list = self.get_specific_urls(keyword, size)\n\n if len(addr_list) == 0:\n print('no url exists')\n break\n\n print(\"url list size : \", len(addr_list))\n\n self.download_crop(addr_list)\n\n print(\"download 1000 images took %s seconds\" % (time.time() - start_time))\n offset+=size\n\n print(\"download finish\")\n\n\nif __name__ == \"__main__\":\n\n obj = ImageDownloader()\n obj.run_download(size=1000)\n","sub_path":"already.py","file_name":"already.py","file_ext":"py","file_size_in_byte":4961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"642320776","text":"import sys\nfrom scrapy.utils.project import get_project_settings\nfrom Hive.spiders.Bee import Bee\nfrom Hive.ConfigHandler import get_common\nfrom scrapy.crawler import CrawlerProcess\n\ndef run():\n print('程序启动!')\n BeeName=sys.argv[1]#获取命令行参数,爬虫名,也为配置文件名\n custom_settings=get_common(BeeName)\n #spider=custom_settings.get('spider','spiderbase')\n spider='Bee'\n project_settings=get_project_settings()\n settings=dict(project_settings.copy())\n #合并配置\n settings.update(custom_settings.get('settings'))\n process=CrawlerProcess(settings)\n process.crawl(spider,**{'BeeName':BeeName})\n process.start()\n\n\nif __name__=='__main__':\n run()\n","sub_path":"Hive_Server/Run.py","file_name":"Run.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"238078103","text":"# file_read_text1.py\n\n# 此示例示意以每次读取一行的形式读取文本文件内容\ntry:\n # 1. 打开文件\n # myf = open('myfile.txt') # 相对路径,相对code\n myf = open('/home/tarena/aid1809/pbase/day16/code/myfile.txt') # 绝对路径\n\n # 2. 读/写文件\n L = myf.readlines() # 把文件内容形成字符串列表返回回来\n print(L)\n # 3. 关闭文件\n myf.close()\nexcept OSError:\n print(\"文件打开失败\")\n\n\n","sub_path":"02-PythonBase/day17/day16_exercise/day16/code/file_read_text2.py","file_name":"file_read_text2.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"157779416","text":"from setuptools import setup\nimport sys\n\npython_min_version = (3, 6)\n\nif sys.version_info < python_min_version:\n sys.exit('pytransifex requires at least Python version {vmaj}.{vmin}.\\n'\n 'You are currently running this installation with\\n\\n{curver}'.format(\n vmaj=python_min_version[0],\n vmin=python_min_version[1],\n curver=sys.version))\n\nsetup(\n name = 'pytransifex',\n packages = [\n 'pytransifex'\n ],\n version = '0.1.7',\n description = 'Yet another Python Transifex API.',\n author = 'Denis Rouzaud',\n author_email = 'denis.rouzaud@gmail.com',\n url = 'https://github.com/opengisch/pytransifex',\n download_url = 'https://github.com/opengisch/pytransifex/archive/0.1.7.tar.gz', # I'll explain this in a second\n keywords = ['Transifex'],\n classifiers = [\n 'Topic :: Software Development :: Localization',\n 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',\n 'Intended Audience :: System Administrators',\n 'Development Status :: 3 - Alpha'\n ],\n install_requires = [\n 'requests'\n ],\n python_requires=\">={vmaj}.{vmin}\".format(vmaj=python_min_version[0], vmin=python_min_version[1]),\n)\n","sub_path":"pypi_install_script/pytransifex-0.1.7.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"94691641","text":"\"\"\"\n\nQuestion:\nDefine a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.\n\nHints:\nConsider use yield\n\n\"\"\"\n\n\ndef get_number_divisible(n):\n for i in range(n):\n if i % 7 == 0:\n yield i\n\n\nresult = get_number_divisible(30)\n\nfor item in result:\n print(item)\n","sub_path":"100+ Python challenging programming exercises/Level_3/Q20.py","file_name":"Q20.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"475113645","text":"# !/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\" @author zhangbohan.dell@gmail.com\n @create 2018-03-08 9:32\n @function 爬取新浪网国内新闻的爬虫\"\"\"\nfrom datetime import datetime\nimport re\nimport json\nimport requests\n\nfrom bs4 import BeautifulSoup\nimport pandas\nimport pymysql\nfrom sqlalchemy import create_engine\n\n\ndef get_content(web_url):\n \"\"\"\n :param web_url: 获取主要内容,编辑、日期时间、标题、正文\n :return: 一个存储有以上内容的字典\n \"\"\"\n result = {}\n res = requests.get(web_url, allow_redirects=False)\n res.encoding = 'utf-8'\n soup = BeautifulSoup(res.text, 'html.parser')\n if soup.select('title')[0].text.strip() != '页面没有找到':\n result['author'] = soup.select(\".show_author\")[0].text.strip(\"责任编辑:\")\n result['content'] = ' '.join([p.text.strip() for p in soup.select('#article p')[1:-2]])\n result['title'] = soup.select('.main-title')[0].text\n timesource = soup.select('.date')[0].text\n result['timesource'] = datetime.strptime(timesource, '%Y年%m月%d日 %H:%M')\n newsid = re.search(\"doc-i(.+).shtml\", web_url).group(1)\n comments_source_url = 'http://comment5.news.sina.com.cn/page/info?version=1' \\\n '&format=json&channel=gn&newsid=comos-{}&group=undefined&' \\\n 'compress=0&ie=utf-8&oe=utf-8&page=1&page_size=3&t_size=3&' \\\n 'h_size=3&thread=1'\n comments_source = requests.get(comments_source_url.format(newsid))\n jd_temp = json.loads(comments_source.text.strip(\"var data=\"))\n result['commentcount'] = jd_temp['result']['count']['total']\n return result\n\ndef get_new_tails(newtail):\n \"\"\"\n\n :param newtail: 从api中获取新网网址列表并调用getContent()函数获取新闻内容\n :return: 一个包含有爬取内容的列表\n \"\"\"\n news_total = []\n res = requests.get(newtail)\n # 将res中的除了json外多余的js代码移除掉\n jd_temp = json.loads(res.text.lstrip(' newsloadercallback(').rstrip(');'))\n for content in jd_temp['result']['data']:\n news_total.append(get_content(content['url']))\n return news_total\n\n\nif __name__ == '__main__':\n # grabMain()\n # mysqlconnect()\n # news_total = []\n CONN = pymysql.connect(host='localhost', user='root',\n password='gj5846gj', db='greb', charset='utf8')\n ENGINE = create_engine('mysql+pymysql://root:+gj5846gj@localhost:3306/greb?charset=utf8',\n encoding='utf-8')\n for new_url in range(1, 20):\n url = \"http://api.roll.news.sina.com.cn/zt_list?channel=news&cat_1=gnxw+&\" \\\n \"cat_2==gdxw1||=gatxw||=zs-pl||=mtjj&level==1||=2&show_ext=1&show_all=1+&\" \\\n \"show_num=22&tag=1&format=json&page={}&callback=newsloadercallback&_=1520686186491\"\n newsurl = url.format(new_url)\n news = get_new_tails(newsurl)\n for i in news:\n arr = []\n arr.append(i)\n df = pandas.DataFrame(arr)\n pandas.io.sql.to_sql(df, name='sina', con=ENGINE, if_exists='append', index=False)\n CONN.close()\n","sub_path":"hack/Greb/greb.py","file_name":"greb.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"469416828","text":"# -*- coding: utf-8 -*-\n\nimport datetime\nimport multiprocessing\nimport functools\nimport os\nimport pathlib\n\nimport pandas\nimport tqdm\n\nfrom acquisition import tx\nfrom config import config\nfrom selector import util\n\nimport acquisition.basic as basic\nimport acquisition.quote_db as quote_db\n\nimport selector.plugin.step as step\nimport selector.plugin.second_wave as second_wave\nimport selector.plugin.step_breakout as step_breakout\n\nimport selector.plugin.up as up\nimport selector.plugin.down as down\nimport selector.plugin.strong_variability as strong_variability\n\nfrom selector.plugin import market_deviation, super, bull_at_bottom, second_stage, hot_strong, magic_line, \\\n base_breakout, blt, vcp, strong_base, amplitude, signal_config, bottom, volume_dry_up, breakout, finance, fund, \\\n trend_weak\nfrom selector.plugin import value_return\nfrom selector.plugin import dynamical_system\nfrom selector.plugin import force_index\nfrom util import qt_util, dt\nfrom util import util as util_util\n\nfrom . import selected\n\n# 横盘 第二波 突破 涨 跌 大涨 大跌\nfrom util.log import logger\n\nselector = {\n 'finance': finance.finance,\n 'finance_ex': finance.finance_ex,\n 'fund': fund.fund,\n 'trend_up': signal_config.mask_config,\n 'trend_weak': trend_weak.trend_weak,\n 'signal_config': signal_config.signal_config,\n 'step': step.step,\n 'step_p': step.step_p,\n '2nd': second_wave.second_wave,\n '2nd2': second_wave.second_wave2,\n 'qd': strong_variability.strong_variability,\n 'up': up.up,\n 'up_p': up.up_p,\n 'down': down.down,\n 'down_p': down.down_p,\n 'amplitude': amplitude.amplitude,\n 'bull_deviation': market_deviation.market_deviation, # 牛市背离\n 'value_return': value_return.value_return, # 价值回归\n 'value_return_ing': value_return.value_return_ing,\n 'super': super.super,\n 'second_stage': second_stage.second_stage, # 第二阶段\n 'magic_line': magic_line.magic_line,\n 'step_breakout': step_breakout.step_breakout,\n 'blt_breakout': breakout.blt_breakout,\n 'vcp_breakout': breakout.vcp_breakout,\n 'magic_line_breakout': breakout.magic_line_breakout,\n 'base_breakout': base_breakout.base_breakout,\n 'blt': blt.blt,\n 'vcp': vcp.vcp,\n 'strong_base': strong_base.strong_base,\n 'volume_dry_up': volume_dry_up.volume_dry_up,\n 'volume_shrink': volume_dry_up.volume_shrink,\n 'volume_dry_up_ing': volume_dry_up.volume_dry_up_ing,\n 'bottom': bottom.bottom,\n 'fallen': bottom.fallen,\n 'bull_at_bottom': bull_at_bottom.bull_at_bottom,\n 'dyn_sys_green': dynamical_system.dynamical_system_green,\n 'dyn_sys_red': dynamical_system.dynamical_system_red,\n 'dyn_sys_blue': dynamical_system.dynamical_system_blue,\n 'hot_strong': hot_strong.hot_strong,\n 'force_index_p': force_index.force_index_positive,\n 'force_index_m': force_index.force_index_minus\n}\n\n\ndef get_strategy_status(strategy):\n for status, strategy_info in config.strategy_map.items():\n if strategy in strategy_info['strategies']:\n return status\n raise Exception('{} is UNKNOWN'.format(strategy))\n\n\ndef get_status_backdays(status):\n strategy_info = config.strategy_map[status]\n return strategy_info['back_day']\n\n\ndef is_match(df, strategy_name, period):\n if util.filter_quote(df):\n return False\n\n status = get_strategy_status(strategy_name)\n backdays = get_status_backdays(status)\n rc = selector.get(strategy_name)(df, period, backdays)\n if rc:\n return True\n\n return False\n\n\ndef dump(data, file):\n # file = gen_cache_path(data.code[-1], datetime.date.today(), period)\n if os.path.exists(file):\n os.remove(file)\n\n if 'date' not in data.columns:\n data.insert(len(data.columns), 'date', data.index)\n\n data.to_csv(file)\n\n\ndef load(file):\n # file = gen_cache_path(code, datetime.date.today(), period)\n data = pandas.read_csv(file, dtype={'code': str})\n\n data['date'] = pandas.to_datetime(data['date'], format='%Y-%m-%d %H:%M:%S')\n # data['code'] = str(data['code'])\n # 将日期列作为行索引\n data.set_index(['date'], inplace=True)\n # data.sort_index(ascending=True, inplace=True)\n\n return data\n\n\ndef _select(strategy_name, period, code_day_quote):\n import util.mysqlcli as mysqlcli\n # _conn = mysqlcli.get_connection()\n\n code, day_quote = code_day_quote\n df = quote_db.get_price_info_df_db(code, days=1000, period_type='D')\n if df.empty:\n logger.info(code, 'no quote')\n return\n\n # 无法频繁获取数据\n if day_quote is not None:\n df = df.append(day_quote)\n\n ret = None\n if is_match(df, strategy_name, period):\n # print('{}'.format(code))\n ret = code\n\n # _conn.close()\n\n return ret\n\n\ndef select_one_strategy(code_list, strategy_name, period, options):\n \"\"\"\n https://docs.python.org/3/library/multiprocessing.html\n This means that if you try joining that process you may get a deadlock\n unless you are sure that all items which have been put on the queue have been consumed.\n Similarly, if the child process is non-daemonic then the parent process may hang on exit\n when it tries to join all its non-daemonic children.\n\n Note that a queue created using a manager does not have this issue.\n \"\"\"\n\n logger.info('[{}] to check [{}]...'.format(len(code_list), strategy_name))\n\n day_quote = None\n\n mp = options['selector_mp']\n use_rt_quote = options['selector_rt_quote']\n if use_rt_quote and dt.istradetime():\n cache_dir = util_util.get_cache_dir()\n cache = os.path.join(cache_dir, 'day_quote_{}.csv'.format(datetime.datetime.now().strftime('%Y%m%d')))\n has_cache = False\n if os.path.exists(cache):\n fname = pathlib.Path(cache)\n if (datetime.datetime.now() - datetime.datetime.fromtimestamp(fname.stat().st_mtime)).seconds > 5 * 60:\n os.remove(cache)\n else:\n has_cache = True\n\n if has_cache:\n day_quote = load(cache)\n else:\n day_quote = tx.get_today_all()\n dump(day_quote, cache)\n\n df_ = quote_db.get_price_info_df_db('000001', days=1, period_type='D')\n for column in day_quote.columns:\n if column not in df_.columns:\n day_quote = day_quote.drop([column], axis=1)\n\n select_func = functools.partial(_select, strategy_name, period)\n\n r = []\n if not mp:\n for code in code_list:\n if not select_func((code, None if day_quote is None else day_quote.loc[day_quote.code == code])):\n continue\n r.append(code)\n return r\n\n nproc = multiprocessing.cpu_count()\n with multiprocessing.Pool(nproc) as p:\n # r = p.map(select_func, [code for code in code_list])\n # code_list = [code for code in r if code]\n\n # for i, _ in enumerate(p.imap_unordered(select_func, [code for code in code_list]), 1):\n # r.append(_)\n # if i % 100 == 0:\n # sys.stderr.write('\\rdone {0:%}'.format(i/len(code_list)))\n arg = [(code, None if day_quote is None else day_quote.loc[day_quote.code == code]) for code in code_list]\n for _ in tqdm.tqdm(p.imap_unordered(select_func, arg),\n total=len(code_list), ncols=64):\n r.append(_)\n\n code_list = [code for code in r if code]\n\n logger.info('{}: {}'.format(strategy_name, len(code_list)))\n\n return code_list\n\n\ndef update_candidate_pool(strategy_list, period='day'):\n t1 = datetime.datetime.now()\n msg = ''\n options = config.get_config_options()\n for strategy in strategy_list:\n code_list = basic.get_all_stock_code()\n # code_list = ['600331']\n code_list = select_one_strategy(code_list, strategy, period, options)\n # 科创板\n # code_list = [code for code in code_list if not code.startswith('688')]\n msg += '{}: {}\\n'.format(strategy, len(code_list))\n basic.upsert_candidate_pool(code_list, 'candidate', strategy, ignore_duplicate=False)\n\n t2 = datetime.datetime.now()\n cost = (t2 - t1).seconds\n qt_util.popup_info_message_box_mp('update candidate finished in [{}s]\\n{}'.format(cost, msg))\n\n\ndef select(strategy_name_list, candidate_list=None, traced_list=None, period='day'):\n begin = datetime.datetime.now()\n\n code_list = []\n if candidate_list:\n if config.update_candidate_pool:\n update_candidate_pool(candidate_list)\n code_list = basic.get_candidate_stock_code(candidate_list)\n\n if traced_list:\n code_list.extend(basic.get_traced_stock_code(traced_list))\n\n if not code_list:\n code_list = basic.get_all_stock_code()\n # code_list = future.get_future_contract_list()\n # 科创板\n # code_list = [code for code in code_list if int(code[:2]) <= 60]\n # code_list = ['000408']\n\n options = config.get_config_options()\n strategy_name_list = config.get_scan_strategy_name_list() if not strategy_name_list else strategy_name_list\n for strategy_name in strategy_name_list:\n code_list = select_one_strategy(code_list, strategy_name, period, options)\n # for code in code_list:\n # selected.add_selected(code, strategy_name)\n # code_list = ['002109']\n status = 'traced' if strategy_name in config.traced_strategy_list else 'allow_buy'\n basic.upsert_candidate_pool(code_list, status, strategy_name, ignore_duplicate=False)\n logger.info(strategy_name, code_list)\n\n # code_list.append('300502')\n code_list.sort()\n\n stock_list = []\n for code in code_list:\n stock_list.append((code, basic.get_stock_name(code)))\n\n end = datetime.datetime.now()\n cost = (end - begin).seconds\n\n log = '\\n'.join([' '.join(t) for t in stock_list])\n with open(config.scan_log_path, 'a') as f:\n f.writelines('[{}] cost [{}s] [{}][{}] [{}]'.format(\n begin, cost, ', '.join(candidate_list), ', '.join(strategy_name_list), len(stock_list)))\n f.writelines('\\n')\n f.writelines(log)\n f.writelines('\\n\\n')\n\n qt_util.popup_info_message_box_mp('scan finished in [{}s]\\ntotal: {}'.format(cost, len(stock_list)))\n","sub_path":"selector/selector.py","file_name":"selector.py","file_ext":"py","file_size_in_byte":10213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"572655207","text":"import select\nimport socket\nimport sys\nimport Queue\n\n# Create a TCP/IP socket\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.setblocking(0)\n\n# Bind the socket to the port\nserver_address = ('localhost', 10000)\nprint >>sys.stderr, 'starting up on %s port %s' % server_address\nserver.bind(server_address)\n\n# Listen for incoming connections\nserver.listen(5)\n\n# Keep up with the queues of outgoing messages\nmessage_queues = {}\n\n\n# The timeout value passed to poll() is represented in milliseconds,\nTIMEOUT = 1000\n\n\"\"\"\nPOLLIN Input ready\nPOLLPRI Priority input ready\nPOLLOUT Able to receive output\nPOLLERR Error\nPOLLHUP Channel closed\nPOLLNVAL Channel not open\n\"\"\"\nREAD_ONLY = select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR\nREAD_WRITE = READ_ONLY | select.POLLOUT\n\n# Set up the poller\npoller = select.poll()\npoller.register(server, READ_ONLY)\n\n# Since poll() returns a list of tuples containing the file descriptor for the socket and the event flag, a mapping from file descriptor numbers to objects is needed to retrieve the socket to read or write from it\n\n# Map file descriptors to socket objects\nfd_to_socket = { server.fileno(): server}\n\n\nwhile True:\n\n # Wait for at least one of the sockets to be ready for processing\n print >>sys.stderr, '\\nwaiting for the next event'\n events = poller.poll(TIMEOUT)\n\n # The server’s loop calls poll(), then processes the “events” returned by looking up the socket and taking action based on the flag in the event.\n for fd, flag in events:\n\n # Retrieve the actual socket from its file descriptor\n s = fd_to_socket[fd]\n\n if flag & (select.POLLIN | select.POLLPRI):\n\n if s is server:\n # A \"readable\" server socket is ready to accept a connection\n connection, client_address = s.accept()\n print >>sys.stderr, 'new connection from', client_address\n connection.setblocking(0)\n fd_to_socket[ connection.fileno() ] = connection\n poller.register(connection, READ_ONLY)\n\n # Give the connection a queue for data we want to send\n message_queues[connection] = Queue.Queue()\n else:\n data = s.recv(1024)\n if data:\n # A readable client socket has data\n print >>sys.stderr, 'received \"%s\" from %s' % (data, s.getpeername())\n message_queues[s].put(data)\n # Add output channel for response\n poller.modify(s, READ_WRITE)\n else:\n # Interpret empty result as closed connection\n print >>sys.stderr, 'closing', client_address, 'after reading no data'\n # Stop listening for input on the connection\n poller.unregister(s)\n s.close()\n\n # Remove message queue\n del message_queues[s]\n elif flag & select.POLLHUP:\n # Client hung up\n print >>sys.stderr, 'closing', client_address, 'after receiving HUP'\n # Stop listening for input on the connection\n poller.unregister(s)\n s.close()\n elif flag & select.POLLOUT:\n # Socket is ready to send data, if there is any to send.\n # The handling for writable sockets looks like the version used in the example for select(), except that modify() is used to change the flags for the socket in the poller, instead of removing it from the output list.\n try:\n next_msg = message_queues[s].get_nowait()\n except Queue.Empty:\n # No messages waiting so stop checking for writability.\n print >>sys.stderr, 'output queue for', s.getpeername(), 'is empty'\n poller.modify(s, READ_ONLY)\n else:\n print >>sys.stderr, 'sending \"%s\" to %s' % (next_msg, s.getpeername())\n s.send(next_msg)\n elif flag & select.POLLERR:\n print >>sys.stderr, 'handling exceptional condition for', s.getpeername()\n # Stop listening for input on the connection\n poller.unregister(s)\n s.close()\n\n # Remove message queue\n del message_queues[s]\n","sub_path":"python-network-cookbook/ch02/poll_server_mode.py","file_name":"poll_server_mode.py","file_ext":"py","file_size_in_byte":4328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"38526842","text":"from django.conf.urls import url \nfrom . import views\n \nurlpatterns = [ \n url(r'^api/create-user', views.create_user),\n url(r'^api/login-user', views.login_user),\n url(r'^api/payment-intent', views.payment_intent),\n url(r'^api/airports-list', views.airports_list),\n url(r'^api/availability-list', views.get_availability),\n url(r'^api/calc-price', views.calc_price),\n url(r'^api/payment-done', views.payment_done),\n url(r'^api/get-upcoming-bookings', views.get_upcoming_bookings),\n url(r'^api/get-past-bookings', views.get_past_bookings),\n url(r'^api/cancel-booking', views.cancel_booking)\n]","sub_path":"airpark/airpark_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"299038414","text":"# encoding: utf-8\n\nfrom sqlite_wrapper import SQLiteWrapper\n\n\nclass Querier(object):\n def __init__(self, path='lianjia-xq.db'):\n self.table = 'ershou_latest'\n self.db = SQLiteWrapper(path)\n\n def get_ershou_by_xiaoqu(self, xiaoqu):\n sql = u'select * from {} where xiaoqu = \"{}\"'.format(self.table, xiaoqu)\n res = self.db.fetchall(sql)\n if len(res) > 0:\n return res\n else:\n sql = u'select * from {} where xiaoqu like \"%{}%\"'.format(self.table, xiaoqu)\n return self.db.fetchall(sql)\n\n\nif __name__ == '__main__':\n q = Querier()\n","sub_path":"spider/info_query.py","file_name":"info_query.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"47863261","text":"#!/usr/bin/env python\r\n# coding: utf-8\r\n\r\n# In[1]:\r\nimport hashlib\r\n\r\n\r\n# In[2]:\r\n\r\n\r\nclass CatCoinBlock:\r\n \r\n def __init__(self, previous_block_hash, transaction_list):\r\n self.previous_block_hash = previous_block_hash\r\n self.transaction_list = transaction_list\r\n \r\n self.block_data = \" - \".join(transaction_list) + \" - \" + previous_block_hash\r\n self.block_hash = hashlib.sha256(self.block_data.encode()).hexdigest()\r\n \r\nt1 = \"Milan sends 20 CC to Hwieun\" \r\nt2 = \"Milan sends 2.1 CC to Yuta\" \r\nt3 = \"Yuta sends 13 CC to Hwieun\"\r\nt4 = \"Yuta sends 8 CC to Milan\"\r\nt5 = \"Hwieun sends 9 CC to Milan\"\r\nt6 = \"Hwieun sends 22 CC to Yuta\" \r\n\r\nt_list = [[t1, t2], [t3, t4], [t5, t6]]\r\n\r\n#contains a list of instances\r\nblocks = [] \r\n\r\n#creating genesis block\r\nblocks.append(CatCoinBlock(\"Initial String\", t_list[0]))\r\n\r\n\r\n#creating rest of the block\r\nfor i in range(1, 3):\r\n blocks.append(CatCoinBlock(blocks[i-1].block_hash, t_list[i]))\r\n\r\n\r\n# In[3]:\r\n\r\n\r\nfor i in range(0, 3):\r\n print(blocks[i].block_data)\r\n print(blocks[i].block_hash) \r\n print(\"\\n\")\r\n\r\n\r\n# In[4]:\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Untitled.py","file_name":"Untitled.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"285200431","text":"import os\nfrom reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer \nfrom reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle \nfrom reportlab.lib.enums import TA_CENTER,TA_JUSTIFY \nfrom reportlab.lib.fonts import addMapping\nfrom reportlab.lib.pagesizes import letter, A4\nfrom reportlab.pdfgen import canvas\n\nfrom src.format_parser import OCROutputParser\nfrom src.utils.helpers import Helpers\nfrom fonts.font_utils import FontUtils\n\nclass OCRDocumentGenerator(object):\n def __init__(self, input_filepath):\n self.input_filepath = input_filepath\n self.ocrOutputParser = OCROutputParser(input_filepath)\n\n def get_page_dimensions(self, page):\n _, _, w, h = Helpers.vertices_to_boundingbox(page['page_info']['page_boundingBox']['vertices'])\n return w, h\n\n def draw_line_text(self, page_canvas, x, y, text, word_space=1.75, horizontal_scale=105, font_name=None, font_size=8):\n txtobj = page_canvas.beginText()\n txtobj.setTextOrigin(x, y)\n txtobj.setWordSpace(word_space)\n txtobj.setHorizScale(horizontal_scale)\n txtobj.setFont(font_name, font_size)\n txtobj.textLine(text=text)\n page_canvas.drawText(txtobj)\n \n def create_pdf(self, pages, pdf_filepath, font_name, font_size=40, scale_factor=4):\n '''\n using first page w & h as canvas\n '''\n w, h = self.get_page_dimensions(pages[0])\n pagesize = (w/scale_factor, h/scale_factor)\n c = canvas.Canvas(pdf_filepath, pagesize=pagesize)\n for page in pages:\n paragraphs, lines = self.ocrOutputParser.get_page_paragraphs_lines(page)\n \n for line in lines:\n boundingBox, text = line['boundingBox'], line['text']\n x, y, _, _ = boundingBox\n y = h - y\n self.draw_line_text(c, x/scale_factor, y/scale_factor, text, 1.75, 105, font_name, font_size/scale_factor)\n c.showPage()\n c.save()\n\n def generate(self, output_filepath):\n font_name = 'arial-unicode-ms'\n FontUtils.load_font(font_name)\n\n pages = self.ocrOutputParser.get_document_pages()\n self.create_pdf(pages, output_filepath, font_name, 34, 4)\n print('created {} pages PDF at {}'.format(len(pages), output_filepath))","sub_path":"docservice/src/document_generator/ocr_doc_generator.py","file_name":"ocr_doc_generator.py","file_ext":"py","file_size_in_byte":2421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"418717883","text":"\r\n#使用PIL来对图像进行添加水印\r\nfrom PIL import Image,ImageDraw,ImageFont\r\nimg=Image.open('./me.jpg').convert(\"RGBA\")#将rgb格式转换为RGBA格式\r\n\r\nimg1=img.size[0]*img.size[1]\r\nprint('img1 ',img1)#得到一个图片大小的整数值\r\nprint('szie[0]',img.size[0])\r\nprint('size[1]',img.size[1])\r\n\r\n#获取字体 并设置大小\r\nnum_size=int(img1/20000)#设置水印的的英文大小为整张图片面积的2000分之一\r\nmyfont=ImageFont.truetype('cambria.ttc',num_size)#设置英文字符的字体\r\nmyfont1=ImageFont.truetype('STKAITI.TTF',80)#设置中文的字体及大小\r\n\r\ndraw=ImageDraw.Draw(img)#创建一个可以用ImageDraw操作的图像\r\ndraw.text((100,6),'EugeneLi',(255,255,255),font=myfont)\r\ndraw.text((100,100),u\"乖巧的剑\",(255,228,225),myfont1)#中文前面加u\r\n\r\n#参数依次是[a,b](以a、b两点作为矩阵的左上角和右下角,在中间画圆),颜色\r\ndraw.ellipse([(img.size[0]-55, 10), (img.size[0], 80)], fill=(255, 0, 0))\r\ndraw.text((img.size[0]-40, -5), '1', font=myfont1, fill=(255, 255, 255, 128))#圆中添加数字\r\n\r\nimg.show()\r\n\r\n\r\n","sub_path":"addFlag.py","file_name":"addFlag.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"576069512","text":"# -*- coding: utf-8 -*-\n\"\"\"Advent of Code 2015 - Day 8: Matchsticks.\"\"\"\n\n\ndef mlen(string):\n start = 1\n end = len(string) - 1\n result = 0\n pos = start\n while pos < end:\n if string[pos] != \"\\\\\":\n pos += 1\n result += 1\n elif string[pos + 1] in [\"\\\\\", '\"']:\n pos += 2\n result += 1\n else:\n pos += 4\n result += 1\n return result\n\n\ndef elen(string):\n result = 2\n for ch in string:\n if ch not in [\"\\\\\", '\"']:\n result += 1\n else:\n result += 2\n return result\n\n\ndef load_and_parse_input(input_file: str):\n puzzle = []\n with open(input_file) as inf:\n for line in inf.readlines():\n puzzle.append(line.strip())\n return puzzle\n\n\ndef part_1(puzzle):\n totals = list(map(len, puzzle))\n mtotals = list(map(mlen, puzzle))\n return sum(totals) - sum(mtotals)\n\n\ndef part_2(puzzle):\n totals = list(map(len, puzzle))\n etotals = list(map(elen, puzzle))\n return sum(etotals) - sum(totals)\n\n\ndef solve(puzzle):\n return (part_1(puzzle), part_2(puzzle))\n\n\nif __name__ == \"__main__\":\n puzzle = load_and_parse_input(\"2015/inputs/08.txt\")\n solution = solve(puzzle)\n print(solution)\n\n expected = (1371, 2117)\n assert expected == solution, f\"expected: {expected} actual: {solution}\"\n","sub_path":"2015/day-08.py","file_name":"day-08.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"315745081","text":"import telebot\nimport json\nfrom pprint import pprint\nimport time\nfrom pyvirtualdisplay import Display\nimport sys\nfrom scrapper import Scrapper\nfrom configuration import Configuration\n\ndef format_result(res):\n out = \"\"\n for obj in res:\n out += \"*\" + obj[\"subject\"] + \"*\" + \"\\n\"\n for notice in obj[\"notices\"]:\n out += \"*-* \" + notice + \"\\n\"\n out += \"\\n\"\n \n return \"0 notices from 0 subjects\" if out == \"\" else out\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1 and sys.argv[1] == \"--vdisplay\":\n display = Display(visible=0, size=(50, 50))\n display.start()\n\n scrapper = Scrapper()\n config = Configuration.read_configuration()\n token = config[\"botToken\"]\n bot = telebot.TeleBot(token)\n running = False\n firstTime = True\n last = []\n last_update = \"Never\"\n\n @bot.message_handler(commands=['Start'])\n def send_welcome(message):\n global running, last, firstTime, last_update\n\n if not running:\n bot.reply_to(message, \"Let's get started!\")\n \n running = True\n while(running):\n result = scrapper.getResult()\n\n if(result != last):\n last_update = time.strftime('%Y-%m-%d %H:%M:%S')\n last = result\n if not firstTime: bot.reply_to(message, \"New notices!\")\n \n if firstTime: firstTime = False\n\n time.sleep(config[\"timer\"] * 60)\n\n @bot.message_handler(commands=['Stop'])\n def send_finish(message):\n global running\n running = False;\n bot.reply_to(message, \"Program has stopped\")\n\n @bot.message_handler(commands=['Show'])\n def send_finish(message):\n global last\n last_formated = format_result(last)\n bot.send_message(message.chat.id, last_formated, parse_mode= \"MARKDOWN\")\n\n @bot.message_handler(commands=['Info'])\n def send_finish(message):\n global last_update\n out = \"*Last update*: \" + str(last_update)\n bot.send_message(message.chat.id, out, parse_mode= \"MARKDOWN\")\n\n @bot.message_handler(commands=['Commands'])\n def send_finish(message):\n out = \"*/Start*: Start program \\n\"\n out += \"*/Stop*: Stop program \\n\"\n out += \"*/Show*: Show all subjects with their notices \\n\" \n out += \"*/Info*: Get program info such as last update time \\n\"\n out += \"*/Commands*: Get commands and their description \\n\" \n bot.send_message(message.chat.id, out, parse_mode= \"MARKDOWN\")\n\n @bot.message_handler(func=lambda m:True)\n def echo_all(message):\n bot.reply_to(message, message.text)\n\n \n while True:\n try:\n bot.polling(none_stop=True)\n except Exception as e:\n time.sleep(15)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"584835545","text":"from django.conf.urls import url\n\nfrom .api import basic, friend, info\nfrom .api import ERROR\n\n\n\nurlpatterns = [\n url(r'^signup$', basic.sign_up, name='signup'),\n url(r'^login$', basic.login, name='login'),\n url(r'^reset$', basic.reset, name='reset'),\n url(r'^logout$', basic.logout, name='logout'),\n # Friendship related below\n url(r'^addreq$', friend.add_req, name='add_req'),\n url(r'^getreq$', friend.get_req, name='get_req'),\n url(r'^resreq$', friend.res_req, name='res_req'),\n url(r'^frdlist$', friend.frd_list, name='frd_list'),\n # info\n url(r'^getavatar$', info.get_avatar, name='get_avatar'),\n\n # Not visible to client below\n url(r'^error_login_required$', ERROR.error_login_required, name='error_login_required'),\n\n]\n","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"465964226","text":"# -*- coding: UTF-8 -*-\nfrom db_module.connect_db import *\nfrom db_module.code_db import *\nfrom battle_module.battle_dao import BattleDao\nfrom battle_module.package_dao import PackageDao\nfrom battle_module.equipment_db import EquipmentDB\nimport math,random\n\nclass BossService:\n def __init__(self):\n self.result=\"\"\n\n def initBoss(self):\n dao = BattleDao()\n boss = dao.selectActiveBoss()\n if(boss==None):\n return \"boss不存在\"\n DBHelper().delete(\"delete from dps\")\n boss.hp = boss.maxhp\n dao.updateBattleInfo(boss)\n return \"world boss init success \"\n\n def handleAfterChallange(self,process,a,boss):\n self.insertDps(process,a,boss)\n if(boss.hp<=0):\n self.bootySend(boss)\n return self.result\n\n def insertDps(self,process,a,boss):\n DBHelper().insert(\"insert dps(damage,userId,bossId) VALUES(\"+str(process.aDamage)+\",\"+str(a.userId)+\",\"+str(boss.userId)+\")\")\n\n def bootySend(self,boss):\n tupleList = DBHelper().selectAll(\"SELECT userId,sum(damage) as damage from dps where bossId=\"+str(boss.userId)+\" GROUP BY userId ORDER BY damage desc\")\n one = []\n two = []\n three = []\n size = len(tupleList)\n for i in range(size):\n if(i<(size/3)):\n one.append(tupleList[i][0])\n elif(i<(size/3*2)):\n two.append(tupleList[i][0])\n else:\n three.append(tupleList[i][0])\n self.handleExpMoney(one,3)\n self.handleExpMoney(two,2)\n self.handleExpMoney(three,1)\n self.result+=\"\\n\"\n self.bootyPackage(tupleList,boss.userId)\n\n def bootyPackage(self,tupleList,bossId):\n dao = PackageDao()\n bootys = dao.select(bossId)\n for b in bootys:\n temp = {}\n for record in tupleList:\n temp[record[0]] = random.randint(0,100)\n rd = {\"ID\":\"\",\"NUM\":0}\n for record in tupleList:\n if (rd['NUM'] < temp[record[0]]):\n rd['ID'] = record[0]\n rd['NUM'] = temp[record[0]]\n self.result += str(BattleDao().selectUserByUserId(rd[\"ID\"]).name)+\" 获得了\"+str(EquipmentDB.EDB[b[2]].name)+\"\\n\"\n dao.insert(rd[\"ID\"],b[2])\n return self.result\n\n def handleExpMoney(self,list,level):\n dao = BattleDao()\n baseExp = 50\n baseMoney =150\n for record in list:\n pa = dao.selectUserByUserId(record)\n aexp = math.floor((baseExp*level)*round(1+random.uniform(-0.1,0.2),2))\n money = math.floor((baseMoney*level)*round(1+random.uniform(-0.1,0.2),2))\n pa.exp += aexp\n self.result += pa.name + \" 获得\"+str(aexp)+\"点经验 获得\"+str(money)+\"大给币\\n\"\n if(pa.exp/100 > pa.level):\n pa.level+=1\n pa.maxhp += 100\n pa.hp += 200\n dao.updateBattleInfo(pa)\n dao.updateCoin(money,pa.userId)\n","sub_path":"battle_module/boss.py","file_name":"boss.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"468663099","text":"load(\"@bazel_skylib//lib:collections.bzl\", \"collections\")\nload(\"@bazel_skylib//lib:paths.bzl\", \"paths\")\nload(\"@fbcode_macros//build_defs/lib:build_mode.bzl\", _build_mode = \"build_mode\")\nload(\"@fbcode_macros//build_defs/lib:cpp_common.bzl\", \"cpp_common\")\nload(\"@fbcode_macros//build_defs/lib:haskell_common.bzl\", \"haskell_common\")\nload(\"@fbcode_macros//build_defs/lib:src_and_dep_helpers.bzl\", \"src_and_dep_helpers\")\nload(\"@fbcode_macros//build_defs/lib:target_utils.bzl\", \"target_utils\")\nload(\"@fbcode_macros//build_defs/lib:third_party.bzl\", \"third_party\")\nload(\"@fbcode_macros//build_defs/lib:visibility.bzl\", \"get_visibility\")\nload(\"@fbcode_macros//build_defs:config.bzl\", \"config\")\nload(\"@fbcode_macros//build_defs:custom_rule.bzl\", \"get_project_root_from_gen_dir\")\nload(\"@fbcode_macros//build_defs:platform_utils.bzl\", \"platform_utils\")\nload(\"@fbsource//tools/build_defs:fb_native_wrapper.bzl\", \"fb_native\")\n\n_HAPPY = target_utils.ThirdPartyToolRuleTarget(\"hs-happy\", \"happy\")\n\ndef _happy_rule(name, platform, happy_src, visibility):\n \"\"\"\n Create rules to generate a Haskell source from the given happy file.\n \"\"\"\n happy_name = name + \"-\" + happy_src\n\n fb_native.genrule(\n name = happy_name,\n visibility = get_visibility(visibility, happy_name),\n out = paths.split_extension(happy_src)[0] + \".hs\",\n srcs = [happy_src],\n cmd = \" && \".join([\n 'mkdir -p `dirname \"$OUT\"`',\n '$(exe {happy}) -o \"$OUT\" -ag \"$SRCS\"'.format(\n happy = target_utils.target_to_label(_HAPPY, fbcode_platform = platform),\n ),\n ]),\n )\n\n return \":\" + happy_name\n\n_ALEX = target_utils.ThirdPartyToolRuleTarget(\"hs-alex\", \"alex\")\n\ndef _alex_rule(name, platform, alex_src, visibility):\n \"\"\"\n Create rules to generate a Haskell source from the given alex file.\n \"\"\"\n alex_name = name + \"-\" + alex_src\n\n fb_native.genrule(\n name = alex_name,\n visibility = get_visibility(visibility, alex_name),\n out = paths.split_extension(alex_src)[0] + \".hs\",\n srcs = [alex_src],\n cmd = \" && \".join([\n 'mkdir -p `dirname \"$OUT\"`',\n '$(exe {alex}) -o \"$OUT\" -g \"$SRCS\"'.format(\n alex = target_utils.target_to_label(_ALEX, fbcode_platform = platform),\n ),\n ]),\n )\n\n return \":\" + alex_name\n\ndef _dep_rule(base_path, name, deps, visibility):\n \"\"\"\n Sets up a dummy rule with the given dep objects formatted and installed\n using `deps` and `platform_deps` to support multi-platform builds.\n\n This is useful to package a given dep list, which requires multi-\n platform dep parameter support, into a single target that can be used\n in interfaces that don't have this support (e.g. macros in `genrule`s\n and `cxx_genrule`).\n \"\"\"\n\n # Setup platform default for compilation DB, and direct building.\n buck_platform = platform_utils.get_buck_platform_for_base_path(base_path)\n lib_deps, lib_platform_deps = src_and_dep_helpers.format_all_deps(deps)\n\n fb_native.cxx_library(\n name = name,\n visibility = get_visibility(visibility, name),\n preferred_linkage = \"static\",\n deps = lib_deps,\n platform_deps = lib_platform_deps,\n default_platform = buck_platform,\n defaults = {\"platform\": buck_platform},\n )\n\nC2HS = target_utils.ThirdPartyRuleTarget(\"stackage-lts\", \"bin/c2hs\")\n\nC2HS_TEMPL = '''\\\nset -e\nmkdir -p `dirname \"$OUT\"`\n\n# The C/C++ toolchain currently expects we're running from the root of fbcode.\ncd {fbcode}\n\n# The `c2hs` tool.\nargs=($(location {c2hs}))\n\n# Add in the C/C++ preprocessor.\nargs+=(\"--cpp=\"$(cc))\n\n# Add in C/C++ preprocessor flags.\ncppflags=(-E)\ncppflags+=($(cppflags{deps}))\nfor cppflag in \"${{cppflags[@]}}\"; do\n args+=(\"--cppopts=$cppflag\")\ndone\n\n# The output file and input source.\nargs+=(\"-o\" \"$OUT\")\nargs+=(\"$SRCS\")\n\nexec \"${{args[@]}}\"\n'''\n\ndef _c2hs(base_path, name, platform, source, deps, visibility):\n \"\"\"\n Construct the rules to generate a haskell source from the given `c2hs`\n source.\n \"\"\"\n\n # Macros in the `cxx_genrule` below don't support the `platform_deps`\n # parameter that we rely on to support multi-platform builds. So use\n # a helper rule for this, and just depend on the helper.\n deps_name = name + \"-\" + source + \"-deps\"\n d = cpp_common.get_binary_link_deps(base_path, deps_name)\n _dep_rule(base_path, deps_name, deps + d, visibility)\n source_name = name + \"-\" + source\n fb_native.cxx_genrule(\n name = source_name,\n visibility = get_visibility(visibility, source_name),\n cmd = (\n C2HS_TEMPL.format(\n fbcode = (\n paths.join(\n \"$GEN_DIR\",\n get_project_root_from_gen_dir(),\n )\n ),\n c2hs = target_utils.target_to_label(C2HS, fbcode_platform = platform),\n deps = \" :\" + deps_name,\n )\n ),\n srcs = [source],\n out = paths.split_extension(source)[0] + \".hs\",\n )\n\n return \":\" + source_name\n\nHSC2HS_TEMPL = '''\\\nset -e\nmkdir -p `dirname \"$OUT\"`\n\n# The C/C++ toolchain currently expects we're running from the root of fbcode.\ncd {fbcode}\n\n# The `hsc2hs` tool.\nargs=({ghc_tool}/bin/hsc2hs)\n\n# Keep hsc2hs's internal files around, since this is useful for debugging and\n# doesn't hurt us.\nargs+=(\"--keep-files\")\n\nargs+=(\"--template=template-hsc.h\")\n\n# Always define __HSC2HS__ in the C program and the compiled Haskell file, and\n# the C header.\nargs+=(\"--define=__HSC2HS__\")\n\n# We need to pass \"-x c++\" to the compiler that hsc2hs invokes, but *before*\n# any file paths; hsc2hs passes flags *after* paths. The easy and morally\n# tolerable workaround is to generate a shell script that partially applies\n# the flag.\nCC_WRAP=\"$OUT\".cc_wrap.sh\necho > \"$CC_WRAP\" '#!/bin/sh'\n\n# TODO: T23700463 Turn distcc back on\necho >> \"$CC_WRAP\" 'BUCK_DISTCC=0 $(cxx) -x c++ \"$@\"'\nchmod +x \"$CC_WRAP\"\n# Set 'CXX' locally to the real compiler being invoked, so that hsc2hs plugins\n# needing to invoke the compiler can do so correctly.\nexport CXX=\"$CC_WRAP\"\nargs+=(\"--cc=$CC_WRAP\")\n\n# Pass in the C/C++ compiler and preprocessor flags.\ncflags=()\ncflags+=(\"-fpermissive\")\ncflags+=($(cxxflags))\ncflags+=($(cxxppflags{deps}))\nltoflag=\"\"\n# Needed for `template-hsc.h`.\ncflags+=(-I{ghc}/lib)\nfor cflag in \"${{cflags[@]}}\"; do\n if [[ \"$cflag\" == \"-flto\" || \"$cflag\" =~ \"-flto=\" ]]; then\n ltoflag=\"$cflag\"\n fi\n args+=(--cflag=\"$cflag\")\ndone\n\n# Add in the C/C++ linker.\nargs+=(\"--ld=$(ld)\")\n\n# Add in the linker flags.\nldflags=($(ldflags-{link_style}{deps}))\nif [ ! -z \"$ltoflag\" ]; then\n ldflags+=(\"$ltoflag\")\nfi\nldflags+=(\"-o\" \"`dirname $OUT`/{out_obj}\")\nfor ldflag in \"${{ldflags[@]}}\"; do\n args+=(--lflag=\"$ldflag\")\ndone\n\n# Link the \"run once\" hsc2hs binary stripped. This makes some hsc files\n# go from 20s to 10s and the \"run once\" binary from 800M to 40M when\n# statically linked. Situations where one would want to debug them are\n# very rare.\n# This doesn't make a difference when dynamically linked.\nargs+=(\"--lflag=-Xlinker\")\nargs+=(\"--lflag=-s\")\n\n# When linking in `dev` mode, make sure that the ASAN symbols that get linked\n# into the top-level binary are made available for any dependent libraries.\nif [ \"{link_style}\" == \"shared\" ]; then\n args+=(\"--lflag=-Xlinker\")\n args+=(\"--lflag=--export-dynamic\")\nfi;\n\n# The output file and input source.\nargs+=(\"-o\" \"$OUT\")\nargs+=(\"$SRCS\")\n\nexec \"${{args[@]}}\"\n'''\n\ndef _hsc2hs(\n base_path,\n name,\n platform,\n source,\n deps,\n visibility):\n \"\"\"\n Construct the rules to generate a haskell source from the given\n `hsc2hs` source.\n \"\"\"\n\n # Macros in the `cxx_genrule` below don't support the `platform_deps`\n # parameter that we rely on to support multi-platform builds. So use\n # a helper rule for this, and just depend on the helper.\n deps_name = name + \"-\" + source + \"-deps\"\n d = cpp_common.get_binary_link_deps(base_path, deps_name)\n _dep_rule(base_path, deps_name, deps + d, visibility)\n\n out_obj = paths.split_extension(paths.basename(source))[0] + \"_hsc_make\"\n source_name = name + \"-\" + source\n fb_native.cxx_genrule(\n name = source_name,\n visibility = get_visibility(visibility, source_name),\n cmd = (\n HSC2HS_TEMPL.format(\n fbcode = (\n paths.join(\n \"$GEN_DIR\",\n get_project_root_from_gen_dir(),\n )\n ),\n ghc_tool = third_party.get_tool_path(\"ghc\", platform),\n ghc = paths.join(third_party.get_build_path(platform), \"ghc\"),\n link_style = config.get_default_link_style(),\n deps = \" :\" + deps_name,\n out_obj = out_obj,\n )\n ),\n srcs = [source],\n out = paths.split_extension(source)[0] + \".hs\",\n )\n\n return \":\" + source_name\n\ndef _get_deps_for_packages(packages, platform):\n return [haskell_common.get_dep_for_package(p, platform) for p in packages]\n\n# Packages enabled by default unless you specify fb_haskell = False\n_FB_HASKELL_PACKAGES = [\n \"aeson\",\n \"async\",\n \"attoparsec\",\n \"binary\",\n \"bytestring\",\n \"containers\",\n \"data-default\",\n \"deepseq\",\n \"directory\",\n \"either\",\n \"filepath\",\n \"hashable\",\n \"mtl\",\n \"optparse-applicative\",\n \"pretty\",\n \"process\",\n \"scientific\",\n \"statistics\",\n \"text\",\n \"text-show\",\n \"time\",\n \"transformers\",\n \"unordered-containers\",\n \"QuickCheck\",\n \"unix\",\n \"vector\",\n]\n\n_ALEX_PACKAGES = [\"array\", \"bytestring\"]\n\n_HAPPY_PACKAGES = [\"array\"]\n\n_IMPLICIT_TP_DEPS = [\n target_utils.ThirdPartyRuleTarget(\"ghc\", \"base\"),\n\n # TODO(agallagher): These probably need to be moved into the TARGETS\n # rule definition for a core lib.\n target_utils.ThirdPartyRuleTarget(\"glibc\", \"dl\"),\n target_utils.ThirdPartyRuleTarget(\"glibc\", \"m\"),\n target_utils.ThirdPartyRuleTarget(\"glibc\", \"pthread\"),\n]\n\ndef _get_implicit_deps():\n \"\"\"\n The deps that all haskell rules implicitly depend on.\n \"\"\"\n\n return _IMPLICIT_TP_DEPS\n\ndef _convert_rule(\n rule_type,\n base_path,\n name = None,\n main = None,\n srcs = (),\n deps = (),\n external_deps = (),\n packages = (),\n compiler_flags = (),\n warnings_flags = (),\n lang_opts = (),\n enable_haddock = False,\n haddock_flags = None,\n enable_profiling = None,\n ghci_bin_dep = None,\n ghci_init = None,\n extra_script_templates = (),\n eventlog = None,\n link_whole = None,\n force_static = None,\n fb_haskell = True,\n allocator = \"jemalloc\",\n dlls = {},\n visibility = None):\n _ignore = enable_haddock\n _ignore = eventlog\n\n is_binary = rule_type in (\n \"haskell_binary\",\n \"haskell_unittest\",\n )\n is_test = rule_type == \"haskell_unittest\"\n is_deployable = rule_type in (\n \"haskell_binary\",\n \"haskell_unittest\",\n \"haskell_ghci\",\n )\n\n out_compiler_flags = []\n out_linker_flags = []\n out_link_style = cpp_common.get_link_style()\n platform = platform_utils.get_platform_for_base_path(base_path)\n\n attributes = {}\n attributes[\"name\"] = name\n attributes[\"visibility\"] = get_visibility(visibility, name)\n\n if is_binary:\n if main != None:\n attributes[\"main\"] = main\n elif not (\"Main.hs\" in srcs):\n fail(\n \"Must define `main` attribute on {0}:{1}\".format(\n base_path,\n name,\n ),\n )\n\n if link_whole != None:\n attributes[\"link_whole\"] = link_whole\n\n if force_static != None:\n attributes[\"preferred_linkage\"] = \"static\"\n\n if rule_type == \"haskell_ghci\":\n out_compiler_flags.append(\"-fexternal-interpreter\")\n\n # Mark binary_link_deps to be preloaded\n d = cpp_common.get_binary_link_deps(base_path, name, allocator = allocator)\n attributes[\"preload_deps\"], attributes[\"platform_preload_deps\"] = \\\n src_and_dep_helpers.format_all_deps(d)\n\n attributes[\"extra_script_templates\"] = [\n src_and_dep_helpers.convert_source(base_path, template)\n for template in extra_script_templates\n ]\n template_base_names = []\n\n # BUCK generates a standard script with the same name as TARGET\n # by default\n template_base_names.append(name)\n for template_path in attributes[\"extra_script_templates\"]:\n template_base_names.append(paths.basename(template_path))\n if len(template_base_names) > len(collections.uniq(template_base_names)):\n fail(\n \"{0}:{1}: parameter `extra_script_templates`: \".format(\n base_path,\n name,\n ) +\n \"Template file names must be unique and not same as \" +\n \"the TARGET name\",\n )\n\n if ghci_bin_dep != None:\n bin_dep_target = src_and_dep_helpers.convert_build_target(base_path, ghci_bin_dep)\n attributes[\"ghci_bin_dep\"] = bin_dep_target\n\n if ghci_init != None:\n attributes[\"ghci_init\"] = src_and_dep_helpers.convert_source(base_path, ghci_init)\n\n if haskell_common.read_hs_profile():\n attributes[\"enable_profiling\"] = True\n elif enable_profiling != None:\n attributes[\"enable_profiling\"] = enable_profiling\n\n if haskell_common.read_hs_eventlog():\n out_linker_flags.append(\"-eventlog\")\n if haskell_common.read_hs_debug():\n out_linker_flags.append(\"-debug\")\n\n if rule_type == \"haskell_library\":\n out_haddock_flags = [\n \"--source-entity\",\n \"https://phabricator.intern.facebook.com/diffusion/FBS/browse/\" +\n \"master/fbcode/%{FILE}$%{LINE}\",\n ]\n\n # keep TARGETS specific flags last, so that they can override the\n # flags before\n if haddock_flags:\n out_haddock_flags.extend(haddock_flags)\n attributes[\"haddock_flags\"] = out_haddock_flags\n\n validated_compiler_flags = []\n validated_compiler_flags.extend(\n haskell_common.get_compiler_flags(compiler_flags, fb_haskell),\n )\n ldflags = (\n cpp_common.get_ldflags(\n base_path,\n name,\n rule_type,\n binary = is_binary,\n deployable = is_deployable,\n # Never apply stripping flags to library rules, as they only\n # get linked when using dynamic linking (which we avoid\n # applying stripping to anyway), and added unused linker flags\n # affect rule keys up the tree.\n strip_mode = None if is_deployable else \"none\",\n build_info = is_deployable,\n platform = platform if is_deployable else None,\n )\n )\n for ldflag in ldflags:\n out_linker_flags.extend([\"-optl\", ldflag])\n out_linker_flags.extend(validated_compiler_flags)\n\n out_compiler_flags.extend(haskell_common.get_warnings_flags(warnings_flags))\n out_compiler_flags.extend(validated_compiler_flags)\n out_compiler_flags.extend(\n haskell_common.get_language_options(lang_opts, fb_haskell),\n )\n build_mode = _build_mode.get_build_mode_for_current_buildfile()\n if build_mode != None:\n out_compiler_flags.extend(build_mode.ghc_flags)\n out_compiler_flags.extend(haskell_common.read_extra_ghc_compiler_flags())\n if out_compiler_flags:\n attributes[\"compiler_flags\"] = out_compiler_flags\n\n # If this is binary and we're using the shared link style, set this in\n # the output attributes.\n if is_deployable and config.get_default_link_style() == \"shared\":\n out_link_style = \"shared\"\n\n # Collect all deps specified by the user.\n user_deps = []\n for dep in deps:\n user_deps.append(target_utils.parse_target(dep, default_base_path = base_path))\n for dep in external_deps:\n user_deps.append(src_and_dep_helpers.normalize_external_dep(dep))\n user_deps.extend(_get_deps_for_packages(packages, platform))\n if fb_haskell:\n user_deps.extend(_get_deps_for_packages(\n [x for x in _FB_HASKELL_PACKAGES if x not in packages],\n platform,\n ))\n user_deps.extend(_get_implicit_deps())\n\n # Convert the various input source types to haskell sources.\n out_srcs = []\n implicit_src_deps = []\n for src in srcs:\n _, ext = paths.split_extension(src)\n if ext == \".y\":\n src = _happy_rule(name, platform, src, visibility)\n out_srcs.append(src)\n implicit_src_deps.extend(\n _get_deps_for_packages(_HAPPY_PACKAGES, platform),\n )\n elif ext == \".x\":\n src = _alex_rule(name, platform, src, visibility)\n out_srcs.append(src)\n implicit_src_deps.extend(\n _get_deps_for_packages(_ALEX_PACKAGES, platform),\n )\n elif ext == \".hsc\":\n src = (\n _hsc2hs(\n base_path,\n name,\n platform,\n src,\n user_deps,\n visibility,\n )\n )\n out_srcs.append(src)\n elif ext == \".chs\":\n src = (\n _c2hs(\n base_path,\n name,\n platform,\n src,\n user_deps,\n visibility,\n )\n )\n out_srcs.append(src)\n else:\n out_srcs.append(src)\n attributes[\"srcs\"] = out_srcs\n\n # The final list of dependencies.\n dependencies = []\n dependencies.extend(user_deps)\n dependencies.extend([\n x\n for x in sorted(collections.uniq(implicit_src_deps))\n if x not in user_deps\n ])\n\n # Handle DLL deps.\n out_dep_queries = []\n if dlls:\n buck_platform = platform_utils.get_buck_platform_for_base_path(base_path)\n dll_deps, dll_ldflags, dll_dep_queries = (\n haskell_common.convert_dlls(\n name,\n platform,\n buck_platform,\n dlls,\n visibility = visibility,\n )\n )\n dependencies.extend(dll_deps)\n optlflags = []\n for f in dll_ldflags:\n optlflags.append(\"-optl\")\n optlflags.append(f)\n out_linker_flags.extend(optlflags)\n out_dep_queries.extend(dll_dep_queries)\n\n # We don't currently support dynamic linking with DLL support, as\n # we don't have a great way to prevent dependency DSOs needed by\n # the DLL, but *not* needed by the top-level binary, from being\n # dropped from the `DT_NEEDED` tags when linking with\n # `--as-needed`.\n if out_link_style == \"shared\":\n out_link_style = \"static_pic\"\n\n if out_dep_queries:\n attributes[\"deps_query\"] = \" union \".join(out_dep_queries)\n attributes[\"link_deps_query_whole\"] = True\n\n out_linker_flags.extend(haskell_common.read_extra_ghc_linker_flags())\n if out_linker_flags:\n attributes[\"linker_flags\"] = out_linker_flags\n\n if is_deployable:\n attributes[\"platform\"] = platform_utils.get_buck_platform_for_base_path(base_path)\n\n # TODO: support `link_style` for `haskell_ghci` rule.\n if rule_type != \"haskell_ghci\":\n attributes[\"link_style\"] = out_link_style\n\n if is_test:\n dependencies.append(haskell_common.get_dep_for_package(\"HUnit\", platform))\n dependencies.append(target_utils.RootRuleTarget(\"tools/test/stubs\", \"fbhsunit\"))\n\n # Add in binary-specific link deps.\n add_preload_deps = rule_type in (\"haskell_library\", \"haskell_binary\")\n if is_binary or add_preload_deps:\n d = cpp_common.get_binary_link_deps(base_path, name, allocator = allocator)\n if is_binary:\n dependencies.extend(d)\n\n # Mark binary_link_deps to be preloaded\n if add_preload_deps:\n attributes[\"ghci_preload_deps\"], attributes[\"ghci_platform_preload_deps\"] = \\\n src_and_dep_helpers.format_all_deps(d)\n\n attributes[\"deps\"], attributes[\"platform_deps\"] = (\n src_and_dep_helpers.format_all_deps(dependencies)\n )\n\n return attributes\n\ndef _dll(base_path, name, dll, visibility = None, **kwargs):\n \"\"\"\n Generate rules to build a dynamic library.\n \"\"\"\n _ignore = dll\n\n # Generate rules to build the haskell library. We set `link_whole`\n # here as it'll be the main component of the shared library we build\n # below. We also use an obsfucated name so that dependents must use\n # their `dll` parameter to depend on it.\n lib_name = name + \"-dll-root\"\n fb_native.haskell_library(\n **_convert_rule(\n rule_type = \"haskell_library\",\n base_path = base_path,\n name = lib_name,\n link_whole = True,\n force_static = True,\n visibility = visibility,\n **kwargs\n )\n )\n\n # For backwards compatiblity with fbbuild, generate a noop rule under\n # the original name. This is so unported fbbuild use cases of DLLs\n # don't break the build.\n\n fb_native.genrule(\n name = name,\n visibility = get_visibility(visibility, name),\n out = \"empty\",\n cmd = 'touch \"$OUT\"',\n )\n\nhaskell_rules = struct(\n convert_rule = _convert_rule,\n dll = _dll,\n get_deps_for_packages = _get_deps_for_packages,\n)\n","sub_path":"infra_macros/fbcode_macros/build_defs/lib/haskell_rules.bzl","file_name":"haskell_rules.bzl","file_ext":"bzl","file_size_in_byte":21739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"497284454","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @Time : 4/28/2019 3:53 PM\r\n# @Author : chinshin\r\n# @FileName: ggnn_dev_jk_gru.py\r\n\r\nfrom __future__ import unicode_literals\r\nfrom __future__ import print_function\r\nimport numpy as np\r\nimport chainer\r\nfrom chainer import cuda\r\nfrom chainer import functions\r\nfrom chainer import links\r\nfrom chainer.backends import cuda\r\nimport chainer_chemistry\r\nfrom chainer_chemistry.config import MAX_ATOMIC_NUM\r\nfrom chainer_chemistry.links import EmbedAtomID\r\nfrom chainer_chemistry.links import GraphLinear\r\n\r\n\r\ndef select_aggr(layer_aggr, n_layers=None, in_size=None, out_size=None, dropout=0.0):\r\n assert layer_aggr is not None\r\n if layer_aggr == 'concat':\r\n aggr = ConcatAggregator()\r\n elif layer_aggr == 'max':\r\n aggr = MaxAggregator()\r\n elif layer_aggr == 'mean':\r\n aggr = AvgAggregator()\r\n elif layer_aggr == 'gru':\r\n assert n_layers is not None and \\\r\n in_size is not None and out_size is not None\r\n aggr = GRUAggregator(n_layers, in_size, out_size, dropout)\r\n elif layer_aggr == 'bigru':\r\n assert n_layers is not None and \\\r\n in_size is not None and out_size is not None\r\n aggr = BiGRUAggregator(n_layers, in_size, out_size, dropout)\r\n elif layer_aggr == 'attn':\r\n assert n_layers is not None\r\n aggr = AttnAggregator()\r\n else:\r\n raise ValueError('No such layer aggr named {}'.format(layer_aggr))\r\n return aggr\r\n\r\n\r\nclass GGNN(chainer.Chain):\r\n\r\n NUM_EDGE_TYPE = 4\r\n\r\n def __init__(self, out_dim, hidden_dim=16,\r\n n_layers=4, n_atom_types=MAX_ATOMIC_NUM, concat_hidden=False,\r\n dropout_rate=0.0, layer_aggr=None,\r\n batch_normalization=False,\r\n weight_tying=True, update_tying=True,\r\n ):\r\n super(GGNN, self).__init__()\r\n n_readout_layer = n_layers if concat_hidden else 1\r\n n_message_layer = 1 if weight_tying else n_layers\r\n n_update_layer = 1 if update_tying else n_layers\r\n self.n_readout_layer = n_readout_layer\r\n self.n_message_layer = n_message_layer\r\n self.out_dim = out_dim\r\n self.hidden_dim = hidden_dim\r\n self.n_layers = n_layers\r\n self.concat_hidden = concat_hidden\r\n self.dropout_rate = dropout_rate\r\n self.batch_normalization = batch_normalization\r\n self.weight_tying = weight_tying\r\n self.update_tying = update_tying\r\n self.layer_aggr = layer_aggr\r\n\r\n with self.init_scope():\r\n # Update\r\n self.embed = EmbedAtomID(out_size=hidden_dim, in_size=n_atom_types)\r\n\r\n self.message_layers = chainer.ChainList(\r\n *[GraphLinear(hidden_dim, self.NUM_EDGE_TYPE * hidden_dim)\r\n for _ in range(n_message_layer)]\r\n )\r\n\r\n self.update_layer = chainer.ChainList(\r\n *[links.Linear(2 * hidden_dim, hidden_dim)\r\n for _ in range(n_update_layer)]\r\n )\r\n # self.update_layer = links.GRU(2 * hidden_dim, hidden_dim)\r\n\r\n # Layer Aggregation\r\n self.aggr = select_aggr(layer_aggr, 1, hidden_dim, hidden_dim)\r\n\r\n # Readout\r\n self.i_layers = chainer.ChainList(\r\n *[GraphLinear(2 * hidden_dim, out_dim)\r\n for _ in range(n_readout_layer)]\r\n )\r\n self.j_layers = chainer.ChainList(\r\n *[GraphLinear(hidden_dim, out_dim)\r\n for _ in range(n_readout_layer)]\r\n )\r\n\r\n def update(self, h, adj, step=0):\r\n # --- Message & Update part ---\r\n # (minibatch, atom, ch)\r\n mb, atom, ch = h.shape\r\n out_ch = ch\r\n message_layer_index = 0 if self.weight_tying else step\r\n update_layer_index = 0 if self.update_tying else step\r\n # m: (minibatch, atom, ch) -> (minibatch, atom, edge_type * ch) -> (minibatch, atom, ch, edge_type)\r\n m = functions.reshape(self.message_layers[message_layer_index](h),\r\n (mb, atom, out_ch, self.NUM_EDGE_TYPE))\r\n\r\n # m: (minibatch, atom, ch, edge_type)\r\n # Transpose\r\n # m: (minibatch, edge_type, atom, ch)\r\n m = functions.transpose(m, (0, 3, 1, 2))\r\n\r\n # adj: (minibatch * edge_type, atom, atom)\r\n adj = functions.reshape(adj, (mb * self.NUM_EDGE_TYPE, atom, atom))\r\n # m: (minibatch * edge_type, atom, ch)\r\n m = functions.reshape(m, (mb * self.NUM_EDGE_TYPE, atom, out_ch))\r\n\r\n # (mb * edge_type, atom, atom) * (mb * edge_type, atom, out_ch)\r\n m = chainer_chemistry.functions.matmul(adj, m)\r\n\r\n # (minibatch * edge_type, atom, out_ch) -> (minibatch, edge_type, atom, out_ch)\r\n m = functions.reshape(m, (mb, self.NUM_EDGE_TYPE, atom, out_ch))\r\n # Take sum\r\n m = functions.sum(m, axis=1)\r\n # (minibatch, atom, out_ch)\r\n\r\n # --- Update part ---\r\n # Contraction\r\n h = functions.reshape(h, (mb * atom, ch))\r\n\r\n # Contraction\r\n m = functions.reshape(m, (mb * atom, ch))\r\n\r\n # input for GRU: (mb * atom, 2 * ch) -> (mb * atom, ch)\r\n # out_h = self.update_layer(functions.concat((h, m), axis=1))\r\n #\r\n out_h = functions.relu(self.update_layer[update_layer_index](functions.concat((h, m), axis=1)))\r\n # Expansion: (mb * atom, ch) -> (mb, atom, ch)\r\n out_h = functions.reshape(out_h, (mb, atom, ch))\r\n return out_h\r\n\r\n def readout(self, h, h0, step=0):\r\n # --- Readout part ---\r\n index = step if self.concat_hidden else 0\r\n # h, h0: (minibatch, atom, ch)\r\n g = functions.sigmoid(\r\n self.i_layers[index](functions.concat((h, h0), axis=2))) \\\r\n * self.j_layers[index](h)\r\n g = functions.sum(g, axis=1) # sum along atom's axis\r\n return g\r\n\r\n def __call__(self, atom_array, adj):\r\n # reset state\r\n # self.update_layer.reset_state()\r\n # [layer.reset_state() for layer in self.update_layer]\r\n if atom_array.dtype == self.xp.int32:\r\n h = self.embed(atom_array) # (minibatch, max_num_atoms)\r\n else:\r\n h = atom_array\r\n h0 = functions.copy(h, cuda.get_device_from_array(h.data).id)\r\n g_list = []\r\n h_list = []\r\n for step in range(self.n_layers):\r\n h = self.update(h, adj, step)\r\n\r\n if self.dropout_rate != 0.0:\r\n h = functions.dropout(h, ratio=self.dropout_rate)\r\n\r\n if self.concat_hidden:\r\n g = self.readout(h, h0, step)\r\n g_list.append(g)\r\n\r\n if self.layer_aggr:\r\n h_list.append(h)\r\n\r\n if self.concat_hidden:\r\n return functions.concat(g_list, axis=1)\r\n elif self.layer_aggr:\r\n output = self.aggr(h_list)\r\n\r\n return self.readout(output, h0, 0)\r\n else:\r\n g = self.readout(h, h0, 0)\r\n return g\r\n\r\n\r\nclass ConcatAggregator(chainer.Chain):\r\n def __init__(self):\r\n super(ConcatAggregator, self).__init__()\r\n\r\n def __call__(self, h_list):\r\n # h_list: list of elem with shape of (mb, node, ch)\r\n # (mb, node, ch * n_conv_layers)\r\n # [mb, atoms, n_layers * hidden_dim]\r\n h = functions.concat(h_list, axis=-1)\r\n return h\r\n\r\n\r\nclass MaxAggregator(chainer.Chain):\r\n def __init__(self):\r\n super(MaxAggregator, self).__init__()\r\n\r\n def __call__(self, h_list):\r\n # hs: (mb, node, ch, n_conv_layers)\r\n h_list = [functions.expand_dims(h, axis=-2) for h in h_list]\r\n # (mb, atoms, n_layers, hidden_dim)\r\n concat_h = functions.concat(h_list, axis=-2)\r\n # (mb, atoms, n_layers, hidden_dim) -> (mb, atoms, hidden_dim)\r\n h = functions.max(concat_h, axis=-2)\r\n return h\r\n\r\n\r\nclass AvgAggregator(chainer.Chain):\r\n def __init__(self):\r\n super(AvgAggregator, self).__init__()\r\n\r\n def __call__(self, h_list):\r\n # hs: (mb, node, ch, n_conv_layers)\r\n h_list = [functions.expand_dims(h, axis=-2) for h in h_list]\r\n # (mb, atoms, n_layers, hidden_dim)\r\n concat_h = functions.concat(h_list, axis=-2)\r\n # (mb, atoms, n_layers, hidden_dim) -> (mb, atoms, hidden_dim)\r\n h = functions.mean(concat_h, axis=-2)\r\n return h\r\n\r\n\r\nclass GRUAggregator(chainer.Chain):\r\n def __init__(self, n_layers, in_size, out_size, dropout=0.0):\r\n super(GRUAggregator, self).__init__()\r\n with self.init_scope():\r\n self.gru_layer = links.NStepGRU(n_layers, in_size, out_size, dropout)\r\n\r\n self.n_layers = n_layers\r\n self.in_size = in_size\r\n self.out_size = out_size\r\n self.dropout = dropout\r\n\r\n def __call__(self, h_list):\r\n h_list = [functions.expand_dims(h, axis=-2) for h in h_list]\r\n concat_h = functions.concat(h_list, axis=-2)\r\n mb, atoms, n_layers, hidden_dim = concat_h.shape\r\n # concat_h: (n_layers, mb, atoms, hidden_dim)\r\n concat_h = functions.transpose(concat_h, axes=(2, 0, 1, 3))\r\n seq_h = functions.reshape(concat_h, shape=(n_layers, mb * atoms, hidden_dim))\r\n seq_h_list = list(seq_h)\r\n _, seq_out_list = self.gru_layer(None, seq_h_list)\r\n # [n_layers, mb * atoms, hidden_dim]\r\n seq_out_arr = functions.concat([functions.expand_dims(seq, axis=0) for seq in seq_out_list], axis=0)\r\n # [mb * atoms, hidden_dim]\r\n seq_out_forward = seq_out_arr[-1, :, :hidden_dim]\r\n # [mb * atoms, 2 * hidden_dim] -> [mb, atoms, 2 * hidden_dim]\r\n seq_out_arr = functions.reshape(seq_out_forward, shape=(mb, atoms, hidden_dim))\r\n # [mb, atoms, 2 * hidden_dim]\r\n h = seq_out_arr\r\n\r\n return h\r\n\r\n\r\nclass BiGRUAggregator(chainer.Chain):\r\n def __init__(self, n_layers, in_size, out_size, dropout):\r\n super(BiGRUAggregator, self).__init__()\r\n with self.init_scope():\r\n self.bigru_layer = links.NStepBiGRU(n_layers, in_size, out_size, dropout)\r\n self.out_layer = GraphLinear(2 * out_size, out_size)\r\n self.n_layers = n_layers\r\n self.in_size = in_size\r\n self.out_size = out_size\r\n self.dropout = dropout\r\n\r\n def __call__(self, h_list):\r\n h_list = [functions.expand_dims(h, axis=-2) for h in h_list]\r\n concat_h = functions.concat(h_list, axis=-2)\r\n mb, atoms, n_layers, hidden_dim = concat_h.shape\r\n # concat_h: (n_layers, mb, atoms, hidden_dim)\r\n concat_h = functions.transpose(concat_h, axes=(2, 0, 1, 3))\r\n seq_h = functions.reshape(concat_h, shape=(n_layers, mb * atoms, hidden_dim))\r\n seq_h_list = list(seq_h)\r\n _, seq_out_list = self.bigru_layer(None, seq_h_list)\r\n # [n_layers, mb * atoms, hidden_dim]\r\n seq_out_arr = functions.concat([functions.expand_dims(seq, axis=0) for seq in seq_out_list], axis=0)\r\n # [mb * atoms, hidden_dim]\r\n seq_out_forward = seq_out_arr[-1, :, :hidden_dim]\r\n # [mb * atoms, hidden_dim]\r\n seq_out_backward = seq_out_arr[0, :, hidden_dim:]\r\n # [mb * atoms, 2 * hidden_dim]\r\n seq_out_arr = functions.concat([seq_out_forward, seq_out_backward], axis=-1)\r\n # [mb * atoms, 2 * hidden_dim] -> [mb, atoms, 2 * hidden_dim]\r\n seq_out_arr = functions.reshape(seq_out_arr, shape=(mb, atoms, 2 * hidden_dim))\r\n # [mb, atoms, 2 * hidden_dim]\r\n h = seq_out_arr\r\n h = self.out_layer(h)\r\n return h\r\n\r\n\r\nclass AttnAggregator(chainer.Chain):\r\n \"\"\"\r\n query: the final graph convolution layer representation\r\n \"\"\"\r\n def __init__(self):\r\n super(AttnAggregator, self).__init__()\r\n\r\n def __call__(self, h_list):\r\n \"\"\"\r\n :param h_list: list of h, h with shape of (mb, node, ch)\r\n :return:\r\n \"\"\"\r\n h_list = [functions.expand_dims(h, axis=-2) for h in h_list]\r\n concat_h = functions.concat(h_list, axis=-2)\r\n # concat_h: (n_layers, mb, atoms, hidden_dim)\r\n concat_h = functions.transpose(concat_h, axes=(2, 0, 1, 3))\r\n n_layers, mb, atoms, hidden_dim = concat_h.shape\r\n query_final = h_list[-1]\r\n energy_final = self.compute_attention(query_final, key=concat_h)\r\n query_first = h_list[0]\r\n energy_first = self.compute_attention(query_first, key=concat_h)\r\n energy = energy_final + energy_first\r\n # (n_layers, 1)\r\n coefs = functions.softmax(energy, axis=0)\r\n coefs = functions.broadcast_to(\r\n functions.reshape(coefs, shape=(n_layers, 1, 1, 1)),\r\n shape=(n_layers, mb, atoms, hidden_dim))\r\n # (n_layers, ) * (n_layers, mb, atoms, hidden_dim)\r\n prod = coefs * concat_h\r\n # (mb, atoms, hidden_dim)\r\n compact = functions.sum(prod, axis=0)\r\n return compact\r\n\r\n def compute_attention(self, query, key):\r\n \"\"\"\r\n :param query: with shape of (mb, atom, ch)\r\n :param key: with shape of (n_layers, mb, atom, ch)\r\n :return: coefs: with shape of (n_layers, 1)\r\n \"\"\"\r\n n_layes, mb, atom, hidden_dim = key.shape\r\n # query: (1, mb, atom, ch)\r\n query = functions.expand_dims(query, axis=0)\r\n # query: (1, mb * atom * hidden_dim)\r\n query = functions.reshape(query, shape=(1, mb * atom * hidden_dim))\r\n key = functions.reshape(key, shape=(n_layes, mb * atom * hidden_dim))\r\n # (n_layes, 1)\r\n energy = functions.matmul(key, query, transb=True)\r\n return energy","sub_path":"models/ggnn_dev_jknet.py","file_name":"ggnn_dev_jknet.py","file_ext":"py","file_size_in_byte":13584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"636874135","text":"import vk\nimport requests\nfrom settings import *\n\nimport random\nimport psycopg2\n\n\n\n\n\n\n\nsession = vk.Session(access_token = sanya_token)\nvk_api = vk.API(session)\n\nv = 5.101\ndata = vk_api.groups.getLongPollServer(v = v, group_id = 185829585)\n\n\n\n\nlastmembers = set()\nwhile True:\n response = requests.get(\n '{server}?act=a_check&key={key}&ts={ts}&wait=25'.format(server=data['server'],\n key=data['key'],\n ts=data['ts'])).json()\n if 'updates' in response:\n updates = response['updates']\n else:\n updates = []\n #print(updates)\n\n\n if updates and updates[0]['type'] == 'message_new' and 'action' in updates[0]['object'] and (updates[0]['object']['action']['type'] == 'chat_invite_user' or updates[0]['object']['action']['type'] == 'chat_invite_user_by_link'):\n conn = psycopg2.connect(host=host, port=5432,\n database=database,\n user = database_user,\n password=database_password)\n\n cur = conn.cursor()\n peer_id = updates[0]['object']['peer_id']\n curmembers = set()\n try:\n items = vk_api.messages.getConversationMembers(v=v, peer_id=peer_id)['items']\n except:\n items = []\n #print(items)\n for member in items:\n curmembers.add((member['member_id'], 'is_admin' in member))\n new = curmembers - lastmembers\n #print(new)\n for usr in new:\n id = usr[0]\n admin = usr[1]\n if id > 0 and not admin:\n user = vk_api.users.get(v = v, user_ids = id)\n name = user[0]['first_name'].lower()\n last = user[0]['last_name'].lower()\n cur.execute('select names from sasha where names = %s;', (name,))\n row1 = cur.fetchall()\n cur.execute('select names from sasha where names = %s;', (last,))\n row2 = cur.fetchall()\n if row1 == [] and row2 == []:\n vk_api.messages.removeChatUser(v = v, chat_id = peer_id - 2 * 10 ** 9, user_id = id)\n curmembers.discard(usr)\n lastmembers = curmembers\n conn.commit()\n conn.close()\n\n elif updates and updates[0]['type'] == 'message_new' and 'action' in updates[0]['object'] and updates[0]['object']['action']['type'] == 'chat_kick_user':\n mem_id = updates[0]['object']['action']['member_id']\n lastmembers.discard((mem_id, True))\n lastmembers.discard((mem_id, False))\n elif updates and updates[0]['type'] == 'message_new' and (updates[0]['object']['from_id'] == 514794333 or updates[0]['object']['from_id'] == 231287650) and updates[0]['object']['peer_id'] < 2 * 10 ** 9:\n conn = psycopg2.connect(host=host, port=5432,\n database=database,\n user=database_user,\n password=database_password)\n\n cur = conn.cursor()\n\n id = updates[0]['object']['from_id']\n message = updates[0]['object']['text'].split()\n if len(message) != 2:\n command = ''\n else:\n command, name = message[0], message[1].lower()\n if command == '/добавить':\n cur.execute('select names from sasha where names = %s;', (name,))\n row = cur.fetchall()\n if row == []:\n cur.execute('insert into sasha values(%s);', (name,))\n vk_api.messages.send(v = v, user_id = id, message = 'добавлено исключение: ' + name, random_id = random.randint(0, 10 ** 6))\n elif command == '/удалить':\n cur.execute('DELETE from sasha WHERE names = %s;', (name,))\n vk_api.messages.send(v = v, user_id = id, message = 'удалено исключение: ' + name, random_id = random.randint(0, 10 ** 6))\n\n if len(message) == 1 and message[0] == '/имена':\n msg = ''\n cur.execute('select * from sasha;')\n row = cur.fetchall()\n for word in row:\n msg += word[0] + '\\n'\n vk_api.messages.send(v=v, user_id=id, message=msg,\n random_id=random.randint(0, 10 ** 6))\n\n conn.commit()\n conn.close()\n\n data['ts'] = response['ts']","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"570689162","text":"# coding: utf-8\n\nfrom random import randrange\nfrom ui import *\n\ndef joga():\n nome = da_boas_vindas()\n quer_jogar = True\n while quer_jogar:\n quer_jogar = jogo_da_forca(nome)\n\ndef jogo_da_forca(nome):\n palavra = palavra_aleatoria()\n imprime_mascara(palavra)\n chutes = []\n erros = 0\n continua_jogo = True\n while erros < 5 and continua_jogo:\n chute = pede_chute()\n if len(chute) > 1:\n if chute == palavra:\n acertou_palavra(palavra)\n continua_jogo = False\n else:\n erros = errou_palavra(chute, erros)\n else:\n chute_valido = valida_chute(chute, chutes)\n chutes.append(chute_valido)\n if not acertou(chute_valido, palavra):\n erros = errou(chute_valido, erros)\n mascara = palavra_mascarada(chutes, palavra)\n print(mascara)\n desenha_boneco(erros)\n if erros == 5:\n informa_que_perdeu(nome)\n quer_jogar = jogar_novamente()\n return quer_jogar\n\ndef obtem_arquivo():\n nome = ('palavras%s.txt' % (randrange(1, 4, 1)))\n arquivo = open(nome, 'r')\n conteudo = arquivo.read()\n palavras = conteudo.split('\\n')\n arquivo.close()\n return palavras\n\ndef palavra_aleatoria():\n palavras = obtem_arquivo()\n palavra_escolhida = palavras[randrange(1, len(palavras), 1)]\n da_dica(palavras[0])\n return palavra_escolhida\n\ndef palavra_mascarada(chutes, palavra):\n mascara = ''\n for letra in palavra:\n for chute in chutes:\n indice = letra.find(chute)\n if indice != -1:\n mascara += letra\n break\n if indice == -1:\n mascara += '_'\n return mascara\n\ndef acertou(chute, palavra):\n if chute in list(palavra):\n return True\n else:\n return False\n\ndef valida_chute(chute, chutes):\n while chute in chutes:\n informa_chute_repetido(chute)\n chute = input()\n return chute\n\ndef errou(chute, erros):\n avisa_que_errou(chute)\n erros += 1\n return erros\n\ndef errou_palavra(palavra, erros):\n avisa_que_errou_palavra(palavra)\n erros += 1\n return erros","sub_path":"forca.py","file_name":"forca.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"97922323","text":"#!/usr/bin/python3\n\"\"\"\nmodule that will run the console\nfor project clone AirBnB holds a package,\ncmd that will be used for creating the command line\nimterpreter\n\"\"\"\nimport cmd\nfrom models import storage\nfrom models.base_model import BaseModel\nfrom models.user import User\nfrom models.state import State\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.place import Place\nfrom models.review import Review\n\n\nclass HBNBCommand(cmd.Cmd):\n \"\"\"class will hold the cmd module\n that will used for running the command line enterpreter\n \"\"\"\n prompt = '(hbnb) '\n\n def do_quit(self, arg):\n \"\"\"Command to exit the prompt directly\n \"\"\"\n return True\n\n def do_EOF(self, arg):\n \"\"\"Allows to exit the prompt by typing ctrl^d\n \"\"\"\n print()\n return True\n\n def emptyline(self):\n \"\"\"When a empty line is passed, does not do\n anything\"\"\"\"\"\"\n \"\"\"\n pass\n\n def default(self, line):\n \"\"\"default value when it not recognice returns\n the erros else while print the requeriment\n \"\"\"\n created_objs = storage.all()\n count = [\"BaseModel.count()\", \"User.count()\",\n \"Place.count()\", \"City.count()\",\n \"State.count()\", \"Amenity.count()\", \"Review.count()\"]\n all = [\"BaseModel.all()\", \"User.all()\",\n \"Place.all()\", \"City.all()\",\n \"State.all()\", \"Amenity.all()\", \"Review.all()\"]\n if line in count:\n trim = line.split(\".\")\n number = 0\n for key_id in created_objs.keys():\n num = key_id.rfind(trim[0])\n if num != -1:\n number = number + 1\n print(number)\n\n elif line in all:\n new_list = []\n for key, obj in created_objs.items():\n trim = line.split(\".\")\n classname = key.split(\".\")\n if trim[0] == classname[0]:\n new_list.append(obj.__str__())\n print(new_list)\n\n else:\n return super().default(line)\n\n def do_create(self, arg):\n \"\"\"Creates a new instance of BaseModel, saves it, and print his id.\n\n If the class name is missing it raise the following error:\n ** class name missing **\n\n If the class name doesn’t exist it raise the following error:\n ** class doesn't exist **\n \"\"\"\n models = [\"BaseModel\", \"User\", \"State\",\n \"City\", \"Amenity\", \"Place\", \"Review\"]\n if not arg:\n print(\"** class name missing **\")\n elif arg not in models:\n print(\"** class doesn't exist **\")\n else:\n arg = arg + \"()\"\n obj = eval(arg)\n obj.save()\n print(obj.id)\n\n def do_show(self, arg):\n \"\"\"Prints the string representation of an\n instance based on the class name and id\n\n If the class name is missing it raise the following error:\n ** class name missing **\n\n If the class name doesn’t exist it raise the following error:\n ** class doesn't exist **\n\n If the id is missing it raise the following error:\n ** instance id missing **\n\n If the instance of the class name doesn’t exist for the\n id it raise the following error:\n ** no instance found **\n \"\"\"\n created_objs = storage.all()\n models = [\"BaseModel\", \"User\", \"State\", \"City\",\n \"Amenity\", \"Place\", \"Review\"]\n if not arg:\n print(\"** class name missing **\")\n return\n else:\n args = arg.split()\n if not args[0] in models:\n print(\"** class doesn't exist **\")\n return\n elif len(args) == 1:\n print(\"** instance id missing **\")\n return\n elif args[0] and args[1]:\n new_key = args[0] + \".\" + args[1]\n if any(new_key == keys for keys in created_objs.keys()):\n print(created_objs[new_key])\n else:\n print(\"** no instance found **\")\n\n def do_destroy(self, arg):\n \"\"\"Deletes an instance based on the class name and id\n\n If the class name is missing it raise the following error:\n ** class name missing **\n\n If the class name doesn’t exist it raise the following error:\n ** class doesn't exist **\n\n If the id is missing it raise the following error:\n ** instance id missing **\n\n If the instance of the class name doesn’t exist for\n the id it raise the following error:\n ** no instance found **\n \"\"\"\n created_objs = storage.all()\n models = [\"BaseModel\", \"User\", \"State\", \"City\",\n \"Amenity\", \"Place\", \"Review\"]\n if not arg:\n print(\"** class name missing **\")\n return\n else:\n args = arg.split()\n if not args[0] in models:\n print(\"** class doesn't exist **\")\n return\n elif len(args) == 1:\n print(\"** instance id missing **\")\n return\n elif args[0] and args[1]:\n new_key = args[0] + \".\" + args[1]\n if any(new_key == keys for keys in created_objs.keys()):\n created_objs.pop(new_key)\n storage.save()\n else:\n print(\"** no instance found **\")\n\n def do_all(self, arg):\n \"\"\"Prints all string representation of all\n instances based or not on the class name.\n If the class name doesn’t exist it raise the following error:\n ** class doesn't exist **\n \"\"\"\n new_list = []\n created_objs = storage.all()\n models = [\"BaseModel\", \"User\", \"State\", \"City\",\n \"Amenity\", \"Place\", \"Review\"]\n if not arg:\n for key_id in created_objs.keys():\n new_list.append(created_objs[key_id].__str__())\n print(new_list)\n else:\n if arg not in models:\n print(\"** class doesn't exist **\")\n else:\n for key_id in created_objs.keys():\n num = key_id.rfind(arg)\n if num != -1:\n new_list.append(created_objs[key_id].__str__())\n print(new_list)\n\n def do_update(self, arg):\n \"\"\"Updates an instance based on the class name and\n id by adding or updating attribute\n\n Usage:\n update \"\"\n\n If the class name is missing it raise the following error:\n ** class name missing **\n\n If the class name doesn’t exist it raise the following error:\n ** class doesn't exist **\n\n If the id is missing it raise the following error:\n ** instance id missing **\n\n If the instance of the class name doesn’t exist\n for the id it raise the following error:\n ** no instance found **\n\n If the attribute name is missing it raise the following error:\n ** attribute name missing **\n\n If the value for the attribute name doesn’t exist it\n raise the following error:\n ** value missing **\n \"\"\"\n if not arg:\n print(\"** class name missing **\")\n else:\n created_objs = storage.all()\n models = [\"BaseModel\", \"User\", \"State\", \"City\",\n \"Amenity\", \"Place\", \"Review\"]\n args = arg.split()\n if not args[0] in models:\n print(\"** class doesn't exist **\")\n return\n if len(args) == 1:\n print(\"** instance id missing **\")\n return\n if args[0] and args[1]:\n new_key = args[0] + \".\" + args[1]\n if any(new_key == keys for keys in created_objs.keys()):\n if len(args) == 2:\n print(\"** attribute name missing **\")\n return\n if len(args) == 3:\n print(\"** value missing **\")\n return\n obj = created_objs[new_key]\n trim = args[3]\n trim = trim[1:-1]\n try:\n trim = int(trim)\n except:\n try:\n trim = float(trim)\n except:\n trim = str(trim)\n setattr(obj, args[2], trim)\n obj.save()\n else:\n print(\"** no instance found **\")\n\n\nif __name__ == '__main__':\n HBNBCommand().cmdloop()\n","sub_path":"console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":8922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"412251684","text":"import random\nimport math\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Circle, Rectangle\n\n\n# 链表类\nclass node():\n def __init__(self, _p, _i):\n self.point = _p\n self.index = _i\n\n def next(self, sdlist):\n return sdlist[self.index]\n\n\nclass sdlist():\n def __init__(self, _list_n=[]):\n self.list_n = _list_n\n self.index = 0\n\n def next(self):\n self.index = self.list_n[self.index].index\n return self.list_n[self.index]\n\n def append(self, p):\n self.list_n[-1].index = len(self.list_n)\n n = node(p, 0)\n self.list_n.append(n)\n\n\n# 向量类\nclass vector():\n def __init__(self, _x, _y):\n self.x = _x\n self.y = _y\n\n # 向量相减\n def sub(self, another):\n IsVector(another)\n newx = self.x - another.x\n newy = self.y - another.y\n return vector(newx, newy)\n\n # 向量相加\n def plus(self, another):\n IsVector(another)\n newx = self.x + another.x\n newy = self.y + another.y\n return vector(newx, newy)\n\n # 向量数乘\n def mult_num(self, m):\n return vector(self.x * m, self.y * m)\n\n # 向量叉乘\n def mult_x(self, another):\n IsVector(another)\n return self.x * another.y - self.y * another.x\n\n # 向量点乘\n def mult_d(self, another):\n IsVector(another)\n return self.x * another.x + self.y * another.y\n\n # 向量的模\n def value(self):\n return (self.x ** 2 + self.y ** 2) ** 0.5\n\n # 向量的单位向量\n def unit(self):\n return vector(self.x / self.value(), self.y / self.value())\n\n # 向量的左垂直向量\n def vert_left(self, m=1):\n return vector(-self.y, self.x).unit().mult_num(m)\n\n # 向量的右垂直向量\n def vert_right(self, m=1):\n return vector(self.y, -self.x).unit().mult_num(m)\n\n # 两向量夹角\n def angle(self, another=None):\n if another == None:\n return math.acos(self.x / self.value()) * (self.y / abs(self.y)) * 180 / math.pi\n else:\n IsVector(another)\n return math.acos(self.mult_d(another) / (self.value() * another().value())) * (\n self.y / abs(self.y)) * 180 / math.pi\n\n\n# 点类\nclass point():\n def __init__(self, _x, _y):\n self.x = _x\n self.y = _y\n\n # 两点生成向量\n def ToVector(self, another=None):\n if another == None:\n return vector(self.x, self.y)\n else:\n newx = self.x - another.x\n newy = self.y - another.y\n return vector(newx, newy)\n\n # 点根据向量移动\n def plus_vector(self, v):\n IsVector(v)\n return point(self.x + v.x, self.y + v.y)\n\n # 两点之间距离\n def distance(self, another):\n IsPoint(another)\n return ((self.x - another.x) ** 2 + (self.y - another.y) ** 2) ** 0.5\n\n # 打印点\n def print(self):\n print(\"( {:.2f}, {:.2f} )\".format(self.x, self.y))\n\n # 画点\n def draw(self):\n plt.plot(self.x, self.y, 'ro')\n\n\n# 线类\nclass line():\n def __init__(self, _sp, _ep):\n self.startpoint = _sp\n self.endpoint = _ep\n self.vector = vector(_ep.x - _sp.x, _ep.y - _sp.y)\n\n # 两线交点\n def point_inter(self, another):\n IsLine(another)\n if Intersect_Line(self, another):\n area1 = abs(\n self.startpoint.ToVector(another.startpoint).mult_x(self.startpoint.ToVector(another.endpoint))) / 2\n area2 = abs(self.endpoint.ToVector(another.startpoint).mult_x(self.endpoint.ToVector(another.endpoint))) / 2\n newx = (area1 * self.endpoint.x - area2 * self.startpoint.x) / (area1 - area2)\n newy = (self.vector.y / self.vector.x) * (newx - self.startpoint.x) + self.startpoint.y\n return point(newx, newy)\n\n # 线方向翻转\n def reverse(self):\n newsp = self.endpoint\n newep = self.startpoint\n return line(newep, newsp)\n\n # 打印线\n def print(self):\n print(\"line( ( {:.2f}, {:.2f} ), ( {:.2f}, {:.2f} ) )\".format(self.startpoint.x, self.startpoint.y,\n self.endpoint.x, self.endpoint.y))\n\n # 画线\n def draw(self):\n plt.plot([self.startpoint.x, self.endpoint.x], [self.startpoint.y, self.endpoint.y], \"b\")\n\n\n# 折线类\nclass polyline():\n def __init__(self, _list_p=[]):\n if not isinstance(_list_p, list):\n raise ValueError(\"not an object of class list\")\n elif len(_list_p) < 2:\n raise ValueError(\"require at least two points in this list\")\n else:\n for p in _list_p:\n IsPoint(p)\n self.list_p = _list_p\n self.side = len(_list_p)\n _list_l = []\n for i in range(len(self.list_p) - 1):\n point1 = self.list_p[i]\n point2 = self.list_p[i + 1]\n _list_l.append(line(point1, point2))\n self.list_l = _list_l\n\n # 折线段闭合为多边形\n def ToPolygon(self):\n if self.side == 2:\n raise ValueError(\"require at least three points in this list\")\n else:\n return polygon(self.list_p)\n\n def draw(self):\n for line_i in self.list_l:\n line_i.draw()\n\n # 打印折线段\n def print(self):\n print(\"polyline(\")\n for line_i in self.list_l:\n line_i.print()\n print(\")\")\n\n\n# 简单多边形类\nclass polygon():\n def __init__(self, _list_p=[]):\n if not isinstance(_list_p, list):\n raise ValueError(\"not an object of class list\")\n elif len(_list_p) < 3:\n raise ValueError(\"require at least three points in this list\")\n else:\n for p in _list_p:\n IsPoint(p)\n self.list_p = _list_p\n self.side = len(_list_p)\n _list_l = []\n for i in range(len(self.list_p) - 1):\n point1 = self.list_p[i]\n point2 = self.list_p[i + 1]\n _list_l.append(line(point1, point2))\n _list_l.append(line(point2, self.list_p[0]))\n self.list_l = _list_l\n i = 1\n _list_n = []\n for p in _list_p:\n node_i = node(p, i)\n _list_n.append(node_i)\n i += 1\n _list_n[i - 2].index = 0\n self.list_n = _list_n\n\n # 多边形的范围\n def content(self):\n content = {\"xmin\": self.list_p[0].x, \"xmax\": self.list_p[0].x, \"ymin\": self.list_p[0].y,\n \"ymax\": self.list_p[0].y}\n for p in self.list_p:\n if p.x < content[\"xmin\"]:\n content[\"xmin\"] = p.x\n elif p.x > content[\"xmax\"]:\n content[\"xmax\"] = p.x\n if p.y < content[\"ymin\"]:\n content[\"ymin\"] = p.y\n elif p.y > content[\"ymax\"]:\n content[\"ymax\"] = p.y\n return content\n\n def print(self):\n print(\"polygon(\")\n for p in self.list_p:\n p.print()\n print(\")\")\n\n\n# 圆类\nclass circle():\n def __init__(self, _cp, _r):\n self.centerpoint = _cp\n self.r = _r\n\n # 画圆\n def draw(self):\n cir = Circle(xy=(self.centerpoint.x, self.centerpoint.y), radius=self.r)\n ax.add_patch(cir)\n\n\n# 矩形类\nclass rectangle():\n def __init__(self, _p, _w, _h, _a):\n self.point = _p\n self.width = _w\n self.height = _h\n self.angle = _a\n\n # 画矩形\n def draw(self):\n rec = Rectangle((self.point.x, self.point.y), self.width, self.height, angle=self.angle)\n ax.add_patch(rec)\n\n\n# 复杂多边形类\nclass polygon_complex():\n def __init__(self, _list_la=[]):\n self.list_la = _list_la\n\n # 打印复杂多边形\n def print(self):\n for pln in self.list_la:\n pln.print()\n\n\n# 检测类\ndef IsVector(v):\n if not isinstance(v, vector):\n raise ValueError(\"not an object of class vector\")\n\n\ndef IsPoint(v):\n if not isinstance(v, point):\n raise ValueError(\"not an object of class point\")\n\n\ndef IsLine(v):\n if not isinstance(v, line):\n raise ValueError(\"not an object of class line\")\n\n\n# 折线段拐向\ndef turn_Line(v1, v2):\n IsVector(v1)\n IsVector(v2)\n value = v1.mult_x(v2)\n if value > 0:\n return \"left\"\n elif value < 0:\n return \"right\"\n elif v1.unit() == v1.unit():\n return \"collinear\"\n else:\n return \"reverse\"\n\n\n# 点是否在线上\ndef On_Line(p, l):\n IsPoint(p)\n IsLine(l)\n v0 = p.ToVector()\n v1 = l.startpoint.ToVector()\n v2 = l.endpoint.ToVector()\n value = v2.sub(v0).mult_x(v1.sub(v0))\n if value == 0:\n return True\n else:\n return False\n\n\n# 两直线段是否相交\ndef Intersect_Line(l1, l2):\n p1 = l1.startpoint\n p2 = l1.endpoint\n p3 = l2.startpoint\n p4 = l2.endpoint\n value1 = p4.ToVector(p1).mult_x(p3.ToVector(p1))\n value2 = p4.ToVector(p2).mult_x(p3.ToVector(p2))\n value3 = p2.ToVector(p3).mult_x(p1.ToVector(p3))\n value4 = p2.ToVector(p4).mult_x(p1.ToVector(p4))\n if value1 * value2 == 0 and value3 * value4 == 0:\n if On_Line(p1, l2) or On_Line(p2, l2):\n return True\n else:\n return False\n elif value1 * value2 <= 0 and value3 * value4 <= 0:\n return True\n else:\n return False\n\n\ndef Intersect_Polyline(l, pl):\n for line_i in pl.list_l:\n if Intersect_Line(l, line_i):\n return True\n return False\n\n\n# 点是否在多边形内\ndef contain_polygan(p, polygon):\n line0 = line(p, point(p.x, polygon.content()[\"ymin\"]))\n n_inter = 0\n for line_i in polygon.list_l:\n if On_Line(p, line_i):\n return False\n elif Intersect_Line(line0, line_i):\n n_inter += 1\n if n_inter // 2 == n_inter:\n return False\n else:\n return True\n\n\n# 模拟器\nclass simulation():\n def __init__(self):\n pass\n\n def point(self):\n x = random.randint(0, 100) / 10\n y = random.randint(0, 100) / 10\n return point(x, y)\n\n def vector(self):\n point1 = self.point()\n point2 = self.point()\n return point1.ToVector(point2)\n\n def line(self):\n point1 = self.point()\n point2 = self.point()\n return line(point1, point2)\n\n def polygon(self):\n line0 = self.line()\n list_p = [line0.startpoint, line0.endpoint]\n point0 = self.point()\n list_p.append(point0)\n point_i = list_p[-1]\n n = random.randint(2, 10)\n for i in range(n - 2):\n point_i = self.point()\n while Intersect_Polyline(line(list_p[-1], point_i), polyline(list_p[:-1])):\n point_i = self.point()\n list_p.append(point_i)\n while Intersect_Polyline(line(list_p[0], point_i), polyline(list_p[1:-1])):\n point_i = self.point()\n list_p[-1] = point_i\n return polygon(list_p)\n\n def polyline(self, n=None):\n line0 = self.line()\n list_p = [line0.startpoint, line0.endpoint]\n point0 = self.point()\n list_p.append(point0)\n point_i = list_p[-1]\n if n == None:\n n = random.randint(2, 5)\n for i in range(n - 2):\n point_i = self.point()\n while Intersect_Polyline(line(list_p[-1], point_i), polyline(list_p[:-1])):\n point_i = self.point()\n list_p.append(point_i)\n return polyline(list_p)\n\n\n# 折线段缓冲区\ndef buffer_polyline(pl, d):\n buffer = []\n for p in pl.list_p:\n circle_i = circle(p, d)\n buffer.append(circle_i)\n circle_i.draw()\n for l in pl.list_l:\n p = l.startpoint.plus_vector(l.vector.vert_right(d))\n w = l.vector.value()\n h = 2 * d\n a = l.vector.angle()\n rectangle_i = rectangle(p, w, h, a)\n buffer.append(rectangle_i)\n rectangle_i.draw()\n return polygon_complex(buffer)\n\n\n# 主程序(折线段拐向)\npolyline1 = simulation().polyline(2)\nvector1 = polyline1.list_l[0].vector\nvector2 = polyline1.list_l[1].vector\nturn = turn_Line(vector1, vector2)\nprint(\"此为检测1(折线段拐向)\\n随机折线段为:\")\npolyline1.print()\nprint(\"拐向为{}\".format(turn))\n\n# 主程序(点是否在线上)\npoint1 = simulation().point()\nline1 = simulation().line()\nOnlineorNot = On_Line(point1, line1)\nprint(\"此为检测2(点是否在线上)\\n随机点为:\")\npoint1.print()\nprint(\"随机线为:\")\nline1.print()\nif OnlineorNot:\n print(\"点在线上\")\nelse:\n print(\"点不在线上\")\n\n# 主程序(两直线段相交及其交点)\nline2 = simulation().line()\nline3 = simulation().line()\nIntersectorNot = Intersect_Line(line2, line3)\nprint(\"此为检测3(两直线段相交及其交点)\\n随机直线段为:\")\nline2.print()\nline3.print()\nif IntersectorNot:\n print(\"两直线段相交,且交点为:\")\n point2 = line2.point_inter(line3)\n point2.print()\nelse:\n print(\"两直线段不相交\")\n\n# 主程序(点是否在多边形内)\npoint3 = simulation().point()\npolygon1 = simulation().polygon()\nInpolygonorNot = contain_polygan(point3, polygon1)\nprint(\"此为检测4(点是否在多边形内)\\n随机点为:\")\npoint3.print()\nprint(\"随机多边形为:\")\npolygon1.print()\nif IntersectorNot:\n print(\"点在多边形内\")\nelse:\n print(\"点不在多边形内\")\n\n# 主程序(折线段的缓冲区)\nfig = plt.figure()\nax = fig.add_subplot()\nplt.xlim(-2, 12)\nplt.ylim(-2, 12)\npolyline2 = simulation().polyline()\nprint(\"此为检测5(折线段的缓冲区)\\n随机折线段为:\")\npolyline2.print()\npolyline2.draw()\nd = 1\nbuffer = buffer_polyline(polyline2, d)\nplt.show()\nprint(\"缓冲区请见图\")\n","sub_path":"sundry/topology2.0.py","file_name":"topology2.0.py","file_ext":"py","file_size_in_byte":13747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"590479790","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.arange(0., 150., 0.2)\ny1 = (-2*x)+180\ny2 = (-x+160)/2\ny3 = -x+100\ny4 = [0] * len(x)\ny5 = [0] * len(x)\n\nplt.plot([],[],color='aquamarine', label='Región Solución', linewidth=5)\nplt.plot([],[],color='m', label='Ecuación 1', linewidth=5)\nplt.plot([],[],color='r', label='Ecuación 2', linewidth=5)\nplt.plot([],[],color='g', label='Ecuación 3', linewidth=5)\nplt.plot([],[],color='orange', label='Ecuación 4', linewidth=5)\nplt.plot([],[],color='y', label='Ecuación 5', linewidth=5)\n\nplt.plot(x , y1 , 'm')\nplt.plot(x , y2 , 'r')\nplt.plot(x , y3 , 'g')\nplt.plot(x , y4 , 'orange')\nplt.plot(y5 , x , 'y')\nplt.plot(40 , 60 , color='k' , marker='o')\nplt.plot(0 , 0 , color='k' , marker='o')\nplt.plot(90 , 0 , color='k' , marker='o')\nplt.plot(80 , 20 , color='k' , marker='o')\nplt.plot(0 , 80 , color='k' , marker='o')\n\nplt.fill_between(x,y4,y3, color='aquamarine', interpolate=True)\nplt.fill_between(x,y2,y3, color='w', interpolate=True)\nplt.fill_between(x,y1,y3, color='w', interpolate=True)\n\nplt.title('Ejercicio 6')\nplt.ylabel('y')\nplt.xlabel('x')\n\nplt.text(40,60,'(40,60)',fontsize=10)\nplt.text(0,0,'(0,0)',fontsize=10)\nplt.text(90,0,'(90,0)',fontsize=10)\nplt.text(80,20,'(80,20)',fontsize=10)\nplt.text(0,80,'(0,80)',fontsize=10)\nplt.text(20,-100,'MAX P(40,60)=520',fontsize=15)\n\nplt.legend(loc='upper right')\n\nplt.show()","sub_path":"Ejercicio6.py","file_name":"Ejercicio6.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"509173654","text":"#! /usr/bin/env python3\n\n# Copyright (c) 2012-2019, Compiler Explorer Authors\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# * 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# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport argparse\nimport json\nimport os\nimport pprint\nimport re\nimport sys\nimport tarfile\nimport urllib\nfrom urllib import parse, request\n\ntry:\n from bs4 import BeautifulSoup\nexcept ImportError:\n raise ImportError(\n \"Please install BeautifulSoup (apt-get install python3-bs4 or pip install beautifulsoup4 should do it)\"\n )\n\nparser = argparse.ArgumentParser(\n description=\"Docenizes HTML version of the official Intel Asm PDFs\"\n)\nparser.add_argument(\n \"-i\",\n \"--inputfolder\",\n type=str,\n help=\"Folder where the input files reside as .html. Default is ./generated/asm-docs\",\n default=\"generated/asm-docs\",\n)\nparser.add_argument(\n \"-o\",\n \"--outputdir\",\n type=str,\n help=\"Output directory for the generated JSON files. Default is ./generated\",\n default=\"generated\",\n)\nparser.add_argument(\n \"-d\",\n \"--downloadfolder\",\n type=str,\n help=\"Folder where the archive will be downloaded and extracted. Default is ./generated/asm-docs\",\n default=\"generated/asm-docs\",\n)\n\n# The maximum number of paragraphs from the description to copy.\nMAX_DESC_PARAS = 25\nSTRIP_PREFIX = re.compile(\n r\"^(([0-9a-fA-F]{2}|m64|NP|(REX|E?VEX\\.)[.0-9A-Z]*|/[0-9a-z]+|[a-z]+)\\b\\s*)*\"\n)\nINSTRUCTION_RE = re.compile(r\"^([A-Z][A-Z0-9]+)\\*?(\\s+|$)\")\n# Some instructions are so broken we just take their names from the filename\nUNPARSEABLE_INSTR_NAMES = [\"PSRLW:PSRLD:PSRLQ\", \"PSLLW:PSLLD:PSLLQ\", \"MOVBE\"]\n# Some files contain instructions which cannot be parsed and which compilers are unlikely to emit\nIGNORED_FILE_NAMES = [\n \"._404\",\n \"404\",\n \"index\",\n # SGX pseudo-instructions\n \"EADD\",\n \"EACCEPT\",\n \"EAUG\",\n \"EACCEPTCOPY\",\n \"EDECVIRTCHILD\",\n \"EINCVIRTCHILD\",\n \"EINIT\",\n \"ELDB:ELDU:ELDBC:ELBUC\",\n \"EMODPE\",\n \"EMODPR\",\n \"EMODT\",\n \"ERDINFO\",\n \"ESETCONTEXT\",\n \"ETRACKC\",\n \"EBLOCK\",\n \"ECREATE\",\n \"EDBGRD\",\n \"EDBGWR\",\n \"EENTER\",\n \"EEXIT\",\n \"EEXTEND\",\n \"EGETKEY\",\n \"ELDB\",\n \"ELDU\",\n \"ENCLS\",\n \"ENCLU\",\n \"EPA\",\n \"EREMOVE\",\n \"EREPORT\",\n \"ERESUME\",\n \"ETRACK\",\n \"EWB\",\n # VMX instructions\n \"INVEPT\",\n \"INVVPID\",\n \"VMCALL\",\n \"VMCLEAR\",\n \"VMFUNC\",\n \"VMLAUNCH\",\n \"VMLAUNCH:VMRESUME\",\n \"VMPTRLD\",\n \"VMPTRST\",\n \"VMREAD\",\n \"VMRESUME\",\n \"VMWRITE\",\n \"VMXOFF\",\n \"VMXON\",\n # Other instructions\n \"INVLPG\",\n \"LAHF\",\n \"RDMSR\",\n \"SGDT\",\n # Unparsable instructions\n # These instructions should be supported in the future\n \"MONITOR\",\n \"MOVDQ2Q\",\n \"MFENCE\",\n]\n# Some instructions are defined in multiple files. We ignore a specific set of the\n# duplicates here.\nIGNORED_DUPLICATES = [\n \"MOV-1\", # move to control reg\n \"MOV-2\", # move to debug reg\n \"CMPSD\", # compare doubleword (defined in CMPS:CMPSB:CMPSW:CMPSD:CMPSQ)\n \"MOVQ\", # defined in MOVD:MOVQ\n \"MOVSD\", # defined in MOVS:MOVSB:MOVSW:MOVSD:MOVSQ\n \"VPBROADCASTB:VPBROADCASTW:VPBROADCASTD:VPBROADCASTQ\", # defined in VPBROADCAST\n \"VGATHERDPS:VGATHERDPD\",\n \"VGATHERQPS:VGATHERQPD\",\n \"VPGATHERDD:VPGATHERQD\",\n \"VPGATHERDQ:VPGATHERQQ\",\n]\n# Where to extract the asmdoc archive.\nASMDOC_DIR = \"asm-docs\"\nARCHIVE_URL = \"https://www.felixcloutier.com/x86/x86.tbz2\"\nARCHIVE_NAME = \"x86.tbz2\"\n\n\nclass Instruction(object):\n def __init__(self, name, variants, variant_descriptions, tooltip, body):\n self.name = name\n self.variants = variants\n self.variant_descriptions = variant_descriptions\n self.tooltip = tooltip.rstrip(\": ,\")\n self.body = body\n\n def __str__(self):\n return f\"Instruction<{self.name}>\"\n\n\ndef get_url_for_instruction(instr):\n return f\"https://www.felixcloutier.com/x86/{urllib.parse.quote(instr.name)}.html\"\n\n\ndef download_asm_doc_archive(downloadfolder):\n if not os.path.exists(downloadfolder):\n print(f\"Creating {downloadfolder} as download folder\")\n os.makedirs(downloadfolder)\n elif not os.path.isdir(downloadfolder):\n print(f\"Error: download folder {downloadfolder} is not a directory\")\n sys.exit(1)\n archive_name = os.path.join(downloadfolder, ARCHIVE_NAME)\n print(\"Downloading archive...\")\n urllib.request.urlretrieve(ARCHIVE_URL, archive_name)\n\n\ndef extract_asm_doc_archive(downloadfolder, inputfolder):\n print(\"Extracting file...\")\n if os.path.isdir(os.path.join(inputfolder, \"html\")):\n for root, dirs, files in os.walk(os.path.join(inputfolder, \"html\")):\n for file in files:\n if os.path.splitext(file)[1] == \".html\":\n os.remove(os.path.join(root, file))\n tar = tarfile.open(os.path.join(downloadfolder, ARCHIVE_NAME))\n tar.extractall(path=inputfolder)\n\n\ndef strip_non_instr(i):\n # removes junk from encodings where the opcode is in the middle\n # of prefix stuff. e.g.\n # 66 0f 38 30 /r PMOVZXBW xmm1, xmm2/m64\n return STRIP_PREFIX.sub(\"\", i)\n\n\ndef instr_name(i):\n match = INSTRUCTION_RE.match(strip_non_instr(i))\n if match:\n return match.group(1)\n\n\ndef get_description_paragraphs(document_soup):\n description_header_node = document_soup.find(id=\"description\")\n i = 0\n description_paragraph_node = description_header_node.next_sibling.next_sibling\n description_paragraphs = []\n while i < MAX_DESC_PARAS and len(description_paragraph_node.text) > 20:\n if description_paragraph_node.name == \"p\":\n description_paragraphs.append(description_paragraph_node)\n i = i + 1\n # Move two siblings forward. Next sibling is the line feed.\n description_paragraph_node = (\n description_paragraph_node.next_sibling.next_sibling\n )\n return description_paragraphs\n\n\ndef parse(filename, f):\n doc = BeautifulSoup(f, \"html.parser\")\n if doc.table is None:\n print(f\"{filename}: Failed to find table\")\n return None\n table = read_table(doc.table)\n variants = set()\n variant_descriptions = {}\n\n for inst in table:\n for op_key in [\n \"Opcode/Instruction\",\n \"OpcodeInstruction\",\n \"Opcode Instruction\",\n \"Opcode*/Instruction\",\n \"Opcode / Instruction\",\n \"Instruction\",\n ]:\n if op_key not in inst:\n continue\n\n variant = instr_name(inst[op_key])\n if not variant:\n continue\n\n variants.add(variant)\n variant_descriptions[variant] = inst.get(\"Description\")\n break\n\n if not variants:\n if filename in UNPARSEABLE_INSTR_NAMES:\n for name in filename.split(\":\"):\n variants.add(name)\n else:\n print(f\"{filename}: Failed to read instruction table\")\n return None\n\n description_paragraphs = get_description_paragraphs(doc)\n\n for para in description_paragraphs:\n for link in para.find_all(\"a\"):\n # this urljoin will only ensure relative urls are prefixed\n # if a url is already absolute it does nothing\n link[\"href\"] = urllib.parse.urljoin(\n \"https://www.felixcloutier.com/x86/\", link[\"href\"]\n )\n link[\"target\"] = \"_blank\"\n link[\"rel\"] = \"noreferrer noopener\"\n\n return Instruction(\n filename,\n variants,\n variant_descriptions,\n description_paragraphs[0].text.strip(),\n \"\".join(map(lambda x: str(x), description_paragraphs)).strip(),\n )\n\n\ndef read_table(table):\n # Finding all 'th' is not enough, since some headers are 'td'.\n # Instead, walk through all children of the first 'tr', filter out those\n # that are only whitespace, keep `get_text()` on the others.\n headers = list(\n map(\n lambda th: th.get_text(),\n filter(lambda th: str(th).strip(), table.tr.children),\n )\n )\n\n result = []\n if headers:\n # common case\n for row in table.find_all(\"tr\"):\n obj = {}\n for column, name in zip(row.find_all(\"td\"), headers):\n # Remove '\\n's in names that contain it.\n obj[name.replace(\"\\n\", \"\")] = column.get_text()\n if obj:\n result.append(obj)\n else:\n # Cases like BEXTR and BZHI\n rows = table.find_all(\"tr\")\n if len(rows) != 1:\n return []\n obj = {}\n for td in rows[0].find_all(\"td\"):\n header = td.p.strong.get_text()\n td.p.strong.decompose()\n obj[header] = td.get_text()\n result.append(obj)\n\n return result\n\n\ndef parse_html(directory):\n print(\"Parsing instructions...\")\n instructions = []\n for root, dirs, files in os.walk(directory):\n for file in files:\n if file.endswith(\".html\"):\n with open(os.path.join(root, file), encoding=\"utf-8\") as f2:\n name = os.path.splitext(file)[0]\n if name in IGNORED_DUPLICATES or name in IGNORED_FILE_NAMES:\n continue\n try:\n instruction = parse(name, f2)\n if not instruction:\n continue\n patch_instruction(instruction)\n instructions.append(instruction)\n except Exception as e:\n print(f\"Error parsing {name}:\\n{e}\")\n return instructions\n\n\ndef self_test(instructions, directory):\n # For each generated instruction, check that there is a path to a file in\n # the documentation.\n directory = os.path.join(directory, \"html\")\n ok = True\n for inst in instructions:\n if not os.path.isfile(os.path.join(directory, inst.name + \".html\")):\n print(f\"Warning: {inst.name} has not file associated\")\n ok = False\n return ok\n\n\ndef patch_instruction(instruction):\n if instruction.name == \"ADDSS\":\n print(\"\\nPatching ADDSS\")\n print(\n \"REMINDER: Check if https://github.com/compiler-explorer/compiler-explorer/issues/2380 is still relevant\\n\"\n )\n\n old_body = instruction.body\n old_tooltip = instruction.tooltip\n instruction.body = old_body.replace(\n \"stores the double-precision\", \"stores the single-precision\"\n )\n instruction.tooltip = old_tooltip.replace(\n \"stores the double-precision\", \"stores the single-precision\"\n )\n\n\ndef trim_str(str, max_len=255):\n return (str[:max_len] + \"...\") if len(str) > max_len else str\n\n\ndef main():\n args = parser.parse_args()\n print(f\"Called with: {args}\")\n\n # If we don't have the html folder already...\n if not os.path.isdir(os.path.join(args.inputfolder, \"html\")):\n # We don't, try with the compressed file\n if not os.path.isfile(os.path.join(args.downloadfolder, \"x86.tbz2\")):\n # We can't find that either. Download it\n try:\n download_asm_doc_archive(args.downloadfolder)\n extract_asm_doc_archive(args.downloadfolder, args.inputfolder)\n except IOError as e:\n print(\"Error when downloading archive:\")\n print(e)\n sys.exit(1)\n else:\n # We have a file already downloaded\n extract_asm_doc_archive(args.downloadfolder, args.inputfolder)\n\n instructions = parse_html(args.inputfolder)\n instructions.sort(key=lambda b: b.name)\n\n all_inst = set()\n for inst in instructions:\n if not all_inst.isdisjoint(inst.variants):\n print(\n f\"Overlap in instruction variants: {inst.variants.intersection(all_inst)} for {inst.name}\"\n )\n all_inst = all_inst.union(inst.variants)\n\n if not self_test(instructions, args.inputfolder):\n print(\"Tests do not pass. Not writing output file. Aborting.\")\n sys.exit(3)\n\n print(f\"Writing {len(instructions)} instructions\")\n\n autocomplete_path = os.path.join(args.outputdir, \"autocomplete.json\")\n with open(autocomplete_path, \"w\") as f:\n autocomplete = {}\n for inst in instructions:\n autocomplete[inst.name.upper()] = {\n \"_\": inst.name.lower(),\n \"*\": inst.tooltip,\n }\n for variant in inst.variants:\n autocomplete[variant.upper()] = {\n \"_\": inst.name.lower(),\n \"*\": inst.variant_descriptions.get(variant, trim_str(inst.tooltip)),\n }\n json.dump(autocomplete, f, separators=(\",\", \":\"))\n\n full_path = os.path.join(args.outputdir, \"full.json\")\n with open(full_path, \"w\") as f:\n full = []\n for inst in instructions:\n full.append(\n {\n \"id\": inst.name.lower(),\n \"variants\": list(inst.variants),\n \"variant_descriptions\": inst.variant_descriptions,\n \"text\": inst.body,\n \"href\": get_url_for_instruction(inst),\n }\n )\n json.dump(full, f, indent=2)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bin/docenizer.py","file_name":"docenizer.py","file_ext":"py","file_size_in_byte":14501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"257891361","text":"import os\n\nfrom worker import Worker\n\n\nclass Application(object):\n\n USER_AGENT = ('Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36'\n ' (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36')\n\n BROWSER_SIZE = (1280, 1024)\n\n MAIN_PAGE_URL = 'https://www.instagram.com/'\n\n browser = None\n following_list = None\n following_count = None\n\n def __init__(self, arguments):\n self.config = arguments\n\n self.check_config()\n\n self.following_list = []\n self.following_count = 0\n\n def check_config(self):\n if self.config.un_follow_only:\n if not self.config.un_follow:\n raise AttributeError('Un-follow option is required.')\n\n if self.config.un_follow:\n if not os.path.exists(self.config.un_follow):\n raise AttributeError('Un-follow file was not found.')\n self.read_unfollow_list()\n\n def run(self):\n Worker.set_application(self)\n Worker.start_browser()\n Worker.start_scenarios()\n\n self.close()\n\n if not self.config.un_follow_only:\n self.save_to_csv()\n\n def close(self):\n # Close browser\n if self.browser:\n self.browser.close()\n self.browser.quit()\n self.browser = None\n\n def save_to_csv(self):\n with open('{}.csv'.format(self.config.output), 'w') as csv:\n csv.write('\\n'.join(self.following_list))\n\n def read_unfollow_list(self):\n with open(self.config.un_follow, 'r') as csv:\n self.unfollowing_list = csv.read().split('\\n')\n","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"50979603","text":"from flask import (\n Flask, render_template, request, flash,\n url_for, redirect, session, make_response\n)\nfrom werkzeug.utils import secure_filename\nimport pandas as pd\nimport rsa\nimport base64\nfrom phe import paillier\nimport json\nimport io\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'dev'\n# public_phe, private_phe = paillier.generate_paillier_keypair()\nwith open(\"keys/homo.phe\", \"r\") as f:\n js = json.load(f)\npublic_phe = paillier.PaillierPublicKey(int(js['pub']))\nprivate_phe = paillier.PaillierPrivateKey(\n public_phe, int(js['p']), int(js['q']))\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n id = int(request.form.get('id'))\n data = pd.read_csv(\"user.csv\")\n\n if len(data.loc[data.id == id]) == 0:\n flash(\"用户不存在,请先申请安全令!\")\n return render_template('register.html')\n\n session['id'] = id\n if (data.loc[data.id == id].identity == \"Null\").any():\n return redirect(url_for('set'))\n\n return redirect(url_for('authentication'))\n\n return render_template('index.html')\n\n\n@app.route('/set', methods=['GET', 'POST'])\ndef set():\n if request.method == 'POST':\n idtt = base64.b64decode(request.form.get('psw').encode())\n data = pd.read_csv(\"user.csv\")\n\n pri_str = base64.b64decode(data.loc[data.id == int(\n session['id']), 'privateKey'].values[0].encode())\n pri = rsa.PrivateKey.load_pkcs1(pri_str)\n content = base64.b64encode(rsa.decrypt(idtt, pri)).decode()\n\n data.loc[data.id == int(session['id']), 'identity'] = content\n data.to_csv(\"user.csv\", index=False)\n flash(\"设置成功,请登录!\")\n return redirect(url_for('authentication'))\n\n return render_template('set.html')\n\n\n@app.route('/authentication', methods=['GET', 'POST'])\ndef authentication():\n if request.method == 'POST':\n try:\n idtt = base64.b64decode(request.form.get('psw').encode())\n data = pd.read_csv(\"user.csv\")\n\n pri_str = base64.b64decode(data.loc[data.id == int(\n session['id']), 'privateKey'].values[0].encode())\n pri = rsa.PrivateKey.load_pkcs1(pri_str)\n\n content = base64.b64encode(rsa.decrypt(idtt, pri)).decode()\n if (data[data.id == int(session['id'])]\n .identity == content).any():\n if (data[data.id == int(session['id'])]\n .status == \"教师\").any():\n return (redirect(url_for('upload')))\n else:\n return(redirect(url_for('download')))\n except Exception as e:\n print(\"------\", session['id'], \"------\", e)\n\n flash(\"鉴别码错误!\")\n\n return render_template('authentication.html')\n\n\n@app.route('/upload', methods=['GET', 'POST'])\ndef upload():\n if request.method == 'POST':\n course = request.form.get('course')\n credit = request.form.get('credit')\n\n f = request.files['file']\n place = \"transcripts/\"+secure_filename(f.filename)\n f.save(place)\n\n mark = pd.read_csv('mark.csv')\n if (mark.course == course).any():\n flash(\"该科成绩已有记录,请勿重复上传!\")\n return render_template('upload.html')\n\n data = pd.read_csv(place).iloc[:, 1:]\n\n # 明文加密成密文,打包成json\n def f(x):\n cipher = public_phe.encrypt(float(x))\n return json.dumps(\n {'text': str(cipher.ciphertext()),\n 'exponent': cipher.exponent})\n data['mark'] = data['mark'].map(f)\n\n # 加入课程名和学分,组合成新的表\n data['course'] = [course for i in range(len(data))]\n data['credit'] = [credit for i in range(len(data))]\n data = pd.concat([mark, data])\n\n data.to_csv(\"mark.csv\", index=False)\n flash(course+\" 成绩上传成功!\")\n\n return render_template('upload.html')\n\n\n@app.route('/download', methods=['GET', 'POST'])\ndef download():\n if request.method == 'POST':\n df = pd.read_csv('mark.csv')\n mark = df[df.id == int(session['id'])]\n\n def f(x):\n x = json.loads(x)\n return paillier.EncryptedNumber(public_phe, int(x['text']), int(x['exponent']))\n mark['mark'] = mark['mark'].map(f)\n\n grade = 0\n for i, v in mark['mark'].items():\n # print(private_phe.decrypt(mark.at[i, 'mark']))\n # print(mark.at[i, 'mark'], int(mark.at[i, 'credit']))\n grade += mark.at[i, 'mark'] * int(mark.at[i, 'credit'])\n mark.loc[len(mark)] = (\"Final Grade:\",\n grade/mark.credit.sum(),\n \",\".join(mark.course.value_counts().keys()),\n mark.credit.sum())\n\n def g(x):\n return json.dumps(\n {'text': str(x.ciphertext()),\n 'exponent': x.exponent})\n\n mark['mark'] = mark['mark'].map(g)\n\n out = io.StringIO()\n mark.to_csv(out, index=False)\n file_name = str(session['id']) + '.csv'\n response = make_response(out.getvalue())\n response.headers[\"Content-Disposition\"] = \"attachment; filename=%s\" % file_name\n response.headers[\"Content-type\"] = \"text/csv\"\n return response\n\n mark = pd.read_csv('mark.csv')\n flash('您已结算成绩的课程有:'+', '.join(mark.course.value_counts().index))\n return render_template('download.html')\n\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n if request.method == 'POST':\n id = request.form.get('id')\n name = request.form.get('name')\n status = request.form.get('status')\n data = pd.read_csv(\"user.csv\")\n\n if len(data.loc[data.id == id]) > 0:\n flash(\"你已经申请过安全令,请勿重复!\")\n return render_template('register.html')\n\n (pub, pri) = rsa.newkeys(512)\n pub = pub.save_pkcs1()\n pri = pri.save_pkcs1()\n data.loc[len(data)] = (str(id), name, status,\n \"Null\", base64.b64encode(pri).decode())\n data.to_csv(\"user.csv\", index=False)\n with open(\"./keys/\"+status+name+str(id)+\".pem\", \"wb\") as f:\n f.write(pub)\n\n if status != '教师':\n with open(\"./keys/\"+status+name+str(id)+\".phe\", \"w\") as f:\n json.dump({\"pub\": str(public_phe.n),\n \"p\": str(private_phe.p),\n \"q\": str(private_phe.q)},\n f)\n\n flash(\"成功向教务发送申请!请等待相关人员下发安全令文件。\")\n return render_template('register.html')\n\n return render_template('register.html')\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"498948699","text":"from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest\nfrom django.template import loader, RequestContext\nfrom django.shortcuts import render, render_to_response\nfrom django.views.decorators.csrf import csrf_exempt\nfrom random import randint\nfrom django.views.generic import TemplateView\nfrom chartjs.views.lines import BaseLineChartView\nimport json\n\nfrom .models import Sparse\nfrom sparse_matrix.utils import *\n\n\ndef index(request,):\n template = loader.get_template('sparse_matrix/index.html')\n return HttpResponse(template.render(request))\n\n\ndef output(request, sparse_id):\n return HttpResponse(\"You're looking at processing time %s.\" % sparse_id)\n\n\n@csrf_exempt\ndef result(request):\n '''\n View to add all the tracking resources\n '''\n\n status,response = set_response_header(request=request,response=HttpResponse(content_type='application/json'))\n if not status:\n return HttpResponseBadRequest(json.dumps({\"Message\":\"Unauthorized request\"}),content_type='application/json')\n data = {'result': ''}\n save_in_db = {}\n # file_ = request.FILES.get('input_')\n\n if request.method=='POST':\n file_ = request.POST.get('input_', None)\n \n # import pdb; pdb.set_trace()\n import time\n length_matrix = len(CSM(file_))\n\n start_time1 = time.time()\n encrypt_CSM_linear(file_)\n decrypt_CSM_linear(encrypt_CSM_linear(file_))\n data['result_linear'] = str(time.time() - start_time1)\n\n start_time2 = time.time()\n encrypt_CSM_quadratic(file_)\n decrypt_CSM_quadratic(encrypt_CSM_quadratic(file_))\n data['result_quadratic'] = str(time.time() - start_time2)\n \n start_time3 = time.time()\n encrypt_CSM_cubic(file_)\n decrypt_CSM_cubic(encrypt_CSM_cubic(file_))\n data['result_cubic'] = str(time.time() - start_time3)\n\n save_in_db['processing_time_l'] = data['result_linear']\n save_in_db['processing_time_q'] = data['result_quadratic']\n save_in_db['processing_time_c'] = data['result_cubic']\n save_in_db['length'] = length_matrix\n newSparse = Sparse(**save_in_db)\n length_in_sparse = Sparse.objects.values('length')\n all_lengths = [p['length'] for p in length_in_sparse]\n if length_matrix in all_lengths:\n pass\n else:\n newSparse.save()\n response.write(\"%s\"%(json.dumps(data)))\n return response\n\n\n\n\n\n@csrf_exempt\ndef sparse(request):\n return render_to_response('sparse_matrix/sparse.html', context_instance=RequestContext(request))\n\n\nclass LineChartJSONView(BaseLineChartView):\n def get_labels(self):\n \"\"\"Return 7 labels.\"\"\"\n latest_length_list = Sparse.objects.values(\n 'length').order_by('-id')[:5]\n all_lengths = [p['length'] for p in latest_length_list]\n return all_lengths\n\n def get_data(self):\n \"\"\"Return 3 datasets to plot.\"\"\"\n latest_time_linear = Sparse.objects.values(\n 'processing_time_l').order_by('-length')[:15]\n all_processing_linear = [p1['processing_time_l']\n for p1 in latest_time_linear]\n \n latest_time_quadratic = Sparse.objects.values(\n 'processing_time_q').order_by('-length')[:15]\n all_processing_quadratic = [p1['processing_time_q']\n for p1 in latest_time_quadratic]\n\n latest_time_cubic = Sparse.objects.values(\n 'processing_time_c').order_by('-length')[:15]\n all_processing_cubic = [p1['processing_time_c']\n for p1 in latest_time_cubic]\n # import pdb; pdb.set_trace()\n\n return [all_processing_linear,all_processing_quadratic, all_processing_cubic] \n\n \nline_chart = TemplateView.as_view(template_name='sparse.html')\nline_chart_json = LineChartJSONView.as_view()\n","sub_path":"sparse_matrix/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"373329914","text":"import random\nimport sys\nimport time\n\nimport zmq\n\nfrom kvmsg import KVMsg\n\n\nSUBTREE = b\"/client/\"\n\n\ndef main():\n # Prepare our context and subscriber\n ctx = zmq.Context()\n snapshot = ctx.socket(zmq.DEALER)\n snapshot.linger = 0\n snapshot.connect(\"tcp://localhost:5556\")\n subscriber = ctx.socket(zmq.SUB)\n subscriber.linger = 0\n subscriber.setsockopt(zmq.SUBSCRIBE, SUBTREE)\n subscriber.connect(\"tcp://localhost:5557\")\n publisher = ctx.socket(zmq.PUSH)\n publisher.linger = 0\n publisher.connect(\"tcp://localhost:5558\")\n\n random.seed(time.time())\n kvmap = {}\n\n # Get state snapshot\n sequence = 0\n snapshot.send_multipart([b\"ICANHAZ?\", SUBTREE])\n while True:\n try:\n kvmsg = KVMsg.recv(snapshot)\n except:\n raise\n return # Interrupted\n\n if kvmsg.key == b\"KTHXBAI\":\n sequence = kvmsg.sequence\n print(f\"I: Received snapshot={sequence:d}\")\n break # Done\n kvmsg.store(kvmap)\n\n poller = zmq.Poller()\n poller.register(subscriber, zmq.POLLIN)\n\n alarm = time.time() + 1\n while True:\n tickless = 1000 * max(0, alarm - time.time())\n try:\n items = dict(poller.poll(tickless))\n except:\n break # Interrupted\n\n if subscriber in items:\n kvmsg = KVMsg.recv(subscriber)\n\n # Discard out-of-sequence kvmsgs, incl. heartbeats\n if kvmsg.sequence > sequence:\n sequence = kvmsg.sequence\n kvmsg.store(kvmap)\n print(f\"I: received update={sequence:d}\")\n\n # If we timed-out, generate a random kvmsg\n if time.time() >= alarm:\n kvmsg = KVMsg(0)\n kvmsg.key = SUBTREE + str(random.randint(1, 10000)).encode()\n kvmsg.body = str(random.randint(1, 1000000)).encode()\n kvmsg.send(publisher)\n kvmsg.store(kvmap)\n alarm = time.time() + 1\n\n print(f\"Interrupted\\n{sequence:d} messages in\")\n\n\nif __name__ == '__main__':\n try:\n main()\n except KeyboardInterrupt:\n print('keybord interrupted', file=sys.stderr)\n","sub_path":"clonecli5.py","file_name":"clonecli5.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"237363399","text":"from my_lib import file_processing as fp\nimport re\ntry:\n content = fp.read_file('./input/input_test.txt')\n # print(content)\n content = \" \".join(content)\n content = content.split(\" \")\n content1 = [re.sub('[\\(\\)\\{\\}<>,.]', '', e) for e in content]\n\n print(content)\n c = max(set(content1), key=content1.count)\n\n print(\"character '\",c,\"' with frequency: \", content1.count(c))\nexcept BaseException as b:\n print(\"[Error] : \", b)\nfinally:\n # test_list = [9, 4, 5, 4, 4, 5, 9, 5, 4]\n # res = max(set(test_list), key=test_list.count)\n # print(max(set(test_list)))\n print(\"------------------------\\nhello\")\n print(\"exit\")\n","sub_path":"day-5/inclass/index2.py","file_name":"index2.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"255632812","text":"from nltk import StanfordPOSTagger\nfrom textblob.taggers import BaseTagger\nfrom pprint import pprint\n\n\nclass StanfordPartOfSpeechTagger(BaseTagger):\n \"\"\"An interface for stanford arabic pos\"\"\"\n\n def __init__(self):\n modelPath = 'textblob_ar/data/arabic.tagger'\n modelJar = 'textblob_ar/data/model.jar'\n self._tagger = StanfordPOSTagger(modelPath, modelJar)\n\n def tag(self, text, tokenize=True):\n \"\"\"Return a list of tuples of the form (word, tag)\n for a given set of text or BaseBlob instance.\n \"\"\"\n\n if tokenize:\n tokens = text.tokens\n else:\n tokens = text\n tags = self._tagger.tag(tokens=tokens)\n result = []\n for tag in tags:\n if tag[0]:\n result.append(tuple(tag[1].split('/')))\n else:\n result.append(tag)\n return [i for i in result if len(i) == 2]\n","sub_path":"textblob_ar/pos_tagger.py","file_name":"pos_tagger.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"526583643","text":"\"\"\"Propagating 2D dynamics on the muller potential using OpenMM.\n\nCurrently, we just put a harmonic restraint on the z coordinate,\nsince OpenMM needs to work in 3D. This isn't really a big deal, except\nthat it affects the meaning of the temperature and kinetic energy. So\ntake the meaning of those numbers with a grain of salt.\n\"\"\"\nfrom mixtape.mslds import *\nfrom numpy import array, reshape, savetxt, loadtxt, zeros\nfrom simtk.unit import kelvin, picosecond, femtosecond, nanometer, dalton\nfrom mixtape.utils import *\nimport simtk.openmm as mm\nimport matplotlib.pyplot as pp\nimport numpy as np\nimport sys\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\nclass MullerForce(mm.CustomExternalForce):\n\n \"\"\"OpenMM custom force for propagation on the Muller Potential. Also\n includes pure python evaluation of the potential energy surface so that\n you can do some plotting\"\"\"\n aa = [-1, -1, -6.5, 0.7]\n bb = [0, 0, 11, 0.6]\n cc = [-10, -10, -6.5, 0.7]\n AA = [-200, -100, -170, 15]\n XX = [1, 0, -0.5, -1]\n YY = [0, 0.5, 1.5, 1]\n\n def __init__(self):\n # start with a harmonic restraint on the Z coordinate\n expression = '1000.0 * z^2'\n for j in range(4):\n # add the muller terms for the X and Y\n fmt = dict(aa=self.aa[j], bb=self.bb[j],\n cc=self.cc[j], AA=self.AA[j],\n XX=self.XX[j], YY=self.YY[j])\n expression += '''+ {AA}*exp({aa} *(x - {XX})^2\n + {bb} * (x - {XX}) * (y - {YY})\n + {cc} * (y - {YY})^2)'''.format(**fmt)\n super(MullerForce, self).__init__(expression)\n\n @classmethod\n def potential(cls, x, y):\n \"Compute the potential at a given point x,y\"\n value = 0\n for j in range(4):\n try:\n value += cls.AA[j] * np.exp(\n cls.aa[j] * (x - cls.XX[j]) ** 2 +\n cls.bb[j] * (x - cls.XX[j]) * (y - cls.YY[j]) +\n cls.cc[j] * (y - cls.YY[j]) ** 2)\n except FloatingPointError:\n value = np.exp(100)\n return value\n\n @classmethod\n def plot(cls, ax=None, minx=-1.5, maxx=1.2, miny=-0.2,\n maxy=2, **kwargs):\n \"Plot the Muller potential\"\n grid_width = max(maxx - minx, maxy - miny) / 200.0\n ax = kwargs.pop('ax', None)\n xx, yy = np.mgrid[minx: maxx: grid_width, miny: maxy: grid_width]\n V = cls.potential(xx, yy)\n # clip off any values greater than 200, since they mess up\n # the color scheme\n if ax is None:\n ax = pp\n ax.contourf(xx, yy, V.clip(max=200), 40, **kwargs)\n\n# Now run code\nPLOT = True\nLEARN = True\nNUM_TRAJS = 1\n\n# each particle is totally independent\nnParticles = 1\nmass = 1.0 * dalton\n# temps = 200 300 500 750 1000 1250 1500 1750 2000\ntemperature = 500 * kelvin\nfriction = 100 / picosecond\ntimestep = 10.0 * femtosecond\nT = 500\nsim_T = 1000\n\nx_dim = 2\ny_dim = 2\nK = 3\nNUM_ITERS = 5\n\nAs = zeros((K, x_dim, x_dim))\nbs = zeros((K, x_dim))\nmus = zeros((K, x_dim))\nSigmas = zeros((K, x_dim, x_dim))\nQs = zeros((K, x_dim, x_dim))\n\n# Allocate Memory\nstart = T / 4\nn_seq = 1\nxs = zeros((n_seq, NUM_TRAJS * (T - start), y_dim))\n\nif PLOT:\n # Clear Display\n pp.cla()\n# Choose starting conformations uniform on the grid\n# between (-1.5, -0.2) and (1.2, 2)\n########################################################################\n\nfor traj in range(NUM_TRAJS):\n system = mm.System()\n mullerforce = MullerForce()\n for i in range(nParticles):\n system.addParticle(mass)\n mullerforce.addParticle(i, [])\n system.addForce(mullerforce)\n\n integrator = mm.LangevinIntegrator(temperature, friction, timestep)\n context = mm.Context(system, integrator)\n startingPositions = (np.random.rand(\n nParticles, 3) * np.array([2.7, 1.8, 1])) + np.array([-1.5, -0.2, 0])\n\n context.setPositions(startingPositions)\n context.setVelocitiesToTemperature(temperature)\n\n trajectory = zeros((T, 2))\n for i in range(T):\n x = context.getState(getPositions=True).\\\n getPositions(asNumpy=True).value_in_unit(nanometer)\n # Save the state\n if i > start:\n xs[0, traj * (T-start) + (i-start), :] = x[0, 0:2]\n trajectory[i, :] = x[0, 0:2]\n integrator.step(10)\nif LEARN:\n # Learn the MetastableSwitchingLDS\n l = MetastableSwitchingLDS(K, x_dim, n_iter=NUM_ITERS)\n l.fit(xs)\n sim_xs, sim_Ss = l.sample(sim_T, init_state=0, init_obs=l.means_[0])\n\nif PLOT:\n pp.plot(trajectory[start:, 0], trajectory[start:, 1], color='k')\n pp.scatter(l.means_[:, 0], l.means_[:, 1], color='r', zorder=10)\n pp.scatter(xs[0, :, 0], xs[0,:, 1], edgecolor='none', facecolor='k', zorder=1)\n Delta = 0.5\n minx = min(xs[0, :, 0])\n maxx = max(xs[0, :, 0])\n miny = min(xs[0, :, 1])\n maxy = max(xs[0, :, 1])\n if LEARN:\n minx = min(min(sim_xs[:, 0]), minx) - Delta\n maxx = max(max(sim_xs[:, 0]), maxx) + Delta\n miny = min(min(sim_xs[:, 1]), miny) - Delta\n maxy = max(max(sim_xs[:, 1]), maxy) + Delta\n pp.scatter(sim_xs[:, 0], sim_xs[:, 1], edgecolor='none',\n zorder=5, facecolor='g')\n pp.plot(sim_xs[:, 0], sim_xs[:, 1], zorder=5, color='g')\n MullerForce.plot(ax=pp.gca(), minx=minx, maxx=maxx, miny=miny, maxy=maxy)\n pp.show()\n","sub_path":"example/muller_potential.py","file_name":"muller_potential.py","file_ext":"py","file_size_in_byte":5417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"27864364","text":"'''\nAuthor: Chin-Chwen Tien\nVersion: 1.0\nCreate Date: Tue June 14, 2016\nObjective: Don't just sit in front of the PC all day!!\n'''\n\nimport time\nimport webbrowser\n\ntotalBreak = 3\nbreakCount = 0\n\nprint(\"This program started on \" + time.ctime())\nwhile breakCount < totalBreak:\n\tprint(\"Current Time: \" + time.ctime())\n\ttime.sleep(30 * 60)\n\tprint(\"Take a break!\")\n\twebbrowser.open(\"https://www.youtube.com/watch?v=DDO_aCkivxU\")\n\tbreakCount += 1\n","sub_path":"takeABreak.py","file_name":"takeABreak.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"46768925","text":"import torch\nimport torch.nn.functional as F\nfrom torch import nn, cuda\nfrom torch.autograd import Variable\n\nclass DeadConv2d(nn.Conv2d):\n def __init__(self, *args, **kwargs):\n super(PartialConv2d, self).__init__(*args, **kwargs)\n self.dead_lock = Variable(torch.ones([self.out_channels], requires_grad=False)).cuda() # 用relu控制稀疏性,也可以用tempered softmax控制?\n\n def forward(self, input, mask_in=None):\n assert len(input.shape) == 4\n raw_out = super(PartialConv2d, self).forward(input)\n # 很简单,每个通道的结果乘以一个scalar,初始为1,并且可以控制在何时启动\n # with torch.no_grad():\n for i in range(self.out_channels):\n raw_out[:,i,:,:] *= self.dead_lock[i]\n\n return raw_out\n\n\n # def _trim(self):\n\n\n\n####old\n# 可以通过学习,每个通道可以分别进行死亡的卷积核,c个通道就有c个权重\n# 控制卷积核的死亡,可以让网络一开始训练一个有力的大模型,随后进行自动化的剪支:\n# 1. 一个精心设计的,不太容易死但是一旦死了就很难复活的卷积核\n# 2. 训练的时候固定所有权重,裁剪的时候,网络其他部分不变,仅让这些权重可以学习\n# 3. 效果好的话,可以加在超分项目上\n\n# import torch\n# import torch.nn.functional as F\n# from torch import nn, cuda\n# from torch.autograd import Variable\n\n# class DeadConv2d(nn.Module):\n# def __init__(self,in_channels, out_channels, kernel_size, stride=1, padding=1, dilation=1,\n# groups=1, bias=True):\n# super(DeadConv2d, self).__init__()\n# self.weights = nn.Parameter(torch.Tensor(out_channels, in_channels, kernel_size[0], kernel_size[1]))\n# self.weights_1x1 = nn.Parameter(torch.Tensor(out_channels, out_channels, 1,1))\n# self.in_channels = in_channels\n# self.out_channels = out_channels\n# self.stride = stride\n# self.padding = padding\n# self.dilation = dilation\n# self.groups = groups\n# if bias:\n# self.bias = nn.Parameter(torch.Tensor(out_channels))\n# else:\n# self.bias = torch.zeros(out_channels)\n \n# self.dead_lock = nn.Parameter(torch.ones(out_channels),requires_grad=False)# 用relu控制稀疏性,也可以用tempered softmax控制?\n\n# def forward(self, input):\n# # 普通卷积\n# output_inner = F.conv2d(input, self.weights, self.bias, 1,\n# self.padding, self.dilation, self.groups)\n \n \n# # 很简单,每个通道的结果乘以一个scalar,初始为1,并且可以控制在何时启动\n# for i in range(self.out_channels):\n# output_inner[:,i,:,:] *= F.relu(self.dead_lock[i])\n \n# return output_inner\n\n\n# # 展示使用\n# conv = DeadConv2d(in_channels = 3, out_channels = 7, kernel_size=[3,3])\n# a = Variable(torch.ones([11,3,10,10]), requires_grad=True)\n# b = torch.mean(conv(a))\n\n\n# # 展示死亡权重冻结\n# for i in range(10):\n# print(conv.dead_lock.requires_grad)\n# conv.dead_lock.requires_grad = not conv.dead_lock.requires_grad\n# b.backward(retain_graph=True)\n# print(a.grad)\n","sub_path":"dead_op.py","file_name":"dead_op.py","file_ext":"py","file_size_in_byte":3258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"386765173","text":"N, Q = map(int, input().split())\n\ngrid = [[False]*N for _ in range(N)]\n\ndef print_grid(grid):\n for i in range(N):\n for j in range(N):\n if grid[i][j]:\n grid[i][j] = 'Y'\n else:\n grid[i][j] = 'N'\n for v in grid:\n print(*v, sep='')\n\nfor _ in range(Q):\n S = list(input().split())\n if S[0] == '1':\n a = int(S[1]) - 1\n b = int(S[2]) - 1\n grid[a][b] = True\n elif S[0] == '2':\n a = int(S[1]) - 1\n for i in range(N):\n if grid[i][a]:\n grid[a][i] = True\n else:\n a = int(S[1]) - 1\n tmp = []\n for i in range(N):\n if grid[a][i]:\n for j in range(N):\n if grid[i][j] and j != a:\n tmp.append([a, j])\n for a, j in tmp:\n grid[a][j] = True\n\nprint_grid(grid)","sub_path":"atcoder/2019/Other/1214_PAST/E.py","file_name":"E.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"582190849","text":"from collections import OrderedDict\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.widgets import RadioButtons, Button\n\nfrom yoink.widgets import (ShutterCrop, DragableColorLine, NothingWidget,\n RecoloredWidget, ScaledColorbar, ImageDumper)\nfrom yoink.textbox import TextBoxFloat\n\n\ndef make_selector_figure(gut=0.04, sepx=0.01, wide=0.2, tall=0.3,\n dx_cbar=0.05):\n fig = plt.figure()\n axes = {}\n\n x0 = gut + wide + sepx\n x1 = 1 - (gut + dx_cbar + sepx)\n\n y0 = gut\n y1 = 1 - gut\n\n l, b = x0, y0\n w, h = x1 - x0, y1 - y0\n img = fig.add_axes([l, b, w, h])\n img.yaxis.set_visible(False)\n img.xaxis.set_visible(False)\n axes['img'] = img\n\n l, b = x1 + sepx, y0\n w, h = dx_cbar, y1 - y0\n cbar = fig.add_axes([l, b, w, h])\n cbar.yaxis.set_visible(False)\n cbar.xaxis.set_visible(False)\n axes['cbar'] = cbar\n\n l, b = gut, 0.5 * (y0 + y1 - tall)\n w, h = wide, tall\n select = fig.add_axes([l, b, w, h])\n select.yaxis.set_visible(False)\n select.xaxis.set_visible(False)\n axes['select'] = select\n\n return fig, axes\n\n\ndef make_annotate_figure(gut=0.04, sepx=0.05, sepy=0.04,\n wide=0.09, tall=0.06, dx_cbar=0.05):\n fig = plt.figure()\n axes = {}\n\n x0 = gut + wide + sepx\n x1 = 1 - (gut + max(dx_cbar, wide) + sepx)\n\n y0 = gut + tall + sepy\n y1 = 1 - gut\n\n l, b = x0, y0\n w, h = x1 - x0, y1 - y0\n axes['img'] = fig.add_axes([l, b, w, h])\n\n l, b = x1 + sepx, gut + tall + sepy\n w, h = dx_cbar, y1 - y0 - tall - sepy\n cbar = fig.add_axes([l, b, w, h])\n cbar.yaxis.set_visible(False)\n cbar.xaxis.set_visible(False)\n axes['cbar'] = cbar\n\n l, b = x1 + sepx, gut\n w, h = wide, tall\n clo = fig.add_axes([l, b, w, h])\n clo.yaxis.set_visible(False)\n clo.xaxis.set_visible(False)\n axes['cbar_lo'] = clo\n\n l, b = x1 + sepx, y1 - tall\n w, h = wide, tall\n chi = fig.add_axes([l, b, w, h])\n chi.yaxis.set_visible(False)\n chi.xaxis.set_visible(False)\n axes['cbar_hi'] = chi\n\n l, b = gut, 1 - gut - tall\n w, h = wide, tall\n yhi = fig.add_axes([l, b, w, h])\n yhi.yaxis.set_visible(False)\n yhi.xaxis.set_visible(False)\n axes['yhi'] = yhi\n\n l, b, = gut, gut + tall + sepy\n ylo = fig.add_axes([l, b, w, h])\n ylo.yaxis.set_visible(False)\n ylo.xaxis.set_visible(False)\n axes['ylo'] = ylo\n\n l, b = x0, gut\n xlo = fig.add_axes([l, b, w, h])\n xlo.yaxis.set_visible(False)\n xlo.xaxis.set_visible(False)\n axes['xlo'] = xlo\n\n l, b = x1 - wide, gut\n xhi = fig.add_axes([l, b, w, h])\n xhi.yaxis.set_visible(False)\n xhi.xaxis.set_visible(False)\n axes['xhi'] = xhi\n\n l, b = x0 + wide + sepx, gut\n w, h = x1 - x0 - 2 * (sepx + wide), tall\n dump = fig.add_axes([l, b, w, h])\n dump.yaxis.set_visible(False)\n dump.xaxis.set_visible(False)\n axes['dump'] = dump\n\n return fig, axes\n\n\ndef run(pixels, path):\n \"\"\"\n \"\"\"\n # Return the widgets or they stop responding\n widgets = {}\n\n # generate layout of figures and axes\n # there should be two figures: one for (sub)selecting data\n # and another for annotating that data with numbers\n sel_fig, sel_axes = make_selector_figure()\n ann_fig, ann_axes = make_annotate_figure()\n\n #\n # Set up the widgets on the selection figure\n #\n # plot source data\n sel_axes['img'].imshow(pixels, interpolation='none', vmin=0, vmax=1)\n\n # add shutters for cropping, initially disabled\n widgets['crop_widget'] = crop_widget = ShutterCrop(sel_axes['img'])\n crop_widget.active = False\n crop_widget.set_visible(False)\n\n # add a line to identify manually select the colorbar, initially disabled\n widgets['cbar_select'] = cbar_select = DragableColorLine(sel_axes['img'],\n sel_axes['cbar'],\n pixels)\n cbar_select.active = False\n cbar_select.set_visible(False)\n\n # Radio buttons to select which Widget is active\n states = OrderedDict()\n states['Do nothing'] = NothingWidget()\n states['Select Colorbar'] = cbar_select\n states['Crop Image'] = crop_widget\n\n def toggle_state(new_state):\n assert new_state in states\n for k in states:\n if k == new_state:\n continue\n states[k].active = False\n states[k].set_visible(False)\n states[new_state].active = True\n states[new_state].set_visible(True)\n toggle_state(states.keys()[0])\n\n widgets['radio'] = select_radio = RadioButtons(sel_axes['select'],\n labels=states.keys(),\n active=0)\n select_radio.on_clicked(toggle_state)\n\n #\n # Now set up widgets on the annotation figure\n #\n # We are converting a multi-color image to a scalar image.\n # Plot that scalar image\n widgets['rcol_widget'] = rcol_widget = RecoloredWidget(ann_axes['img'],\n pixels)\n # fill axes with textboxes for typing in the x & y limits\n # these set the scale of x and y\n rcol_widget.make_xyextent_textboxes(ann_axes['xlo'],\n ann_axes['xhi'],\n ann_axes['ylo'],\n ann_axes['yhi'])\n\n # Crop the re-colored image when the cropping shutters move\n crop_widget.on_changed(rcol_widget.crop)\n\n # Draw a colorbar for the re-colored image, and set the initial cmap\n widgets['cbar_widget'] = cbar_widget = ScaledColorbar(ann_axes['cbar'],\n rcol_widget.image)\n rcol_widget.digitize(cbar_select.l, cbar_select.rgb)\n\n # Re-draw the colormap when the colorbar-selector moves\n # re-digitizing is expensive, so only do it when you release the mouse\n cbar_select.on_release(rcol_widget.digitize)\n\n # Create textbox widgets to manually specifying the range of z\n widgets['tb_lo'] = tblo = TextBoxFloat(ann_axes['cbar_lo'], '0')\n widgets['tb_hi'] = tbhi = TextBoxFloat(ann_axes['cbar_hi'], '1')\n # If the textbox changes, propagate those changes to the colorbar ticks\n tblo.on_changed(cbar_widget.set_min)\n tbhi.on_changed(cbar_widget.set_max)\n\n # Add a button to dump the data to a file\n widgets['dump_button'] = dump_button = Button(ann_axes['dump'],\n 'Dump to file')\n widgets['dumper'] = dumper = ImageDumper(rcol_widget.image,\n cbar_widget,\n cbar_select,\n path)\n dump_button.on_clicked(dumper.dump_npz)\n\n # Return all the widgets. If you don't, they don't respond interactively.\n # Maybe they are getting garbage collected?\n return widgets\n","sub_path":"yoink/cmap_app.py","file_name":"cmap_app.py","file_ext":"py","file_size_in_byte":6997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"336789896","text":"\nimport numpy as np\nfrom numpy import linalg as LA\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.linear_model import Ridge\nfrom MLE.pySGL import blockwise_descent\nfrom MLE.pyPQN.minConF_PQN import minConf_PQN\nfrom MLE.pyPQN.SquaredError import SquaredError\nfrom MLE.pyPQN.projectRandom2 import randomProject\n# import trace\n\n\nclass LinearRegression:\n\n def __init__(self, marker_groups, alpha=None, lbda=None):\n \"\"\"\n Wrapper for Linear Regression model combining Group Lasso (using either PQN or SGL) and Ridge.\n This wrapper is compatible with GridSearchCV of Sci-Kit-Learn. Main methods are fit and predict.\n\n Args:\n marker_groups (list): marker indicators for each feature/column of X\n alpha (int): Ridge regularizer\n lbda (int): Group Lasso regularizer\n \"\"\"\n\n self.marker_groups = marker_groups\n self.alpha = alpha\n self.lbda = lbda\n self.model = None\n self.feature_support = None\n self.feature_indices = None\n self.group_lasso_strategy = 'PQN' # 'PQN' or 'SGL' or 'None'\n self.coef = None\n self.sample_weight = None\n self.X = None\n self.y = None\n\n def fit(self, X, y, sample_weight=None):\n\n if sample_weight is None:\n sample_weight = np.ones(y.shape)\n\n self.sample_weight = sample_weight\n self.X = X\n self.y = y\n\n # print('-'*20 + \"Running group lasso:\")\n # print(f'X = {X}, y = {y}, sample_weight = {sample_weight}')\n\n if self.group_lasso_strategy == 'SGL':\n feature_support = self.group_lasso_SGL(X, y)\n elif self.group_lasso_strategy == 'PQN':\n feature_support = self.group_lasso_PQN(X, y, sample_weight)\n else:\n markers, repeats = np.unique(self.marker_groups, return_counts=True)\n feature_support = markers\n\n markers, repeats = np.unique(self.marker_groups, return_counts=True)\n feature_indices = []\n for i in markers:\n if i in feature_support:\n feature_indices.extend(np.repeat(True, repeats[i]))\n else:\n feature_indices.extend(np.repeat(False, repeats[i]))\n\n # print('-'*20 + \"Running Ridge:\")\n\n model = Ridge(alpha=self.alpha)\n model.fit(X[:, feature_indices], y, sample_weight=sample_weight)\n self.coef = model.coef_\n\n # print('-'*20 + \"Saving regression results.\")\n\n self.model = model\n self.feature_support = feature_support\n self.feature_indices = feature_indices\n\n return self\n\n def score(self, X, y, sample_weight=None):\n\n self.fit(X, y, sample_weight)\n y_predict = self.predict(X)\n score_ = mean_squared_error(y, y_predict)\n\n return score_\n\n def get_params(self, deep=True):\n\n params = {\"alpha\": self.alpha, \"lbda\": self.lbda, \"marker_groups\": self.marker_groups}\n\n return params\n\n def set_params(self, **params):\n\n for parameter, value in params.items():\n setattr(self, parameter, value)\n\n return self\n\n def predict(self, X):\n\n model = self.model\n feature_indices = self.feature_indices\n\n if feature_indices is None:\n raise ValueError('Feature indices cannot be None!')\n\n # print('-' * 20 + \"Running predict for linear regression.\")\n # print(f'X = {X[:, feature_indices]}')\n\n y_predict = model.predict(X[:, feature_indices])\n\n return y_predict\n\n def group_lasso_SGL(self, X, y):\n\n markers = np.unique(self.marker_groups)\n\n fs_model = blockwise_descent.SGL(groups=self.marker_groups, alpha=0., lbda=self.lbda, rtol=1e-3)\n fs_model.fit(X, y)\n coefs = fs_model.coef_\n\n feature_support = []\n for j in markers:\n indices = np.where(self.marker_groups == j)[0]\n if LA.norm(coefs[indices], 2) != 0:\n feature_support.append(int(j))\n\n return feature_support\n\n def group_lasso_PQN(self, X, y, sample_weight):\n\n d1, d2 = X.shape\n markers, repeats = np.unique(self.marker_groups, return_counts=True)\n\n # print('-'*20 + 'Running PQN:', d2)\n\n w1 = np.zeros((d2,))\n\n # tracer for segfault:\n # tracer = trace.Trace(trace=1, count=0, outfile='trace_output')\n # tracer.run('minConf_PQN(fun_object, w1, fun_project, verbose=3)[0]')\n # tracer.results().write_results(show_missing=True)\n\n w2 = minConf_PQN(self.fun_object, w1, self.fun_project, verbose=0)[0]\n\n\n # print('-' * 20 + 'Producing the feature support after PQN run:')\n # print(f'w2 = {w2}')\n\n feature_support = []\n for j in markers:\n indices = np.where(self.marker_groups == j)[0]\n if LA.norm(w2[indices], 2) != 0:\n feature_support.append(int(j))\n\n return feature_support\n\n def fun_project(self, w):\n\n # print('-'*20 + 'Starting fun_project')\n markers, repeats = np.unique(self.marker_groups, return_counts=True)\n\n\n v = np.zeros((markers.shape[0],))\n v1 = np.zeros(w.shape)\n\n # print('-' * 20 + 'Starting for loop in fun_project')\n # print(f'markers={markers}')\n # print(f'w={w}')\n\n for i in markers:\n indices1 = np.where(self.marker_groups == i)[0]\n w_group = w[indices1]\n # print(f'w_group={w_group}')\n v[i] = LA.norm(w_group, 2)\n\n # print(f'v[i]={v[i]}')\n\n if v[i] != 0:\n v1[indices1] = w_group / v[i]\n\n # print('-' * 20 + 'Calling randomProject:')\n\n\n p = randomProject(v, self.lbda)\n\n test = v1 * np.repeat(p, repeats)\n\n # print('-' * 20 + 'randomProject Finished:', p, repeats)\n # print('-'*20 + f'test={test}')\n\n return test\n\n def fun_object(self, w):\n # return SquaredError(w, X, y)\n\n # print('-' * 20 + 'Running fun_object')\n\n test = SquaredError(w, np.tile(np.reshape(np.sqrt(self.sample_weight), (np.size(self.X, 0), 1)),\n (1, np.size(self.X, 1))) * self.X, np.sqrt(self.sample_weight) * self.y)\n\n # print('-' * 20 + 'Returning from fun_object')\n\n return test\n","sub_path":"MLE/linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":6261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"115065637","text":"'''\nImplementation of BackPropogation for CNN\n\ndelta = del(Loss)/del(z_val)\n'''\nimport numpy as np\n'''\nFrom Fully Connected layerto Fully Connected layer\n'''\ndef BackProp_FC_to_FC(delta, prev_weights, prev_activations, z_vals, final = False):\n '''\n Reset delta if not FC is not a final layer \n '''\n if not final:\n sp = sigmoid_prime(z_vals)\n delta = np.dot(prev_weights.transpose(), delta) * sp\n \n Slopeb = delta\n Slopew = np.dot(delta, prev_activations.transpose())\n return (Slopew, Slopeb, delta)\n\n'''\nFrom fully connected to 3D layer\n'''\ndef BackProp_FC_TO_3D(delta, prev_weights, prev_activations, z_vals):\n #Calculate delta\n sp = sigmoid_prime(z_vals)\n delta = np.dot(prev_weights.transpose(), delta) * sp\n \n Slopeb = delta\n images\n #Reshape Prev activations\n depth, dim1, dim2 = prev_activations.shape\n prev_activations = prev_activations.reshape((1, depth * dim1 * dim2))\n \n Slopew = np.dot(delta, prev_activations)\n Slopew = Slopew.reshape((delta.shape[0], depth, dim1, dim2))\n \n return (Slopew, Slopeb, delta)\n\n'''\nFrom Pooling layer to convolution layer\nOnly delta Changes\n'''\ndef BackProp_Pool_to_Conv(delta, prev_weights, input_from_conv, max_indices, pool_size, pool_output):\n #Get Shape\n x, y, z = pool_output.shape\n a, b, c, d = prev_weights.shape\n \n #Reshape Weights and PoolLayer\n prev_weights = prev_weights.reshape((a, b * c * d))\n pool_output = pool_output.reshape((x * y * z, 1))\n\n #Reshape MaxIndex matrix\n max_indices = max_indices.reshape((x, y * z, 2))\n \n #Bckpropogate delta from fc layer to pooLLayer\n sp = sigmoid_prime(pool_output)\n delta = np.dot(prev_weights.transpose(), delta) * sp\n delta = delta.reshape((x, y * z))\n pool_output = pool_output.reshape((x, y * z))\n \n #depth height width\n depth, height, width = input_from_conv.shape\n delta_new = np.zeros((depth, height, width))\n \n for d in range(depth):\n row, col = 0, 0\n for i in range(max_indices.shape[1]):\n to_pool = input_from_conv[d][row : poolsize[0] + row, col : poolsize[1] + col]\n \n #Get new delta\n delta_from_pooling = max_prime(pool_output[d][i], delta[d][i], to_pool)\n delta_new[d][row : poolsize[0] + row, col : poolsize[1] + col] = delta_from_pooling\n \n col += poolsize[1]\n if col >= width:\n col = 0\n row += poolsize[1]\n \n #Return New delta \n return delta_new\n\ndef BackProp_To_Conv(delta, weight_filters, stride, input_to_conv, pre_z_values):\n #Get shape of weights\n num_filters, depth, filter_size, filter_size = weight_filters.shape\n\n #Initialze Slope of weights and biases\n Slopeb = np.zeros((num_filters, 1))\n Slopew = np.zeros((weight_filters.shape))\n \n total_delta_per_layers = delta.shape[1]*delta.shape[2]\n #Reshape delta\n delta = delta.reshape((delta.shape[0], total_delta_per_layers))\n \n #For all Filters evaluate Slopew and Slopeb for filter\n for j in range(num_filters):\n col, row = 0, 0\n for i in range(total_delta_per_layers):\n to_conv = input_to_conv[:, row:row+filter_size, col:col+filter_size]\n Slopew[j] += to_conv * delta[j][i]\n Slopeb[j] += delta[j][i]\n #update col\n col += stride[1]\n \n \n if (col + filter_size) - stride >= input_to_conv.shape[2]:\n col = 0\n row += stride\n return (Slopeb, Slopew)\n\n#Helper functon for transition from pooling layer to convolution layer\ndef max_prime(res, delta, tile_to_pool):\n dim1, dim2 = tile_to_pool.shape\n tile_to_pool = tile_to_pool.reshape((dim1 * dim2))\n new_delta = np.zeros((tile_to_pool.shape))\n \n for i in range(len(tile_to_pool)):\n num = tile_to_pool[i]\n if num < res:\n new_delta[i] = 0\n else:\n new_delta[i] = delta\n return new_delta.reshape((dim1, dim2))\n","sub_path":"BackPropogationCNN.py","file_name":"BackPropogationCNN.py","file_ext":"py","file_size_in_byte":4059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"380946833","text":"\n#Solution - Falnker task (5)\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndef main():\n df = pd.read_csv(\"flanker_data/P1Flanker1.csv\")\n # TASK A\n mean = df[\"Correct\"].mean() \n correct_df = df[df.Correct == 1]\n correct_Mean = correct_df[\"ReactionTime\"].mean()\n incorrect_df = df[df.Correct == 0]\n incorrect_Mean = incorrect_df[\"ReactionTime\"].mean()\n # ~print results\n print(f\"A1. mean accuracy across the task: \\t\\t\\t\\t\\t {mean}\")\n print(f\"A2. mean reaction time across the task - for correct responses only:\\t {correct_Mean}\")\n print(f\"A3. mean reaction time across the task - for incorrect responses only:\\t {incorrect_Mean}\")\n # TASK B\n congruent = correct_df[correct_df.Condition == 0][\"ReactionTime\"].mean()\n neutral = correct_df[correct_df.Condition == 1][\"ReactionTime\"].mean()\n incongruent = correct_df[correct_df.Condition == 2][\"ReactionTime\"].mean()\n # create barplot \n bplot = pd.DataFrame({'mean reaction time':['congruent', 'neutral', 'incongruent'], 'val':[congruent, neutral, incongruent]})\n bplot.plot.bar(x='mean reaction time', y='val', rot=0)\n plt.show()\n \nif __name__ == \"__main__\":\n main()","sub_path":"Flanker_task.py","file_name":"Flanker_task.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"129028375","text":"import Member\n\nclass Party:\n\n\tpartyMembers = []\n\n\tdef __init__(self):\n\t\tself.partyMembers = []\n\n\tdef addMember(self, newMember):\n\t\tself.partyMembers.append(newMember)\n\n##\tdef addMember(self, className, newName, level):\n##\t\tnewMember = Member.Member(className, newName, level)\n##\t\tself.partyMembers.append(newMember)\n\n\tdef __str__(self):\n\t\tstringList = []\n\t\tspacing = 2\n\t\t\n\t\tfor member in self.partyMembers:\n\t\t\tnewList = str(member).split(\"\\n\")\n\t\t\tstringList.append(newList)\n\n\t\toutString = \"\"\n\t\tfor i in range(len(stringList[0])):\n\t\t\tnewLine = \"\"\n\t\t\tfor each in stringList:\n\t\t\t\tif (each[i] != \"\\n\"):\n\t\t\t\t\tnewLine+=each[i]\n\t\t\t\t\tnewLine+=(\" \"*spacing+\"|\"+\" \"*spacing)\n\t\t\tnewLine+=\"\\n\"\n\t\t\toutString+=newLine\n\n\t\treturn outString\n","sub_path":"Party.py","file_name":"Party.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"611849139","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 16 11:31:34 2017\n\n@author: vitorhadad\n\"\"\"\nimport numpy as np\n\nclass Game:\n \n def __init__(self, n_players):\n \n self.n_players = n_players\n self.value = self.reset()\n \n \n def step(self, actions):\n rs = self.decide(actions)\n self.value = self.next_shock(self.value)\n return self.value, rs, False, None\n \n \n def reset(self):\n vs = np.random.uniform(size = (self.n_players - 1))\n self.value = np.hstack([vs, 0])\n return self.value\n \n \n def next_shock(self, s):\n s = s.copy()\n ds = 0.02*(.5 - s) + np.random.normal(0,.1, size = self.n_players)\n s = np.clip(s + ds, 0, 1)\n s[-1] = 0\n return s\n \n\n def decide(self, actions):\n \n bids, weight = actions[:-1], actions[-1]\n \n largest = np.argwhere(np.isclose(bids, np.max(bids))).flatten()\n winner = np.random.choice(largest)\n \n loser = 1 - winner\n #payment = bids[winner]*(1 - weight) + bids[loser]*weight\n payment = bids[loser]\n \n rs = np.zeros((self.n_players))\n rs[winner] = self.value[winner] - payment \n rs[loser] = 0\n rs[-1] = -np.mean(self.value[:-1] - bids)\n \n return rs\n \n \n#%%\nif __name__ == \"__main__\":\n \n import matplotlib.pyplot as plt\n \n auc = Game(n_players = 3)\n vs = [auc.value]\n for _ in range(100):\n v,*_ = auc.step(np.array([0, .5, .5]))\n vs += [v]\n plt.plot(vs)\n \n #%%\n vs = auc.value.copy()\n a = np.array([0.4, 0.8, 1])\n _,rs,*_ = auc.step(a)\n ","sub_path":"auction.py","file_name":"auction.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"261647528","text":"\nimport copy\nimport random\nimport time\n\nimport numpy as np\nfrom scipy.stats import truncnorm\n\nfrom Parameter_Search.Algorithms import Error_Calculation as Test\n\n'''Tabu search algorithm for the optimization of the opioid ODE system'''\n\n# Ranges of Parameters ------------------------\n\n\ndef randParameter(ranges):\n \"\"\" Returns a new random vector of parameters\"\"\"\n Theta = []\n for i in range(len(ranges)):\n Theta += [runif(ranges[i])]\n return Theta\n\n\ndef centParameter(ranges):\n \"\"\"Returns a new vector parameter with middle of all ranges\"\"\"\n Theta = []\n for i in range(len(ranges)):\n Theta += [(ranges[i][0] + ranges[i][1]) / 2]\n return Theta\n\n\n# Different functions to determine a new parameter\n# Continuous Changes\n# Uniform\ndef runif(range):\n \"\"\" Helper Function for runifParater to return random uniform from range low to high\"\"\"\n return np.random.uniform(range[0], range[1])\n\n\ndef runifParameter(parameter, i, ranges):\n \"\"\" With order of ap, cp, hr, mr, amt, ct, cmt, hor, mor, hs, ms, ds, ri, pg, fenor\n Adjusts the current ith Parameter.\"\"\"\n return runif(ranges[i])\n\n\n# Global scale controls the standard deviation for rnorm.\n# ie Larger globscale searches a smaller area\nglobscale = 5\n\n\n# Normal\ndef rnorm(parameter, range, scale=globscale):\n ''' Helper Function for rnormParameter.\n Truncated normal distribution centered around current parameter estimate.\n sd = changes with globscale parameter defined outside of function\n '''\n lower, upper = range[0], range[1]\n mu, sigma = parameter, (upper - lower) / scale\n return (truncnorm(\n (lower - mu) / sigma, (upper - mu) / sigma, loc=mu, scale=sigma).rvs(1)[0] - mu)\n\n\ndef rnormParameter(parameter, i, ranges):\n \"\"\" Returns a new ith parameter with normal distribution\"\"\"\n return rnorm(parameter=parameter, range=ranges[i])\n\n\n# Neighbor Functions ---------------------\ndef Neighbor(Theta, ranges, n=4):\n \"\"\"Takes in vector of parameters, Theta, and returns a new vector neighbor\n that differs in n indices.\n uses the function rand to sample next parameter\n value.\n Same Function for both continuous and discrete.\"\"\"\n indices = random.sample(range(len(Theta) - 1), n)\n for i in indices:\n Theta[i] += rnormParameter(Theta[i], i, ranges=ranges)\n return Theta\n\n\n# Accept Probability for Annealing ---------------------------\ndef accept_propose(current, proposal, temperature):\n \"\"\"Returns True if Proposal parameter vector should be accepted. else False\"\"\"\n # Proposal is better than current\n if proposal < current:\n return True\n else:\n prob = np.exp(-(proposal - current) / temperature)\n return prob > random.random()\n\ndef cost(solution, region_list, historical_deaths, years_range, dt, ini_method):\n \"\"\" Calculates the cost of the solution that this passed in with respect to the model.\"\"\"\n return Test.calculate_error(parameters=solution, test_years=years_range,\n region_list=region_list, historical_deaths=historical_deaths, dt=dt,\n ini_method=ini_method)\n\n\n# Taboo Search ----------------------------------------------\ndef tabu(region_list, historical_deaths, years_range, ranges, dt, init_method, max_time=120, thresh=250):\n \"\"\" Runs Taboo search from a randomly generated parameter for max_time and returns the best solution found\"\"\"\n\n # Initial Solution and its cost\n solution = randParameter(ranges)\n old_pop, old_cost = cost(solution, region_list, historical_deaths, years_range, dt, init_method)\n best_cost = old_cost\n best_solution = copy.deepcopy(solution)\n best_pop = old_pop\n\n # Taboo threshold tracker\n count = 0\n\n # Dictionary to store\n param_error_dict = {}\n\n # record time\n t0 = time.clock()\n\n # taboo until max_time\n while time.clock() - t0 < max_time:\n # Get Neighbor solution and its cost\n new_solution = Neighbor(solution, ranges)\n new_pop, new_cost = cost(new_solution, region_list, historical_deaths, years_range, dt, init_method)\n # If it's better, record it\n if new_cost < best_cost:\n best_cost = new_cost\n best_pop = new_pop\n best_solution = copy.deepcopy(new_solution)\n # Track the improvement\n param_error_dict[(tuple(best_solution), tuple(best_pop))] = best_cost\n\n # Keep of count of how many neighbors since last improvement\n else:\n count += 1\n # Our proposed solution is still within threshold and\n # its not to big\n if count < thresh and not accept_propose(old_cost, new_cost, .5):\n solution = new_solution\n # Restart at last best solution\n else:\n solution = copy.deepcopy(best_solution)\n count = 0\n return (best_solution, best_pop), param_error_dict, best_cost\n","sub_path":"Parameter_Search/Algorithms/Tabu_Search.py","file_name":"Tabu_Search.py","file_ext":"py","file_size_in_byte":4927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"499589947","text":"#!/usr/bin/env python\n\n# Copyright 2019 Juliane Mai - juliane.mai(at)uwaterloo.ca\n#\n# License\n# This file is part of Juliane Mai's personal code library.\n#\n# Juliane Mai's personal code library is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Juliane Mai's personal code library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n\n# You should have received a copy of the GNU Lesser General Public Licensefstop\n# along with Juliane Mai's personal code library. If not, see .\n#\n\nfrom __future__ import print_function\n\n\"\"\"\nHelper functions for Sobol' sensitivity analysis of RAVEN\n\nHistory\n-------\nWritten, JM, Jun 2019\n\"\"\"\n\nfrom pathlib2 import Path\n\ndef writeString(fname, string):\n \"\"\"\n Arguments\n ---------\n fname (Union[Text, pathlib2.Path]) : file name\n string (Text) : file's content to write\n\n Return\n ------\n None\n\n Purpose\n -------\n Write given string to file. All necessary directories\n will be created.\n \"\"\"\n\n makeDirectories([Path(fname)])\n with open(str(fname), \"w\") as f:\n f.write(string)\n f.close()\n\ndef makeDirectories(fnames):\n \"\"\"\n Arguments\n ---------\n fnames (List[pathlib2.Path]): file or directory names.\n\n Return\n ------\n None\n\n\n Purpose\n -------\n Create all directories necessary to be able to access\n the given filenames or directory\n \n Note\n ----\n Anything in 'fnames' with a file extension in the form of '.*' is\n considered to be file, anything else to represent a directory.\n \"\"\"\n\n dirs = set([f.parent if f.suffix else f for f in fnames])\n for d in dirs:\n d.mkdir(parents=True, exist_ok=True)\n","sub_path":"examples/raven-gr4j-cemaneige/model/raven_common.py","file_name":"raven_common.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"322989213","text":"from selenium import webdriver\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\nimport random\r\nimport csv\r\n\r\n\r\nclass Crawler:\r\n def __init__(self):\r\n self.browser = webdriver.Firefox()\r\n\r\n def log_in(self, url):\r\n\r\n self.browser.get(url)\r\n\r\n time.sleep(10)\r\n telephone = self.browser.find_element_by_xpath('/html/body/div[2]/div[7]/div[1]/input')\r\n\r\n telephone.send_keys('18291893261')\r\n time.sleep(2)\r\n classify_code = self.browser.find_element_by_xpath('/html/body/div[2]/div[7]/div[1]/div/span')\r\n classify_code.click()\r\n code = input(\"Please enter the classify code:\")\r\n password = self.browser.find_element_by_xpath('/html/body/div[2]/div[7]/div[2]/input')\r\n password.send_keys(str(code))\r\n time.sleep(random.randint(8, 10))\r\n login = self.browser.find_element_by_xpath('/html/body/div[2]/div[7]/div[3]/button[2]')\r\n login.click()\r\n time.sleep(random.randint(5, 10))\r\n # sure = self.browser.find_element_by_xpath('//*[@id=\"iLoginComp-tip-confirm-id\"]')\r\n # sure.click()\r\n # time.sleep(random.randint(5, 10))\r\n #\r\n # birthday = self.browser.find_element_by_xpath('//*[@id=\"yodaBirthdayCodeInput\"]')\r\n # birthday.send_keys('20000318')\r\n #\r\n # time.sleep(random.randint(5, 10))\r\n # check = self.browser.find_element_by_xpath('//*[@id=\"yodaVerifyBtn\"]')\r\n # check.click()\r\n\r\n time.sleep(random.randint(6, 10))\r\n # self.location()\r\n\r\n # cookie = browser.get_cookies()\r\n # print(cookie)\r\n\r\n def location(self):\r\n loc = self.browser.find_element_by_xpath('/html/body/mieta/div[1]/div/div/div/div/div/div/div[1]/div[1]')\r\n loc.click()\r\n time.sleep(10)\r\n loc_again = self.browser.find_element_by_xpath(\r\n '/html/body/mieta/div[1]/div/div/div/div/div/div/div/div[2]/div/p[2]/span')\r\n loc_again.click()\r\n time.sleep(10)\r\n\r\n # def scroll_the_window(self):\r\n # all_window_heights = []\r\n # all_window_heights.append(self.browser.execute_script(\"return document.body.scrollHeight;\"))\r\n # while True:\r\n # self.browser.execute_script('scroll(0,10000)')\r\n # time.sleep(random.randint(5, 10)) # 随机数避免被检测出是爬虫\r\n # check_height = self.browser.execute_script(\"return document.body.scrollHeight;\")\r\n # if check_height == all_window_heights[-1]:\r\n # print(\"已经到了浏览器底层\")\r\n # break\r\n # else:\r\n # all_window_heights.append(check_height)\r\n # print(\"正在下拉浏览器\")\r\n def scroll_the_window(self):\r\n js = \"return action=document.body.scrollHeight\"\r\n height = self.browser.execute_script(js)\r\n\r\n # 将滚动条调整至页面底部\r\n self.browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')\r\n time.sleep(5)\r\n\r\n # 定义初始时间戳(秒)\r\n t1 = int(time.time())\r\n\r\n # 定义循环标识,用于终止while循环\r\n status = True\r\n\r\n # 重试次数\r\n num = 0\r\n\r\n while status:\r\n # 获取当前时间戳(秒)\r\n t2 = int(time.time())\r\n # 判断时间初始时间戳和当前时间戳相差是否大于30秒,小于30秒则下拉滚动条\r\n if t2 - t1 < 30:\r\n new_height = self.browser.execute_script(js)\r\n if new_height > height:\r\n time.sleep(1)\r\n self.browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')\r\n # 重置初始页面高度\r\n height = new_height\r\n # 重置初始时间戳,重新计时\r\n t1 = int(time.time())\r\n elif num < 3: # 当超过30秒页面高度仍然没有更新时,进入重试逻辑,重试3次,每次等待30秒\r\n time.sleep(3)\r\n num = num + 1\r\n else: # 超时并超过重试次数,程序结束跳出循环,并认为页面已经加载完毕!\r\n print(\"滚动条已经处于页面最下方!\")\r\n status = False\r\n # 滚动条调整至页面顶部\r\n self.browser.execute_script('window.scrollTo(0, 0)')\r\n break\r\n\r\n def get_source(self):\r\n html = self.browser.page_source\r\n html = html.encode('utf8')\r\n # print(html)\r\n soup = BeautifulSoup(html, 'lxml')\r\n self.save_data(soup)\r\n\r\n def save_data(self, soup):\r\n # 确定用的那个css字体\r\n\r\n file = soup.find('body').find('style').text\r\n file_name = file[-17:-4]\r\n # print(file)\r\n a_list = soup.find(class_=\"_14I_ga12izfkrbg8LnpHcW\").find_all('li')\r\n\r\n for item in a_list:\r\n time.sleep(2)\r\n name = item.find(class_='_1DtOrxweBD8MIzOOrhn9cs').text\r\n print(\"name:\", name)\r\n sales = item.find(class_=\"_257aD1mYh6bWz4bmXz3DSv _3fbi7-DiA-2q0ecYl1bi2j mtsi-num\").string[2:-1]\r\n\r\n print(\"sales:\", sales)\r\n final_sales = \"\"\r\n for temp in sales:\r\n final_sales += num_map[file_name][temp]\r\n print(num_map[file_name][temp], end=\"\")\r\n print(\"\\n\")\r\n\r\n send_time = item.find(class_=\"_3fbi7-DiA-2q0ecYl1bi2j mtsi-num\").string[:-2]\r\n final_send_time = \"\"\r\n print(\"send_time:\", send_time)\r\n for temp in send_time:\r\n final_send_time += num_map[file_name][temp]\r\n print(num_map[file_name][temp], end=\"\")\r\n print(\"\\n\")\r\n distance = item.find(class_=\"_3fbi7-DiA-2q0ecYl1bi2j _2vTtS2LuUOARC19vNowA9w mtsi-num\").string\r\n if distance[-2] == \"k\":\r\n distance = distance[:-2]\r\n else:\r\n distance = distance[:-1]\r\n final_distance = \"\"\r\n print(\"distance:\", distance)\r\n for temp in distance:\r\n if temp == \".\":\r\n final_distance += \".\"\r\n print(\".\", end=\"\")\r\n else:\r\n final_distance += num_map[file_name][temp]\r\n print(num_map[file_name][temp], end='')\r\n print(\"\\n\")\r\n starting_price = item.find(class_=\"_3DcMzS2xKx7PfzNq_sUnxn\").find(\r\n class_='_3fbi7-DiA-2q0ecYl1bi2j mtsi-num').string[4:]\r\n final_start_price = \"\"\r\n print(\"start_price:\", starting_price)\r\n for temp in starting_price:\r\n print(num_map[file_name][temp], end=\"\")\r\n final_start_price += num_map[file_name][temp]\r\n print('\\n')\r\n delivery_price = item.find(class_=\"_3DcMzS2xKx7PfzNq_sUnxn\").find_all(\r\n class_=\"_3fbi7-DiA-2q0ecYl1bi2j _2vTtS2LuUOARC19vNowA9w mtsi-num\")[0].string\r\n print(delivery_price)\r\n final_delivery_price = \"\"\r\n if delivery_price == \"免配送费\":\r\n delivery_price = 0\r\n print(\"delivery_price:\", delivery_price)\r\n final_delivery_price += \"0\"\r\n else:\r\n delivery_price = delivery_price[4:]\r\n print(\"delivery_price:\", delivery_price)\r\n for temp in delivery_price:\r\n if temp == \".\":\r\n final_delivery_price += \".\"\r\n print(\".\")\r\n else:\r\n print(num_map[file_name][temp], end=\"\")\r\n final_delivery_price += num_map[file_name][temp]\r\n print(\"\\n\")\r\n final_mean_price = \"\"\r\n try:\r\n mean_price = item.find(class_=\"_3DcMzS2xKx7PfzNq_sUnxn\").find_all(\r\n class_='_3fbi7-DiA-2q0ecYl1bi2j _2vTtS2LuUOARC19vNowA9w mtsi-num')[1].string[4:]\r\n print(\"mean_price:\", mean_price)\r\n for temp in mean_price:\r\n final_mean_price += num_map[file_name][temp]\r\n print(num_map[file_name][temp], end=\"\")\r\n print(\"\\n\")\r\n except:\r\n mean_price = 0\r\n print(\"mean_price:\", mean_price)\r\n final_mean_price += \"0\"\r\n\r\n score = item.find(class_=\"_3fbi7-DiA-2q0ecYl1bi2j _3xfmNN1n12Gov71h-3rfhp\").string\r\n final_score = str(score)\r\n print(\"score:\", score)\r\n with open('BP/BPmeituanData.csv', 'a+', newline='', encoding='utf-8-sig')as f:\r\n writer = csv.writer(f)\r\n writer.writerow(\r\n [name, final_sales, final_send_time, final_distance, final_start_price, final_delivery_price,\r\n final_mean_price, final_score])\r\n\r\n\r\nnum_map = {'08220675.woff': {'\\ue0f9': '9', '\\ue275': '2', '\\ue13e': '4', '\\uf785': '0', '\\ue5c7': '1', '\\uf8f9': '5',\r\n '\\uf8fc': '7',\r\n '\\ue060': '6', '\\ue6c0': '3', '\\uf140': '8'},\r\n '5f0be5ce.woff': {'\\ue350': '9', '\\ue4d4': '6', '\\uf005': '5', '\\uf56f': '2', '\\ue97b': '1', '\\ue458': '0',\r\n '\\ue5e0': '4',\r\n '\\ue379': '8', '\\ue3fc': '7', '\\ueb7b': '3'},\r\n '8a16e02d.woff': {'\\uf80c': '3', '\\ue196': '9', '\\ue7ba': '5', '\\ue04c': '8', '\\uf41d': '2', '\\ue92a': '7',\r\n '\\ue9cf': '6',\r\n '\\ue3c9': '1', '\\ue340': '0', '\\ued8b': '4'},\r\n 'c722c643.woff': {'\\uee40': '2', '\\uf117': '8', '\\uf3e7': '6', '\\uebc4': '7', '\\ue990': '0', '\\ueb02': '3',\r\n '\\uef32': '1',\r\n '\\ueed7': '9', '\\uec2e': '5', '\\ue518': '4'},\r\n 'd2324528.woff': {'\\ue703': '7', '\\ue8c2': '9', '\\ue5b9': '5', '\\ue199': '3', '\\ue168': '2', '\\uf34f': '6',\r\n '\\ue14f': '8',\r\n '\\uead7': '1', '\\ue9d3': '0', '\\uf80a': '4'},\r\n '26454aeb.woff': {'\\ue426': '9', '\\ue13b': '6', '\\ueae8': '3', '\\uee88': '4', '\\uf553': '0', '\\uf8a6': '7',\r\n '\\uf8d8': '2',\r\n '\\uf08d': '5', '\\uf198': '1', '\\ued18': '8'},\r\n 'b3b7ee0d.woff': {'\\ue69f': '2', '\\uf58f': '0', '\\uf170': '4', '\\uf0ea': '5', '\\ue391': '1', '\\ue1be': '9',\r\n '\\uf4fa': '7',\r\n '\\ueb13': '6', '\\ue1dd': '3', '\\uf79f': '8'},\r\n '7e941ac2.woff': {'\\ued9a': '7', '\\ue7a5': '5', '\\ue641': '0', '\\ueb24': '6', '\\uf4fd': '1', '\\ue306': '9',\r\n '\\ue3a5': '8',\r\n '\\uf62e': '2', '\\uf484': '4', '\\uef14': '3'},\r\n 'd2f7b57f.woff': {'\\ue163': '2', '\\uea95': '1', '\\ueff2': '3', '\\ue5f2': '0', '\\uf1c9': '5', '\\uf0ef': '8',\r\n '\\uea41': '6',\r\n '\\ue3b5': '9', '\\ue85a': '4', '\\uf0fc': '7'},\r\n 'd308c5b0.woff': {'\\uebd3': '6', '\\ue716': '0', '\\uf3b7': '5', '\\ue62a': '9', '\\uec06': '7', '\\ue76b': '8',\r\n '\\uefca': '4',\r\n '\\uf4af': '2', '\\uee0c': '3', '\\ueb02': '1'},\r\n '0bec55e0.woff': {'\\uef81': '3',\r\n '\\uf276': '6', '\\uf25e': '0', '\\ue7aa': '4', '\\ue84b': '8', '\\ue92b': '2', '\\ue3d6': '5',\r\n '\\uea3d': '7',\r\n '\\uf633': '9',\r\n '\\ue694': '1'},\r\n \"95a89f18.woff\": {'\\uee64': '7', '\\ue6c8': '2', '\\uf3ce': '3', '\\ue511': '0', '\\uef0e': '4', '\\ue2bc': '9', '\\uea5b': '8',\r\n '\\ueb5a': '1', '\\ueb7e': '6', '\\uf397': '5'},\r\n '57ed9f2a.woff': {'\\ue579': '8', '\\uedca': '1', '\\ue9d1': '4', '\\uf58f': '7', '\\uef2a': '5', '\\ue543': '9', '\\uee84': '2',\r\n '\\ueebc': '3', '\\uf684': '6', '\\ue860': '0'\r\n }\r\n }\r\n\r\nif __name__ == '__main__':\r\n with open('BP/BPmeituanData.csv', 'a+', newline='', encoding='utf-8-sig') as f:\r\n writer = csv.writer(f)\r\n writer.writerow(\r\n ['name', 'sales', 'send_time', 'distance', 'start_price', 'delivery_price', 'mean_price', 'score'])\r\n\r\n crawler = Crawler()\r\n # crawler.log_in(\r\n # 'https://h5.waimai.meituan.com/waimai/mindex/kingkong?navigateType=910&firstCategoryId=910&secondCategoryId=910&title=%E7%BE%8E%E9%A3%9F')\r\n crawler.log_in('https://h5.waimai.meituan.com/waimai/mindex/home')\r\n time.sleep(60)\r\n # crawler.scroll_the_window()\r\n crawler.get_source()\r\n","sub_path":"PCA_Clustering/meituanDataBP.py","file_name":"meituanDataBP.py","file_ext":"py","file_size_in_byte":12707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"559430531","text":"# -*- coding: UTF-8 -*-\nimport core.game as game\nimport script.lib as lib\nimport script.people\nimport script.world\nimport script.play_cfg\nfrom script.mainflow import main_func\n\n\nclass Target_group():\n def __init__(self, group_data):\n self.data = group_data\n\n def deal_people(p):\n if p == {}:\n return None\n else:\n return Target_people(p)\n\n self.p1 = deal_people(group_data['队伍队员'][0])\n self.p2 = deal_people(group_data['队伍队员'][1])\n self.p3 = deal_people(group_data['队伍队员'][2])\n self.p4 = deal_people(group_data['队伍队员'][3])\n self.p5 = deal_people(group_data['队伍队员'][4])\n self.p6 = deal_people(group_data['队伍队员'][5])\n self.peoplelist = [self.p1, self.p2, self.p3, self.p4, self.p5, self.p6]\n\n\nclass Target_people():\n # def __str__(self):\n # return self.姓名 + ' ' + str(self.当前体力) + ' ' + str(self.体力上限) + ' '\n\n def __init__(self, people_data):\n self.data = people_data\n self.姓名 = self.data['姓名']\n self.当前体力 = self.data['属���']['体力上限']\n self.体力上限 = self.data['属性']['体力上限']\n\n def 近战鉴定(self, difficult):\n here = self.data['经验']['近战经验'] * 5 + self.data['能力']['近战'] * 10\n game.pl('近战经验*5+近战*10=' + str(here) + ' 难度:' + str(difficult))\n if difficult < here:\n return True\n else:\n return False\n\n\nclass Target_world():\n def __init__(self, world_data):\n self.data = world_data\n self.当前进度 = 1\n self.当前剧情 = world_data['剧情列表'][self.当前进度]\n\n\nclass Target_scene():\n def __init__(self, scene_data):\n self.data = scene_data\n self.名称 = self.data['名称']\n self.难度 = self.data['难度']\n\n\ntgroup = None\ntworld = None\ntscene = None\n\n\ndef init_play():\n global tgroup, tworld, tscene\n if game.data['试炼设置']['试炼队伍'] == None or game.data['试炼设置']['试炼世界'] == None:\n game.pl('没有指定[试炼队伍]或[试炼世界],请于[试炼设置]中选择', 'notice')\n main_func()\n tgroup = Target_group(game.data['试炼设置']['试炼队伍'])\n tworld = Target_world(game.data['试炼设置']['试炼世界'])\n tscene = Target_scene(tworld.当前剧情)\n main_play()\n\n\ndef main_play():\n global tgroup, tworld, tscene\n game.clr_cmd()\n game.pline()\n string = '剧情容量:' + lib.value_bar(tworld.当前进度, tworld.data['剧情容量'])\n string += game.align(' 下一剧情:' + tscene.名称, 40, 'right')\n game.pl(string)\n for p in tgroup.peoplelist:\n prefix = '人物体力(' + p.姓名 + '):'\n prefix = game.align(prefix, 20)\n game.pl(prefix + lib.value_bar(p.当前体力, p.体力上限))\n game.pline('--', 'notice')\n\n def begin_scene():\n game.call_event('进行剧情_' + tworld.当前剧情['名称'], arg=(tgroup, tworld, tscene))\n main_play()\n\n game.pcmd('[100] 开始剧情', 100, begin_scene)\n game.pl()\n game.pcmd('[101] 调整剧情', 101, lambda: \"break\")\n game.pl()\n game.pcmd('[999] 结束试炼', 999, main_func)\n game.askfor_order()\n","sub_path":"script/play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":3330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"279697755","text":"import tkinter as tk\nfrom tkinter import Menu, Tk, Text, DISABLED, RAISED,Frame, FLAT, Button, Scrollbar, Canvas, END\nfrom tkinter import messagebox as MessageBox\nfrom tkinter import ttk,filedialog, INSERT\nimport os\nimport pathlib\nfrom campo import Campo\nfrom arbol import Arbol\nimport http.client\nformularios=[]\ntextos=[]\ncontrol=0\nnotebook= None\n#Metodo GET para probar peticiones al servidor\ndef myGET():\n myConnection = http.client.HTTPConnection('localhost', 8000, timeout=10)\n\n headers = {\n \"Content-type\": \"text/plain\"\n }\n\n myConnection.request(\"GET\", \"/data/database.tytus\", \"\", headers)\n response = myConnection.getresponse()\n print(\"Status: {} and reason: {}\".format(response.status, response.reason))\n myData = response.read()\n print(myData.decode(\"utf-8\") )\n myConnection.close()\n\n#Metodo POST para probar peticiones al servidor\ndef myPOST():\n myConnection = http.client.HTTPConnection('localhost', 8000, timeout=10)\n\n headers = {\n \"Content-type\": \"text/plain\"\n }\n\n postData = \"Test http.server from http.client :D\"\n\n myConnection.request(\"POST\", \"/\", postData, headers)\n response = myConnection.getresponse()\n print(\"Status: {} and reason: {}\".format(response.status, response.reason))\n myData = response.read()\n print(myData.decode(\"utf-8\") )\n myConnection.close() \n\n\ndef CrearMenu(masterRoot):\n\n ########### menu ############\n #Se crea la barra\n barraDeMenu=Menu(masterRoot, tearoff=0,relief=FLAT, font=(\"Verdana\", 12),activebackground='red')\n #Se crean los menus que se deseen\n archivo=Menu(barraDeMenu, tearoff=0)\n #Crear las opciones de la opción del menú\n #Se elimino el comando de crear Ventana por problemas con las imagenes\n\n archivo.add_command(label=\"Nueva ventana\")\n archivo.add_command(label=\"Abrir query\",command=abrir)\n archivo.add_command(label=\"Abrir un modelo\")\n archivo.add_separator()\n archivo.add_command(label=\"Nueva Query\",command=lambda: añadir('Nuevo'))\n archivo.add_command(label=\"Guardar como...\",command=guardarComo)\n archivo.add_command(label=\"Guardar\",command=guardarArchivo)\n archivo.add_command(label=\"Cerrar pestaña actual\",command=cerrarPestaña)\n archivo.add_separator()\n archivo.add_command(label=\"Salir\")\n\n #creando el Editar\n editar=Menu(barraDeMenu, tearoff=0)\n #agregando su lista\n editar.add_command(label=\"Cortar\")\n editar.add_command(label=\"Pegar\")\n editar.add_command(label=\"Copiar\")\n editar.add_separator()\n editar.add_command(label=\"Seleccionar todo\")\n editar.add_command(label=\"Formato\")\n editar.add_command(label=\"Preferencias\")\n\n #se agrega Tools\n tools=Menu(barraDeMenu, tearoff=0)\n #se agrega su lista\n tools.add_command(label=\"Configuración\")\n tools.add_command(label=\"Utilidades\")\n #Temporary tools to test client-server connection\n tools.add_command(label=\"SELECT (GET)\", command = myGET)\n tools.add_command(label=\"CREATE (POST)\", command = myPOST)\n \n\n #se agrega ayuda\n ayuda=Menu(barraDeMenu, tearoff=0)\n #lista de ayuda\n ayuda.add_command(label=\"Documentación de TytuSQL\")\n ayuda.add_command(label=\"Acerca de TytuSQL\")\n\n #Se agrgan los menús a la barra\n barraDeMenu.add_cascade(label=\"Archivo\",menu=archivo)\n barraDeMenu.add_cascade(label=\"Editar\",menu=editar)\n barraDeMenu.add_cascade(label=\"Herramientas\",menu=tools)\n barraDeMenu.add_cascade(label=\"Ayuda\",menu=ayuda)\n #Se indica que la barra de menú debe estar en la ventana\n return barraDeMenu\n\ndef abrir():\n global archivo\n global notebook\n global control\n archivo = filedialog.askopenfilename(title = \"Abrir Archivo\")\n if archivo != '':\n name = os.path.basename(archivo)\n añadir(name)\n lenguaje = pathlib.Path(archivo).suffix\n entrada = open(archivo, encoding=\"utf-8\")\n content = entrada.read()\n textos[control-1].text.insert(tk.INSERT, content)\n entrada.close()\n notebook.select(control-1)\ndef guardarArchivo():\n global archivo\n idx = 0\n if notebook.select():\n idx = notebook.index('current')\n if archivo == \"\":\n guardarComo()\n else:\n guardarc = open(archivo, \"w\", encoding=\"utf-8\")\n guardarc.write(textos[idx].text.get(1.0, END))\n guardarc.close()\n\ndef guardarComo():\n global archivo\n idx = 0\n if notebook.select():\n idx = notebook.index('current')\n guardar = filedialog.asksaveasfilename(title = \"Guardar Archivo\")\n if guardar != '':\n fguardar = open(guardar, \"w+\", encoding=\"utf-8\")\n fguardar.write(textos[idx].text.get(1.0, END))\n fguardar.close()\n archivo = guardar\n\ndef CrearVentana():\n raiz = Tk()\n #Configuracion de ventana\n raiz.title(\"TytuSQL\") #Cambiar el nombre de la ventana\n #raiz.iconbitmap('resources/icon.ico')\n raiz.rowconfigure(0, minsize=800, weight=1)\n raiz.columnconfigure(1, minsize=800, weight=1)\n raiz.config(menu=CrearMenu(raiz), background='silver')\n\n #Frame del Arbol\n FrameIzquiero = Frame(raiz, relief=RAISED, bd=2)\n FrameIzquiero.pack(side=\"left\", fill=\"both\")\n #Se llama a la clase Arbol\n Arbol(FrameIzquiero)\n\n #Boton para realizar consulta\n Button(raiz, text=\"Enviar Consulta\").pack(side=\"top\",fill=\"both\")\n #Consola de Salida\n consola = Text(raiz)\n consola.pack(side=\"bottom\",fill=\"both\")\n consola.insert(1.0,\"Consola de Salida\")\n consola.config(state=DISABLED)\n ###### CREAMOS EL PANEL PARA LAS PESTAÑAS ########\n global notebook\n global control\n notebook=ttk.Notebook(raiz)\n notebook.pack(side=\"right\", fill=\"both\", expand=True)\n añadir('Nuevo')\n raiz.mainloop()\n\ndef añadir(titulo):\n global control\n global notebook\n formularios.append(Frame(notebook,bg=\"white\"))\n contador=control\n notebook.add(formularios[contador], text=titulo)\n valor=Campo(formularios[contador])\n valor.pack(side=\"left\", fill=\"both\",expand=True)\n vsb=Scrollbar(formularios[contador],orient=\"vertical\",command=valor.text.yview)\n valor.text.configure(yscrollcommand=vsb.set)\n vsb.pack(side=\"right\",fill=\"y\")\n textos.append(valor)\n contador=control+1\n control=contador\n\ndef cerrarPestaña():\n global notebook\n global control\n b=notebook.select()\n a=notebook.index(b)\n notebook.forget(a)\n\ndef main():\n CrearVentana()\nif __name__ == \"__main__\":\n main()\n","sub_path":"client/team04/ventana.py","file_name":"ventana.py","file_ext":"py","file_size_in_byte":6424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"157999763","text":"import sys\n\nNUM_DAYS = 368\nBUCKETS_PER_DAY = 6\n\ndef findHigherThanAvg(inFNm, inFNm2, outFNm, num_time_buckets=NUM_DAYS*BUCKETS_PER_DAY):\n with open(outFNm, \"w\") as fOut:\n placeToFreq = {}\n with open(inFNm, \"r\") as fIn:\n for line in fIn:\n vals = line.strip().split(\" \")\n freq = int(vals[0])\n coords = vals[1].split(\",\")\n placeToFreq[tuple(coords)] = freq\n with open(inFNm2, \"r\") as fIn:\n for line in fIn:\n vals = line.strip().split(\" \")\n coords = vals[1].split(\",\")\n coords = (coords[0], coords[1])\n freq = float(vals[0])\n percent = freq/placeToFreq[coords]\n for i in range(1, len(vals)):\n fOut.write(\"%s,\" % vals[i])\n fOut.write(\"%f,%d\\n\" % (percent, freq))\n\nif __name__ == \"__main__\":\n findHigherThanAvg(sys.argv[1], sys.argv[2], sys.argv[3])\n","sub_path":"time_freq.py","file_name":"time_freq.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"448138116","text":"from xml.dom import minidom\n\n\ndef show(file):\n doc = minidom.parse(file)\n name = doc.getElementsByTagName(\"name\")[0]\n print(name.firstChild.data)\n books = doc.getElementsByTagName(\"book\")\n for book in books:\n sid = book.getAttribute(\"id\")\n author = book.getElementsByTagName(\"author\")[0]\n title = book.getElementsByTagName(\"title\")[0]\n genre = book.getElementsByTagName(\"genre\")[0]\n price = book.getElementsByTagName(\"price\")[0]\n print(\"ID: %s, Author: %s, Title: %s, Genre: %s, Price: %s\" %\n (sid, author.firstChild.data, title.firstChild.data, genre.firstChild.data, price.firstChild.data))\n\n\nshow(\"books.xml\")\n","sub_path":"Python2/Excercise3_DOM.py","file_name":"Excercise3_DOM.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"627447965","text":"\nfrom graph import Graph\nfrom heap import PriorityQueueUpdate\n\n\ndef optimal_path_dijksta(graph, source, destimation):\n pq = PriorityQueueUpdate()\n pq.enqueue(source, 0)\n source_vertex = graph.get_vertex(source)\n source_vertex.cost = 0\n path = []\n while pq.size() > 0:\n dest = pq.dequeue()\n dest_vertex = graph.get_vertex(dest.key)\n dest_vertex.visited = True\n\n if dest.key == destimation:\n current = dest_vertex\n path.append(destimation)\n while current.previous:\n path.insert(0, current.previous.name)\n current = current.previous\n\n return path, dest_vertex.cost\n\n for _, edge in dest_vertex.edges.items():\n if graph.get_vertex(edge.finish.name).visited is False:\n cost = dest_vertex.cost + edge.weight\n if cost < edge.finish.cost:\n edge.finish.cost = cost\n graph.get_vertex(edge.finish.name).cost = cost\n graph.get_vertex(edge.finish.name).previous = dest_vertex\n pq.enqueue(edge.finish.name, edge.finish.cost)\n\n return None\n\n\ng = Graph()\ng.add_vertex('A')\ng.add_vertex('B')\ng.add_vertex('C')\ng.add_vertex('D')\ng.add_vertex('E')\ng.add_vertex('F')\ng.add_vertex('G')\ng.add_vertex('H')\n\ng.add_edge('A', 'B', 20)\ng.add_edge('A', 'D', 80)\ng.add_edge('A', 'G', 20)\ng.add_edge('B', 'F', 10)\ng.add_edge('B', 'A', 20)\ng.add_edge('C', 'H', 20)\ng.add_edge('D', 'C', 10)\ng.add_edge('D', 'F', 40)\ng.add_edge('E', 'B', 80)\ng.add_edge('E', 'G', 30)\ng.add_edge('F', 'D', 40)\ng.add_edge('G', 'A', 20)\ng.add_edge('G', 'D', 120)\n\nprint(optimal_path_dijksta(g, 'E', 'H'))\n","sub_path":"python/graph/graph_dijkstra.py","file_name":"graph_dijkstra.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"361810925","text":"#!/usr/bin/python3\n\nimport os\nimport subprocess as sp\n\nenv_vars = dict(os.environ)\n\ncreate_file = ['echo', 'This is a message for:', env_vars[\"USER\"]]\n\nwith open(\"/tmp/file.out\", \"w\") as f:\n result = sp.call(create_file, stderr=sp.DEVNULL, stdout=f)\n if result == 0:\n print(\"Sucessfull!\")\n else:\n print(\"Error while processing command.\")\n","sub_path":"os/calling_commands.py","file_name":"calling_commands.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"127309482","text":"# -*- coding: utf-8 -*-\ndef KOLVO_KRIT(): #запрос количества критериев с проверкой\n i = True\n while i == True:\n print('\\n-----')\n N = input('* Введите количество критериев целым числом: ')\n \n if N == 'exit': break\n \n if N.isdigit() == True:\n N = int(N)\n break\n else:\n print('\\n** Необходимо целое число!')\n continue\n return N\n\n\ndef WHAT_VALUE(I,J): #запрос оценки критериев с проверкой\n i = True\n while i == True:\n print('\\n-----')\n print('* В методе Саати для оценки относительной важности критериев рекомендуется специальная шкала от 1 до 9, где:\\n** 1 - компонентs равной важности,\\n** 3 - умеренное превосходство,\\n** 5 - существенное превосходство,\\n** 7 - значительное превосходство,\\n** 9 - очень сильное превосходство.\\n** !!Значения 2, 4, 6, 8 - используются как промежуточные между двумя соседними компонентами.')\n print('\\n*** Относительная важность ритерия -№'+str(I)+' отностиельно -№'+str(J))\n VALUE = input('**** Введите оценку критериев ненулевым целым числом(от 1 до 9): ')\n \n if VALUE.isdigit() == True and int(VALUE) > 0 and int(VALUE) <= 9:\n break\n else:\n print('\\n***** Необходимо целое число от 1 до 9!')\n continue\n return VALUE\n\n\ndef MATRIX(N): #создание матрицы\n A = []\n N = N + 1\n for i in range(N):\n B = []\n for j in range(N): B.append(None)\n A.append(B)\n\n for i in range(N):\n for j in range(N):\n \n if A[i][j] != None: continue\n \n VALUE = 000\n \n if j == 0: VALUE = 'к№' + str(i) \n if i == 0: VALUE = 'к№' + str(j)\n \n if i == j: \n VALUE = 1\n if i == 0: VALUE = 'Кр '\n \n if VALUE == 000: VALUE = WHAT_VALUE(i,j) \n \n VALUE = str(VALUE)\n \n if VALUE.isdigit() == True: \n VALUE = round(float(VALUE),2)\n A[j][i] = round(1 / VALUE,2)\n \n A[i][j] = VALUE \n return A\n\n\ndef isint(value): #определение целое ли число\n try:\n float(value)\n return True\n except ValueError:\n return False\n\n\ndef isfloat(value): #определение дробно ли число\n try:\n float(value)\n return True\n except ValueError:\n return False\n\n\ndef WHAT_KOEF(A): #расчет коэфициентов\n all_sum = 0\n W = []\n for i in range(len(A)):\n W.append(0)\n if i == 0: continue\n \n for j in range(len(A)):\n OZENKA = A[i][j] \n\n if isfloat(OZENKA) == True or isint(OZENKA) == True:\n \n all_sum = all_sum + OZENKA\n \n W[i] = W[i] + OZENKA\n \n for i in range(len(A)): \n W[i] = W[i] / all_sum\n W[i] = round(W[i],2)\n return W\n \n \ndef PRINT_KOEF(W): #вывод коэфициентов\n print('\\n-----')\n print('Весовые коэффициенты критериев:')\n for i in range(len(W)):\n if i == 0: continue\n print('Критерий №' + str(i) + ' = ' + str(W[i]))\n\n\ndef PRINT_MATRIX(A): #вывод матрицы\n print('\\n-----')\n for i in range(len(A)):\n LINE = ''\n for j in range(len(A)): \n LINE = LINE + str(A[i][j]) + ' '\n print(LINE)\n\n\nrabota = True\nwhile rabota == True:\n print('\\n----------------')\n print('!!! Если необходимо завершить работу введите \"exit\" вместо количества критериев')\n \n n = KOLVO_KRIT() \n if n == 'exit': break\n a = MATRIX(n)\n PRINT_MATRIX(a)\n w = WHAT_KOEF(a)\n PRINT_KOEF(w)\n","sub_path":"analiz.py","file_name":"analiz.py","file_ext":"py","file_size_in_byte":4442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"561955960","text":"class Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n HashMap = {}\n for i in strs:\n B = list(i)\n B.sort()\n # print(B)\n current = \"\".join(B)\n HashMap[current] = [i] if current not in HashMap else HashMap[current] + [i]\n return [HashMap[i] for i in HashMap] \n","sub_path":"Week_02/lc49.py","file_name":"lc49.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"608508263","text":"import turtle\n'''\nfilename: recCircle.py\nlanguage: python3\nauthor: Alex Habermann hehe3301@gmail.com\npurpose: This program draws recursive circles with one circle at each four vertexs of the circle\n'''\n\n\ndef ready(rad):\n turtle.speed(0)\n turtle.ht()\n turtle.up()\n turtle.goto(0,-rad)\n turtle.down()\n turtle.colormode(1)\n turtle.bgcolor('black')\n turtle.pensize(1.1)\n\ndef drawcircle(depth,rad,maxdepth):\n if depth == 0:\n pass\n else:\n colorset(depth,maxdepth)\n turtle.circle(rad,90)\n drawcircle(depth-1,41.4*rad/100,maxdepth)\n colorset(depth,maxdepth)\n turtle.circle(rad,90)\n drawcircle(depth-1,41.4*rad/100,maxdepth)\n colorset(depth,maxdepth)\n turtle.circle(rad,90)\n drawcircle(depth-1,41.4*rad/100,maxdepth)\n colorset(depth,maxdepth)\n turtle.circle(rad,90)\n drawcircle(depth-1,41*rad/100,maxdepth)\n colorset(depth,maxdepth)\ndef colorset(depth,maxdepth):\n x,y=turtle.pos()\n R=((depth-1)/maxdepth)\n G=(x*x + y*y)/(300*300)\n B=((maxdepth-depth+1)/maxdepth)\n turtle.pencolor((R,G,B))\n \ndef main():\n rad=250\n depth=6\n# rad=int(input('What max radius do you want to use? '))\n# depth=int(input('What depth do you want to draw? '))\n ready(rad)\n drawcircle(depth,rad,depth)\n turtle.up()\n turtle.goto(-250,-250)\n turtle.down()\n turtle.write('Alex Habermann')\nmain()\n","sub_path":"recCircle.py","file_name":"recCircle.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"361081960","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import MainMenu\nfrom .forms import BookForm\nfrom django.http import HttpResponseRedirect\nfrom .models import Book\nfrom django.views.generic.edit import CreateView\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.urls import reverse_lazy\nfrom django.contrib.auth.decorators import login_required\n\n\nclass Register(CreateView):\n template_name = 'registration/register.html'\n form_class = UserCreationForm\n success_url = reverse_lazy('register-success')\n\n def form_valid(self, form):\n form.save()\n return HttpResponseRedirect(self.success_url)\n\n\ndef index(request):\n return render(request, \n 'bookMng/index.html',\n {\n 'item_list': MainMenu.objects.all()\n })\n\n\n@login_required(login_url=reverse_lazy('login'))\ndef all_books(request):\n books = Book.objects.all()\n\n for b in books:\n b.pic_path = b.picture.url[14:]\n\n return render(request,\n 'bookMng/all_books.html',\n {\n 'item_list': MainMenu.objects.all(),\n 'books': books,\n })\n\n\n@login_required(login_url=reverse_lazy('login'))\ndef my_books(request):\n books = Book.objects.filter(username=request.user)\n\n for b in books:\n b.pic_path = b.picture.url[14:]\n\n return render(request,\n 'bookMng/my_books.html',\n {\n 'item_list': MainMenu.objects.all(),\n 'books': books,\n })\n\n\n@login_required(login_url=reverse_lazy('login'))\ndef post_book(request):\n submitted = False\n if request.method == 'POST':\n form = BookForm(request.POST, request.FILES)\n if form.is_valid():\n # form.save()\n book = form.save(commit=False)\n try:\n book.username = request.user\n except Exception:\n pass\n book.save()\n return HttpResponseRedirect('/post_book?submitted=True')\n else:\n form = BookForm()\n if 'submitted' in request.GET:\n submitted = True\n\n return render(request,\n 'bookMng/post_book.html',\n {\n 'form': form,\n 'item_list': MainMenu.objects.all(),\n 'submitted': submitted\n })\n\n\n@login_required(login_url=reverse_lazy('login'))\ndef about_us(request):\n return render(request, 'bookMng/about_us.html')\n\n\n@login_required(login_url=reverse_lazy('login'))\ndef book_details(request, book_id):\n book = Book.objects.get(id=book_id)\n\n book.pic_path = book.picture.url[14:]\n return render(request,\n 'bookMng/book_details.html',\n {\n 'item_list': MainMenu.objects.all(),\n 'book': book,\n })\n\n\n@login_required(login_url=reverse_lazy('login'))\ndef book_delete(request, book_id):\n book = Book.objects.get(id=book_id)\n book.delete()\n\n return render(request,\n 'bookMng/book_delete.html',\n {\n 'item_list': MainMenu.objects.all(),\n })","sub_path":"bookMng/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"62630321","text":"from consts import Consts\nfrom parsing import Parsing\n\n\nclass Aux:\n\n @property\n def unique_tags_from_train_file(self) -> dict:\n tags_from_train = Parsing.parse_wtag_file_to_tags(\"../\" + Consts.PATH_TO_TRAINING)\n idx = 1\n tags_dict = {}\n for tag in tags_from_train:\n if tag not in tags_dict:\n tags_dict[tag] = idx\n idx += 1\n return tags_dict\n\n @property\n def unique_suffixes_and_prefixes(self):\n sentences, _ = Parsing().parse_wtag_file_to_lists(\"../\" + Consts.PATH_TO_TRAINING)\n words_in_train = set()\n for sentence in sentences:\n for word in sentence:\n words_in_train.add(word.lower())\n\n with open(\"prefix.txt\") as p:\n prefixes = {line.rstrip().lower()[:4] for line in p.readlines()}\n\n with open(\"suffix.txt\") as s:\n suffixes = set()\n for word in s.readlines():\n if len(word) > 4:\n suffixes.add(word[-4].rstrip().lower())\n else:\n suffixes.add(word.rstrip().lower())\n\n prefixes_in_train = set()\n suffixes_in_train = set()\n for word in words_in_train:\n for prefix in prefixes:\n if word.startswith(prefix):\n prefixes_in_train.add(prefix)\n for suffix in suffixes:\n if word.endswith(suffix):\n suffixes_in_train.add(suffix)\n\n return sorted(prefixes_in_train), sorted(suffixes_in_train)\n\n\nif __name__ == \"__main__\":\n tags = Aux().unique_tags_from_train_file\n print(\"tags:\", tags, \"\\namount:\", len(tags))\n # prefixes_output, suffixes_output = Aux().unique_suffixes_and_prefixes\n # print(\"prefixes:\", prefixes_output, \"\\namount:\", len(prefixes_output))\n # print(\"suffixes:\", suffixes_output, \"\\namount:\", len(suffixes_output))\n","sub_path":"utils/auxForTags.py","file_name":"auxForTags.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"218714155","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# vi: ts=4 sw=4\n\nfrom ..Protocols import *\n\n\n\nclass thumbnails_contrast(thumbnails):\n \n def __init__(self, name='thumbnails', **kwargs):\n \n self.name = self.__class__.__name__ if name is None else name\n \n self.default_ext = '.jpg'\n self.run_args = {\n 'crop' : 0.5,\n 'blur' : 1.0,\n 'resize' : 0.5,\n 'cmap' : mpl.cm.bone,\n }\n self.run_args.update(kwargs)\n \n\n @run_default\n def run(self, data, output_dir, **run_args):\n \n results = {}\n \n outfile = self.get_outfile(data.name, output_dir)\n data.plot_image(save=outfile, size=10*run_args['resize'], **run_args)\n \n return results\n \n","sub_path":"SciAnalysis/ImAnalysis/Flakes/Protocols.py","file_name":"Protocols.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"255865456","text":"# coding:utf-8\nfrom flask import jsonify,request\nfrom . import api\nfrom ..entity import MarketArea\n\n\n@api.route('/getmarketarea',methods=['POST'])\ndef getMarketArea():\n gid=request.args.get('gid',1,type=int)\n query = MarketArea.query.filter(MarketArea.gid == gid)\n if query is None:\n return jsonify({\n 'geom': 'None'\n })\n jsondata = []\n for marketarea in query:\n jsondata.append(marketarea.to_json())\n return jsonify({\n 'data': jsondata\n })\n","sub_path":"app/api/posts.py","file_name":"posts.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"584494375","text":"from __future__ import (absolute_import, division, print_function, \n unicode_literals)\n\nimport numpy as np\n\nfrom .constants import Constants\n\nfrom ._wrffortran import (dcomputetk, dinterp3dz, dinterp2dxy, dinterp1d,\n dcomputeseaprs, dfilter2d, dcomputerh, dcomputeuvmet,\n dcomputetd, dcapecalc3d, dcloudfrac, wrfcttcalc, \n calcdbz, dcalrelhl, dcalcuh, dcomputepv, \n dcomputeabsvort, dlltoij, dijtoll, deqthecalc,\n omgcalc, virtual_temp, wetbulbcalc, dcomputepw,\n wrf_monotonic, wrf_vintrp, dcomputewspd, \n dcomputewdir)\n\nfrom .decorators import (left_iteration, cast_type, \n extract_and_transpose, check_args)\nfrom .util import combine_dims, npbytes_to_str, psafilepath\nfrom .py3compat import py3range\nfrom .specialdec import (uvmet_left_iter, cape_left_iter, \n cloudfrac_left_iter, check_cape_args)\n\nclass DiagnosticError(Exception):\n \"\"\"Raised when an error occurs in a diagnostic routine.\"\"\"\n def __init__(self, message=None):\n \"\"\"Initialize a :class:`wrf.DiagnosticError` objection.\n \n Args:\n \n message (:obj:`str`): The error message.\n \n \"\"\"\n self._msg = message\n \n def __str__(self):\n return self._msg\n \n def __call__(self, message):\n \"\"\"Callable method to make the exception object raise itself.\n \n This allows the exception to be thrown from inside Fortran routines \n by using f2py's callback mechanism. This is no longer used within \n wrf-python, but may be useful to other users.\n \n See Also:\n \n `f2py doc `_\n \n \"\"\"\n raise self.__class__(message)\n\n# The routines below are thin wrappers around the Fortran functions. These \n# are not meant to be called by end users. Use the public API instead for \n# that purpose.\n\n# IMPORTANT! Unless otherwise noted, all variables used in the routines \n# below assume that Fortran-ordered views are being used. This allows\n# f2py to pass the array pointers directly to the Fortran routine.\n\n@check_args(0, 3, (3, 3, None, None))\n@left_iteration(3, 2, ref_var_idx=0, ignore_args=(2,3))\n@cast_type(arg_idxs=(0,1))\n@extract_and_transpose()\ndef _interpz3d(field3d, z, desiredloc, missingval, outview=None):\n \"\"\"Wrapper for dinterp3dz.\n \n Located in wrf_user.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty(field3d.shape[0:2], np.float64, order=\"F\")\n \n result = dinterp3dz(field3d, \n outview,\n z, \n desiredloc, \n missingval)\n return result\n\n\n@check_args(0, 3, (3,))\n@left_iteration(3, combine_dims([(0,-3),(1,-2)]), ref_var_idx=0, \n ignore_args=(1,))\n@cast_type(arg_idxs=(0,1))\n@extract_and_transpose()\ndef _interp2dxy(field3d, xy, outview=None):\n \"\"\"Wrapper for dinterp2dxy.\n \n Located in wrf_user.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty((xy.shape[-1], field3d.shape[-1]), np.float64, \n order=\"F\")\n \n result = dinterp2dxy(field3d,\n outview,\n xy)\n return result\n\n\n@check_args(0, 1, (1,1,None,None))\n@left_iteration(1, combine_dims([(2,0)]), ref_var_idx=0, ignore_args=(2,3))\n@cast_type(arg_idxs=(0,1,2))\n@extract_and_transpose()\ndef _interp1d(v_in, z_in, z_out, missingval, outview=None):\n \"\"\"Wrapper for dinterp1d.\n \n Located in wrf_user.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(z_out)\n\n result = dinterp1d(v_in,\n outview,\n z_in,\n z_out,\n missingval)\n \n return result\n\n\n@left_iteration(3, combine_dims([(3,0), (1,0)]), \n ref_var_idx=0, ignore_args=(1,3,4))\n@cast_type(arg_idxs=(0,))\n@extract_and_transpose(do_transpose=False)\ndef _vertcross(field3d, xy, var2dz, z_var2d, missingval, outview=None):\n \"\"\"Return the vertical cross section.\n \n This routine was originally written in scripted NCL code and doesn't \n directly wrap a Fortran routine.\n \n Located in WRFUserARW.ncl.\n \n \"\"\"\n # Note: This is using C-ordering\n if outview is None:\n outview = np.empty((z_var2d.shape[0], xy.shape[0]), dtype=var2dz.dtype)\n \n var2dtmp = _interp2dxy(field3d, xy)\n \n for i in py3range(xy.shape[0]):\n outview[:,i] = _interp1d(var2dtmp[:,i], var2dz[:,i], z_var2d, \n missingval)\n \n return outview\n\n\n@left_iteration(2, combine_dims([(1,0)]), ref_var_idx=0, ignore_args=(1,))\n@cast_type(arg_idxs=(0,))\n@extract_and_transpose(do_transpose=False)\ndef _interpline(field2d, xy, outview=None):\n \"\"\"Return the two-dimensional field interpolated to a line.\n \n This routine was originally written in scripted NCL code and doesn't \n directly wrap a Fortran routine.\n \n Located in WRFUserARW.ncl.\n \n \"\"\"\n # Note: This is using C-ordering\n if outview is None:\n outview = np.empty(xy.shape[0], dtype=field2d.dtype)\n\n tmp_shape = (1,) + field2d.shape\n var2dtmp = np.empty(tmp_shape, field2d.dtype)\n var2dtmp[0,:,:] = field2d[:,:]\n \n var1dtmp = _interp2dxy(var2dtmp, xy)\n \n outview[:] = var1dtmp[0, :]\n \n return outview\n\n\n@check_args(0, 3, (3,3,3,3)) \n@left_iteration(3, 2, ref_var_idx=0)\n@cast_type(arg_idxs=(0,1,2,3))\n@extract_and_transpose()\ndef _slp(z, t, p, q, outview=None):\n \"\"\"Wrapper for dcomputeseaprs.\n \n Located in wrf_user.f90.\n \n \"\"\"\n t_surf = np.zeros(z.shape[0:2], np.float64, order=\"F\")\n t_sea_level = np.zeros(z.shape[0:2], np.float64, order=\"F\")\n level = np.zeros(z.shape[0:2], np.int32, order=\"F\")\n \n if outview is None:\n outview = np.empty(z.shape[0:2], np.float64, order=\"F\")\n \n errstat = np.array(0)\n errmsg = np.zeros(Constants.ERRLEN, \"c\")\n \n result = dcomputeseaprs(z,\n t,\n p,\n q,\n outview,\n t_sea_level,\n t_surf,\n level,\n errstat=errstat,\n errmsg=errmsg)\n \n if int(errstat) != 0:\n raise DiagnosticError(\"\".join(npbytes_to_str(errmsg)).strip())\n \n return result\n\n\n@check_args(0, 3, (3,3))\n@left_iteration(3, 3, ref_var_idx=0)\n@cast_type(arg_idxs=(0,1))\n@extract_and_transpose()\ndef _tk(pressure, theta, outview=None):\n \"\"\"Wrapper for dcomputetk.\n \n Located in wrf_user.f90.\n \n \"\"\"\n # No need to transpose here since operations on 1D array\n shape = pressure.shape\n if outview is None: \n outview = np.empty_like(pressure)\n result = dcomputetk(outview.ravel(order=\"A\"),\n pressure.ravel(order=\"A\"), \n theta.ravel(order=\"A\"))\n result = np.reshape(result, shape, order=\"F\")\n \n return result \n\n\n@check_args(0, 2, (2,2))\n@left_iteration(2, 2, ref_var_idx=0)\n@cast_type(arg_idxs=(0,1))\n@extract_and_transpose()\ndef _td(pressure, qv_in, outview=None):\n \"\"\"Wrapper for dcomputetd.\n \n Located in wrf_user.f90.\n \n \"\"\"\n shape = pressure.shape\n if outview is None:\n outview = np.empty_like(pressure)\n \n result = dcomputetd(outview.ravel(order=\"A\"),\n pressure.ravel(order=\"A\"), \n qv_in.ravel(order=\"A\"))\n result = np.reshape(result, shape, order=\"F\")\n \n return result\n\n\n@check_args(0, 2, (2,2,2))\n@left_iteration(2, 2, ref_var_idx=0)\n@cast_type(arg_idxs=(0,1,2))\n@extract_and_transpose()\ndef _rh(qv, q, t, outview=None):\n \"\"\"Wrapper for dcomputerh.\n \n Located in wrf_user.f90.\n \n \"\"\"\n shape = qv.shape\n if outview is None:\n outview = np.empty_like(qv)\n result = dcomputerh(qv.ravel(order=\"A\"),\n q.ravel(order=\"A\"),\n t.ravel(order=\"A\"),\n outview.ravel(order=\"A\"))\n result = np.reshape(result, shape, order=\"F\")\n \n return result\n\n\n# Note: combining the -3 and -2 dimensions from u, then the -1 dimension \n# from v\n@check_args(0, 3, (3,3,2,2,2,2), stagger=(-1,-2,-1,-2,None,None),\n refstagdim=-1)\n@left_iteration(3, combine_dims([(0, (-3,-2)), \n (1, (-1,))]), \n ref_var_idx=0, ignore_args=(6,7))\n@cast_type(arg_idxs=(0,1,2,3,4,5))\n@extract_and_transpose()\ndef _avo(u, v, msfu, msfv, msfm, cor, dx, dy, outview=None):\n \"\"\"Wrapper for dcomputeabsvort.\n \n Located in wrf_pvo.f90.\n \n \"\"\"\n if outview is None:\n outshape = (v.shape[0],) + u.shape[1:]\n outview = np.empty(outshape, np.float64, order=\"F\")\n \n result = dcomputeabsvort(outview,\n u,\n v,\n msfu,\n msfv,\n msfm,\n cor,\n dx,\n dy)\n \n return result\n\n\n@check_args(0, 3, (3,3,3,3,2,2,2,2), stagger=(-1,-2,None,None,-1,-2,None, \n None),\n refstagdim=-1)\n@left_iteration(3, 3, ref_var_idx=2, ignore_args=(8,9))\n@cast_type(arg_idxs=(0,1,2,3,4,5,6,7))\n@extract_and_transpose()\ndef _pvo(u, v, theta, prs, msfu, msfv, msfm, cor, dx, dy, outview=None):\n \"\"\"Wrapper for dcomputepv.\n \n Located in wrf_pvo.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(prs)\n \n result = dcomputepv(outview,\n u,\n v,\n theta,\n prs,\n msfu,\n msfv,\n msfm,\n cor,\n dx,\n dy)\n \n return result\n\n\n@check_args(0, 3, (3,3,3))\n@left_iteration(3, 3, ref_var_idx=0)\n@cast_type(arg_idxs=(0,1,2))\n@extract_and_transpose()\ndef _eth(qv, tk, p, outview=None):\n \"\"\"Wrapper for deqthecalc.\n \n Located in eqthecalc.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(qv)\n \n result = deqthecalc(qv,\n tk,\n p,\n outview)\n \n return result\n\n\n@uvmet_left_iter()\n@cast_type(arg_idxs=(0,1,2,3))\n@extract_and_transpose()\ndef _uvmet(u, v, lat, lon, cen_long, cone, isstag=0, has_missing=False, \n umissing=Constants.DEFAULT_FILL, vmissing=Constants.DEFAULT_FILL, \n uvmetmissing=Constants.DEFAULT_FILL, outview=None):\n \"\"\"Wrapper for dcomputeuvmet.\n \n Located in wrf_user.f90.\n \n \"\"\"\n longca = np.zeros(lat.shape[0:2], np.float64, order=\"F\")\n longcb = np.zeros(lon.shape[0:2], np.float64, order=\"F\")\n rpd = Constants.PI/180.\n \n if outview is None:\n outdims = u.shape + (2,)\n outview = np.empty(outdims, np.float64, order=\"F\")\n \n result = dcomputeuvmet(u,\n v,\n outview,\n longca,\n longcb,\n lon,\n lat,\n cen_long,\n cone,\n rpd,\n isstag, \n has_missing,\n umissing,\n vmissing,\n uvmetmissing)\n \n return result\n\n\n@check_args(0, 3, (3,3,3,3))\n@left_iteration(3, 3, ref_var_idx=0)\n@cast_type(arg_idxs=(0,1,2,3))\n@extract_and_transpose()\ndef _omega(qv, tk, w, p, outview=None):\n \"\"\"Wrapper for omgcalc.\n \n Located in wrf_rip_phys_routines.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(qv)\n \n result = omgcalc(qv,\n tk,\n w,\n p,\n outview)\n \n return result\n\n\n@check_args(0, 3, (3,3))\n@left_iteration(3, 3, ref_var_idx=0)\n@cast_type(arg_idxs=(0,1))\n@extract_and_transpose()\ndef _tv(tk, qv, outview=None):\n \"\"\"Wrapper for virtual_temp.\n \n Located in wrf_rip_phys_routines.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(tk)\n \n result = virtual_temp(tk,\n qv,\n outview)\n \n return result\n\n\n@check_args(0, 3, (3,3,3)) \n@left_iteration(3, 3, ref_var_idx=0, ignore_args=(3,))\n@cast_type(arg_idxs=(0,1,2))\n@extract_and_transpose()\ndef _wetbulb(p, tk, qv, psafile=psafilepath(), outview=None):\n \"\"\"Wrapper for wetbulbcalc.\n \n Located in wrf_rip_phys_routines.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(p)\n \n errstat = np.array(0)\n errmsg = np.zeros(Constants.ERRLEN, \"c\")\n \n result = wetbulbcalc(p,\n tk,\n qv,\n outview,\n psafile,\n errstat,\n errmsg)\n \n if int(errstat) != 0:\n raise DiagnosticError(\"\".join(npbytes_to_str(errmsg)).strip())\n \n return result\n\n\n@check_args(0, 3, (3,3,3,2)) \n@left_iteration(3, 2, ref_var_idx=0, ignore_args=(4,))\n@cast_type(arg_idxs=(0,1,2,3))\n@extract_and_transpose()\ndef _srhel(u, v, z, ter, top, outview=None):\n \"\"\"Wrapper for dcalrelhl.\n \n Located in wrf_relhl.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(ter)\n \n result = dcalrelhl(u, \n v, \n z, \n ter, \n top,\n outview)\n \n return result\n\n\n@check_args(2, 3, (3,2,3,3,3), stagger=(-3,None,None,None,-3)) \n@left_iteration(3, 2, ref_var_idx=2, ignore_args=(5,6,7,8))\n@cast_type(arg_idxs=(0,1,2,3,4))\n@extract_and_transpose()\ndef _udhel(zstag, mapfct, u, v, wstag, dx, dy, bottom, top, outview=None):\n \"\"\"Wrapper for dcalcuh.\n \n Located in calc_uh.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(mapfct)\n \n tem1 = np.zeros((u.shape[0], u.shape[1], u.shape[2]), np.float64, \n order=\"F\")\n tem2 = np.zeros((u.shape[0], u.shape[1], u.shape[2]), np.float64, \n order=\"F\")\n \n result = dcalcuh(zstag, \n mapfct, \n dx, \n dy, \n bottom, \n top, \n u,\n v, \n wstag, \n outview, \n tem1, \n tem2)\n \n return result\n\n\n@check_args(0, 3, (3,3,3,3), stagger=(None, None, None, -3)) \n@left_iteration(3, 2, ref_var_idx=0)\n@cast_type(arg_idxs=(0,1,2,3))\n@extract_and_transpose()\ndef _pw(p, tv, qv, ht, outview=None):\n \"\"\"Wrapper for dcomputepw.\n \n Located in wrf_pw.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty(p.shape[0:2], p.dtype, order=\"F\")\n \n result = dcomputepw(p,\n tv,\n qv,\n ht,\n outview)\n \n return result\n\n\n@check_args(0, 3, (3,3,3,3,3,3)) \n@left_iteration(3, 3, ref_var_idx=0, ignore_args=(6,7,8))\n@cast_type(arg_idxs=(0,1,2,3,4,5))\n@extract_and_transpose()\ndef _dbz(p, tk, qv, qr, qs, qg, sn0, ivarint, iliqskin, outview=None):\n \"\"\"Wrapper for calcdbz.\n \n Located in wrf_user_dbz.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(p)\n \n result = calcdbz(p,\n tk,\n qv,\n qr,\n qs,\n qg,\n sn0,\n ivarint,\n iliqskin,\n outview)\n \n return result\n\n\n@check_cape_args()\n@cape_left_iter()\n@cast_type(arg_idxs=(0,1,2,3,4,5), outviews=(\"capeview\", \"cinview\"))\n@extract_and_transpose(outviews=(\"capeview\", \"cinview\"))\ndef _cape(p_hpa, tk, qv, ht, ter, sfp, missing, i3dflag, ter_follow,\n psafile=psafilepath(), capeview=None, cinview=None):\n \"\"\"Wrapper for dcapecalc3d.\n \n Located in rip_cape.f90.\n \n \"\"\"\n if capeview is None:\n capeview = np.zeros(p_hpa.shape[0:3], p_hpa.dtype, order=\"F\")\n \n if cinview is None:\n cinview = np.zeros(p_hpa.shape[0:3], p_hpa.dtype, order=\"F\")\n \n errstat = np.array(0)\n errmsg = np.zeros(Constants.ERRLEN, \"c\")\n \n # note that p_hpa, tk, qv, and ht have the vertical flipped\n result = dcapecalc3d(p_hpa,\n tk,\n qv,\n ht,\n ter,\n sfp,\n capeview,\n cinview,\n missing,\n i3dflag,\n ter_follow,\n psafile,\n errstat,\n errmsg)\n \n if int(errstat) != 0:\n raise DiagnosticError(\"\".join(npbytes_to_str(errmsg)).strip())\n \n return result\n\n@check_args(0, 3, (3,3))\n@cloudfrac_left_iter()\n@cast_type(arg_idxs=(0, 1), outviews=(\"lowview\", \"medview\", \"highview\"))\n@extract_and_transpose(outviews=(\"lowview\", \"medview\", \"hightview\"))\ndef _cloudfrac(p, rh, lowview=None, medview=None, highview=None):\n \"\"\"Wrapper for dcloudfrace.\n \n Located in wrf_cloud_fracf.f90.\n \n \"\"\"\n if lowview is None:\n lowview = np.zeros(p.shape[0:2], p.dtype, order=\"F\")\n \n if medview is None:\n medview = np.zeros(p.shape[0:2], p.dtype, order=\"F\")\n \n if highview is None:\n highview = np.zeros(p.shape[0:2], p.dtype, order=\"F\")\n \n result = dcloudfrac(p, \n rh, \n lowview, \n medview, \n highview)\n \n return result\n\n\ndef _lltoxy(map_proj, truelat1, truelat2, stdlon,\n lat1, lon1, pole_lat, pole_lon,\n known_x, known_y, dx, dy, latinc, loninc, lat, lon,\n outview=None):\n \"\"\"Wrapper for dlltoij.\n \n Located in wrf_user_latlon_routines.f90.\n \n \"\"\"\n if outview is None:\n outview = np.zeros((2), dtype=np.float64, order=\"F\")\n \n errstat = np.array(0)\n errmsg = np.zeros(Constants.ERRLEN, \"c\")\n \n result = dlltoij(map_proj,\n truelat1,\n truelat2,\n stdlon,\n lat1,\n lon1,\n pole_lat,\n pole_lon,\n known_x,\n known_y,\n dx,\n dy,\n latinc,\n loninc,\n lat,\n lon,\n outview,\n errstat,\n errmsg)\n \n if int(errstat) != 0:\n raise DiagnosticError(\"\".join(npbytes_to_str(errmsg)).strip())\n \n return result\n\n\ndef _xytoll(map_proj, truelat1, truelat2, stdlon, lat1, lon1,\n pole_lat, pole_lon, known_x, known_y, dx, dy, latinc,\n loninc, x, y, outview=None):\n \"\"\"Wrapper for dijtoll.\n \n Located in wrf_user_latlon_routines.f90.\n \n \"\"\"\n if outview is None:\n outview = np.zeros((2), dtype=np.float64, order=\"F\")\n \n errstat = np.array(0)\n errmsg = np.zeros(Constants.ERRLEN, \"c\")\n \n result = dijtoll(map_proj,\n truelat1,\n truelat2,\n stdlon,\n lat1,\n lon1,\n pole_lat,\n pole_lon,\n known_x,\n known_y,\n dx,\n dy,\n latinc,\n loninc,\n x,\n y,\n outview,\n errstat,\n errmsg)\n \n if int(errstat) != 0:\n raise DiagnosticError(\"\".join(npbytes_to_str(errmsg)).strip())\n \n return result\n\n\n@check_args(0, 3, (3,3,3,3,3,3,2)) \n@left_iteration(3, 2, ref_var_idx=0, ignore_args=(7,))\n@cast_type(arg_idxs=(0,1,2,3,4,5,6))\n@extract_and_transpose()\ndef _ctt(p_hpa, tk, qice, qcld, qv, ght, ter, haveqci, outview=None):\n \"\"\"Wrapper for wrfcttcalc.\n \n Located in wrf_fctt.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(ter)\n \n result = wrfcttcalc(p_hpa,\n tk,\n qice,\n qcld,\n qv,\n ght,\n ter,\n outview,\n haveqci)\n \n return result\n\n\n@check_args(0, 2, (2,))\n@left_iteration(2, 2, ref_var_idx=0, ignore_args=(1,))\n@cast_type(arg_idxs=(0,))\n@extract_and_transpose()\ndef _smooth2d(field, passes, outview=None):\n \"\"\"Wrapper for dfilter2d.\n \n Located in wrf_user.f90.\n \n \"\"\"\n # Unlike NCL, this routine will not modify the values in place, but \n # copies the original data before modifying it.\n \n if isinstance(field, np.ma.MaskedArray):\n missing = field.fill_value\n else:\n missing = Constants.DEFAULT_FILL\n \n if outview is None:\n outview = field.copy(order=\"A\")\n else:\n outview[:] = field[:]\n \n field_tmp = np.zeros(outview.shape, outview.dtype, order=\"F\") \n\n dfilter2d(outview, \n field_tmp, \n passes,\n missing)\n \n return outview\n\n\n@check_args(0, 3, (3,3,2)) \n@left_iteration(3, 3, ref_var_idx=0, ignore_args=(3,4,5))\n@cast_type(arg_idxs=(0,1,2))\n@extract_and_transpose()\ndef _monotonic(var, lvprs, coriolis, idir, delta, icorsw, outview=None):\n \"\"\"Wrapper for wrf_monotonic.\n \n Located in wrf_vinterp.f90.\n \n \"\"\"\n # If icorsw is not 0, then the input variable might get modified by the \n # fortran routine. We don't want this, so make a copy and pass that on.\n var = var.copy(order=\"A\") if icorsw != 0 else var\n \n if outview is None:\n outview = np.empty_like(var)\n \n result = wrf_monotonic(outview,\n var,\n lvprs,\n coriolis,\n idir,\n delta,\n icorsw)\n \n return result\n\n\n# Output shape is interp_levels.shape + field.shape[-2:]\n@check_args(0, 3, (3,3,3,3,3,2,2,2,3)) \n@left_iteration(3, combine_dims([(9, (-1,)),\n (0, (-2,-1))]), \n ref_var_idx=0, ignore_args=(9,10,11,12,13,14))\n@cast_type(arg_idxs=(0,1,2,3,4,5,6,7,8,9))\n@extract_and_transpose()\ndef _vintrp(field, pres, tk, qvp, ght, terrain, sfp, smsfp,\n vcarray, interp_levels, icase, extrap, vcor, logp,\n missing, outview=None):\n \"\"\"Wrapper for wrf_vintrp.\n \n Located in wrf_vinterp.f90.\n \n \"\"\"\n if outview is None:\n outdims = field.shape[0:2] + interp_levels.shape\n outview = np.empty(outdims, field.dtype, order=\"F\")\n \n errstat = np.array(0)\n errmsg = np.zeros(Constants.ERRLEN, \"c\")\n \n result = wrf_vintrp(field,\n outview,\n pres,\n tk,\n qvp,\n ght,\n terrain,\n sfp,\n smsfp,\n vcarray,\n interp_levels,\n icase,\n extrap,\n vcor,\n logp,\n missing,\n errstat,\n errmsg)\n \n if int(errstat) != 0:\n raise DiagnosticError(\"\".join(npbytes_to_str(errmsg)).strip())\n \n return result\n\n@check_args(0, 2, (2,2)) \n@left_iteration(2, 2, ref_var_idx=0)\n@cast_type(arg_idxs=(0,1))\n@extract_and_transpose()\ndef _wspd(u, v, outview=None):\n \"\"\"Wrapper for dcomputewspd.\n \n Located in wrf_wind.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(u)\n \n result = dcomputewspd(outview,\n u,\n v)\n \n return result\n\n\n@check_args(0, 2, (2,2)) \n@left_iteration(2, 2, ref_var_idx=0)\n@cast_type(arg_idxs=(0,1))\n@extract_and_transpose()\ndef _wdir(u, v, outview=None):\n \"\"\"Wrapper for dcomputewdir.\n \n Located in wrf_wind.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(u)\n \n result = dcomputewdir(outview,\n u,\n v)\n \n return result\n \n\n","sub_path":"src/wrf/extension.py","file_name":"extension.py","file_ext":"py","file_size_in_byte":25450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"293679017","text":"#coding=utf-8\n# Python内置的@property装饰器就是负责把一个方法变成属性调用的:\n# 注意到这个神奇的@property,我们在对实例属性操作的时候,就知道该属性很可能不是直接暴露的,而是通过getter和setter方法来实现的。\n# 还可以定义只读属性,只定义getter方法,不定义setter方法就是一个只读属性:\n\n\n\n\nclass Student(object):\n\n @property\n def score(self):\n return self._score\n\n @score.setter\n def score(self, value):\n if not isinstance(value, int):\n raise ValueError('score must be an integer!')\n if value < 0 or value > 100:\n raise ValueError('score must between 0 ~ 100!')\n self._score = value\n\n def set_score(self, value):\n if not isinstance(value, int):\n raise ValueError('score must be an integer!')\n if value < 0 or value > 100:\n raise ValueError('score must between 0 ~ 100!')\n self._score = value\n\n def get_score(self):\n return self._score\n\ns = Student()\ns.score = 60\nprint('s.score =', s.score)\n\ns.set_score(70) # ok!\nprint(s.get_score())\ns.set_score(9999)\n\n# ValueError: score must between 0 ~ 100!\ns.score = 9999\n\n","sub_path":"com/classTest/highClassTest/propertyTest.py","file_name":"propertyTest.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"584602631","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# Usage: gen_json.py\n\n\"\"\" libs\n\"\"\"\nimport configparser\nimport os\nimport pandas as pd\nimport csv\nimport json\nimport pprint\nimport datetime\nimport urllib.error\nimport urllib.parse\nimport urllib.request\nimport http.client\nimport requests\nimport io\nimport chardet\n\n\"\"\" defs\n\"\"\"\ndef get_resource_file_dict(resource_file_dict_file):\n \n with open(resource_file_dict_file) as f:\n resource_file_dict = json.load(f)\n f.close()\n\n return(resource_file_dict)\n\ndef output_json(filepath, o_dict):\n\n f = open(filepath, 'w')\n json.dump(o_dict, f, indent=4, ensure_ascii=False)\n \n return()\n\ndef call_api(request_url):\n\n response_dict = None\n request = urllib.request.Request(request_url)\n\n try:\n with urllib.request.urlopen(request, timeout=3) as response:\n response_page = response.read()\n\n except urllib.error.HTTPError as e:\n w = 'HTTPError'\n print(\"%12s %s %s\" % (w, e.code, request_url))\n pass\n\n except urllib.error.URLError as e:\n w = 'URLError'\n print(\"%12s %s %s\" % (w, e.code, request_url))\n pass\n\n except http.client.BadStatusLine as e:\n w = 'BadStatusError'\n print(\"%12s %s %s\" % (w, e.code, request_url))\n pass\n\n else:\n response_dict = json.loads(response_page)\n\n return(response_dict)\n\n\ndef get_package_data():\n\n ckan_dict = {}\n resource_dict = {}\n \n for f_title in DATA_DICT:\n type = DATA_DICT[f_title]['type']\n dataset = DATA_DICT[f_title]['dataset']\n\n api_com = 'package_show' + '?id=' + dataset\n url = BASE_URL + '/api/3/action/' + api_com\n\n if type == \"url\":\n resp_dict = call_api(url)\n ckan_dict[f_title] = resp_dict\n resource_dict[f_title] = resp_dict['result']\n\n return(resource_dict)\n\ndef get_resource(f_title, url):\n \n res = urllib.request.urlopen(url)\n\n encoding = chardet.detect(res.read())['encoding']\n\n if encoding == None:\n # print(\"P0\", encoding)\n res = urllib.request.urlopen(url)\n res = res.read().decode('shift-jis')\n elif encoding == 'UTF-8-SIG':\n # print(\"P1\", encoding)\n res = urllib.request.urlopen(url)\n res = res.read().decode('utf-8-sig')\n else:\n # print(\"P1\", encoding)\n res = urllib.request.urlopen(url)\n res = res.read()\n \n df = pd.read_csv(io.StringIO(res))\n \n return (df)\n\ndef gen_patients_summary():\n\n # load inspections.csv\n inspections_filepath = WORK_DIR + \"/\" + TOOL_DIR + \"/\" + INPUT_DIR + \"/\" + 'inspections.csv'\n df_inspections = pd.read_csv(inspections_filepath)\n df_patients_summary = df_inspections\n \n # add column in inspections\n df_patients_summary['患者判明数'] = 0\n df_patients_summary['退院者数'] = 0\n df_patients_summary['死亡者数'] = 0\n df_patients_summary['軽症'] = 0\n df_patients_summary['中等症'] = 0\n df_patients_summary['重症'] = 0\n\n # load inspections.csv\n patients_filepath = WORK_DIR + \"/\" + TOOL_DIR + \"/\" + INPUT_DIR + \"/\" + 'patients.csv'\n df_patients = pd.read_csv(patients_filepath)\n\n # check for each patients info\n for index, row in df_patients.iterrows():\n patients_date = row['公表_年月日']\n\n # find patients in each inspection's day\n for index2, row2 in df_patients_summary.iterrows():\n summary_date = row2['年月日']\n\n if summary_date == patients_date:\n patients_num = df_patients_summary.loc[index2, '患者判明数']\n df_patients_summary.loc[index2, '患者判明数'] = patients_num + 1\n break\n\n return(df_patients_summary)\n\ndef save_df(f_title, df):\n \n filename = f_title + '.csv'\n filepath = WORK_DIR + \"/\" + TOOL_DIR + \"/\" + INPUT_DIR + \"/\" + filename\n print(\"create:\", filename)\n df.to_csv(filepath)\n\n return()\n\ndef get_resource_file(resource_dict):\n\n for f_title in DATA_DICT:\n format = DATA_DICT[f_title]['type']\n dataset = DATA_DICT[f_title]['dataset']\n filename = DATA_DICT[f_title]['filename']\n\n if format == 'url':\n url = resource_dict[f_title]['resources'][0]['url']\n # リソースのcsvファイルを取得し、文字コードをutf8へ変換後\n # dfに格納\n df = get_resource(f_title, url)\n # dfをcsvファイルに保存\n save_df(f_title, df)\n \n elif format == \"file\":\n if f_title == \"patients_summary\":\n # patients_summaryのデータをinspectionとpatientsの\n # データから生成\n df = gen_patients_summary()\n save_df(f_title, df)\n else:\n print(\"wrong format\")\n exit()\n \n return()\n\ndef show_package_info(resource_dict):\n\n for f_title in DATA_DICT:\n format = DATA_DICT[f_title]['type']\n\n if format == \"url\":\n last_modified = resource_dict[f_title][\"resources\"][0][\"last_modified\"]\n print( f_title, last_modified)\n\n return()\n\ndef main():\n\n # パッケージのメタデータを取得\n resource_dict = get_package_data()\n\n show_package_info(resource_dict)\n \n filename = \"package.json\"\n filepath = WORK_DIR + \"/\" + TOOL_DIR + \"/\" + INPUT_DIR + \"/\" + filename\n output_json(filepath, resource_dict)\n \n get_resource_file(resource_dict)\n\nif __name__ == '__main__':\n\n config = configparser.ConfigParser()\n path = os.getcwd()\n config.read('{}/../config.ini'.format(path), encoding=\"utf-8\")\n config_section = 'development'\n\n WORK_DIR = config.get(config_section, 'WORK_DIR')\n\n INPUT_DIR = config.get(config_section, 'INPUT_DIR')\n OUTPUT_DIR = config.get(config_section, 'OUTPUT_DIR')\n TOOL_DIR = config.get(config_section, 'TOOL_DIR')\n RESOURCE_FILE = config.get(config_section, 'RESOURCE_FILE')\n BASE_URL = config.get(config_section, 'CKAN_URL')\n \n DEBUG = 1\n\n \"\"\"\n hotline: 新型コロナコールセンター相談件数\n visit: 新型コロナ受診相談件数\n inspections: 検査実施数\n patients: 福岡市新型コロナ陽性患者発表情報\n \"\"\"\n\n resource_file_path = WORK_DIR + \"/\" + TOOL_DIR + \"/\" + RESOURCE_FILE\n DATA_DICT = get_resource_file_dict(resource_file_path)\n \n main()\n","sub_path":"script/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":6412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"218032003","text":"import requests\nfrom bs4 import BeautifulSoup\n\nclass Connection():\n '''The main connection class that keeps state about the current connection.'''\n \n def __init__(self):\n '''Initialize the session for the connection.'''\n self.session = requests.Session()\n self.courses_id = []\n # login state\n # 0 = NOT LOGGED IN, 1 = LOGGED IN\n self.state = 0\n\n def login(self, user, pwd):\n '''\n Login to gradescope using email and password.\n Note that the future commands depend on account privilages.\n '''\n init_resp = self.session.get(\"https://www.gradescope.com/\")\n parsed_init_resp = BeautifulSoup(init_resp.text, 'html.parser')\n #print(init_resp)\n #print(parsed_init_resp.find_all('form'))\n\n for form in parsed_init_resp.find_all('form'):\n if form.get(\"action\") == \"/login\":\n for inp in form.find_all('input'):\n if inp.get('name') == \"authenticity_token\":\n auth_token = inp.get('value')\n\n login_data = {\n \"utf8\": \"✓\",\n \"session[email]\": user,\n \"session[password]\": pwd,\n \"session[remember_me]\": 0,\n \"commit\": \"Log In\",\n \"session[remember_me_sso]\": 0,\n \"authenticity_token\": auth_token,\n }\n \n login_resp = self.session.post(\"https://www.gradescope.com/login\", params=login_data)\n if len(login_resp.history) != 0:\n if login_resp.history[0].status_code == requests.codes.found:\n self.state = 1\n return True\n else:\n return False\n\n\n\n","sub_path":"login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"504235201","text":"\"\"\"\nCollection of functions to perform spectral analysis on 1-D signals\n\"\"\"\nimport numpy as np\nfrom scipy.fftpack import fft, ifft\nfrom statsmodels.tsa.stattools import acf\n\n\ndef band_pass(signal, low, high):\n \"\"\"\n Band pass filter working in the frequency domain\n\n :param signal: timeseries\n :param low: lower bound of the frequency band to keep\n :param high: higher bound of the frequency band to keep\n :return: filtered signal\n :rtype: numpy.array\n \"\"\"\n return np.array(\n i.real for i in ifft([i for i in fft(signal) if low < i < high])\n )\n\n\ndef remove_band(signal, low, high):\n \"\"\"\n Band filter working in the frequency domain. The frequency band specified\n is removed from the signal's spectrum\n\n :param signal: timeseries\n :param low: lower bound of the frequency band to eliminate\n :param high: higher bound of the frequency band to eliminate\n :return: filtered signal\n :rtype: numpy.array\n \"\"\"\n return np.array(\n i.real for i in ifft([i for i in fft(signal) if not low < i < high])\n )\n\n\ndef cut_frequencies(signal, threshold, keep_high=False):\n \"\"\"\n Cuts frequencies of the spectrum of a signal at a threshold\n\n :param signal: timeseries\n :param threshold: threshold to cut signal's spectrum\n :param keep_high: if true only frequencies > threshold will be kept,\n otherwise low frequencies will be kept\n :return: filtered signal\n :rtype: numpy.array\n \"\"\"\n if keep_high:\n return np.array(\n i.real for i in ifft([i for i in fft(signal) if i < threshold])\n )\n return np.array(\n i.real for i in ifft([i for i in fft(signal) if i > threshold])\n )\n\n\ndef autocorr(signal, **kwargs):\n \"\"\"\n Calculates autocorrelation coefficients for a signal\n\n :param signal: timeseries\n :param kwargs: keyword arguments of statsmodels.tsa.statstool.acf\n :return: autocorrelation coefficients\n :rtype: numpy.array\n \"\"\"\n return acf(signal, **kwargs)\n","sub_path":"src/spectral_analysis/spectrum.py","file_name":"spectrum.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"141410254","text":"import requests\nimport datetime\nimport re\nfrom conf import oj_user_info\nfrom models.local_pg_models import engine as local_engine, HduSubmission\nfrom models.utils import SessionBuilder, RemainList, local_psql as lpsql\n\nSETTING = {\n 'host': 'http://acm.hdu.edu.cn/',\n 'login': 'userloginex.php?action=login',\n 'submit': 'submit.php?action=submit',\n 'submissions': 'status.php'\n}\n\nCONFIG = {\n 'max_record_count': 15, # 每一页的记录条数上限\n 'code_min_bytes': 50,\n 'code_max_bytes': 65536\n}\n\nSTATUS = { # hdu -> sdustoj 的(状态, 得分)代换\n 'Accepted': ('AC', 100),\n 'Wrong Answer': ('WA', 0),\n 'Presentation Error': ('PE', 50),\n 'Compilation Error': ('CE', 0),\n 'Runtime Error': ('RE', 0), # 这个状态比较特别,他会有一串附加信息\n 'Time Limit Exceeded': ('TLE', 0),\n 'Memory Limit Exceeded': ('MLE', 0),\n 'Output Limit Exceeded': ('OLE', 0),\n 'Queuing': ('PD', 0),\n 'Compiling': ('CP', 0),\n 'Running': ('RJ', 0),\n '': ('PD', 0) # 防出错\n}\n\nFINISHED_STATUS = [ # 表示已完成的状态\n 'Accepted',\n 'Wrong Answer',\n 'Presentation Error',\n 'Compilation Error',\n 'Runtime Error',\n 'Time Limit Exceeded',\n 'Memory Limit Exceeded',\n 'Output Limit Exceeded'\n]\n\n\nauth_user, auth_pass = oj_user_info['hdu']\n\nsession = requests.session()\n\n\ndef get_url(url, *args):\n return SETTING['host'] + SETTING[url] % args\n\n\ndef do_login():\n data = {\n 'username': auth_user,\n 'userpass': auth_pass,\n 'login': 'Sign In'\n }\n res = session.post(get_url('login'), data=data)\n print(\"HDU Login: %s\" % (res.status_code,))\n return res.status_code == 302 or res.status_code == 200\n\n\ndef do_submit(pid, lang, code):\n data = {\n 'check': 0,\n 'problemid': pid,\n 'language': lang,\n 'usercode': code,\n }\n res = session.post(get_url('submit'), data=data)\n return res.url == get_url('submissions')\n\n\ndef get_submissions(page=0):\n data = {\n 'first': page,\n 'user': auth_user,\n }\n res = session.get(get_url('submissions'), params=data)\n regex = \"\"\"\"\"\" + \\\n \"\"\"(\\\\d+)\"\"\" + \\\n \"\"\"([-\\\\d: ]+)\"\"\" + \\\n \"\"\"(([\\\\w ]+)|\"\"\" + \\\n \"\"\"([\\\\w ]+))\"\"\" + \\\n \"\"\"(\\\\d+)\"\"\" + \\\n \"\"\"(\\\\d*)MS\"\"\" + \\\n \"\"\"(\\\\d*)K\"\"\" + \\\n \"\"\"()?(\\\\d+) ?B\"\"\" + \\\n \"\"\"([\\\\S]*?)\"\"\" + \\\n \"\"\"([\\\\S\\\\s]*?)\"\"\" + \\\n \"\"\"\"\"\"\n rex = re.findall(regex, res.text)\n li = [{\n 'run_id': it[0],\n 'submit_time': it[1],\n 'status': it[3] if len(it[3]) > 0 else it[4],\n 'pid': it[5],\n 'time': it[6],\n 'memory': it[7],\n 'length': it[9],\n 'language': it[10],\n 'author': it[11]\n } for it in rex]\n # runID, submitDate, status, pid, time, memory, codeLength, language, author\n return li\n\n\ndef request_submit(sid, pid, lang, code):\n \"\"\"\n 向HDU提交。\n :param sid: sdustoj的提交id\n :param pid: hdu的题目id\n :param lang: hdu的语言代号\n :param code: 代码\n :return: \n \"\"\"\n # 首先检查代码长度限制。\n byte_length = len(code.encode('gb2312')) # 经过确认,hdu的代码大概是采用gb2312确认代码长度的\n if not CONFIG['code_min_bytes'] <= byte_length <= CONFIG['code_max_bytes']:\n return None, {\n 'status': 'LLE',\n 'score': 0,\n 'finished': True\n }\n # 长时间不用之后,登录状态可能会掉。需要注意修复。\n retry_count = 1\n while retry_count >= 0:\n do_result = do_submit(pid, lang, code)\n if do_result:\n # 提交成功。由于hdu没有runid的返回机制,因此只能选择使用数据库全时刻轮询,并且在提交时立刻查询。\n psql = lpsql.session()\n\n submission_messages = get_submissions(0) # 直接抓取一次status表的第一页的数据\n if submission_messages is None or len(submission_messages) <= 0: # 这意味着出错了\n return None, {\n 'status': 'SF',\n 'score': 0,\n 'finished': True\n }\n new_submission = submission_messages[0] # 获得第一条数据\n\n # 构造新的提交缓存到中间数据库\n submission = HduSubmission(\n run_id=new_submission['run_id'],\n pid=new_submission['pid'],\n time=new_submission['time'],\n memory=new_submission['memory'],\n length=new_submission['length'],\n language=new_submission['language'],\n status=new_submission['status'],\n submission_id=sid,\n submit_time=datetime.datetime.now(),\n update_time=datetime.datetime.now(),\n finished=False\n )\n psql.add(submission)\n psql.commit()\n print(\"-- Hdu Update: run_id=%s\" % (new_submission['run_id'],))\n return {\n 'run_id': new_submission['run_id']\n }, None\n else:\n retry_count -= 1\n do_login() # 针对可能的错误,试图进行一次重新登陆。\n return None, {\n 'status': 'SF',\n 'score': 0,\n 'finished': True\n }\n\n\ndef update_submit(sid, status):\n \"\"\"\n 更新提交信息。\n :param sid: sdustoj的提交id\n :param status: 更新状态内容\n :return: (isOk, status, update)\n \"\"\"\n # 根据协定,status的内容包括run_id\n run_id = status['run_id']\n psql = lpsql.session()\n submission = psql.query(HduSubmission).filter_by(run_id=run_id).first()\n if submission is not None:\n finished = submission.finished\n ret_status = None if finished else status\n if re.match('Runtime Error', submission.status) is not None: # 这里需要特别处理一下RE状态。\n status, score = STATUS['Runtime Error']\n else:\n status, score = STATUS[submission.status]\n ret_update = {\n 'status': status,\n 'score': score,\n 'time': submission.time,\n 'memory': submission.memory,\n 'finished': finished\n }\n return finished, ret_status, ret_update\n else: # 找不到相关记录。这表示出错了,返回提交失败的状态。\n return True, None, {\n 'status': 'SF',\n 'score': 0,\n 'time': '-1',\n 'memory': '-1',\n 'finished': True\n }\n\n\ndef reptile_submit():\n \"\"\"\n 爬取所有的提交并刷新到中间数据库。\n :return: \n \"\"\"\n psql = lpsql.session()\n submissions = psql.query(HduSubmission).filter_by(finished=False).order_by(HduSubmission.id).all()\n if len(submissions) > 0: # 有未完成的内容,确认进行查询。\n print(\"Hdu analyse submissions count %s @ %s\" % (len(submissions), datetime.datetime.now()))\n remain = RemainList(submissions) # 构成一个剩余列表,以便排查\n page = 0\n while True:\n records = get_submissions(page) # 获取该页的所有记录\n for record in records:\n run_id = int(record['run_id'])\n submission = remain.pop(lambda s: s.run_id == run_id)\n if submission is not None: # 找到了与当前网页记录匹配的数据库项目\n # 从记录更新数据库\n submission.time = record['time']\n submission.memory = record['memory']\n submission.status = record['status']\n submission.finished = record['status'] in FINISHED_STATUS\n print(\"Hdu Reptile Submission: run_id=%s\" % (run_id,))\n if len(records) < CONFIG['max_record_count'] or remain.is_empty(): # 满足了退出条件\n break\n page += 1\n psql.commit()\n\n\ndef init():\n if not do_login():\n raise Exception('Login failed. Please check your authentication or network.')\n\ninit()\n\n","sub_path":"Judge/virtual-judge/functions/hdu.py","file_name":"hdu.py","file_ext":"py","file_size_in_byte":8504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"48303655","text":"#!/usr/bin/python3\nimport sys\n\ndef solver(file):\n\n\tdef solve(n):\n\t\tif (n == 0): return \"Case #{:d}: INSOMNIA\\n\".format(c)\n\t\tres = set()\n\t\tk = 1\n\t\twhile (len(res) != 10):\n\t\t\tres = res.union(set(str(k * n)))\n\t\t\tk += 1\n\t\treturn \"Case #{:d}: {:d}\\n\".format(c, (k - 1) * n)\n\twith open(file, 'r') as f:\n\t\tf.readline()\n\t\tc = 1\n\t\twith open(\"out.txt\", 'w') as w:\n\t\t\tfor line in f:\n\t\t\t\tw.write(solve(int(line.split()[0])))\n\t\t\t\tc += 1\n\nif __name__ == \"__main__\":\n\tif (len(sys.argv) == 2): solver(sys.argv[1])\n\telse: raise IndexError(\"Not enough arguments.\")\n","sub_path":"codes/CodeJamCrawler/16_0_1/morloch6174/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"650635371","text":"from django import forms\r\nfrom django.shortcuts import get_object_or_404\r\n\r\nfrom crispy_forms.helper import FormHelper\r\nfrom crispy_forms.layout import Layout, Div, HTML, Submit, Reset, Button\r\nfrom crispy_forms.bootstrap import FormActions\r\n\r\nfrom .models import Place, PlaceExternalRating, PlaceCategory\r\nfrom addresses.forms import AddressField\r\nfrom addresses.models import Address, Country\r\n\r\n# Basic Place Form\r\nclass PlaceForm(forms.ModelForm):\r\n\t# address = AddressField()\r\n\r\n\tclass Meta:\r\n\t\tmodel = Place\r\n\t\tfields = ('title', 'address')\r\n\r\n\tdef __init__(self, country=None, *args, **kwargs):\r\n\t\tsuper(PlaceForm, self).__init__(*args, **kwargs)\r\n\t\tself.fields['address']=forms.ModelChoiceField(queryset=Address.objects.filter(locality__state__country=country))\r\n\r\n\r\n\r\nclass PlaceUpdateAdminForm(forms.ModelForm):\r\n\talias_english = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows': 1}))\r\n\talias_local = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows': 1}))\r\n\tdescription = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows': 6}))\r\n\t# TODO: some bug in addressField in 3rd-party plugin ... need to fix\r\n\t# address = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows': 1}))\r\n\r\n\tclass Meta:\r\n\t\tmodel = Place\r\n\t\tfields = ('title', 'name_local', 'alias_english', 'alias_local', 'description', 'address', 'phone', 'website', 'categories', 'status')\r\n\r\n\tdef __init__(self, *args, **kwargs):\r\n\t\tsuper(PlaceUpdateAdminForm, self).__init__(*args, **kwargs)\r\n\t\t# self.fields['parent'].queryset = Place.objects.filter(address__locality=self.instance.address.locality)\t\r\n\t\tself.fields['address']=forms.ModelChoiceField(queryset=Address.objects.filter(locality__state__country=self.instance.address.locality.state.country))\r\n\t\tself.fields['categories'].widget.attrs['size']='6'\r\n\t\t# self.fields['participants'].required = False\r\n\r\n\t\tself.helper = FormHelper()\r\n\t\tself.helper.label_class = 'form-label'\r\n\t\t# self.helper.field_class = 'form-field'\r\n\t\tself.helper.layout = Layout(\r\n\t\t Div(\r\n\t \t\tDiv(\r\n\t \t\t\tDiv('title', css_class='col-md-7'),\r\n\t \t\t\tDiv('name_local', css_class='col-md-5'),\r\n\t\t\t\t\tcss_class='row'\r\n\t\t\t\t), \r\n\t\t\t\tDiv( \r\n\t\t \tDiv('alias_english', css_class='col-md-5'),\r\n\t\t \tDiv('alias_local', css_class='col-md-5'),\r\n\t\t \tDiv('status', css_class='col-md-2'),\r\n\t\t\t\t\tcss_class='row'\r\n\t\t\t\t), \r\n\t\t Div(\r\n\t\t \tDiv('address', css_class='col-md-5'),\r\n\t\t Div('website', css_class='col-md-4'),\r\n\t\t Div('phone', css_class='col-md-3'),\r\n\t\t css_class='row'\r\n\t\t ), \r\n\t\t\t\tDiv(\r\n\t\t\t\t\tDiv('description', css_class='col-md-7'),\r\n\t\t\t\t\tDiv('categories', css_class='col-md-5'),\r\n\t\t\t\t\tcss_class='row'\r\n\t\t\t\t), \r\n\t\t # Div(\t\t \r\n\t\t # Div('parent', css_class='col-md-8'),\r\n\t\t # Div('status', css_class='col-md-4'),\r\n\t\t # css_class='row'\r\n\t\t # ), \r\n\t\t FormActions(\r\n\t\t Submit('save', 'Save'),\r\n\t\t Reset('reset', 'Reset'),\r\n\t\t Button('cancel', 'Cancel', data_dismiss=\"modal\")\r\n\t\t )\r\n\t\t )\r\n\t\t)\r\n\r\n\t\t# for fieldname in ['participants', 'frequency', 'occasion']:\r\n\t\t# self.fields['google_id'].help_text = None\r\n\r\n\r\nclass PlaceExternalRatingForm(forms.ModelForm):\r\n\tclass Meta:\r\n\t\tmodel = PlaceExternalRating\r\n\t\tfields = ('site_id', 'url', 'rating', 'review_count')\r\n\r\n\tdef __init__(self, *args, **kwargs):\r\n\t\tsuper(PlaceExternalRatingForm, self).__init__(*args, **kwargs)\r\n\r\n\t\tself.helper = FormHelper()\r\n\t\tself.helper.label_class = 'form-label'\r\n\t\t# self.helper.field_class = 'form-field'\r\n\t\tself.helper.layout = Layout(\r\n\t\t Div(\r\n\t \t\tDiv(\r\n\t\t\t\t\tDiv('rating', css_class='col-md-6'),\r\n\t\t\t\t\tDiv('review_count', css_class='col-md-6'),\r\n\t\t\t\t\tcss_class='row'\r\n\t\t\t\t), \r\n\t\t 'url',\r\n\t\t 'site_id',\r\n\t\t FormActions(\r\n\t\t Submit('save', 'Save'),\r\n\t\t Reset('reset', 'Reset'),\r\n\t\t Button('cancel', 'Cancel', data_dismiss=\"modal\")\r\n\t\t )\r\n\t\t )\r\n\t\t)\r\n\r\n\r\nclass PlaceCategoryForm(forms.ModelForm):\r\n\tdescription = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows': 3}))\r\n\tslug = forms.CharField(required=False)\r\n\r\n\tclass Meta:\r\n\t\tmodel = PlaceCategory\r\n\t\tfields = ('title', 'description', 'parent', 'slug')\r\n\r\n\tdef __init__(self, *args, **kwargs):\r\n\t\tsuper(PlaceCategoryForm, self).__init__(*args, **kwargs)\r\n\r\n\t\tself.helper = FormHelper()\r\n\t\tself.helper.label_class = 'form-label'\r\n\t\t# self.helper.field_class = 'form-field'\r\n\t\tself.helper.layout = Layout(\r\n\t\t Div(\r\n\t \t\tDiv(\r\n\t\t\t\t\tDiv('title', css_class='col-md-6'),\r\n\t\t\t\t\tDiv('parent', css_class='col-md-6'),\r\n\t\t\t\t\tcss_class='row'\r\n\t\t\t\t), \r\n\t\t 'slug',\r\n\t\t 'description',\r\n\t\t FormActions(\r\n\t\t Submit('save', 'Save'),\r\n\t\t Reset('reset', 'Reset'),\r\n\t\t Button('cancel', 'Cancel', data_dismiss=\"modal\")\r\n\t\t )\r\n\t\t )\r\n\t\t)","sub_path":"places/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":5006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"260206480","text":"from django.db.models import Q\nfrom django.conf import settings\nfrom file_system.repository.file_repository import FileRepository\nfrom beagle_etl.metadata.validator import MetadataValidator\nfrom runner.operator.helper import format_sample_name\n\n\ndef get_project_id(request_id):\n return request_id.split(\"_\")[0]\n\n\ndef get_gene_panel(request_id):\n return FileRepository.filter(\n metadata={settings.REQUEST_ID_METADATA_KEY: request_id}, values_metadata=settings.RECIPE_METADATA_KEY\n ).first()\n\n\ndef get_samples(request_id):\n return FileRepository.filter(\n metadata={settings.REQUEST_ID_METADATA_KEY: request_id}, values_metadata=settings.SAMPLE_ID_METADATA_KEY\n ).all()\n\n\ndef get_number_of_tumor_samples(request_id):\n return FileRepository.filter(\n metadata={settings.REQUEST_ID_METADATA_KEY: request_id, settings.TUMOR_OR_NORMAL_METADATA_KEY: \"Tumor\"},\n values_metadata=settings.SAMPLE_ID_METADATA_KEY,\n ).count()\n\n\ndef get_emails_to_notify(request_id, notification_type=None):\n investigator_email = FileRepository.filter(\n metadata={settings.REQUEST_ID_METADATA_KEY: request_id},\n values_metadata=settings.INVESTIGATOR_EMAIL_METADATA_KEY,\n ).first()\n lab_head_email = FileRepository.filter(\n metadata={settings.REQUEST_ID_METADATA_KEY: request_id}, values_metadata=settings.LAB_HEAD_EMAIL_METADATA_KEY\n ).first()\n send_to = settings.BEAGLE_NOTIFIER_VOYAGER_STATUS_EMAIL_TO\n if notification_type in settings.BEAGLE_NOTIFIER_VOYAGER_STATUS_NOTIFY_EXTERNAL:\n if investigator_email not in settings.BEAGLE_NOTIFIER_VOYAGER_STATUS_BLACKLIST and investigator_email:\n send_to.append(investigator_email)\n if lab_head_email not in settings.BEAGLE_NOTIFIER_VOYAGER_STATUS_BLACKLIST and lab_head_email:\n send_to.append(lab_head_email)\n return list(set(send_to))\n\n\ndef generate_sample_data_content(files, pipeline_name, pipeline_github, pipeline_version, dmp_samples=None):\n result = \"SAMPLE_ID\\tREQUEST_ID\\tPROJECT_ID\\tPATIENT_ID\\tCOLLAB_ID\\tSAMPLE_TYPE\\tGENE_PANEL\\tONCOTREE_CODE\\tSAMPLE_CLASS\\tSPECIMEN_PRESERVATION_TYPE\\tSEX\\tTISSUE_SITE\\tIGO_ID\\tRUN_MODE\\tPIPELINE\\tPIPELINE_GITHUB_LINK\\tPIPELINE_VERSION\\n\"\n ret_str = \"metadata__{sample_id_key}\".format(sample_id_key=settings.SAMPLE_ID_METADATA_KEY)\n query = Q(file__file_group_id=settings.IMPORT_FILE_GROUP)\n query |= Q(file__file_group__slug=\"origin-unknown\")\n query |= Q(file__file_group__slug=\"fero-legacy-data\")\n query = query & Q(file__path__in=files)\n samples = FileRepository.filter(q=query).order_by(ret_str).distinct(ret_str).all()\n for sample in samples:\n metadata = sample.metadata\n result += generate_sample_data_content_str(metadata, pipeline_name, pipeline_github, pipeline_version)\n if dmp_samples:\n for sample in dmp_samples:\n metadata = sample[0].metadata\n project_id = metadata[settings.REQUEST_ID_METADATA_KEY]\n result += generate_sample_data_content_str(\n metadata, pipeline_name, pipeline_github, pipeline_version, project_id\n )\n return result\n\n\ndef generate_sample_data_content_str(metadata, pipeline_name, pipeline_github, pipeline_version, project_id=None):\n if project_id:\n project_id = get_project_id(metadata[settings.REQUEST_ID_METADATA_KEY])\n result = \"{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n\".format(\n metadata.get(\n settings.CMO_SAMPLE_TAG_METADATA_KEY,\n format_sample_name(\n metadata[settings.CMO_SAMPLE_NAME_METADATA_KEY], metadata[settings.SAMPLE_CLASS_METADATA_KEY]\n ),\n ),\n metadata[settings.REQUEST_ID_METADATA_KEY],\n project_id,\n metadata[settings.PATIENT_ID_METADATA_KEY],\n metadata[\"investigatorSampleId\"],\n MetadataValidator.clean_value(metadata[settings.SAMPLE_CLASS_METADATA_KEY]),\n MetadataValidator.clean_value(metadata[settings.RECIPE_METADATA_KEY]),\n MetadataValidator.clean_value(metadata[settings.ONCOTREE_METADATA_KEY]),\n MetadataValidator.clean_value(metadata[settings.SAMPLE_CLASS_METADATA_KEY]),\n MetadataValidator.clean_value(metadata[\"preservation\"]),\n MetadataValidator.clean_value(metadata[\"sex\"]),\n MetadataValidator.clean_value(metadata[\"tissueLocation\"]),\n metadata[settings.SAMPLE_ID_METADATA_KEY],\n MetadataValidator.clean_value(metadata[\"runMode\"]),\n pipeline_name,\n pipeline_github,\n pipeline_version,\n )\n return result\n","sub_path":"notifier/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":4582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"100277254","text":"def parse_line(line):\n arr = line.replace(',', '').split()\n base = arr[0]\n weight = int(arr[1][1:-1])\n upper_list = arr[3:]\n return base, weight, upper_list\n\n\ndef parse_file(filename):\n arr = []\n with open(filename, 'r') as f:\n for line in f:\n result = parse_line(line)\n arr.append(result)\n return arr\n\n\ndef find_base_program(array):\n potential_bases = set([base for (base, _, _) in array])\n for _, _, upper_list in array:\n for program in upper_list:\n if program in potential_bases:\n potential_bases.remove(program)\n return potential_bases.pop()\n\n\nclass Node:\n def __init__(self, name, weight, children=None):\n self.name = name\n self.weight = weight\n self.children = []\n if children is not None:\n for child in children:\n self.add_child(child)\n\n\n def __repr__(self):\n return '{} ({})'.format(self.name, self.weight)\n\n\n def add_child(self, node):\n assert isinstance(node, Node)\n self.children.append(node)\n\n\n def print(self, depth=0, last=False):\n if depth == 0:\n line = self\n else:\n if last:\n line = \"{}└{} {}\".format(4*(depth-1)*' ', 2*'─', self)\n else:\n line = \"{}├{} {}\".format(4*(depth-1)*' ', 2*'─', self)\n print(line)\n for i, child in enumerate(self.children):\n if i == len(self.children) - 1:\n child.print(depth+1, True)\n else:\n child.print(depth+1)\n\n\n def find_imbalance(self):\n if len(self.children) == 0:\n return False, self.weight, self.name\n\n branches_weights = []\n branches = {}\n for child in self.children:\n imbalanced, branch_weight, branch_name = child.find_imbalance()\n if imbalanced:\n return True, branch_weight, branch_name\n else:\n branches_weights.append(branch_weight)\n branches[branch_weight] = branch_name\n\n weights_dict = {weight: branches_weights.count(weight) for weight in branches_weights}\n if len(weights_dict) != 1:\n for key, value in weights_dict.items():\n if value == 1:\n wrong_weight = key\n else:\n good_weight = key\n wrong_name = branches[wrong_weight]\n wrong_child = next(child for child in self.children if child.name == wrong_name)\n return True, (wrong_child.weight - (wrong_weight-good_weight)), wrong_name\n return False, self.weight + sum(branches_weights), self.name \n\n\ndef prepare_nodes(array):\n nodes = {}\n for tup in array:\n name, weight, _ = tup\n nodes[name] = Node(name, weight)\n for tup in array:\n name, _, children_names = tup\n parent = nodes[name]\n for child_name in children_names:\n child = nodes[child_name]\n parent.add_child(child)\n return nodes\n\n\nexample_array = parse_file(\"advent7_example.txt\")\ninput_array = parse_file(\"advent7_input.txt\")\n\n\nprint('Part 1:')\n\nexample_result = find_base_program(example_array)\nprint(\"Example: {} (should return 'tknk')\".format(example_result))\n\ninput_result = find_base_program(input_array)\nprint(\"Result: {} \".format(input_result)) # vtzay\n\nprint()\nprint('Part 2:')\n\nexample_nodes = prepare_nodes(example_array)\nexample_nodes[example_result].print()\n\n_, example_result2, _ = example_nodes[example_result].find_imbalance()\nprint(\"Example: {} (should return 60)\".format(example_result2))\n\ninput_nodes = prepare_nodes(input_array)\n_, input_result2, _ = input_nodes[input_result].find_imbalance()\nprint(\"Result: {} \".format(input_result2)) # 910\n","sub_path":"07/advent7.py","file_name":"advent7.py","file_ext":"py","file_size_in_byte":3785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"433800308","text":"\r\n\"\"\"\r\nDemonstrates using the .circle() method.\r\n\"\"\"\r\n\r\n# Import \r\nfrom lab.cnc import CNC\r\n\r\n# Initialize\r\ncnc = CNC()\r\ncnc.home()\r\ncnc.move_to(100, 400, 0)\r\n\r\n# Loop\r\nfor radius in range(50, 300, 50):\r\n print(\"Making circle of radius {} mm\".format(radius))\r\n cnc.circle(radius, 150)\r\n\r\n# Return home\r\ncnc.move_to(0, 0, 0)","sub_path":"jetson/examples/cnc/make_circles.py","file_name":"make_circles.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"83794228","text":"import base64\nfrom bs4 import BeautifulSoup\nfrom getpass import getpass\nimport email.encoders as encoders\nfrom email.mime.base import MIMEBase\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.mime.image import MIMEImage\nimport smtplib\nimport socket\nimport ssl\nimport time\nfrom ..nbconvert import run\nfrom ..hideinput.exporters import _html_no_code_email_template\n\n\ndef attach_parts(msg, parts):\n imgCount = 0\n for part in parts:\n if isinstance(part, (list, tuple)):\n partType, partText = part\n maintype, subtype = partType.split('/', 1)\n if maintype == 'text':\n part = MIMEText(partText, _subtype=subtype)\n elif maintype == 'image':\n imgCount += 1\n part = MIMEImage(partText, _subtype=subtype)\n part.add_header('Content-ID', ''.format(imgCount))\n else:\n pass\n msg.attach(part)\n\n\ndef send_mail(from_addr, to_addrs, message, attempts=1, retryDelaySecs=1, mailhost=('smtp.gmail.com', 587), useTLS=True, outlook=False):\n result = None\n attempts = attempts\n\n if mailhost is None:\n mailhost = [input('input mailhost address:'), int(input('input mailhost port:'))]\n\n for attempt in range(0, attempts):\n try:\n\n with smtplib.SMTP(mailhost[0], mailhost[1], timeout=10) as s:\n if useTLS:\n s.starttls(context=ssl.create_default_context())\n pw = getpass('password for %s:' % from_addr)\n s.login(from_addr, pw)\n result = s.sendmail(from_addr, to_addrs, message)\n except (smtplib.SMTPSenderRefused, smtplib.SMTPRecipientsRefused) as e:\n time.sleep(retryDelaySecs)\n if attempt == attempts:\n raise e\n except (smtplib.SMTPException, socket.error, IOError) as e:\n time.sleep(retryDelaySecs)\n if attempt == attempts:\n raise e\n return result\n\n\ndef email_notebook(notebook,\n from_user='',\n to_user='',\n subject='',\n template=_html_no_code_email_template,\n header='

TEST HEADER

',\n footer='

TEST FOOTER

',\n execute=False,\n execute_timeout=100,\n new_notebook=False,\n postprocessor=None,\n postprocessor_kwargs=None):\n\n x = run(to='html',\n in_=notebook,\n template=template,\n execute=execute,\n execute_timeout=execute_timeout,\n new_notebook=new_notebook)\n\n if not x:\n raise Exception('Something went wrong with NBConvert')\n\n msg = MIMEMultipart()\n soup = BeautifulSoup(x, 'html.parser')\n\n # extract imgs for outlook\n imgs = soup.find_all('img')\n\n # strip markdown links\n for item in soup.findAll('a', {'class': 'anchor-link'}):\n item.decompose()\n\n # remove dataframe table borders\n for item in soup.findAll('table', {'border': 1}):\n item['border'] = 0\n item['cellspacing'] = 0\n item['cellpadding'] = 0\n\n # add header and footer\n if header or footer:\n head = soup.find('div', {'class': 'header'})\n foot = soup.find('div', {'class': 'footer'})\n head.append(BeautifulSoup(header or '', 'html.parser'))\n foot.append(BeautifulSoup(footer or '', 'html.parser'))\n\n # attach main part\n for i, img in enumerate(imgs):\n if not img.get('localdata'):\n continue\n # part = MIMEBase('application', 'octet-stream')\n # part.set_payload(base64.b64decode(img.get('localdata')))\n part = MIMEImage(base64.b64decode(img.get('localdata')), 'png', name='Cell_%s_Img_%d.png' % (img.get('cell_id'), i))\n del img['localdata']\n img['src'] = 'cid:Cell_%s_Img_%d.png' % (img.get('cell_id'), i)\n encoders.encode_base64(part)\n # part.add_header('Content-Disposition', 'attachment', filename=img.get('cell_id'))\n part.add_header('Content-Disposition', 'inline', filename='Cell_%s_Img_%d.png' % (img.get('cell_id'), i))\n part.add_header('Content-ID', '<%s>' % 'Cell_%s_Img_%d.png' % (img.get('cell_id'), i))\n msg.attach(part)\n\n if postprocessor:\n if postprocessor_kwargs is None:\n postprocessor_kwargs = {}\n print('running postprocessor %s' % str(postprocessor))\n tmp = postprocessor(soup, **postprocessor_kwargs)\n if tmp is not None:\n soup = tmp\n\n attach_parts(msg, [('text/html', str(soup))])\n\n headerExtra = ''\n importance = 'Importance: Normal\\r\\n'\n\n msg_as_string = msg.as_string()\n\n composed = 'From: %s\\r\\nTo: %s\\r\\n' % (from_user, to_user) + \\\n headerExtra + importance + \\\n \"Subject: %s\\r\\n%s\" % (subject, msg_as_string)\n send_mail(from_user, to_user, composed, attempts=1, retryDelaySecs=2)\n","sub_path":"_deprecated/email/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":5003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"361269834","text":"from airflow.hooks.base_hook import BaseHook\nfrom sqlalchemy import create_engine\nfrom sqlalchemy_utils import create_database, database_exists\nimport sqlalchemy\n\ndatalake_conn_string = BaseHook.get_connection('postgres_datalake').get_uri()\n\nengine = create_engine(datalake_conn_string)\n\n# create database\nif not database_exists(engine.url):\n create_database(engine.url)\n engine.execute(\"GRANT ALL PRIVILEGES ON DATABASE {db} TO {user};\".format(user = engine.url.username, db = engine.url.database))\n\n# create schema, give permissions\nif not engine.dialect.has_schema(engine, 'views'):\n engine.execute(sqlalchemy.schema.CreateSchema('views'))\n engine.execute(\"GRANT ALL PRIVILEGES ON SCHEMA views TO {user};\".format(user = engine.url.username))\n engine.execute(\"GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA views TO {user};\".format(user = engine.url.username))\n engine.execute(\"ALTER DEFAULT PRIVILEGES IN SCHEMA views GRANT ALL PRIVILEGES ON TABLES TO {user};\".format(user = engine.url.username))\n","sub_path":"airflow/setup_views.py","file_name":"setup_views.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"533185904","text":"import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n# 200KHz\r\n\r\nPole = 10 # motor pole pairs\r\nfre_filter = 500 # filter date > fre_filter\r\n\r\nfilename = \"D:\\\\Sylvain\\\\Desktop\\\\C1test00007.csv\"\r\ndf = pd.read_csv(filename, header=4)\r\nValue = np.array(df).T\r\nX = Value[0]\r\nY = Value[1]\r\nT = []\r\nindex = []\r\ni = 0\r\nwhile i < len(Y) - 2:\r\n if Y[i] * Y[i + 1] < 0:\r\n V = X[i] + abs(X[i + 1] - X[i]) * Y[i] / (Y[i + 1] - Y[i])\r\n T.append(V)\r\n i += 1\r\n index.append(i)\r\n elif Y[i] * Y[i + 1] == 0:\r\n k = 2\r\n while Y[i] * Y[i + k] == 0:\r\n k += 1\r\n if i + k > len(Y) - 2:\r\n break\r\n if Y[i + k] - Y[i] != 0:\r\n V = X[i] + abs(X[i + k] - X[i]) * Y[i] / (Y[i + k] - Y[i])\r\n T.append(V)\r\n index.append(i)\r\n i = i + k\r\n else:\r\n i += 1\r\n# process freq data and index\r\ni = 0\r\nS = []\r\nwhile i < len(T) - 1:\r\n s = T[i + 1] - T[i]\r\n S.append(1 / s)\r\n i += 1\r\nM, N, index_list = [], [], []\r\nfor v, i, index_i in zip(S, T, index):\r\n if abs(v) < 500:\r\n M.append(v)\r\n N.append(i)\r\n index_list.append(index_i)\r\nN0 = N[0]\r\nN = [n - N0 for n in N]\r\nM = [60 * m / Pole for m in M]\r\n\r\nfig = plt.figure()\r\nax = plt.subplot(2, 1, 1)\r\nax.set(xlabel=\"t(s)\", ylabel=\"Speed(rpm)\", title=\"M24 speed via BEMF\")\r\nax.spines[\"top\"].set_color(\"none\")\r\nax.spines[\"right\"].set_color(\"none\")\r\n# ax.spines[\"bottom\"].set_position((\"data\",0))\r\nax.xaxis.set_ticks_position(\"bottom\")\r\n# ax.spines[\"left\"].set_position((\"data\",0))\r\nax.plot(N, M, \"xr-\")\r\nplt.grid()\r\n# ax.plot(N,M,\"bx\")\r\n\r\n\r\n# process RMS data\r\nrms = []\r\ni_start = index_list[0]\r\nfor i in index_list[1:]:\r\n sum_list = np.arange(i_start, i, 1)\r\n Div_number = i - i_start\r\n i_start = i\r\n rms_temp = 0\r\n for j in sum_list:\r\n rms_temp = rms_temp + Y[j]**2\r\n rms_temp = np.sqrt(rms_temp / Div_number)\r\n rms.append(rms_temp)\r\n\r\nax2 = plt.subplot(2, 1, 2)\r\nax2.set(xlabel=\"t(s)\", ylabel=\"BEMF(rms)\", title=\"M24 BEMF vs Time\")\r\nax2.spines[\"top\"].set_color(\"none\")\r\nax2.spines[\"right\"].set_color(\"none\")\r\n# ax.spines[\"bottom\"].set_position((\"data\",0))\r\nax2.xaxis.set_ticks_position(\"bottom\")\r\n# ax.spines[\"left\"].set_position((\"data\",0))\r\nax2.plot(N[1:], rms, \"bx\")\r\nplt.grid()\r\nfig.tight_layout()\r\nplt.show()\r\n","sub_path":"BEMF_DataProcess.py","file_name":"BEMF_DataProcess.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"139465089","text":"# -*- coding: utf-8 -*-\n\"\"\"\nA high-level interface for the bot.\n\n@author: silver\n\"\"\"\n\nfrom inventory import LEFT_CLICK, RIGHT_CLICK, WID_INVENTORY, WID_MOUSE\nimport logbot\nimport entities\nimport items\nimport plugins\n\n\nlog = logbot.getlogger('INTERFACE')\n\n\nclass BotInterface(object):\n \"\"\"This is meant to be a high-level abstraction of the bot, implementing\n all aspects of a normal player interface, as well as being a central,\n unified location for bot behaviour access gained through plugins.\"\"\"\n def __init__(self, bot_entity):\n self._entity = bot_entity\n self.world = bot_entity.world\n self.behaviours = plugins.behaviours\n self.verbs = {}\n for plugin in plugins.behaviours:\n plugin = plugins.behaviours[plugin]\n for verb in plugin.verbs:\n if verb in self.verbs:\n msg = 'Cannot override pre-existing verb \"%s\"' % verb\n self.world.chat.send_message(msg)\n continue\n else:\n self.verbs[verb] = plugin.verbs[verb]\n self._active_slot = None\n\n def __getattr__(self, name):\n if name in self.verbs:\n return self.verbs[name]\n raise AttributeError(\"BotInterface object has no attribute '%s'\"\n % name)\n\n @property\n def held(self):\n return self.inventory.ready[self._active_slot]\n\n @held.setter\n def held(self, item):\n self.inventory.ready[self._active_slot] = item\n\n @property\n def inventory(self):\n return self.world.inventories[WID_INVENTORY]\n\n @property\n def mouse(self):\n return self.world.inventories[WID_MOUSE]\n\n def click_entity(self, entity_ref, button):\n \"\"\"Click on given entity or entity id.\n entity_ref := eid or entity object\n button := LEFT_CLICK or RIGHT_CLICK\n \"\"\"\n # LEFT_CLICK and RIGHT_CLICK are pulled from inventory, but this\n # packet uses an opposite schema from what inventory uses.. *sigh*..\n button = not button\n target_eid = entity_ref if type(entity_ref) == int else entity_ref.eid\n self.world.send_packet('animation', eid=self.entity.eid, animation=1)\n self.world.send_packet('use entity', eid=self.entity.eid,\n target=target_eid, button=button)\n\n def click_slot(self, button, slot, shift=False, func=None):\n func = lambda x: x if not func else func\n return self.mouse.click_slot(button, slot, func, shift)\n\n def click(self, clickable, mouse_button, shift=False, func=None):\n \"\"\"click(entity, button) -> None\n click(slot_item, button, shift=False, func=None) -> [] (read below)\n\n 'Click' on the clickable. This should mirror the minecraft UI, so\n 'clicking' here should have the same effect as clicking on the same\n item in the minecraft client.\n\n For this to work, you must send in a recognized item type. Currently,\n the recognized types are:\n Entity\n Slot (Item or NoItem)\n If sending 'Slot'\n\n Slots can be acquired through the inventory attribute of this class.\n Entities can be acquired through world.entities.\n \"\"\"\n if isinstance(clickable, entities.Entity):\n self.click_entity(clickable, mouse_button)\n elif isinstance(clickable, items.Slot):\n self.click_slot(mouse_button, clickable, shift, func)\n else:\n log.msg(\"Unrecognized item type to click: \" + str(type(clickable)))\n\n def drop_item(self, item):\n \"\"\"Drop given item, moving it to held slot if needed.\"\"\"\n def drop(success):\n if success:\n self.world.reactor.callLater(0.2, self.drop)\n return success\n self.hold(item, func=drop)\n\n def drop(self, count=-1, item=None):\n \"\"\"drop() -> drop the whole stack of the currently-held item\n drop(13) -> drop 13 of the currently-held item\n \"\"\"\n packet = {'state': None, 'x': 0, 'y': 0, 'z': 0, 'face': 0}\n if count < 0:\n packet['state'] = 3\n self.world.send_packet(\"player digging\", packet)\n self.held = None\n else:\n packet['state'] = 4\n for I in xrange(count):\n if self.held.count:\n log.msg(\"dropping one \" + str(self.held.name))\n self.world.send_packet('player digging', packet)\n self.held.count -= 1\n if not self.held.count:\n self.held = None\n\n def drop_everything(self):\n \"\"\"Drop everything in the inventory\"\"\"\n delay = 0\n increment = 0.3\n for item in self.inventory.ready:\n if not item:\n continue\n self.world.reactor.callLater(delay, self.drop_item, item)\n delay += increment\n\n for item in self.inventory.general:\n if not item:\n continue\n self.world.reactor.callLater(delay, self._drop_item, item)\n delay += increment\n\n def left_click(self, what, shift=False, func=None):\n \"\"\"Shortcut for click, using mouse_button=LEFT_CLICK\"\"\"\n self.click(what, LEFT_CLICK, shift, func)\n\n def right_click(self, what, shift=False, func=None):\n \"\"\"Shortcut for click, using mouse_button=RIGHT_CLICK\"\"\"\n self.click(what, RIGHT_CLICK, shift, func)\n\n def hold(self, item, lookup=True, general_inventory=True,\n func=lambda x: x):\n \"\"\"hold(item) -> True, [], or Exception is raised with error message.\n hold the specified item, which must be in the ready inventory.\n if item is a Slot object, hold that item.\n if item is a string, look for that item, and hold that.\n\n if general_inventory is True, then the action will be performed\n asynchronously, and a list will be returned instead of True. Once the\n asynchronous activity is completed, the results (True or False) will be\n appended to the list.\n \"\"\"\n if lookup and isinstance(item, (str, unicode)):\n item_str = item\n options = self.inventory.ready.lookup(item)\n if options:\n item = options[0]\n elif general_inventory:\n options = self.inventory.general.lookup(item)\n if options:\n item = options[0]\n else:\n msg = \"Couldn't find '\" + item_str + \"' in inventory.\"\n raise Exception(msg)\n else:\n msg = \"Couldn't find '\" + item_str + \"' in ready inventory.\"\n raise Exception(msg)\n if item not in self.inventory.ready:\n if not general_inventory or (item not in self.inventory.general):\n msg = \"Could not find '\" + item.name + \"' in inventory.\"\n raise Exception(msg)\n if item in self.inventory.ready:\n self.world.send_packet('held item change',\n {'item': item.gc_slot_number})\n func(True)\n return True\n # now for the more complex, async case..\n ready = self.inventory.ready\n general = self.inventory.general\n item_str = item.name # now that we have the item, use it exactly\n # the methods we create can set the result[0] to whatever, thus adding\n # a deferred result. ..we should really make an event engine.\n#TODO: event engine (avoid this circuitous stuff)\n result = []\n\n ## if the move of the stack succeeds, this will be executed.\n def switch_to(success):\n if not success:\n result.append(False)\n options = ready.lookup(item_str)\n if not options:\n result.append(False)\n return False\n item = options[0]\n self.world.send_packet('held item change',\n {'item': item.gc_slot_number})\n result.append(func(True))\n if ready.has_room():\n self.move_stack(item, ready, switch_to)\n return result\n\n # ready does not have room. Make method to pass to move_stack\n # in case it succeeds at swapping out an item from ready\n def general_to_ready(success):\n if not success or not ready.has_room():\n result.append(False)\n self.move_stack(item, ready, switch_to)\n swappable = general[8] # ..may as well use the last item..\n self.move_stack(swappable, general, general_to_ready)\n return result\n\n def move_stack(self, item, dest, func=None):\n \"\"\"Try to move the given items to the given destination. If we\n succeed, run func(True), otherwise, run func(False)\"\"\"\n def put_callback(success):\n if not success:\n func(False)\n return False\n self.mouse.put_stack(dest, func=func)\n # Execution order (dependent upon success of each):\n # take_stack -> put_callback -> put_stack -> func\n self.mouse.take_stack(item, func=put_callback)\n\n","sub_path":"twistedbot/botinterface.py","file_name":"botinterface.py","file_ext":"py","file_size_in_byte":9203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"631672061","text":"##\n## Copyright (c) 2017, 2018 RockNSM.\n##\n## This file is part of RockNSM\n## (see http://rocknsm.io).\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,\n## software distributed under the License is distributed on an\n## \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n## KIND, either express or implied. See the License for the\n## specific language governing permissions and limitations\n## under the License.\n##\n##\nfrom flask import Flask, Blueprint, Response\nfrom flask_restful import Api\n\nfrom resources.query import QueryRequest, ApiRequest, RawRequest\n\nfrom config import Config\n\n# Declare the blueprint\napi_bp = Blueprint('query', __name__)\napi = Api(api_bp)\n\n# Add resources\n# consider 'login_required' for queries\n\n# RawRequest handles valid stenographer queries\n# GET /raw/host+1.2.3.4+and+port+80\n# POST /query -d 'host 1.2.3.4 and port 80'\n# api.add_resource(RawRequest,\n# '/raw//',\n# '/query/',\n# )\napi.add_resource(RawRequest, '/raw/', endpoint=\"query.rawrequest.get\", methods=['GET']) # GET /raw/host+1.2.3.4+port+80\napi.add_resource(RawRequest, '/query/', endpoint=\"query.rawrequest.post\", methods=['POST']) # POST /query -d 'host 1.2.3.4 port 21'\n\n# QueryRequest handles encoded queries\n# GET /uri/name/value\n# POST / Json or HTML Forms\n# api.add_resource(QueryRequest,\n# '/uri//',\n# '/',\n# )\napi.add_resource(QueryRequest, '/', endpoint=\"query.queryrequest.post\", methods=['POST']) # POST / -d '{ \"port\":21, \"after-ago\":\"1m\" }'\napi.add_resource(QueryRequest, '/uri/', endpoint=\"query.queryrequest.get\", methods=['GET']) # GET /uri/host/1.2.3.4/port/80\n\n# ApiRequest handles metadata requests\n# GET /urls GET /urls/d6c1e79adf9f46bf6187fd92fff016e5,734d929c61e64315b140cb7040115a70\n# GET /ids GET /ids/734d929c61e64315b140cb7040115a70,7065d7548b8e717b5bdac1d074e80b55\n# GET /status GET /status/734d929c61e64315b140cb7040115a70,7065d7548b8e717b5bdac1d074e80b55\n# GET /stats GET /stats/sensor.1,sensor.2\napi.add_resource(ApiRequest,\n '///',\n '//', methods=['GET']\n )\n","sub_path":"docket/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"355696126","text":"\"\"\"empty message\n\nRevision ID: e0fe944d0566\nRevises: \nCreate Date: 2021-03-31 15:42:09.097237\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'e0fe944d0566'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('character',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=250), nullable=False),\n sa.Column('height', sa.Integer(), nullable=True),\n sa.Column('mass', sa.Integer(), nullable=True),\n sa.Column('hair_color', sa.String(length=250), nullable=True),\n sa.Column('skin_color', sa.String(length=250), nullable=True),\n sa.Column('gender', sa.String(length=250), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('planet',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=250), nullable=False),\n sa.Column('diameter', sa.Integer(), nullable=True),\n sa.Column('gravity', sa.String(length=30), nullable=True),\n sa.Column('climate', sa.String(length=250), nullable=True),\n sa.Column('population', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('starship',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=250), nullable=False),\n sa.Column('model', sa.String(length=250), nullable=True),\n sa.Column('passengers', sa.Integer(), nullable=True),\n sa.Column('consumable', sa.String(length=250), nullable=True),\n sa.Column('cargo_capacity', sa.Integer(), nullable=True),\n sa.Column('hyperdrive_rating', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('user',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=250), nullable=False),\n sa.Column('email', sa.String(length=250), nullable=True),\n sa.Column('password', sa.String(length=10), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('favorite',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('users_id', sa.Integer(), nullable=True),\n sa.Column('name', sa.String(length=250), nullable=True),\n sa.ForeignKeyConstraint(['users_id'], ['user.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('favorite')\n op.drop_table('user')\n op.drop_table('starship')\n op.drop_table('planet')\n op.drop_table('character')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/e0fe944d0566_.py","file_name":"e0fe944d0566_.py","file_ext":"py","file_size_in_byte":2675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"209246478","text":"#\n# Copyright (c) 2018 Juniper Networks, Inc. All rights reserved.\n#\n\n\"\"\"\nThis file contains implementation of job api handler code\n\"\"\"\nimport gevent\nimport json\nimport random\nfrom enum import Enum\nfrom vnc_api.vnc_api import VncApi\n\n\nclass JobStatus(Enum):\n INIT = 0\n IN_PROGRESS = 1\n COMPLETE = 2\n FAILED = 3\n# end class JobStatus\n\n\nclass JobHandler(object):\n JOB_STATUS_MAPPING = {\n 'SUCCESS': JobStatus.COMPLETE,\n 'FAILURE': JobStatus.FAILED,\n 'UNKNOWN': JobStatus.FAILED\n }\n\n def __init__(self, job_type, job_input, device_list, api_server_config,\n logger):\n self._job_type = job_type\n self._job_input = job_input\n self._device_list = device_list\n self._api_server_config = api_server_config\n self._logger = logger\n self._job_id = None\n self._job_status = JobStatus.INIT\n super(JobHandler, self).__init__()\n # end __init__\n\n def push(self, timeout, max_retries):\n vnc_api = self._get_vnc_api(**self._api_server_config)\n self._job_status = JobStatus.IN_PROGRESS\n job_execution_id = None\n try:\n self._logger.debug(\"job handler: executing job for (%s, %s)\" %\n (self._device_list, str(self._job_type)))\n job_execution_info = vnc_api.execute_job(\n job_template_fq_name=self._job_type,\n job_input=self._job_input,\n device_list=self._device_list\n )\n\n job_execution_id = job_execution_info.get('job_execution_id')\n self._logger.debug(\"job started with execution id %s\" %\n job_execution_id)\n self._wait(vnc_api, job_execution_id, timeout, max_retries)\n except Exception as e:\n self._logger.error(\"job handler: push failed for (%s, %s)\"\n \" execution id %s: %s\" % (self._device_list,\n str(self._job_type), job_execution_id, repr(e)))\n self._job_status = JobStatus.FAILED\n\n if self._job_status == JobStatus.FAILED:\n raise Exception(\"job handler: push failed for (%s, %s)\"\n \" execution id %s\" % (self._device_list,\n str(self._job_type), job_execution_id))\n self._logger.debug(\"job handler: push succeeded for (%s, %s)\"\n \" execution id %s\" % (self._device_list,\n str(self._job_type), job_execution_id))\n # end push\n\n def _check_job_status(self, vnc_api, job_execution_id, status):\n try:\n job_status = vnc_api.job_status(job_execution_id)\n return self._verify_job_status(job_status, status)\n except Exception as e:\n self._logger.error(\"job handler: error while querying \"\n \"job status for execution_id %s: %s\" %\n (job_execution_id, repr(e)))\n return False\n # end _check_job_status\n\n def _get_job_status(self, vnc_api, job_execution_id):\n if self._check_job_status(vnc_api, job_execution_id,\n JobStatus.COMPLETE):\n return JobStatus.COMPLETE\n if self._check_job_status(vnc_api, job_execution_id,\n JobStatus.FAILED):\n return JobStatus.FAILED\n\n return JobStatus.IN_PROGRESS\n # end _get_job_status\n\n def _wait(self, vnc_api, job_execution_id, timeout, max_retries):\n retry_count = 1\n while not self.is_job_done():\n self._job_status = self._get_job_status(vnc_api, job_execution_id)\n if not self.is_job_done():\n if retry_count >= max_retries:\n self._logger.error(\n \"job handler: timed out waiting for job %s for device\"\n \" %s and job_type %s:\" %\n (job_execution_id, self._device_list,\n str(self._job_type)))\n self._job_status = JobStatus.FAILED\n else:\n retry_count += 1\n gevent.sleep(timeout)\n # end _wait\n\n def get_job_status(self):\n return self._job_status\n # end get_job_status\n\n def is_job_done(self):\n if self._job_status == JobStatus.COMPLETE or \\\n self._job_status == JobStatus.FAILED:\n return True\n return False\n # end is_job_done\n\n @staticmethod\n def _get_vnc_api(ips, port, username, password, tenant, use_ssl):\n return VncApi(api_server_host=random.choice(ips),\n api_server_port=port, username=username,\n password=password, tenant_name=tenant,\n api_server_use_ssl=use_ssl)\n # end _get_vnc_api\n\n @classmethod\n def _verify_job_status(cls, job_status, status):\n return job_status and \\\n cls.JOB_STATUS_MAPPING.get(job_status.get('job_status')) == \\\n status\n # end _verify_job_status\n# end class JobHandler\n","sub_path":"src/config/device-manager/device_manager/plugins/ansible/job_handler.py","file_name":"job_handler.py","file_ext":"py","file_size_in_byte":5038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"561094529","text":"# Name: Allie Blaising \r\n\r\n# Stack class implemented with array\r\nclass Stack:\r\n \"\"\"Implements an efficient last-in first-out Abstract Data Type using a Python List\"\"\"\r\n\r\n # capacity is max number of Nodes, init_items is optional List parameter for initialization\r\n # if the length of the init_items List exceeds capacity, raise IndexError\r\n def __init__(self, capacity, init_items=None):\r\n \"\"\"Creates an empty stack with a capacity\"\"\"\r\n self.capacity = capacity # capacity of stack\r\n self.items = [None]*capacity # array for stack\r\n self.num_items = 0 # number of items in stack\r\n if init_items is not None: # if init_items is not None, initialize stack\r\n if len(init_items) > capacity:\r\n raise IndexError\r\n else:\r\n self.num_items = len(init_items)\r\n self.items[:self.num_items] = init_items\r\n\r\n def __eq__(self, other):\r\n return ((type(other) == Stack)\r\n and self.capacity == other.capacity\r\n and self.items[:self.num_items] == other.items[:other.num_items]\r\n )\r\n\r\n def __repr__(self):\r\n return (\"Stack({!r}, {!r})\".format(self.capacity, self.items[:self.num_items]))\r\n\r\n def is_empty(self):\r\n if self.num_items <= 0: \r\n return True\r\n return False\r\n '''Returns True if the stack is empty, and False otherwise\r\n MUST have O(1) performance'''\r\n\r\n def is_full(self):\r\n if self.num_items >= self.capacity: \r\n return True \r\n return False\r\n '''Returns True if the stack is full, and False otherwise\r\n MUST have O(1) performance'''\r\n\r\n def push(self, item):\r\n if self.is_full(): \r\n raise IndexError \r\n else: \r\n self.items[self.num_items] = item # num_items refers to the current index + 1, so if we index to \r\n # self.num_items, we can initialize the None value here to the value inputted in the push \r\n self.num_items += 1 \r\n return self \r\n '''If stack is not full, pushes item on stack. \r\n If stack is full when push is attempted, raises IndexError\r\n MUST have O(1) performance'''\r\n\r\n def pop(self): \r\n if not self.is_empty(): \r\n removed = self.items[self.num_items - 1] # extracts last non-None item \r\n self.items[self.num_items - 1] = None # changes last item to None (i.e. remove)\r\n self.num_items -= 1 \r\n return removed # just return the value at the index that we converted to None\r\n else: \r\n raise IndexError\r\n '''If stack is not empty, pops item from stack and returns item.\r\n If stack is empty when pop is attempted, raises IndexError\r\n MUST have O(1) performance'''\r\n\r\n def peek(self):\r\n if not self.is_empty(): \r\n return self.items[self.num_items-1] # extracts last non-None item, but doesn't modify to \r\n # none, so item is not popped \r\n else: \r\n raise IndexError\r\n '''If stack is not empty, returns next item to be popped (but does not pop the item)\r\n If stack is empty, raises IndexError\r\n MUST have O(1) performance'''\r\n\r\n def size(self):\r\n return self.num_items\r\n '''Returns the number of elements currently in the stack, not the capacity\r\n MUST have O(1) performance'''\r\n\r\n ","sub_path":"stack_array.py","file_name":"stack_array.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"600084892","text":"#Zach Watts\n#Lab 7: ROT Cipher\n\nrot_13 = {\n 'a' : 'n',\n 'b' : 'o',\n 'c' : 'p',\n 'd' : 'q',\n 'e' : 'r',\n 'f' : 's',\n 'g' : 't',\n 'h' : 'u',\n 'i' : 'v',\n 'j' : 'w',\n 'k' : 'x',\n 'l' : 'y',\n 'm' : 'z',\n 'n' : 'a',\n 'o' : 'b',\n 'p' : 'c',\n 'q' : 'd',\n 'r' : 'e',\n 's' : 'f',\n 't' : 'g',\n 'u' : 'h',\n 'v' : 'i',\n 'w' : 'j',\n 'x' : 'k',\n 'y' : 'l',\n 'z' : 'm',\n ' ' : ' '\n}\n\nalpha = 'abcdefghijklmnopqrstuvqxyz'\n\ndef main():\n rot = rotations()\n msg = message()\n choice = enc_or_dec()\n if choice == 'e':\n encrypt(rot, msg)\n elif choice == 'd':\n decrypt(rot, msg)\n exit()\n\ndef rotations():\n valid = 0\n while not valid:\n rot = int(input(\"Enter the number of rotations: \"))\n try:\n valid = 1\n except:\n ValueError\n print(\"Input must be a number\")\n return rot\n\ndef message():\n valid = 0\n while not valid:\n #msg = \"\"\n #while len(msg) < 1:\n msg = str(input(\"Enter the message you would like to encrypt\\n\\\n or decrypt without numbers, special characters or capital letters: \"))\n for char in msg:\n if char not in alpha:\n print(\"You have entered invalid character(s)\")\n else: \n valid = 1\n break\n return msg\n\ndef enc_or_dec():\n valid = 0\n while not valid:\n choice = input(\"Enter 'e' if you would like to encrypt your\\n\\\n message or 'd' if you would like to decrypt your message: \")\n if choice == 'e':\n valid = 1\n elif choice == 'd':\n valid = 1\n else:\n print(\"That is not a valid choice.\")\n return choice\n\ndef encrypt(rot_, msg_):\n enc_msg = \"\"\n for char in msg_:\n for idx, letter in enumerate(alpha):\n if char == letter:\n try: enc_msg += alpha[idx + rot_]\n except:\n IndexError\n enc_msg += alpha[idx - 26 + rot_]\n if char == \" \":\n enc_msg += \" \"\n print(enc_msg)\n return enc_msg\n\ndef decrypt(rot_, msg_):\n dec_msg = \"\"\n for char in msg_:\n for idx, letter in enumerate(alpha):\n if char == letter:\n try: dec_msg += alpha[idx - rot_]\n except:\n IndexError\n dec_msg += alpha[idx + 26 - rot_]\n if char == \" \":\n dec_msg += \" \"\n print(dec_msg)\n return dec_msg\n\n'''\ndef decrypt(rot_, msg_):\n dec_msg = \"\"\n dec_lst = [] \n for char in msg_:\n dec_lst.append(char)\n for char in dec_lst:\n\n for idx, letter in enumerate(alpha):\n dec_msg += \n pass\n'''\n\n\n'''\n#----------------------------------------VERSION 1---------------------------------------------#\ndef encrypt():\n valid = 0\n encrypted = \"\"\n while not valid:\n user_msg = input(\"Please input your message in lower case letters: \")\n try:\n for char in user_msg:\n encrypted += rot_13[char]\n valid = 1\n except:\n KeyError\n print(\"That value cannot be encrypted!\")\n print(encrypted)\n return encrypted\n#-----------------------------------------------------------------------------------------------#\n'''\n\nmain()","sub_path":"Code/Zach/PDX_6_14/Python/zach_lab_7.py","file_name":"zach_lab_7.py","file_ext":"py","file_size_in_byte":3359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"216942346","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^list/$', views.list, name='list'),\n url(r'^wish/$', views.wish_books, name='wish'),\n url(r'^wish/save/$', views.wish_books_save, name='wish_save'),\n url(r'^register/$', views.register, name='register'),\n url(r'^register/save/$', views.register_save, name='register_save'),\n url(r'^list/rent/(?P\\d+)/$', views.rent, name='rent'),\n url(r'^return/(?P\\d+)/$', views.return_book, name='return_book'),\n]","sub_path":"our_book/books/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"77653096","text":"##### import packages #####\nimport serial\nimport sys\t\t#for terminating the program immediately\nimport time\nimport tty, termios, sys #for getChar function\n\nfrom threading import Thread\n\nfrom flask import Flask , render_template,request\n\n\n\n##### global variables ####\n#rSpeed = 0\n#lSpeed = 0\nleft = right = 0\nJOYSTICK_DELAY = 0.05\nMOTOR_SPEED_MAX = 200\nMOTOR_SPEED_STEP = 17\nMOTOR_SPEED_TURN = 70\nMOTOR_SPEED_minISTEP = 10\n\n\n##### robot class #####\nclass autRobot:\n\tdef __init__(self):\n\t\t#self.portfd = 0; # File descriptor of robot which data in written to and has to be read from\n\t\tself.motorSpeedLeft = 0 # The number has to be set on the left motor input\n\t\tself.motorSpeedRight = 0 # The number has to be set on the right motor input\n\t\tself.motorShaftLeft = 0 # Left shaft encoder data\n\t\tself.motorShaftRight = 0 # Right shaft encoder data\n\t\tself.omegaL = 0.0 # Left angular velocity\n\t\tself.omegaR = 0.0 # Right angular velocity\n\t\tself.sonarRear = 0 # data of sonar number 0\n\t\tself.sonarRearL = 0 # data of sonar number 1\n\t\tself.sonarFrontL = 0 # data of sonar number 2\n\t\tself.sonarFront = 0 # data of sonar number 3\n\t\tself.sonarFrontR = 0 # data of sonar number 4\n\t\tself.sonarRearR = 0 # data of sonar number 5\n\t\tself.battery = 0.0 # battery life percentage\n\t\tself.reset = 0 # does robot need reseting?\n\t\tself.rSpeed = 0\n\t\tself.lSpeed = 0\n\n\t\t##### try to connect to serial port #####\n\t\ttry:\n\t\t\tser = serial.Serial(\"/dev/ttyUSB0\",38400) # try to connect to serial port\n\t\t\tself.portfd = ser\n\t\t\tprint(\"Successfully connected to seial! (USB0)\")\n\t\texcept:\n\t\t\ttry:\n\t\t\t\tser = serial.Serial(\"/dev/ttyUSB1\",38400)\n\t\t\t\tself.portfd = ser\n\t\t\t\tprint(\"Successfully connected to serial! (USB1)\")\n\t\t\texcept:\n\t\t\t\tprint(\"Sorry! Can NOT connect to the robot!\")\n\t\t\t\tsys.exit() #terminates the program immediately\n\n\n\t##### write motor speed in serial port #####\n\tdef writeData(self, rSpeed, lSpeed):\n\t\trobot.portfd.write(bytes(\"S %d %d\\n\"%(rSpeed, lSpeed), 'UTF-8'))\n\n\n\t##### read date from serial port & assign them to robot #####\n\tdef readData(self):\n\t\tdata = []\n\t\tfor count in range(0,9):\n\t\t\ttmp = self.portfd.readline().decode('UTF-8') \n\t\t\tif(count < 8):\n\t\t\t\tdata.append(int(tmp))\n\t\t\t\t#print (\"The %d's data is %s\"%(count+1, data[count]))\n\t\t\telse:\n\t\t\t\tself.battery = float(tmp)\n\t\t\t\t#print(robot.battery)\n\n\t\tself.motorShaftLeft = data[0]\n\t\tself.motorShaftRight = data[1]\n\t\tself.sonarRear = data[2]\n\t\tself.sonarRearL = data[3]\n\t\tself.sonarFrontL = data[4]\n\t\tself.sonarFront = data[5]\n\t\tself.sonarFrontR = data[6]\n\t\tself.sonarRearR = data[7] \n\n\t##### print robot data in terminal #####\n\tdef printData(self):\n\t\t#pfd = \"Port File Descriptor: %s\"% (robot.portfd)\n\t\tmspl = \"Left Motor Speed: %d\"% (self.motorSpeedLeft)\n\t\tmspr = \"Right Motor Speed: %d\"% (self.motorSpeedRight)\n\t\tmshl = \"Left Shaft Encoder Data: %d\"% (self.motorShaftLeft)\n\t\tmshr = \"Right Shaft Encoder Data: %d\"% (self.motorShaftRight)\n\t\tsr = \"Rear Sonar Data: %d\"% (self.sonarRear)\n\t\tsrl = \"Rear-Left Sonar Data: %d\"% (self.sonarRearL)\n\t\tsfl = \"Front-Left Sonar Data: %d\"% (self.sonarFrontL)\n\t\tsf = \"Front Sonar Data: %d\"% (self.sonarFront)\n\t\tsfr = \"Front-Right Sonar Data: %d\"% (self.sonarFrontR);\n\t\tsrr = \"Rear-Right Sonar Data: %d\"% (self.sonarRearR);\n\t\tbt = \"Battery Voltage: %f\"% (self.battery);\n\n\t\tprint(\"\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n\"%(mspl, mspr, mshl, mshr, sr, srl, sfl, sf, sfr, srr, bt))\n\n\n\t##### detect key from keyboard #####\n\tdef getChar(self):\n\t #Returns a single character from standard input\n\t\tfd = sys.stdin.fileno()\n\t\told_settings = termios.tcgetattr(fd)\n\t\ttry:\n\t\t\ttty.setraw(sys.stdin.fileno())\n\t\t\tch = sys.stdin.read(1)\n\t\tfinally:\n\t\t\ttermios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n\t\treturn ch\n\n\tdef setMotorSpeeds(self, right, left):\n\t\trobot.motorSpeedRight = right\n\t\trobot.motorSpeedLeft = left \n\t\t#print(\"rSpeed = %d, lSpeed = %d \\n\"%(right, left))\n\t\tself.updateRobot()\n\n\tdef updateRobot(self):\n\t\tself.writeData(self.motorSpeedRight, self.motorSpeedLeft)\n\t\tself.readData()\n\t\tself.printData()\n\n\n\tdef joystickMode(self):\n\t\tch = self.getChar()\n\t\tprint (\"char = %s\"%(ch))\n\t\t#if (ch == 'o' or ch == 'O' or ch == 'j' or ch == 'J' or ch == 'w' or ch == 'W' or ch == 's' or ch == 'S' or ch == 'd' or ch == 'D' or ch == 'a' or ch == 'A'):\n\t\t#if (self.getChar()):\n\t\tif(ch == 'o' or ch == 'O'):\n\t\t\tsys.exit() #terminates the program immediately\n\t\telif(ch == 'j' or ch == 'J'): \n\t\t\tself.rSpeed = self.lSpeed = 0\n\t\t\tself.setMotorSpeeds(self.rSpeed, self.lSpeed) \n\t\telif(ch == 'w' or ch == 'W'):\n\t\t\tif(self.lSpeed < MOTOR_SPEED_MAX or self.rSpeed < MOTOR_SPEED_MAX):\n\t\t\t\tself.lSpeed = min(MOTOR_SPEED_MAX, self.lSpeed + MOTOR_SPEED_STEP)\n\t\t\t\tself.rSpeed = min(MOTOR_SPEED_MAX, self.rSpeed + MOTOR_SPEED_STEP)\n\t\t\t\tself.setMotorSpeeds(self.rSpeed, self.lSpeed)\n\t\telif(ch == 's' or ch == 'S'): \n\t\t\tif(self.lSpeed > -1*MOTOR_SPEED_MAX or self.rSpeed > -1*MOTOR_SPEED_MAX):\n\t\t\t\tself.lSpeed = max(-1*MOTOR_SPEED_MAX, self.lSpeed - MOTOR_SPEED_STEP)\n\t\t\t\tself.rSpeed = max(-1*MOTOR_SPEED_MAX, self.rSpeed - MOTOR_SPEED_STEP)\n\t\t\t\tself.setMotorSpeeds(self.rSpeed, self.lSpeed) \n\t\telif(ch == 'a' or ch == 'A'): \n\t\t\tif(self.lSpeed > -1*MOTOR_SPEED_MAX or self.rSpeed < MOTOR_SPEED_MAX):\n\t\t\t\tself.lSpeed = max(-1*MOTOR_SPEED_MAX, self.lSpeed - MOTOR_SPEED_STEP)\n\t\t\t\tself.rSpeed = min(MOTOR_SPEED_MAX, self.rSpeed + MOTOR_SPEED_STEP)\n\t\t\t\tself.setMotorSpeeds(self.rSpeed, self.lSpeed) \n\t\telif(ch == 'd' or ch == 'D'): \n\t\t\tif (self.lSpeed < MOTOR_SPEED_MAX or self.rSpeed > -1*MOTOR_SPEED_MAX):\t\t\t\t\t\t\n\t\t\t\tself.lSpeed = min(MOTOR_SPEED_MAX, self.lSpeed + MOTOR_SPEED_STEP)\n\t\t\t\tself.rSpeed = max(-1*MOTOR_SPEED_MAX, self.rSpeed - MOTOR_SPEED_STEP)\n\t\t\t\tself.setMotorSpeeds(self.rSpeed, self.lSpeed) \n\t\ttime.sleep(JOYSTICK_DELAY)\n########### End of class ###########\n\n\n##### create robot object #####\nrobot = autRobot()\n\n\ndef joySM():\n\twhile True:\n\t\trobot.joystickMode()\n\nt = Thread(target = joySM)\nt.start()\n\n\napp=Flask (__name__)\n@app.route('/login/',methods=['GET', 'POST'])\ndef index(myname):\n\tif (request.method=='POST'):\n\t\tmy_command=request.form['command']\n\t\tif my_command==\"UP\":\n\t\t\tif(robot.lSpeed < MOTOR_SPEED_MAX or robot.rSpeed < MOTOR_SPEED_MAX):\n\t\t\t\trobot.lSpeed = min(MOTOR_SPEED_MAX, robot.lSpeed + MOTOR_SPEED_STEP)\n\t\t\t\trobot.rSpeed = min(MOTOR_SPEED_MAX, robot.rSpeed + MOTOR_SPEED_STEP)\n\t\t\t\trobot.setMotorSpeeds(robot.rSpeed, robot.lSpeed)\n\t\telif my_command==\"DOWN\":\n\t\t\tif(robot.lSpeed > -1*MOTOR_SPEED_MAX or robot.rSpeed > -1*MOTOR_SPEED_MAX):\n\t\t\t\trobot.lSpeed = max(-1*MOTOR_SPEED_MAX, robot.lSpeed - MOTOR_SPEED_STEP)\n\t\t\t\trobot.rSpeed = max(-1*MOTOR_SPEED_MAX, robot.rSpeed - MOTOR_SPEED_STEP)\n\t\t\t\trobot.setMotorSpeeds(robot.rSpeed, robot.lSpeed) \n\t\telif my_command==\"LEFT\":\n\t\t\tif(robot.lSpeed > -1*MOTOR_SPEED_MAX or robot.rSpeed < MOTOR_SPEED_MAX):\n\t\t\t\trobot.lSpeed = max(-1*MOTOR_SPEED_MAX, robot.lSpeed - MOTOR_SPEED_STEP)\n\t\t\t\trobot.rSpeed = min(MOTOR_SPEED_MAX, robot.rSpeed + MOTOR_SPEED_STEP)\n\t\t\t\trobot.setMotorSpeeds(robot.rSpeed, robot.lSpeed) \n\t\telif my_command==\"RIGHT\":\n\t\t\tif (robot.lSpeed < MOTOR_SPEED_MAX or robot.rSpeed > -1*MOTOR_SPEED_MAX):\t\t\t\t\t\t\n\t\t\t\trobot.lSpeed = min(MOTOR_SPEED_MAX, robot.lSpeed + MOTOR_SPEED_STEP)\n\t\t\t\trobot.rSpeed = max(-1*MOTOR_SPEED_MAX, robot.rSpeed - MOTOR_SPEED_STEP)\n\t\t\t\trobot.setMotorSpeeds(robot.rSpeed, robot.lSpeed)\n\t\telif my_command==\"STOP\":\n\t\t\trobot.rSpeed = robot.lSpeed = 0\n\t\t\trobot.setMotorSpeeds(robot.rSpeed, robot.lSpeed)\n\t\t#else:\n\t\t\t#rSpeed = lSpeed = 0\n\t\t\t#setMotorSpeeds(rSpeed, lSpeed)\n\t\ttime.sleep(JOYSTICK_DELAY)\n\t\treturn render_template('myHTML.html',myname=myname,command=my_command)\n\treturn render_template('myHTML.html',myname=myname,command=None)\nif __name__ == '__main__':\n\tapp.run(debug=True, host='0.0.0.0',port=2000)\n\n\nt.join()\n\n\n#t=Thread(target = fluskFunc, args=(myname, robot.rSpeed, robot.lSpeed, robot.setMotorSpeeds))\n\n\n\n#joySM()\n#fluskFunc(myname, robot.rSpeed, robot.lSpeed, robot.setMotorSpeeds)\n#t.start()\n","sub_path":"Flask_Method1.py","file_name":"Flask_Method1.py","file_ext":"py","file_size_in_byte":8142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"48386945","text":"import torch\nfrom torchvision.utils import save_image\n\nimport sampler\nimport sampler_o\nimport utils\nfrom gradient_visualizer import GradientVisualizer\n\nif __name__ == \"__main__\":\n image_path = './imgs/cute.jpg'\n cute_cat = utils.loadimage(image_path).unsqueeze(0)\n print(cute_cat.shape)\n\n trans_mat = torch.Tensor([[[0.6705, 0.4691, -0.1369],\n [-0.4691, 0.6705, -0.0432]]])\n out_shape = [128, 128]\n\n bilinear_sampler = sampler.Sampler('bilinear', 'zeros')\n bilinear_tarnsformed = bilinear_sampler.warp_image(\n cute_cat, trans_mat, out_shape=out_shape)\n # save_image(bilinear_tarnsformed, 'bilinear_transformed.png')\n # utils.showimg(bilinear_tarnsformed)\n\n bicubic_sampler = sampler.Sampler('bicubic', 'zeros')\n bicubic_tarnsformed = bilinear_sampler.warp_image(\n cute_cat, trans_mat, out_shape=out_shape)\n # save_image(bicubic_tarnsformed, 'bicubic_transformed.png')\n # utils.showimg(bicubic_tarnsformed)\n\n # utils.torchseed(666)\n # linearized_sampler_o = sampler_o.Sampler('linearized', 'zeros')\n # linearized_tarnsformed_o = linearized_sampler_o.warp_image(\n # cute_cat, trans_mat, out_shape=out_shape)\n # save_image(linearized_tarnsformed_o, 'linearized_transformed_ori.png')\n # # utils.showimg(linearized_tarnsformed_o)\n\n # utils.torchseed(666)\n linearized_sampler = sampler.Sampler('linearized', 'zeros')\n linearized_tarnsformed = linearized_sampler.warp_image(\n cute_cat, trans_mat, out_shape=out_shape)\n # save_image(linearized_tarnsformed, 'linearized_tarnsformed.png')\n # utils.showimg(linearized_tarnsformed)\n\n # print(linearized_tarnsformed_o.equal(linearized_tarnsformed))\n\n print(sampler.LinearizedMutilSample.hyperparameters())\n # sampler.LinearizedMutilSample.set_hyperparameters(noise_strength=2)\n\n # target_mo = torch.rand(1, 2)*2 - 1\n # target_mo = torch.zeros(1, 2)\n # print(target_mo)\n\n visualizer = GradientVisualizer(input=cute_cat, out_shape=[16, 16])\n visualizer.draw_gradient_grid(bilinear_sampler)\n visualizer.draw_gradient_grid(bicubic_sampler)\n # utils.torchseed(666)\n # visualizer.draw_gradient_grid(linearized_sampler_o, 'linearized_ori')\n utils.torchseed(666)\n visualizer.draw_gradient_grid(linearized_sampler)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"641573811","text":"# Written by Nisto\n# Developed under Python 3.4.2\n\nimport os\nimport sys\nimport struct\nimport math\n\nKDT_FILESIZE_LIMIT = 52428800 # 50 MiB\nKDT_HEADER_SIZE = 0x10\nKDT_OFF_ID = 0x00\nKDT_OFF_FILESIZE = 0x04\nKDT_OFF_TICKDIV = 0x08\nKDT_OFF_RESV1 = 0x0A\nKDT_OFF_TRACKS = 0x0C\nKDT_OFF_RESV2 = 0x0E\nKDT_OFF_SIZETBL = 0x10\n\n# KDT_EVT_SET_CHAN_VOL = 0x87\n# KDT_EVT_SET_PANNING = 0x8A\n# KDT_EVT_SET_CTRL_VOL = 0x8B\n# KDT_EVT_SET_CHANNEL = 0xC6\n# KDT_EVT_SET_TEMPO = 0xC7\n# KDT_EVT_PITCH_BEND = 0xC8\n# KDT_EVT_SET_INSTRUMENT = 0xC9\n# KDT_EVT_NOTE_OFF_STOP = 0xCA\n# KDT_EVT_NOTE_OFF_CONT = 0xCB\n# KDT_EVT_SET_TEMPO_LO = 0xCC\n# KDT_EVT_SET_TEMPO_HI = 0xCD\n# KDT_EVT_RESERVED = 0xCE\n# KDT_EVT_END_OF_TRACK = 0xFF\n\nclass KDT:\n def __init__(self, path, log=False, convert=False):\n self.path = path\n self.log = log\n self.convert = convert\n\n if os.path.getsize(self.path) > KDT_FILESIZE_LIMIT:\n sys.exit(\"ERROR: File too large: %s\" % self.path)\n\n with open(self.path, \"rb\") as kdt:\n self.buf = kdt.read()\n\n if self.buf[KDT_OFF_ID:KDT_OFF_ID+4] != b\"KDT1\" \\\n or os.path.getsize(self.path) < KDT_HEADER_SIZE :\n sys.exit(\"ERROR: Not a valid KDT1 file: %s\" % self.path)\n\n self.filesize = get_u32_le(self.buf, KDT_OFF_FILESIZE)\n self.tickdiv = get_u16_le(self.buf, KDT_OFF_TICKDIV)\n self.tracks = get_u16_le(self.buf, KDT_OFF_TRACKS)\n\n if self.filesize > os.path.getsize(path):\n sys.exit(\"ERROR: Indicated filesize exceeds actual filesize: %s\" % self.path)\n\n self.buf = bytearray(self.buf[:self.filesize])\n\n if self.convert:\n self.midi = bytearray(self.filesize * 4)\n\n if self.tracks > 0:\n\n self.offset = KDT_OFF_SIZETBL\n\n self.trk_size_tbl = []\n\n for trknum in range(self.tracks):\n self.trk_size_tbl.append( get_u16_le(self.buf, self.offset) )\n self.offset += 2\n\n self.trk_off_tbl = []\n\n for trknum in range(self.tracks):\n self.trk_off_tbl.append(self.offset)\n self.offset += self.trk_size_tbl[trknum]\n\n self.set_track(0)\n\n def set_track(self, trknum):\n self.trknum = trknum\n self.trk_size = self.trk_size_tbl[trknum]\n self.trk_off_start = self.trk_off_tbl[trknum]\n self.trk_off_end = self.trk_off_start + self.trk_size\n self.offset = self.trk_off_start\n self.channel = 0\n self.running = 0 # sequence running status (expect delta-time when zero - note or command otherwise)\n\n def read_cmd(self):\n cmd = self.buf[self.offset]\n\n if self.log: print(\"0x%04X COMMAND Command: 0x%02X/0x%02X \" % (self.offset - self.trk_off_start, cmd, cmd & 0x7F), end=\"\")\n\n # all commands except 0xCA and 0xCB take a parameter\n if cmd == 0xCA:\n self.running = 0\n self.offset += 1\n elif cmd == 0xCB:\n self.running = 1\n self.offset += 1\n else:\n param = self.buf[self.offset+1]\n self.running = param & 0x80\n self.offset += 2\n\n # Might be worth looking into:\n # http://web.archive.org/web/20151016183420/http://wiki.spinout182.com/w/Music_Sequences\n # https://sites.google.com/site/messiaen64/parsed-music-files\n\n if cmd == 0x86: # Sets reverb type (hall, room, etc.) on first call, volume/depth on next call (e.g. 86[tt], 86[vv]) ... I think?\n # param & 0x??\n if self.log: print(\"(Set Reverb Type), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n self.midi[self.moff:self.moff+4] = b\"\\xFF\\x01\\x01\\x3F\"\n self.moff += 4\n\n elif cmd == 0x87: # Set main / channel volume\n if self.log: print(\"(Set Main/Channel Volume), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n # self.midi[self.moff+2] = int(127.0 * math.sqrt((param & 0x7F) / 127.0))\n self.midi[self.moff+0] = 0xB0 | self.channel\n self.midi[self.moff+1] = 0x07\n self.midi[self.moff+2] = param & 0x7F\n self.moff += 3\n\n elif cmd == 0x8A: # Set panning\n if self.log: print(\"(Set Panning), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n # self.midi[self.moff+2] = int(127.0 * math.sqrt((param & 0x7F) / 127.0))\n self.midi[self.moff+0] = 0xB0 | self.channel\n self.midi[self.moff+1] = 0x0A\n self.midi[self.moff+2] = param & 0x7F\n self.moff += 3\n\n elif cmd == 0x8B: # Set controller volume (\"expression is a percentage of the channel volume\"?)\n if self.log: print(\"(Set Controller Volume), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n # self.midi[self.moff+2] = int(127.0 * math.sqrt((param & 0x7F) / 127.0))\n self.midi[self.moff+0] = 0xB0 | self.channel\n self.midi[self.moff+1] = 0x0B\n self.midi[self.moff+2] = param & 0x7F\n self.moff += 3\n\n elif cmd == 0xC6: # Set channel\n if self.log: print(\"(Set Channel), Parameter: 0x%02X\" % (param & 0x0F))\n if self.convert:\n # the tenth channel is the \"drum channel\" and could result in a\n # quiet track (both in Awave and fb2k)\n self.channel = param & 0x0F\n if self.channel >= 9:\n self.channel += 1\n self.channel &= 0x0F\n self.midi[self.moff:self.moff+4] = b\"\\xFF\\x01\\x01\\x3F\"\n self.moff += 4\n\n elif cmd == 0xC7: # Set tempo\n if self.log: print(\"(Set Tempo), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n # this equation is taken from the Silent Hill 2 driver;\n # Suikoden 2 and Silent Hill 1 both add by 2 instead of 10;\n # I don't know why, or what it represents, but adding by 10\n # seems to give a more accurate result for ALL games;\n # change if needed, and please report\n bpm = ((param & 0x7F) * 2) + 10\n\n # micrsoseconds per quarter-note = microseconds per minute / beats per minute\n mpqn = 60000000 // bpm\n\n self.midi[self.moff+0] = 0xFF\n self.midi[self.moff+1] = 0x51\n self.midi[self.moff+2] = 0x03\n self.midi[self.moff+3] = (mpqn >> 16) & 0xFF\n self.midi[self.moff+4] = (mpqn >> 8) & 0xFF\n self.midi[self.moff+5] = (mpqn >> 0) & 0xFF\n self.moff += 6\n\n elif cmd == 0xC8: # Pitch bend\n if self.log: print(\"(Pitch Bend), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n pitch = (param & 0x7F) << 7\n self.midi[self.moff+0] = 0xE0 | self.channel\n self.midi[self.moff+1] = pitch & 0x7F # LSB\n self.midi[self.moff+2] = pitch >> 7 # MSB\n self.moff += 3\n\n elif cmd == 0xC9: # Set instrument\n if self.log: print(\"(Set Instrument), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n self.midi[self.moff+0] = 0xC0 | self.channel\n self.midi[self.moff+1] = param & 0x7F\n self.moff += 2\n\n elif cmd == 0xCA: # Note-off last note (reset running status)\n if self.log: print(\"(Note-off + reset running status)\")\n if self.convert:\n self.midi[self.moff+0] = 0x80 | self.channel\n self.midi[self.moff+1] = self.note\n self.midi[self.moff+2] = 0\n self.moff += 3\n\n elif cmd == 0xCB: # Note-off last note (keep running status)\n if self.log: print(\"(Note-off + keep running status)\")\n if self.convert:\n self.midi[self.moff+0] = 0x80 | self.channel\n self.midi[self.moff+1] = self.note\n self.midi[self.moff+2] = 0\n self.moff += 3\n\n elif cmd == 0xCC: # Set tempo, low (added sometime in 2001)\n # (param & 0x7F) & 0xFF\n if self.log: print(\"(Set Tempo, BPM=0-127), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n bpm = param & 0x7F\n mpqn = 60000000 // bpm\n self.midi[self.moff+0] = 0xFF\n self.midi[self.moff+1] = 0x51\n self.midi[self.moff+2] = 0x03\n self.midi[self.moff+3] = (mpqn >> 16) & 0xFF\n self.midi[self.moff+4] = (mpqn >> 8) & 0xFF\n self.midi[self.moff+5] = (mpqn >> 0) & 0xFF\n self.moff += 6\n\n elif cmd == 0xCD: # Set tempo, high (added sometime in 2001)\n # (param & 0x7F) | 0x80\n if self.log: print(\"(Set Tempo, BPM=128-255), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n bpm = (param & 0x7F) | 0x80\n mpqn = 60000000 // bpm\n self.midi[self.moff+0] = 0xFF\n self.midi[self.moff+1] = 0x51\n self.midi[self.moff+2] = 0x03\n self.midi[self.moff+3] = (mpqn >> 16) & 0xFF\n self.midi[self.moff+4] = (mpqn >> 8) & 0xFF\n self.midi[self.moff+5] = (mpqn >> 0) & 0xFF\n self.moff += 6\n\n elif cmd == 0xCE: # Reserved (does nothing) as of 2002\n if self.log: print(\"(Reserved), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n self.midi[self.moff:self.moff+4] = b\"\\xFF\\x01\\x01\\x3F\"\n self.moff += 4\n\n elif cmd == 0xDB: # Reverb send amount? (or may at least affect reverb somehow it seems)\n # param & 0x??\n if self.log: print(\"(Reverb Send Amount?), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n # self.midi[self.moff:self.moff+4] = b\"\\xFF\\x01\\x01\\x3F\"\n # self.moff += 4\n self.midi[self.moff+0] = 0xB0 | self.channel\n self.midi[self.moff+1] = 0x5B\n self.midi[self.moff+2] = param & 0x7F\n self.moff += 3\n\n elif cmd == 0xF6: # Tune request?\n # param & 0x??\n if self.log: print(\"(Tune Request?), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n self.midi[self.moff:self.moff+4] = b\"\\xFF\\x01\\x01\\x3F\"\n self.moff += 4\n\n elif cmd == 0xFF: # End of track\n if self.log: print(\"(End of track)\")\n if self.convert:\n self.midi[self.moff+0] = 0xFF\n self.midi[self.moff+1] = 0x2F\n self.midi[self.moff+2] = 0x00\n self.moff += 3\n\n else:\n if self.log: print(\"(Unknown), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert: # Remaining commands are probably a subset of Sony's SEQp or SCEIMidi format\n self.midi[self.moff:self.moff+4] = b\"\\xFF\\x01\\x01\\x3F\"\n self.moff += 4\n\n def read_note(self):\n self.note = self.buf[self.offset] & 0x7F\n self.velocity = self.buf[self.offset+1] & 0x7F\n self.running = self.buf[self.offset+1] & 0x80\n if self.log: \n if self.velocity:\n print(\"0x%04X NOTE-ON Key: 0x%02X, Velocity: 0x%02X\" % (self.offset - self.trk_off_start, self.note, self.velocity))\n else:\n print(\"0x%04X NOTE-OFF Key: 0x%02X\" % (self.offset - self.trk_off_start, self.note))\n if self.convert:\n self.midi[self.moff+0] = (0x90 if self.velocity else 0x80) | self.channel\n self.midi[self.moff+1] = self.note\n self.midi[self.moff+2] = self.velocity\n # self.midi[self.moff+2] = int(127.0 * math.sqrt(self.velocity / 127.0))\n self.moff += 3\n self.offset += 2\n\n def read_delta_time(self):\n if self.log: print(\"0x%04X DELTA-TIME Time: \" % (self.offset - self.trk_off_start), end=\"\")\n if self.convert:\n self.midi[self.moff] = self.buf[self.offset]\n self.moff += 1\n self.time = self.buf[self.offset] & 0x7F\n more = self.buf[self.offset] & 0x80\n self.offset += 1\n while more:\n if self.convert:\n self.midi[self.moff] = self.buf[self.offset]\n self.moff += 1\n self.time <<= 7\n self.time |= self.buf[self.offset] & 0x7F\n more = self.buf[self.offset] & 0x80\n self.offset += 1\n if self.log: print(\"%d\" % self.time)\n self.running = 1\n\n def read_seq(self):\n if not self.running:\n self.read_delta_time()\n else:\n if self.buf[self.offset] & 0x80:\n self.read_cmd()\n else:\n self.read_note()\n\n # instead of having delta-times of 0 between events, KDT1 uses the\n # MSB in the command parameter / note velocity to save some bytes\n if self.convert:\n if self.running:\n if self.offset < self.trk_off_end:\n self.midi[self.moff] = 0\n self.moff += 1\n\n def find_cmd(self, cmd):\n cmd |= 0x80\n\n while self.offset < self.trk_off_end:\n if self.running:\n if self.buf[self.offset] == cmd:\n return True\n self.read_seq()\n\n return False\n\ndef get_u16_le(buf, offset=0):\n return struct.unpack(\"H\", n & 0xFFFF)\n\ndef put_u32_be(n):\n return struct.pack(\">I\", n & 0xFFFFFFFF)\n\ndef isnum(n):\n try:\n int(n)\n except ValueError:\n return False\n return True\n\ndef print_bgm_type(kdt):\n dynamic = False\n for trknum in range(2, kdt.tracks): # skip tracks 0 and 1\n for cmd in [0x87, 0x8B]:\n kdt.set_track(trknum)\n if kdt.find_cmd(cmd):\n volume = kdt.buf[kdt.offset+1] & 0x7F\n if volume == 0:\n dynamic = True\n if dynamic:\n print(\"Dynamic: %s\" % os.path.basename(kdt.path))\n else:\n print(\"Standard: %s\" % os.path.basename(kdt.path))\n\ndef print_initial_track_volumes(kdt):\n basename = os.path.basename(kdt.path)\n for trknum in range(kdt.tracks):\n for cmd in [0x87, 0x8B]:\n kdt.set_track(trknum)\n if kdt.find_cmd(cmd):\n voltype = \"main\" if cmd == 0x87 else \"ctrl\"\n volume = kdt.buf[kdt.offset+1] & 0x7F\n print(\"%s: track %02d %s volume = 0x%02X\" % (basename, trknum, voltype, volume))\n\ndef print_note_event_counts(kdt):\n basename = os.path.basename(kdt.path)\n for trknum in range(2, kdt.tracks): # skip tracks 0 and 1\n events = 0\n kdt.set_track(trknum)\n while kdt.offset < kdt.trk_off_end:\n if kdt.running:\n if kdt.buf[kdt.offset] < 0x80:\n events += 1\n kdt.read_seq()\n\n print(\"%s: %d note events in track %02d\" % (basename, events, trknum))\n # if events == 0:\n # print(\"%s: no note events in track %02d\" % (basename, trknum))\n\n# Prints all sequence events as human-readable lines for each track\ndef print_events(kdt):\n kdt.log = True\n for trknum in range(kdt.tracks):\n print(\"TRACK %02d\" % trknum)\n print(\"=\" * 80)\n print()\n kdt.set_track(trknum)\n while kdt.offset < kdt.trk_off_end:\n kdt.read_seq()\n print(\"\\n\" * 5)\n\n# Creates separate KDT files for each track (I suck at naming stuff :P)\ndef demute_and_isolate_all_tracks_to_separate_files(kdt):\n out_path = os.path.splitext(kdt.path)[0]\n for filenum in range(kdt.tracks):\n out_buf = kdt.buf\n for trknum in range(kdt.tracks):\n for cmd in [0x87, 0x8B]: # try finding main/channel vol first, then controller vol\n kdt.set_track(trknum)\n if kdt.find_cmd(cmd):\n if trknum < 2 or trknum == filenum:\n if not out_buf[kdt.offset+1] & 0x7F:\n out_buf[kdt.offset+1] |= 0x6E # demute (ALL initially demuted tracks in Silent Hill except track 2 of T.KDT and T2.KDT are initialized to 0x6E)\n else:\n out_buf[kdt.offset+1] &= 0x80 # isolate (keep status bit intact)\n\n with open(\"%s (track %02d).KDT\" % (out_path, filenum), \"wb\") as out:\n out.write(out_buf)\n\n# Creates a new KDT file with specified tracks demuted\ndef demute_and_isolate_specified_tracks_to_single_file(kdt, demute_args):\n if not demute_args:\n sys.exit(\"ERROR: No tracks to demute supplied\")\n\n demute = []\n\n for arg in demute_args:\n if \"-\" in arg:\n if arg.count(\"-\") == 1:\n start, end = arg.split(\"-\")\n if isnum(start) and isnum(end):\n start = int(start)\n end = int(end)\n\n if start > end:\n start, end = end, start\n\n if start > kdt.tracks-1:\n start = kdt.tracks-1 if kdt.tracks else 0\n\n if end > kdt.tracks-1:\n end = kdt.tracks-1 if kdt.tracks else 0\n\n if start == end:\n if start not in demute:\n demute.append(start)\n else:\n for n in range(start, end+1):\n if n not in demute:\n demute.append(n)\n else:\n sys.exit(\"Invalid argument: %s\" % arg)\n else:\n sys.exit(\"Invalid argument: %s\" % arg)\n elif isnum(arg):\n n = int(arg)\n\n if n > kdt.tracks-1:\n n = kdt.tracks-1 if kdt.tracks else 0\n\n if n not in demute:\n demute.append(n)\n else:\n sys.exit(\"Invalid argument: %s\" % arg)\n\n out_buf = kdt.buf\n\n for trknum in range(kdt.tracks):\n for cmd in [0x87, 0x8B]:\n kdt.set_track(trknum)\n if kdt.find_cmd(cmd):\n if trknum < 2 or trknum in demute:\n if not out_buf[kdt.offset+1] & 0x7F:\n out_buf[kdt.offset+1] |= 0x6E\n else:\n out_buf[kdt.offset+1] &= 0x80\n\n i = 0\n tracks = []\n demute = sorted(demute)\n\n while i < len(demute):\n start = end = demute[i]\n i += 1\n while end + 1 in demute:\n end += 1\n i += 1\n if start == end:\n tracks.append(\"%02d\" % start)\n else:\n tracks.append(\"%02d-%02d\" % (start, end))\n\n if len(demute) == 1:\n out_path = \"%s (track %s).KDT\" % (os.path.splitext(kdt.path)[0], tracks[0])\n else:\n out_path = \"%s (tracks %s).KDT\" % (os.path.splitext(kdt.path)[0], \", \".join(tracks))\n\n with open(out_path, \"wb\") as out:\n out.write(out_buf)\n\ndef kdt2midi(path):\n kdt = KDT(path, convert=True)\n\n kdt.midi[0x00:0x04] = b\"MThd\"\n kdt.midi[0x04:0x08] = put_u32_be(6) # mthd size\n kdt.midi[0x08:0x0A] = put_u16_be(1) # midi type\n kdt.midi[0x0A:0x0C] = put_u16_be(kdt.tracks)\n kdt.midi[0x0C:0x0E] = put_u16_be(kdt.tickdiv)\n kdt.moff = 0x0E\n\n for trknum in range(kdt.tracks):\n kdt.set_track(trknum)\n\n mtrk_off_start = kdt.moff\n\n kdt.midi[kdt.moff:kdt.moff+4] = b\"MTrk\" # id\n kdt.moff += 4\n kdt.midi[kdt.moff:kdt.moff+4] = put_u32_be(0) # size (tmp)\n kdt.moff += 4\n kdt.midi[kdt.moff+0] = 0x00 # delta time\n kdt.midi[kdt.moff+1] = 0xFF # meta event\n kdt.midi[kdt.moff+2] = 0x03 # event: track/seq name\n kdt.midi[kdt.moff+3] = 0x08 # size\n kdt.moff += 4\n kdt.midi[kdt.moff:kdt.moff+8] = bytes(\"Track %02d\" % trknum, encoding=\"ascii\")\n kdt.moff += 8\n\n while kdt.offset < kdt.trk_off_end:\n kdt.read_seq()\n\n kdt.midi[mtrk_off_start+4:mtrk_off_start+8] = put_u32_be( kdt.moff - (mtrk_off_start + 8) )\n\n with open(os.path.splitext(kdt.path)[0] + \".midi\", \"wb\") as midi:\n midi.write(kdt.midi[0:kdt.moff])\n\ndef main(argc=len(sys.argv), argv=sys.argv):\n path = os.path.realpath(argv[1])\n\n if not os.path.exists(path):\n sys.exit(\"ERROR: Invalid path\")\n\n # for filename in os.listdir(path):\n # fp = os.path.join(path, filename)\n # found = False\n # if os.path.splitext(fp)[1].upper() == \".KDT\":\n # kdt = KDT(fp)\n # for track in range(2, kdt.tracks):\n # kdt.set_track(track)\n # if kdt.find_cmd(0xC8):\n # print(\"Found pitch bend in track %02d of %s\" % (track, filename))\n # found = True\n # if found:\n # print(\"\\n\")\n\n # if os.path.isdir(path):\n # for filename in os.listdir(path):\n # filepath = os.path.join(path, filename)\n # if os.path.splitext(filename)[1].upper() == \".KDT\":\n # # print_note_event_counts(KDT(filepath))\n # print_initial_track_volumes(KDT(filepath))\n # #if os.path.splitext(filename)[1].upper() == \".TD\":\n # # with open(filepath, \"rb\") as td:\n # # with open(\"%s.kdt\" % os.path.splitext(filepath)[0], \"wb\") as kdt:\n # # kdt.write(td.read()[0x30:])\n # else:\n # sys.exit(\"ERROR: Expected a directory path\")\n # print_initial_track_volumes(KDT(path))\n\n # demute_and_isolate_all_tracks_to_separate_files(KDT(path))\n\n # demute_and_isolate_specified_tracks_to_single_file(KDT(path), argv[2:])\n\n # print_events(KDT(path))\n\n kdt2midi(path)\n\n return 0\n\nif __name__==\"__main__\":\n main()\n","sub_path":"kdt-tool.py","file_name":"kdt-tool.py","file_ext":"py","file_size_in_byte":22177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"88679897","text":"from typing import Union\n\nfrom dependency import User, user_collection, image_collection, PAGINATION_PAGE_SIZE, UniversalMLImage\nimport math\n\n\n# ---------------------------\n# User Database Interactions\n# ---------------------------\n\n\ndef add_user_db(user: User) -> dict:\n \"\"\"\n Add a new user to the database.\n \"\"\"\n\n # User types define permissions.\n if user.roles is None:\n roles = []\n\n if not user_collection.find_one({\"username\": user.username}):\n user_collection.insert_one(user.dict())\n return {'status': 'success', 'detail': 'account with username [' + str(user.username) + '] created.'}\n else:\n return {'status': 'failure', 'detail': 'Account with this username already exists'}\n\n\ndef get_user_by_name_db(username: str) -> Union[User, None]:\n \"\"\"\n Finds a user in the database by a given username\n :param username: username of user\n :return: User with successful record or None\n \"\"\"\n if not user_collection.find_one({\"username\": username}):\n return None\n\n database_result = user_collection.find_one({\"username\": username})\n user_object = User(**database_result)\n return user_object\n\n\ndef set_user_roles_db(username: str, updated_roles: list) -> bool:\n \"\"\"\n Sets the roles for a given user\n :param username: Username of user that will have roles modified\n :param updated_roles: Array of roles that user will now have\n :return: Success: True or False\n \"\"\"\n if not user_collection.find_one({\"username\": username}):\n return False\n\n user_collection.update_one({'username': username}, {'$set': {'roles': updated_roles}})\n return True\n\n\n# ---------------------------\n# Image Database Interactions\n# ---------------------------\n\n\ndef add_image_db(image: UniversalMLImage):\n \"\"\"\n Adds a new image to the database based on the UniversalMLImage model.\n \"\"\"\n\n if not image_collection.find_one({\"hash_md5\": image.hash_md5}):\n image_collection.insert_one(image.dict())\n\n\ndef add_user_to_image(image: UniversalMLImage, username: str):\n \"\"\"\n Adds a user account to an image. This is used to track what users upload images\n :param image: UniversalMLImage to update\n :param username: Username of user who is accessing image\n :return: None\n \"\"\"\n if image_collection.find_one({\"hash_md5\": image.hash_md5}):\n existing_users = image_collection.find_one({\"hash_md5\": image.hash_md5})['users']\n if username not in existing_users: # Only update if not in list already\n image_collection.update_one(\n {\"hash_md5\": image.hash_md5},\n {'$set': {'users': [existing_users, username]}}\n )\n\n\ndef get_images_from_user_db(username: str, page: int = -1):\n \"\"\"\n Returns a list of image hashes associated with the username. If a page number is provided, will return\n PAGINATION_PAGE_SIZE\n :param page: Page to return of results. Will return all if page is -1\n :param username: Username of user to get images for\n :return: Array of image hashes, total pages\n \"\"\"\n user = get_user_by_name_db(username)\n if not user: # If user does not exist, return empty\n return [], 0\n\n if page < 0:\n result = list(image_collection.find({\"users\": username}, {\"_id\"}))\n else:\n # We use this for actual db queries. Page 1 = index 0\n page_index = page - 1\n result = list(image_collection.find({\"users\": username}, {\"_id\"}).skip(PAGINATION_PAGE_SIZE * page_index).limit(\n PAGINATION_PAGE_SIZE))\n\n # Finally convert the dict of results to a flat list\n result = [image_map['_id'] for image_map in result]\n return result, math.ceil(len(list(image_collection.find({\"users\": username}, {\"_id\"}))) / PAGINATION_PAGE_SIZE)\n\n\ndef get_models_from_image_db(image: UniversalMLImage, model_name=\"\"):\n projection = {\n \"_id\": 0,\n \"models\": 1\n }\n\n if not image_collection.find_one({\"hash_md5\": image.hash_md5}):\n return {}\n\n if model_name != \"\":\n results = image_collection.find_one({\"hash_md5\": image.hash_md5}, projection)\n return {model_name: results['models'][model_name]}\n else:\n return image_collection.find_one({\"hash_md5\": image.hash_md5}, projection)['models']\n\n\ndef get_image_by_md5_hash_db(image_hash) -> Union[UniversalMLImage, None]:\n if not image_collection.find_one({\"hash_md5\": image_hash}):\n return None\n\n result = image_collection.find_one({\"hash_md5\": image_hash})\n result.pop('_id')\n return UniversalMLImage(**result)\n","sub_path":"server/db_connection.py","file_name":"db_connection.py","file_ext":"py","file_size_in_byte":4558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"629783687","text":"from rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom upday.authentication.student_authentication import StudentAuthentication\nfrom upday.modules.common.service.encrypt_service import EncryptService\nfrom upday.modules.community.serializer.like_serializer import TriggerValidator, CancelValidator\nfrom upday.modules.community.service.like_service import LikeService\nfrom upday.permission.basic_permission import BasicPermission\n\nencrypt_handler = EncryptService()\nlike_handler = LikeService()\n\n\nclass TriggerView(APIView):\n \"\"\"\n 点击喜欢帖子\n \"\"\"\n authentication_classes = (StudentAuthentication,)\n permission_classes = (BasicPermission,)\n\n def post(self, request, *args, **kwargs):\n validator = TriggerValidator(data=request.data, context={'request': request})\n validator.is_valid(raise_exception=True)\n conclusion = validator.validated_data['conclusion']\n student = request.user\n like_handler.create_like_and_add_num(student=student, conclusion=conclusion)\n # 计算今日点赞量,并增加能量值\n like_handler.check_and_add_achievement(student)\n\n return Response(\n data={'result': 'Success'}, content_type='application/json'\n )\n\n\nclass CancelView(APIView):\n \"\"\"\n 取消帖子\n \"\"\"\n authentication_classes = (StudentAuthentication,)\n permission_classes = (BasicPermission,)\n\n def post(self, request, *args, **kwargs):\n validator = CancelValidator(data=request.data, context={'request': request})\n validator.is_valid(raise_exception=True)\n conclusion = validator.validated_data['conclusion']\n like = validator.validated_data['like']\n student = request.user\n like_handler.delete_and_subtract_num_and_check_achievement(like, student, conclusion=conclusion)\n\n return Response(\n data={'result': 'Success'}, content_type='application/json'\n )\n","sub_path":"upday/modules/community/views/like_views.py","file_name":"like_views.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"485287927","text":"\"\"\"QuerySetTesting 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\nfrom queryApp.views import *\n\nurlpatterns = [\n path('', data_send, name=\"home\"),\n path('data', data_load, name=\"data\"),\n path('chart', chart, name=\"data\"),\n path('data//', detail_view_via_form, name=\"customers\"),\n path('dataq//', detail_view, name=\"customersq\"),\n path('customer_saved', updateUser.as_view(), name=\"customer_saved\"),\n path('map', map, name=\"customers\"),\n]\n","sub_path":"queryApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"150183394","text":"class Formatter():\n \n def __init__(self, arg):\n self.arg = arg\n\n def get_filth_type(self):\n return f'Type: {str(type(self.arg))}'\n\nclass DrinkFormatter(Formatter):\n \n def __init__(self, json: dict):\n if(isinstance(json, dict) != True):\n raise TypeError('The argument must be of type dict')\n self.json = json\n Formatter.__init__(self, json)\n\n def make_ingredients_string(self):\n ingredients = [self.json.get(ing) for ing in self.json if 'Ingredient' in ing and self.json.get(ing) is not None]\n measurements = [self.json.get(measure) for measure in self.json if 'Measure' in measure and self.json.get(measure) is not None]\n if(len(measurements) == 0):\n return ingredients\n ingredient_list = []\n for i in range(len(ingredients)):\n if(i < len(measurements)):\n ingredient_list.append(measurements[i].strip() + \" \" + ingredients[i])\n elif(ingredients[i] == ' '):\n pass\n else:\n ingredient_list.append(ingredients[i])\n return ingredient_list\n\n def __repr__(self):\n return f'DrinkFormatter Arg Type: {str(type(self.json))}'","sub_path":"util/Formatter.py","file_name":"Formatter.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"64246051","text":"import logging\n\nlog_levels = {\n 'ERROR': logging.ERROR,\n 'WARNING': logging.WARNING,\n 'DEBUG': logging.DEBUG,\n 'INFO': logging.INFO,\n 'CRITICAL': logging.CRITICAL,\n 'NOTSET': logging.NOTSET,\n}\n\ndef enc_logger(logger, log_config):\n logging_format = '[%(levelname)s] %(asctime)-15s:%(message)s'\n Formatter = logging.Formatter(fmt=logging_format)\n log_level = log_levels.get(log_config.get('log_level'))\n file_handler = logging.FileHandler(log_config.get('log_file'))\n file_handler.setLevel(log_levels.get('DEBUG'))\n file_handler.setFormatter(Formatter)\n logger.addHandler(file_handler)\n\n","sub_path":"OAuth2/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"188276955","text":"import csv\r\nimport numpy as np\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom sklearn.naive_bayes import MultinomialNB\r\nfrom sklearn.pipeline import Pipeline\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom yellowbrick.text import FreqDistVisualizer\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom pycm import *\r\n\r\n# An example of natural language processing\r\n\r\n\r\nwith open('train.tsv','r') as f:\r\n\treader = csv.reader(f,delimiter='\\t')\r\n\tyval = []\r\n\txval = []\r\n\tfor row in reader:\r\n\t\tyval.append(row[0])\r\n\t\txval.append(row[1])\r\n\t\t\r\nvectorizer = CountVectorizer()\r\ndocs = vectorizer.fit_transform(xval)\r\nfeatures = vectorizer.get_feature_names()\r\nvisualizer = FreqDistVisualizer(features=features)\r\nvisualizer.fit(docs)\r\nvisualizer.poof()\r\n\r\npipe = Pipeline([('TfidVec', TfidfVectorizer(max_features=300)),\r\n ('bayes' , MultinomialNB(multi_class='auto')), ])\r\n\r\nparams = {'TfidVec__max_df': [1.0, 0.9],\r\n 'TfidVec__min_df': [0.1,0.0],\r\n 'bayes__alpha' : np.linspace(0.6,1.0,5)}\r\n\t\t\t\r\nconvert = GridSearchCV(pipe,params)\t\t\t\r\nmodel = convert.fit( xval, yval )\r\nprint('score is', model.score(xval, yval))\r\n#print(model)\r\n\r\nwith open('test.tsv','r') as f:\r\n\treader = csv.reader(f)\r\n\tsample_x = []\r\n\tfor row in reader:\r\n\t\tsample_test.append(','.join(row))\r\n\r\ny_pred = model.predict(sample_test)\r\n\r\ncm = ConfusionMatrix(actual_vector=y_val, predict_vector=y_pred)\r\nprint(cm)\r\n\r\nwith open('result.csv','w') as f:\r\n\tfor x in y_pred:\r\n\t\tf.write(\"%s,\\n\"%(x))\r\n\t\r\n\r\n\t\r\n\t\r\n","sub_path":"NLP/NLP_example.py","file_name":"NLP_example.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"200676329","text":"from threeza.conventions import k_and_tau_to_horizon_str, horizon_str_to_k_and_tau, MAX_TAU\n\n\ndef test_horizon():\n for tau in [-MAX_TAU+1, 153, 1, 0, -3, MAX_TAU-1]:\n for k in [141,0,1,4]:\n h = k_and_tau_to_horizon_str(k=k, tau=tau)\n k_back, tau_back = horizon_str_to_k_and_tau(h)\n assert k==k_back\n assert tau==tau_back\n\n\nif __name__=='__main__':\n test_horizon()","sub_path":"tests/categorical/test_horizon.py","file_name":"test_horizon.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"596659326","text":"\n\n#calss header\nclass _CULTIVATED():\n\tdef __init__(self,): \n\t\tself.name = \"CULTIVATED\"\n\t\tself.definitions = [u'Someone who is cultivated has had a good education and knows a lot about and likes art, music, painting, etc.', u'Cultivated land is used to grow crops: ']\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/_cultivated.py","file_name":"_cultivated.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"76839780","text":"import discord\nfrom discord.ext import commands\nfrom random import choice as randomchoice\nfrom .utils.dataIO import fileIO\nfrom .utils import checks\nimport os\n\ndefaultQuotes = [\n\t\"Thats why I love switch hitting, I like to be in control ~ Jan, from the Hypermine Dragon Fight - 21st May 2016\",\n\t\"Thank you for wwaking within our server today- That sounds wrong. That does not sound PG at all -Jandoncom 24/5/16\",\n\t\"EVERYONE RUN! GECKOR IS DRIVING A TRUCK AGAIN /o\\ ~ N7DeltaForce 03/06/16\",\n\t\"Everyone wants a piece of this -Jandoncom 7/6/2016\",\n\t\"I Want Khip Kho's Heart! ~ Jandoncom 7/6/2016\"]\n\nclass Quote:\n\t\"\"\"Quote System for Red-DiscordBot\n\n\tBased on the MIRC Quote Script by Zsadist (Hawkee Link: http://hawkee.com/snippet/8378/ )\"\"\"\n\n\tdef __init__(self, bot):\n\t\tself.bot = bot\n\t\tself.quotes = fileIO(\"data/quote/quotes.json\", \"load\")\n\n\tdef save_quotes(self):\n\t\tfileIO(\"data/quote/quotes.json\", 'save', self.quotes)\n\n\t@commands.group(pass_context=True, invoke_without_command=True)\n\tasync def quote(self, ctx):\n\t\t\"\"\"Random Quote to be Drawn\"\"\"\n\t\tawait self.bot.say(\"Quote: \" + randomchoice(self.quotes) + \" \")\n\n\t@quote.command()\n\tasync def add(self, quote):\n\t\t\"\"\"Adds a Quote to the List\"\"\"\n\t\tif quote in self.quotes:\n\t\t\tawait self.bot.say(\"That quote is already in the database!\")\n\t\telse:\n\t\t\tself.quotes.append(quote)\n\t\t\tself.save_quotes()\n\t\t\tawait self.bot.say(\"Quote: \" + quote + \" has been saved to the database!\")\n\n\t@quote.command()\n\t@checks.mod_or_permissions(adminstrator=True)\n\tasync def remove(self, quote):\n\t\t\"\"\"Removes a Quote from the list\"\"\"\n\t\tif quote not in self.quotes:\n\t\t\tawait self.bot.say(\"That quote is already in the database!\")\n\t\telse:\n\t\t\tself.quotes.remove(quote)\n\t\t\tself.save_quotes()\n\t\t\tawait self.bot.say(\"Quote: \" + quote + \" has been removed from the database!\")\n\ndef check_folder():\n\tif not os.path.exists(\"data/quote\"):\n\t\tprint(\"Creating data/quote\")\n\t\tos.makedirs(\"data/quote\")\n\ndef check_files():\n\tfileName = \"data/quote/quotes.json\"\n\tif not fileIO(fileName, \"check\"):\n\t\tprint(\"Creating Empty Quote.json File\")\n\t\tprint(\"Creation Complete! Enjoy your new Quote System ~ Wolfstorm\")\n\t\tfileIO(fileName, \"save\", defaultQuotes)\n\ndef setup(bot):\n\tcheck_folder()\n\tcheck_files()\n\tQuoteSystem = Quote(bot)\n\tbot.add_cog(QuoteSystem)\n\n\n","sub_path":"quote/quote.py","file_name":"quote.py","file_ext":"py","file_size_in_byte":2264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"253493071","text":"import requests\nimport bs4\nimport subprocess\nfrom datetime import datetime\n\ndef main():\n prediction = get_prediction()\n print(prediction)\n say_prediction(prediction)\n\ndef get_prediction():\n res = requests.get('https://tenki.jp/heatshock/5/25/5040/22130/')\n res.raise_for_status()\n soup = bs4.BeautifulSoup(res.text, \"html.parser\")\n elem = soup.select('.today-weather .heatshock-telop-2')\n return elem[0].getText()\n \n\ndef jtalk(t):\n open_jtalk=['open_jtalk']\n mech=['-x','/var/lib/mecab/dic/open-jtalk/naist-jdic']\n htsvoice=['-m','/usr/share/hts-voice/mei/mei_normal.htsvoice']\n speed=['-r','1.0']\n outwav=['-ow','open_jtalk.wav']\n cmd=open_jtalk+mech+htsvoice+speed+outwav\n c = subprocess.Popen(cmd,stdin=subprocess.PIPE)\n c.stdin.write(t.encode())\n c.stdin.close()\n c.wait()\n aplay = ['aplay','-q','open_jtalk.wav']\n wr = subprocess.Popen(aplay)\n\ndef say_prediction(prediction):\n d = datetime.now()\n text = '%s月%s日、本日のヒートショック予報をします。本日は、%s、です。' % (d.month, d.day, prediction)\n jtalk(text)\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"test/get_prediction.py","file_name":"get_prediction.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"231643796","text":"#!/usr/bin/python\nimport os, sys, subprocess\n\ncwd = os.getcwd()\nserver = sys.argv[1]\nfile = open(\"./out/pids.pid\", \"r\")\nhostNum = \"\";\n\nkill = False\nfor line in file:\n # get port:pid or Proxy:pid\n pid = line.strip('\\n').split(\":\")\n\n if (pid[0] == \"Server12345\") and (server == \"all\" or server == \"1\" ):\n hostNum = \"13\"\n host = \"dh2026pc\" + hostNum + \".utm.utoronto.ca\"\n remoteCommand = 'cd \"{}\";kill {};'.format(cwd, pid[1])\n print(remoteCommand)\n kill = True\n elif (pid[0] == \"Server12346\") and (server == \"all\" or server == \"2\"):\n hostNum = \"14\"\n host = \"dh2026pc\" + hostNum + \".utm.utoronto.ca\"\n remoteCommand = 'cd \"{}\";kill {};'.format(cwd, pid[1])\n print(remoteCommand)\n kill = True\n elif (pid[0] == \"Server12347\") and (server == \"all\" or server == \"3\") :\n hostNum = \"15\"\n host = \"dh2026pc\" + hostNum + \".utm.utoronto.ca\"\n remoteCommand = 'cd \"{}\";kill {};'.format(cwd, pid[1])\n print(remoteCommand)\n kill = True\n elif (pid[0] == \"Proxy\") and (server == \"all\" or server == \"p\" ):\n print(\"Killed Proxy\")\n subprocess.Popen([\"kill\",pid[1]])\n continue\n elif (pid[0] == \"Monitor\") and (server == \"all\" or server == \"m\" ):\n print(\"Killed Monitor\")\n subprocess.Popen([\"kill\",pid[1]])\n\n if(kill):\n subprocess.Popen([\"ssh\", host, remoteCommand])\n kill = False\n \n ","sub_path":"A1/KillService.py","file_name":"KillService.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"232782605","text":"import logging\nfrom abc import abstractmethod, ABC\nfrom wrapt import synchronized\nfrom datetime import datetime\n\nfrom investing_algorithm_framework.core.events.observable import Observable\nfrom investing_algorithm_framework.core.events.observer import Observer\nfrom investing_algorithm_framework.configuration.constants \\\n import FRAMEWORK_NAME\n\nlogger = logging.getLogger(FRAMEWORK_NAME)\n\n\nclass Worker(Observable, ABC):\n \"\"\"\n Class Worker: manages the execution of a task and the context around\n executing it.\n \"\"\"\n\n id = None\n last_run: datetime = None\n\n def start(self, **kwargs) -> None:\n \"\"\"\n Function that will start the worker, and notify its observers when\n it is finished\n \"\"\"\n\n try:\n logger.info(\"Starting worker {}\".format(self.get_id()))\n except Exception as e:\n logger.exception(e)\n return\n\n try:\n self.work(**kwargs)\n self.notify_observers()\n self.update_last_run()\n except Exception as e:\n logger.error(\"Error occurred in worker {}\".format(self.get_id()))\n logger.exception(e)\n self.update_last_run()\n\n logger.info(\"Worker {} finished\".format(self.get_id()))\n\n @abstractmethod\n def work(self, **kwargs) -> None:\n \"\"\"\n Function that needs to be implemented by a concrete class.\n \"\"\"\n pass\n\n def add_observer(self, observer: Observer) -> None:\n super(Worker, self).add_observer(observer)\n\n def remove_observer(self, observer: Observer) -> None:\n super(Worker, self).remove_observer(observer)\n\n def get_id(self) -> str:\n assert getattr(self, 'id', None) is not None, (\n \"{} should either include a id attribute, or override the \"\n \"`get_id()`, method.\".format(self.__class__.__name__)\n )\n\n return getattr(self, 'id')\n\n @classmethod\n @synchronized\n def update_last_run(cls) -> None:\n \"\"\"\n Update last run, this function is synchronized, which means that\n different instances can update the last_run attribute from different\n threads.\n \"\"\"\n cls.last_run = datetime.now()\n\n @classmethod\n def get_last_run(cls):\n return cls.last_run\n","sub_path":"investing_algorithm_framework/core/workers/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"123830918","text":"\"\"\"\nFind the sum of the digits in the number 100!\n\"\"\"\n\ndef factorial(n):\n \"\"\" Returns the result n! \"\"\"\n if n == 0 or n == 1:\n return n\n else:\n return n * factorial(n-1)\n\n\n\nif __name__ == \"__main__\":\n # find 100!\n number = factorial(100)\n\n \n total = 0\n\n # add the value of each digit to total\n for digit in str(number):\n total += int(digit)\n\n print(total)\n\n","sub_path":"projectEuler/factorial_digit_sum.py","file_name":"factorial_digit_sum.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"393953061","text":"\nimport cv2\nimport numpy as np\nimport time\n\ndef binary_2_hex(masked):\n bin_str = \"\" \n big_out_arr = []\n new_arr = []\n for sub_arr in masked:\n for i,bin in enumerate(sub_arr):\n # print(bin_str)\n if i%8 == 0 and not i==0:\n # Convert the last string into a 4 dig hex in case it's 3\n hex_num = hex(int(bin_str.ljust(8, '0') , 2))\n if len(str(hex_num)) == 3 :\n hex_num = \"0x0\" + hex_num[2]\n new_arr.append(hex_num)\n bin_str = \"\" + str(bin)\n else:\n bin_str = bin_str + str(bin)\n \n # Convert the last string into a 4 dig hex in case it's 3\n hex_num = hex(int(bin_str.ljust(8, '0') , 2))\n if len(str(hex_num)) == 3 :\n hex_num = \"0x0\" + hex_num[2]\n\n new_arr.append(hex_num) #pad with 0's right\n bin_str = \"\"\n big_out_arr.append(new_arr)\n new_arr = []\n # print(\"------------\")\n \n return big_out_arr\n\n # print(big_out_arr)\ndef my_flatten(big_out_arr):\n one_d_out_arr = []\n for row in big_out_arr:\n for elem in row:\n one_d_out_arr.append(elem)\n\n return one_d_out_arr\n \n############ Script params, please feel free to edit\n# Default params for swoop logo\n# new_size = (25, 35) \n# graphic_file = 'swoop_logo.png'\n# show_img = False # Show what the final image will look like\n# write_to_file = True\n# invert_colour_selection = False\n# array_name = \"swoop_logo\"\n\n# Default params for battery\nnew_size = (100, 50) \ngraphic_file = 'battery-full.png'\nshow_img = False # Show what the final image will look like\nwrite_to_file = True\ninvert_colour_selection = True\narray_name = \"battery_full\"\n\n############ Start of the script\n# read the image file\nimg = cv2.imread(graphic_file, 2)\n\n# rescale and convert to binary\nbw_img = cv2.resize(img, dsize=new_size, interpolation = cv2.INTER_AREA) \nret, bw_img = cv2.threshold(bw_img, 70, 255, cv2.THRESH_BINARY)\n\n# Show image \nif show_img == True:\n cv2.imshow(\"Binary\", bw_img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\n# Convert 255's to 1's. 3 is a temporary number\nmasked = np.int32(bw_img)\nif invert_colour_selection == True:\n masked[masked==255] = 3\n masked[masked==0] = 1\n masked[masked==3] = 0\nelse:\n masked[masked==255] = 1\n\n\n\n# Group the 1's into 8 for hex conversion\nmasked = binary_2_hex(masked)\nmasked = my_flatten(masked)\n# masked = masked.flatten(order='C') #<- for use with numpy - now deprecated\n\n# Print in a form that directly copy-pastes\nprint('[%s]' % ', '.join(map(str, masked)))\nprint(len(list(masked)))\n\nif write_to_file == True:\n with open(\"image_hex.txt\", \"w\") as hex_img_file:\n hex_img_file.write(\"static const uint8_t {}[{}] PROGMEM = {{\\n\\t\".format(array_name, len(list(masked)) ))\n for i, hex_code in enumerate(masked):\n if i==(len(masked)-1): #if its the last number, dont add a comma after\n hex_img_file.write(str(hex_code))\n else:\n hex_img_file.write(str(hex_code)+\", \")\n\n hex_img_file.write(\"\\n};\\n\")\n\n\n\n\n\n","sub_path":"img_to_bw.py","file_name":"img_to_bw.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"376165874","text":"from random import randint\r\n\r\ndef roll(sd=6):\r\n rolled = randint(1,sd)\r\n return rolled\r\n\r\ndef main():\r\n sd = 6\r\n rolling = True\r\n while rolling:\r\n again = input('press enter to roll or \"q\" for quit: ')\r\n if again.lower() != 'q':\r\n rolled = roll(sd)\r\n print(rolled)\r\n else:\r\n rolling = False\r\n print('End program')\r\n\r\nmain()\r\n","sub_path":"Dice roll.py","file_name":"Dice roll.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"19633746","text":"\n# Copyright 2016-2022 The FEAGI 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\nparameters = {}\ngenome = {}\ngenome_stats = {}\ngenome_test_stats = []\nbrain = {}\ncortical_list = []\ncortical_map = {}\nintercortical_mapping = []\nupstream_neurons = {}\nmemory_list = {}\nactivity_stats = {}\ntemp_neuron_list = []\noriginal_genome_id = []\nfire_list = []\ntermination_flag = False\nvariation_counter_actual = 0\nexposure_counter_actual = 0\nmnist_training = {}\nmnist_testing = {}\ntop_10_utf_memory_neurons = {}\ntop_10_utf_neurons = {}\nv1_members = []\nprunning_candidates = set()\ngenome_id = \"\"\nevent_id = '_'\nblueprint = \"\"\ncomprehension_queue = ''\nworking_directory = ''\nconnectome_path = ''\npaths = {}\nwatchdog_queue = ''\nexit_condition = False\nfcl_queue = ''\nproximity_queue = ''\nlast_ipu_activity = ''\nlast_alertness_trigger = ''\ninfluxdb = ''\nmongodb = ''\nrunning_in_container = False\nhardware = ''\ngazebo = False\nhw_controller_path = ''\nhw_controller = None\nopu_pub = None\nbrain_activity_pub = None\nbrain_activity_pub_freq = 1\nrouter_address_gazebo = None\nrouter_address_godot = None\nrouter_address_virtual = None\nburst_timer = None\ngenome2 = {}\ngenome_ver = None\nfire_queue = {}\ncontroller_config = None\nburst_publisher = None\nburst_activities = {}\nopu_data = {}\ncortical_dimensions = {}\nvoxel_dict = {}\n\n# rules = \"\"\nbrain_is_running = False\n\n# live_mode_status can have modes of idle, learning, testing, tbd\nlive_mode_status = 'idle'\nfcl_history = {}\nbrain_run_id = \"\"\nburst_detection_list = {}\nburst_count = 0\nfire_candidate_list = {}\nprevious_fcl = {}\nfuture_fcl = {}\nlabeled_image = []\ntraining_neuron_list_utf = {}\ntraining_neuron_list_img = {}\nempty_fcl_counter = 0\nneuron_mp_list = []\npain_flag = False\ncumulative_neighbor_count = 0\ntime_neuron_update = ''\ntime_apply_plasticity_ext = ''\nplasticity_time_total = None\nplasticity_time_total_p1 = None\nplasticity_dict = {}\n\ntester_test_stats = {}\n\n# Flags\nflag_ready_to_inject_image = False\n","sub_path":"src/inf/runtime_data.py","file_name":"runtime_data.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"650124423","text":"import signal\nimport time\n\nclass GracefulKiller:\n kill_now = False\n def __init__(self):\n signal.signal(signal.SIGINT, self.exit_gracefully)\n signal.signal(signal.SIGTERM, self.exit_gracefully)\n\n def exit_gracefully(self,signum, frame):\n self.kill_now = True\n\nif __name__ == '__main__':\n killer = GracefulKiller()\n print(\"I'm going into the loop\")\n while True:\n if killer.kill_now:\n break\n\n print (\"End of the program. I was killed gracefully\")\n","sub_path":"playground/trap_key.py","file_name":"trap_key.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"39737763","text":"\"\"\"\nCreation of Trainloader and Testloader from CIFAR10 Dataset\n\"\"\"\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\n\ntransform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n])\n\n# Training Data from CIFAR10 Dataset\ntrain_data = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(train_data, batch_size=512, shuffle=True, num_workers=2)\n\n# Testing Data from CIFAR10 Dataset\ntest_data = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)\ntestloader = torch.utils.data.DataLoader(test_data, batch_size=512, shuffle=False, num_workers=2)\n\n# Class labels\nclasses = ('Airplane', 'Car', 'Bird', 'Cat', 'Deer', 'Dog', 'Frog', 'Horse', 'Ship', 'Truck')\n","sub_path":"06_Deep_CNN_Architectures/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"314730834","text":"import turtle\r\nimport gameScreen\r\n#Pen\r\npen = turtle.Turtle()\r\npen.speed(0)\r\npen.shape(\"square\")\r\npen.penup()\r\npen.hideturtle()\r\n\r\ndef pen_update(score_a, score_b):\r\n pen.clear()\r\n pen.goto(-600, 300)\r\n pen.color(\"Blue\")\r\n pen.write(\"Player Blue: {}\".format(score_a), align=\"left\", font=(\"Courier\", 24, \"normal\"))\r\n pen.color(\"red\")\r\n pen.goto(600, 300)\r\n pen.write(\"Player Red: {}\".format(score_b), align=\"right\", font=(\"Courier\", 24, \"normal\"))\r\n gameScreen.ball.dx = 2\r\n gameScreen.ball.dy = 1.4\r\n","sub_path":"Air Hockey/pen.py","file_name":"pen.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"411053943","text":"import functions as func\r\n\r\ndef completion_time(bt):\r\n ct = []\r\n for i in range(len(bt)):\r\n if i != 0:\r\n ct.append(bt[i] + ct[i - 1])\r\n else:\r\n ct.append(bt[0])\r\n return ct\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print('Non-Preemptive process')\r\n print('Criteria:- Arrival Time')\r\n arrival_time = [0, 1, 2, 3, 4]\r\n burst_time = [4, 3, 1, 2, 5]\r\n comp_time = completion_time(burst_time)\r\n tat = func.turn_around_time(arrival_time, comp_time)\r\n w_time = func.waiting_time(comp_time, arrival_time, burst_time)\r\n func.display(arrival_time, burst_time, comp_time, w_time, tat)\r\n","sub_path":"Programs/Python/first come first serve.py","file_name":"first come first serve.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"394109762","text":"\n\n#========================= User Defined Variables =========================\ninFile = '/Users/biggus/Desktop/2KBup_collapsed_upstream_ex-conserved_mosquito-motifs_nr.te.hgp.ngt0.pVal.culled.txt'\noutFile = '/Users/biggus/Desktop/2KBup_collapsed_upstream_ex-conserved_mosquito-motifs_nr.te.hgp.ngt0.pVal.culled.sorted.txt'\n\n#==========================================================================\n\n#--------- Script Specific Function Definitions ---------------------\n\n\n#--------------------------------------------------------------------\n\n\ninFile = open(inFile, 'rU').readlines()\n\n\nfor i in range (0, len(inFile)):\n line = inFile[i].split('\\t')\n motifPair = [line[0], line[1]]\n motifPair.sort()\n line[0],line[1] = motifPair[0],motifPair[1]\n inFile[i] = '\\t'.join(line)\n \n \noutFile = open(outFile, 'w')\noutFile.writelines(inFile)\noutFile.close()\n ","sub_path":"gusPyCode/ModuleDiscovery/orderMotifPairs.py","file_name":"orderMotifPairs.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"407594313","text":"# Copyright 2014 Huawei Technologies Co. Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n__author__ = \"Grace Yu (grace.yu@huawei.com)\"\n\n\"\"\"Module to get configs from provider and isntallers and update\n them to provider and installers.\n\"\"\"\nfrom compass.deployment.installers.installer import OSInstaller\nfrom compass.deployment.installers.installer import PKInstaller\nfrom compass.deployment.utils import constants as const\nfrom compass.utils import util\n\n\nimport logging\n\n\nclass DeployManager(object):\n \"\"\"Deploy manager module.\"\"\"\n def __init__(self, adapter_info, cluster_info, hosts_info):\n \"\"\"Init deploy manager.\"\"\"\n self.os_installer = None\n self.pk_installer = None\n\n # Get OS installer\n os_installer_name = adapter_info[const.OS_INSTALLER][const.NAME]\n self.os_installer = DeployManager._get_installer(OSInstaller,\n os_installer_name,\n adapter_info,\n cluster_info,\n hosts_info)\n\n # Get package installer\n pk_info = adapter_info.setdefault(const.PK_INSTALLER, {})\n if pk_info:\n pk_installer_name = pk_info[const.NAME]\n self.pk_installer = DeployManager._get_installer(PKInstaller,\n pk_installer_name,\n adapter_info,\n cluster_info,\n hosts_info)\n\n @staticmethod\n def _get_installer(installer_type, name, adapter_info, cluster_info,\n hosts_info):\n \"\"\"Get installer instance.\"\"\"\n callback = getattr(installer_type, 'get_installer')\n installer = callback(name, adapter_info, cluster_info, hosts_info)\n\n return installer\n\n def deploy(self):\n \"\"\"Deploy the cluster.\"\"\"\n deployed_config = self.deploy_os()\n package_deployed_config = self.deploy_target_system()\n\n util.merge_dict(deployed_config, package_deployed_config)\n\n return deployed_config\n\n def check_cluster_health(self, callback_url):\n logging.info(\"DeployManager check_cluster_health...........\")\n self.pk_installer.check_cluster_health(callback_url)\n\n def clean_progress(self):\n \"\"\"Clean previous installation log and progress.\"\"\"\n self.clean_os_installtion_progress()\n self.clean_package_installation_progress()\n\n def clean_os_installtion_progress(self):\n # OS installer cleans previous installing progress.\n if self.os_installer:\n self.os_installer.clean_progress()\n\n def clean_package_installation_progress(self):\n # Package installer cleans previous installing progress.\n if self.pk_installer:\n self.pk_installer.clean_progress()\n\n def prepare_for_deploy(self):\n self.clean_progress()\n\n def deploy_os(self):\n \"\"\"Deploy OS to hosts which need to in the cluster.\n\n Return OS deployed config.\n \"\"\"\n if not self.os_installer:\n return {}\n\n pk_installer_config = {}\n if self.pk_installer:\n # generate target system config which will be installed by OS\n # installer right after OS installation is completed.\n pk_installer_config = self.pk_installer.generate_installer_config()\n logging.debug('[DeployManager]package installer config is %s',\n pk_installer_config)\n\n # Send package installer config info to OS installer.\n self.os_installer.set_package_installer_config(pk_installer_config)\n\n # start to deploy OS\n return self.os_installer.deploy()\n\n def deploy_target_system(self):\n \"\"\"Deploy target system to all hosts in the cluster.\n\n Return package deployed config.\n \"\"\"\n if not self.pk_installer:\n return {}\n\n return self.pk_installer.deploy()\n\n def redeploy_os(self):\n \"\"\"Redeploy OS for this cluster without changing configurations.\"\"\"\n if not self.os_installer:\n logging.info(\"Redeploy_os: No OS installer found!\")\n return\n\n self.os_installer.redeploy()\n logging.info(\"Start to redeploy OS for cluster.\")\n\n def redeploy_target_system(self):\n \"\"\"Redeploy target system for the cluster without changing config.\"\"\"\n if not self.pk_installer:\n logging.info(\"Redeploy_target_system: No installer found!\")\n return\n\n self.pk_installer.deploy()\n logging.info(\"Start to redeploy target system.\")\n\n def redeploy(self):\n \"\"\"Redeploy the cluster without changing configurations.\"\"\"\n self.redeploy_os()\n self.redeploy_target_system()\n\n def remove_hosts(self, package_only=False, delete_cluster=False):\n \"\"\"Remove hosts from both OS and/or package installlers server side.\"\"\"\n if self.os_installer and not package_only:\n self.os_installer.delete_hosts()\n\n if self.pk_installer:\n self.pk_installer.delete_hosts(delete_cluster=delete_cluster)\n\n def os_installed(self):\n if self.os_installer:\n self.os_installer.ready()\n if self.pk_installer:\n self.pk_installer.os_ready()\n\n def cluster_os_installed(self):\n if self.os_installer:\n self.os_installer.cluster_ready()\n if self.pk_installer:\n self.pk_installer.cluster_os_ready()\n\n def package_installed(self):\n if self.pk_installer:\n self.pk_installer.ready()\n\n def cluster_installed(self):\n if self.pk_installer:\n self.pk_installer.cluster_ready()\n\n\nclass Patcher(DeployManager):\n \"\"\"Patcher Module.\"\"\"\n def __init__(self, adapter_info, cluster_info, hosts_info, cluster_hosts):\n self.pk_installer = None\n self.cluster_info = cluster_info\n registered_roles = cluster_info['flavor']['roles']\n\n pk_info = adapter_info.setdefault(const.PK_INSTALLER, {})\n if pk_info:\n pk_installer_name = pk_info[const.NAME]\n self.pk_installer = Patcher._get_installer(PKInstaller,\n pk_installer_name,\n adapter_info,\n cluster_info,\n hosts_info)\n\n patched_role_mapping = {}\n for role in registered_roles:\n patched_role_mapping[role] = []\n for host in cluster_hosts:\n if len(host['patched_roles']) == 0:\n continue\n for role in host['patched_roles']:\n patched_role_mapping[role['name']].append(host)\n self.patched_role_mapping = patched_role_mapping\n\n def patch(self):\n patched_config = self.pk_installer.patch(self.patched_role_mapping)\n\n return patched_config\n\n\nclass PowerManager(object):\n \"\"\"Manage host to power on, power off, and reset.\"\"\"\n\n def __init__(self, adapter_info, cluster_info, hosts_info):\n os_installer_name = adapter_info[const.OS_INSTALLER][const.NAME]\n self.os_installer = DeployManager._get_installer(OSInstaller,\n os_installer_name,\n adapter_info,\n cluster_info,\n hosts_info)\n\n def poweron(self):\n if not self.os_installer:\n logging.info(\"No OS installer found, cannot power on machine!\")\n return\n self.os_installer.poweron()\n\n def poweroff(self):\n if not self.os_installer:\n logging.info(\"No OS installer found, cannot power on machine!\")\n return\n self.os_installer.poweroff()\n\n def reset(self):\n if not self.os_installer:\n logging.info(\"No OS installer found, cannot power on machine!\")\n return\n self.os_installer.reset()\n","sub_path":"compass/deployment/deploy_manager.py","file_name":"deploy_manager.py","file_ext":"py","file_size_in_byte":8826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"5333585","text":"import os\r\nimport h5py as h5\r\nimport numpy as np\r\nfrom sklearn.model_selection import train_test_split\r\n\r\ndir_emoji = './app_data/tweets_emojis'\r\ndir_emoji2 = './app_data/tweets_emojis_processed'\r\ndir_labels = './app_data/tweets_emojis_labels'\r\ndir_workspace = './app_data/model_workspace'\r\nh5_path = dir_workspace + '/dataset.hdf5'\r\n\r\nquery_list = [ \r\n \"Affirmative Action\", \"DACA immigration\" , \r\n \"Assisted Suicide\", \"Capital punishment\", \r\n \"labor unions\", \"vaccines\", \"concealed weapons\", \r\n \"self-driving cars\",\"Artificial intelligence\", \r\n \"Donald Trump\",\"Planned Parenthood\", \"Social Security\", \"NRA\", \r\n \"Fracking\", \"Nuclear Energy\", \"NSA Surveillance\", \"Military Spending\", \r\n \"Foreign Aid\", \"Dakota Access Pipeline\", \"Oil Drilling\", \"Paris Climate Agreement\", \r\n \"Trans Pacific Partnership\", \"China Tariffs\", \"Labor Unions\", \r\n \"Universal Basic Income\", \"Paid Sick Leave\", \"Safe Haven\", \"Medicaid\", \r\n \"Edward Snowden\", \"Whistleblower Protection\", \"Armed Teachers\", \"Gun Control\",\r\n \"In-State Tuition\", \"Immigration Ban\", \"Border Wall\", \"First Amendment\", \r\n \"Confederate Flag\", \"Death Penalty\", \"Religious Freedom Act\",\r\n \"Obamacare\", \"Marijuana\"\r\n ]\r\nquery_list2 = [\"brexit_tweets\", \"ferguson_tweets\", \"travel_ban_tweets\", \"trump_tweets\", \"ireland_tweets\"]\r\nquery_list.extend(query_list2)\r\n\r\n\r\n#Write train/test data/label in subgroup of hdf5 file\r\ndef write_to_h5(h5_path, X, y, test_size=0.25, shuffle=False, sub_group = None):\r\n assert(len(X) == len(y))\r\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, shuffle=shuffle)\r\n with h5.File(h5_path, \"a\") as f:\r\n dt = h5.special_dtype(vlen=bytes)\r\n f.create_dataset(sub_group + \"/X_train\", data = [n.encode(\"ascii\", \"ignore\") for n in X_train], dtype = dt)\r\n f.create_dataset(sub_group + \"/X_test\", data = [n.encode(\"ascii\", \"ignore\") for n in X_test], dtype=dt)\r\n f.create_dataset(sub_group + \"/y_train\", data = [n.encode(\"ascii\", \"ignore\") for n in y_train] , dtype=dt)\r\n f.create_dataset(sub_group + \"/y_test\", data = [n.encode(\"ascii\", \"ignore\") for n in y_test], dtype=dt)\r\n \r\n#Write to new subgroup for each query_term\r\nfor query in query_list:\r\n data_path = (dir_emoji2 + '/' + query + ' Emoji2.txt')\r\n label_path = (dir_labels + '/' + query + ' Labels.txt')\r\n if(not(os.path.exists(data_path) and os.path.exists(data_path))):\r\n continue\r\n with open(data_path, \"r\", encoding=\"utf-8\") as f:\r\n data = [x.strip() for x in f.readlines()]\r\n with open(label_path, \"r\", encoding=\"utf-8\") as f:\r\n labels = [x.strip() for x in f.readlines()]\r\n if(len(data) == len(labels)):\r\n write_to_h5(h5_path, data, labels, sub_group=query)\r\n \r\n\r\n#For all tweet data files in directory\r\n#files_found = os.listdir(input_directory)\r\n#Does any query_list \r\n#anymatch = lambda x: any([query in x for query in query_list])\r\n#files_match = filter(lambda x: any( [ query_list ]))\r\n\r\n\r\n#Experiment 1 - Separate data into topics. Train one classifier for each topic set. Test classifier on that same data set\r\n \r\n'''\r\nBrexit\r\nFerguson\r\nIreland\r\nDonald Trump\r\nTravel Ban\r\n\r\nNaive Bayes\r\nSVM\r\nLogistic Regression\r\nDeep Averaging Network\r\n'''\r\n\r\n#Experiment 2 - Combine all tweets from all topics into one set. Train one classifier over all topics. Test each classifier on data from individual topics.\r\n\r\n'''\r\nBrexit\r\nFerguson\r\nIreland\r\nDonald Trump\r\nTravel Ban\r\nCombined Test Set\r\n\r\nNaive Bayes\r\nSVM\r\nLogistic Regression\r\nDeep Averaging Network\r\n'''\r\n#Experiment 3 - Use the four classifiers trained in experiment 2. Test accuracy on topics it has never seen before (tweets with topics it wasn’t trained on)\r\n\r\n'''\r\n\r\nObamacare\r\nNet Neutrality\r\nGay Marriage\r\nAffirmative Action\r\nConcealed Weapons\r\nCombined Test Set\r\n\r\n\r\nNaive Bayes\r\nSVM\r\nLogistic Regression\r\nDeep Averaging Network\r\n'''\r\n\r\n\r\n#Experiment 4 - Retrain classifiers using a whole bunch of political topics in table A. Test overall accuracy on combined data set. \r\n\r\n'''\r\nAccuracy on Combined Tweets\r\n\r\nNaive Bayes\r\nSVM\r\nLogistic Regression\r\nDeep Averaging NN\r\n'''\r\n#Experiment 5 - Using best performing sentiment classifier from experiment 4, to predict democratic politician sentiment for various topics. \r\n#Reported sentiment numbers are in terms of the probability of the “positive” class. \r\n\r\n'''\r\nNominate Dim1\r\nNet Neutrality\r\nGay Marriage\r\nImmigration Ban\r\nObamacare\r\nBorder Wall\r\n\r\n\r\nBarack Obama\r\nElizabeth Warren\r\nHillary Clinton\r\nKamala Harris\r\nJoe Biden\r\n'''\r\n\r\n#Experiment 6 - Using best performing sentiment classifier from experiment 4, to predict republican politician sentiment for various topics. \r\n#Reported sentiments are in terms of the probability of the “positive” class. \r\n\r\n'''\r\nNominate Dim1\r\nNet Neutrality\r\nGay Marriage\r\nImmigration Ban\r\nObamacare\r\nBorder Wall\r\n\r\n\r\nMike Pence\r\nMarco Rubio\r\nBobby Jindal\r\nRand Paul\r\nPaul Ryan\r\n'''\r\n\r\n#Experiment 7 - Use sentiment classifier output as features, build political classifier as democratic or republican\r\n'''\r\nAccuracy over test politicians\r\n\r\n\r\nLogistic Regression\r\nSupport Vector Machine\r\nDecision Trees\r\nNeural Network\r\n'''\r\n\r\n#Experiment 8 - Using sentiment classifier output as features, predict the DW-Nominate score of politicians.\r\n\r\n'''\r\n\r\nAccuracy over test politicians\r\n\r\n\r\nLogistic Regression\r\nLinear Regression w/ logistic transformation\r\nGLM with logistic link function\r\nBeta Regression\r\nMultilayer Perceptron with Sigmoid Activation\r\nDecision Trees\r\n'''\r\n\r\n#Experiment 9 - Using sentiment classifier output as features, predict the DW-Nominate score of politicians.\r\n'''\r\nRBF Kernel\r\nTrigonometric Kernel\r\n3rd Degree Polynomial Basis Expansion\r\n\r\n\r\nLogistic Regression\r\nLinear Regression w/ logistic transformation\r\nGLM with logistic link function\r\nBeta Regression\r\n'''\r\n\r\n\r\n#Experiment 10 - Do not use the sentiment classifiers for various topics at all. Instead directly classify whether democratic or \r\n#republican using standard NLP techniques. Neural networks use pre-trained embeddings. Softmax layer is used at the end to predict classes. \r\n#Accuracies are reported as amount correct divided by total predictions. \r\n'''\r\nDemocrat/Republican Prediction Accuracies\r\n\r\nRecurrent Neural Network\r\nDeep Averaging Neural Network\r\nHierarchical Network\r\nNaive Bayes\r\nLogistic Regression\r\nSupport Vector Machines\r\n'''\r\n\r\n#Experiment 11 - Do not use the sentiment classifiers for various topics at all. Instead directly predict DW-Nominate scores. \r\n#Neural networks use pre-trained embeddings. Accuracy is reported as the expected value of 1 - (DW Score Prediction Error)\r\n\r\n'''\r\nDW-Nominate Accuracy\r\n\r\nRecurrent Neural Network\r\nDeep Averaging Neural Network\r\nHierarchical Network\r\nNaive Bayes\r\nLogistic Regression\r\nSupport Vector Machines\r\n'''\r\n","sub_path":"p4_split_data.py","file_name":"p4_split_data.py","file_ext":"py","file_size_in_byte":6820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"620491854","text":"#!venv/bin/python\n# coding: utf-8\nimport sys\nimport argparse\n\nimport base\nimport backends\nimport actions\n\n\ndef main(args=None):\n parser = argparse.ArgumentParser(description=u\"web watcher\")\n\n choices = ['all']\n choices.extend(base.BACKENDS.all_names())\n parser.add_argument(\n 'selected_backends', nargs='*', default='all',\n help=u'backends using for', choices=choices)\n\n parser.add_argument(\n '--output_method', default='JustPrint',\n choices=actions.actions.__ALL__,\n help=u'specify output method')\n\n args = parser.parse_args(args)\n\n if args.selected_backends == 'all':\n backends = base.BACKENDS.all()\n else:\n backends = base.BACKENDS.filter(args.selected_backends)\n\n getattr(actions, args.output_method)(backends)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"654037361","text":"from django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.shortcuts import render, redirect, get_object_or_404\n\nfrom .models import Road, Image, Issue, IssueDetail\n\n# Create your views here.\ndef index(request):\n if request.user.is_authenticated:\n return redirect('home:dashboard')\n return render(request, 'home/index.html')\n\n@login_required\ndef dashboard(request):\n if request.user.role == 'min':\n state = request.GET.get('state', None)\n district = request.GET.get('district', None)\n block = request.GET.get('block', None)\n\n roads = Road.objects.all().order_by('-last_modified')\n states = roads.values_list('state', flat=True).distinct().order_by('state')\n\n if state and district and block:\n roads = roads.filter(state=state)\n districts = roads.values_list('district', flat=True).distinct().order_by('district')\n roads = roads.filter(district=district)\n blocks = roads.values_list('block', flat=True).distinct().order_by('block')\n roads = roads.filter(block=block)\n if roads.exists():\n context = {\n 'states': states,\n 'districts': districts,\n 'blocks': blocks,\n 'roads': roads,\n\n 'selected_state': state,\n 'selected_district': district,\n 'selected_block': block,\n }\n return render(request, 'home/dashboard.html', context)\n else:\n return redirect('home:dashboard')\n\n context = {\n 'states': states,\n }\n return render(request, 'home/dashboard.html', context)\n else:\n roads = request.user.assigned_roads.all()\n context = {\n 'roads': roads,\n }\n return render(request, 'home/dashboard.html', context)\n \n\n@login_required\ndef road_details(request, slug):\n if request.user.role == 'min':\n road = get_object_or_404(Road, slug=slug)\n else:\n road = get_object_or_404(Road, slug=slug, assigned_to=request.user)\n context = {\n 'road': road,\n }\n return render(request, 'home/road_details.html', context)\n\ndef ajax_state_changed(request):\n state = request.GET.get('state', None)\n data = {}\n\n if state:\n roads = Road.objects.filter(state=state)\n districts = roads.values_list('district', flat=True).distinct().order_by('district')\n\n for district in districts:\n data[district] = district\n\n return JsonResponse(data)\n\ndef ajax_district_changed(request):\n state = request.GET.get('state', None)\n district = request.GET.get('district', None)\n data = {}\n\n if state and district:\n roads = Road.objects.filter(state=state, district=district)\n blocks = roads.values_list('block', flat=True).distinct().order_by('block')\n\n for block in blocks:\n data[block] = block\n\n return JsonResponse(data)","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"434338467","text":"import time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as exp\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.common.exceptions import TimeoutException\n\ndriver = webdriver.Firefox(executable_path='C:\\\\Users\\\\Braian\\\\.wdm\\\\drivers\\\\geckodriver\\\\win64\\\\v0.28.0\\\\geckodriver.exe')\n\ndriver.get('https://www.morele.net/kategoria/laptopy-31/')\ndriver.maximize_window()\ntemp = driver.find_elements_by_class_name('cat-list-products')[0].find_element_by_class_name('pushAddToBasketData')\ntime.sleep(5)\ntemp.click()\ntry:\n temp = WebDriverWait(driver, 5).until(exp.element_to_be_clickable((By.CLASS_NAME, 'js_no-warrant-btn_desktop')))\n temp.click()\n time.sleep(5)\n temp = WebDriverWait(driver, 5).until(exp.element_to_be_clickable((By.CLASS_NAME, 'show-basket')))\n temp.click()\n temp = WebDriverWait(driver, 5).until(exp.element_to_be_clickable((By.CLASS_NAME, 'confirm-button')))\nexcept TimeoutException:\n driver.get('https://www.morele.net/koszyk/')\ntime.sleep(5)\ntemp = driver.find_element_by_xpath('/html/body/div[3]/main/div/div[3]/div/div[1]/div/div[2]/div/ul/li[2]')\ndriver.execute_script(\"arguments[0].click();\", temp)\ntime.sleep(5)\ntemp = driver.find_element_by_xpath('/html/body/div[8]/div/div/div[2]/div[3]/button[2]')\ndriver.execute_script(\"arguments[0].click();\", temp)\n","sub_path":"morele/secondScenario/firefox.py","file_name":"firefox.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"304913815","text":"\n\nfrom xai.brain.wordbase.nouns._novice import _NOVICE\n\n#calss header\nclass _NOVICES(_NOVICE, ):\n\tdef __init__(self,): \n\t\t_NOVICE.__init__(self)\n\t\tself.name = \"NOVICES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"novice\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_novices.py","file_name":"_novices.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"443334416","text":"#!/usr/bin/python\n\nimport sys\nimport random\nimport pygame\n\n\n# Global constants\nCELL_SIZE = 40\nX_CELLS = 24\nY_CELLS = 16\n\nWIDTH = X_CELLS * CELL_SIZE\nHEIGHT = Y_CELLS * CELL_SIZE\nSIZE = WIDTH, HEIGHT\nFPS = 60\n\nUP = (0, -1)\nDOWN = (0, 1)\nLEFT = (-1, 0)\nRIGHT = (1, 0)\n\nBLACK = (0, 0, 0)\nGRAY = (100, 100, 100)\nWHITE = (255, 255, 255)\n\n\n# Game constants\nSNAKE_START_SPEED = 3\n\nSCREEN_BG_COLOR = (247, 208, 203)\nSCREEN_BORDER_COLOR = (183, 110, 121)\nSNAKE_COLOR = (170, 170, 170)\nSNAKE_BORDER_COLOR = (97, 101, 110)\n\n\n# Objects classes\n\nclass BaseObject(object):\n count = 0\n\n def __init__(self, coord=None, size=None):\n self.__class__.count += 1\n\n self.color = tuple(random.randint(0, 255) for i in range(3))\n self.size = size if size else random.randint(20, 100)\n self.x = coord[0] if coord else random.random() * (WIDTH - self.size) + self.size/2\n self.y = coord[1] if coord else random.random() * (HEIGHT - self.size) + self.size/2\n\n def draw(self, screen):\n pygame.draw.rect(\n screen,\n self.color,\n (self.x - self.size/2, self.y - self.size/2, self.size, self.size)\n )\n\n\nclass MovableObject(BaseObject):\n speed = 1\n\n def __init__(self, coord=None, size=None):\n super(MovableObject, self).__init__(coord, size)\n\n self.vector = (\n random.random() * random.choice((-1, 1)),\n random.random() * random.choice((-1, 1))\n )\n\n def move(self):\n self.x += self.vector[0] * self.speed\n self.y += self.vector[1] * self.speed\n\n\nclass SnakeSegment(MovableObject):\n speed = CELL_SIZE\n\n def __init__(self, coord=None):\n super(SnakeSegment, self).__init__()\n\n self.size = CELL_SIZE\n self.x = coord[0] if coord else (X_CELLS + (X_CELLS+1)%2) * CELL_SIZE/2\n self.y = coord[1] if coord else (Y_CELLS + (Y_CELLS+1)%2) * CELL_SIZE/2\n self.vector = (0, 0)\n self.color = SNAKE_COLOR\n self.border_color = SNAKE_BORDER_COLOR\n self.border_width = int(round(0.05 * self.size))\n\n def draw(self, screen):\n super(SnakeSegment, self).draw(screen)\n pygame.draw.rect(\n screen,\n self.border_color,\n (self.x - self.size/2, self.y - self.size/2, self.size-1, self.size-1),\n self.border_width\n )\n\n\nclass Snake(object):\n min_size = 3\n\n def __init__(self):\n self.stack = [SnakeSegment() for i in range(self.min_size)]\n self.head = self.stack[-1]\n self.speed = SNAKE_START_SPEED\n self.vector = UP\n\n self.build_snake()\n\n def build_snake(self):\n l = len(self.stack)\n for i, segment in enumerate(self.stack):\n segment.vector = (-self.vector[0], -self.vector[1])\n for j in range(l-i):\n segment.move()\n\n def grow(self):\n tail = self.stack[0]\n new_tail = SnakeSegment((tail.x, tail.y))\n new_tail.vector = (-tail.vector[0], -tail.vector[1])\n new_tail.move()\n self.stack.insert(0, new_tail)\n\n def move(self):\n new_head = self.stack.pop(0)\n new_head.x, new_head.y = self.head.x, self.head.y\n new_head.vector = self.vector\n self.head = new_head\n self.stack.append(new_head)\n self.head.move()\n\n def draw(self, screen):\n for segment in self.stack:\n segment.draw(screen)\n\n\nclass Apple(BaseObject):\n\n def __init__(self, coord=None):\n super(Apple, self).__init__()\n \n self.size = CELL_SIZE - 2\n self.x = coord[0] if coord else random.randint(0, X_CELLS-1)*CELL_SIZE + CELL_SIZE/2\n self.y = coord[1] if coord else random.randint(0, Y_CELLS-1)*CELL_SIZE + CELL_SIZE/2\n\n def reinit(self):\n self.__init__()\n\n\n# Game class\n\nclass GameSnake(object):\n RUNNING, FINISHED, PAUSED = (1, 0, -1)\n BORDER = True\n\n def __init__(self):\n self.screen = pygame.display.set_mode(SIZE)\n self.clock = pygame.time.Clock()\n\n self.game_state = self.RUNNING\n self.game_time_ms = 0\n self.score = 0\n self.snake_speed = SNAKE_START_SPEED\n self.next_step_ms = 0\n\n self.snake = Snake()\n self.apple = Apple()\n self.init_apple()\n\n def init_apple(self):\n while self._is_apple_under_snake():\n self.apple.reinit()\n\n def _is_apple_under_snake(self):\n for segment in self.snake.stack:\n if segment.x == self.apple.x and segment.y == self.apple.y:\n return True\n return False\n\n def speed_up(self):\n self.snake_speed += 0.1\n\n def check_snake_move(self):\n head = self.snake.head\n\n if head.x == self.apple.x and head.y == self.apple.y:\n self.score += 1\n self.snake.grow()\n self.init_apple()\n self.speed_up()\n return True\n\n for segment in self.snake.stack[:-1]:\n if segment.x == head.x and segment.y == head.y:\n return False\n\n if self.BORDER:\n if head.x < 0 or head.x > WIDTH:\n return False\n if head.y < 0 or head.y > HEIGHT:\n return False\n else:\n self._pass_through_border()\n return True\n\n def _pass_through_border(self):\n head = self.snake.head\n if head.x < head.size/2:\n head.x = WIDTH - head.size/2\n if head.x > WIDTH - head.size/2:\n head.x = head.size/2\n if head.y < head.size/2:\n head.y = HEIGHT - head.size/2\n if head.y > HEIGHT - head.size/2:\n head.y = head.size/2\n\n def check_events(self):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_r:\n self.__init__()\n if event.key == pygame.K_p:\n self.game_state *= -1\n if event.key == pygame.K_q:\n pygame.quit()\n sys.exit()\n\n head = self.snake.head\n if event.key == pygame.K_UP and head.vector != DOWN:\n self.snake.vector = UP\n # self.next_step_ms = 1000.0 / self.snake_speed\n if event.key == pygame.K_DOWN and head.vector != UP:\n self.snake.vector = DOWN\n # self.next_step_ms = 1000.0 / self.snake_speed\n if event.key == pygame.K_LEFT and head.vector != RIGHT:\n self.snake.vector = LEFT\n # self.next_step_ms = 1000.0 / self.snake_speed\n if event.key == pygame.K_RIGHT and head.vector != LEFT:\n self.snake.vector = RIGHT\n # self.next_step_ms = 1000.0 / self.snake_speed\n\n def update_screen(self):\n if self.game_state is self.RUNNING:\n tick_ms = self.clock.get_time()\n self.next_step_ms += tick_ms\n self.game_time_ms += tick_ms\n\n self.screen.fill(SCREEN_BG_COLOR)\n self._draw_grid()\n self._draw_border()\n\n allow_move = True\n if self.next_step_ms > 1000.0 / self.snake_speed:\n self.next_step_ms = 0\n self.snake.move()\n allow_move = self.check_snake_move()\n\n if allow_move:\n self.apple.draw(self.screen)\n self.snake.draw(self.screen)\n self.render_text()\n else:\n self.game_state = self.FINISHED\n pygame.time.wait(500)\n self.show_final_banner()\n\n def run(self):\n while True:\n self.check_events()\n self.update_screen()\n self.clock.tick(FPS)\n pygame.display.flip()\n\n def _draw_grid(self):\n for gx in range(0, WIDTH + CELL_SIZE, CELL_SIZE):\n pygame.draw.line(self.screen, WHITE, (gx - 1, -1), (gx - 1, HEIGHT - 1), 2)\n for gy in range(0, HEIGHT + CELL_SIZE, CELL_SIZE):\n pygame.draw.line(self.screen, WHITE, (-1, gy - 1), (WIDTH - 1, gy - 1), 2)\n\n def _draw_border(self):\n if self.BORDER:\n sb_color = SCREEN_BORDER_COLOR\n x_br, y_br = WIDTH-2, HEIGHT-2\n pygame.draw.line(self.screen, sb_color, (0, 0), (0, y_br), 2)\n pygame.draw.line(self.screen, sb_color, (x_br, 0), (x_br, y_br), 2)\n pygame.draw.line(self.screen, sb_color, (0, 0), (x_br, 0), 2)\n pygame.draw.line(self.screen, sb_color, (0, y_br), (x_br, y_br), 2)\n\n def render_text(self):\n game_time_s = int(round(self.game_time_ms/1000.0))\n label_timer = LABEL_FONT.render(\"Time: %i\" % game_time_s, True, BLACK)\n lh = label_timer.get_height()\n self.screen.blit(label_timer, (CELL_SIZE/2, (CELL_SIZE-lh)/2))\n\n label_score = LABEL_FONT.render(\"Score: %i\" % self.score, True, BLACK)\n self.screen.blit(label_score, (CELL_SIZE/2, (3*CELL_SIZE-lh)/2))\n\n label_hotkeys = LABEL_FONT.render(\"restart/pause/quit: r/p/q\", True, GRAY)\n self.screen.blit(label_hotkeys, (CELL_SIZE/2, HEIGHT-(CELL_SIZE+lh)/2))\n\n def show_final_banner(self):\n self.screen.fill(SCREEN_BG_COLOR)\n banner = BANNER_FONT.render(\"Game Over\", True, BLACK)\n w, h = banner.get_size()\n self.screen.blit(banner, ((WIDTH-w)/2, (HEIGHT-h)/2-110))\n\n game_time_s = int(round(self.game_time_ms/1000.0))\n time_banner = BANNER_FONT.render(\"Time: %i sec\" % game_time_s, True, BLACK)\n w, h = time_banner.get_size()\n self.screen.blit(time_banner, ((WIDTH-w)/2, (HEIGHT-h)/2-10))\n\n score_banner = BANNER_FONT.render(\"Score: %i\" % self.score, True, BLACK)\n self.screen.blit(score_banner, ((WIDTH-w)/2, (HEIGHT-h)/2+40))\n\n\nif __name__ == \"__main__\":\n # pygame initialization\n pygame.init()\n pygame.display.set_caption(\"Snake\")\n\n # resources initialization\n LABEL_FONT = pygame.font.SysFont(\"monospace\", size=CELL_SIZE//2)\n BANNER_FONT = pygame.font.SysFont(\"monospace\", size=CELL_SIZE, bold=True)\n\n # game initialization\n game = GameSnake()\n game.run()\n","sub_path":"pygame/snake/snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":10251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"58767229","text":"#!/usr/bin/env python\nimport wget\nimport os\nimport urllib\nimport GPS_tools\n#####################################################################################\n#GPS_filedownloader.py\n#This code will download any RINEX, nav or UNR\n#time series file requested\n#Written by Brendan Crowell, University of Washington\n#Last edited January 10, 2019\n#Broadcast navigation messages are only downloaded from CDDIS\n#RINEX files will try to download from UNAVCO, then CWU, then CDDIS, then SOPAC\n#Time Series files will only download from UNR, cartesian positions\n#VARIABLES\n#year - 4 digit string of year\n#doy - 3 digit string of day of year\n#site - 4 digit string of site id\n#####################################################################################\n#This subroutine downloads the broadcast navigation message for a given day from CDDIS\ndef getbcorbit(year, doy):\n if not os.path.exists('nav'): #if nav folder doesn't exist, make it\n os.makedirs('nav')\n fname = 'nav/brdc' + doy + '0.' + year[-2:] + 'n.Z'\n fname2 = 'nav/brdc' + doy + '0.' + year[-2:] + 'n'\n if (os.path.isfile(fname2) == True):\n print ('Navigation file ' + fname2 + ' already exists')\n else:\n url = 'ftp://cddis.nasa.gov/gnss/data/daily/' + year + '/' + doy + '/' + year[-2:] + 'n/brdc' + doy + '0.' + year[-2:] + 'n.Z'\n wget.download(url, out='nav/')\n os.system('gunzip' + ' ' + fname)\n\n#This subroutine downloads the ultra rapid sp3 file for a given day from CDDIS\ndef getsp3file(year, doy):\n if not os.path.exists('nav'): #if nav folder doesn't exist, make it\n os.makedirs('nav')\n [gpsweek,gpsdow]=PPPML_tools.gpsweekdow(int(year),int(doy))\n week = str(int(gpsweek))\n dow = str(int(gpsdow))\n fname = 'nav/igu' + week + dow + '_12.sp3.Z'\n fname2 = 'nav/igu' + week + dow + '_12.sp3'\n if (os.path.isfile(fname2) == True):\n print ('Navigation file ' + fname2 + ' already exists')\n else:\n\n url = 'ftp://cddis.gsfc.nasa.gov/gnss/products/' + week + '/igu' + week + dow + '_12.sp3.Z'\n print(url)\n wget.download(url, out='nav/')\n os.system('gunzip' + ' ' + fname)\n\n#This subroutine will download RINEX files given the station, year and day of year. \ndef getrinex(site, year, doy):\n if not os.path.exists('rinex'): #if rinex folder doesn't exist, make it\n os.makedirs('rinex')\n fnameZ = 'rinex/' + site + doy + '0.' + year[-2:] + 'd.Z'\n fnamebz2 = 'rinex/' + site + doy + '0.' + year[-2:] + 'd.bz2'\n fnamed = 'rinex/' + site + doy + '0.' + year[-2:] + 'd'\n fnameo = 'rinex/' + site + doy + '0.' + year[-2:] + 'o'\n if (os.path.isfile(fnameo) == True): \n print ('Rinex file ' + fnameo + ' already exists')\n else:\n try:\n url = 'ftp://data-out.unavco.org/pub/rinex/obs/' + year + '/' + doy + '/' + site + doy + '0.' + year[-2:] + 'd.Z'\n print ('Attempting to download ' + fnamed + ' from UNAVCO')\n wget.download(url, out='rinex/')\n os.system('gunzip' + ' ' + fnameZ)\n os.system('./crx2rnx' + ' ' + fnamed)\n os.remove(fnamed)\n except Exception:\n print ('File not at UNAVCO, checking CWU')\n try:\n url = 'https://www.geodesy.cwu.edu/data_ftp_pub/data/' + year+ '/' + doy + '/30sec/' + site + doy + '0.' + year[-2:] + 'd.bz2'\n print ('Attempting to download ' + fnamed + ' from CWU')\n wget.download(url, out='rinex/')\n os.system('bzip2 -d' + ' ' + fnamebz2)\n os.system('./crx2rnx' + ' ' + fnamed)\n os.remove(fnamed)\n except Exception:\n print ('File not at CWU, checking CDDIS')\n try:\n url = 'ftp://cddis.nasa.gov/gnss/data/daily/' + year+ '/' + doy + '/' + year[-2:] + 'd/' + site + doy + '0.' + year[-2:] + 'd.Z'\n print ('Attempting to download ' + fnamed + ' from CDDIS')\n wget.download(url, out='rinex/')\n os.system('gunzip' + ' ' + fnameZ)\n os.system('./crx2rnx' + ' ' + fnamed)\n os.remove(fnamed)\n except Exception:\n print ('File not at CDDIS, checking SOPAC')\n try:\n url = 'ftp://garner.ucsd.edu/pub/rinex/' + year+ '/' + doy + '/' + site + doy + '0.' + year[-2:] + 'd.Z'\n print ('Attempting to download ' + fnamed + ' from SOPAC')\n wget.download(url, out='rinex/')\n os.system('gunzip' + ' ' + fnameZ)\n os.system('./crx2rnx' + ' ' + fnamed)\n os.remove(fnamed)\n except Exception:\n print ('File not found at SOPAC, moving onto next station')\n\n#This subroutine will download highrate (1-Hz) RINEX files\ndef getrinexhr(site, year, doy):\n if not os.path.exists('rinex_hr'): #if rinex highrate folder doesn't exist, make it\n os.makedirs('rinex_hr')\n fnameZ = 'rinex/' + site + doy + '0.' + year[-2:] + 'd.Z'\n fnamebz2 = 'rinex/' + site + doy + 'i.' + year[-2:] + 'd.bz2'\n fnamecwuo = 'rinex/' + site + doy + 'i.' + year[-2:] + 'o'\n fnamecwud = 'rinex/' + site + doy + 'i.' + year[-2:] + 'd'\n fnamed = 'rinex/' + site + doy + '0.' + year[-2:] + 'd'\n fnameo = 'rinex/' + site + doy + '0.' + year[-2:] + 'o'\n if (os.path.isfile(fnameo) == True): \n print ('Rinex file ' + fnameo + ' already exists')\n else:\n try:\n url = 'ftp://garner.ucsd.edu/pub/rinex_highrate/' + year+ '/' + doy + '/' + site + doy + '0.' + year[-2:] + 'd.Z'\n print (url)\n print ('Attempting to download ' + fnamed + ' from SOPAC')\n wget.download(url, out='rinex/')\n os.system('gunzip' + ' ' + fnameZ)\n os.system('./crx2rnx' + ' ' + fnamed)\n os.remove(fnamed)\n except Exception:\n print ('File not at SOPAC, checking UNAVCO')\n try:\n url = 'ftp://data-out.unavco.org/pub/highrate/5-Hz/rinex/' + year + '/' + doy + '/' + site + '/' + site + doy + '0.' + year[-2:] + 'd.Z'\n print ('Attempting to download ' + fnamed + ' from UNAVCO')\n wget.download(url, out='rinex/')\n os.system('gunzip' + ' ' + fnameZ)\n os.system('./crx2rnx' + ' ' + fnamed)\n os.remove(fnamed)\n except Exception:\n print ('File not at UNAVCO checking CWU')\n try:\n url = 'https://www.geodesy.cwu.edu/data_ftp_pub/data/' + year+ '/' + doy + '/01sec/' + site + doy + 'i.' + year[-2:] + 'd.bz2'\n print ('Attempting to download ' + fnamed + ' from CWU')\n wget.download(url, out='rinex/')\n os.system('bzip2 -d' + ' ' + fnamebz2)\n os.system('./crx2rnx' + ' ' + fnamecwud)\n os.rename(fnamecwuo, fnameo)\n os.remove(fnamecwud)\n except Exception:\n print ('File not at CWU, moving on')\n\n\n#This subroutine downloads the cartesian time series in IGS08 from the UNR database to use for a priori locations\ndef gettseries(site):\n if not os.path.exists('tseries'): #if tseries folder doesn't exist, make it\n os.makedirs('tseries')\n siteid = site.upper()\n fname = 'tseries/' + siteid + '.IGS08.txyz2'\n if (os.path.isfile(fname) == True): \n print ('Timeseries file ' + fname + ' already exists')\n else:\n url = 'http://geodesy.unr.edu/gps_timeseries/txyz/IGS08/' + siteid + '.IGS08.txyz2'\n wget.download(url, out='tseries/')\n\n\n\n\n#Examples\n##getrinexhr('lwck','2018','002')\n##getrinex('p494','2018','002')\n##getbcorbit('2018','002')\n##gettseries('p494')\n##\n#getsp3file('2018','002')\n\n\n","sub_path":"GPS_filedownloader.py","file_name":"GPS_filedownloader.py","file_ext":"py","file_size_in_byte":7912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"13121271","text":"#!/usr/bin/env python3\n\n\"\"\"Contains a cog with commands that quote people.\"\"\"\n\nimport random\n\nimport discord\nfrom discord.ext import commands\n\nimport utils.helpers\n\nclass Quoting:\n \"\"\"Commands that quote people.\"\"\"\n\n @commands.command()\n @commands.cooldown(6, 12, commands.BucketType.channel)\n async def quote(self, ctx, *, user:str):\n \"\"\"Quote a user.\n \n * user - The user you wish to quote.\n \"\"\"\n user = await utils.helpers.member_by_substring(ctx, user)\n quotes = []\n async for message in ctx.channel.history():\n if message.author.id == user.id:\n quotes.append(message)\n if len(quotes) == 0:\n await ctx.send(\"Could not quote that user.\")\n else:\n message = random.choice(quotes)\n quote = f\"**{user.name} said:**\\n{message.content}\"\n await ctx.send(quote)\n\n @commands.command()\n @commands.cooldown(6, 12, commands.BucketType.channel)\n async def didsay(self, ctx, user:str, *, quote=\"\"):\n \"\"\"Checks if a user said a particular phrase.\n \n * user - A member to mention.\n * phrase - A phrase to check against. Leave blank to show all instances.\n \"\"\"\n user = await utils.helpers.member_by_substring(ctx, user)\n paginator = commands.Paginator(max_size=625)\n length = 0\n async for message in ctx.channel.history():\n if message.author.id == user.id and quote.lower() in message.content.lower():\n content = message.content.replace(\"```\", \"\")\n paginator.add_line(f\"{message.created_at.ctime()}: {content}\")\n length += 1\n if len(paginator.pages) == 0:\n if len(quote) == 0:\n quote = \"anything\"\n await ctx.send((f\"{user.name} did not say **{quote}** in the last {length} messages. \"\n \"Or it was deleted.\"))\n else:\n message = await ctx.send(paginator.pages[0])\n await ctx.bot.add_pager(message, paginator.pages, author_id=ctx.author.id)\n\ndef setup(bot):\n \"\"\"Setup function for Quoting.\"\"\"\n bot.add_cog(Quoting())\n","sub_path":"cogs/core/quote.py","file_name":"quote.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"230525733","text":"from __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport json\n\nimport flask\n\nfrom git_code_debt.server import logic\nfrom git_code_debt.server import metric_config\nfrom git_code_debt.server.presentation.commit_delta import CommitDeltaPresenter\nfrom git_code_debt.server.presentation.delta import DeltaPresenter\nfrom git_code_debt.server.render_mako import render_template\n\n\nchanges = flask.Blueprint('changes', __name__)\n\n\n@changes.route('/changes///')\ndef show(metric_name, start_timestamp, end_timestamp):\n start_timestamp = int(start_timestamp)\n end_timestamp = int(end_timestamp)\n\n metric_changes = sorted(logic.get_major_changes_for_metric(\n flask.g.db, start_timestamp, end_timestamp, metric_name,\n ))\n metric_changes = [\n (\n datetime.datetime.fromtimestamp(timestamp).strftime(\n '%Y-%m-%d %H:%M:%S',\n ),\n sha,\n CommitDeltaPresenter.from_data(\n metric_name,\n DeltaPresenter('javascript:;', value),\n )\n )\n for timestamp, sha, value in metric_changes\n ]\n\n override_classname = (\n 'color-override'\n if metric_name in metric_config.color_overrides\n else ''\n )\n\n rendered_template = render_template(\n 'changes.mako',\n changes=metric_changes,\n override_classname=override_classname,\n )\n\n return json.dumps({'body': rendered_template})\n","sub_path":"git_code_debt/server/servlets/changes.py","file_name":"changes.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"185258806","text":"import random\nfrom operator import itemgetter\nCNF=[]\nwith open(\"cnf.txt\") as f:\n var,clause=[int(x) for x in next(f).split()]\n for line in f:\n cnf=[]\n #print(line)\n for i in line.split():\n if(int(i)!=0):\n cnf.append(int(i))\n \n CNF.append(cnf)\n #remove last two empty array\n #print(CNF) \n\nclause_number=clause\nprint(\"Clause: \",clause_number)\nliteral_number=3\nvariable_number=var\nprint(\"Variable : \",variable_number)\npop_size=10\n\n\ndef generatePopulation():\n population=[]\n \n for eachChromosome in range(pop_size):\n chromosome=[]\n for gene in range(variable_number):\n chromosome.append(random.randint(0,1))\n population.append(chromosome)\n return population\n \n \n \ndef fitness(chromosome):\n OR=0\n AND=0 #true-clause number\n print(chromosome)\n for i in range(0,clause_number):\n for j in range(0,literal_number):\n if(CNF[i][j]>0):\n OR|= chromosome[CNF[i][j]-1]\n elif(CNF[i][j]<0):\n #print(\"out of range: \",i,j,CNF,abs(CNF[i][j])-1)\n OR |= (chromosome[abs(CNF[i][j])-1]+1)%2\n AND+=OR \n OR=0\n return AND\n\ndef rankChromosome(population):\n fitnesses=[]\n for chromosome in population:\n fit=fitness(chromosome)\n fitnesses.append(fit)\n print(chromosome)\n print(fit)\n pop_fitness_tuple=zip(population,fitnesses)\n sortedPop=sorted(pop_fitness_tuple,key= itemgetter(-1),reverse=True)\n #print(sortedPop)\n return sortedPop\n\ndef tournamentSelection(population):\n tournament_size=5\n best=None\n for i in range(tournament_size):\n chromosome=population[random.randint(0,pop_size-1)]\n if best is None or fitness(chromosome)>fitness(best):\n best=chromosome\n return best\n\ndef onePointCrossover(parent_a,parent_b):\n c=random.randint(0,variable_number)\n c=int(variable_number/2)\n #print(c)\n for i in range(c,variable_number):\n temp=parent_a[i]\n parent_a[i]=parent_b[i]\n parent_b[i]=temp\n return (parent_a,parent_b)\n\ndef twoPointCrossover(parent_a,parent_b):\n c=random.randint(0,variable_number)\n d=random.randint(0,variable_number)\n if c>d:\n temp=c\n c=d\n d=temp\n #print(c,d)\n for i in range(c,d):\n temp=parent_a[i]\n parent_a[i]=parent_b[i]\n parent_b[i]=temp\n return (parent_a,parent_b)\n\ndef bit_flip_mutation(parent):\n probability=1/variable_number\n for i in range(variable_number):\n if probability >= random.random():\n parent[i]=(parent[i]+1)%2\n #print(parent[i])\n return parent\n\ndef main():\n newPopSize=0;\n max_generation=1000\n generation=0\n population=generatePopulation()\n #rankedPop=rankChromosome(population)\n best=None\n #best_fit=rankedPop[0][1]\n## population=generatePopulation()\n## print(population)\n## rankedPop=rankChromosome(population)\n## print(rankedPop)\n \n while generation<=max_generation:\n for chromosome in population:\n if best is None or fitness(chromosome)>fitness(best):\n best=chromosome\n #print(\"generation\",generation)\n## rankedPop=rankChromosome(population)\n## best=rankedPop[0][0]\n## best_fit=rankedPop[0][1]\n print(\"best: \",best)\n best_fit=fitness(best)\n if best_fit==clause_number:\n return best,generation\n newPop=[]\n \n while len(newPop)<=pop_size:\n parent_a=tournamentSelection(population)\n parent_b=tournamentSelection(population)\n if(random.random()>=0.5):\n child_a,child_b=onePointCrossover(parent_a,parent_b)\n else:\n child_a,child_b=twoPointCrossover(parent_a,parent_b)\n child_a=bit_flip_mutation(child_a)\n child_b=bit_flip_mutation(child_b)\n newPop.append(child_a)\n newPop.append(child_b)\n population.extend(newPop)\n \n rankedPop=rankChromosome(population)\n population=rankedPop[:pop_size] #elitism\n generation+=1\n return best,max_generation\nif __name__==\"__main__\":\n best,generation=main()\n best_fit=fitness(best)\n print(\"Result Clause: \",best)\n print(\"Best fit: \", best_fit)\n print(\"Generation: \",generation)\n## best=None\n## population=generatePopulation()\n## for chromosome in population:\n## if best is None or fitness(chromosome)>fitness(best):\n## best=chromosome\n## best_fit=fitness(best)\n## if best_fit==clause_number:\n## return best\n## newPop=[]\n## while len(newPop)<=pop_size:\n## \n## print\n## print(\"best: \",best)\n## print(fitness(best))\n## print(population)\n## rankedPop=rankChromosome(population)\n## print(rankedPop)\n## \n#population=generatePopulation()\n#rankedPop=rankChromosome(population)\n#parent_a=tournamentSelection(population)\n#print(parent_a)\n#parent_b=tournamentSelection(population)\n#print(parent_b)\n#tup=onePointCrossover(parent_a,parent_b)\n#print(tup)\n#mutate=bit_flip_mutation(parent_a)\n#print(rankedPop[0][1])\n#print(tournamentSelection(population))\n \n","sub_path":"genetic algorithm.py","file_name":"genetic algorithm.py","file_ext":"py","file_size_in_byte":5252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"1253162","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport h5py\nimport radiative_transfer as rt\n\nf = h5py.File(\"LWIR_TUD_MAKO.h5\", \"r\")\nprint(list(f.keys()))\n\nX = f[\"X\"][...].astype(np.float32)\ntau = f[\"tau\"][...].astype(np.float32)\nLa = f[\"La\"][...].astype(np.float32)\nLd = f[\"Ld\"][...].astype(np.float32)\nTs = f[\"Ts\"][...].astype(np.float32)\n\nf.close()\n\nf = h5py.File(\"LWIR_Emissivity_DB_MAKO.h5\")\nprint(list(f.keys()))\n\nemis = f[\"emis\"][...].astype(np.float32)\n\nf.close()\n\ndT = np.arange(-10, 10.5, 0.5).astype(np.float32)\nL = rt.compute_LWIR_apparent_radiance(X, emis, Ts, tau, La, Ld, dT)\nT = Ts[:, np.newaxis] + dT[np.newaxis,:]\n\n# Save as HDF5 file\nhf = h5py.File('LWIR_HSI_MAKO.h5', 'w')\nd = hf.create_dataset('X', data=X)\nd.attrs['units'] = 'cm^{-1}'\nd.attrs['name'] = 'Wavenumbers'\nd.attrs['info'] = 'Spectral axis for L, emis, tau, La, Ld'\nd.attrs['label'] = r'$\\tilde{\\nu} \\,\\, \\left[\\si{cm^{-1}} \\right]$'\n\nd = hf.create_dataset('L', data=L)\nd.attrs['units'] = 'µW/(cm^2 sr cm^{-1})'\nd.attrs['name'] = 'Apparent Spectral Radiance'\nd.attrs['info'] = 'For spaceborn nadir-viewing sensor. Shape is (nX, nE, nA, nT) where nX is # spectral channels, nE is # materials, nA is # atmospheres, nT is # surface temperatures'\nd.attrs['label'] = r'$L(\\tilde{\\nu})\\,\\,\\left[\\si{\\micro W/(cm^2.sr.cm^{-1})}\\right]$'\n\nd = hf.create_dataset('emis', data=emis)\nd.attrs['units'] = 'none'\nd.attrs['name'] = 'Emissivity'\nd.attrs['info'] = 'Effective, Hemispherically-averaged Emissivity'\nd.attrs['label'] = r'$\\varepsilon(\\tilde{\\nu})$'\n\nd = hf.create_dataset('T', data=T)\nd.attrs['units'] = 'K'\nd.attrs['name'] = 'Surface temperature'\nd.attrs['info'] = ''\nd.attrs['label'] = r'$T_s \\,\\, \\left[ \\si{K} \\right]$'\n\nd = hf.create_dataset('tau', data=tau)\nd.attrs['units'] = 'none'\nd.attrs['name'] = 'Transmissivity'\nd.attrs['info'] = 'For nadir-viewing path'\nd.attrs['label'] = r'$\\tau(\\tilde{\\nu})$'\n\nd = hf.create_dataset('La', data=La)\nd.attrs['units'] = 'µW/(cm^2 sr cm^{-1})'\nd.attrs['name'] = 'Atmospheric Path Spectral Radiance'\nd.attrs['info'] = 'For nadir-viewing path, earth-to-space'\nd.attrs['label'] = r'$L_a(\\tilde{\\nu})\\,\\,\\left[\\si{\\micro W/(cm^2.sr.cm^{-1})}\\right]$'\n\nd = hf.create_dataset('Ld', data=Ld)\nd.attrs['units'] = 'µW/(cm^2 sr cm^{-1})'\nd.attrs['name'] = 'Atmospheric Downwelling Spectral Radiance'\nd.attrs['info'] = 'Hemispherically-averaged, space-to-earth'\nd.attrs['label'] = r'$L_d(\\tilde{\\nu})\\,\\,\\left[\\si{\\micro W/(cm^2.sr.cm^{-1})}\\right]$'\n\nhf.close()\n\n# Reshape and split into training, testing, and validation subsets\nnX, nE, nA, nT = L.shape\nidx=[]\nfor ixE in range(nE):\n for ixA in range(nA):\n for ixT in range(nT):\n idx.append([ixE, ixA, ixT])\nidx = np.asarray(idx)\nL = np.reshape(L, (L.shape[0], np.prod(L.shape[1:])))\nL = L.T\nemis = emis.T\ntau = tau.T\nLa = La.T\nLd = Ld.T\n\nixP = np.random.permutation(np.arange(L.shape[0]))\nL = L[ixP,:]\nidx = idx[ixP,:]\nixE = idx[:, 0]\nixA = idx[:, 1]\nixT = idx[:, 2]\n\n# Split into training, testing, and validation\nf_tr = 0.75\n\ndef gen_indices(f, N):\n ix_tr = np.round(np.linspace(0, N-1, np.int(f * N))).astype(np.int)\n ix_diff = np.sort(np.asarray(list(set.difference(set(np.arange(N)), set(ix_tr)))))\n ix_te = ix_diff[0::2]\n ix_va = ix_diff[1::2]\n return ix_tr, ix_te, ix_va\n\nixTrain, ixTest, ixValidate = gen_indices(f_tr,L.shape[0])\n\nnp.savez('LWIR_HSI_MAKO.npz', X=X, L=L, ixE=ixE, ixA=ixA, ixT=ixT, emis=emis, T=T, tau=tau, La=La, Ld=Ld,\n ixTrain=ixTrain, ixTest=ixTest, ixValidate=ixValidate)\n\nfor _ in range(5):\n ii = np.random.randint(0,L.shape[0])\n ixE = idx[ii, 0]\n ixA = idx[ii, 1]\n ixT = idx[ii, 2]\n mdl = tau[ixA,:] * (emis[ixE,:] * rt.planckian(X, T[ixA,ixT]) + (1 - emis[ixE,:]) * Ld[ixA,:]) + La[ixA,:]\n plt.plot(X, L[ii,:])\n plt.plot(X,mdl,'.')\n plt.show()\n","sub_path":"Compute_LWIR_Apparent_Radiance.py","file_name":"Compute_LWIR_Apparent_Radiance.py","file_ext":"py","file_size_in_byte":3809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"420120004","text":"from rest_framework.routers import Route, SimpleRouter\n\n\nclass UWSRouter(SimpleRouter):\n routes = [\n Route(\n url=r'^{prefix}$',\n mapping={'get': 'list', 'post': 'create'},\n name='{basename}-list',\n initkwargs={'suffix': 'List'}\n ),\n Route(\n url=r'^{prefix}/{lookup}$',\n mapping={'get': 'retrieve', 'post': 'update', 'delete': 'destroy'},\n name='{basename}-detail',\n initkwargs={'suffix': 'Detail'}\n ),\n Route(\n url=r'^{prefix}/{lookup}/results$',\n mapping={'get': 'get_results'},\n name='{basename}-results',\n initkwargs={'suffix': 'Results'}\n ),\n Route(\n url=r'^{prefix}/{lookup}/parameters$',\n mapping={'get': 'get_parameters'},\n name='{basename}-parameters',\n initkwargs={'suffix': 'Parameters'}\n ),\n Route(\n url=r'^{prefix}/{lookup}/destruction$',\n mapping={'get': 'get_destruction', 'post': 'post_destruction'},\n name='{basename}-destruction',\n initkwargs={'suffix': 'Destruction'}\n ),\n Route(\n url=r'^{prefix}/{lookup}/executionduration$',\n mapping={'get': 'get_executionduration', 'post': 'post_executionduration'},\n name='{basename}-executionduration',\n initkwargs={'suffix': 'Executionduration'}\n ),\n Route(\n url=r'^{prefix}/{lookup}/phase$',\n mapping={'get': 'get_phase', 'post': 'post_phase'},\n name='{basename}-phase',\n initkwargs={'suffix': 'Phase'}\n ),\n Route(\n url=r'^{prefix}/{lookup}/error$',\n mapping={'get': 'get_error'},\n name='{basename}-error',\n initkwargs={'suffix': 'Error'}\n ),\n Route(\n url=r'^{prefix}/{lookup}/quote$',\n mapping={'get': 'get_quote'},\n name='{basename}-quote',\n initkwargs={'suffix': 'Quote'}\n ),\n Route(\n url=r'^{prefix}/{lookup}/owner$',\n mapping={'get': 'get_owner'},\n name='{basename}-owner',\n initkwargs={'suffix': 'Owner'}\n ),\n ]\n","sub_path":"daiquiri/uws/routers.py","file_name":"routers.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"366358933","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 18 12:43:50 2019\n\n@author: s1881079\n\"\"\"\n\nimport ImgPro as ip\nimport MtchBD as mb\n\nfrom bdComps import SuspObj\n\nfrom simg_process import *\n\nimport os\n\n\ndef downloadImgOnly(url_txt,img_folder,key_txt):\n '''\n download images only and preview with online api to see how the api work on them\n \n '''\n key = ip.gen_process.getExtInfo(key_txt)\n \n if os.path.exists(img_folder,) is False:\n os.makedirs(img_folder)\n \n lst_gsv = ip.downloadGSV(url_txt,img_folder,key)\n \n img_csv = 'test_camloc'\n ip.gen_process.writeObjInfoCsv(lst_gsv,img_folder,img_csv)\n \n \nif __name__ == '__main__':\n url_txt = '../../data/gge_url/test_ggeurl.txt'\n img_folder = '../../intm_output/preview_imgs/'\n key_txt = '../../../locked/GSVdl_key.txt'\n \n downloadImgOnly(url_txt,img_folder,key_txt)\n ","sub_path":"workspace_merge/src/SemSticker/testGround.py","file_name":"testGround.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"499702313","text":"#!/usr/bin/env python\n\nfrom setuptools import setup, find_packages\nimport os, versioneer, subprocess, re\n\n__author__ = \"Lukas Elflein, Johannes Hörmann\"\n__copyright__ = \"Copyright 2019, IMTEK Simulation, University of Freiburg\"\n__maintainer__ = \"Johannes Hörmann\"\n__email__ = \"johannes.hoermann@imtek.uni-freiburg.de\"\n__date__ = \"Oct 25, 2019\"\n\nmodule_dir = os.path.dirname(os.path.abspath(__file__))\n\nif __name__ == \"__main__\":\n setup(\n name='continuous2discrete',\n version=versioneer.get_version(),\n cmdclass=versioneer.get_cmdclass(),\n description='Sample continuous (concentration) distributions and generate xyz file format coordiante sets',\n long_description=open(os.path.join(module_dir, 'README.md')).read(),\n url='https://github.com/lukaselflein/generate_distributed_structure',\n author='Lukas Elflein, Johannes Hörmann',\n author_email='johannes.hoermann@imtek.uni-freiburg.de',\n license='MIT',\n packages=find_packages(),\n package_data={'': ['ChangeLog.md']},\n python_requires='>3.6.3',\n zip_safe=False,\n install_requires=[\n 'ase>=3.19.0b1',\n 'matplotlib>=3.0.3',\n 'numpy >= 1.16.2',\n 'pandas>=0.24.2',\n 'pytest>=5.2.2',\n 'pytest-datadir>=1.3.1',\n 'scipy>=1.2.1',\n 'six>=1.12.0'],\n entry_points={\n 'console_scripts': [\n 'c2d = continuous2discrete.continuous2discrete:main',\n 'pnp = continuous2discrete.poisson_nernst_planck_distribution:main'\n ],\n }\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"605041932","text":"# Fernando Herrera\n# Last Edit: Week 2(?) of MSEIP '18\n# This program reads from an iris plant data set that was provided to us and \n# attempts to accurately identify the three plant species. No cross val.\nimport csv \nimport random\nimport math\n\ninput_Count = 4\nhidden1_Count = 10\noutput_Count = 3\nlearningRate = 0.05\nbeta = .95\n\n# Randomize weights. inner value is the columns. Outer value is the rows.\ninput_hidden1_LayerWeight = ( [[random.uniform(-1,1) for x in range(input_Count)] \nfor y in range(hidden1_Count)] )\nhidden1_output_LayerWeight = ( [[random.uniform(-1,1) for x in range(hidden1_Count)] \nfor y in range(output_Count)] )\n\ninput_hidden1_ThetaWeight = [random.uniform(-1,1) for x in range(hidden1_Count)]\nhidden1_output_ThetaWeight = [random.uniform(-1,1) for x in range(output_Count)]\n\ninput_hidden1_WeightChange = ( [[0 for x in range(input_Count)] for \ny in range(hidden1_Count)] )\nhidden1_output_WeightChange = ( [[0 for x in range(hidden1_Count)] for \ny in range(output_Count)] )\n\nhidden_Output = [0 for x in range(hidden1_Count)]\nfinal_Output = [0 for x in range(output_Count)]\n\n#Start of Neural Network\n\ninput = []\n\nwith open('iris.csv', newline='') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',')\n\t\n for row in csvreader:\n inputrow = []\n for counter in range(len(row)):\n inputrow.append(float(row[counter]))\n # Store all values in input.\n input.append(inputrow)\n\nfor e in range(100):\n performance = 0\n for r in range(len(input)):\n #print(\"Row \", r)\n\n # FEED FORWARD START\n #--------------------\n\n # Input layer -> Hidden Layer\n # j is row.\n for j in range(hidden1_Count):\n hidden_Output[j] = 0\n # k is column.\n for k in range(input_Count):\n # 150[r]x4[c] * 10[r]x4[c]\n hidden_Output[j] += input[r][k] * input_hidden1_LayerWeight[j][k]\n hidden_Output[j] = hidden_Output[j] - input_hidden1_ThetaWeight[j]\n # Perform activation function with X values.\n hidden_Output[j] = 1 / (1 + math.exp(-hidden_Output[j]))\n # hidden_Output now holds the Y.\n\n # Hidden layer -> Output layer\n for j in range(output_Count):\n # Reset.\n final_Output[j] = 0\n for k in range(hidden1_Count):\n final_Output[j] += (hidden_Output[k] * \n hidden1_output_LayerWeight[j][k] )\n final_Output[j] = final_Output[j] - hidden1_output_ThetaWeight[j]\n # Perform activation function with X values.\n final_Output[j] = 1 / (1 + math.exp(-final_Output[j]))\n\n # BACK PROPOGATION START\n #-----------------------\n\n # Temporary arrays for storing deltas.\n deltaOutputLayer = [0 for x in range(output_Count)]\n deltaHiddenLayer = [0 for x in range(hidden1_Count)]\n\n # Adjust values in output layer.\n for j in range(output_Count):\n # Calculate new deltas(3) from output layer.\n deltaOutputLayer[j] = ( final_Output[j] * (1 - final_Output[j]) * \n (input[r][4+j] - final_Output[j]) )\n # Adjust theta weight.\n for k in range(hidden1_Count):\n # Calculate new weights(10) from output layer.\n hidden1_output_LayerWeight[j][k] = ( \n hidden1_output_LayerWeight[j][k] + (learningRate * \n deltaOutputLayer[j] * hidden_Output[k]) + \n (beta * hidden1_output_WeightChange[j][k]) )\n\n hidden1_output_WeightChange[j][k] = (\n (learningRate * deltaOutputLayer[j] * hidden_Output[k]) )\n # Calculate new theta(3) from output layer.\n hidden1_output_ThetaWeight[j] = ( hidden1_output_ThetaWeight[j] + \n (learningRate * -1 * deltaOutputLayer[j]) )\n\n # Adjust values in hidden layer.\n for j in range(hidden1_Count):\n sum = 0\n for i in range(output_Count):\n # [column][row]\n # [0][0], [1][0], [2],[0]\n sum += deltaOutputLayer[i] * hidden1_output_LayerWeight[i][j]\n deltaHiddenLayer[j] = hidden_Output[j] * (1 - hidden_Output[j]) * sum\n for k in range(input_Count):\n input_hidden1_LayerWeight[j][k] = ( \n input_hidden1_LayerWeight[j][k] + \n (learningRate * deltaHiddenLayer[j] * input[r][k]) +\n (beta * input_hidden1_WeightChange[j][k]) )\n\n input_hidden1_WeightChange[j][k] = (\n (learningRate * deltaHiddenLayer[j] * input[r][k]) )\n input_hidden1_ThetaWeight[j] = ( input_hidden1_ThetaWeight[j] + \n (learningRate * -1 * deltaHiddenLayer[j]) )\n\n for j in range(3):\n performance += abs(input[r][4+j] - final_Output[j])\n\n #row END\n performance = performance / 150\n print(\"Loss is: \", performance)\n#epoch END\n\nfor r in range(len(input)):\n for j in range(hidden1_Count):\n # Reset.\n hidden_Output[j] = 0\n # k is column.\n for k in range(input_Count):\n # 150[r]x4[c] * 10[r]x4[c]\n hidden_Output[j] += input[r][k] * input_hidden1_LayerWeight[j][k]\n hidden_Output[j] = hidden_Output[j] - input_hidden1_ThetaWeight[j]\n # Perform activation function with X values.\n hidden_Output[j] = 1 / (1 + math.exp(-hidden_Output[j]))\n # hidden_Output now holds the Y.\n #print(hidden_Output[j]\n\n # Hidden layer -> Output layer\n for j in range(output_Count):\n # Reset.\n final_Output[j] = 0\n for k in range(hidden1_Count):\n final_Output[j] += hidden_Output[k] * hidden1_output_LayerWeight[j][k]\n final_Output[j] = final_Output[j] - hidden1_output_ThetaWeight[j]\n # Perform activation function with X values.\n final_Output[j] = 1 / (1 + math.exp(-final_Output[j]))\n\n print(\"Prediction: \", final_Output[j], \"Label: \", input[r][j+4])\n print(\" \")\n\n","sub_path":"plant_nn_v1.py","file_name":"plant_nn_v1.py","file_ext":"py","file_size_in_byte":6184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"24603848","text":"\n\n\n\nimport smtplib\n\ns=smtplib.SMTP('smtp.gmail.com','587')\ns.starttls()\nreceiver='harshitarkumbar22@gmail.com'\nsender='gaganmsdhonikumar@gmail.com'\nmsg=\"hii\"\ns.login(sender,'89456123')\ns.sendmail(sender,receiver,msg)\nprint(\"msg sent successfully\")\ns.quit()","sub_path":"gml.py","file_name":"gml.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"291231792","text":"import glob\nimport time\nimport pickle\nimport os\nimport numpy as np\nfrom sklearn.svm import LinearSVC\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom . import lesson_functions\n\n\ndef read_images():\n \"\"\"\n Read the training images \n Returns the images splited between cars and not cars\n\n This test images are downloaded from the GTI vehicle image database\n http://www.gti.ssr.upm.es/data/Vehicle_database.html\n \"\"\"\n # Read in car and non-car images\n images = glob.glob('images/**/**/*.png')\n cars = []\n notcars = []\n for image in images:\n if 'non-vehicles' in image:\n notcars.append(image)\n else:\n cars.append(image)\n\n print(\"Cars found: \", len(cars))\n print(\"Not cars found: \", len(notcars))\n print(\"Total: \", len(cars) + len(notcars))\n\n return cars, notcars\n\n\ndef training():\n \"\"\"\n Training Linear SVC\n Returns the trained Linear SVC and a trained StandardScaler \n \"\"\"\n\n dir = os.path.dirname(__file__)\n trainingFilePath = dir + \"/../training.p\"\n\n if os.path.isfile(trainingFilePath) is False:\n t = time.time()\n\n cars, notcars = read_images()\n\n print(\"Extracting features...\")\n car_features = lesson_functions.extract_features(cars)\n notcar_features = lesson_functions.extract_features(notcars)\n\n\n print(\"Getting vectors...\")\n # Create an array stack of feature vectors\n X = np.vstack((car_features, notcar_features)).astype(np.float64)\n # Fit a per-column scaler\n X_scaler = StandardScaler().fit(X)\n # Apply the scaler to X\n X_scaled = X_scaler.transform(X)\n\n # Define the labels vector\n y = np.hstack((np.ones(len(car_features)), np.zeros(len(notcar_features))))\n\n\n # Split up data into randomized training and test sets\n print(\"Splitting...\")\n rand_state = np.random.randint(0, 100)\n X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)\n print(len(y_train), \"training images\")\n print(len(y_test), \"testing images\")\n\n\n # Use a linear SVC \n print(\"Training...\")\n svc = LinearSVC()\n svc.fit(X_train, y_train)\n\n # Get the score of the SVC\n test_accuracy = round(svc.score(X_test, y_test), 4)\n print('Test Accuracy of SVC = ', test_accuracy)\n\n t2 = time.time()\n print(round(t2-t, 2), 'Seconds to train')\n\n # save values to transform 3D to 2D\n data = {'svc': svc, 'X_scaler': X_scaler}\n\n # save file\n with open(trainingFilePath, 'wb') as f:\n pickle.dump(data, file=f)\n\n else:\n trainingData = pickle.load( open(trainingFilePath, \"rb\") )\n svc = trainingData['svc']\n X_scaler = trainingData['X_scaler']\n\n\n return svc, X_scaler\n","sub_path":"src/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"37944838","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nSCORR - Salvus Correlation\n\n:copyright:\n Korbinian Sager (korbinian_sager@brown.edu), 2021\n:license:\n MIT License\n\"\"\"\nfrom pathlib import Path\n\nimport numpy as np\nimport pytest\nfrom scorr.extensions import scorr_extensions\nfrom scorr.noise_source.noise_source_setup import setup_noise_source\nfrom scorr.tasks import preparation\n\n# specify where the tests should run\nDIR_PROJECT = Path.home() / \"scorr_inversion_synthetic\"\n\n# specify mesh\nmesh_name = \"Globe3D_prem_iso_one_crust_100.e\"\n# mesh_name = \"Globe3D_prem_iso_one_crust_100_with_s20.e\"\n\n# load and edit configuration\nconfig = scorr_extensions.load_configuration(DIR_PROJECT / \"config\" / \"scorr.json\", type=\"scorr\")\n\nconfig[\"working_dir_local\"] = DIR_PROJECT\nconfig[\"simulation\"][\"reference_stations\"] = config[\"working_dir_local\"] / \"reference_stations.json\"\nconfig[\"simulation\"][\"mesh\"] = config[\"working_dir_local\"] / mesh_name\n\nconfig[\"simulation\"][\"green_starttime\"] = -400.0\nconfig[\"simulation\"][\"corr_max_lag\"] = 21600.0\nconfig[\"simulation\"][\"corr_max_lag_causal\"] = 7200\nconfig[\"simulation\"][\"dt\"] = 0.5\n\nconfig[\"simulation\"][\"kernel-fields\"] = \"VP,VS,RHO\"\nconfig[\"simulation\"][\"anisotropy\"] = False\nconfig[\"simulation\"][\"attenuation\"] = True\nconfig[\"simulation\"][\"sampling_rate_boundary\"] = 20\nconfig[\"simulation\"][\"sampling_rate_volume\"] = 20\nconfig[\"noise_source\"][\"filename\"] = config[\"working_dir_local\"] / \"noise_source\" / \"noise_source.h5\"\n# config[\"noise_source\"][\"filename\"] = config[\"working_dir_local\"] / \"noise_source\" / \"noise_source_obs.h5\"\n\nconfig[\"simulation\"][\"sideset\"] = \"r1\"\nconfig[\"simulation\"][\"green_component\"] = 0\nconfig[\"simulation\"][\"green_amplitude\"] = -1.0e10\nconfig[\"noise_source\"][\"component_dist_source\"] = 0\nconfig[\"noise_source\"][\"component_wavefield\"] = 0\nconfig[\"simulation\"][\"recording\"] = \"u_ELASTIC\"\nconfig[\"noise_source\"][\"filter_spec\"] = [0.0033333, 0.01]\nconfig[\"simulation\"][\"absorbing\"][\"boundaries\"] = None\nconfig[\"simulation\"][\"absorbing\"][\"axis-aligned\"] = False\nconfig[\"simulation\"][\"spherical\"] = True\n\n# loc_sources = [[0.0, 0.0, 100.0]]\n# loc_receivers = [[[0.0, 0.0, 100.0], [0.0, 10.0, 100.0], [0.0, 20.0, 100.0],\n# [0.0, 30.0, 100.0], [0.0, 40.0, 100.0], [0.0, 50.0, 100.0],\n# [0.0, 60.0, 100.0], [0.0, 70.0, 100.0], [0.0, 80.0, 100.0],\n# [0.0, 90.0, 100.0], [0.0, 100.0, 100.0], [0.0, 110.0, 100.0],\n# [0.0, 121.0, 100.0], [0.0, 130.0, 100.0], [0.0, 140.0, 100.0],\n# [0.0, 150.0, 100.0], [0.0, 160.0, 100.0], [0.0, 170.0, 100.0],\n# [0.0, 180.0, 100.0], [0.0, -10.0, 100.0], [0.0, -20.0, 100.0],\n# [0.0, -29.0, 100.0], [0.0, -40.0, 100.0], [0.0, -50.0, 100.0],\n# [0.0, -60.0, 100.0], [0.0, -70.0, 100.0], [0.0, -79.0, 100.0],\n# [0.0, -90.0, 100.0], [0.0, -100.0, 100.0], [0.0, -110.0, 100.0],\n# [0.0, -120.0, 100.0], [0.0, -130.0, 100.0], [0.0, -141.0, 100.0],\n# [0.0, -150.0, 100.0], [0.0, -160.0, 100.0], [0.0, -170.0, 100.0],\n# [10.0, 0.0, 100.0], [20.0, 0.0, 100.0],\n# [30.0, 0.0, 100.0], [40.0, 0.0, 100.0], [50.0, 0.0, 100.0],\n# [60.0, 0.0, 100.0], [70.0, 0.0, 100.0], [80.0, 0.0, 100.0],\n# [90.0, 0.0, 100.0], [-10.0, 0.0, 100.0], [-20.0, 0.0, 100.0],\n# [-30.0, 0.0, 100.0], [-40.0, 0.0, 100.0], [-50.0, 0.0, 100.0],\n# [-60.0, 0.0, 100.0], [-70.0, 0.0, 100.0], [-80.0, 0.0, 100.0],\n# [-90.0, 0.0, 100.0],\n# [45.0, 45.0, 100.0], [45.0, -45.0, 100.0], [-45.0, -45.0, 100.0], [-45.0, 45.0, 100.0],\n# [33.051491, -114.827057, 100.0]\n# ]]\n\nloc_receivers = []\n# n_sources = 1\nn_sources = 15\nwith open(DIR_PROJECT / \"_sts-1_filtered.txt\", mode=\"r\") as fh:\n for i_src in range(n_sources):\n loc_receivers.append([])\n for line in fh:\n station = [float(item) for item in line.strip().split(\",\")]\n loc_receivers[i_src].append(station)\n fh.seek(0)\n\nloc_sources = []\n# source_list = [3]\nsource_list = [3, 4, 12, 14, 15, 19, 22, 30, 37, 42, 46, 51, 114, 115, 120]\nassert len(source_list) == n_sources\nfor i_src in range(n_sources):\n loc_sources.append(loc_receivers[i_src].pop(source_list[i_src]))\n\n# some safety measures, stf generation is not yet general enough\nnt_corr = abs(config[\"simulation\"][\"corr_max_lag\"]) / config[\"simulation\"][\"dt\"]\nnt_green = abs(config[\"simulation\"][\"green_starttime\"]) / config[\"simulation\"][\"dt\"]\n\nassert np.mod(nt_corr, 1) == pytest.approx(0, abs=1.0e-8)\nassert np.mod(nt_green, 1) == pytest.approx(0, abs=1.0e-8)\nassert np.mod(nt_corr, config[\"simulation\"][\"sampling_rate_boundary\"]) == pytest.approx(0, abs=1.0e-8)\nassert np.mod(nt_green, config[\"simulation\"][\"sampling_rate_boundary\"]) == pytest.approx(0, abs=1.0e-8)\n\n# save configuration\nscorr_extensions.save_configuration(filename=config[\"working_dir_local\"] / \"config\" / \"scorr.json\",\n config=config, type=\"scorr\")\n\n#####################################\n########## NOISE SOURCE ##########\n#####################################\n\n# save load source configuration\nconfig_noise_source = scorr_extensions.load_configuration(filename=config[\"working_dir_local\"] / \"config\" /\n \"noise_source.json\", type=\"noise_source\")\nconfig_noise_source[\"type\"] = \"homogeneous\"\n# config_noise_source[\"type\"] = \"gaussian\"\n# config_noise_source[\"spectrum\"][\"f_peak\"] = 0.005\n\n# save noise source configuration\nscorr_extensions.save_configuration(\n filename=config[\"working_dir_local\"] / \"config\" / \"noise_source.json\", config=config_noise_source,\n type=\"noise_source\")\n\n#####################################\n########## SITE ##########\n#####################################\n\n# load site configuration\n# site = scorr_extensions.load_configuration(DIR_PROJECT / \"config\" / \"site.json\", type=\"site\")\n\n# change site configuration\nsite = {\"site\": \"daint\",\n \"ranks_salvus\": 192,\n \"ranks_scorr\": 24,\n \"ping_interval_in_seconds\": 60,\n \"wall_time_in_seconds_salvus\": 18000,\n \"wall_time_in_seconds_scorr\": 7200}\n\n# save site configuration\nscorr_extensions.save_configuration(filename=config[\"working_dir_local\"] / \"config\" / \"site.json\",\n config=site, type=\"site\")\n\n#####################################\n########## MEASUREMENT ##########\n#####################################\n\n# load measurement configuration\nconfig_measurement = scorr_extensions.load_configuration(DIR_PROJECT / \"config\" / \"measurement.json\",\n type=\"measurement\")\n\n# change measurement configuration\n# config_measurement[\"type\"] = \"waveform_differences\"\n# config_measurement[\"type\"] = \"log_amplitude_ratio\"\nconfig_measurement[\"type\"] = \"cc_time_shift\"\nconfig_measurement[\"component_recording\"] = 2\nconfig_measurement[\"pick_window\"] = True\nconfig_measurement[\"pick_manual\"] = False\nconfig_measurement[\"min_period_in_s\"] = 200.0\nconfig_measurement[\"scale\"] = 1e10\nconfig_measurement[\"snr\"] = None\nconfig_measurement[\"surface_wave_velocity_in_mps\"] = 3700.0\n# config_measurement[\"surface_wave_velocity_in_mps\"] = 4000.0\nconfig_measurement[\"window_halfwidth_in_sec\"] = 600.0\nconfig_measurement[\"number_of_stacked_windows_min\"] = None\nconfig_measurement[\"station_list\"] = None\n\n# save measurement configuration\nscorr_extensions.save_configuration(filename=config[\"working_dir_local\"] / \"config\" / \"measurement.json\",\n config=config_measurement, type=\"measurement\")\n\n#####################################\n######## RUN PREPARATION ########\n#####################################\n\nsetup_noise_source(config=config, site=site, config_noise_source=config_noise_source)\npreparation.prepare_source_and_receiver(config=config, identifier_prefix=\"syn\",\n loc_sources=loc_sources, loc_receivers=loc_receivers)\n","sub_path":"scorr/cli_scripts/prepare_events_spherical_synthetic.py","file_name":"prepare_events_spherical_synthetic.py","file_ext":"py","file_size_in_byte":7763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"188259985","text":"#!/usr/bin/python3\n\nfrom nobones import population\nfrom nobones import nbmath\nfrom nobones import nbspatial\nfrom nobones import genetics\n\npop1 = population.Population()\npop2 = population.Population()\nind = population.Individual()\n\npop1.generateIndividual(0,0,1,'r','','A',0,70,300,'(0, 255, 0)')\npop2.generateIndividual(0,0,2,'r','','A',0,70,300,'(0, 0, 255)')\n\nfor x in range(0,20):\n\tpop1.generateIndividual(0,0,1,'r','','',0,70,300,'(0, 255, 0)')\n\tpop2.generateIndividual(0,0,2,'r','','',0,70,300,'(0, 0, 255)')\n\nspace = nbspatial.Space()\nlife = genetics.Genetics()\n\nspace.loadWorld('testworld.jpg', 7100, 4000)\n\ndef getColor(color):\n\tnewColor = color.replace(' ','').replace('(','').replace(')','').split(',')\n\t\n\treturn (int(newColor[0]),int(newColor[1]),int(newColor[2]))\n\t\ndef mixColor(color1, color2):\n\tnewColor1 = getColor(color1)\n\tnewColor2 = getColor(color2)\n\t\n\tR = (int(newColor1[0])+int(newColor2[0]))/2\n\tG = (int(newColor1[1])+int(newColor2[1]))/2\n\tB = (int(newColor1[2])+int(newColor2[2]))/2\n\n\treturn (int(R),int(G),int(B))\n\t\ndef getRandomInd(inds):\n\tlength = len(inds)\n\n\tif length == 1:\n\t\treturn inds[0]\n\telse:\n\t\tind = nbmath.randomBetween(0,length-1)\n\t\treturn inds[ind]\n\ndef mating(close):\n\tnewInd = population.Individual()\n\trandInd = population.Individual()\n\n\t_randInd = getRandomInd(close)\n\trandInd.loadIndividual(_randInd)\n\t\n\t_newInd = life.produceOffspring(ind.getIndividual(), randInd.getIndividual())\n\tnewInd.loadIndividual(_newInd)\n\t\n\tnewInd.misc = mixColor(ind.misc, randInd.misc)\n\t\n\tnewInd.social = ind.social\n\t\n\tind.loadIndividual(newInd.getIndividual())\n\nfor x in range(0,2000):\n\tprint(x)\n \n\tspace.copyForDrawing()\n \n\tpop1.selectAll()\n \n\twhile pop1.feedToEnd() != 'done':\n\t\tind.loadIndividual(pop1.selectedIndividual)\n\t\t\n\t\tif ind.social == 'A':\n\t\t\tmodified_ind = space.moveRandomly(pop1.selectedIndividual, 150)\t\t\n\t\t\t\n\t\t\tind.loadIndividual(modified_ind)\n\t\t\t\n\t\t\tX = ind.X\n\t\t\tY = ind.Y\n\t\t\t\n\t\t\tpop1.saveSelectedIndividual(modified_ind)\n\t\telse:\n\t\t\tmodified_ind = space.moveCloseTo(pop1.selectedIndividual, X, Y, 200)\n\t\t\tind.loadIndividual(modified_ind)\n\t\t\t\n\t\t\tpop1.saveSelectedIndividual(modified_ind)\n\t\t\t\n\t\tclose = space.individualsCloseTo(pop1.Selected + pop2.Selected, ind.X, ind.Y, 29)\n\t\t\n\t\tif close != None:\n\t\t\tmating(close)\n\t\t\t\n\t\t\tpop1.saveSelectedIndividual(ind.getIndividual())\n\t\t\n\t\tspace.markCopyAt(ind.X,ind.Y,getColor(ind.misc))\n\t\t\n\tpop2.selectAll()\n\t\t\n\twhile pop2.feedToEnd() != 'done':\n\t\tind.loadIndividual(pop2.selectedIndividual)\n\t\t\n\t\tif ind.social == 'A':\n\t\t\tmodified_ind = space.moveRandomly(pop2.selectedIndividual, 150)\t\t\n\t\t\t\n\t\t\tind.loadIndividual(modified_ind)\n\t\t\t\n\t\t\tX = ind.X\n\t\t\tY = ind.Y\n\t\t\t\n\t\t\tpop2.saveSelectedIndividual(modified_ind)\n\t\telse:\n\t\t\tmodified_ind = space.moveCloseTo(pop2.selectedIndividual, X, Y, 200)\n\t\t\tind.loadIndividual(modified_ind)\n\t\t\t\n\t\t\tpop2.saveSelectedIndividual(modified_ind)\n\n\t\tclose = space.individualsCloseTo(pop1.Selected + pop2.Selected, ind.X, ind.Y, 29)\n\t\t\n\t\tif close != None:\n\t\t\tmating(close)\n\t\t\t\n\t\t\tpop2.saveSelectedIndividual(ind.getIndividual())\n\t\t\n\t\tspace.markCopyAt(ind.X,ind.Y,getColor(ind.misc))\n\t\n\t#just for the filenames\n\tif x < 10:\n\t\tnr = '000' + str(x)\n\telif x < 100:\n\t\tnr = '00' + str(x)\n\telif x < 1000:\n\t\tnr = '0' + str(x)\n\t\t\n\tspace.saveCopy('/home/kim/test/testworld_edit' + nr + '.jpg')\n\t\nprint('finished.');\n","sub_path":"space-test (EXAMPLE).py","file_name":"space-test (EXAMPLE).py","file_ext":"py","file_size_in_byte":3306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"551825961","text":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nfrom odoo import api, fields, models\nfrom odoo.exceptions import UserError,ValidationError\nfrom odoo.tools.translate import _\n\n\nclass cls_wizarddetallespagoparcial(models.Model):\n _name = 'detalles.pago.parcial'\n \n def _default_wizard_factura(self):\n factura=self._context.get('factura',False)\n return factura\n \n invoice_id=fields.Many2one(\"account.invoice\",string=\"Factura\",default=_default_wizard_factura)\n name = fields.Char(track_visibility='onchange',required=False,string='Descripcion')\n impuestos= fields.Boolean(string='Aplica Impuestos')\n \n @api.onchange('checkall')\n def onchange_actividad(self):\n for record in self:\n for line in record.linesfactura_ids:\n line.checkproceso=record.checkall\n \n \n checkall = fields.Boolean(string='Seleccionar todos los registros a procesar',track_visibility='onchange')\n linesfactura_ids = fields.Many2many('account.invoice.line', 'wizard_detalles_pagos_parcial')\n\n\n\n\n @api.multi\n def genera_detalles_pagos_parciales(self):\n for record in self:\n totalcheck=0\n devengadofactura_id = self._context.get('active_ids', False)\n for devengado in devengadofactura_id:\n devengado_obj=record.env['account.invoice'].search([('id', '=',devengado)])\n\n\n pagoparcial={\n 'invoice_id':devengado_obj.id,\n 'name':record.name,\n 'utilizado':False,\n 'impuestos':record.impuestos,\n }\n pagoparcial_obj=record.env['pago.parcial'].with_context(check_move_validity=False).create(pagoparcial)\n\n if record.impuestos:\n \ttotalcheck=1\n for lines in record.linesfactura_ids:\n if lines.checkproceso:\n totalcheck=1\n if round(lines.importeapagar,2)<=0:\n raise ValidationError('El importe de los registros seleccionados deber ser mayor a 0')\n else:\n importeporpagar=lines.importeporpagar+lines.importeapagar \n if round(lines.totaldetalle,2)>=round(importeporpagar,2):\n lines.importeporpagar=importeporpagar\n \n #detallesmomentos_obj = self.env['account.invoice.line']\n #detallesmomentos=detallesmomentos_obj.search([('invoice_id','=',devengado),('momentogastoline_id', '=',lines.id)])\n \n detallespagoparcial={\n 'pagoparcial_id':pagoparcial_obj.id,\n 'invoiceline_id':lines.id,\n 'importeparcial':lines.importeapagar,\n }\n record.env['pago.parcial.lines'].with_context(check_move_validity=False).create(detallespagoparcial)\n else:\n raise ValidationError('Existen registros en donde el importe a pagar excede el importe total del detalle')\n lines.checkproceso=False\n lines.importeapagar=0\n pagoparcial_obj._compute_importe()\n if totalcheck==0:\n raise ValidationError('No se ha seleccionado ningun detalles')\n\n","sub_path":"extrasGDL/finanzas/wizard/wizard_pago_parcial.py","file_name":"wizard_pago_parcial.py","file_ext":"py","file_size_in_byte":3630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"392335969","text":"\n\"\"\"Sequential Neural Processes.\n\nG. Singh et al., \"Sequential Neural Processes\".\nhttp://arxiv.org/abs/1906.10264\n\"\"\"\n\nfrom typing import Tuple, Dict, Optional\n\nimport torch\nfrom torch import Tensor, nn\nfrom torch.nn import functional as F\n\nfrom .base_np import BaseNP, kl_divergence_normal, nll_normal\n\n\nclass DeterministicEncoder(nn.Module):\n \"\"\"Encoder and aggregator r = f(x, y).\n\n Args:\n x_dim (int): Dimension size of x.\n y_dim (int): Dimension size of y.\n r_dim (int): Dimension size of r (representation).\n \"\"\"\n\n def __init__(self, x_dim: int, y_dim: int, r_dim: int) -> None:\n super().__init__()\n\n self.fc = nn.Sequential(\n nn.Linear(x_dim + y_dim, 64),\n nn.ReLU(),\n nn.Linear(64, 64),\n nn.ReLU(),\n nn.Linear(64, r_dim),\n )\n\n def forward(self, x: Tensor, y: Tensor) -> Tensor:\n \"\"\"Forward method r = f(x, y).\n\n Args:\n x (torch.Tensor): x context data, size\n `(batch_size, num_context, x_dim)`.\n y (torch.Tensor): x context data, size\n `(batch_size, num_context, y_dim)`.\n\n Returns:\n r (torch.Tensor): Aggregated representation, size\n `(batch_size, r_dim)`.\n \"\"\"\n\n h = torch.cat([x, y], dim=-1)\n h = self.fc(h)\n\n # Aggregate representations for all contexts per batch and dimension.\n # (batch_size, num_context, r_dim) -> (batch_size, r_dim)\n r = h.mean(dim=1)\n\n return r\n\n\nclass StochasticEncoder(nn.Module):\n \"\"\"Stochastic encoder p(z|h, r).\n\n Args:\n h_dim (int): Dimension size of h (rnn hidden state).\n r_dim (int): Dimension size of r (representation).\n z_dim (int): Dimension size of z (stochastic latent).\n \"\"\"\n\n def __init__(self, h_dim: int, r_dim: int, z_dim: int) -> None:\n super().__init__()\n\n self.fc = nn.Sequential(\n nn.Linear(h_dim + r_dim, 64),\n nn.ReLU(),\n nn.Linear(64, 64),\n nn.ReLU(),\n nn.Linear(64, 128),\n )\n self.fc_mu = nn.Linear(128, z_dim)\n self.fc_var = nn.Linear(128, z_dim)\n\n def forward(self, h: Tensor, r: Tensor) -> Tuple[Tensor, Tensor]:\n \"\"\"Forward method p(z|h, r).\n\n Args:\n h (torch.Tensor): Hidden state, size `(batch_size, h_dim)`.\n r (torch.Tensor): Representation, size `(batch_size, r_dim)`.\n\n Returns:\n mu (torch.Tensor): Encoded aggregated mean, size\n `(batch_size, z_dim)`.\n var (torch.Tensor): Encoded aggregated variance, size\n `(batch_size, z_dim)`.\n \"\"\"\n\n h = torch.cat([h, r], dim=-1)\n s = self.fc(h)\n\n # Mean and variance of N(mu(s), var(s)^0.5)\n mu = self.fc_mu(s)\n var = F.softplus(self.fc_var(s))\n\n return mu, var\n\n\nclass Decoder(nn.Module):\n \"\"\"Decoder.\n\n Args:\n x_dim (int): Dimension size of x.\n y_dim (int): Dimension size of y.\n h_dim (int): Dimension size of h (rnn hidden state).\n z_dim (int): Dimension size of z (stochastic latent).\n \"\"\"\n\n def __init__(self, x_dim: int, y_dim: int, h_dim: int, z_dim: int) -> None:\n super().__init__()\n\n self.fc = nn.Sequential(\n nn.Linear(x_dim + h_dim + z_dim, 64),\n nn.ReLU(),\n nn.Linear(64, 64),\n nn.ReLU(),\n )\n\n self.fc_mu = nn.Linear(64, y_dim)\n self.fc_var = nn.Linear(64, y_dim)\n\n def forward(self, x: Tensor, h: Tensor, z: Tensor\n ) -> Tuple[Tensor, Tensor]:\n \"\"\"Forward method.\n\n Args:\n x (torch.Tensor): x context data, size\n `(batch_size, num_points, x_dim)`.\n h (torch.Tensor): RNN hidden state, size `(batch_size, h_dim)`.\n z (torch.Tensor): Stochastic latent, size `(batch_size, z_dim)`.\n\n Returns:\n mu (torch.Tensor): Decoded mean, size\n `(batch_size, num_points, y_dim)`.\n var (torch.Tensor): Decoded variance, size\n `(batch_size, num_points, y_dim)`.\n \"\"\"\n\n # Data size\n num_points = x.size(1)\n\n # Concat inputs\n h = h.unsqueeze(1).repeat(1, num_points, 1)\n z = z.unsqueeze(1).repeat(1, num_points, 1)\n h = torch.cat([x, h, z], dim=-1)\n\n # Forward\n h = self.fc(h)\n mu = self.fc_mu(h)\n var = F.softplus(self.fc_var(h))\n\n return mu, var\n\n\nclass SequentialNP(BaseNP):\n \"\"\"Sequential Neural Process class.\n\n Args:\n x_dim (int): Dimension size of x.\n y_dim (int): Dimension size of y.\n r_dim (int): Dimension size of r (representation).\n z_dim (int): Dimension size of z (stochastic latent).\n h_dim (int): Dimension size of h (rnn hidden state).\n\n Attributes:\n encoder_r (DeterministicEncoder): Encoder for deterministic\n representation `r`.\n encoder_z (StochasticEncoder): Encoder for stochastic latent `z`.\n decoder (Decoder): Decoder for predicting y with representation and\n query.\n rnn_cell (nn.RNNCell): RNN for sequence.\n \"\"\"\n\n def __init__(self, x_dim: int, y_dim: int, r_dim: int, z_dim: int,\n h_dim: int) -> None:\n super().__init__()\n\n self.z_dim = z_dim\n self.h_dim = h_dim\n\n self.encoder_r = DeterministicEncoder(x_dim, y_dim, r_dim)\n self.encoder_z = StochasticEncoder(h_dim, r_dim, z_dim)\n self.decoder = Decoder(x_dim, y_dim, h_dim, z_dim)\n self.rnn_cell = nn.RNNCell(r_dim + z_dim, h_dim)\n\n def sample(self, x_context: Tensor, y_context: Tensor, x_target: Tensor,\n y_target: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:\n \"\"\"Samples queried y target.\n\n Args:\n x_context (torch.Tensor): x for context, size\n `(batch_size, seq_len, num_context, x_dim)`.\n y_context (torch.Tensor): y for context, size\n `(batch_size, seq_len, num_context, y_dim)`.\n x_target (torch.Tensor): x for target, size\n `(batch_size, seq_len, num_target, x_dim)`.\n y_target (torch.Tensor, optional): y for target, size\n `(batch_size, recon_len, num_target, y_dim)`.\n\n Returns:\n mu (torch.Tensor): Mean of y, size\n `(batch_size, seq_len, num_target, y_dim)`.\n var (torch.Tensor): Variance of y, size\n `(batch_size, seq_len, num_target, y_dim)`.\n \"\"\"\n\n # Initial parameters\n batch, seq_len, num_target, _ = x_target.size()\n recon_len = y_target.size(1) if y_target is not None else 0\n\n h_t = x_target.new_zeros((batch, self.h_dim))\n z_t = x_target.new_zeros((batch, self.z_dim))\n\n # Sample\n # t < recon_len: Reconstruct observations\n # t >= recon_len: Sample from prior\n y_mu_list = []\n y_var_list = []\n for t in range(seq_len):\n # 1. Encode context: r = f(x, y)\n if y_target is not None and t < recon_len:\n r_t = self.encoder_r(x_target[:, t], y_target[:, t])\n else:\n r_t = self.encoder_r(x_context[:, t], y_context[:, t])\n\n # 2. Update rnn: h_t = rnn(z, r, h_{t-1})\n h_t = self.rnn_cell(torch.cat([z_t, r_t], dim=-1), h_t)\n\n # 3. Sample stochastic latent: z ~ p(h, r)\n z_t_mu, z_t_var = self.encoder_z(h_t, r_t)\n z_t = z_t_mu + z_t_var ** 0.5 * torch.randn_like(z_t_var)\n\n # 4. Render target y: y = renderer(x, z, h)\n y_t_mu, y_t_var = self.decoder(x_target[:, t], z_t, h_t)\n\n y_mu_list.append(y_t_mu)\n y_var_list.append(y_t_var)\n\n # Stack and resize\n y_mu = torch.stack(y_mu_list)\n y_var = torch.stack(y_var_list)\n\n y_mu = y_mu.transpose(0, 1)\n y_var = y_var.transpose(0, 1)\n\n return y_mu, y_var\n\n def loss_func(self, x_context: Tensor, y_context: Tensor, x_target: Tensor,\n y_target: Tensor) -> Dict[str, Tensor]:\n \"\"\"Loss function for the negative conditional log probability.\n\n Args:\n x_context (torch.Tensor): x for context, size\n `(batch_size, seq_len, num_context, x_dim)`.\n y_context (torch.Tensor): y for context, size\n `(batch_size, seq_len, num_context, y_dim)`.\n x_target (torch.Tensor): x for target, size\n `(batch_size, seq_len, num_target, x_dim)`.\n y_target (torch.Tensor): y for target, size\n `(batch_size, seq_len, num_target, y_dim)`.\n\n Returns:\n loss_dict (dict of [str, torch.Tensor]): Calculated loss.\n \"\"\"\n\n # Initial parameters\n batch, seq_len, *_ = x_context.size()\n h_t = x_target.new_zeros((batch, self.h_dim))\n z_t = x_target.new_zeros((batch, self.z_dim))\n\n nll_loss = x_target.new_zeros((batch,))\n kl_loss = x_target.new_zeros((batch,))\n\n for t in range(seq_len):\n # 1. Encode context and target: r = f(x, y)\n r_t_ctx = self.encoder_r(x_context[:, t], y_context[:, t])\n r_t_tgt = self.encoder_r(x_target[:, t], y_target[:, t])\n\n # 2. Update rnn: h_t = rnn(z, r, h_{t-1})\n h_t = self.rnn_cell(torch.cat([z_t, r_t_ctx], dim=-1), h_t)\n\n # 3. Sample stochastic latent z ~ p(h, r), q(h, r)\n z_t_mu_ctx, z_t_var_ctx = self.encoder_z(h_t, r_t_ctx)\n\n z_t_mu_tgt, z_t_var_tgt = self.encoder_z(h_t, r_t_tgt)\n z_t = (z_t_mu_tgt\n + z_t_var_tgt ** 0.5 * torch.randn_like(z_t_var_tgt))\n\n # 4. Render target y: y = renderer(x, z, h)\n y_t_mu, y_t_var = self.decoder(x_target[:, t], z_t, h_t)\n\n # Loss\n nll_loss += nll_normal(y_target[:, t], y_t_mu, y_t_var).sum(-1)\n kl_loss += kl_divergence_normal(\n z_t_mu_tgt, z_t_var_tgt, z_t_mu_ctx, z_t_var_ctx)\n\n loss_dict = {\n \"loss\": (nll_loss + kl_loss).mean(),\n \"nll\": nll_loss.mean(),\n \"kl\": kl_loss.mean(),\n }\n\n return loss_dict\n","sub_path":"neuralprocess/sequential_np.py","file_name":"sequential_np.py","file_ext":"py","file_size_in_byte":10270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"548434758","text":"# Copyright (c) 2019 Uber Technologies, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nfrom typing import Callable\n\nimport pytest\nimport torch\n\nfrom ludwig.utils.image_utils import (\n crop,\n crop_or_pad,\n grayscale,\n num_channels_in_image,\n pad,\n resize_image,\n ResizeChannels,\n)\n\n\n@pytest.mark.parametrize(\"pad_fn\", [pad, torch.jit.script(pad)])\n@pytest.mark.parametrize(\n \"img,size,padded_img\",\n [\n (\n torch.arange(12, dtype=torch.int).reshape(3, 2, 2),\n 4,\n torch.Tensor(\n [\n 0,\n 0,\n 1,\n 1,\n 0,\n 0,\n 1,\n 1,\n 2,\n 2,\n 3,\n 3,\n 2,\n 2,\n 3,\n 3,\n 4,\n 4,\n 5,\n 5,\n 4,\n 4,\n 5,\n 5,\n 6,\n 6,\n 7,\n 7,\n 6,\n 6,\n 7,\n 7,\n 8,\n 8,\n 9,\n 9,\n 8,\n 8,\n 9,\n 9,\n 10,\n 10,\n 11,\n 11,\n 10,\n 10,\n 11,\n 11,\n ]\n )\n .type(torch.int)\n .reshape(3, 4, 4),\n )\n ],\n)\ndef test_pad(pad_fn: Callable, img: torch.Tensor, size: int, padded_img: torch.Tensor):\n output_img = pad_fn(img, size)\n assert torch.equal(output_img, padded_img)\n\n\n@pytest.mark.parametrize(\"crop_fn\", [crop, torch.jit.script(crop)])\n@pytest.mark.parametrize(\n \"img,size,cropped_img\",\n [\n (\n torch.arange(27, dtype=torch.int).reshape(3, 3, 3),\n 2,\n torch.Tensor([0, 1, 3, 4, 9, 10, 12, 13, 18, 19, 21, 22]).type(torch.int).reshape(3, 2, 2),\n )\n ],\n)\ndef test_crop(crop_fn: Callable, img: torch.Tensor, size: int, cropped_img: torch.Tensor):\n output_img = crop_fn(img, size)\n assert torch.equal(output_img, cropped_img)\n\n\n@pytest.mark.parametrize(\"crop_or_pad_fn\", [crop_or_pad, torch.jit.script(crop_or_pad)])\n@pytest.mark.parametrize(\n \"img,new_size,expected_img\",\n [\n (\n torch.arange(12, dtype=torch.int).reshape(3, 2, 2),\n 4,\n torch.Tensor(\n [\n 0,\n 0,\n 1,\n 1,\n 0,\n 0,\n 1,\n 1,\n 2,\n 2,\n 3,\n 3,\n 2,\n 2,\n 3,\n 3,\n 4,\n 4,\n 5,\n 5,\n 4,\n 4,\n 5,\n 5,\n 6,\n 6,\n 7,\n 7,\n 6,\n 6,\n 7,\n 7,\n 8,\n 8,\n 9,\n 9,\n 8,\n 8,\n 9,\n 9,\n 10,\n 10,\n 11,\n 11,\n 10,\n 10,\n 11,\n 11,\n ]\n )\n .type(torch.int)\n .reshape(3, 4, 4),\n ),\n (\n torch.arange(27, dtype=torch.int).reshape(3, 3, 3),\n 2,\n torch.Tensor([0, 1, 3, 4, 9, 10, 12, 13, 18, 19, 21, 22]).type(torch.int).reshape(3, 2, 2),\n ),\n ],\n)\ndef test_crop_or_pad(crop_or_pad_fn: Callable, img: torch.Tensor, new_size: int, expected_img: torch.Tensor):\n output_image = crop_or_pad_fn(img, new_size)\n assert torch.equal(output_image, expected_img)\n\n\n@pytest.mark.parametrize(\"resize_image_fn\", [resize_image, torch.jit.script(resize_image)])\n@pytest.mark.parametrize(\n \"img,new_size,resize_method,expected_img\",\n [\n (\n torch.arange(27, dtype=torch.int).reshape(3, 3, 3),\n 2,\n \"crop_or_pad\",\n torch.Tensor([0, 1, 3, 4, 9, 10, 12, 13, 18, 19, 21, 22]).type(torch.int).reshape(3, 2, 2),\n ),\n (\n torch.arange(27, dtype=torch.int).reshape(3, 3, 3),\n 2,\n \"interpolate\",\n torch.Tensor([1, 2, 6, 7, 10, 12, 14, 16, 19, 20, 24, 25]).type(torch.int).reshape(3, 2, 2),\n ),\n ],\n)\ndef test_resize_image(\n resize_image_fn: Callable, img: torch.Tensor, new_size: int, resize_method: str, expected_img: torch.Tensor\n):\n output_img = resize_image_fn(img, new_size, resize_method)\n assert torch.equal(output_img, expected_img)\n\n\n@pytest.mark.parametrize(\"grayscale_fn\", [grayscale, torch.jit.script(grayscale)])\n@pytest.mark.parametrize(\n \"input_img,grayscale_img\",\n [(torch.arange(12).reshape(3, 2, 2).type(torch.int), torch.Tensor([[[3, 4], [5, 6]]]).type(torch.int))],\n)\ndef test_grayscale(grayscale_fn: Callable, input_img: torch.Tensor, grayscale_img: torch.Tensor):\n output_img = grayscale_fn(input_img)\n assert torch.equal(output_img, grayscale_img)\n\n\ndef test_num_channels_in_image():\n image_2d = torch.randint(0, 1, (10, 10))\n image_3d = torch.randint(0, 1, (3, 10, 10))\n assert num_channels_in_image(image_2d) == 1\n assert num_channels_in_image(image_3d) == 3\n\n with pytest.raises(ValueError):\n num_channels_in_image(torch.rand(5))\n num_channels_in_image(None)\n\n\n@pytest.mark.parametrize(\"image_shape\", [(1, 10, 10), (3, 10, 10), (5, 10, 10)])\n@pytest.mark.parametrize(\"num_channels_expected\", [1, 2, 3, 4])\ndef test_ResizeChannels_module(image_shape, num_channels_expected):\n image = torch.randint(0, 1, image_shape)\n fn = ResizeChannels(num_channels_expected)\n assert fn(image).shape == tuple([num_channels_expected] + list(image_shape[1:]))\n\n\n@pytest.mark.parametrize(\"image_shape\", [(2, 1, 10, 10), (2, 3, 10, 10), (2, 5, 10, 10)])\n@pytest.mark.parametrize(\"num_channels_expected\", [1, 2, 3, 4])\ndef test_ResizeChannels_module_with_batch_dim(image_shape, num_channels_expected):\n image = torch.randint(0, 1, image_shape)\n fn = ResizeChannels(num_channels_expected)\n assert fn(image).shape == tuple([image_shape[0], num_channels_expected] + list(image_shape[2:]))\n","sub_path":"tests/ludwig/utils/test_image_utils.py","file_name":"test_image_utils.py","file_ext":"py","file_size_in_byte":7486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"467900185","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 24 11:47:53 2020\n\n@author: jruiz\n\"\"\"\nimport numpy as np\nimport os\nimport pickle\n\nimport sys\n\nsys.path.append(\"../\")\n\n\n\n#Seleccionar aqui el operador de las observaciones que se desea usar.\nfrom Lorenz_63_ObsOperator import forward_operator_nonlinear as forward_operator\nfrom Lorenz_63_ObsOperator import forward_operator_nonlinear_tl as forward_operator_tl\nimport copy\n\nimport tempered_hybrid_module as thm \n\nimport multiprocessing as mp\n\n\nmax_proc=10\n\n# Configuracion del sistema del modelo y del sistema de asimilacion.\nda_exp=dict() #Este diccionario va a contener las variables importantes para nuestro experimento.\n\nda_exp['obs_operator_name'] = 'nonlinear' #CUIDADO, esto tiene que ser consistente con el import que figura mas arriba.\n\nda_exp['random_seed']=10\n#------------------------------------------------------------\n# Especificamos los parametros que usara el modelo\n#------------------------------------------------------------\na = 10.0 # standard L63 10.0 \nr = 28.0 # standard L63 28.0\nb = 8.0/3.0 # standard L63 8.0/3.0\n\nda_exp['p']=np.array([a,r,b])\nda_exp['pim']=np.array([a,r,b])\n\n#------------------------------------------------------------\n# Model and experienet setup\n#------------------------------------------------------------\n\nda_exp['dt']=0.01 # Paso de tiempo para la integracion del modelo de Lorenz\nda_exp['numstep']=10000\n# Cantidad de ciclos de asimilacion.\nda_exp['x0']=np.array([ 8.0 , 0.0 , 30.0 ]) # Condiciones iniciales para el spin-up del nature run (no cambiar)\nda_exp['numtrans']=600 # Tiempo de spin-up para generar el nature run (no cambiar)\n\n#------------------------------------------------------------\n# Configuracion del sistema de asimilacion\n#------------------------------------------------------------\n\nda_exp['dx0'] = np.array([ 5.0 , 5.0 , 5.0 ]) # Error inicial de la estimacion. \nda_exp['R0']=2.0 # Varianza del error de las observaciones.\nda_exp['bst']=16 # Cantidad de pasos de tiempo entre 2 asimilaciones.\nda_exp['forecast_length'] = 2 # Plazo de pronostico (debe ser al menos 1)\nda_exp['nvars']=3 # Numero de variables en el modelo de Lorenz (no tocar)\n\nda_exp['EnsSize']=30 #Numero de miembros en el ensamble.\n\nda_exp['rtps_alpha'] = 0.0 #Relaxation to prior spread (Whitaker y Hamill 2012) # 0.6 es un buen parametro (no se usa por el momento)\nda_exp['rejuv_param'] = 0.0 #Parametro de rejuvenecimiento (Acevedo y Reich 2017) #0.4 es un buen parametro\nda_exp['multinf']=1.0 #Inflacion multiplicativa (solo se aplica al ETKF, no al ETPF)\n\n#Obtengo el numero de observaciones (lo obtengo directamente del forward operator)\nda_exp['nobs']=np.size(forward_operator(np.array([0,0,0])))\n\n#Definimos una matriz de error de las observaciones\nda_exp['R']=da_exp['R0']*np.identity(da_exp['nobs']) #En esta formulacion asumimos que los errores \n #en diferentes observaciones son todos iguales y \n#Creamos un vector de bias para las observaciones.\nda_exp['obs_bias']=np.zeros(da_exp['nobs']) #que no estan correlacionados entre si.\n\nda_exp['P_from_file']=False #Si vamos a leer la matriz P de un archivo.\nda_exp['P_to_file']=False #Si vamos a estimar y guardar la matriz P a partir de los pronosticos.\n\nda_exp['P0']=10.0*np.array([[0.6 , 0.5 , 0.0 ],[0.5 , 0.6 , 0.0 ],[0.0 , 0.0 , 1.0 ]])\n#P=None\n\n#Definimos una matriz Q para compensar los efectos no lineales y posibles errores de modelo.\nda_exp['Q']=0.4 * np.identity(3)\n\nda_exp['forward_operator'] = forward_operator\nda_exp['forward_operator_tl'] = forward_operator_tl\n\n\nda_exp['ntemp']=1 # Numero de temperados (1 recupera un ciclo de DA tradicional)\nda_exp['bridge']=0.0 # Coeficiente de combiancion entre ETPF y ETKF. 0-ETKF puro, 1-ETPF puro.\n\n\nfilename = './Sensitivity_to_bridging_R'+str(da_exp['R0'])+'_bst'+str(da_exp['bst'])+'_ntemp'+str(da_exp['ntemp'])+'_'+da_exp['obs_operator_name']+'.pkl'\n\n#Run experiments in parallel. \n\nos.environ['OMP_NUM_THREADS']=\"1\"\n\n#Create a list of configurations. We will then iterate over these configurations to run experiments in parallel.\n\nda_exp_list=list() #Here we will store all possible configurations that we want to run.\n\n\nfor ibridge in range( 0 , 11 ) :\n\n da_exp['bridge']= ibridge / 10.0\n \n da_exp_list.append( copy.deepcopy( da_exp ) ) #Add this configuration to the configuration list\n\n\npool = mp.Pool( min( max_proc , len( da_exp_list ) ) )\n\nresults = pool.map( thm.da_cycle_tempered_hybrid , da_exp_list )\n\npool.close()\n\nwith open( filename , 'wb') as handle:\n pickle.dump( results , handle, protocol=pickle.HIGHEST_PROTOCOL)\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":"Lorenz_63/TEMPERED_HYBRID_EXPERIMENTS/bridging_sensitivity.py","file_name":"bridging_sensitivity.py","file_ext":"py","file_size_in_byte":5029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"545709190","text":"from app.models.question import Question\nfrom rest_framework import serializers\nfrom rest_framework.reverse import reverse\n\n\nclass QuestionSerializer(serializers.ModelSerializer):\n first_option_result = serializers.ReadOnlyField()\n links = serializers.SerializerMethodField()\n\n class Meta:\n model = Question\n fields = ('id', 'description', 'first_option_result', 'links', )\n\n def get_links(self, obj):\n request = self.context['request']\n return {\n 'self': reverse('question-detail',\n kwargs={'pk': obj.pk},request=request),\n }","sub_path":"app/serializers/question_serializer.py","file_name":"question_serializer.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"110410741","text":"from odoo import fields, models, api, _\nfrom odoo.exceptions import UserError\n\n# SC_STATES = [('draft', 'Draft'), ('open', 'Open'), ('done', 'Done')]\n\n\nclass stock_card(models.Model):\n _name = \"fal.stock.card\"\n _inherit = ['mail.thread', 'mail.activity.mixin']\n _description = \"Stock Card\"\n\n name = fields.Char(\"Number\", default=\"/\")\n date_start = fields.Date(\"Date Start\", required=True, track_visibility='onchange', default=fields.Date.today())\n date_end = fields.Date(\"Date End\", required=True, track_visibility='onchange', default=fields.Date.today())\n location_id = fields.Many2one('stock.location', 'Location', track_visibility='onchange', required=True)\n product_id = fields.Many2one('product.product', 'Product', track_visibility='onchange', required=True)\n lot_id = fields.Many2one('stock.production.lot', 'Serial Number')\n expired_date = fields.Date(string=\"Expired Date\")\n line_ids = fields.One2many('fal.stock.card.line', 'stock_card_id', 'Details', ondelete=\"cascade\")\n state = fields.Selection([\n ('draft', 'Draft'), ('open', 'Open'),\n ('done', 'Done')], 'Status', readonly=True,\n required=True, default=\"draft\")\n user_id = fields.Many2one('res.users', 'Created', default=lambda self: self.env.user)\n\n @api.multi\n def unlink(self):\n for order in self:\n if order.state not in ('draft'):\n raise UserError(_('In order to delete a stock card, \\\n you must cancel it first.'))\n return super(stock_card, self).unlink()\n\n @api.multi\n def action_calculate(self):\n # empty stock_card_line\n # find stock move product_id and location_id, start_date to end_date\n # insert into stock_card_line\n # if out from location (source_id) then fill to qty_out\n # if exist on location (dest_id) then fill to qty_in\n # count qty_balance = qty_start + qty_in - qty_out\n # start balance counted from sum qty stock move before start_date\n\n stock_move = self.env['stock.move']\n stock_card_line = self.env['fal.stock.card.line']\n\n for sc in self:\n self.env.cr.execute(\n \"delete from fal_stock_card_line \\\n where stock_card_id=%s\" % sc.id\n )\n\n qty_start = 0.0\n qty_balance = 0.0\n qty_in = 0.0\n qty_out = 0.0\n product_uom = False\n\n sql2 = \"select move_id from \\\n stock_move_line where product_id = %s\" % (sc.product_id.id)\n self.env.cr.execute(sql2)\n res = self.env.cr.fetchall()\n move_ids = []\n if res and res[0] != 'None':\n for move in res:\n move_ids.append(move[0])\n else:\n raise UserError(_('No Data for this Product!'))\n\n # beginning balance in\n sql = \"select sum(product_uom_qty) from stock_move where product_id=%s \\\n and date < '%s' and location_dest_id=%s \\\n and id IN %s \\\n and state='done'\" % (\n sc.product_id.id, sc.date_start,\n sc.location_id.id,\n '(%s)' % ', '.join(map(repr, tuple(move_ids))),)\n\n self.env.cr.execute(sql)\n res = self.env.cr.fetchone()\n\n if res and res[0]:\n qty_start = res[0]\n\n # beginning balance out\n sql_prod_qty_out = \"select sum(product_uom_qty) from stock_move \\\n where product_id=%s and date < '%s' and \\\n location_id=%s and state='done'\" % (\n sc.product_id.id, sc.date_start, sc.location_id.id)\n\n self.env.cr.execute(sql_prod_qty_out)\n res_prod_qty_out = self.env.cr.fetchone()\n\n if res_prod_qty_out and res_prod_qty_out[0]:\n qty_start = qty_start - res_prod_qty_out[0]\n\n # product uom\n # import pdb;pdb.set_trace()\n prod = sc.product_id\n product_uom = prod.uom_id\n\n data = {\n \"stock_card_id\": sc.id,\n \"name\": 'Beginning Data',\n \"date\": False,\n \"qty_start\": qty_start,\n \"qty_in\": qty_in,\n \"qty_out\": qty_out,\n \"qty_balance\": qty_start,\n \"product_uom_id\": product_uom.id,\n }\n stock_card_line.create(data)\n\n # mutasi\n sm_ids = stock_move.search([\n '|',\n ('location_dest_id', '=', sc.location_id.id),\n ('location_id', '=', sc.location_id.id),\n ('product_id', '=', sc.product_id.id),\n ('date', '>=', sc.date_start),\n ('date', '<=', sc.date_end),\n ('state', '=', 'done'),\n ('id', 'in', move_ids)\n ], order='date asc')\n\n for sm in sm_ids:\n\n qty_in = 0.0\n qty_out = 0.0\n\n if product_uom.id != sm.product_uom.id:\n factor = product_uom.factor / sm.product_uom.factor\n else:\n factor = 1.0\n\n # incoming, dest = location\n if sm.location_dest_id == sc.location_id:\n qty_in = sm.product_uom_qty * factor\n # outgoing, source = location\n elif sm.location_id == sc.location_id:\n qty_out = sm.product_uom_qty * factor\n\n qty_balance = qty_start + qty_in - qty_out\n\n name = sm.name if sm.name != prod.display_name else \"\"\n partner_name = sm.partner_id.name if sm.partner_id else \"\"\n notes = sm.picking_id.note or \"\"\n po_no = sm.group_id.name if sm.group_id else \"\"\n origin = sm.origin or \"\"\n finish_product = \"\"\n\n if \"MO\" in origin:\n mrp = self.env['mrp.production']\n mo = mrp.search([(\"name\", \"=\", origin)])\n finish_product = \"%s\" % (\n mo[0].product_id.name,\n ) if mo else \"\"\n\n data = {\n \"stock_card_id\": sc.id,\n \"move_id\": sm.id,\n \"picking_id\": sm.picking_id.id,\n \"date\": sm.date,\n \"qty_start\": qty_start,\n \"qty_in\": qty_in,\n \"qty_out\": qty_out,\n \"qty_balance\": qty_balance,\n \"product_uom_id\": product_uom.id,\n \"name\": \"%s/ %s/ %s/ %s/ %s/ %s\" % (\n name, finish_product,\n partner_name, po_no, notes, origin),\n }\n stock_card_line.create(data)\n qty_start = qty_balance\n return\n\n def action_draft(self):\n # set to \"draft\" state\n return self.write(\n {'state': 'draft'}\n )\n\n def action_confirm(self):\n # set to \"confirmed\" state\n return self.write(\n {'state': 'open'}\n )\n\n def action_done(self):\n # set to \"done\" state\n return self.write(\n {'state': 'done'}\n )\n\n @api.model\n def create(self, vals):\n if vals.get('name', '/') == '/':\n seq_obj = self.env['ir.sequence']\n vals['name'] = seq_obj.next_by_code(\n 'fal.stock.card') or '/'\n new_id = super(stock_card, self).create(vals)\n return new_id\n\n\nclass stock_card_line(models.Model):\n _name = \"fal.stock.card.line\"\n _description = \"Stock Card Line\"\n\n name = fields.Char(\"Description\")\n stock_card_id = fields.Many2one('fal.stock.card', 'Stock Card')\n move_id = fields.Many2one('stock.move', 'Stock Move')\n picking_id = fields.Many2one('stock.picking', 'Picking')\n date = fields.Date(\"Date\")\n qty_start = fields.Float(\"Start\")\n qty_in = fields.Float(\"Qty In\")\n qty_out = fields.Float(\"Qty Out\")\n qty_balance = fields.Float(\"Balance\")\n product_uom_id = fields.Many2one('uom.uom', 'UoM')\n","sub_path":"fal_stock_card/models/stock_card.py","file_name":"stock_card.py","file_ext":"py","file_size_in_byte":8136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"370185763","text":"import torch\nfrom torch.nn import Linear, Sigmoid, Tanh\nfrom torch import sigmoid, tanh\nfrom artemis.general.should_be_builtins import bad_value\nfrom uoro_demo.torch_utils.interfaces import RecurrentStatelessModule\nfrom uoro_demo.torch_utils.training import get_rnn_class\n\n\nclass StatelessPredictorRNN(RecurrentStatelessModule):\n\n def __init__(self, n_in, n_hid, n_out, rnn_type='elman', output_rep='linear', freeze_rnn = False, bias=True):\n\n super(StatelessPredictorRNN, self).__init__()\n self.rnn = get_rnn_class(rnn_type)(n_in, n_hid)\n self.n_hid=n_hid\n self.n_out = n_out\n self.rnn_type = rnn_type\n self.output_layer = {\n 'linear': lambda: torch.nn.Linear(n_hid, n_out, bias = bias),\n }[output_rep]()\n self.freeze_rnn = freeze_rnn\n\n if freeze_rnn:\n it_happened = False\n for param_name, p in self.rnn.named_parameters():\n if param_name.startswith('weight_hh') or param_name.startswith('bias_hh'):\n p.requires_grad = False\n it_happened = True\n assert it_happened\n\n #\n # def parameters(self):\n # if self.freeze_rnn:\n # # Note this also disables the input-to-state parameters, but that's ok for now.\n # rnn_parameters = list(self.rnn.parameters())\n # return (p for p in super(StatelessPredictorRNN, self).parameters() if p not in rnn_parameters)\n # else:\n # return (p for p in super(StatelessPredictorRNN, self).parameters())\n\n def forward(self, x, prev_state):\n \"\"\"\n :param x: A (batch_size, n_dim) input\n :param prev_state: A representation of the previous hidden state: (\n :return: A (batch_size, n_out) output\n \"\"\"\n hidden_history, hidden_state = self.rnn(x[None], prev_state)\n prediction = self.output_layer(hidden_history[-1, :, :]) # (last_step, )\n return prediction, hidden_state\n\n # _, hidden_state = self.rnn(x[None], prev_state)\n # hidden_history, _ = self.rnn(x[None], prev_state)\n # prediction = self.output_layer(hidden_history[-1, :, :]) # (last_step, )\n # return prediction, hidden_state\n\n def get_initial_state(self, x_init):\n assert x_init.dim() == 2, 'x_init should have 2 dimensions: (batch_size, n_dims). Its shape is {}'.format(x_init.size())\n\n return torch.autograd.Variable(torch.zeros(1, len(x_init), self.n_hid), requires_grad=True) if self.rnn_type in ('elman', 'gru') else \\\n (torch.autograd.Variable(torch.zeros(1, len(x_init), self.n_hid), requires_grad=True), torch.autograd.Variable(torch.zeros(1, len(x_init), self.n_hid), requires_grad=True)) if self.rnn_type == 'lstm' else \\\n bad_value(self.rnn_type)\n\n\nclass GRUPredictor(RecurrentStatelessModule):\n\n def __init__(self, n_in, n_hid, n_out, bias = True):\n super(GRUPredictor, self).__init__()\n self.n_hid = n_hid\n self.f_xz = Linear(n_in, n_hid, bias=bias)\n self.f_xr = Linear(n_in, n_hid, bias=bias)\n self.f_xh = Linear(n_in, n_hid, bias=bias)\n self.f_hz = Linear(n_hid, n_hid, bias=False)\n self.f_hr = Linear(n_hid, n_hid, bias=False)\n self.f_hrh = Linear(n_hid, n_hid, bias=False)\n self.f_hy = Linear(n_hid, n_out, bias=bias)\n\n def forward(self, x, h_old):\n z = sigmoid(self.f_xz(x) + self.f_hz(h_old))\n r = sigmoid(self.f_xr(x) + self.f_hr(h_old))\n h = z * h_old + (1-z)* tanh(self.f_xh(x) + self.f_hrh(r*h_old))\n y = self.f_hy(h)\n return y, h\n\n def get_initial_state(self, x_init):\n return torch.autograd.Variable(torch.zeros(len(x_init), self.n_hid), requires_grad=True)","sub_path":"uoro_demo/predictor_funcs.py","file_name":"predictor_funcs.py","file_ext":"py","file_size_in_byte":3735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"365408037","text":"\"\"\"\nIsha Slavin.\nWeek 3 - TASK #1.\n\"\"\"\n\nfrom base import BaseOptimizer\nfrom oracle import Oracle\nimport numpy as np\nimport pandas as pd\nimport math\nimport random\nfrom benchmarkfunctions import SparseQuadratic, MaxK\nfrom matplotlib import pyplot as plt\n\n# this class implements the Gradient-Less Descent with Binary Search Algorithm using a Comparison Oracle.\n# source: https://arxiv.org/pdf/1911.06317.pdf.\n\n\nclass GLDOptimizer(BaseOptimizer):\n \"\"\"\n INPUTS:\n 1. defined_func (type = FUNC) objective function; inputted into Oracle class for function evaluations.\n 2. x_0: (type = NUMPY ARRAY) starting point (of dimension = n).\n 3. R: (type = INT) maximum search radius (ex.: 10).\n 4. r: (type = INT) minimum search radius (ex.: 0.1).\n 5. function_budget: (type = INT) total number of function evaluations allowed.\n \"\"\"\n\n def __init__(self, defined_func, x_0, R, r, function_budget):\n super().__init__()\n\n self.function_evals = 0\n self.defined_func = defined_func\n self.x_0 = x_0\n self.R = R\n self.r = r\n self.function_budget = function_budget\n self.f_vals = []\n self.list_of_xt = []\n\n K = math.log(self.R / self.r, 10)\n self.K = K\n\n def step(self):\n # x_t.\n if self.function_evals == 0:\n ### DM: Rewrote in a slightly more efficient way\n x_t = self.x_0\n # x_k = np.random.rand(1, n)\n # x_k = x_k[0]\n # print('xk:')\n # print(x_k)\n self.list_of_xt.append(x_t)\n else:\n x_t = self.list_of_xt[-1]\n # list of x_t's for this one step.\n v_list = [x_t]\n # n: dimension of x_t.\n n = len(x_t)\n # sampling distribution (randomly generated at each step).\n D = np.random.randn(n) / n\n # iterate through k's in K (which equals log(R/r)).\n for k in range(int(self.K)):\n # calculate r_k.\n r_k = 2 ** -k\n r_k = r_k * self.R\n # print('r_k: ', r_k)\n r_k_D = np.dot(r_k, D)\n # sample v_k from r_k_D.\n random_dir = random.randint(0, n - 1)\n v_k = r_k_D[random_dir]\n # print('vk: ', v_k)\n next_el = x_t + v_k\n # add each x_t + v_k to a list for all k in K.\n v_list.append(next_el)\n # length will never be 0 (I think), this is just to make sure.\n if len(v_list) == 0:\n # list_of_xt.append(x_t)\n # f_vals.append(defined_func(x_t))\n # continue\n \"\"\" fix this to return the proper output. \"\"\"\n return 0\n # now that we have our list of vk's, let's use the comparison oracle to determine the argmin of the elements.\n # while there are at least two elements to input into the comparison Oracle.\n while len(v_list) >= 2:\n new_instance_1 = Oracle(self.defined_func)\n # print('0:', v_list[0])\n # print('1:', v_list[1])\n # input the first two elements of the list into the oracle.\n first_comparison = new_instance_1(v_list[0], v_list[1])\n # INCREMENT function_evals by 1.\n self.function_evals += 1\n # possibilities of Oracle output:\n if first_comparison == +1:\n # 0th elem is smaller.\n # remove 1st element.\n v_list.pop(1)\n elif first_comparison == -1:\n # 1st elem is smaller.\n # remove 0th element.\n v_list.pop(0)\n else:\n # function values are equal with elements 0 and 1 of list.\n # choose one at random to drop.\n rand_choice = random.choice([0, 1])\n v_list.pop(rand_choice)\n list_length = len(v_list)\n # the list is length 1 after all comparisons have been made (or if input R = input r).\n if list_length == 1:\n # print(t)\n # remaining element is our ARGMIN.\n argmin = v_list[0]\n x_t = argmin\n self.list_of_xt.append(x_t)\n self.f_vals.append(self.defined_func(x_t))\n # now, let's check if the function budget is depleted.\n if self.reachedFunctionBudget(self.function_budget, self.function_evals):\n # if budget is reached return parent.\n # solution, list of all function values, termination.\n while len(self.f_vals) > (self.function_budget/2):\n self.f_vals.pop()\n return x_t, self.f_vals, 'B'\n # return solution, list of all function values, termination (which will be False here).\n return x_t, self.f_vals, False\n\n\n'''\n # in the STEP function, use what Daniel did.\n # when function evals is still 0, take xk from self.x_0.\n # if not, do what you usually do to generate the xt and then append it to the list of xt's.\n'''\n\n# ---------\nprint('sample invoke.')\n# GLD - FUNCTION sample invocation.\nn_def = 20000 # problem dimension.\ns_exact = 200 # True sparsity.\nnoise_amp = 0.001 # noise amplitude.\n# initialize objective function.\nobj_func_1 = SparseQuadratic(n_def, s_exact, noise_amp)\nobj_func_2 = MaxK(n_def, s_exact, noise_amp)\nmax_function_evals = 10000\nx_0_ = np.random.rand(n_def)\nprint('shape of x_0_: ', len(x_0_))\nR_ = 10\nr_ = .01\n# GLDOptimizer instance.\n# def __init__(self, defined_func, x_0, R, r, function_budget).\nstp1 = GLDOptimizer(obj_func_1, x_0_, R_, r_, max_function_evals)\n# stp1 = GLDOptimizer(obj_func_2, x_0_, R_, r_, max_function_evals)\n# step.\ntermination = False\nprev_evals = 0\nwhile termination is False:\n # optimization step.\n solution, func_value, termination = stp1.step()\n # print('step')\n print('current value: ', func_value[-1])\n# print the solution.\nprint('\\n')\nprint('solution: ', solution)\n# plot the decreasing function.\nplt.plot(func_value)\n#plt.show()\n# log x-axis.\nplt.semilogy(func_value)\n#plt.show()\n# ---------\nprint('\\n')\nprint('number of function vals: ', len(func_value))\n","sub_path":"ExampleCode/gld_optimizer.py","file_name":"gld_optimizer.py","file_ext":"py","file_size_in_byte":6070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"476242111","text":"from rake_nltk import Rake\n\nfrom difflib import SequenceMatcher\n\nimport nltk\n\n#from nltk.stem import PorterStemmer\n\n#from nltk.stem import LancasterStemmer\n\nfrom nltk.stem import WordNetLemmatizer \n \nfrom nltk.corpus import wordnet\n\nimport gensim\n\nfrom nltk.tokenize import sent_tokenize, word_tokenize\n\nimport array \n\n\"\"\"porter = PorterStemmer()\n\nlancaster=LancasterStemmer()\n\n#defining stemming for sentence\n\ndef stemSentence(sentence):\n token_words=word_tokenize(sentence)\n token_words\n stem_sentence=[]\n for word in token_words:\n stem_sentence.append(porter.stem(word))\n stem_sentence.append(\" \")\n return \"\".join(stem_sentence)\n\"\"\"\n\n\n#x=stemSentence(sentence)\n\nlemmatizer = WordNetLemmatizer()\n\n# function to convert nltk tag to wordnet tag\n\n#for lemmatization\ndef nltk_tag_to_wordnet_tag(nltk_tag):\n if nltk_tag.startswith('J'):\n return wordnet.ADJ\n elif nltk_tag.startswith('V'):\n return wordnet.VERB\n elif nltk_tag.startswith('N'):\n return wordnet.NOUN\n elif nltk_tag.startswith('R'):\n return wordnet.ADV\n else: \n return None\n\ndef lemmatize_sentence(sentence):\n #tokenize the sentence and find the POS tag for each token\n nltk_tagged = nltk.pos_tag(nltk.word_tokenize(sentence)) \n #tuple of (token, wordnet_tag)\n wordnet_tagged = map(lambda x: (x[0], nltk_tag_to_wordnet_tag(x[1])), nltk_tagged)\n lemmatized_sentence = []\n for word, tag in wordnet_tagged:\n if tag is None:\n #if there is no available tag, append the token as is\n lemmatized_sentence.append(word)\n else: \n #else use the tag to lemmatize the token\n lemmatized_sentence.append(lemmatizer.lemmatize(word, tag))\n return \" \".join(lemmatized_sentence)\n \n#defining similar\n\ndef similar(a, b):\n return SequenceMatcher(None, a, b).ratio()\n\na = Rake(min_length=1, max_length=4)\nr = Rake(min_length=1, max_length=4)\ns = Rake(min_length=1, max_length=4)\nt = Rake(min_length=1, max_length=4)\nu = Rake(min_length=1, max_length=4)\nv = Rake(min_length=1, max_length=4)\n# Extraction given the text.\nstr = open('answer.txt', 'r').read()\n\nstr1 = open('key1.txt','r').read()\nstr2 = open('key2.txt','r').read()\nstr3 = open('key3.txt','r').read()\nstr4 = open('key4.txt','r').read()\nmanual = [\n 'rapid automatic keyword extraction', 'concrete application depend', 'widely use nlp technique', 'automatically extract keywords', 'compact representation', 'keywords', 'write', 'word', 'well', 'together', 'sequence', 'rake', 'purpose', 'provide', 'one', 'lot', 'language', 'known', 'domain', 'document', 'content', 'algorithm'\n ]\nstr5='.'.join(manual)\n\nans=lemmatize_sentence(str)\n\ns1=lemmatize_sentence(str1)\ns2=lemmatize_sentence(str2)\ns3=lemmatize_sentence(str3)\ns4=lemmatize_sentence(str4)\ns5=lemmatize_sentence(str5)\n\n#a=stemSentence(s1)\n#b=stemSentence(s2)\na.extract_keywords_from_text(ans)\nr.extract_keywords_from_text(s1)\ns.extract_keywords_from_text(s2)\nt.extract_keywords_from_text(s3)\nu.extract_keywords_from_text(s4)\nv.extract_keywords_from_text(s5)\n\n# Extraction given the list of strings where each string is a sentence.\n#r.extract_keywords_from_sentences(\"list of sentences\")\n\n# To get keyword phrases ranked highest to lowest.\na1=a.get_ranked_phrases()\nr1=r.get_ranked_phrases()\nr2=s.get_ranked_phrases()\nr3=t.get_ranked_phrases()\nr4=u.get_ranked_phrases()\nr5=v.get_ranked_phrases()\n#print(r.extract_keywords_from_sentences(s3))\n\n#print(s.extract_keywords_from_sentences(s4))\n# To get keyword phrases ranked highest to lowest with scores.\n#print(similar(r.get_ranked_phrases_with_scores(),s.get_ranked_phrases_with_scores()))\n\n\n\n\n\n#c=stemSentence(s5)\n#print(answer_list)\n#print(phrase_list)\na1.sort()\nr1.sort()\nr2.sort()\nr3.sort()\nr4.sort()\nr5.sort()\n\narr = array.array('d', [0,0,0,0,0])\narr[0]=similar(a1,r1)\narr[1]=similar(a1,r2)\narr[2]=similar(a1,r3)\narr[3]=similar(a1,r4)\narr[4]=similar(a1,r5)\n\nprint(arr)\nprint(\"keywords from key1 \\n\")\nprint(r1,'\\n')\nprint(\"keywords from key2 \\n\")\nprint(r2,'\\n')\nprint(\"keywords from key3 \\n\")\nprint(r3,'\\n')\nprint(\"keywords from key4 \\n\")\nprint(r4,'\\n')\nprint(\"keywords from key5 \\n\")\nprint(r5,'\\n')\nprint(max(arr))\n#print(r.get_word_degrees(),'\\n')\n\n#print(r.get_ranked_phrases_with_scores())\n#print(s.get_ranked_phrases_with_scores())\n\n\n#print(s.get_word_degrees(),'\\n')\n#print(r._build_word_co_occurance_graph(str))\n","sub_path":"rake-nltk-master/tests/rake_t.py","file_name":"rake_t.py","file_ext":"py","file_size_in_byte":4421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"276858315","text":"from copy import deepcopy\ns=input()+\"T\"\nx,y=[int(i) for i in input().split()]\n\n\ndx=[]\ndy=[]\n\ndir_is_X=True\nstep=0\nfor char in s:\n\tif char=='F':\n\t\tstep+=1\n\telse:\n\t\tif dir_is_X:\n\t\t\tdx.append(step)\n\t\t\tdir_is_X=False\n\t\t\tstep=0\n\t\telse:\n\t\t\tdy.append(step)\n\t\t\tstep=0\n\t\t\tdir_is_X=True\n#print(dx)\n#print(dy)\nnowX=set([0])\n#print(type(nowX))\nnextX=set([])\nnowY=set([0])\nnextY=set([])\n\nfor num in dx:\n\t#print(type(nextX))\n\tfor now in nowX:\n\t\tnextX.add(now+num)\n\t\tnextX.add(now-num)\n\tnowX=deepcopy(nextX)\n\tnextX=set([])\nfor num in dy:\n\tfor now in nowY:\n\t\tnextY.add(now+num)\n\t\tnextY.add(now-num)\n\tnowY=deepcopy(nextY)\n\tnextY=set([])\nif (x in nowX) and (y in nowY):\n\tprint(\"Yes\")\nelse:\n\tprint(\"No\")\n\n\n\n#10^7なら行けるっしょ\n\"\"\"\ndpX[0][bpos]=True\ndpY[0][bpos]=True\n\nfor i in range(len(dx)):\n\tfor j in range(bpos*2+1):\n\t\tif dpX[i][j]:\n\t\t\tdpX[i+1][j-dx[i]]=True\n\t\t\tdpX[i+1][j+dx[i]]=True\nfor i in range(len(dy)):\n\tfor j in range(bpos*2+1):\n\t\tif dpY[i][j]:\n\t\t\tdpY[i+1][j-dy[i]]=True\n\t\t\tdpY[i+1][j+dy[i]]=True\n#print()\n#for nums in dpX:\n#\tprint(nums)\n#rint()\n#for nums in dpY:\n#\tprint(nums)\nif dpX[len(dx)][bpos+x] and dpY[len(dy)][bpos+y]:\n\tprint(\"Yes\")\nelse:\n\tprint(\"No\")\n\"\"\"\n\n\n","sub_path":"atcoder/arc/080/ARC087D.py","file_name":"ARC087D.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"94840523","text":"# vim: ai ts=4 sts=4 et sw=4\n# encoding=utf-8\nimport locale\nfrom django.contrib import admin\nfrom django.conf import settings\nfrom igreport import util, media\nfrom django.core.exceptions import PermissionDenied\nfrom igreport.models import Report\n\nclass ReportAdmin(admin.ModelAdmin):\n\n list_display = ['sender', 'message', 'accused', 'amount_formatted', 'report_time', 'options']\n list_filter = ['datetime']\n ordering = ['-datetime']\n date_hierarchy = 'datetime'\n search_fields = ['connection__identity', 'reference_number']\n actions = None\n Media = media.JQueryUIMedia\n change_list_template = 'igreport/change_list.html'\n change_list_results_template = 'igreport/change_list_results.html'\n list_per_page = 50\n\n def __init__(self, *args, **kwargs):\n super(ReportAdmin, self).__init__(*args, **kwargs)\n self.list_display_links = (None,)\n\n def report_time(self, obj):\n return obj.datetime.strftime('%d/%m/%Y %H:%M')\n\n report_time.short_description = 'Report Date'\n report_time.admin_order_field = 'datetime'\n\n def message(self, obj):\n text = obj.report\n width = ''\n if text and len(text) > 40:\n width = '280px'\n\n style = 'font-size:13px;'\n if width:\n style += 'width:%s;' % width\n if style:\n style = ' style=\"%s\"' % style\n html = '
%s
' % (obj.id, style, text)\n return html\n\n message.short_description = 'Report'\n message.allow_tags = True\n\n def accused(self, obj):\n text = obj.subject\n width = ''\n if text and len(text) > 40:\n width = '200px'\n\n style = 'font-size:13px;'\n if width:\n style += 'width:%s;' % width\n if style:\n style = ' style=\"%s\"' % style\n if not text:\n text = '(none)'\n html = '%s
' % (style, text)\n return html\n\n accused.short_description = 'Accused'\n accused.allow_tags=True\n\n def sender(self, obj):\n msisdn = obj.connection.identity\n t = (msisdn, msisdn, msisdn)\n html = '%s' % t\n return html\n \n sender.short_description = 'Sender'\n sender.admin_order_field = 'connection'\n sender.allow_tags = True\n\n def amount_formatted(self, obj):\n if obj.amount:\n amount = int(obj.amount)\n locale.setlocale(locale.LC_ALL, '')\n amount = locale.format(\"%d\", amount, grouping=True)\n currency = ''\n if obj.currency:\n currency = obj.currency.code\n amount = '%s' % amount\n if currency:\n amount = '%s%s' % (currency, amount)\n return amount\n return 'NA'\n \n amount_formatted.short_description = 'Amount'\n amount_formatted.admin_order_field = 'amount'\n amount_formatted.allow_tags=True\n\n def options(self, obj):\n\n html = 'Details | Accept' % (obj.id, obj.id)\n\n return html\n\n options.short_description = 'Options'\n options.allow_tags = True\n \n def has_add_permission(self, request):\n return False\n\n def has_delete_permission(self, request, obj=None):\n return False\n\n def change_view(self, request, object_id, extra_context=None):\n raise PermissionDenied\n \n def changelist_view(self, request, extra_context=None):\n title = 'Pending Reports'\n \n ids = [ '{id:%s,completed:%s,synced:%s,closed:%s}' % \\\n (obj.id, 'true' if obj.completed else 'false', \\\n 'true' if obj.synced else 'false', 'true' if obj.closed else 'false') \\\n for obj in self.queryset(self) ]\n js = '[%s]' % ','.join(ids)\n bottom_js = '\\nvar reports=%s;\\nrptsetc();\\n' % js\n \n #bottom_js=''\n buttons = [ dict(label='Refresh', link=''), ]\n context = dict(title=title, include_file='igreport/report.html', bottom_js=bottom_js, buttons=buttons)\n return super(ReportAdmin, self).changelist_view(request, extra_context=context)","sub_path":"igreport_project/igreport_src/igreport/report_admin.py","file_name":"report_admin.py","file_ext":"py","file_size_in_byte":4402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"527758787","text":"\"\"\"Django.db.model-esque API for defining structs.\"\"\"\nimport math, collections\nfrom CodeModule.exc import CorruptedData, InvalidSchema, PEBKAC #these are just empty Exception subclasses\n\nclass CField(object):\n def __init__(self, name = None, container = None, *args, **kwargs):\n if name is not None:\n self.__fieldname = name\n \n self.__container = container\n super(CField, self).__init__(*args, **kwargs)\n\n def extSuper(self, exobject):\n \"\"\"Helper function: Get super of an object we don't know the class of.\n\n Not to be used to call a function of the same name as yourself.\"\"\"\n if \"__bases__\" in exobject.__dict__.keys():\n #this is a class\n return super(exobject, exobject)\n else:\n return super(exobject.__class__, exobject)\n \n def find_argument_field(self, argfieldname):\n \"\"\"Given a dynamic argument name, return the field instance.\n\n This function is the basis of the *_dynamic_argument functions. It\n returns a CField object directly.\"\"\"\n argcontainer = self.__container\n\n while argcontainer != None:\n try:\n return argcontainer.__getfield(argfieldname)\n except:\n argcontainer = argcontainer.__container\n\n #Only raised if the argument field requested does not exist\n raise AttributeError\n\n def alter_dynamic_argument(self, argfieldname, callback):\n arg = self.find_argument_field(argfieldname)\n newarg = callback(arg.core)\n arg.core = newarg\n\n def get_dynamic_argument(self, argfieldname):\n v = self.find_argument_field(argfieldname).core\n return v\n\n def set_dynamic_argument(self, argfieldname, newval):\n self.alter_dynamic_argument(argfieldname, lambda x: newval)\n\n def reparent(self, name = None, container = None):\n #Not sure if this is still needed; since I've eliminated almost all code\n #which moves CFields around between structures/lists.\n if self.__container is not None and container is not None:\n #you must first remove the current container before adding a new one\n #this prevents you from putting the same data in two places\n raise RuntimeError\n\n if name is None:\n del self.__fieldname\n else:\n self.__fieldname = name\n\n self.__container = container\n \n def save(self, fileobj):\n \"\"\"Default implementation of file encoding/saving.\n \n Most CField subclasses can just define the bytes property, and we'll\n just save it automatically.\"\"\"\n fileobj.write(self.bytes)\n \n def load(self, fileobj):\n \"\"\"Default implementation of file parsing/loading.\n \n CField subclasses that can define bytelength before having been loaded,\n i.e. everything that is not a null-terminated string, and have a bytes\n property, can just use this implementation.\n \n If you cannot guarantee the length of a field, make bytelength raise an\n exception when called before loading, and override this load method.\"\"\"\n obytes = fileobj.read(self.bytelength)\n self.bytes = obytes\n \n def parsebytes(self, obytes):\n \"\"\"Default implementation of byte string parsing.\n \n Like CField.load, fields that don't know their size until after they\n have been parsed should override parsebytes with a proper parser for\n that field type.\n \n CField.parsebytes is equivalent to CField.load, but for byte strings\n instead of files. The byte string equivalent to CField.save is the bytes\n property.\n \n The bytes property may have a setter. In this case, the setter method\n property should only accept properly formatted input with no extra bytes\n while parsebytes may accept said input with extra bytes, so long as it\n returns any bytes it does not need.\"\"\"\n self.bytes = obytes[0:self.bytelength]\n return obytes[self.bytelength:-1]\n\n #When this is declared True, Struct and Union will attempt to hide the field\n #entirely from user code by returning the core property in getattribute.\n #If it's False, then the field will not be hidden, so that users may access\n #it's subfields.\n \n #We have PRIMITIVE because in most cases we don't want users moving CFields\n #around directly. CFields exist mainly as wrappers around native Python data\n #objects and users should be working with those. Declaring PRIMITIVE = False\n #indicates that your object has subfields useful to it's users.\n PRIMITIVE = True\n\ndef Magic(magicbytes):\n class MagicInstance(CField):\n def load(self, fileobj):\n fbytes = fileobj.read(len(magicbytes))\n self.bytes = fbytes\n \n @property\n def bytes(self):\n return magicbytes\n \n @bytes.setter\n def bytes(self, obytes):\n if obytes == magicbytes:\n return\n else:\n raise CorruptedData\n \n def parsebytes(self, obytes):\n omagic = obytes[0:len(magicbytes)]\n self.bytes = omagic\n return obytes[len(magicbytes):-1]\n \n @property\n def core(self):\n return magicbytes\n \n @core.setter\n def core(self, val):\n if val != magicbytes:\n raise CorruptedData\n\n return MagicInstance\n\ndef String(encoding = \"utf-8\", terminator = \"\\u0000\"):\n class StringInstance(CField):\n def __init__(self, *args, **kwargs):\n self.__corestr = \"\"\n super(StringInstance, self).__init__(*args, **kwargs)\n \n def load(self, fileobj):\n corestr = []\n while True:\n ltr = fileobj.read(1)\n corestr.append(ltr)\n if (ltr == b\"\\x00\"):\n break\n self.bytes = b\"\".join(corestr)\n \n @property\n def core(self):\n return self.__corestr\n\n @core.setter\n def core(self, val):\n self.__corestr = val\n \n @property\n def bytes(self):\n return self.__corestr.encode(encoding) + b\"\\x00\"\n \n @bytes.setter\n def bytes(self, inbytes):\n if inbytes[-1] != 0:\n raise CorruptedData\n self.__corestr = inbytes[0:-1].decode(encoding)\n \n @property\n def bytelength(self):\n raise PEBKAC #Strings are always variable length null-terminated,\n #and thus cannot have a bytelength\n \n def parsebytes(self, obytes):\n corestr = []\n overindex = 0\n \n for i in range(0, len(obytes)):\n ltr = obytes[i]\n corestr += ltr\n if (ltr == b\"\\x00\"):\n overindex = i + 1\n break\n \n self.bytes = \"\".join(corestr)\n return obytes[overindex:-1]\n \n def __str__(self):\n return self.core\n return StringInstance\n\ndef UnterminatedString(sizeParam, encoding = \"utf-8\", allow_decoding_failure = False):\n \"\"\"Create an instance of a known-length, non-terminated string field.\n \n allow_decoding_failure: If decoding a bytestring fails, type will act as a Blob.\"\"\"\n #Assumes countType = ByteCount for now, add support for EntriesCount later\n class UnterminatedStringInstance(CField):\n def __init__(self, *args, **kwargs):\n self.__corestr = \"\"\n super(UnterminatedStringInstance, self).__init__(*args, **kwargs)\n \n def load(self, fileobj):\n count = sizeParam\n if type(sizeParam) is not int:\n count = self.get_dynamic_argument(sizeParam)\n \n self.bytes = fileobj.read(count)\n \n @property\n def core(self):\n return self.__corestr\n\n @core.setter\n def core(self, val):\n if type(val) is bytes:\n self.bytes = val\n else:\n self.bytes = val.encode(encoding)\n \n @property\n def bytes(self):\n if type(self.__corestr) is not bytes:\n return self.__corestr.encode(encoding)\n else:\n return self.__corestr\n \n @bytes.setter\n def bytes(self, inbytes):\n try:\n if self.bytelength != len(inbytes):\n self.set_dynamic_argument(sizeParam, len(inbytes))\n self.__corestr = inbytes.decode(encoding)\n else:\n self.__corestr = inbytes.decode(encoding)\n except UnicodeDecodeError:\n if allow_decoding_failure:\n if self.bytelength != len(inbytes):\n self.set_dynamic_argument(sizeParam, len(inbytes))\n self.__corestr = inbytes\n else:\n self.__corestr = inbytes\n else:\n raise\n \n @property\n def bytelength(self):\n count = sizeParam\n if type(sizeParam) is not int:\n count = self.get_dynamic_argument(sizeParam)\n \n return count\n \n def parsebytes(self, obytes):\n count = sizeParam\n if type(sizeParam) is not int:\n count = self.get_dynamic_argument(sizeParam)\n \n self.bytes = obytes[:count]\n return obytes[count:-1]\n \n def __str__(self):\n return self.core\n \n return UnterminatedStringInstance\n\nLittleEndian = 0 # 0x12345678 = b'\\x78\\x56\\x34\\x12'\nBigEndian = 1 # 0x12345678 = b'\\x12\\x34\\x56\\x78'\nNetworkEndian = BigEndian\n\nUnsigned = 0 # Binary integers interpreted directly\nSignedTwos = Signed = 1 # High bit on means absolute value is complement of lower bits, plus one\nSignedOnes = 2 # High bit on means absolute value is complement of lower bits\nSignedMagnitude = 3 # High bit on means absolute value is all lower bits\n\ndef Int(size, endianness = BigEndian, signedness = Unsigned):\n \"\"\"Integer parsing class factory.\n\n It's result can also be subclassed. If you are writing a variable-int subclass,\n set size - 1 and override ALL parsing functions.\"\"\"\n bytecount = math.floor(size / 8)\n if size % 8 is not 0 and size is not -1:\n raise InvalidSchema #we only support byte-aligned ints for now\n \n decomp = pow(2,size)\n bitmask = pow(2,size) - 1\n highbit = pow(2,size - 1)\n\n if (size == -1): #support for var-int subclasses\n bitmask = -1\n\n class IntInstance(CField):\n \"\"\"Class which parses ints of arbitrary size, endianness, and sign format.\"\"\"\n def __init__(self, *args, **kwargs):\n self.__coreint = 0\n self.__lengthlock = None\n self.__lengthparam = None\n super(IntInstance, self).__init__(*args, **kwargs)\n \n def load(self, fileobj):\n bytes = fileobj.read(bytecount)\n self.bytes = bytes\n\n def __int__(self):\n return self.__coreint\n \n def tie_to_length(self, length, param = None):\n \"\"\"Establish a relationship between this integer and the length of some parameter.\n \n When this relationship is established, the int will be locked to the\n length of this parameter. All attempts to change it will fail.\n \n This is important for the implementation of the Array field, which\n requires that it's size argument equal it's actual size for correct\n structure encoding.\n \n The lock will break if the field is made to parse new data; this\n indicates that a new structure is going to be parsed and thus the\n tied field must be updated with the new data.\"\"\"\n self.__lengthlock = length\n self.__lengthparam = param\n \n @property\n def core(self):\n if self.__lengthlock is not None:\n if self.__lengthparam is not None:\n return len(self.__lengthlock.__getattribute__(self.__lengthparam))\n return len(self.__lengthlock)\n return self.__coreint\n \n @core.setter\n def core(self, val):\n #If we have a length-lock, all attempts to write to the field with\n #invalid data will fail.\n if self.__lengthlock is not None and self.__lengthparam is not None \\\n and val != len(self.__lengthlock.__getattribute__(self.__lengthparam)):\n raise CorruptedData\n if self.__lengthlock is not None and val != len(self.__lengthlock):\n raise CorruptedData\n self.__coreint = val & bitmask\n \n @property\n def bytes(self):\n data = b''\n \n formattedint = self.__coreint\n if self.__lengthlock is not None:\n if self.__lengthparam is not None:\n formattedint = len(self.__lengthlock.__getattribute__(self.__lengthparam))\n else:\n formattedint = len(self.__lengthlock)\n \n if self.__coreint < 0:\n if signedness is Unsigned:\n #You can't write negative integers to an unsigned field.\n raise CorruptedData\n elif signedness is SignedTwos:\n formattedint = ~abs(formattedint) + 1\n elif signedness is SignedOnes:\n formattedint = ~abs(formattedint)\n elif signedness is SignedMagnitude:\n formattedint = formattedint + highbit\n \n if endianness == LittleEndian:\n for i in range(0, bytecount):\n data += bytes(chr(formattedint >> i * 8 & 0xFF), \"raw_unicode_escape\")\n else:\n for i in range(bytecount, 0, -1):\n data += bytes(chr(formattedint >> (i - 1) * 8 & 0xFF), \"raw_unicode_escape\")\n\n return data\n \n @bytes.setter\n def bytes(self, obytes):\n self.bytesetter(obytes)\n \n def bytesetter(self, obytes):\n \"\"\"MASSIVE HACK used so that Enum can set IntInstance.bytes from within Enum.bytes.setter.\"\"\"\n \n self.__lengthlock = None\n self.__lengthparam = None\n \n result = 0\n if endianness is LittleEndian:\n stride = 1\n begin = 0\n end = bytecount\n if endianness is BigEndian:\n stride = -1\n begin = bytecount - 1\n end = -1\n\n for i in range (begin, end, stride):\n result = result + (obytes[i] << i*8)\n\n if result & highbit != 0:\n if signedness is Unsigned:\n pass\n elif signedness is SignedTwos:\n #since ints are infinitely big 2s compliment, just shifting the bytes in will not\n #give us a negative number since we started with a positive number, and thus py3k will\n #sign extend that erronous highbit foreer. so instead we bitwise decode it to unsigned\n #and arithmetically negate it to change the high bit\n result = result - decomp\n elif signedness is SignedOnes:\n result = result - bitmask\n elif signedness is SignedMagnitude:\n result = -(result - highbit)\n \n self.__coreint = result\n \n return obytes[bytecount:]\n \n def parsebytes(self, obytes):\n self.bytes = obytes[0:bytecount]\n return obytes[bytecount:-1]\n \n @property\n def bytelength(self):\n return bytecount\n\n return IntInstance\n\nLeU8 = BeU8 = U8 = Int(8)\nLeU16 = Int(16, LittleEndian)\nBeU16 = Int(16, BigEndian)\nLeU24 = Int(24, LittleEndian)\nBeU24 = Int(24, BigEndian)\nLeU32 = Int(32, LittleEndian)\nBeU32 = Int(32, BigEndian)\nLeS8 = BeS8 = Int(8, signedness = Signed)\nLeS16 = Int(16, LittleEndian, Signed)\nBeS16 = Int(16, BigEndian, Signed)\nLeS24 = Int(24, LittleEndian, Signed)\nBeS24 = Int(24, BigEndian, Signed)\nLeS32 = Int(32, LittleEndian, Signed)\nBeS32 = Int(32, BigEndian, Signed)\n\nEntriesCount = 0 # Array size is in number of instances of the contained type\nBytesCount = 1 # Array size is in number of encoded bytes in the underlying datablob\nParseToEOF = 2 # Array is continuously parsed until some bytes before EOF.\n\ndef Array(containedType, sizeParam, countType = EntriesCount, *args, **kwargs):\n \"\"\"Array class factory.\n\n CModel arrays can have multiple count types:\n\n EntriesCount - Parse a specific number of entries from sizeParam\n BytesCount - Parse a specific number of bytes from sizeParam\n ParseToEOF - Parse until sizeParam bytes left in the file\n\n sizeParam can be an integer (for fixed-size arrays) or the name of another\n previously-parsed integer parameter in the cmodel.Struct.\"\"\"\n class ArrayInstance(CField, list):\n def __init__(self, *args, **kwargs):\n super(ArrayInstance, self).__init__(*args, **kwargs)\n self.__uniqid = 0\n \n if countType is BytesCount:\n if type(sizeParam) is str:\n self.find_argument_field(sizeParam).tie_to_length(self, \"bytes\")\n elif countType is EntriesCount:\n if type(sizeParam) is str:\n self.find_argument_field(sizeParam).tie_to_length(self)\n \n def load(self, fileobj):\n scount = sizeParam\n if type(sizeParam) is not int:\n scount = self.get_dynamic_argument(sizeParam)\n \n if countType is BytesCount:\n endLoc = scount + fileobj.tell()\n \n while fileobj.tell() < endLoc:\n item = containedType()\n self.append(item)\n \n oldLoc = fileobj.tell()\n item.load(fileobj)\n \n if oldLoc == fileobj.tell():\n #Child types are REQUIRED to consume at least one byte\n #in byte-counted array mode.\n raise InvalidSchema\n \n if type(sizeParam) is str:\n self.find_argument_field(sizeParam).tie_to_length(self, \"bytes\")\n elif countType is EntriesCount:\n for i in range(0, scount):\n item = containedType()\n self.append(item)\n \n item.load(fileobj)\n if type(sizeParam) is str:\n self.find_argument_field(sizeParam).tie_to_length(self)\n elif countType is ParseToEOF:\n #determine end position\n curpos = fileobj.tell()\n fileobj.seek(scount, whence=SEEK_END)\n endpos = fileobj.tell()\n fileobj.seek(curpos, whence=SEEK_SET)\n lastpos = fileobj.tell()\n\n while curpos < endpos:\n lastpos = curpos\n item = containedType()\n self.append(item)\n \n item.load(fileobj)\n curpos = fileobj.tell()\n if lastpos == curpos:\n raise InvalidSchema #we MUST consume SOME bytes in this mode\n \n if curpos > endpos:\n raise CorruptedData #we overwrote some other data\n\n def save(self, fileobj):\n for thing in self:\n thing.save(fileobj)\n \n #The following three items exist specifically to ensure field objects\n #don't escape their parent structures, just the data.\n def __getitem__(self, key):\n #Uncoerce field into core data. Does not support slicing yet.\n if super(ArrayInstance, self).__getitem__(key).PRIMITIVE != False:\n return super(ArrayInstance, self).__getitem__(key).core\n else:\n #If this is an array of structs, do not core them.\n return super(ArrayInstance, self).__getitem__(key)\n\n def __setitem__(self, key, value):\n super(ArrayInstance, self).__getitem__(key).core = value\n \n def __delitem__(self, key):\n super(ArrayInstance, self).__delitem__(key)\n \n def append(self, item):\n if type(item) != containedType:\n #Arrays, unlike Python lists, can only contain one type\n #We'll try to coerce the input into a real type by wrapping it\n nitem = containedType()\n nitem.core = item\n item = nitem\n \n itemname = str(self.__uniqid)\n self.__uniqid += 1\n super(ArrayInstance, self).append(item)\n \n item.reparent(itemname, container = self)\n \n def extend(self, otherlist):\n for item in otherlist:\n self.append(item)\n \n def __add__(self, item):\n self.extend(item)\n return self\n \n def __radd__(self, item):\n self.extend(item)\n return self\n \n def __iadd__(self, item):\n self.extend(item)\n return self\n \n @property\n def bytes(self):\n childbytes = []\n for thing in self:\n childbytes.append(thing.bytes)\n return b\"\".join(childbytes)\n \n @property\n def bytelength(self):\n return len(self.bytes)\n \n def parsebytes(self, obytes):\n scount = sizeParam\n if type(sizeParam) is not int:\n scount = self.get_dynamic_argument(sizeParam)\n \n if countType is EntriesCount:\n items = scount\n for i in range(0,items):\n if (len(obytes) == 0):\n #We ran out of data before parsing was complete.\n raise CorruptedData\n \n childItem = containedType()\n self.append(childItem)\n obytes = childItem.parsebytes(obytes)\n \n if type(sizeParam) is str:\n self.find_argument_field(sizeParam).tie_to_length(self)\n return obytes\n elif countType is BytesCount:\n bytecount = scount\n mybytes = obytes[:bytecount]\n while len(mybytes) > 0:\n #Just keep parsing until we run out of bytes.\n childItem = containedType()\n self.append(childItem)\n \n oldcount = len(mybytes)\n mybytes = childItem.parsebytes(mybytes)\n \n if oldcount == len(mybytes):\n #All Array subtypes must consume at least ONE byte.\n #If the contained type is empty, then parsing it again\n #won't do anything and we will infinitely-loop until\n #we run out of memory.\n raise InvalidSchema\n \n if type(sizeParam) is str:\n self.find_argument_field(sizeParam).tie_to_length(self, \"bytes\")\n return obytes[bytecount:]\n elif countType is ParseToEOF:\n mybytes = b\"\"\n if scount is 0:\n mybytes = obytes\n else:\n mybytes = obytes[:-(scount)]\n\n while len(mybytes) > 0:\n childItem = containedType()\n self.append(childItem)\n \n oldcount = len(mybytes)\n mybytes = childItem.parsebytes(mybytes)\n \n if oldcount == len(mybytes):\n raise InvalidSchema\n return obytes[-(scount):]\n \n @property\n def core(self):\n \"\"\"Core property for ArrayInstance.\n\n Implemented by repacking the whole ArrayInstance into a normal list.\"\"\"\n normallist = []\n for item in self:\n normallist.append(item.core)\n \n return normallist\n\n @core.setter\n def core(self, normallist):\n del self[:]\n \n for item in normallist:\n self.append(item)\n \n #Since this CField is a subtype of list, it doubles as a native Python\n #object and thus should be exposed to the user\n PRIMITIVE = False\n \n return ArrayInstance\n\ndef Blob(sizeParam):\n class BlobInstance(CField):\n def __init__(self, *args, **kwargs):\n self.__obytes = b\"\"\n if type(sizeParam) is int:\n self.__obytes = bytes(sizeParam)\n \n super(BlobInstance, self).__init__(*args, **kwargs)\n \n def load(self, fileobj):\n count = sizeParam\n if type(sizeParam) is not int:\n count = self.get_dynamic_argument(sizeParam)\n \n self.bytes = fileobj.read(count)\n \n @property\n def bytes(self):\n return self.__obytes\n \n @bytes.setter\n def bytes(self, obytes):\n if len(obytes) != len(self.__obytes):\n #WARNING: Assumes non-fixed-length field.\n #If fixed-length, do not send irregularly sized data\n self.set_dynamic_argument(sizeParam, len(obytes))\n self.__obytes = obytes\n else:\n self.__obytes = obytes\n \n def parsebytes(self, obytes):\n count = sizeParam\n if type(sizeParam) is not int:\n count = self.get_dynamic_argument(sizeParam)\n \n self.bytes = obytes[0:count]\n return obytes[count:-1]\n \n @property\n def core(self):\n return self.bytes\n \n @core.setter\n def core(self, nbytes):\n if type(sizeParam) is not int:\n self.set_dynamic_argument(sizeParam, len(nbytes))\n self.bytes = nbytes\n else:\n if count > len(nbytes):\n self.bytes = nbytes[:count] + bytes(count - len(nbytes))\n else:\n self.bytes = nbytes[:count]\n \n @property\n def bytelength(self):\n if type(sizeParam) is not int:\n return self.get_dynamic_argument(sizeParam)\n else:\n return sizeParam\n \n return BlobInstance\n\ndef If(variableName, condition, basetype = None, *args, **kwargs):\n \"\"\"Creates IF-Fields, which only exist if a condition is satisfied in external data.\n \n Can be called in one of two ways:\n \n If(\"name-of-variable\", lambda var: var > 256, OtherType)\n \n where there is a single variablename which is looked up and passed to the\n callable to determine if OtherType should be parsed, or in this way:\n \n If(lambda pStruct: pStruct.group > 0, OtherType)\n \n where the variablename is omitted and \"\"\"\n \n ctxtprov = lambda s, vn: s.get_dynamic_argument(vn)\n \n if basetype == None:\n basetype = condition\n condition = variableName\n variableName = None\n \n ctxtprov = lambda s, vn: s._CField__container\n \n base = None\n if (len(args) == 0 and len(kwargs) == 0):\n base = basetype\n else:\n base = basetype(*args, **kwargs)\n \n class IfInstance(base):\n \"\"\"Conditional load class that turns into an empty value if an external condition is unfulfilled.\"\"\"\n def load(self, fileobj):\n if condition(ctxtprov(self, variableName)):\n super(IfInstance, self).load(fileobj)\n \n def save(self, fileobj):\n if condition(ctxtprov(self, variableName)):\n super(IfInstance, self).save(fileobj)\n \n @property\n def core(self):\n if condition(ctxtprov(self, variableName)):\n return super(IfInstance, self).core\n else:\n return None\n\n @core.setter\n def core(self, val):\n if condition(ctxtprov(self, variableName)):\n super(IfInstance, self).core = val\n\n @property\n def bytes(self):\n if condition(ctxtprov(self, variableName)):\n return super(IfInstance, self).bytes\n else:\n return b\"\"\n\n @bytes.setter\n def bytes(self, val):\n if condition(ctxtprov(self, variableName)):\n super(IfInstance, self).bytesetter(val)\n \n def parsebytes(self, obytes):\n if condition(ctxtprov(self, variableName)):\n return super(IfInstance, self).parsebytes(obytes)\n \n return IfInstance\n\nclass EmptyField(CField):\n \"\"\"Base field class for all fields that do not actually parse bytes from the structure.\"\"\"\n def load(self, fileobj):\n pass\n\n @property\n def bytes(self):\n return b\"\"\n\n @bytes.setter\n def bytes(self, obytes):\n if len(obytes) > 0:\n raise CorruptedData\n \n def parsebytes(self, obytes):\n return obytes\n \n @property\n def core(self):\n return None\n\ndef BitRange(targetParam, fromBits, toBits):\n \"\"\"Define a range of bits shadowed from another field.\n\n The BitRange itself takes up no space, it just reparses existing, already parsed data.\"\"\"\n lomask = pow(2, fromBits) - 1\n bitmask = pow(2, toBits) - 1 - lomask\n clearmask = -1 - bitmask\n if toBits is -1:\n bitmask = -1 - lomask\n clearmask = lomask\n \n #TODO: Make bitrange lock it's targetParam integer\n class BitRangeInstance(EmptyField):\n @property\n def core(self):\n basebits = self.get_dynamic_argument(targetParam)\n ourbits = (basebits & bitmask) >> fromBits\n return ourbits\n \n @core.setter\n def core(self, newbits):\n basebits = self.get_dynamic_argument(targetParam)\n ourbits = ((newbits << toBits) & bitmask) | (basebits & clearmask)\n self.set_dynamic_argument(targetParam, ourbits)\n\n return BitRangeInstance\n\ndef Bias(targetParam, biasFactor):\n \"\"\"Define a field based on another field that returns the first field's value, incremented by a bias value.\"\"\"\n class BiasInstance(EmptyField):\n @property\n def core(self):\n basebits = self.get_dynamic_argument(targetParam)\n ourbits = basebits + biasFactor\n return ourbits\n \n @core.setter\n def core(self, newbits):\n ourbits = newbits - biasFactor\n self.set_dynamic_argument(targetParam, ourbits)\n\ndef Enum(storageType, *valueslist, **kwargs):\n \"\"\"Class factory for the Enum field type.\n \n Notably, this function is responsible for allocating enum values.\n \n You can control enum allocation by specifying iotaUpdate, which is called\n after each unspecified enum value to select a new one. By default this\n increments the enum value so that enum values are allocated in-order.\"\"\"\n iota = 0\n valuesDict = {}\n iotaUpdate = None\n \n try:\n iotaUpdate = kwargs[\"iotaUpdate\"]\n except:\n #By default, increment\n iotaUpdate = lambda x: x+1\n \n for value in valueslist:\n if type(value) is str:\n #insert unspecified enum values\n valuesDict[value] = iota\n iota = iotaUpdate(iota)\n else:\n #insert pre-specified enum values\n valuesDict[value[0]] = value[1]\n iota = iotaUpdate(value[1])\n \n class EnumInstance(storageType):\n \"\"\"Enum class that wraps a storageType.\n \n Requires the wrapped type's values conform to the known set of enum values.\n \n This set of enum values was allocated when the field type was created.\"\"\"\n @property\n def core(self):\n return super(EnumInstance, self).core\n \n @core.setter\n def core(self, val):\n \"\"\"Enum core.fset that restricts input values\"\"\"\n if val not in valuesDict.values():\n raise CorruptedData\n \n storageType.core.fset(self, val)\n \n @property\n def bytes(self):\n return super(EnumInstance, self).bytes\n \n @bytes.setter\n def bytes(self, val):\n \"\"\"Enum bytes.fset that validates parsed data\"\"\"\n oldCore = self.core\n self.bytesetter(val)\n \n if self.core not in valuesDict.values():\n raise CorruptedData\n \n #This exports values into the parent structure, for convenience\n EXPORTEDVALUES = valuesDict\n \n return EnumInstance\n\nclass _CFieldDecl(type):\n \"\"\"[Super, meta] X class for all declarative types.\"\"\"\n def __new__(mcls, name, bases, cdict):\n #All declarative types have subfields\n cdict[\"PRIMITIVE\"] = False\n return super(_CFieldDecl, mcls).__new__(mcls, name, bases, cdict)\n\nclass _Struct(_CFieldDecl):\n \"\"\"Metaclass for all Struct types.\n \n It is responsible for taking the static variables in the structure and\n moving them outside of the class namespace, and taking the exported variables\n from certain fields and placing them in the class namespace (i.e. for enums)\"\"\"\n DEFAULT_BASE_MADE = False\n def __new__(mcls, name, bases, cdict):\n \"\"\"Metaclass that copies order and the named fields into two class-mangled variables.\"\"\"\n if name == \"Struct\" and not mcls.DEFAULT_BASE_MADE:\n #Do nothing if the Struct class hasn't been constructed yet\n mcls.DEFAULT_BASE_MADE = True\n return super(_Struct, mcls).__new__(mcls, name, bases, cdict)\n order = []\n try:\n order = cdict[\"__order__\"]\n del cdict[\"__order__\"]\n\n cfields = {}\n for fieldname in order:\n cfields[fieldname] = cdict[fieldname]\n del cdict[fieldname]\n \n try:\n exVals = cfields[fieldname].EXPORTEDVALUES\n cdict.update(exVals)\n except:\n pass\n \n cdict[\"_Struct__order\"] = order\n cdict[\"_Struct__fields\"] = cfields\n cdict[\"_Struct__coretype\"] = collections.namedtuple(\"_Struct_{}__coretype\".format(name), order)\n except:\n #Check if the class is a subclass of a valid Struct, or if something\n #is up and we should bail out so that the user knows to fix his\n #Struct subclass.\n #Also, this technically does not yet support merging orders,\n #so this is really only useful for subclasses of a struct without\n #any fields. Otherwise you will have to merge your __order__ yourself.\n #TODO: Automatically merge __order__ lists in __mro__ order.\n hasvalidbase = False\n for base in bases:\n if \"_Struct__order\" in base.__dict__.keys():\n hasvalidbase = True\n #copy the superclass data into the child class\n cdict[\"_Struct__order\"] = base._Struct__order\n cdict[\"_Struct__fields\"] = base._Struct__fields\n cdict[\"_Struct__coretype\"] = base._Struct__coretype\n \n if not hasvalidbase:\n #Structs must either have __order__ or valid superclasses with __order__\n raise InvalidSchema\n \n return super(_Struct, mcls).__new__(mcls, name, bases, cdict)\n\nclass Struct(CField, metaclass=_Struct):\n def __init__(self, *args, **kwargs):\n self.__storage = {}\n for field in self.__order:\n self.__storage[field] = self.__fields[field](name = field, container = self)\n \n super(Struct, self).__init__(*args, **kwargs)\n \n def __getattribute__(self, name):\n if name == \"_Struct__order\":\n #practically I can't keep users from altering the struct order\n #without making this class twice as verbose\n #I hope the use of the PEP8-mangling will discourage that\n return super(Struct, self).__getattribute__(name)\n elif name in self.__order:\n field = self.__storage[name]\n if field.PRIMITIVE:\n return field.core\n else:\n return field\n else:\n return super(Struct, self).__getattribute__(name)\n\n def __setattr__(self, name, val):\n if name == \"_Struct__order\":\n raise CorruptedData #we really shouldn't alter the struct order so brazenly\n elif name in self.__order:\n #Since it is possible for a user program to get access to a field\n #object, we should copy core-to-core for fields and direct-to-core\n #for other Python objects.\n try:\n if \"PRIMITIVE\" in val.__dict__.keys():\n self.__storage[name].core = val.core\n else:\n self.__storage[name].core = val\n except AttributeError:\n #Not a class, just do the direct storage method\n self.__storage[name].core = val\n else:\n super(Struct, self).__setattr__(name, val)\n \n def _CField__getfield(self, name):\n \"\"\"Internal function that allows CField to access fields irregardless of PRIMITIVE.\n \n While it is possible for anyone to call this, you should be discouraged\n by the use of the __variable mangling indicating that this function is\n intended for CField and CField only.\"\"\"\n return self.__storage[name]\n \n def __delattr__(self, name):\n #Uh yeah, you aren't deleting stuff from structs. That would change the\n #schema, and binary formats are parsed with a fixed schema.\n raise CorruptedData\n\n def save(self, fileobj):\n for field in self.__order:\n self.__storage[field].save(fileobj)\n\n def load(self, fileobj):\n for field in self.__order:\n self.__storage[field].load(fileobj)\n \n @property\n def bytes(self):\n lisbytes = []\n for field in self.__order:\n lisbytes.append(self.__storage[field].bytes)\n \n return b\"\".join(lisbytes)\n \n @bytes.setter\n def bytes(self, val):\n for field in self.__order:\n val = self.__storage[field].parsebytes(val)\n \n if len(val) > 0:\n #raise an exception if the input was too big\n raise CorruptedData\n \n def parsebytes(self, obytes):\n for field in self.__order:\n obytes = self.__storage[field].parsebytes(obytes)\n \n @property\n def core(self):\n items = []\n for field in self.__order:\n items.append(self.__storage[field].core)\n return self.__coretype(*items)\n \n @core.setter\n def core(self, items):\n \"\"\"Setter method for structs that accepts dictionaries or tuples.\"\"\"\n if type(items) is dict:\n for key, value in items.items():\n self.__storage[key].core = value\n else:\n if len(self.__order) != len(items):\n #we need as many items as there are fields\n raise CorruptedData\n \n for item, field in zip(items, self.__order):\n self.__storage[field].core = item\n\nExternalTag = 0\nInternalTag = 1\n\nclass _Union(_CFieldDecl):\n DEFAULT_BASE_MADE = False\n \n def __new__(mcls, name, bases, cdict):\n if name == \"Union\" and not mcls.DEFAULT_BASE_MADE:\n #Do nothing if the Union class hasn't been constructed yet\n mcls.DefaultBaseMade = True\n return super(_Union, mcls).__new__(mcls, name, bases, cdict)\n #The \"Default\" class is the type of field that gets used for the mapping\n #if the field is unspecified.\n defaultField = EmptyField\n try:\n defaultField = cdict[\"__defaultfield__\"]\n del cdict[\"__defaultfield__\"]\n except:\n pass\n \n #\"External tag\" mode is activated when __tagname__ is defined\n #When __tagname__ is defined, the value of the tag will be parsed at\n #runtime from parent structures (i.e. the dynamic arugments mechanism)\n #otherwise we run in \"Internal tag\" mode, where we allocate space for\n #the field ourselves.\n #You still need to declare the field type.\n try:\n tagname = cdict[\"__tagname__\"]\n del cdict[\"__tagname__\"]\n cdict[\"_Union__tagname\"] = tagname\n cdict[\"_Union__mode\"] = ExternalTag\n except:\n cdict[\"_Union__mode\"] = InternalTag\n \n tag = cdict[\"__tag__\"]\n del cdict[\"__tag__\"]\n cdict[\"_Union__tag\"] = tag\n \n #The tag type is required to export values\n #We need it to generate the type mapping. Really.\n values = tag.EXPORTEDVALUES\n reverseValues = {}\n mapping = {}\n for vname, value in values.items():\n if value in mapping.keys() and cdict[vname] is not cdict[reverseValues[value]]:\n #You are not allowed to generate two different field types\n #for the same enum value.\n raise InvalidSchema\n \n try: #Attempt to fill the mapping with the user-specified field\n mapping[value] = cdict[vname]\n del cdict[vname]\n except: #Otherwise use the default\n mapping[value] = defaultField\n \n try: #reverseValues is a dict of lists, because dicts are not\n #guaranteed to be bijective functions\n reverseValues[value].append(vname)\n except KeyError:\n reverseValues[value] = [vname]\n \n #We also need to import any Enum values into ourself\n try:\n exVals = cfields[vname].EXPORTEDVALUES\n cdict.update(exVals)\n except:\n pass\n \n #Import the exported values from any Enums in our Union.\n cdict.update(values)\n \n cdict[\"_Union__mapping\"] = mapping\n cdict[\"_Union__reverseValues\"] = reverseValues\n cdict[\"_Union__coretype\"] = collections.namedtuple(\"_Union_{}__coretype\".format(name), [\"tag\", \"contents\"])\n\n #\"MissingNO mode\"\n #when __reparse_on_retag__ is enabled, and user code attempts to change\n #the tag, instead of erasing the child field, we instead grab it's bytes\n #and make the new tag's field attempt to parse them.\n try:\n cdict[\"_Union__reparse_on_retag\"] = cdict[\"__reparse_on_retag__\"]\n del cdict[\"__reparsable__\"]\n except:\n cdict[\"_Union__reparse_on_retag\"] = False\n\n return super(_Union, mcls).__new__(mcls, name, bases, cdict)\n\nclass Union(CField, metaclass = _Union):\n \"\"\"Implements a tagged union.\n \n A tagged union is a type which delegates to mulitple different types based\n on a tag value, which specifies which type to delegate to.\n\n It can either specify the tag type and storage directly, or refer to an\n external variable for the tag.\"\"\"\n def __init__(self, *args, **kwargs):\n if self.__mode is InternalTag:\n self.__tagstorage = self.__tag(name = \"__tag__\", container = self)\n self.__fieldstorage = None\n self.__currenttag = None\n elif self.__mode is ExternalTag:\n self.__tagstorage = self.find_argument_field(self.__tagname)\n self.__fieldstorage = self.__mapping[self.__tagstorage.core](name = \"__contents__\", container = self)\n self.__currenttag = self.__tagstorage.core\n \n super(Union, self).__init__(*args, **kwargs)\n \n def load(self, fileobj):\n if self.__mode is InternalTag:\n self.__tagstorage.load(fileobj)\n self.__updatestate()\n self.__fieldstorage.load(fileobj)\n \n @property\n def bytes(self):\n self.__updatestate()\n obytes = b\"\"\n if self.__mode is InternalTag:\n obytes += self.__tagstorage.bytes\n return obytes + self.__fieldstorage.bytes\n \n def parsebytes(self, obytes):\n if self.__mode is InternalTag:\n obytes = self.__tagstorage.parsebytes(obytes)\n self.__updatestate()\n return self.__fieldstorage.parsebytes(obytes)\n \n @property\n def core(self):\n self.__updatestate()\n try:\n return self.__coretype(self.__tag__, self.__fieldstorage.core)\n except AttributeError:\n return self.__coretype(self.__tag__, None)\n \n @core.setter\n def core(self, val):\n if len(val) != 2:\n raise PEBKAC #must give two values, the tag and the contents\n \n self.__tag__ = val[0]\n self.__contents__.core = val[1]\n \n def __updatestate(self):\n \"\"\"This function is called to ensure that the tag value and current field match.\n \n It is usually called when the tag or contents are accessed, to keep them synced.\"\"\"\n if self.__tagstorage.core == self.__currenttag:\n return #nothing needs to be done\n \n if self.__currenttag is None:\n #Tag was not parsed at __init__\n #It better have been parsed by now!!\n self.__currenttag = self.__tagstorage.core\n self.__fieldstorage = self.__mapping[self.__tagstorage.core](name = \"__contents__\", container = self)\n \n newval = self.__tagstorage.core\n if self.__mapping[self.__currenttag] is not self.__mapping[newval]:\n if self.__reparse_on_retag:\n #\"MissingNO\" mode (bytewise reparse)\n #You have to declare __reparse_on_retag__ = True in your class\n #since this is a behavior 99% of users DON'T want.\n oldfield = self.__fieldstorage\n self.__fieldstorage = self.__mapping[newval](name = \"__contents__\", container = self)\n \n #new fields may throw out bytes.\n self.__fieldstorage.parsebytes(oldfield.bytes)\n else:\n self.__fieldstorage = self.__mapping[newval](name = \"__contents__\", container = self)\n \n self.__currenttag = newval\n\n def __getattribute__(self, name):\n if name.startswith(\"_Union\"):\n #psuedoprivate variables are accessed directly\n return super(Union, self).__getattribute__(name)\n elif name == \"__tag__\":\n #__tag__ is a special member\n self.__updatestate()\n return self.__tagstorage.core\n elif name == \"__contents__\":\n #__contents__ will give you the current tag\n self.__updatestate()\n if self.__fieldstorage.PRIMITIVE:\n return self.__fieldstorage.core\n else:\n return self.__fieldstorage\n elif name in self.__tagstorage.EXPORTEDVALUES.keys():\n #naming a field will let you access that field, regardless of the\n #current tag\n if name not in self.__reverseValues[self.__tag__]:\n #check if accessing this field would cause a field change, and\n #if so, change the tag.\n self.__tag__ = self.__mapping[name]\n return self.__contents__\n else:\n #User variable or class/user function\n return super(Union, self).__getattribute__(name)\n\n def __setattr__(self, name, val):\n if name.startswith(\"_Union\"):\n #psuedoprivates are specialcased to avoid recursion\n super(Union, self).__setattr__(name, val)\n elif name == \"__tag__\":\n #setting __tag__ forces the field to change\n self.__tagstorage.core = val\n self.__updatestate()\n elif name == \"__contents__\":\n self.__updatestate()\n\n try:\n if \"PRIMITIVE\" in val.__dict__.keys():\n self.__fieldstorage.core = val.core\n else:\n self.__fieldstorage.core = val\n except AttributeError:\n #Not a class, just do the direct storage method\n self.__fieldstorage.core = val\n elif name in self.__tagstorage.EXPORTEDVALUES.keys():\n tagvalue = self.__tagstorage.EXPORTEDVALUES[name]\n if self.__tag__ != tagvalue:\n self.__tag__ = tagvalue\n self.__contents__ = val\n else:\n super(Union, self).__setattr__(name, val)\n","sub_path":"rip_scripts/CodeModule/cmodel.py","file_name":"cmodel.py","file_ext":"py","file_size_in_byte":49619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"567372027","text":"import os\nimport cv2 as cv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndir = 'D:\\Projects\\Oh\\data\\images\\silhouette\\silhouette'\nsub_dir_names = list()\nfor root, dirs, files in os.walk(dir, topdown=True):\n for name in dirs:\n sub_dir_names.append(name)\n\ntarget_file_names = {}\nfor dir_name in sub_dir_names:\n dir_path= os.path.join(dir, dir_name)\n file_paths = list()\n for file_name in os.listdir(dir_path):\n file_paths.append(os.path.join(dir_path, file_name))\n target_file_names[dir_name] = file_paths\n\n\npath = 'D:\\Projects\\Oh\\data\\images\\silhouette\\\\avg_silhouette_map'\nfor key, value in target_file_names.items():\n imgs = list()\n for file_path in value:\n img = cv.cvtColor(cv.imread(file_path), cv.COLOR_BGRA2GRAY)\n ret, img = cv.threshold(img, 1, 255, cv.THRESH_BINARY)\n img = cv.morphologyEx(img, cv.MORPH_OPEN, cv.getStructuringElement(cv.MORPH_RECT,(4,4)))\n img = img.astype(np.float32)/255\n imgs.append(img)\n\n avg_img = np.zeros(imgs[0].shape, dtype = np.float32)\n for img in imgs:\n avg_img += img\n avg_img /= len(imgs)\n avg_img *= 255\n avg_img = avg_img.astype(np.uint8)\n\n if len(imgs) == 1:\n avg_img = cv.erode(avg_img, cv.getStructuringElement(cv.MORPH_RECT, (30,30)))\n avg_img = cv.GaussianBlur(avg_img, ksize=(49,49), sigmaX=0)\n\n cv.imwrite(os.path.join(path, str(key)+'.png'), avg_img)\n\n","sub_path":"src/python_img/test_code/oh_avg_silhouette.py","file_name":"oh_avg_silhouette.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"312013027","text":"# the docs for the format: https://docs.google.com/spreadsheets/d/1LGEnOfUu5PjuE42dMoEhIRve5rv3vNsBtk-8DWozwdg/edit?ts=5e322488#gid=870428257\n# https://docs.google.com/spreadsheets/d/1raDs8m-Yd_XOFskueqqcMcMxvR2KVhTJg6ILsQXBhnw/edit#gid=121665415\nimport codecs\nfrom datetime import datetime\nnow = datetime.now() # current date and time\n\n#check if the sting contains a number or not;\ndef hasNumbers(inputString): return any(char.isdigit() for char in inputString)\n\n\namazon_unshipped_file = \"20138290295018306.txt\"\n\nfile_stream = codecs.open(amazon_unshipped_file, 'r', 'utf-8')\npdp_file = codecs.open(\"20138290295018306.csv\", 'w', 'utf-16')\npdp_first_line = \"Anrede;Firma;Vorname;Nachname;Land;PLZ;Ort;Straße;Hausnummer;Referenz 1;Telefon;E-Mail;Adresszusatz;Bundesland;Inhalt;Gewicht;default;Referenz 2 \\n\"\npdp_file.write(pdp_first_line) # first write the first line into file:\n\ndef listToString(s):\n # initialize an empty string \n str1 = \" \"\n # return string \n return (str1.join(s))\n\n#https://docs.google.com/spreadsheets/d/1raDs8m-Yd_XOFskueqqcMcMxvR2KVhTJg6ILsQXBhnw/edit#gid=121665415 check here, you will see the mappings.\nsku_dpd_reference_pairs = {\n \"1000\":\"302008\",\n \"1001\":\"160012\",\n \"1002\":\"160007\",\n \"1003\":\"160011\",\n \"1004\":\"2020024\",\n \"1005\":\"270013\",\n \"1006\":\"heater\",\n \"1007\":\"BDZ-168\",\n \"1012\":\"700023\",\n \"1013\":\"270016+270004\",\n \"1014\":\"Trolley-008X/310002/FAMB008X\",\n \"1015-L\":\"302014\",\n \"1015-M\":\"302013\",\n \"1016\":\"302009\",\n \"1017\":\"302012\",\n \"1019-Basic\":\"700016\",\n \"1019-Pro\":\"302011\",\n \"1020-3S\":\"270039\",\n \"1020-5S\":\"270038+270039\",\n \"1021\":\"190038\",\n \"1022\":\"302002\",\n \"1023\":\"190031\",\n \"1024\":\"302010\",\n \"1025\":\"160013\",\n \"1026-Advance\":\"Boat-C\",\n \"1026-Basic\":\"Boat-A\",\n \"1026-Mini\":\"Boat-Mini\",\n \"1026-Pro\":\"Boat-D\",\n \"1027\":\"160019\",\n \"1028\":\"160004\",\n \"1029\":\"160010\",\n \"1030-270\":\"230002\",\n \"1030-290\":\"230003\",\n \"1031-180\":\"230004\",\n \"1031-235\":\"230001\",\n \"1032-Set\":\"210017-Set\",\n \"1032-Standard\":\"210017-Standard\",\n \"1032-Winterskin\":\"210017-Winterskin\",\n \"1033\":\"270036\",\n \"1034\":\"270038\",\n \"1035-Set\":\"210011-Set\",\n \"1035-Standard\":\"210011-Standard\",\n \"1035-Winterskin\":\"210011-Winterskin\",\n \"1036-Single\":\"260003\",\n \"1036-Double\":\"260004\",\n \"1037-Classic\":\"059NEW+DLeg\",\n \"1037-Comfort\":\"059AD(270001)\",\n \"1037-Comfort-Camouflage\":\"270005-Camo\",\n \"1037-Deluxe\":\"270006\",\n \"1038-Classic\":\"059NEW+DLeg\",\n \"1038-Comfort\":\"270001\",\n \"1038-Deluxe\":\"270012\",\n \"1039-Camouflage\":\"4000SK-Camo\",\n \"1039-Schwarz\":\"4000SK-Black\",\n \"1040-Camouflage\":\"6000sk-Camo\",\n \"1040-Schwarz\":\"6000sk-Black\",\n \"1041-R1\":\"Trolley-051-1W/310001/FAMB051\",\n \"1041-R2\":\"Trolley-051-2W/310003\",\n \"1041-R3\":\"Trolley-008X/310002/FAMB008X\",\n \"1042-001\":\"10 ft 2 teilig 2.75 lbs-Camo\",\n \"1042-002\":\"10 ft 2 teilig 2.75 lbs-Black\",\n \"1042-003\":\"10 ft 2 teilig 3 lbs-Camo\",\n \"1042-004\":\"10 ft 2 teilig 3 lbs-Black\",\n \"1042-005\":\"10 ft 3 teilig 2.75 lbs-Camo\",\n \"1042-006\":\"10 ft 3 teilig 2.75 lbs-Black\",\n \"1042-007\":\"10 ft 3 teilig 3 lbs-Camo\",\n \"1042-008\":\"10 ft 3 teilig 3 lbs-Black\",\n \"1042-009\":\"12 ft 3 teilig 3 lbs-Camo\",\n \"1042-010\":\"12 ft 3 teilig 3 lbs-Black\",\n \"1042-011\":\"12 ft 3 teilig 3.5 lbs-Camo\",\n \"1042-012\":\"12 ft 3 teilig 3.5 lbs-Black\",\n \"1043-LG\":\"FL-01-Green-Large\",\n \"1043-LS\":\"FL-01-Black-Large\",\n \"1043-MG\":\"FL-01-Green-Small\",\n \"1043-MS\":\"FL-01-Black-Small\",\n \"1044-Classic 696921\":\"270016\",\n \"1044-Comfort 736120\":\"270024\",\n \"1044-Comfort 746523\":\"270023\",\n \"1044-Comfort 786821\":\"270019\",\n \"1044-Deluxe 716521\":\"270031\",\n \"1044-Deluxe 736319\":\"270025\",\n \"1044-Transporttasche\":\"190035\",\n \"1045-PARENT\":\"270020\",\n \"2X-KD4H-M022\":\"FA214-4+4SW02\",\n \"AP-978G-XXFK\":\"270005\",\n \"C9-KRTX-RO2C\":\"270025\",\n \"JX-9LRX-UUZA\":\"FA02-4\",\n \"YS-RMGJ-0IZT\":\"270025\",\n \"210014\":\"210014\"\n}\n\ni = 0\nfor l in file_stream:\n i=i+1\n if (i==1): # not need the first line\n None\n else:\n list_from_amzon = l.split(\"\\t\")\n recipient_name = list_from_amzon[16]\n ship_address_1 = list_from_amzon[17]\n ship_address_2 = list_from_amzon[18]\n ship_address_3 = list_from_amzon[19]\n ship_postal_code =list_from_amzon[22]\n ship_city =list_from_amzon[20]\n ship_country =list_from_amzon[23].replace(\"\\r\\n\", \"\") # remove the enter \n buyer_phone_number =list_from_amzon[9]\n buyer_email =list_from_amzon[7]\n buyer_name =list_from_amzon[8]\n sku=list_from_amzon[10]\n order_id=list_from_amzon[0]\n dpd_reference = sku_dpd_reference_pairs.get(sku, \"Not Find. please check photo with this amazon_order_id = {}, sku = {}\".format(order_id, sku))\n product_name = list_from_amzon[11]\n # print(dpd_reference)\n # print(product_name)\n # print(recipient_name)\n # print(ship_address_1)\n # print(ship_postal_code)\n # print(ship_city)\n # print(ship_country)\n # print(buyer_phone_number)\n # print(buyer_email)\n\n name = recipient_name#\"Denis Potemin-2\"\n Firm = \"\" #if(hasNumbers(ship_address_1)) else ship_address_1 # if the address do not have number, then it is the company.\n Hausnummer = ship_address_1.split(' ')[-1] #if(hasNumbers(ship_address_1)) else ship_address_1 # if the address do not have number, then it is the company.\n address_1 = listToString(ship_address_1.split(' ')[:-1]) #if(hasNumbers(ship_address_1)) else ship_address_1 # if the address do not have number, then it is the company.\n strasse = (address_1+\" \"+ship_address_2+\" \"+ship_address_3) #if(hasNumbers(ship_address_1)) else (ship_address_2+\" \"+ship_address_3)\n PLZ = ship_postal_code #\"95336\"\n Ort = ship_city #\"Mainleus\"\n Land = ship_country#\"DEU\"\n Telefon=buyer_phone_number #\"015226395381019-Basic9\"\n E_Mail= buyer_email #\"fischenundmehr@gmail.com\"\n reference2 = order_id # before it is the `buyer_name` ,now it is the Referenz 2: in the 面单.\n Referenz = dpd_reference #this is the Referenz 1: in the 面单.\n Inhalt = \"\"#product_name\n Versanddatum =now.strftime(\"%d.%m.%Y %H:%M:%S\")\n if(sku ==\"1013\"): #1013\t046+021\t(这个需要两个面单,同一个人两个货)\n dataFirstLine = \";{};{};;{};{};{};{};{};{};{};{};;;{};;;{}; \\n\".format(Firm, name, Land, PLZ, Ort, strasse, Hausnummer, \"270016\", Telefon, E_Mail, Inhalt, reference2)\n pdp_file.write(dataFirstLine)\n dataFirstLine = \";{};{};;{};{};{};{};{};{};{};{};;;{};;;{}; \\n\".format(Firm, name, Land, PLZ, Ort, strasse, Hausnummer, \"270004\", Telefon, E_Mail, Inhalt, reference2)\n pdp_file.write(dataFirstLine)\n else: \n dataFirstLine = \";{};{};;{};{};{};{};{};{};{};{};;;{};;;{}; \\n\".format(Firm, name, Land, PLZ, Ort, strasse, Hausnummer, Referenz, Telefon, E_Mail, Inhalt, reference2)\n pdp_file.write(dataFirstLine)\n\nfile_stream.close()\npdp_file.close()","sub_path":"CarptourDe/changeAmazonToDpdOrders.py","file_name":"changeAmazonToDpdOrders.py","file_ext":"py","file_size_in_byte":7113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"245848070","text":"from django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\nfrom apps.telegram_bot.tasks import upload_file\nfrom .models import CampaignUser, CampaignFile\nfrom .tasks import send_paid_push\n\n\n@receiver(post_save, sender=CampaignFile)\ndef upload_save_file_id(sender, instance, created, **kwargs):\n if not instance.telegram_file_hash:\n upload_file.apply_async(args=[instance.id], countdown=1)\n\n\n@receiver(post_save, sender=CampaignUser)\ndef paid_push_notification(sender, instance, created, **kwargs):\n if not created and instance.has_receipt_date_changed():\n send_paid_push.delay(\n instance.user.user_id,\n instance.agent.bot_token,\n instance.campaign.title,\n instance.push_channels_context()\n )\n","sub_path":"apps/telegram_adv/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"343612081","text":"import os\nimport string\nimport unicodedata\nimport pandas as pd\nfrom multiprocessing import Pool\n\nfrom bidi.algorithm import get_display\nfrom arabic_reshaper import arabic_reshaper\nfrom nltk.tag.stanford import StanfordPOSTagger\n\nroot = \"C:/Users/arian.milanian/Documents\"\nos.environ['JAVAHOME'] = \"{}/JRE8/bin\".format(root)\n\ndef reshape_arabic(text):\n text = arabic_reshaper.reshape(text)\n text = get_display(arabic_reshaper.reshape(text))\n return text\n\ndef get_tags(chunk):\n lang, words = list(chunk.items())[0]\n models = {\"english\": \"english-bidirectional-distsim.tagger\", \"arabic\": \"arabic.tagger\" }\n tagger = StanfordPOSTagger(\"{}/stanford-pos/models/{}\".format(root, models[lang]),\n \"{}/stanford-pos/stanford-postagger.jar\".format(root), encoding=\"utf-8\")\n return [tag[1].rsplit(\"/\",1) for tag in tagger.tag(words)]\n \ndef is_arabic(word):\n word = word.translate(str.maketrans(\"\",\"\",string.punctuation))\n return \"ARABIC\" in unicodedata.name(word[0]) if word else False\n \ndef iter_chunks(words, lang, n):\n return [{lang: words[i:i+n]} for i in range(0, len(words), n)]\n \nif __name__ == \"__main__\":\n data = pd.read_csv(\"../output/small.csv\", encoding=\"utf-8\")\n tweets = data[\"norm.body\"].tolist()\n wordmap = {\"arabic\":[], \"english\":[]}\n for word in set(\"\".join(tweets).split()):\n wordmap[\"arabic\" if is_arabic(word) else \"english\"].append(word)\n for lang, words in wordmap.items():\n tags = Pool().map(get_tags, iter_chunks(words, lang, 2500))\n open(\"../output/{}-tags.txt\".format(lang), \"w\", encoding=\"utf-8\").write(\",\".join([\"{} {}\".format(x, y) for tag in tags for x, y in tag]))\n break\n","sub_path":"notebooks/arabic_pos_tagger.py","file_name":"arabic_pos_tagger.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"152430368","text":"\"\"\"This file is a Beeline spider created on top of the ATSSpider\nscrapy crawl beeline -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"http://www.beeline-group.com/en/careers/job_vacancies.html\"\n\nsample url:\n http://www.beeline-group.com/en/careers/job_vacancies.html\n\"\"\"\n\nfrom urlparse import urljoin\nfrom re import compile\n\nfrom scrapy.http import FormRequest\nfrom scrapy.selector import Selector\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, NormalizedJoin\n\n\nclass Beeline(ATSSpider):\n\n name = 'beeline'\n num_re = compile(r\"(\\d+)\")\n headers = {\n 'X-Requested-With': 'XMLHttpRequest',\n 'Content-Type': 'application/x-www-form-urlencoded',\n }\n\n def parse(self, response):\n sel = Selector(response)\n if not hasattr(self, 'logo_url'):\n logo_url = sel.xpath('//img[@id=\"logo\"]/@src').extract()\n self.logo_url = urljoin(response.url, logo_url[0]) if logo_url else ''\n\n countries = sel.xpath(\n '//ul[@id=\"selFilterCountry_list\"]/li'\n )\n for coun in countries:\n country_id = coun.xpath('./@onclick').re(self.num_re)\n if country_id:\n yield FormRequest(\n response.url, callback=self.parse_jobs_list,\n formdata={\n 'type': '4',\n 'act': 'getJobList',\n 'country': '%s' % country_id[0],\n },\n headers=self.headers,\n meta={\n 'country': coun.xpath('./text()').extract(),\n 'country_id': country_id[0],\n }\n )\n\n def parse_jobs_list(self, response):\n sel = Selector(response)\n jobs = sel.xpath('//div[@id=\"joblistjobs\"]/div')\n for job in jobs:\n job_id = job.xpath('./@id').re(self.num_re)\n if job_id:\n meta = {\n 'title': job.xpath(\n './/div[@class=\"col col0\"]/text()'\n ).extract(),\n 'jobtype': job.xpath(\n './/div[@class=\"col col2\"]/text()'\n ).extract(),\n 'location': job.xpath(\n './/div[@class=\"col col3\"]/text()'\n ).extract() + response.meta.get('country'),\n 'ref_num': job_id[0],\n 'url': self.start_urls[0] + '?job=%s' % job_id[0]\n }\n yield FormRequest(\n response.url, callback=self.parse_job_callback(),\n formdata={\n 'type': '4',\n 'act': 'getJobDetail',\n 'country': '%s' % response.meta.get('country_id'),\n 'job': '%s' % job_id[0],\n },\n meta=meta\n )\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n loader.add_value('logo_url', self.logo_url)\n loader.add_value('url', response.meta.get('url'))\n loader.add_value('title', response.meta.get('title'))\n loader.add_value('jobtype', response.meta.get('jobtype'))\n loader.add_value(\n 'location', response.meta.get('location'), NormalizedJoin(\", \")\n )\n loader.add_value(\n 'referencenumber', response.meta.get('ref_num'),\n Prefix('%s-' % self.name)\n )\n loader.add_xpath('description', '//div[@class=\"jobform\"]')\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/beeline.py","file_name":"beeline.py","file_ext":"py","file_size_in_byte":3742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"431949292","text":"import math\n\nimport numpy as np\n\nprint(\"Naive Bayes Classificator for male/female classification\")\nprint(\"See https://en.wikipedia.org/wiki/Naive_Bayes_classifier#Sex_classification for details.\")\n\n# arguments\n\nprior_m = 0.5\nprior_f = 1 - prior_m\n\n\ndef get_gaussian_probability(x: float, mean: float, sigma_square: float) -> float:\n return (1 / (math.sqrt(2 * math.pi * sigma_square))) * math.exp(-1 * (pow(x - mean, 2) / (2 * sigma_square)))\n\n\ndef get_posterior_probability(prior: float, sample: np.ndarray, means: np.ndarray, variances: np.ndarray):\n # because each feature is conditionally independent of all other features,\n # the posterior probability for the class equals to the product of all feature probabilities\n\n prob = prior\n\n for f_i in range(sample.size):\n prob *= get_gaussian_probability(sample.item(f_i), means.item(f_i), variances.item(f_i))\n\n return prob\n\n\ndef get_variances(c: np.ndarray, means: np.ndarray) -> np.ndarray:\n x_i_squares = np.multiply(1.0 / len(c), np.sum(np.multiply(c, c), axis=0))\n return np.subtract(x_i_squares, np.multiply(means, means))\n\n\ndef get_means(c: np.ndarray) -> np.ndarray:\n return np.multiply(1.0 / len(c), np.sum(c, axis=0))\n\n\n# data\n\nsamples = np.matrix(([6, 180, 12], [5.92, 190, 11],\n [5.58, 170, 12], [5.92, 165, 10],\n [5, 100, 6], [5.5, 150, 8],\n [5.42, 130, 7], [5.75, 150, 9]))\n\nsamples_m = samples[:4]\nsamples_f = samples[4:]\n\n# ~ training by learning means and variances for each class\n\nmale_means = get_means(samples_m)\nfemale_means = get_means(samples_f)\n\nmale_variances = get_variances(samples_m, male_means)\nfemale_variances = get_variances(samples_f, female_means)\n\nprint(\"P(male)={}\".format(prior_m))\nprint(\"P(female)={}\".format(prior_f))\n\nprint(\"Male means for each feature: {}\".format(male_means))\nprint(\"Female means for each feature: {}\".format(female_means))\n\nprint(\"Male variances for each feature: {}\".format(male_variances))\nprint(\"Female variances for each feature: {}\".format(female_variances))\n\n# classification of unknown sample\n\nvalidation_sample = np.matrix([[6, 130, 8]])\n\nposterior_male = get_posterior_probability(prior_m, validation_sample, male_means, male_variances)\nposterior_female = get_posterior_probability(prior_f, validation_sample, female_means, female_variances)\n\nprint(\"P(x|male)= {}\".format(posterior_male))\nprint(\"P(x|female)={}\".format(posterior_female))\n\nif posterior_male > posterior_female:\n print(\"x should be classified as male\")\nelif posterior_female > posterior_male:\n print(\"x should be classified as female\")\nelse:\n print(\"the probability for each class is equal\")","sub_path":"naive_bayes.py","file_name":"naive_bayes.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"501195943","text":"# -*- coding:utf-8 -*-\r\nfrom selenium import webdriver\r\nfrom email.mime.image import MIMEImage\r\nimport datetime\r\nimport os\r\nimport send_email\r\nimport send_dooray\r\nimport datetime\r\n\r\n\r\ndef go():\r\n\r\n\t#===================================================#\r\n\t#메일에 들어갈 내용\r\n\tmail_body = {}\r\n\tabort_date = \"N\"\r\n\tabort_thing = \"N\"\r\n\tabort_why = \"N\"\r\n\r\n\t#오늘날짜\r\n\ttoday = datetime.datetime.now()\r\n\t#===================================================#\r\n\r\n\tdriver = webdriver.Chrome()\r\n\tdriver.get(\"https://www.safedriving.or.kr/main.do\")\r\n\r\n\t#화면 최대화\r\n\tdriver.maximize_window()\r\n\r\n\t#스크린샷\r\n\tfilename = os.getcwd() + \"/todayscreen\" + \".png\"\r\n\tshot = driver.get_screenshot_as_file(filename)\r\n\r\n\t#MIMEImage로 변환 \r\n\tfp = open(filename, 'rb')\r\n\tcontext = fp.read()\r\n\timg = MIMEImage(context)\r\n\tcontext = str(context)\r\n\tfp.close()\r\n\r\n\tis_write = True\r\n\t#이전 시간에 보냈는지 확인\r\n\twith open('safedriving.txt', mode='a+', encoding='utf8') as title_file:\r\n\t\ttitle_file.seek(0)\r\n\t\ttempline = title_file.read()\r\n\t\t#파일에 내용이 없으면 False\r\n\t\tif not templine: \r\n\t\t\tis_write = False\r\n\t\t#기존에 읽었으면 True\r\n\t\tif( context == templine):\r\n\t\t\tis_write = True\r\n\t\t\t\t\r\n\tif is_write is False : \r\n\t\twith open('safedriving.txt', mode='w', encoding='utf8') as title_file:\r\n\t\t\ttitle_file.write(context)\r\n\t\tsend_email.send(\"도로교통공단 안전운전 통합민원\",dict=[], attach_img=img)\r\n\r\n\tdriver.quit()","sub_path":"FlyHigh_Personal_Project_ParkSeHwan/safedriving.py","file_name":"safedriving.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"245066347","text":"#################### IMPORTS #################### \nimport numpy as np \nimport os\nimport skimage.io as io\nimport skimage.transform as trans\nfrom keras.models import *\nfrom keras.layers import *\nfrom keras.optimizers import *\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras import backend as keras\n\nimport utils\nimport ni_utils\n\n# from focal_loss.losses import *\n# import dill\n\nfrom deep_learning.DataGeneratorClass import *\nfrom deep_learning.base_networks import *\n# from deep_learning.parameters import *\nfrom deep_learning.inception_networks import *\nfrom deep_learning.residualAttentionNetworkModels import *\nfrom deep_learning.loss_functions import quantile_loss\nfrom keras.constraints import NonNeg\n\nfrom dunet_model import *\n\nimport tensorflow as tf\nfrom keras.backend.tensorflow_backend import set_session\nfrom keras.losses import categorical_hinge, hinge, squared_hinge, hinge, binary_crossentropy\nfrom CLR.clr_callback import *\n\n#Set up GPU environment\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]= \"4\"\n\nconfig = tf.compat.v1.ConfigProto()\nconfig.gpu_options.allow_growth = True\nconfig.gpu_options.per_process_gpu_memory_fraction = 1\n\n\n#################### LOSSES ####################\n#Losses taken from https://lars76.github.io/neural-networks/object-detection/losses-for-segmentation/\ndef dice_loss(y_true, y_pred):\n numerator = 2 * tf.reduce_sum(y_true * y_pred, axis=(1,2,3))\n denominator = tf.reduce_sum(y_true + y_pred, axis=(1,2,3))\n\n return 1 - numerator / denominator\n\ndef loss(y_true, y_pred):\n def dice_loss(y_true, y_pred):\n numerator = 2 * tf.reduce_sum(y_true * y_pred, axis=(1,2,3))\n denominator = tf.reduce_sum(y_true + y_pred, axis=(1,2,3))\n\n return tf.reshape(1 - numerator / denominator, (-1, 1, 1))\n\n return binary_crossentropy(y_true, y_pred) + dice_loss(y_true, y_pred)\n\n#################### PARAMETERS AND DIRECTORIES ####################\n#Parameters\ntrain_params_multiclass = {'normalize': False,\n 'batch_size': 16,\n 'n_classes': 1,\n 'n_channels': 1,\n 'shuffle': True}\n\n#Directories\nBASE_DIR = '/nfsshare/gianca-group/dpena3/active_learning/ATLAS_feb2020'\nDATA_DIR = ''\nPERCENT_FOLDER = 'test5'\ndataDir = BASE_DIR + '/pre-processing/data_model-ready/' + DATA_DIR\nimgDir = dataDir\n\n#Dataframe\nfileIn = '../pre-processing/ATLAS_stroke_labels_20200122.csv'\n# fileIn = '../pre-processing/ATLAS_stroke_regression_20200223.csv' #has lesion areas in it\n\n#################### DATAFRAMES ####################\nxlsFilepath = fileIn\npatFr = ni_utils.loadSubjGt(fileIn, 'stroke_ct') \npatFr = patFr[patFr['labels'] == 1][:600] #get only stroke\n# patFr = patFr[patFr[patFr['label'] == 1]['lesion_area'].values > 1500] #get only large strokes\npatIDList = patFr['filename'].tolist()\npatFr_labels = patFr['labels'].tolist()\n\nprint('Number of subjects', len(patIDList))\n\n#################### MODEL INPUTS ####################\n#Imput image\n# input_dim = (192, 192, 1) #regular unet\ninput_dim = (192, 192, 4) #dunet\n\ninput_dim_for_data_gen = input_dim\n\n#Generator\ntrain_generator = DataGenerator_stroke_d_unet(patIDList,\n '',\n data_dir=dataDir,\n xls_filepath = xlsFilepath,\n dim=input_dim_for_data_gen,\n **train_params_multiclass)\n#Regular unet DataGenerator_stroke_unet\n#DUNET DataGenerator_stroke_d_unet\n\n#Model\nmodel = Unet3d()\nmodel.compile(optimizer = Adam(lr = 1e-5), loss = dice_loss, metrics = ['accuracy'])\nprint(model.summary())\nnEpochs = 30\n\n#D_Unet\n#Unet_origin\n#Unet3d\n\n#Model saving directory\nnetwork_model_dir = BASE_DIR + '/model/saved_models/'\nFILEPATH_MODEL = \"multiclass_weights_siamese_merge_L1_inception\" + \".hdf5\"\nFILEPATH_MODEL = os.path.join(network_model_dir, PERCENT_FOLDER, FILEPATH_MODEL)\n\nfinal_folder_path = os.path.join(network_model_dir, PERCENT_FOLDER)\nif not os.path.exists(final_folder_path):\n os.makedirs(final_folder_path)\n\n#Callbacks\ncallbacks_list = [ModelCheckpoint(FILEPATH_MODEL,\n monitor='loss',\n verbose=1,\n save_best_only=True,\n mode='auto')]\n\n#################### TRAIN ####################\n#Train\nmodel.fit_generator(generator=train_generator,\n verbose=1,\n epochs=nEpochs,\n callbacks=callbacks_list,\n use_multiprocessing=False,\n workers=4)","sub_path":"flask_unet/unet/stroke_segmentation.py","file_name":"stroke_segmentation.py","file_ext":"py","file_size_in_byte":4549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"174765898","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport os\nimport glob\nimport re\nimport sys\nimport urllib\nimport tarfile\nimport zipfile\nimport os.path as osp\nfrom scipy.io import loadmat\nimport numpy as np\nimport h5py\nfrom scipy.misc import imsave\n\nfrom torchreid.utils.iotools import mkdir_if_missing, write_json, read_json\n\n\nclass VIPeR(object):\n \"\"\"\n VIPeR\n\n Reference:\n Gray et al. Evaluating appearance models for recognition, reacquisition, and tracking. PETS 2007.\n\n URL: https://vision.soe.ucsc.edu/node/178\n \n Dataset statistics:\n # identities: 632\n # images: 632 x 2 = 1264\n # cameras: 2\n \"\"\"\n dataset_dir = 'viper'\n\n def __init__(self, root='data', split_id=0, verbose=True, **kwargs):\n super(VIPeR, self).__init__()\n self.dataset_dir = osp.join(root, self.dataset_dir)\n self.dataset_url = 'http://users.soe.ucsc.edu/~manduchi/VIPeR.v1.0.zip'\n self.cam_a_path = osp.join(self.dataset_dir, 'VIPeR', 'cam_a')\n self.cam_b_path = osp.join(self.dataset_dir, 'VIPeR', 'cam_b')\n self.split_path = osp.join(self.dataset_dir, 'splits.json')\n\n self._download_data()\n self._check_before_run()\n \n self._prepare_split()\n splits = read_json(self.split_path)\n if split_id >= len(splits):\n raise ValueError(\"split_id exceeds range, received {}, but expected between 0 and {}\".format(split_id, len(splits)-1))\n split = splits[split_id]\n\n train = split['train']\n query = split['query'] # query and gallery share the same images\n gallery = split['gallery']\n\n train = [tuple(item) for item in train]\n query = [tuple(item) for item in query]\n gallery = [tuple(item) for item in gallery]\n \n num_train_pids = split['num_train_pids']\n num_query_pids = split['num_query_pids']\n num_gallery_pids = split['num_gallery_pids']\n \n num_train_imgs = len(train)\n num_query_imgs = len(query)\n num_gallery_imgs = len(gallery)\n\n num_total_pids = num_train_pids + num_query_pids\n num_total_imgs = num_train_imgs + num_query_imgs\n\n if verbose:\n print(\"=> VIPeR loaded\")\n print(\"Dataset statistics:\")\n print(\" ------------------------------\")\n print(\" subset | # ids | # images\")\n print(\" ------------------------------\")\n print(\" train | {:5d} | {:8d}\".format(num_train_pids, num_train_imgs))\n print(\" query | {:5d} | {:8d}\".format(num_query_pids, num_query_imgs))\n print(\" gallery | {:5d} | {:8d}\".format(num_gallery_pids, num_gallery_imgs))\n print(\" ------------------------------\")\n print(\" total | {:5d} | {:8d}\".format(num_total_pids, num_total_imgs))\n print(\" ------------------------------\")\n\n self.train = train\n self.query = query\n self.gallery = gallery\n\n self.num_train_pids = num_train_pids\n self.num_query_pids = num_query_pids\n self.num_gallery_pids = num_gallery_pids\n\n def _download_data(self):\n if osp.exists(self.dataset_dir):\n print(\"This dataset has been downloaded.\")\n return\n\n print(\"Creating directory {}\".format(self.dataset_dir))\n mkdir_if_missing(self.dataset_dir)\n fpath = osp.join(self.dataset_dir, osp.basename(self.dataset_url))\n\n print(\"Downloading VIPeR dataset\")\n urllib.urlretrieve(self.dataset_url, fpath)\n\n print(\"Extracting files\")\n zip_ref = zipfile.ZipFile(fpath, 'r')\n zip_ref.extractall(self.dataset_dir)\n zip_ref.close()\n\n def _check_before_run(self):\n \"\"\"Check if all files are available before going deeper\"\"\"\n if not osp.exists(self.dataset_dir):\n raise RuntimeError(\"'{}' is not available\".format(self.dataset_dir))\n if not osp.exists(self.cam_a_path):\n raise RuntimeError(\"'{}' is not available\".format(self.cam_a_path))\n if not osp.exists(self.cam_b_path):\n raise RuntimeError(\"'{}' is not available\".format(self.cam_b_path))\n\n def _prepare_split(self):\n if not osp.exists(self.split_path):\n print(\"Creating 10 random splits\")\n\n cam_a_imgs = sorted(glob.glob(osp.join(self.cam_a_path, '*.bmp')))\n cam_b_imgs = sorted(glob.glob(osp.join(self.cam_b_path, '*.bmp')))\n assert len(cam_a_imgs) == len(cam_b_imgs)\n num_pids = len(cam_a_imgs)\n print(\"Number of identities: {}\".format(num_pids))\n num_train_pids = num_pids // 2\n\n splits = []\n for _ in range(10):\n order = np.arange(num_pids)\n np.random.shuffle(order)\n train_idxs = order[:num_train_pids]\n test_idxs = order[num_train_pids:]\n assert not bool(set(train_idxs) & set(test_idxs)), \"Error: train and test overlap\"\n\n train = []\n for pid, idx in enumerate(train_idxs):\n cam_a_img = cam_a_imgs[idx]\n cam_b_img = cam_b_imgs[idx]\n train.append((cam_a_img, pid, 0))\n train.append((cam_b_img, pid, 1))\n\n test = []\n for pid, idx in enumerate(test_idxs):\n cam_a_img = cam_a_imgs[idx]\n cam_b_img = cam_b_imgs[idx]\n test.append((cam_a_img, pid, 0))\n test.append((cam_b_img, pid, 1))\n\n split = {'train': train, 'query': test, 'gallery': test,\n 'num_train_pids': num_train_pids,\n 'num_query_pids': num_pids - num_train_pids,\n 'num_gallery_pids': num_pids - num_train_pids\n }\n splits.append(split)\n\n print(\"Totally {} splits are created\".format(len(splits)))\n write_json(splits, self.split_path)\n print(\"Split file saved to {}\".format(self.split_path))\n\n print(\"Splits created\")\n","sub_path":"torchreid/data_manager/viper.py","file_name":"viper.py","file_ext":"py","file_size_in_byte":6163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"320023133","text":"import logging\r\n\r\n#to save the messages in a particular location instead of displaying it in the console\r\nlogging.basicConfig(filename=\"C:\\\\seleniumLogs\\\\test.log\",\r\n format='%(asctime)s: %(levelname)s: %(message)s',\r\n datefmt='%m/%d/%Y %I:%M:%S %p') #set time and date format\r\n\r\nlogger=logging.getLogger() #creating this variable will allow us to use it instead of logging object\r\nlogger.setLevel(logging.DEBUG) #an alternative method to set message level\r\n\r\n#by default the debug and info messages are not printed as they are not serious enough.. printing starts from warning message onwards\r\nlogger.debug(\"This is a debug message.\")\r\nlogger.info(\"This is an info message.\")\r\n\r\n#the following messages are printed due to their severity level\r\nlogger.warning(\"This is a warning message.\")\r\nlogger.error(\"This is an error message.\")\r\nlogger.critical(\"This is a critical message.\")","sub_path":"loggingDemo2.py","file_name":"loggingDemo2.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"312444179","text":"import nltk\nfrom string import punctuation\n\nnltk.download()\n\n\ndef preprocessamento(docs):\n \"Preprocessa os documentos da lista docs para a lista docsp, eliminando stopwords, pontuação e 1 unico caracter.\"\n # Pre-processamento de uma lista de documentos\n # docs = []\n docsp = []\n print(\"=========================Preprocessamento de Documentos=========================\")\n print(\"================================================================================\")\n caracteres = ['!', '?', ',', '.', ':', ';', '-', '/', '_', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '(', ')', '[', ']', '{', '}']\n\n for d in docs:\n # Remoção de pontuação\n for p in caracteres:\n d = d.replace(p, \"\")\n d = d.replace(\"\\n\", \" \")\n d = d.replace(\"\\r\", \"\")\n d = d.strip()\n # Remoção de caixa alta\n d = d.lower()\n # Quebra por palavras\n d = d.split(\" \")\n docsp.append(d)\n print(\"Doc:\", d)\n\n stopwords = []\n stopwords = set(nltk.corpus.stopwords.words('portuguese') + list(punctuation))\n\n for d in docsp:\n for p in d:\n if p in stopwords:\n d.remove(p)\n elif len(p) <= 1:\n d.remove(p)\n # print(\"Doc:\", d)\n print(\"================================================================================\")\n\n return docsp","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"367546260","text":"import pretty_midi\n# Create a PrettyMIDI object\n# Pretty MIDIオブジェクトを作る。\ncello_c_chord = pretty_midi.PrettyMIDI()\n\n# Create an Instrument instance for a cello instrument\n# Instrument Instanceを作る。ここではCello\n\n# 楽器名を入れると、対応するGeneral MIDI program numberを返してくれる\ncello_program = pretty_midi.instrument_name_to_program('Cello')\n\n\n# Instrument instanceをCelloとして作成\ncello = pretty_midi.Instrument(program=cello_program)\n\n\n# Iterate over note names, which will be converted to note number later\n# メロディをNoteNameで記載していますが、後ほどNoteNumberに変換されます。\n\nfor note_name in ['C5', 'E5', 'G5']:\n # Retrieve the MIDI note number for this note name\n # NoteNameからNote Numberを検索しています。\n note_number = pretty_midi.note_name_to_number(note_name)\n\n # Create a Note instance, starting at 0s and ending at .5s\n # NoteInstanceを作成します。音(pitch)の開始時間と終了時間、\n # velocityを定義します。\n note = pretty_midi.Note(\n velocity=100, pitch=note_number, start=0, end=.5)\n\n # Add it to our cello instrument\n # 上記で作成したNoteInstanceをCelloInstrumentに加えます。\n cello.notes.append(note)\n\n\n# Add the cello instrument to the PrettyMIDI object\n# ChelloInstrumentをPrettyMIDIオブジェクトに加えます。\ncello_c_chord.instruments.append(cello)\n\n\n# Write out the MIDI data\n# PrettyMIDIオブジェクトをMIDIファイルとして書き出しましょう。\ncello_c_chord.write('cello-C-chord.mid')","sub_path":"manimidi.py","file_name":"manimidi.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"564271302","text":"from Game.Shared.Constants import Constants\nfrom Game.Bricks import *\n\nimport os\nimport pygame\n\nclass Level:\n def __init__(self, game):\n self.__game = game\n self.__bricks = []\n self.__remainingBrickCount = 0\n self.__currentLevel = 1 #alway start from level 1\n\n def getBricks(self):\n return self.__bricks\n\n def getRemainingBrickCount(self):\n return self.__remainingBrickCount\n\n def hitBrick(self):\n self.__remainingBrickCount -= 1\n\n def loadNextLevel(self):\n pass\n \n def load(self, level):\n self.__currentLevel = level\n x, y = 0, 0\n levelDataFilePath = os.path.join(Constants.RESOURCE_BASE_PATH, \"Levels\\\\Level\" + str(level) + \".dat\")\n f = open(levelDataFilePath, mode=\"rt\")\n lines = f.readlines()\n for line in lines:\n for digit in line:\n if digit == \"1\": #this is a normal brick\n brick = Brick(self.__game, (x, y), pygame.image.load(Constants.NORMAL_BRICK_SPRITE))\n self.__remainingBrickCount += 1 #increase the brick count when a new brick is added\n elif digit == \"2\": #this is a life brick\n brick = LifeBrick(self.__game, (x, y), pygame.image.load(Constants.LIFE_BRICK_SPRITE))\n self.__remainingBrickCount += 1 #increase the brick count when a new brick is added\n elif digit == \"3\": #this is a power brick\n brick = PowerBrick(self.__game, (x, y), pygame.image.load(Constants.POWER_BRICK_SPRITE))\n self.__remainingBrickCount += 1 #increase the brick count when a new brick is added\n else: #should be 0, do not show any brick\n pass\n self.__bricks.append(brick) #add the newly created brick in the bricks list\n x += (Constants.BRICK_SIZE[0]+5) #increase x by the width of the brick plus 5 pixel gap for next brick\n x = 0 #reset the x to 0 for next line of brick\n y += (Constants.BRICK_SIZE[1] + 10) #increase y by the height of the brick plus 10 pixel gap for next line\n\n#test\n#myLevel = Level(\"\")\n#myLevel.load(1)\n","sub_path":"sq/BallGame/Version6/Game/Level.py","file_name":"Level.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"307614567","text":"# This file is used to create an MXD file based on a datapack. It needs to be run via the python application that is\n# packaged with arcgis.\n# For many users this is the default python, for other users they may have to specify this location\n# for example ('C:\\Python27\\ArcGIS10.5\\python create_mxd.py').\n\nimport os\nimport logging\nimport shutil\nfrom multiprocessing import Pool\nimport json\n\ntry:\n input = raw_input\nexcept NameError:\n pass\n\nlogging.basicConfig()\nlogger = logging.getLogger(\"create_mxd\")\n\nlogger.warning(\"Creating an MXD file for your data...\")\n\n\nif os.getenv(\"LOG_LEVEL\"):\n logger.setLevel(os.getenv(\"LOG_LEVEL\"))\n\ntry:\n from django.conf import settings\n\n BASE_DIR = settings.BASE_DIR\nexcept Exception:\n BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nSUPPORTED_VERSIONS = [\"10.5.1\"]\nVERSIONS = [\"10.6.1\", \"10.6\", \"10.5.1\", \"10.5\", \"10.4.1\", \"10.4\"]\n\ntry:\n import arcpy\nexcept Exception as e:\n logger.warning(e)\n input(\n \"Could not import ArcPY. ArcGIS 10.4 or 10.5 is required to run this script. \"\n \"Please ensure that it is installed and activated. \"\n \"If multiple versions of python are installed ensure that you are using python that came bundled with ArcGIS. \"\n \"Press any key to exit.\"\n )\n raise\n\nversion = arcpy.GetInstallInfo().get(\"Version\")\nif arcpy.GetInstallInfo().get(\"Version\") not in SUPPORTED_VERSIONS:\n logger.warning(\n (\n \"This script only supports versions {0}. \"\n \"It might work for {1} but it will likely not support all of the datasets.\".format(\n SUPPORTED_VERSIONS, [version for version in VERSIONS if version not in SUPPORTED_VERSIONS]\n )\n )\n )\n\n\ndef update_mxd_from_metadata(file_name, metadata, verify=False):\n \"\"\"\n :param file_name: A path to the mxd file.\n :param metadata: The metadata providing the names, filepaths, and types to add to the mxd.\n :return: The original file.\n \"\"\"\n mxd = arcpy.mapping.MapDocument(os.path.abspath(file_name))\n df = mxd.activeDataFrame\n version = get_version()\n for layer_name, layer_info in metadata[\"data_sources\"].items():\n for file_info in layer_info[\"files\"]:\n # As of arcgis 10.5.1 shapefiles can't be imported as zips.\n if file_info[\"file_ext\"] in [\".zip\"]:\n logger.warning(\n \"This script can't automatically add zipped shapefiles. \"\n \"You can try to use the osm layer in the template folder then update \"\n \"the source data after extracting the shapefiles.\"\n )\n continue\n file_path = os.path.abspath(os.path.join(BASE_DIR, file_info[\"file_path\"]))\n # If possible calculate the statistics now so that they are correct when opening arcmap.\n try:\n logger.warning((\"Calculating statistics for the file {0}...\".format(file_path)))\n arcpy.CalculateStatistics_management(file_path)\n except Exception as e:\n logger.warning(e)\n layer_file = get_layer_file(layer_info[\"type\"], version)\n if not layer_file:\n logger.warning(\n (\n \"Skipping layer {0} because the file type is not supported for ArcMap {1}\".format(\n layer_name, version\n )\n )\n )\n if version == \"10.5\":\n logger.warning(\n \"However with your version of ArcMap you can still drag and drop this layer onto the Map.\"\n )\n continue\n if file_info[\"file_ext\"] in [\".kml\", \".kmz\"]:\n kml_layer = os.path.splitext(os.path.basename(file_path))[0]\n template_dir = os.path.join(BASE_DIR, \"arcgis\", \"templates\")\n layer_file = os.path.join(template_dir, \"{}.lyr\".format(kml_layer))\n try:\n layer_from_file = arcpy.KMLToLayer_conversion(\n in_kml_file=file_path, output_folder=template_dir, output_data=kml_layer\n )\n except Exception:\n # This could fail for various reasons including that the file already exists.\n # If KMLs are very important to your workflow please contact us and we can make this more robust.\n logger.warning(\"Could not create a new KML layer file and gdb, it may already exist.\")\n layer_from_file = arcpy.mapping.Layer(layer_file)\n layer_from_file.name = layer_info[\"name\"] + file_info[\"file_ext\"].replace(\".\", \"_\")\n logger.warning((\"Adding layer: {0}...\".format(layer_from_file.name)))\n arcpy.mapping.AddLayer(df, layer_from_file, \"TOP\")\n del layer_from_file\n else:\n layer_from_file = arcpy.mapping.Layer(layer_file)\n layer_from_file.name = layer_info[\"name\"] + file_info[\"file_ext\"].replace(\".\", \"_\")\n logger.warning((\"Adding layer: {0}...\".format(layer_from_file.name)))\n try:\n arcpy.mapping.AddLayer(df, layer_from_file, \"TOP\")\n # Get instance of layer from MXD, not the template file.\n try:\n logger.warning((\"Updating layer: {0}...\".format(layer_from_file.name)))\n layer = arcpy.mapping.ListLayers(mxd)[0]\n update_layer(layer, file_path, layer_info[\"type\"], verify=verify)\n except Exception:\n logger.error(\"Could not update layer {0}\".format(layer_from_file.name))\n except Exception:\n logger.error(\"Could not add layer {0}\".format(layer_from_file.name))\n finally:\n del layer_from_file\n\n logger.debug(\"Getting dataframes...\")\n df = mxd.activeDataFrame\n\n df.extent = arcpy.Extent(*metadata[\"bbox\"])\n\n mxd.activeView = df.name\n arcpy.RefreshActiveView()\n mxd.save()\n del mxd # remove handle on file\n return file_name\n\n\ndef get_mxd_template(version):\n \"\"\"\n :param version: A version for the correct arcgis MapDocument template.\n :return: A file path to the correct arcgis MapDocument template.\n \"\"\"\n if \"10.6\" in version:\n template_file_name = \"template-10-6.mxd\"\n elif \"10.5\" in version:\n template_file_name = \"template-10-5.mxd\"\n elif \"10.4\" in version:\n template_file_name = \"template-10-4.mxd\"\n template_file = os.path.abspath(os.path.join(BASE_DIR, \"arcgis\", \"templates\", template_file_name))\n if not os.path.isfile(template_file):\n logger.warning(\"This script requires an mxd template file which was not found.\")\n raise Exception(\"File Not Found: {0}\".format(template_file))\n return template_file\n\n\ndef get_layer_file(type, version):\n \"\"\"\n\n :param type: Type of templace (i.e. raster, osm...)\n :param version: arcgis version (i.e. 10.5)\n :return: The file path to the correct layer.\n \"\"\"\n # Temporarily patch the version\n if \"10.6\" in version:\n version = \"10.6\"\n layer_basename = \"{0}-{1}.lyr\".format(type, version.replace(\".\", \"-\"))\n layer_file = os.path.abspath(os.path.join(BASE_DIR, \"arcgis\", \"templates\", layer_basename))\n logger.warning((\"Fetching layer template: {0}\".format(layer_file)))\n if os.path.isfile(layer_file):\n return layer_file\n return None\n\n\ndef get_version():\n \"\"\"\n :return: Returns the version of arcmap that is installed.\n \"\"\"\n\n try:\n version = arcpy.GetInstallInfo().get(\"Version\")\n if version in VERSIONS:\n return version\n raise Exception(\"UNSUPPORTED VERSION\")\n except Exception:\n logger.warning(\n (\n \"Unable to determine ArcGIS version. This script only supports versions {0}\".format(\n str(SUPPORTED_VERSIONS)\n )\n )\n )\n raise\n\n\ndef update_layer(layer, file_path, type, verify=False):\n \"\"\"\n :param layer: An Arc Layer object to be updated.\n :param file_path: A new datasource.\n :param verify: If true will validate the datasource after the layer is updated.\n :return: The updated ext.\n \"\"\"\n for lyr in arcpy.mapping.ListLayers(layer):\n if lyr.supports(\"DATASOURCE\"):\n try:\n logger.debug(\"layer: {0}\".format(lyr))\n logger.debug(\"removing old layer workspacePath: {0}\".format(lyr.workspacePath))\n except Exception:\n # Skip layers that don't have paths.\n continue\n try:\n # Try to update the extents based on the layers\n logger.debug(\"Updating layers from {0} to {1}\".format(lyr.workspacePath, file_path))\n if type == \"raster\" and os.path.splitext(file_path)[1] != \".gpkg\":\n logger.debug(\"Replacing Datasource\")\n lyr.replaceDataSource(\n os.path.dirname(file_path), \"RASTER_WORKSPACE\", os.path.basename(file_path), verify\n )\n elif type == \"elevation\":\n logger.debug(\"updating elevation\")\n lyr.replaceDataSource(os.path.dirname(file_path), \"NONE\", os.path.basename(file_path), verify)\n else:\n logger.debug(\"updating raster or vector gpkg\")\n logger.debug(\"Replacing WorkSpace Path\")\n lyr.findAndReplaceWorkspacePath(lyr.workspacePath, file_path, verify)\n if lyr.isFeatureLayer:\n logger.debug(arcpy.RecalculateFeatureClassExtent_management(lyr).getMessages())\n except Exception as e:\n logger.error(e)\n raise\n\n\ndef create_mxd(mxd=None, metadata=None, verify=False):\n \"\"\"\n Updates the template mxd with a new gpkg datasource. If an mxd is provided the result is written to that file.\n :param mxd: An mxd to write the result to (optional).\n :param metadata: The metadata file to use for updating the mxd.\n :param verify: Raise an exception if there is an error in the MXD after adding the new gpkg.\n :return: The contents (binary) of the mxd file.\n \"\"\"\n template_file = get_mxd_template(get_version())\n # with get_temp_mxd(metadata, verify=verify) as temp_mxd_file:\n # copy temp file to permanent file if specified.\n if mxd:\n logger.warning((\"writing file to {0}\".format(mxd)))\n shutil.copy(template_file, mxd)\n # return mxd\n update_mxd_from_metadata(mxd, metadata, verify=verify)\n with open(mxd, \"rb\") as open_mxd_file:\n return open_mxd_file.read()\n\n\ndef create_mxd_process(mxd=None, metadata=None, verify=False):\n \"\"\"\n This wraps create_mxd to overcome issues with licensing by running in a unique process.\n Updates the template mxd with a new gpkg datasource. If an mxd is provided the result is written to that file.\n :param mxd: An mxd to write the result to (optional).\n :param metadata: The metadata file to use for updating the mxd.\n :param verify: Raise an exception if there is an error in the MXD after adding the new gpkg.\n :return: The contents (binary) of the mxd file.\n \"\"\"\n pool = Pool()\n result = pool.apply_async(create_mxd, kwds={\"mxd\": mxd, \"metadata\": metadata, \"verify\": verify})\n mxd = result.get()\n return mxd\n\n\nif __name__ == \"__main__\":\n\n try:\n metadata_file = os.path.join(os.path.dirname(__file__), \"metadata.json\")\n\n with open(metadata_file, \"r\") as open_metadata_file:\n metadata = json.load(open_metadata_file)\n\n mxd_output = os.path.join(os.path.dirname(__file__), \"{0}.mxd\".format(metadata[\"name\"]))\n create_mxd(mxd=mxd_output, metadata=metadata, verify=True)\n except Exception as e:\n logger.warning(e)\n input(\"Press enter to exit.\")\n","sub_path":"eventkit_cloud/tasks/arcgis/create_mxd.py","file_name":"create_mxd.py","file_ext":"py","file_size_in_byte":12056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"357100994","text":"import json\n\nimport pydantic\nimport json\nfrom typing import Optional, List\nfrom pydantic import validators\n\n\nclass ISBN10FormatError(Exception):\n '''\n Custom error that is raised when ISBN10 doesn't have the right format.\n '''\n def __init__(self, value: str, message: str) -> None:\n self.value = value\n self.message = message\n super.__init__(message)\n\n\n\n\nclass ISBNMissingError(Exception):\n '''\n Custom Error that is raised when ISBN10 and ISBN13 are missing\n '''\n\n def __init(self, title: str, message: str) -> None:\n self.title = title\n self.message = message\n super().__init__(message)\n\nclass Book(pydantic.BaseModel):\n title: str\n author: str\n publisher: str\n price: float\n isbn_10: Optional[str]\n isbn_13: Optional[str]\n subtitle: Optional[str]\n\n\n # Every book has to be one of two 'isbn_10' or 'isbn_13'\n @pydantic.root_validator(pre=True)\n @classmethod\n def check_isbn10_or_isbn13(cls, values):\n '''\n Make sure that there is either ISBN_10 or ISBN_13 methods\n '''\n if \"isbn_10\" not in values and \"isbn_13\" not in values:\n raise ISBNMissingError(title=values[\"title\"], message=\"Doc should have either\")\n return values\n\n\n @pydantic.validator(\"isbn_10\")\n @classmethod\n def isbn_10_valid(cls, value) :\n '''\n Validator to check whether ISBN10 has a valie value\n \n '''\n chars = [ c for c in value if c in \"0123456789Xx\" ]\n if len(chars) != 10:\n raise Exception(\"MSG\",value=value)\n\n\n def char_to_int(char: str) -> int:\n if char in \"xX\":\n return 10\n return int(char)\n \n weighted_sum = sum((10 - i) * char_to_int(x) for i, x in enumerate(chars))\n if weighted_sum % 11 != 0:\n raise ISBN10FormatError(value=value, message='ISBN10 divisible by 11.')\n\n\n return value\n\n\n class config:\n '''\n Pydantic config class\n '''\n allow_mutation = False\n\n\ndef main() -> None:\n '''\n\n Main Function\n Read the JSON file.\n Here were are loading the data\n '''\n with open('/root/PY/data/pydantic_data.json') as file:\n data = json.load(file)\n '''\n This is the line that I don't understand but okay for now as we tend \n to overpass the tiem, For now remember to deconstruct the classes like this.\n '''\n books = [Book(**item) for item in data]\n print(data[0]['title'])\n print(books[0].title)\n print(books[0].dict(include={'price', 'title'}))\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"pydantic/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"635651660","text":"# -*- coding: UTF-8 -*-\nimport email\nimport mimetypes\nimport smtplib\nimport os\nimport xlsxwriter\nimport decimal\nfrom email.header import Header\nfrom settings import get_mysql_db\n\n# import sys\n# reload(sys)\n# sys.setdefaultencoding('utf-8')\n\n\ndef send_email(year, month, day):\n # qbiayrpxpkbebhab\n sender = 'zhujianwei@donews.com'\n receivers = [\n 'zhujianwei@donews.com',\n 'wanshitao@donews.com',\n 'jijiazhen@donews.com',\n 'lichenguang@donews.com',\n 'chenkangjian@donews.com',\n 'zhanyanjun@donews.com',\n 'yangliu@donews.com',\n 'shuyong@donews.com',\n ] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱\n # username = \"421414186@qq.com\"\n # password = \"odbtbqrfpqrmbhbj\"\n\n username = \"zhujianwei@donews.com\"\n password = \"4656BIsheng\"\n\n file_name = 'csv_file/statistics_result_table' + year + '-' + month + '-' + day + '.xlsx'\n # 构造MIMEMultipart对象做为根容器\n main_msg = email.MIMEMultipart.MIMEMultipart()\n\n # 构造MIMEText对象做为邮件显示内容并附加到根容器\n text_msg = email.MIMEText.MIMEText(year + '-' + month + '-' + day + \"统计结果表\", _charset=\"utf-8\")\n main_msg.attach(text_msg)\n\n # 构造MIMEBase对象做为文件附件内容并附加到根容器\n ctype, encoding = mimetypes.guess_type(file_name)\n if ctype is None or encoding is not None:\n ctype = 'application/octet-stream'\n maintype, subtype = ctype.split('/', 1)\n file_msg = email.MIMEImage.MIMEImage(open(file_name, 'rb').read(), subtype)\n\n # 设置附件头\n basename = os.path.basename(file_name)\n file_msg.add_header('Content-Disposition', 'attachment', filename=basename) # 修改邮件头\n main_msg.attach(file_msg)\n\n subject = year + '-' + month + '-' + day + '统计结果表'\n main_msg['Subject'] = Header(subject, 'utf-8')\n main_msg['From'] = 'zhujianwei@donews.com'\n main_msg['To'] = ','.join(receivers)\n smtp = smtplib.SMTP('smtp.exmail.qq.com', 25)\n fullText = main_msg.as_string()\n smtp.login(username, password)\n smtp.sendmail(sender, receivers, fullText)\n smtp.quit()\n\n\ndef export(year, month, day):\n table_name = 'statistics_result_table'\n conn = get_mysql_db()\n cursor = conn.cursor()\n sql1 = \"\"\"\n select\n media as 库名,\n news_count as 新闻数,\n total_count as 总资源数,\n total_count_1 as Mongo总资源数,\n format(total_size/1024/1024/1024, 2) as OSS日志存储总量G,\n format(total_size_1/1024/1024/1024, 2) as Mongo共有数据存储总量G,\n format(avg_size_1/1024/1024, 2) as 平均大小M,\n format(total_size_1*100/(select sum(total_size_1) from statistics_result_table where\n datetime ='{}'), 2) as 百分占比\n from statistics_result_table where datetime = %s;\n \"\"\".format(year + '-' + month + '-' + day)\n\n\n sql2 = \"\"\"\n select\n media as 库名,\n news_count as 新闻数,\n img_location_count_1 as 图片数据量,\n format(img_location_size_1/1024/1024/1024, 2) as 图片大小G,\n small_img_location_count_1 as 缩略图数据量,\n format(small_img_location_size_1/1024/1024/1024, 2) as 缩略图大小G,\n video_location_count_1 as 视频数据量,\n format(video_location_size_1/1024/1024/1024, 2) as 视频大小G\n from {} where datetime = %s;\n \"\"\".format(\"statistics_result_table\")\n\n sql3 = \"\"\"\n select\n media as 库名,\n ifnull(format(img_location_count_1/news_count, 2), 0) as 平均图片数量,\n ifnull(format(small_img_location_count_1/news_count, 2), 0) as 平均缩略图数量,\n ifnull(format(video_location_count_1/news_count, 2), 0) as 平均视频数量,\n ifnull(format(img_location_size_1/img_location_count_1/1024, 2), 0) as 单条数据平均图片大小kb,\n ifnull(format(small_img_location_size_1/small_img_location_count_1/1024, 2), 0) as 单条数据平均缩略图大小kb,\n ifnull(format(video_location_size_1/video_location_count_1/1024, 2), 0) as 单条数据视频大小kb,\n format(ifnull(img_location_size_1/img_location_count_1/1024, 0) + \n ifnull(small_img_location_size_1/small_img_location_count_1/1024, 0) + \n ifnull(video_location_size_1/video_location_count_1/1024, 0), 2) as 平均单条数据\n from {} where datetime = %s;\n \"\"\".format(\"statistics_result_table\")\n\n workbook = xlsxwriter.Workbook('csv_file/statistics_result_table' + year + '-' + month + '-' + day + '.xlsx')\n count = 1\n for sql in [sql1, sql2, sql3]:\n cursor.execute(sql, year + '-' + month + '-' + day)\n # 搜取所有结果\n results = cursor.fetchall()\n # 获取MYSQL里面的数据字段名称\n fields = cursor.description\n sheet = workbook.add_worksheet('table_' + table_name + str(count))\n count += 1\n # 写上字段信息\n for field in range(0,len(fields)):\n sheet.write(0, field, fields[field][0])\n\n # 获取并写入数据段信息\n for row in range(1, len(results)+1):\n for col in range(0, len(fields)):\n value = results[row-1][col]\n if str(value).find(\".\") != -1 or str(value) == '0':\n if str(value).find(\",\") != -1:\n value = decimal.Decimal(str(value).replace(\",\", ''))\n value = decimal.Decimal(value)\n sheet.write(row, col, value)\n workbook.close()\n\n\n# 结果测试\nif __name__ == \"__main__\":\n export(year='2017', month='10', day='08')\n send_email(year='2017', month='10', day='08')\n","sub_path":"send_email_test.py","file_name":"send_email_test.py","file_ext":"py","file_size_in_byte":5760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"163628129","text":"# -*- encoding: utf-8 -*-\nfrom abjad.tools import mathtools\nfrom experimental.tools.musicexpressiontools.SingleContextSetExpression \\\n import SingleContextSetExpression\n\n\nclass SingleContextTimeSignatureSetExpression(SingleContextSetExpression):\n r'''Single-context time signature set expression.\n '''\n\n ### INITIALIZER ###\n\n def __init__(\n self,\n source_expression=None,\n target_timespan=None,\n target_context_name=None,\n fresh=True,\n persist=True,\n ):\n SingleContextSetExpression.__init__(\n self,\n attribute='time_signatures',\n source_expression=source_expression,\n target_timespan=target_timespan,\n target_context_name=target_context_name,\n fresh=fresh,\n persist=persist,\n )\n\n ### PUBLIC METHODS ###\n\n def evaluate(self):\n r'''Evaluate single-context time signature set expression.\n\n Returns timespan-scoped single-context time signature set expression.\n '''\n from experimental.tools import musicexpressiontools\n target_timespan = self._evaluate_anchor_timespan()\n expression = \\\n musicexpressiontools.TimespanScopedSingleContextTimeSignatureExpression(\n source_expression=self.source_expression,\n target_timespan=target_timespan,\n target_context_name=self.target_context_name,\n fresh=self.fresh,\n )\n expression._lexical_rank = self._lexical_rank\n return expression\n\n def make_time_signatures(self):\n from experimental.tools import musicexpressiontools\n if hasattr(self.source_expression, 'evaluate_early'):\n expression = self.source_expression.evaluate_early()\n assert isinstance(\n expression,\n musicexpressiontools.IterablePayloadExpression)\n time_signatures = expression.payload\n else:\n expression = self.source_expression.evaluate()\n assert isinstance(\n expression,\n musicexpressiontools.IterablePayloadExpression)\n time_signatures = expression.payload[:]\n time_signatures = [\n mathtools.NonreducedFraction(x) for x in time_signatures]\n if time_signatures:\n self.root_specification._time_signatures = time_signatures[:]\n return time_signatures\n","sub_path":"abjad/experimental/tools/musicexpressiontools/SingleContextTimeSignatureSetExpression.py","file_name":"SingleContextTimeSignatureSetExpression.py","file_ext":"py","file_size_in_byte":2435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"328827653","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Server Monitor Bot\n# by Aliaksandr Zakharenka\n#\n# ///////////////////////////////// https://al3xable.me/ ////////////////////////////////////\n# // //\n# // .__ ________ ___. .__ //\n# // _____ | | \\_____ \\ ___ ________ \\_ |__ | | ____ _____ ____ //\n# // \\__ \\ | | _(__ < \\ \\/ /\\__ \\ | __ \\ | | _/ __ \\ / \\ _/ __ \\ //\n# // / __ \\_| |__ / \\ > < / __ \\_ | \\_\\ \\| |__\\ ___/ | Y Y \\\\ ___/ //\n# // (____ /|____//______ //__/\\_ \\(____ / |___ /|____/ \\___ > /\\ |__|_| / \\___ > //\n# // \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ //\n# // //\n# ///////////////////////////////////////////////////////////////////////////////////////////\n\nimport json\nimport logging\nimport time\nimport urllib.request\nfrom multiprocessing import Process\nfrom urllib.error import HTTPError, URLError\n\nfrom telegram import TelegramError\nfrom telegram.ext import Updater, CommandHandler\n\nupdater = None\nconfig = None\nlogger = None\n\n\ndef servers_monitor(bot):\n while True:\n try:\n fail = False\n resp = '```\\n'\n\n for host in config['hosts']:\n r, st = checkHost(host)\n fail = fail or not st\n if not st:\n resp += r\n\n resp += '```'\n\n if fail:\n bot.sendMessage(chat_id=config['chat'], text=resp, parse_mode=\"Markdown\")\n\n time.sleep(config['monitorSleep'])\n except TelegramError as e:\n logger.error('Monitor exception: {}'.format(e.message))\n except Exception as e:\n logger.error('Monitor exception: {}'.format(e.args))\n\n\ndef chat(bot, update):\n update.message.reply_text(update.message.chat.id)\n # bot.sendPhoto(chat_id=config['master'], photo=open(file, 'rb'))\n\n\ndef checkHost(host):\n resp = ''\n srvip = host[0]\n\n start_time = time.time()\n\n try:\n code = urllib.request.urlopen(\"http://\" + srvip, timeout=5).getcode()\n except HTTPError as e:\n code = e.code\n except URLError as e:\n code = e.reason\n except Exception as e:\n code = str(e.args)\n\n ping = int((time.time() - start_time) * 1000)\n\n ok = (code in [200, 401, 402, 403, 404])\n\n resp += \"%-18s | %4sms | %s\\n\" % (host[0], ping, str(code))\n\n return resp, ok\n\n\ndef status(bot, update):\n resp = '```\\n'\n\n for host in config['hosts']:\n r, st = checkHost(host)\n resp += r\n\n resp += '```'\n\n update.message.reply_text(resp, parse_mode=\"Markdown\")\n\n\ndef main():\n # INIT #\n global config, logger, updater\n\n config = json.loads(open('bot.json', 'r').read())\n logger = logging.getLogger(__name__)\n updater = Updater(config['token'])\n\n logging.basicConfig(format='[%(asctime)s] [%(levelname)s:%(name)s] %(message)s', level=logging.INFO,\n filename=config['logFileName'])\n\n updater.dispatcher.add_handler(CommandHandler('chat', chat))\n updater.dispatcher.add_handler(CommandHandler('status', status))\n\n updater.start_polling(timeout=config['poolTimeout'])\n\n monitor = Process(target=servers_monitor, args=(updater.bot,))\n monitor.start()\n\n updater.idle()\n\n # Stopping thread\n monitor.terminate()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tgsrvmon.py","file_name":"tgsrvmon.py","file_ext":"py","file_size_in_byte":3598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"369869620","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom keras.datasets import boston_housing\nfrom keras import models\nfrom keras import layers\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\n(train_data, train_targets), (test_data, test_targets) = boston_housing.load_data()\n\n# Normalization of the data (centered around 0 within -1 and +1 standard deviations)\n# so all values have a similar range\nmean = train_data.mean(axis = 0)\nstd = train_data.std(axis = 0)\n\ntrain_data -= mean\ntrain_data /= std\n\ntest_data -= mean\ntest_data /= std\n\n# The number of samples is small, the network will also be small so we minimize the overfitting\ndef build_model():\n model = models.Sequential()\n model.add(layers.Dense(64, activation = 'relu', input_shape = (train_data.shape[1],)))\n model.add(layers.Dense(64, activation = 'relu'))\n # No activation so the output can take any value\n model.add(layers.Dense(1))\n\n # MAE : mean absolute value, good for regressions\n # MSE : mean squared error, good for regressions\n model.compile(optimizer = 'rmsprop', loss = 'mse', metrics = ['mae'])\n return model\n\n# K-fold, the model is trained on 3/4 of the dataset and validated with the last 1/2\n# this is done 4 times so it runs with the whole dataset and we compute the average\nk = 4\nnum_val_samples = len(train_data) // k\nnum_epochs = 500\nall_mae_histories = []\n\nfor i in range(k):\n print('processing fold #', i)\n val_data = train_data[i * num_val_samples: (i + 1) * num_val_samples]\n val_targets = train_targets[i * num_val_samples: (i + 1) * num_val_samples]\n partial_train_data = np.concatenate(\n [\n train_data[:i * num_val_samples],\n train_data[(i + 1) * num_val_samples:]\n ],\n axis = 0\n )\n partial_train_targets = np.concatenate(\n [\n train_targets[:i * num_val_samples],\n train_targets[(i + 1) * num_val_samples:]\n ],\n axis = 0\n )\n model = build_model()\n history = model.fit(\n partial_train_data,\n partial_train_targets,\n validation_data = (val_data, val_targets),\n epochs = num_epochs,\n batch_size = 1,\n verbose = 0\n )\n # MAE by epoch\n mae_history = history.history['val_mean_absolute_error']\n all_mae_histories.append(mae_history)\n\n# MAE by epoch for all the folds\naverage_mae_history = [np.mean([x[i] for x in all_mae_histories]) for i in range(num_epochs)]\n\nplt.plot(range(1, len(average_mae_history) + 1), average_mae_history)\nplt.xlabel('Epochs')\nplt.ylabel('Validation MAE')\nplt.show()\n\ndef smooth_curve(points, factor = 0.9):\n smoothed_points = []\n for point in points:\n if smoothed_points:\n previous = smoothed_points[-1]\n smoothed_points.append(previous * factor + point * (1 - factor))\n else:\n smoothed_points.append(point)\n return smoothed_points\n\nsmooth_mae_history = smooth_curve(average_mae_history[10:])\n\nplt.clf()\nplt.plot(range(1, len(smooth_mae_history) + 1), smooth_mae_history)\nplt.xlabel('Epochs')\nplt.ylabel('Validation MAE')\nplt.show()\n\n# 80 epochs seems to be optimal\nmodel = build_model()\nmodel.fit(train_data, train_targets, epochs = 80, batch_size = 16, verbose = 0)\ntest_mse_score, test_mae_score = model.evaluate(test_data, test_targets)\n\nprint(test_mse_score)\nprint(test_mae_score)\n","sub_path":"deep-learning-python/3-boston-housing.py","file_name":"3-boston-housing.py","file_ext":"py","file_size_in_byte":3195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"298361617","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n# Mean Absolute Percentage Loss:\ndef MAPELoss(output, target):\n output, target = output.detach().cpu(), target.detach().cpu()\n return torch.mean(torch.abs((target - output) / target)).item()\n\n\n# Accuracy:\ndef Accuracy(output, target):\n output = torch.argmax(output, axis=1)\n return ((output == target).sum() / target.size(0)).item()\n\n\n# Mish Activation Function:\nclass Mish(nn.Module):\n def __init__(self):\n super(Mish, self).__init__()\n \n \n def forward(self, x):\n return x * torch.tanh(F.softplus(x))\n\n\n# Transformer模型中的encoder:\nclass TransformerEncoder(nn.Module):\n def __init__(self, embedSize, window, numHeads=4):\n super(TransformerEncoder, self).__init__()\n self.embedSize = embedSize\n self.attention = nn.MultiheadAttention(embedSize, numHeads)\n self.mlp = nn.Sequential(\n nn.Dropout(0.1),\n nn.Linear(embedSize, embedSize * 2),\n Mish(),\n nn.Linear(embedSize * 2, embedSize)\n )\n self.layerNorm0 = nn.LayerNorm(embedSize)\n self.layerNorm1 = nn.LayerNorm(embedSize)\n \n \n def forward(self, x):\n xt = x.transpose(0, 1)\n h1 = self.attention(xt, xt, xt)[0]\n h2 = self.layerNorm0((h1 + xt).transpose(0, 1))\n h3 = self.mlp(h2)\n h4 = self.layerNorm1(h2 + h3)\n return h4 + x\n \n\n# 模型最前面的LSTM部分:\nclass Encoder(nn.Module):\n def __init__(self, inputSize, hiddenSize, window, numLayers, dropout, \n bidirectional, isAttention, attentionHeads):\n super(Encoder, self).__init__()\n self.inputSize = inputSize\n self.hiddenSize = hiddenSize\n self.bidirectional = bidirectional\n self.isAttention = isAttention\n self.lstm = nn.LSTM(\n inputSize, \n hiddenSize, \n numLayers, \n batch_first=True,\n bidirectional=bidirectional,\n dropout=dropout\n )\n if isAttention:\n self.attention = TransformerEncoder(hiddenSize * 2 if bidirectional else hiddenSize, \n window, \n attentionHeads)\n \n \n def forward(self, y, index, pos, neg):\n device = y.device\n ouputSize = self.hiddenSize * 2 if self.bidirectional else self.hiddenSize\n \n # Mainstream:\n factorY, _ = self.lstm(y)\n \n # Index:\n factorI, _ = self.lstm(index)\n \n # Positive:\n factorP = torch.zeros([pos.size(0), pos.size(1), ouputSize]).to(device)\n for i in range(0, self.inputSize, pos.shape[-1]):\n factorP_I, _ = self.lstm(pos[..., i: i + self.inputSize])\n factorP += factorP_I\n \n factorP /= pos.shape[-1]\n \n # Negative:\n factorN = torch.zeros([neg.size(0), neg.size(1), ouputSize]).to(device)\n for i in range(0, self.inputSize, neg.shape[-1]):\n factorN_I, _ = self.lstm(neg[..., i: i + self.inputSize])\n factorN += factorN_I\n \n factorN /= neg.shape[-1]\n \n # Attention:\n if self.isAttention:\n factorY = self.attention(factorY)\n factorI = self.attention(factorI)\n factorP = self.attention(factorP)\n factorN = self.attention(factorN)\n \n # Output result:\n return factorY, factorI, factorP, factorN\n\n\n# 模型中的Multi-Input LSTM:\nclass MI_LSTM(nn.Module):\n def __init__(self, inputSize, hiddenSize):\n super(MI_LSTM, self).__init__()\n concatSize = inputSize + hiddenSize\n self.inputSize = inputSize\n self.hiddenSize = hiddenSize\n self.lF = nn.Linear(concatSize, hiddenSize)\n self.lO = nn.Linear(concatSize, hiddenSize)\n self.lCY = nn.Linear(concatSize, hiddenSize)\n self.lCI = nn.Linear(concatSize, hiddenSize)\n self.lCP = nn.Linear(concatSize, hiddenSize)\n self.lCN = nn.Linear(concatSize, hiddenSize)\n self.lIY = nn.Linear(concatSize, hiddenSize)\n self.lII = nn.Linear(concatSize, hiddenSize)\n self.lIP = nn.Linear(concatSize, hiddenSize)\n self.lIN = nn.Linear(concatSize, hiddenSize)\n \n wA = torch.nn.init.kaiming_normal_(torch.zeros([hiddenSize, hiddenSize]))\n bAY = torch.nn.init.uniform_(torch.zeros([hiddenSize]))\n bAI = torch.nn.init.uniform_(torch.zeros([hiddenSize]))\n bAP = torch.nn.init.uniform_(torch.zeros([hiddenSize]))\n bAN = torch.nn.init.uniform_(torch.zeros([hiddenSize]))\n self.wA = nn.Parameter(wA)\n self.bAY = nn.Parameter(bAY)\n self.bAI = nn.Parameter(bAI)\n self.bAP = nn.Parameter(bAP)\n self.bAN = nn.Parameter(bAN)\n \n \n def forward(self, factorY, factorI, factorP, factorN):\n batch, window, device = factorY.size(0), factorY.size(1), factorY.device\n h = torch.zeros([batch, window, self.hiddenSize]).to(device)\n cT = torch.zeros([batch, self.hiddenSize]).to(device)\n hT = torch.zeros([batch, self.hiddenSize]).to(device)\n for t in range(window):\n cT, hT = self.Step(factorY[:, t, :],\n factorI[:, t, :],\n factorP[:, t, :],\n factorN[:, t, :],\n cT, hT)\n h[:, t, :] = hT\n \n return h\n \n \n def Step(self, yT, iT, pT, nT, cT=None, hT=None):\n device, batch = yT.device, yT.size(0)\n if cT is None:\n cT = torch.zeros([batch, self.hiddenSize]).to(device)\n \n if hT is None:\n hT = torch.zeros([batch, self.hiddenSize]).to(device)\n \n hTyT = torch.cat([hT, yT], dim=-1)\n hTiT = torch.cat([hT, iT], dim=-1)\n hTpT = torch.cat([hT, pT], dim=-1)\n hTnT = torch.cat([hT, nT], dim=-1)\n \n f = torch.sigmoid(self.lF (hTyT))\n o = torch.sigmoid(self.lO (hTyT))\n iY = torch.sigmoid(self.lIY(hTyT))\n iI = torch.sigmoid(self.lII(hTyT))\n iP = torch.sigmoid(self.lIP(hTyT))\n iN = torch.sigmoid(self.lIN(hTyT))\n \n lY = torch.tanh(self.lCY(hTyT)) * iY\n lI = torch.tanh(self.lCI(hTiT)) * iI\n lP = torch.tanh(self.lCP(hTpT)) * iP\n lN = torch.tanh(self.lCN(hTnT)) * iN\n lT = self.GetAttention(lY, lI, lP, lN, cT)\n \n cNext = cT * f + lT\n hNext = torch.tanh(cNext) * o\n \n return cNext, hNext\n \n \n def GetAttention(self, lY, lI, lP, lN, cT):\n cTwA = cT @ self.wA\n attention = [\n torch.tanh((lY * cTwA).sum(dim=-1, keepdim=True) + self.bAY),\n torch.tanh((lI * cTwA).sum(dim=-1, keepdim=True) + self.bAI),\n torch.tanh((lP * cTwA).sum(dim=-1, keepdim=True) + self.bAP),\n torch.tanh((lN * cTwA).sum(dim=-1, keepdim=True) + self.bAN)\n ]\n attention = torch.cat(attention, dim=-1)\n attention = torch.softmax(attention, dim=-1)\n lT = (attention[:, 0: 1] * lY + \n attention[:, 1: 2] * lI + \n attention[:, 2: 3] * lP + \n attention[:, 3: 4] * lN )\n return lT\n \n\n# 模型中的Attention Layer:\nclass Attention(nn.Module):\n def __init__(self, inputSize, embedSize, window, attentionLayers, attentionHeads):\n super(Attention, self).__init__()\n self.inputSize = inputSize\n self.embedSize = embedSize\n self.attention = nn.Sequential(*[TransformerEncoder(inputSize, \n window, \n attentionHeads) \n for _ in range(attentionLayers)])\n self.linear = nn.Linear(inputSize, embedSize)\n self.v = nn.Parameter(torch.nn.init.uniform_(torch.zeros([embedSize])))\n \n \n def forward(self, x):\n h = self.attention(x)\n h = torch.tanh(self.linear(h))\n b = torch.softmax(h @ self.v, dim=1).unsqueeze(-1)\n return (h * b).sum(dim=1)\n \n\n# 模型最後面的FC層(regressor):\nclass Regressor(nn.Module):\n def __init__(self, inputSize, layers):\n super(Regressor, self).__init__()\n if layers > 1:\n blocks = ([nn.BatchNorm1d(inputSize)] + \n [self.MakeBlock(inputSize, inputSize * 2 ** (layers - 2))] + \n [self.MakeBlock(inputSize * 2 ** i, inputSize * 2 ** (i - 1))\n for i in range(layers - 2, 0, -1)])\n elif layers == 1:\n blocks = []\n \n else:\n raise ValueError(\"Layers must greater than 1 .\")\n \n self.extractor = nn.Sequential(*blocks)\n self.regressor = nn.Linear(inputSize, 1)\n \n \n def MakeBlock(self, inputSize, outputSize):\n return nn.Sequential(\n nn.Linear(inputSize, outputSize),\n Mish(),\n nn.BatchNorm1d(outputSize)\n )\n \n \n def forward(self, x):\n h = self.extractor(x)\n h = self.regressor(h)\n return h\n\n\n# 模型最後面的FC層(classifier):\nclass Classifier(nn.Module):\n def __init__(self, inputSize, layers):\n super(Classifier, self).__init__()\n if layers > 1:\n blocks = ([nn.BatchNorm1d(inputSize)] + \n [self.MakeBlock(inputSize, inputSize * 2 ** (layers - 2))] + \n [self.MakeBlock(inputSize * 2 ** i, inputSize * 2 ** (i - 1))\n for i in range(layers - 2, 0, -1)])\n elif layers == 1:\n blocks = []\n \n else:\n raise ValueError(\"Layers must greater than 1 .\")\n \n self.extractor = nn.Sequential(*blocks)\n self.classifier = nn.Linear(inputSize, 3)\n \n \n def MakeBlock(self, inputSize, outputSize):\n return nn.Sequential(\n nn.Linear(inputSize, outputSize),\n Mish(),\n nn.BatchNorm1d(outputSize)\n )\n \n \n def forward(self, x):\n h = self.extractor(x)\n h = self.classifier(h)\n return h\n \n\n# 完整模型:\nclass Model(nn.Module):\n def __init__(self, \n window=30,\n inputSize=1,\n embedSize0=64, \n embedSize1=128, \n embedSize2=128,\n encoderLayers=2,\n encoderDropout=0.1,\n encoderBidirectional=True,\n encoderAttention=True,\n attentionHeads=4,\n attentionLayers=1,\n regressorLayers=4):\n \n super(Model, self).__init__()\n self.window = window\n self.encoder = Encoder(inputSize, \n embedSize0, \n window,\n encoderLayers, \n encoderDropout, \n encoderBidirectional,\n encoderAttention,\n attentionHeads)\n self.lstm = MI_LSTM(embedSize0 * 2 if encoderBidirectional else embedSize0, \n embedSize1)\n self.attention = Attention(embedSize1,\n embedSize2,\n window,\n attentionLayers,\n attentionHeads)\n self.regressor = Regressor(embedSize2,\n regressorLayers)\n \n \n def forward(self, y, index, pos, neg):\n h = self.encoder(y, index, pos, neg)\n h = self.lstm(*h)\n h = self.attention(h)\n h = self.regressor(h)\n return h\n \n\n# 分類版本完整模型:\nclass ClassifierModel(nn.Module):\n def __init__(self, \n window=30,\n inputSize=1,\n embedSize0=64, \n embedSize1=128, \n embedSize2=128,\n encoderLayers=2,\n encoderDropout=0.1,\n encoderBidirectional=True,\n encoderAttention=True,\n attentionHeads=4,\n attentionLayers=1,\n classificationLayers=4):\n \n super(ClassifierModel, self).__init__()\n self.window = window\n self.encoder = Encoder(inputSize, \n embedSize0, \n window,\n encoderLayers, \n encoderDropout, \n encoderBidirectional,\n encoderAttention,\n attentionHeads)\n self.lstm = MI_LSTM(embedSize0 * 2 if encoderBidirectional else embedSize0, \n embedSize1)\n self.attention = Attention(embedSize1,\n embedSize2,\n window,\n attentionLayers,\n attentionHeads)\n self.classifier = Classifier(embedSize2,\n classificationLayers)\n \n \n def forward(self, y, index, pos, neg):\n h = self.encoder(y, index, pos, neg)\n h = self.lstm(*h)\n h = self.attention(h)\n h = self.classifier(h)\n return h\n \n \n ","sub_path":"Save/XLNX_0_Acc=0.9810224622488022.py","file_name":"XLNX_0_Acc=0.9810224622488022.py","file_ext":"py","file_size_in_byte":13640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"322248572","text":"from discord.ext import commands\nimport random\nimport wikipedia\n\n\nclass Wiki(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(name=\"wiki\", description=\"Get a link to a random wiki article\", aliases=[\"wikipedia\"])\n @commands.guild_only()\n async def wiki(self, ctx):\n page = wikipedia.random(1)\n try:\n info = wikipedia.page(page)\n except wikipedia.DisambiguationError as e:\n s = random.choice(e.options)\n info = wikipedia.page(s)\n url = info.url\n author = ctx.author.mention\n await ctx.send(author + ' ' + str(url) + '')\n\n\ndef setup(bot):\n bot.add_cog(Wiki(bot))\n","sub_path":"cogs/wiki.py","file_name":"wiki.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"273544739","text":"import pygame\nimport random\nfrom vecmath import *\nfrom hypos import hpHypoList\nfrom hypos import noHpHypoList\nfrom . import los\n\nclass SituationManager(object):\n\t\"\"\" \n\tThis class deals with all the things that can and can't be seen or heard\n\tBy any given character in the game. It also deal with targeting and holds\n\tOther situational properties. It is used by any object of the Actor class. \n\t\"\"\"\n\n\tactors = pygame.sprite.Group()\n\tlevelEntities = None\n\twalls = None\n\tfloors = None\n\tnoises = pygame.sprite.Group()\n\tcurrentlevel = None\n\n\tdef __init__(self, host):\n\t\tself.host = host\n\t\tself.friendsInSight = []\n\t\tself.enemiesInSight = []\n\t\tself.enemyLastSeenTile = pygame.sprite.GroupSingle()\n\t\tself.tileToInvestigate = pygame.sprite.GroupSingle()\n\t\tself.struckBy = pygame.sprite.GroupSingle()\n\t\tself.heard = pygame.sprite.Group()\n\t\tself.sightTimer = {}\n\n\tdef inSightRadius(self, target):\n\t\t\"\"\" Determine weather or not a target entity is within the host actor's \n\t\tfield of view.\n\t\t\"\"\"\n\t\treturn self.host.pointWithinFocusRange(89, target.rect.center)\n\n\tdef updateActorsInSight(self):\n\t\tunobstructedActors = los.table[self.host]\n\t\tvisibleActors = [actor for actor in unobstructedActors if self.inSightRadius(actor)]\n\t\tself.friendsInSight = [actor for actor in visibleActors if actor.team is self.host.team]\n\t\tself.enemiesInSight = [actor for actor in visibleActors if actor.team is not self.host.team]\n\n\tdef updateEnemyLastSeenTile(self):\n\t\tlastSeenTile = self.enemyLastSeenTile.sprite\n\t\tif self.host.getCurrentTile() is lastSeenTile:\n\t\t\tself.enemyLastSeenTile.empty()\n\n\tdef updateHearing(self):\n\t\ttileSize = 30\n\t\t# at base the character can hear up to 10 tiles away.\n\t\tbaseRange = tileSize * 10\n\t\thearingRange = baseRange + (self.host.characterSheet.statsbonus[\"WIS\"] * tileSize)\n\t\tfor noise in SituationManager.noises:\n\t\t\tcannotSeeSource = not noise.source in self.enemiesInSight\n\t\t\tsourceIsEnemy = not noise.source.team is self.host.team\n\t\t\tdistanceToNoise = self.host.getDistanceTo(noise.rect.center)\n\t\t\tsoundInRange = distanceToNoise < hearingRange\n\t\t\tif cannotSeeSource and sourceIsEnemy and soundInRange:\n\t\t\t\tself.heard.add(noise)\n\n\tdef update(self):\n\t\tself.updateActorsInSight()\n\t\tself.struckBy.empty()\n\t\tself.updateEnemyLastSeenTile()\n\t\tself.updateHearing()\n\n\tdef getClosestEntity(self, entities, limit=400):\n\t\t\"\"\" Find the closest entity from a list of entities, within a given\n\t\tdistance.\n\t\t\"\"\"\n\t\ttargetlist = {}\n\n\t\tfor entity in entities:\n\t\t\tdistance = self.host.getDistanceTo(entity.rect.center)\n\t\t\tif distance < limit:\n\t\t\t\ttargetlist[int(distance)] = entity\n\n\t\tif targetlist:\n\t\t\treturn targetlist[min(targetlist)]\n\t\treturn None\n\n\tdef getEnemyTarget(self):\n\t\t\"\"\" Find the closest enemy the host actor should target.\n\t\t\"\"\"\n\t\ttarget = self.getClosestEntity(self.enemiesInSight)\n\t\tif target:\n\t\t\tself.enemyLastSeenTile.add(target.getCurrentTile())\n\t\treturn target\n\n\tdef getFleeTarget(self):\n\t\t\"\"\" Find the closest enemy that the host actor should flee from.\n\t\t\"\"\"\n\t\ttarget = self.getClosestEntity(self.enemiesInSight, 120)\n\t\tif target:\n\t\t\tself.enemyLastSeenTile.add(target.getCurrentTile())\n\t\treturn target\n\n\tdef getHuntTarget(self):\n\t\tif self.enemyLastSeenTile.sprite:\n\t\t\treturn self.enemyLastSeenTile.sprite\n\n\t\tnoisesUnobstructed = {}\n\t\tnoisesObstructed = {}\n\t\tfor noise in self.heard:\n\t\t\tdistance = self.host.getDistanceTo(noise.rect.center)\n\t\t\tvisible = los.testSight(self.host, noise, SituationManager.currentlevel.mapHash)\n\t\t\tif visible:\n\t\t\t\tnoisesUnobstructed[int(distance)] = noise\n\t\t\telse:\n\t\t\t\tnoisesObstructed[int(distance)] = noise\n\n\t\tif noisesUnobstructed:\n\t\t\ttarget = noisesUnobstructed[min(noisesUnobstructed)]\n\t\t\tself.enemyLastSeenTile.add(target.source.getCurrentTile())\n\t\t\treturn self.enemyLastSeenTile.sprite\n\n\t\telif noisesObstructed:\n\t\t\ttarget = noisesObstructed[min(noisesObstructed)]\n\t\t\tself.enemyLastSeenTile.add(target.source.getCurrentTile())\n\t\t\treturn self.enemyLastSeenTile.sprite\n\t\t\n\t\treturn None\n\n\tdef getAttackable(self):\n\t\ttarget = self.getEnemyTarget()\n\t\tinRange = False\n\t\tif target:\n\t\t\tinRange = self.host.getDistanceTo(target.rect.center) <= self.host.getAttackRange()\n\t\tif inRange:\n\t\t\treturn target\n\t\treturn False\n\n\tdef getUnseenDestination(self):\n\t\tfloorlist = SituationManager.floors.sprites()\n\t\trandom.shuffle(floorlist)\n\t\tmapHash = SituationManager.currentlevel.mapHash\n\t\tchoice = next(tile for tile in floorlist if not los.testSight(self.host, tile, mapHash))\n\t\treturn choice\n\n\t##\n\t# This one should get a tile that cannot be seen by the actor\n\t# passed in as an argument. It is assumed that the actor has a \n\t##\n\tdef getHiddenDestination(self, actor):\n\t\thidingSpot = False\n\t\tfor tile in SituationManager.floors.sprites():\n\t\t\t#check if the tile can is closer to the host than the actor\n\t\t\tcanRunTo = False\n\t\t\tdistanceToHost = tile.getDistanceTo(self.host.rect.center)\n\t\t\tdistanceToActor = tiles.getDistanceTo(actor.rect.center)\n\t\t\tif distanceToHost < distanceToActor:\n\t\t\t\tcanRunTo = True\n\t\t\t#check if the actor can see that tile.\n\t\t\tmapHash = SituationManager.currentlevel.mapHash\n\t\t\tif canRunTo and not los.testSight(actor, tile, mapHash):\n\t\t\t\thidingSpot = tile\n\n\t\treturn hidingSpot\n\n\tdef itemCheck(self, itemlist):\n\t\tpossibleItems = []\n\t\tfor item in self.host.characterSheet.equipment:\n\t\t\tif self.host.characterSheet.equipment[item] in itemlist:\n\t\t\t\tpossibleItems.append(item)\n\t\treturn possibleItems\n\n\tdef shouldHeal(self):\n\t\t#check that the itemToUse is a health item.\n\t\t#if so, return it.\n\t\titem = self.host.itemToUse\n\t\tif item and self.host.characterSheet.equipment[item] in hpHypoList:\n\t\t\treturn self.host.itemToUse\n\n\t\t#otherwise, check the inventory and such\n\t\thealth = self.host.characterSheet.currentHp\n\t\tfullHealth = self.host.characterSheet.fullHp\n\t\thealthLost = fullHealth - health\n\t\t\n\t\tneedsHealing = healthLost > fullHealth/2\n\t\tif not needsHealing:\n\t\t\treturn False\n\t\t\n\t\twantsHealing = self.host.characterSheet.rollVsStat(\"WIS\", 10)\n\t\tif not wantsHealing:\n\t\t\treturn False\n\t\t\n\t\tpossibleItems = self.itemCheck(hpHypoList)\n\t\tif possibleItems:\n\t\t\t#This needs to be a more intelligent choice.\n\t\t\treturn random.choice(possibleItems)\n\t\t\n\t\treturn False\n\n\tdef shouldBoost(self):\n\t\t#check that the itemToUse is a health item.\n\t\t#if so, return it.\n\t\titem = self.host.itemToUse\n\t\tif item and not self.host.characterSheet.equipment[item] in hpHypoList:\n\t\t\treturn self.host.itemToUse\n\n\t\t#otherwise, check the inventory and such\n\t\tpossibleItems = self.itemCheck(noHpHypoList)\n\t\tif possibleItems:\n\t\t\t#This needs to be a more intelligent choice.\n\t\t\treturn random.choice(possibleItems)\n\t\t\n\t\treturn False\n\n\t##\n\t# chooses a nearby leader based on the charisma of \n\t# surrounding characters. Will be expanded upon when personalities come\n\t# into play.\n\t##\n\tdef shouldFollowLeader(self):\n\t\tleader = None\n\t\tpotentialLeaders = {}\n\t\tfor friend in self.friendsInSight:\n\t\t\tfriendCharisma = friend.characterSheet.statsbonus[\"CHA\"] \n\t\t\thostCharisma = self.host.characterSheet.statsbonus[\"CHA\"]\n\t\t\tdifference = friendCharisma - hostCharisma\n\t\t\tif difference > 0:\n\t\t\t\tpotentialLeaders[difference] = friend\n\n\t\tif potentialLeaders:\n\t\t\tleader = potentialLeaders[max(potentialLeaders)]\n\n\t\treturn leader\n\n","sub_path":"ai/situationmanager.py","file_name":"situationmanager.py","file_ext":"py","file_size_in_byte":7130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"489117683","text":"# -*- coding: utf-8 -*-\n# @Author: zhaoa\n# @Date: 2018-10-15 21:30:30\n# @Last Modified by: zhaoanke\n# @Last Modified time: 2018-10-16 22:27:44\n\n\nimport re\n\nnames = [\"name1\", \"_name\", \"2_name\", \"__name__\"]\n\n\nfor i in names:\n res = re.match(r\"^[_A-Za-z]+[\\w_]$\", i)\n\n if res:\n res.group()\n else:\n print(\"命名错误\", i)\n","sub_path":"10月-Python和Linux高级编程/03web服务器/01re正则表达式/10-15 正则表达式判断变量名.py","file_name":"10-15 正则表达式判断变量名.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"506028530","text":"import os\nimport subprocess\n\n\ndef load_env():\n from dotenv import load_dotenv\n from pathlib import Path\n\n load_dotenv()\n env_path = Path('.') / '.env'\n load_dotenv(dotenv_path=env_path)\n\n\ndef crawl_process():\n spider_1 = os.getenv('SPIDER_1', default='tecblog')\n tecmundo_pages = os.getenv('TECMUNDO_PAGES', default=2)\n\n spider_2 = os.getenv('SPIDER_2', default='tecmundo')\n tecblog_pages = os.getenv('TECBLOG_PAGES', default=2)\n\n comando = 'scrapy crawl {0} -a paginas=\"{1}\" --logfile ./logs/{2}.log'.format\n\n subprocess.call(comando(spider_1, tecmundo_pages, spider_1), shell=True)\n subprocess.call(comando(spider_2, tecblog_pages, spider_2), shell=True)\n\n\ndef main():\n load_env()\n crawl_process()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"crawlers/entrypoint.py","file_name":"entrypoint.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"77962584","text":"\"\"\"\nScript to create grid(s), given input args.\n\"\"\"\n\n# Authors: Gianni Barlacchi \n\nimport argparse\nimport sys\nimport logging\nimport pandas as pd\nimport gensim\nimport pkg_resources\nfrom geol.geol_logger.geol_logger import logger\nfrom geol.utils import utils\nimport re\nimport os\nimport numpy as np\n\n\ndef main(argv):\n\n parser = argparse.ArgumentParser('Build your own grid.')\n\n parser.add_argument('-o', '--outputfolder',\n help='Output folder where to save the matrix.',\n action='store',\n dest='outputfolder',\n required=True,\n type=str)\n\n parser.add_argument('-i', '--input',\n help='Input file with point-of-interests. NOTE: in the case of strategy=nearest|alphabetically, the input file must contains the column cellID.',\n action='store',\n dest='inputfile',\n required=True,\n type=str)\n\n parser.add_argument('-a', '--area',\n action='store',\n dest='area',\n help='Area name',\n default=None,\n type=str)\n\n parser.add_argument('-s', '--size',\n action='store',\n dest='size',\n help='Word2Vec words size. Used when employing Google News model.',\n default=None,\n type=str)\n\n parser.add_argument('-v', '--verbose',\n help='Level of output verbosity.',\n action='store',\n dest='verbosity',\n default=0,\n type=int,\n nargs=\"?\")\n\n args = parser.parse_args()\n\n if(args.verbosity == 1):\n logging.basicConfig(\n format='%(levelname)s: %(message)s', level=logging.INFO)\n\n elif(args.verbosity == 2):\n logging.basicConfig(\n format='%(levelname)s: %(message)s', level=logging.DEBUG)\n\n logger.info(\"Loading w2v model.\")\n\n model = None\n\n ext = tuple([\".biz\", \".bin\"])\n\n if(args.inputfile.endswith(ext)):\n model = gensim.models.KeyedVectors.load_word2vec_format(args.inputfile, binary=True)\n else:\n model = gensim.models.Word2Vec.load(args.inputfile)\n\n tree = pd.read_csv(pkg_resources.resource_filename(\n 'geol', '/resources/category_tree.csv'), encoding='iso-8859-1')\n\n words = tree['level1_name'].dropna().drop_duplicates().tolist() + \\\n tree['level2_name'].dropna().drop_duplicates().tolist() + \\\n tree['level3_name'].dropna().drop_duplicates().tolist() + \\\n tree['level4_name'].dropna().drop_duplicates().tolist()\n\n m = re.search('_s([0-9]+)_', args.inputfile)\n\n if args.size:\n size = args.size\n else:\n if m:\n size = m.group(1)\n\n m = re.search('.+/(.+).model', args.inputfile)\n\n if m:\n model_details = m.group(1)\n else:\n model_details = 'gnews'\n\n outputfile = os.path.abspath(os.path.join(\n args.outputfolder, \"matrix_\" + args.area + \"_\" + model_details + \".txt\"))\n\n f = open(outputfile, 'w', encoding='utf-8')\n\n for word in words:\n\n word = utils.normalize_word(word)\n\n w = word.split(' ')\n v = [0] * int(size)\n\n if len(w) > 1:\n tmp_w2v = []\n for e in w:\n if e in model:\n tmp_w2v.append(model[e])\n if len(tmp_w2v) > 0:\n v = np.mean(tmp_w2v, axis=0)\n elif word in model:\n v = model[word]\n\n v = map(str, v)\n s = ','.join(map(str, v))\n f.write(word.replace(\" \", \"_\") + \"::n\" + \"\\t1.0\\t0\\t\" + s + \"\\n\")\n\n f.close()\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"scripts/SPTK_matrix.py","file_name":"SPTK_matrix.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"41862647","text":"morse_map = {\r\n \"A\": \".-\", \"B\": \"-...\", \"C\": \"-.-.\", \"D\": \"-..\", \"E\": \".\", \"F\": \"..-.\",\r\n \"G\": \"--.\", \"H\": \"....\", \"I\": \"..\", \"J\": \".---\", \"K\": \"-.-\", \"L\": \".-..\",\r\n \"M\": \"--\", \"N\": \"-.\", \"O\": \"---\", \"P\": \".--.\", \"Q\": \"--.-\", \"R\": \".-.\",\r\n \"S\": \"...\", \"T\": \"-\", \"U\": \"..-\", \"V\": \"..-\", \"W\": \".--\", \"X\": \"-..-\",\r\n \"Y\": \"-.--\", \"Z\": \"--..\", \" \": \"+\", \"1\": \".----\", \"2\": \"..---\", \"3\": \"...--\",\r\n \"4\": \"....-\", \"5\": \".....\", \"6\": \"-....\", \"7\": \"--...\", \"8\": \"---..\", \"9\": \"----.\",\r\n \"0\": \"-----\", \"?\": \"..--..\", \",\": \"--..--\", \".\": \".-.-.-\",\r\n }\r\n\r\ninv_morse_map = {y:x for x, y in morse_map.items()}\r\n\r\n\r\n\r\ndef text2morse():\r\n user_input = input(\"Enter your text to convert it to morse code:\\n(Spaces will later symbolise the beginning of a new letter)\\n(A plus sign will later symbolise the beginning of a new word)\\n(Only english letters, numbers and '?', ',', '.')\\n\")\r\n for char in user_input:\r\n print(morse_map[char.upper()], end=\" \")\r\n\r\ndef morse2text():\r\n user_input = input(\"Enter your morse code to convert it to normal text:\\n(Put spaces after each letter)\\n(Use a plus sign to symbolise the start of a new word)\\n(Only english letters, numbers and '?', ',', '.')\\n\")\r\n for char in user_input.split(\" \"):\r\n print(inv_morse_map[char], end=\"\")\r\n\r\n\r\n\r\nwhile True:\r\n selection = input(\"\\nDo you want to do 'Text2Morse' or 'Morse2Text'?\\n(Type 't2m' or 'm2t' respectively)\\n('quit' to close the converter)\\n\")\r\n\r\n if selection == \"t2m\":\r\n text2morse()\r\n continue\r\n\r\n elif selection == \"m2t\":\r\n morse2text()\r\n continue\r\n\r\n elif selection == \"quit\":\r\n break\r\n\r\n else:\r\n print(\"Unknown command, please type either 't2m' or 'm2t'\\n\")\r\n continue\r\n","sub_path":"morse-textconverter.py","file_name":"morse-textconverter.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"465075853","text":"# encoding: utf-8\nimport numpy as np\nfrom sklearn import datasets\nimport chainer\nfrom chainer import cuda, Function, report, training, utils, Variable\nfrom chainer import iterators, optimizers, serializers\nfrom chainer import Link, Chain, ChainList\nimport chainer.functions as F\nimport chainer.links as L\nfrom chainer.datasets import tuple_dataset\nfrom chainer import training\nfrom chainer.training import extensions\n\nnp.random.seed(0)\n\n# クロスエントロピー誤差を用いる場合\nclass IrisChain(Chain):\n def __init__(self):\n super(IrisChain, self).__init__()\n with self.init_scope():\n self.l1 = L.Linear(4, 6)\n self.l2 = L.Linear(6, 3)\n\n # 第一引数はデータのバッチ、第二引数は対応する教師データのバッチにしないといけない\n def __call__(self, x, y):\n return F.softmax_cross_entropy(self.fwd(x), y)\n\n def fwd(self, x):\n h1 = F.sigmoid(self.l1(x))\n h2 = self.l2(h1)\n\n return h2\n\nif __name__ == '__main__':\n # データの生成\n iris = datasets.load_iris()\n X = iris.data.astype(np.float32)\n Y = iris.target.astype(np.int32) # 整数値\n N = Y.size\n\n index = np.arange(N)\n xtrain = X[index[index % 2 != 0], :]\n ytrain = Y[index[index % 2 != 0]] # 教師信号は整数値\n trains = tuple_dataset.TupleDataset(xtrain, ytrain)\n\n xtest = X[index[index % 2 == 0], :]\n ytest = Y[index[index % 2 == 0]] # Yは一次元なので\n tests = tuple_dataset.TupleDataset(xtest, ytest)\n\n # モデルの学習\n model = IrisChain()\n optimizer = optimizers.SGD()\n optimizer.setup(model)\n\n # ミニバッチ法\n epochs = 1000 # エポック数\n bs = 25 # ミニバッチのサイズ\n\n train_iterator = iterators.SerialIterator(trains, bs)\n updater = training.StandardUpdater(train_iterator, optimizer, device=-1)\n trainer = training.Trainer(updater, (epochs, 'epoch'))\n test_iterator = iterators.SerialIterator(tests, bs, repeat=False, shuffle=False)\n # こんな感じでextendできる\n trainer.extend(extensions.Evaluator(test_iterator, model, device=-1))\n # trainer.extend(extensions.LogReport())\n trainer.extend(extensions.ProgressBar())\n\n # モデルの学習\n trainer.run()\n\n # モデルの評価 extendsでも行える\n xt = Variable(xtest)\n yt = model.fwd(xt)\n ans = yt.data\n nrow, ncol = ans.shape\n\n correct_ans_count = 0\n for i in range(nrow):\n teacher_class = np.argmax(ans[i, :])\n if teacher_class == ytest[i]:\n correct_ans_count += 1\n\n print(\"accuracy = {0}\".format(correct_ans_count / nrow))\n","sub_path":"chapter5/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"517100076","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport time\nfrom torch.autograd import Variable\nimport random\nimport numpy\nimport math\n\nfrom torch.nn.modules import dropout\n\nfrom . import model_constants as cons\nfrom .model_utils import make_higher_node, reparameterize, span_beat_to_note_num\nfrom . import model_utils as utils\nfrom .utils import note_tempo_infos_to_beat\nfrom .module import GatedGraph, SimpleAttention, ContextAttention\nfrom .model_constants import QPM_INDEX, QPM_PRIMO_IDX, TEMPO_IDX, PITCH_IDX\n\n# VOICE_IDX = 11\n# PITCH_IDX = 13\n# TEMPO_IDX = PITCH_IDX + 13\nDYNAMICS_IDX = TEMPO_IDX + 5\nLEN_DYNAMICS_VEC = 4\nTEMPO_PRIMO_IDX = -2\nNUM_VOICE_FEED_PARAM = 2\n\n\n\nclass VirtuosoNet(nn.Module):\n def __init__(self):\n super(VirtuosoNet, self).__init__()\n\n def encode_style(self, x, y, edges, note_locations, num_samples=10, return_z=True):\n score_embedding = self.score_encoder(x, edges, note_locations)\n if return_z:\n performance_embedding = self.performance_encoder(score_embedding, y, edges, note_locations, return_z=return_z, num_samples=num_samples)\n return performance_embedding\n else:\n z, mu, var = self.performance_encoder(score_embedding, y, edges, note_locations, return_z=return_z, num_samples=num_samples)\n return z, mu ,var\n\n\n\n def encode_style_distribution(self, x, y, edges, note_locations):\n score_embedding = self.score_encoder(x, edges, note_locations)\n _, perform_mu, perform_var = self.performance_encoder(score_embedding, y, edges, note_locations)\n\n return perform_mu, perform_var\n\n def forward(self, x, y, edges, note_locations, initial_z=None):\n score_embedding = self.score_encoder(x, edges, note_locations)\n if initial_z is None:\n performance_embedding, perform_mu, perform_var = self.performance_encoder(score_embedding, y, edges, note_locations, return_z=False)\n else: \n perform_mu, perform_var = 0, 0\n if type(initial_z) is str and initial_z == 'zero':\n zero_mean = torch.zeros(self.performance_encoder.performance_encoder_mean.out_features)\n one_std = torch.zeros_like(zero_mean) # log std 0\n performance_embedding = reparameterize(zero_mean, one_std).to(x.device)\n elif isinstance(initial_z, torch.Tensor) and not initial_z.is_cuda:\n performance_embedding = torch.Tensor(initial_z).to(x.device).view(1,-1)\n else:\n performance_embedding = initial_z\n residual_info = self.residual_info_selector(x, note_locations)\n output, alter_out = self.performance_decoder(score_embedding, performance_embedding, residual_info, edges, note_locations)\n return output, perform_mu, perform_var, alter_out\n\n\nclass TrillRNN(nn.Module):\n def __init__(self, net_params, device):\n super(TrillRNN, self).__init__()\n self.hidden_size = net_params.note.size\n self.num_layers = net_params.note.layer\n self.input_size = net_params.input_size\n self.output_size = net_params.output_size\n self.device = device\n self.is_graph = False\n self.loss_type = 'MSE'\n\n # self.lstm = nn.LSTM(self.input_size, self.hidden_size, self.num_layers, batch_first=True, bidirectional=True, dropout=DROP_OUT)\n # self.fc = nn.Linear(hidden_size * 2, num_output) # 2 for\n\n self.note_fc = nn.Sequential(\n nn.Linear(self.input_size, self.hidden_size),\n nn.ReLU(),\n nn.Dropout(DROP_OUT),\n nn.Linear(self.hidden_size, self.hidden_size),\n nn.ReLU(),\n )\n self.note_lstm = nn.LSTM(self.hidden_size, self.hidden_size, num_layers=self.num_layers, bidirectional=True, batch_first=True)\n\n self.out_fc = nn.Sequential(\n nn.Linear(self.hidden_size * 2, self.hidden_size),\n nn.ReLU(),\n nn.Dropout(DROP_OUT),\n nn.Linear(self.hidden_size, self.output_size),\n )\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x, y, edges, note_locations, start_index, initial_z=0):\n note_contracted = self.note_fc(x)\n hidden_out, _ = self.note_lstm(note_contracted)\n\n out = self.out_fc(hidden_out)\n\n if self.loss_type == 'MSE':\n up_trill = self.sigmoid(out[:,:,-1])\n out[:,:,-1] = up_trill\n else:\n out = self.sigmoid(out)\n return out, False, False, torch.zeros(1)\n\n\nclass TrillGraph(nn.Module):\n def __init__(self, net_params, trill_index, loss_type, device):\n super(TrillGraph, self).__init__()\n self.loss_type = loss_type\n self.hidden_size = net_params.note.size\n self.num_layers = net_params.note.layer\n self.input_size = net_params.input_size\n self.output_size = net_params.output_size\n self.num_edge_types = net_params.num_edge_types\n self.is_trill_index = trill_index\n self.device = device\n\n # self.lstm = nn.LSTM(self.input_size, self.hidden_size, self.num_layers, batch_first=True, bidirectional=True, dropout=DROP_OUT)\n # self.fc = nn.Linear(hidden_size * 2, num_output) # 2 for\n\n self.note_fc = nn.Sequential(\n nn.Linear(self.input_size, self.hidden_size),\n nn.ReLU(),\n nn.Dropout(DROP_OUT),\n nn.Linear(self.hidden_size, self.hidden_size),\n nn.ReLU(),\n )\n self.graph = GatedGraph(self.hidden_size, self.num_edge_types)\n\n self.out_fc = nn.Sequential(\n nn.Linear(self.hidden_size, self.hidden_size),\n nn.ReLU(),\n nn.Dropout(DROP_OUT),\n nn.Linear(self.hidden_size, self.output_size),\n )\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x, edges):\n # hidden = self.init_hidden(x.size(0))\n # hidden_out, hidden = self.lstm(x, hidden) # out: tensor of shape (batch_size, seq_length, hidden_size*2)\n if edges.shape[0] != self.num_edge_types:\n edges = edges[:self.num_edge_types, :, :]\n\n # Decode the hidden state of the last time step\n is_trill_mat = x[:, :, self.is_trill_index]\n is_trill_mat = is_trill_mat.view(1,-1,1).repeat(1,1,self.output_size).view(1,-1,self.output_size)\n is_trill_mat = Variable(is_trill_mat, requires_grad=False)\n\n note_contracted = self.note_fc(x)\n note_after_graph = self.graph(note_contracted, edges, iteration=5)\n out = self.out_fc(note_after_graph)\n\n if self.loss_type == 'MSE':\n up_trill = self.sigmoid(out[:,:,-1])\n out[:,:,-1] = up_trill\n else:\n out = self.sigmoid(out)\n # out = out * is_trill_mat\n return out\n\n\n","sub_path":"src/virtuoso/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"428614262","text":"import urllib.request\nimport xml.etree.ElementTree\nimport logging\n\ndef extract_xml_tree_from_url(url):\n\tlogging.debug(\"Starting download of %s\" % url)\n\tdata = urllib.request.urlopen(url)\n\n\tif data.getcode() != 200:\n\t\traise RuntimeError(\"Didnt get a 200 response from the webserver.\")\n\n\ttree = xml.etree.ElementTree.parse(data)\n\troot = tree.getroot()\n\tlogging.debug(\"Successfully extraced a root node for a xml tree.\")\n\n\treturn root\n\ndef get_relevant_rain_params(url,ns):\n\t\n\troot = extract_xml_tree_from_url(url)\n\n\tlink_title = \"Nederbördsmängd\" # datat vi öker är nederbörd\n\tlink_summary = \"summa 1 dygn, 1 gång/dygn, kl 06\" # vi vill att dataserien är dygnsvis\n\tnexturl = \"\"\n\n\txpath_querey = \".//default:resource[default:title='%s']\" % link_title\n\n\tlogging.debug(\"Searching for \"+xpath_querey)\n\tnodes = root.findall(xpath_querey ,ns)\n\tlogging.debug(\"found %i relevant nodes of that type\" % len(nodes) )\n\tfor node in nodes:\n\t\tlogging.debug(\"Looking at a node of tag-type:\"+node.tag+\" and title \"+node.find('default:title',ns).text)\n\t\tlogging.debug(\"The summary is: \"+node.find(\"default:summary\",ns).text)\n\n\t\tif node.find(\"default:summary\",ns).text == link_summary:\n\t\t\tlinknode = node.find(\"./default:link[@type='application/xml']\",ns)\n\t\t\tnexturl = linknode.get(\"href\")\n\n\n\tif nexturl == \"\":\n\t\traise RuntimeError(\"Kunde inte hitta en länklista för %s över %s\" % (link_title,link_summary));\n\n\treturn(nexturl)\n\ndef get_link_for_stockholm(url,name_space):\n\troot = extract_xml_tree_from_url(url)\n\tnexturl =\"\"\n\tstation_name = \"Stockholm\"\n\tXPath_querey = \".//default:station[default:name='%s']\" % station_name\n\n\tlogging.debug(\"finding by XPath querey = \"+XPath_querey)\n\n\tstation_element = root.find(XPath_querey, name_space)\n\tlogging.debug(name_space)\t\n\tnexturl = station_element.find(\"./ns2:link[@type='application/xml']\",name_space).get(\"href\")\n\n\tif nexturl == \"\":\n\t\traise RuntimeError(\"Kunde inte hitta en resurs som pekar på regnet för plats %s\" % station_name);\n\n\treturn nexturl\n\ndef get_link_to_data_last_months(url,name_space):\n\troot = extract_xml_tree_from_url(url)\n\tnexturl =\"\"\n\ttime_period = \"latest-months\"\n\n\telement = root.find(\".//default:period[ns2:key='%s']\" % time_period,name_space)\n\tnexturl = element.find(\"./ns2:link[@type='application/xml']\",name_space).get(\"href\")\n\t\n\tif nexturl == \"\":\n\t\traise RuntimeError(\"Kunde inte hitta en resurs som pekar på regnet för tid %s\" % time_period);\n\n\treturn nexturl\t\n\ndef get_link_to_xml_data(url,name_space):\n\troot = extract_xml_tree_from_url(url)\n\tnexturl =\"\"\n\ttime_period = \"latest-months\"\n\n\tnexturl = root.find(\".//default:data/ns2:link[@type='application/xml']\",name_space).get(\"href\")\n\t\n\tif nexturl == \"\":\n\t\traise RuntimeError(\"Kunde inte hitta en xml-data-länk\");\n\n\treturn nexturl\t\n\n\ndef download_data(url,file_path):\n\tlogging.debug(\"Starting to fetch the url %s\" % url)\n\tdata = urllib.request.urlopen(url)\n\tcharset = data.headers.get_content_charset()\n\tif charset is None:\n\t\tcharset = \"utf-8\" # en vild gissning!\n\n\tcontent = data.read()\n\twith open( file_path,'w') as f:\n\t\tf.write( content.decode(charset) )\n\treturn\n\n\nif __name__ == '__main__':\n\tlogging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s')\n\tsmhi_base_api_entry_point = \"http://opendata-download-metobs.smhi.se/api/version/latest.xml\"\n\tns_type_1 = {\"default\": \"http://opendata.smhi.se/xsd/portal.xsd\"}\n\tns_type_2 = {'default': \"http://opendata.smhi.se/xsd/metobs_v1.xsd\"\n\t\t\t\t, \"ns2\": \"http://opendata.smhi.se/xsd/portal.xsd\"}\n\n\train_links_list_url = get_relevant_rain_params(smhi_base_api_entry_point,ns_type_1)\n\tresource_url = get_link_for_stockholm(rain_links_list_url,ns_type_2)\n\tdata_type_url = get_link_to_data_last_months(resource_url,ns_type_2)\n\tdata_url = get_link_to_xml_data(data_type_url,ns_type_2)\n\tdownload_data(data_url,\"raw_rain_data.xml\")","sub_path":"WeatherAnalysis/download_rain_data.py","file_name":"download_rain_data.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"246010712","text":"from numpy import *\nfrom burnman import *\n\ndefault_location_core = \"/Users/sabrinaberger/RockyPlanets/Code/EoS/core_constant_\"\ndefault_location_mantle = \"/Users/sabrinaberger/RockyPlanets/Code/EoS/mantle_constant_\"\n\n\nmantleMaterial = minerals.SLB_2011.mg_fe_silicate_perovskite()\nmantleMaterial.set_composition([0.1, 0.1, 0.8])\nmantleComposite = Composite([mantleMaterial], [1])\n\ncoreMaterial = minerals.Murakami_2013.fe_perovskite()\ncoreComposite = Composite([coreMaterial], [1])\n\n\ndef mantle(pressures, temperatures):\n density = mantleMaterial.evaluate(\n ['density'], pressures, temperatures)\n return density\n\n\ndef core(pressures, temperatures):\n density = coreMaterial.evaluate(\n ['density'], pressures, temperatures)\n return density\n\npressures_range = linspace(0, 3.6385e10, 1e4)\ntemperature_range = linspace(300, 3000, 10)\n\n\ndef constant_temperatures_eos_creator(pressures, temp_eos, location_core, location_mantle):\n for temp in temp_eos:\n temperatures = empty(len(pressures))\n temperatures.fill(temp)\n mantle_eos = mantle(pressures, temperatures)\n core_eos = core(pressures, temperatures)\n\n # c_ makes sure lists end up columned\n savetxt(location_mantle + str(temp) +\n \".dat\", c_[mantle_eos[0], pressures], fmt='%e')\n savetxt(location_core + str(temp) +\n \".dat\", c_[core_eos[0], pressures], fmt='%e')\n\n# To do: implement iron class, wasn't working in adiabat eos so try later\n\n# # iron class taken from example_build_planet.py\n# # A basic set of EoS parameters for solid iron\n#\n# class iron(burnman.Mineral):\n# def __init__(self):\n# # Parameters for gamma - Fe are from Tsujino et al. 2013\n# # G_0 G_Prime0 from Mao et al. 2001 (fig. 3)\n# self.params = {\n# 'equation_of_state': 'slb3',\n# 'T_0': 1273.,x\n# 'V_0': 7.381e-06,\n# 'K_0': 111.5e9,\n# 'Kprime_0': 5.2,\n# 'G_0': 83.2e9, # Shear modulus and derivative from Gleason and Mao, 2013\n# 'Gprime_0': 2.04,\n# 'molar_mass': 55.845 / 1000.,\n# 'n': 1,\n# 'Debye_0': 340.,\n# 'grueneisen_0': 2.28,\n# 'q_0': 0.21,\n# 'eta_s_0': 2.0 # Wholly invented value\n# }\n# burnman.Mineral.__init__(self)\n\n","sub_path":"constant_burnman.py","file_name":"constant_burnman.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"424118999","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport json\nimport unittest\n\nfrom adfmt.enums import (\n RequestMethod,\n BasePermission,\n ParamTyping,\n ApiDoc,\n)\n\n\nclass TestRequestMethod(unittest.TestCase):\n m = RequestMethod\n\n def test_get(self) -> None:\n m = self.m\n\n get = m.Get\n self.assertEqual(get.formatted, '{get}')\n\n def test_post(self) -> None:\n m = self.m\n\n post = m.Post\n self.assertEqual(post.formatted, '{post}')\n\n\nclass CustomPermission(BasePermission):\n Admin = 'User admin'\n Nothing = ''\n\n\nclass TestPermissionDerive(unittest.TestCase):\n p = CustomPermission\n\n def test_admin(self) -> None:\n p = self.p\n\n admin = p.Admin\n self.assertEqual(admin.explain, 'User admin')\n\n def test_nothing(self) -> None:\n p = self.p\n\n nothing = p.Nothing\n self.assertEqual(nothing.explain, '')\n\n\nclass TestParamTyping(unittest.TestCase):\n t = ParamTyping\n\n def test_str(self) -> None:\n t = self.t\n\n string = t.Str\n self.assertEqual(string.formatted, '{String}')\n\n def test_list(self) -> None:\n t = self.t\n\n array = t.List\n self.assertEqual(array.formatted, '{Array}')\n\n def test_num(self) -> None:\n t = self.t\n\n number = t.Num\n self.assertEqual(number.formatted, '{Number}')\n\n def test_obj(self) -> None:\n t = self.t\n\n obj = t.Obj\n self.assertEqual(obj.formatted, '{Object}')\n\n def test_bool(self) -> None:\n t = self.t\n\n boolean = t.Bool\n self.assertEqual(boolean.formatted, '{Boolean}')\n\n\nclass TestApiDoc(unittest.TestCase):\n a = ApiDoc\n\n def test_declare(self) -> None:\n a = self.a\n\n declare = a.Declare\n self.assertEqual(\n declare.statement(\n method=RequestMethod.Post,\n path='/test',\n title='test',\n ),\n '@api {post} /test test',\n )\n\n def test_permission(self) -> None:\n a = self.a\n\n perm = a.Perm\n self.assertEqual(\n perm.instruction(\n permit=CustomPermission.Admin,\n ),\n '@apiPermission admin User admin',\n )\n\n def test_group(self) -> None:\n a = self.a\n\n group = a.Group\n self.assertEqual(\n group.explain(\n content='test',\n ),\n '@apiGroup test',\n )\n\n def test_description(self) -> None:\n a = self.a\n\n desc = a.Desc\n self.assertEqual(\n desc.explain(\n content='test',\n ),\n '@apiDescription test',\n )\n\n def test_header(self) -> None:\n a = self.a\n\n header = a.Header\n self.assertEqual(\n header.param(\n typing=ParamTyping.Str,\n group='(test)',\n name='test',\n explain='param: test',\n ),\n '@apiHeader (test) {String} test param: test',\n )\n\n self.assertEqual(\n header.example(\n name='header-example',\n content=json.dumps(dict(test='test')),\n ),\n '@apiHeaderExample {json} header-example\\n%s' % json.dumps(dict(test='test')),\n )\n\n def test_param(self) -> None:\n a = self.a\n\n param = a.Param\n self.assertEqual(\n param.param(\n typing=ParamTyping.Num,\n group='(test)',\n name='test',\n explain='param: test',\n ),\n '@apiParam (test) {Number} test param: test',\n )\n\n self.assertEqual(\n param.example(\n name='param-example',\n content=json.dumps(dict(test='test')),\n ),\n '@apiParamExample {json} param-example\\n%s' % json.dumps(dict(test='test')),\n )\n\n def test_success(self) -> None:\n a = self.a\n\n success = a.Success\n self.assertEqual(\n success.param(\n typing=ParamTyping.Bool,\n group='(test)',\n name='test',\n explain='success: test',\n ),\n '@apiSuccess (test) {Boolean} test success: test',\n )\n\n self.assertEqual(\n success.example(\n name='success-example',\n content=json.dumps(dict(test='test')),\n ),\n '@apiSuccessExample {json} success-example\\n%s' % json.dumps(dict(test='test')),\n )\n\n def test_error(self) -> None:\n a = self.a\n\n error = a.Error\n self.assertEqual(\n error.param(\n typing=ParamTyping.List,\n group='(test)',\n name='test',\n explain='error: test',\n ),\n '@apiError (test) {Array} test error: test',\n )\n\n self.assertEqual(\n error.example(\n name='error-example',\n content=json.dumps(dict(test='test')),\n ),\n '@apiErrorExample {json} error-example\\n%s' % json.dumps(dict(test='test')),\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/test_enums.py","file_name":"test_enums.py","file_ext":"py","file_size_in_byte":5233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"} +{"seq_id":"429948946","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 20 13:37:33 2015\n\n@author: Lingfei Hu\n\"\"\"\n\nimport sys\n\ninput_file = open(sys.argv[1])\noutput_file = open(sys.argv[2], 'w')\n\nword_list = []\n\nfor line in input_file:\n line = line.strip()\n if line == '':\n continue\n if line.startswith(';'):\n continue\n word_list.append(line)\n \nword_list_str = '\\', \\''.join(word_list)\n\noutput_file.write(word_list_str)\n \ninput_file.close()\noutput_file.close()","sub_path":"bia-660/final/list_generator.py","file_name":"list_generator.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}